Lines Matching +full:no +full:- +full:dump +full:- +full:oops
1 //===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
11 //===----------------------------------------------------------------------===//
45 //===----------------------------------------------------------------------===//
47 //===----------------------------------------------------------------------===//
81 Init = Init->IgnoreParens();
84 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
93 Context.getCanonicalType(AT->getElementType()).getUnqualifiedType();
97 return BT && BT->isCharType() && BT->getKind() != BuiltinType::SChar;
100 switch (SL->getKind()) {
102 // char8_t array can be initialized with a UTF-8 string.
103 // - C++20 [dcl.init.string] (DR)
105 // by a UTF-8 string literal.
106 if (ElemTy->isChar8Type() ||
114 if (ElemTy->isCharType())
115 return (SL->getKind() == StringLiteralKind::UTF8 &&
119 if (ElemTy->isChar8Type())
132 if (ElemTy->isCharType() || ElemTy->isChar8Type())
140 if (ElemTy->isCharType() || ElemTy->isChar8Type())
148 if (ElemTy->isCharType() || ElemTy->isChar8Type())
177 E->setType(Ty);
178 E->setValueKind(VK_PRValue);
189 E->setValueKind(VK_PRValue);
201 D = Parent->getDecl();
202 Parent = Parent->getParent();
205 if (const auto *VD = dyn_cast_if_present<VarDecl>(D); VD && VD->isConstexpr())
218 cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe());
219 uint64_t StrLength = ConstantArrayTy->getZExtSize();
222 if (const StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens()))
231 IAT->getElementType(), ConstVal, nullptr, ArraySizeModifier::Normal, 0);
240 // FIXME: Avoid truncation for 64-bit length strings.
242 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
247 if (SL->isPascal())
248 StrLength--;
252 if (StrLength > CAT->getZExtSize())
253 S.Diag(Str->getBeginLoc(),
255 << CAT->getZExtSize() << StrLength << Str->getSourceRange();
258 if (StrLength - 1 > CAT->getZExtSize())
259 S.Diag(Str->getBeginLoc(),
261 << Str->getSourceRange();
271 //===----------------------------------------------------------------------===//
273 //===----------------------------------------------------------------------===//
311 bool VerifyOnly; // No diagnostics.
415 // initializers, but ill-formed with C++20 designated initializers.
435 } else if (OldInit->getType().isDestructedType() && !FullyOverwritten) {
444 } else if (!OldInit->getSourceRange().isValid()) {
457 // non-designated initializers or a multi-level designator.)
463 << NewInitRange << FullyOverwritten << OldInit->getType();
464 SemaRef.Diag(OldInit->getBeginLoc(), diag::note_previous_initializer)
465 << (OldInit->HasSideEffects(SemaRef.Context) && FullyOverwritten)
466 << OldInit->getSourceRange();
519 SemaRef.Context.getAsArrayType(Entity.getParent()->getType());
521 ElsCount = Embed->getDataElementCount();
523 ElsCount = std::min(CAType->getSize().getZExtValue(),
524 ElsCount - CurEmbedIndex);
525 if (ElsCount == Embed->getDataElementCount()) {
533 EmbedExpr(SemaRef.Context, Embed->getLocation(), Embed->getData(),
536 if (CurEmbedIndex >= Embed->getDataElementCount()) {
559 // Retrieves the fully-structured initializer list used for
575 // If there are fewer initializer-clauses in the list than there are
579 Entity.getType()->getBaseElementTypeUnsafe()->isRecordType();
586 // We treat this as copy-initialization, because aggregate initialization
587 // always performs copy-initialization on its elements.
595 InitExpr->setType(SemaRef.Context.VoidTy);
600 // shall be value-initialized.
607 // std:: for stlport. This is effectively a compiler-side implementation of
617 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
618 CXXRecordDecl *R = CtorDecl->getParent();
620 if (CtorDecl->getMinRequiredArguments() == 0 &&
621 CtorDecl->isExplicit() && R->getDeclName() &&
622 SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
624 for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
625 ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
626 if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND))
630 if (IsInStd && llvm::StringSwitch<bool>(R->getName())
644 SemaRef.Diag(CtorDecl->getLocation(),
647 SemaRef.Diag(Entity.getDecl()->getLocation(),
659 SemaRef.Diag(Entity.getDecl()->getLocation(),
665 Entity.getParent()->isVariableLengthArrayNew();
681 // If we're building a fully-structured list, we'll check this at the end
683 // that there are no designators so we can just check now.
696 if (Init >= ILE->getNumInits() || !ILE->getInit(Init)) {
699 : PerformEmptyInit(ILE->getEndLoc(), BaseEntity);
706 assert(Init < ILE->getNumInits() && "should have been expanded");
707 ILE->setInit(Init, BaseInit.getAs<Expr>());
710 dyn_cast<InitListExpr>(ILE->getInit(Init))) {
714 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
715 FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(),
726 SourceLocation Loc = ILE->getEndLoc();
727 unsigned NumInits = ILE->getNumInits();
731 if (Init >= NumInits || !ILE->getInit(Init)) {
732 if (const RecordType *RType = ILE->getType()->getAs<RecordType>())
733 if (!RType->getDecl()->isUnion())
738 assert(!VerifyOnly && "should not fill with no-init in verify-only mode");
739 Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
741 ILE->setInit(Init, Filler);
743 ILE->updateInit(SemaRef.Context, Init, Filler);
747 // If there are fewer initializer-clauses in the list than there are
749 // shall be initialized from its brace-or-equal-initializer [...]
750 if (Field->hasInClassInitializer()) {
761 ILE->setInit(Init, DIE.get());
763 ILE->updateInit(SemaRef.Context, Init, DIE.get());
769 if (Field->getType()->isReferenceType()) {
772 // If an incomplete or empty initializer-list leaves a
774 // ill-formed.
776 << Field->getType()
777 << (ILE->isSyntacticForm() ? ILE : ILE->getSyntacticForm())
778 ->getSourceRange();
779 SemaRef.Diag(Field->getLocation(), diag::note_uninit_reference_member);
794 ILE->setInit(Init, MemberInit.getAs<Expr>());
800 ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
804 = dyn_cast<InitListExpr>(ILE->getInit(Init))) {
808 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
809 FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),
816 /// with expressions that perform value-initialization of the
825 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
834 // (and therefore some of its properties, such as instantiation-dependence)
845 Outer->setInit(OuterIndex, Outer->getInit(OuterIndex));
851 if (ILE->isTransparent())
854 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
855 const RecordDecl *RDecl = RType->getDecl();
856 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion()) {
857 FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(), Entity, ILE,
860 assert((!RDecl->isUnion() || !isa<CXXRecordDecl>(RDecl) ||
861 !cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) &&
863 // The fields beyond ILE->getNumInits() are default initialized, so in
866 unsigned NumElems = numStructUnionElements(ILE->getType());
867 if (!RDecl->isUnion() && RDecl->hasFlexibleArrayMember())
869 if (!VerifyOnly && ILE->getNumInits() < NumElems)
870 ILE->resizeInits(SemaRef.Context, NumElems);
875 for (auto &Base : CXXRD->bases()) {
885 for (auto *Field : RDecl->fields()) {
886 if (Field->isUnnamedBitField())
900 if (RDecl->isUnion())
911 unsigned NumInits = ILE->getNumInits();
913 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
914 ElementType = AType->getElementType();
916 NumElements = CAType->getZExtSize();
923 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
924 ElementType = VType->getElementType();
925 NumElements = VType->getNumElements();
929 ElementType = ILE->getType();
940 if (Init >= NumInits && (ILE->hasArrayFiller() || SkipEmptyInitChecks))
943 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
944 if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
945 ILE->setInit(Init, ILE->getArrayFiller());
946 else if (!InitExpr && !ILE->hasArrayFiller()) {
947 // In VerifyOnly mode, there's no point performing empty initialization
958 PerformEmptyInit(ILE->getEndLoc(), ElementEntity);
972 // For arrays, just set the expression used for value-initialization
975 ILE->setArrayFiller(Filler);
977 ILE->setInit(Init, Filler);
979 // For arrays, just set the expression used for value-initialization
982 ILE->setArrayFiller(Filler);
991 ILE->updateInit(SemaRef.Context, Init, Filler);
1001 FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
1025 createInitListExpr(T, IL->getSourceRange(), IL->getNumInits());
1030 FullyStructuredList->setSyntacticForm(IL);
1045 FullyStructuredList->markError();
1053 maxElements = static_cast<int>(CAT->getZExtSize());
1059 RecordDecl *structDecl = DeclType->castAs<RecordType>()->getDecl();
1062 InitializableMembers += CXXRD->getNumBases();
1063 for (const auto *Field : structDecl->fields())
1064 if (!Field->isUnnamedBitField())
1067 if (structDecl->isUnion())
1069 return InitializableMembers - structDecl->hasFlexibleArrayMember();
1073 if (const auto *RT = DeclType->getAs<RecordType>())
1074 return RT->getDecl();
1075 if (const auto *Inject = DeclType->getAs<InjectedClassNameType>())
1076 return Inject->getDecl();
1097 Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
1099 return CXXRD->getNumBases() == 1 && CXXRD->field_empty();
1105 Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
1107 if (CXXRD->getNumBases()) {
1111 auto FieldIt = ParentRD->field_begin();
1112 assert(FieldIt != ParentRD->field_end() &&
1113 "no fields but have initializer for member?");
1114 return ++FieldIt == ParentRD->field_end();
1125 /// onwards, with the fully-braced, desugared form of the initialization.
1133 if (T->isArrayType())
1135 else if (T->isRecordType())
1137 else if (T->isVectorType())
1138 maxElements = T->castAs<VectorType>()->getNumElements();
1144 SemaRef.Diag(ParentIList->getInit(Index)->getBeginLoc(),
1154 SourceRange(ParentIList->getInit(Index)->getBeginLoc(),
1155 ParentIList->getSourceRange().getEnd()));
1166 StructuredSubobjectInitList->setType(T);
1168 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
1169 // Update the structured sub-object initializer so that it's ending
1171 if (EndIndex < ParentIList->getNumInits() &&
1172 ParentIList->getInit(EndIndex)) {
1174 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
1175 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
1179 if (!VerifyOnly && (T->isArrayType() || T->isRecordType()) &&
1180 !ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
1182 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
1184 << StructuredSubobjectInitList->getSourceRange()
1186 StructuredSubobjectInitList->getBeginLoc(), "{")
1189 StructuredSubobjectInitList->getEndLoc()),
1194 auto *CXXRD = T->getAsCXXRecordDecl();
1195 if (!VerifyOnly && CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1196 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
1198 << StructuredSubobjectInitList->getSourceRange() << T;
1204 /// single-element braced initializer list.
1208 // non-dependent, we warned during the initial parse; otherwise, the
1237 // No warning, might be direct-list-initialization.
1238 // FIXME: Should we warn for copy-list-initialization in these cases?
1244 // No warning, braces are part of the syntax of the underlying construct.
1248 // No warning, we already warned when initializing the result.
1263 << Entity.getType()->isSizelessBuiltinType() << Braces
1272 /// This also fills in \p StructuredList with the fully-braced, desugared
1283 if (!ExprTy->isArrayType())
1286 IList->setType(ExprTy);
1287 StructuredList->setType(ExprTy);
1293 if (Index < IList->getNumInits() && !T->isIncompleteType()) {
1296 (SemaRef.getLangOpts().OpenCL && T->isVectorType());
1301 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
1307 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1308 << IList->getInit(Index)->getSourceRange();
1309 } else if (T->isSizelessBuiltinType()) {
1313 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1314 << T << IList->getInit(Index)->getSourceRange();
1316 int initKind = T->isArrayType() ? 0 :
1317 T->isVectorType() ? 1 :
1318 T->isScalarType() ? 2 :
1319 T->isUnionType() ? 3 :
1324 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1325 << initKind << IList->getInit(Index)->getSourceRange();
1330 if (T->isScalarType() && IList->getNumInits() == 1 &&
1331 !isa<InitListExpr>(IList->getInit(0)))
1332 warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
1336 auto *CXXRD = T->getAsCXXRecordDecl();
1337 if (CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1341 if (IList->getNumInits() == 0) {
1343 HasEquivCtor = CD && !CD->isDeleted();
1347 SemaRef.Diag(IList->getBeginLoc(),
1349 << IList->getSourceRange() << T;
1363 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
1368 } else if (DeclType->isScalarType()) {
1371 } else if (DeclType->isVectorType()) {
1378 if (DeclType->isRecordType()) {
1379 assert(DeclType->isAggregateType() &&
1380 "non-aggregate records should be handed in CheckSubElementType");
1382 Bases = CXXRD->bases();
1384 Bases = cast<CXXRecordDecl>(RD)->bases();
1386 CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),
1389 } else if (DeclType->isArrayType()) {
1396 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
1400 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1403 } else if (DeclType->isReferenceType()) {
1406 } else if (DeclType->isObjCObjectType()) {
1408 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_objc_class) << DeclType;
1410 } else if (DeclType->isOCLIntelSubgroupAVCType() ||
1411 DeclType->isSizelessBuiltinType()) {
1415 } else if (DeclType->isDependentType()) {
1418 // dependent non-array type or an array type with a value-dependent bound
1421 AggrDeductionCandidateParamTypes->push_back(DeclType);
1424 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1437 Expr *expr = IList->getInit(Index);
1439 if (ElemType->isReferenceType())
1444 if (SubInitList->getNumInits() == 1 &&
1445 IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
1447 // FIXME: It would be more faithful and no less correct to include an
1449 expr = SubInitList->getInit(0);
1455 assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
1464 // Each member is copy-initialized from the corresponding
1465 // initializer-clause.
1469 InitializationKind::CreateCopy(expr->getBeginLoc(), SourceLocation());
1475 (ElemType->isExtVectorType() && !Entity.getType()->isExtVectorType())
1479 if (TmpEntity.getType()->isDependentType()) {
1482 // dependent non-array type or an array type with a value-dependent
1486 // In the presence of a braced-init-list within the initializer, we should
1487 // not perform brace-elision, even if brace elision would otherwise be
1502 AggrDeductionCandidateParamTypes->push_back(ElemType);
1509 // If the assignment-expression can initialize a member, the member is
1513 // assignment-expression.
1534 AggrDeductionCandidateParamTypes->push_back(ElemType);
1540 } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
1551 // FIXME: Should we do this checking in verify-only mode?
1565 assert((ElemType->isRecordType() || ElemType->isVectorType() ||
1566 ElemType->isOpenCLSpecificType()) && "Unexpected type");
1597 // [...] Otherwise, if the member is itself a non-empty
1602 if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) ||
1603 ElemType->isAggregateType()) {
1613 SemaRef.Diag(expr->getBeginLoc(),
1615 << expr->getSourceRange()
1616 << FixItHint::CreateInsertion(expr->getBeginLoc(), "{")
1618 SemaRef.getLocForEndOfToken(expr->getEndLoc()), "}");
1631 "expected non-aggregate initialization to fail");
1647 // a complex number component-wise. When an explicit initializer list for
1653 if (IList->getNumInits() < 2)
1660 SemaRef.Diag(IList->getBeginLoc(), diag::ext_complex_component_init)
1661 << IList->getSourceRange();
1664 QualType elementType = DeclType->castAs<ComplexType>()->getElementType();
1680 if (Index >= IList->getNumInits()) {
1683 if (DeclType->isSizelessBuiltinType())
1684 SemaRef.Diag(IList->getBeginLoc(),
1688 << DeclType << IList->getSourceRange();
1690 SemaRef.Diag(IList->getBeginLoc(),
1694 << IList->getSourceRange();
1704 Expr *expr = IList->getInit(Index);
1709 SemaRef.Diag(SubIList->getBeginLoc(), diag::ext_many_braces_around_init)
1710 << DeclType->isSizelessBuiltinType() << SubIList->getSourceRange();
1717 SemaRef.Diag(expr->getBeginLoc(),
1719 << DeclType->isSizelessBuiltinType() << DeclType
1720 << expr->getSourceRange();
1737 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1751 IList->setInit(Index, ResultExpr);
1759 AggrDeductionCandidateParamTypes->push_back(DeclType);
1767 if (Index >= IList->getNumInits()) {
1773 SemaRef.Diag(IList->getBeginLoc(),
1775 << DeclType << IList->getSourceRange();
1782 Expr *expr = IList->getInit(Index);
1785 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_non_aggr_init_list)
1786 << DeclType << IList->getSourceRange();
1801 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1811 IList->setInit(Index, expr);
1816 AggrDeductionCandidateParamTypes->push_back(DeclType);
1824 const VectorType *VT = DeclType->castAs<VectorType>();
1825 unsigned maxElements = VT->getNumElements();
1827 QualType elementType = VT->getElementType();
1829 if (Index >= IList->getNumInits()) {
1830 // Make sure the element type can be value-initialized.
1833 IList->getEndLoc());
1838 // If the initializing element is a vector, try to copy-initialize
1840 Expr *Init = IList->getInit(Index);
1841 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
1850 SemaRef.PerformCopyInitialization(Entity, Init->getBeginLoc(), Init,
1863 IList->setInit(Index, ResultExpr);
1869 AggrDeductionCandidateParamTypes->push_back(elementType);
1878 if (Index >= IList->getNumInits()) {
1879 CheckEmptyInitializable(ElementEntity, IList->getEndLoc());
1892 const VectorType *T = Entity.getType()->castAs<VectorType>();
1893 if (isBigEndian && (T->getVectorKind() == VectorKind::Neon ||
1894 T->getVectorKind() == VectorKind::NeonPoly)) {
1903 // Because of this, explicitly call out that it is non-portable.
1905 SemaRef.Diag(IList->getBeginLoc(),
1911 if (elementType->isFloatingType())
1913 else if (elementType->isSignedIntegerType())
1915 else if (elementType->isUnsignedIntegerType())
1920 SemaRef.Diag(IList->getBeginLoc(),
1936 if (Index >= IList->getNumInits())
1941 QualType IType = IList->getInit(Index)->getType();
1942 if (!IType->isVectorType()) {
1948 const VectorType *IVT = IType->castAs<VectorType>();
1949 unsigned numIElts = IVT->getNumElements();
1951 if (IType->isExtVectorType())
1955 IVT->getVectorKind());
1965 SemaRef.Diag(IList->getBeginLoc(),
1984 auto *CXXRD = ElementType->getAsCXXRecordDecl();
2004 InitType = Parent->getType();
2005 Parent = Parent->getParent();
2011 ? dyn_cast_if_present<EmbedExpr>(ExprList[0]->IgnoreParens())
2016 if (InitType->isArrayType()) {
2017 const ArrayType *InitArrayType = InitType->getAsArrayTypeUnsafe();
2018 QualType InitElementTy = InitArrayType->getElementType();
2019 QualType EmbedExprElementTy = EE->getDataStringLiteral()->getType();
2022 (InitElementTy->isCharType() && EmbedExprElementTy->isCharType());
2039 if (checkDestructorReference(arrayType->getElementType(),
2040 IList->getEndLoc(), SemaRef)) {
2046 if (canInitializeArrayWithEmbedDataString(IList->inits(), Entity,
2048 EmbedExpr *Embed = cast<EmbedExpr>(IList->inits()[0]);
2049 IList->setInit(0, Embed->getDataStringLiteral());
2052 // Check for the special-case of initializing an array with a string.
2053 if (Index < IList->getNumInits()) {
2054 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
2061 // FIXME: Should we do these checks in verify-only mode too?
2063 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef,
2068 IList->getInit(Index));
2069 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
2073 AggrDeductionCandidateParamTypes->push_back(DeclType);
2081 bool HasErr = IList->getNumInits() != 0 || SemaRef.getLangOpts().CPlusPlus;
2090 // init a VLA in C++ in all cases (such as with non-trivial constructors).
2094 SemaRef.Diag(VAT->getSizeExpr()->getBeginLoc(),
2096 << VAT->getSizeExpr()->getSourceRange();
2109 maxElements = CAT->getSize();
2115 QualType elementType = arrayType->getElementType();
2116 while (Index < IList->getNumInits()) {
2117 Expr *Init = IList->getInit(Index);
2162 if ((CurEmbed || isa<EmbedExpr>(Init)) && elementType->isScalarType()) {
2165 elementIndex + CurEmbedIndex - EmbedElementIndexBeforeInit - 1;
2168 elementIndex = elementIndex + Embed->getDataElementCount() -
2169 EmbedElementIndexBeforeInit - 1;
2178 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
2185 SemaRef.Diag(IList->getBeginLoc(), diag::ext_typecheck_zero_array_size);
2192 // If there are any members of the array that get value-initialized, check
2200 IList->getEndLoc());
2211 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
2215 // Disallow flexible array init on non-top-level object
2220 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
2229 SemaRef.Diag(InitExpr->getBeginLoc(), FlexArrayDiag)
2230 << InitExpr->getBeginLoc();
2231 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2248 if (RD->isInvalidDecl()) {
2255 if (RD->isUnion() && IList->getNumInits() == 0) {
2257 for (FieldDecl *FD : RD->fields()) {
2258 QualType ET = SemaRef.Context.getBaseElementType(FD->getType());
2259 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2267 cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
2270 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2272 if (Field->hasInClassInitializer() ||
2273 (Field->isAnonymousStructOrUnion() &&
2274 Field->getType()->getAsCXXRecordDecl()->hasInClassInitializer())) {
2275 StructuredList->setInitializedFieldInUnion(*Field);
2280 llvm_unreachable("Couldn't find in-class initializer");
2283 // Value-initialize the first member of the union that isn't an unnamed
2285 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2287 if (!Field->isUnnamedBitField()) {
2290 IList->getEndLoc());
2292 StructuredList->setInitializedFieldInUnion(*Field);
2304 Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;
2307 // remaining base classes have no explicit initializer.
2312 // each non-trailing aggregate element that is a pack expansion is assumed
2313 // to correspond to no elements of the initializer list, and (1.7) a
2320 // position corresponding to each non-trailing aggregate element of
2326 AggrDeductionCandidateParamTypes->push_back(
2330 if (I + 1 == E && RD->field_empty()) {
2331 if (Index < IList->getNumInits())
2332 Index = IList->getNumInits();
2339 SourceLocation InitLoc = Init ? Init->getBeginLoc() : IList->getEndLoc();
2361 RecordDecl::field_iterator FieldEnd = RD->field_end();
2362 size_t NumRecordDecls = llvm::count_if(RD->decls(), [&](const Decl *D) {
2369 while (Index < IList->getNumInits()) {
2370 Expr *Init = IList->getInit(Index);
2371 SourceLocation InitLoc = Init->getBeginLoc();
2391 DesignatedInitExpr::Designator *D = DIE->getDesignator(0);
2392 if (!VerifyOnly && D->isFieldDesignator()) {
2393 FieldDecl *F = D->getFieldDecl();
2396 QualType ET = SemaRef.Context.getBaseElementType(F->getType());
2420 if (IList->getNumInits() == 1) {
2424 return IL->getValue().isZero();
2429 // Don't allow non-designated initializers on randomized structures.
2430 if (RD->isRandomized() && !IsZeroInitializer(Init)) {
2443 if (InitializedSomething && RD->isUnion())
2447 if (Field->getType()->isIncompleteArrayType())
2450 if (Field->isUnnamedBitField()) {
2462 *Field, IList->getInit(Index)->getBeginLoc());
2471 QualType ET = SemaRef.Context.getBaseElementType(Field->getType());
2480 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2485 if (RD->isUnion() && StructuredList) {
2487 StructuredList->setInitializedFieldInUnion(*Field);
2498 if (!VerifyOnly && InitializedSomething && !RD->isUnion() &&
2499 !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
2503 for (RecordDecl::field_iterator it = HasDesignatedInit ? RD->field_begin()
2505 end = RD->field_end();
2510 if (!it->isUnnamedBitField() && !it->hasInClassInitializer() &&
2511 !it->getType()->isIncompleteArrayType()) {
2515 SemaRef.Diag(IList->getSourceRange().getEnd(), Diag) << *it;
2521 // Check that any remaining fields can be value-initialized if we're not
2523 if (!StructuredList && Field != FieldEnd && !RD->isUnion() &&
2524 !Field->getType()->isIncompleteArrayType()) {
2526 if (!Field->isUnnamedBitField() && !Field->hasInClassInitializer())
2529 IList->getEndLoc());
2537 RecordDecl::field_iterator I = HasDesignatedInit ? RD->field_begin()
2539 for (RecordDecl::field_iterator E = RD->field_end(); I != E; ++I) {
2540 QualType ET = SemaRef.Context.getBaseElementType(I->getType());
2541 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2548 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
2549 Index >= IList->getNumInits())
2552 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
2562 if (isa<InitListExpr>(IList->getInit(Index)) ||
2564 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2567 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
2570 if (RD->isUnion() && StructuredList) {
2572 StructuredList->setInitializedFieldInUnion(*Field);
2588 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
2589 PE = IndirectField->chain_end(); PI != PE; ++PI) {
2592 (IdentifierInfo *)nullptr, DIE->getDesignator(DesigIdx)->getDotLoc(),
2593 DIE->getDesignator(DesigIdx)->getFieldLoc()));
2604 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
2610 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
2613 IndexExprs[I] = DIE->getSubExpr(I + 1);
2614 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
2616 DIE->getEqualOrColonLoc(),
2617 DIE->usesGNUSyntax(), DIE->getInit());
2631 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
2644 /// Check the well-formedness of a C99 designated initializer.
2648 /// IList, is well-formed for a current object of type @p DeclType
2663 /// @param NextField If non-NULL and the first designator in @p DIE is
2669 /// @param NextElementIndex If non-NULL and the first designator in @p
2670 /// DIE is an array designator or GNU array-range designator, this
2694 if (DesigIdx == DIE->size()) {
2695 // C++20 designated initialization can result in direct-list-initialization
2699 if (DIE->isDirectInit()) {
2700 Expr *Init = DIE->getInit();
2702 "designator result in direct non-list initialization?");
2704 DIE->getBeginLoc(), Init->getBeginLoc(), Init->getEndLoc());
2716 AggrDeductionCandidateParamTypes->push_back(CurrentObjectType);
2725 // to re-process the designator.
2727 IList->setInit(OldIndex, DIE->getInit());
2734 if (IList->getInit(OldIndex) != DIE->getInit())
2735 DIE->setInit(IList->getInit(OldIndex));
2736 IList->setInit(OldIndex, DIE);
2741 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
2749 Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2750 StructuredList->getInit(StructuredIndex) : nullptr;
2751 if (!ExistingInit && StructuredList->hasArrayFiller())
2752 ExistingInit = StructuredList->getArrayFiller();
2757 SourceRange(D->getBeginLoc(), DIE->getEndLoc()));
2770 // designated initializer re-initializes only its current object
2773 SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
2780 StructuredList = E->getUpdater();
2783 DesignatedInitUpdateExpr(SemaRef.Context, D->getBeginLoc(),
2784 ExistingInit, DIE->getEndLoc());
2785 StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2786 StructuredList = DIUE->getUpdater();
2790 // designated init update of an already-fully-initialized object in
2791 // verify-only mode. The only reason we would need the structure is
2800 if (D->isFieldDesignator()) {
2812 SourceLocation Loc = D->getDotLoc();
2814 Loc = D->getFieldLoc();
2822 FieldDecl *KnownField = D->getFieldDecl();
2824 const IdentifierInfo *FieldName = D->getFieldName();
2833 D = DIE->getDesignator(DesigIdx);
2834 KnownField = cast<FieldDecl>(*IFD->chain_begin());
2839 return true; // No typo correction when just trying this out.
2843 if (SemaRef.DiagRedefinedPlaceholderFieldDecl(DIE->getBeginLoc(), RD,
2849 if (DeclContextLookupResult Lookup = RD->lookup(FieldName);
2851 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2853 SemaRef.Diag(Lookup.front()->getLocation(),
2863 DeclarationNameInfo(FieldName, D->getFieldLoc()),
2874 SourceLocation Loc = D->getFieldLoc();
2879 Loc = IList->getBeginLoc();
2882 << FieldName << CurrentObjectType << DIE->getSourceRange();
2891 NumBases = CXXRD->getNumBases();
2895 for (auto *FI : RD->fields()) {
2896 if (FI->isUnnamedBitField())
2910 if (RD->isUnion()) {
2913 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
2915 assert(StructuredList->getNumInits() == 1
2918 Expr *ExistingInit = StructuredList->getInit(0);
2922 ExistingInit, SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
2929 StructuredList->resizeInits(SemaRef.Context, 0);
2930 StructuredList->setInitializedFieldInUnion(nullptr);
2933 StructuredList->setInitializedFieldInUnion(*Field);
2942 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
2949 // The ordered identifiers in the designators of the designated-
2950 // initializer-list shall form a subsequence of the ordered identifiers
2951 // in the direct non-static data members of T.
2958 // catches cases where we have a top-level field designator that jumps
2960 // otherwise-valid C++20 program, so is the only case that's required for
2965 (*NextField == RD->field_end() ||
2966 (*NextField)->getFieldIndex() > Field->getFieldIndex() + 1)) {
2969 for (auto FI = RD->field_begin(); FI != RD->field_end(); ++FI) {
2970 if (FI->isUnnamedBitField())
2972 if (*NextField != RD->field_end() &&
2979 PrevField->getFieldIndex() > KnownField->getFieldIndex()) {
2980 SemaRef.Diag(DIE->getInit()->getBeginLoc(),
2982 << KnownField << PrevField << DIE->getSourceRange();
2984 unsigned OldIndex = StructuredIndex - 1;
2985 if (StructuredList && OldIndex <= StructuredList->getNumInits()) {
2986 if (Expr *PrevInit = StructuredList->getInit(OldIndex)) {
2987 SemaRef.Diag(PrevInit->getBeginLoc(),
2989 << PrevField << PrevInit->getSourceRange();
2998 D->setFieldDecl(*Field);
3000 // Make sure that our non-designated initializer list has space
3002 if (StructuredList && FieldIndex >= StructuredList->getNumInits())
3003 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
3006 if (Field->getType()->isIncompleteArrayType()) {
3008 if ((DesigIdx + 1) != DIE->size()) {
3013 = DIE->getDesignator(DesigIdx + 1);
3014 SemaRef.Diag(NextD->getBeginLoc(),
3016 << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc());
3017 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
3023 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
3024 !isa<StringLiteral>(DIE->getInit())) {
3027 SemaRef.Diag(DIE->getInit()->getBeginLoc(),
3029 << DIE->getInit()->getSourceRange();
3030 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
3037 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
3050 IList->setInit(Index, DIE->getInit());
3054 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
3057 IList->setInit(OldIndex, DIE);
3068 QualType FieldType = Field->getType();
3088 if (Field != RD->field_end() && Field->isUnnamedBitField())
3102 if (RD->isUnion())
3120 // [ constant-expression ]
3130 // [ constant-expression ... constant-expression ]
3134 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
3142 if (D->isArrayDesignator()) {
3143 IndexExpr = DIE->getArrayIndex(*D);
3144 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
3147 assert(D->isArrayRangeDesignator() && "Need array-range designator");
3150 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
3152 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
3153 IndexExpr = DIE->getArrayRangeEnd(*D);
3161 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
3162 FullyStructuredList->sawArrayRangeDesignator();
3166 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
3175 SemaRef.Diag(IndexExpr->getBeginLoc(),
3178 << IndexExpr->getSourceRange();
3194 StructuredList && StructuredList->isStringLiteralInit();
3203 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParenImpCasts();
3206 QualType CharTy = AT->getElementType();
3216 uint64_t StrLen = SL->getLength();
3217 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
3218 StrLen = cast<ConstantArrayType>(AT)->getZExtSize();
3219 StructuredList->resizeInits(Context, StrLen);
3224 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
3226 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
3231 StructuredList->updateInit(Context, i, Init);
3236 Context.getObjCEncodingForType(E->getEncodedType(), Str);
3240 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
3241 StrLen = cast<ConstantArrayType>(AT)->getZExtSize();
3242 StructuredList->resizeInits(Context, StrLen);
3249 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
3254 StructuredList->updateInit(Context, i, Init);
3259 // Make sure that our non-designated initializer list has space
3262 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
3263 StructuredList->resizeInits(SemaRef.Context,
3278 QualType ElementType = AT->getElementType();
3327 if (StructuredIndex < StructuredList->getNumInits())
3328 ExistingInit = StructuredList->getInit(StructuredIndex);
3366 if (Index < IList->getNumInits()) {
3367 if (auto *Init = dyn_cast_or_null<InitListExpr>(IList->getInit(Index)))
3368 ExpectedNumInits = Init->getNumInits();
3370 ExpectedNumInits = IList->getNumInits() - Index;
3378 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
3390 if (!ResultType->isArrayType())
3392 Result->setType(ResultType);
3394 // Pre-allocate storage for the structured initializer list.
3400 NumElements = CAType->getZExtSize();
3406 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) {
3407 NumElements = VType->getNumElements();
3408 } else if (CurrentObjectType->isRecordType()) {
3410 } else if (CurrentObjectType->isDependentType()) {
3414 Result->reserveInits(SemaRef.Context, NumElements);
3424 // No structured initializer list to update
3428 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
3431 // No need to diagnose when `expr` is nullptr because a more relevant
3435 diagnoseInitOverride(PrevInit, expr->getSourceRange());
3459 SourceLocation Loc = Index->getBeginLoc();
3469 << toString(Value, 10) << Index->getSourceRange();
3495 if (!Index->isTypeDependent() && !Index->isValueDependent())
3509 bool StartDependent = StartIndex->isTypeDependent() ||
3510 StartIndex->isValueDependent();
3511 bool EndDependent = EndIndex->isTypeDependent() ||
3512 EndIndex->isValueDependent();
3533 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
3554 //===----------------------------------------------------------------------===//
3556 //===----------------------------------------------------------------------===//
3564 Type = AT->getElementType();
3565 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
3567 Type = VT->getElementType();
3569 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
3572 Type = CT->getElementType();
3585 Result.Type = Base->getType();
3594 return (D ? D->getDeclName() : DeclarationName());
3602 return Variable.VariableOrMember->getDeclName();
3695 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
3697 OS << "`-";
3734 D->printQualifiedName(OS);
3742 LLVM_DUMP_METHOD void InitializedEntity::dump() const {
3746 //===----------------------------------------------------------------------===//
3748 //===----------------------------------------------------------------------===//
3872 S.Type = Function->getType();
4093 assert(Syntactic->getNumInits() == 1 &&
4097 S.Type = Syntactic->getInit(0)->getType();
4109 this->Failure = Failure;
4110 this->FailedOverloadResult = Result;
4113 //===----------------------------------------------------------------------===//
4115 //===----------------------------------------------------------------------===//
4125 if (VD->getInit() || VD->getEndLoc().isMacroID())
4128 QualType VariableTy = VD->getType().getCanonicalType();
4129 SourceLocation Loc = S.getLocForEndOfToken(VD->getEndLoc());
4150 assert(Entity.getType()->isObjCRetainableType() &&
4160 if (!Entity.getType()->isObjCRetainableType())
4188 if (!S.isCompleteType(List->getExprLoc(), E)) {
4197 List->getNumInits()),
4202 List->getExprLoc(), List->getBeginLoc(), List->getEndLoc());
4213 /// cv-qualified) T.
4216 if (Info.Constructor->getNumParams() == 0)
4220 Info.Constructor->getParamDecl(0)->getType().getNonReferenceType();
4222 Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext()));
4239 if (!Info.Constructor || Info.Constructor->isInvalidDecl())
4246 // ... and the constructor or user-defined conversion function is a
4248 // - 13.3.1.3, when the argument is the temporary in the second step
4249 // of a class copy-initialization, or
4250 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
4251 // - the second phase of 13.3.1.7 when the initializer list has exactly
4254 // is to X or reference to (possibly cv-qualified X),
4255 // user-defined conversion sequences are not considered.
4268 // - When initializing a temporary to be bound to the first parameter
4270 // cv-qualified T as its first argument, called with a single
4271 // argument in the context of direct-initialization, explicit
4287 // ([over.match.ctor]) or by list-initialization ([over.match.list])
4289 // U that convert to the non-reference type cv T are candidates.
4291 // direct-initialization.
4298 auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
4299 if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) {
4300 const auto &Conversions = SourceRD->getVisibleConversionFunctions();
4303 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4304 D = D->getUnderlyingDecl();
4309 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4337 /// \param IsListInit Is this list-initialization?
4338 /// \param IsInitListCopy Is this non-list-initialization resulting from a
4339 /// list-initialization from {x} where x is the same
4356 ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
4371 // - If the initializer expression is a prvalue and the cv-unqualified
4375 // Per DR (no number yet), this does not apply when initializing a base
4376 // class or delegating to another constructor from a mem-initializer.
4380 UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isPRValue() &&
4381 S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {
4389 const RecordType *DestRecordType = DestType->getAs<RecordType>();
4392 = cast<CXXRecordDecl>(DestRecordType->getDecl());
4403 // - Otherwise, if T is a class type, constructors are considered. The
4413 // When objects of non-aggregate type T are list-initialized, such that
4418 // - Initially, the candidate functions are the initializer-list
4424 // If the initializer list has no elements and T has a default constructor,
4434 // - If no viable initializer-list constructor is found, overload resolution
4459 if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
4460 // Add the user-defined conversion step that calls the conversion function.
4461 QualType ConvType = CD->getConversionType();
4464 Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
4473 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
4477 // of a const-qualified type T, T shall be a class type with a
4478 // user-provided default constructor.
4480 // If the implicit default constructor initializes all subobjects, no
4486 if (!CtorDecl->getParent()->allowConstDefaultInit()) {
4494 // In copy-list-initialization, if an explicit constructor is chosen, the
4495 // initializer is ill-formed.
4496 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
4503 // In some copy-initialization contexts, a two-stage overload resolution
4508 // For deleted functions in other contexts, there is no need to get the
4513 // Add the constructor initialization step. Any cv-qualification conversion is
4516 Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
4538 SourceType = Fn->getType();
4540 } else if (!UnqualifiedTargetType->isRecordType()) {
4584 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4590 // reference-related to the referenced type, bind directly to that element
4594 if (InitList->getNumInits() == 1) {
4595 Expr *Initializer = InitList->getInit(0);
4605 SourceLocation DeclLoc = Initializer->getBeginLoc();
4626 (void)S.Context.getUnqualifiedArrayType(InitList->getType(), T2Quals);
4637 // Not reference-related. Create a temporary and bind to that.
4644 if (DestType->isRValueReferenceType() ||
4647 isa<IncompleteArrayType>(T1->getUnqualifiedDesugaredType()) &&
4648 DestType->isRValueReferenceType()) {
4650 // List-initialization of an object or reference of type T is defined as
4661 cv1T1, DestType->isRValueReferenceType() ? VK_XValue : VK_LValue);
4679 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
4680 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
4684 if (DestType->isReferenceType()) {
4690 if (DestType->isRecordType() &&
4691 !S.isCompleteType(InitList->getBeginLoc(), DestType)) {
4697 // - If the braced-init-list contains a designated-initializer-list, T shall
4705 bool IsDesignatedInit = InitList->hasDesignatedInit();
4706 if (!DestType->isAggregateType() && IsDesignatedInit) {
4713 // - If T is a class type and the initializer list has a single element of
4715 // initialized from that element (by copy-initialization for
4716 // copy-list-initialization, or by direct-initialization for
4717 // direct-list-initialization).
4718 // - Otherwise, if T is a character array and the initializer list has a
4719 // single element that is an appropriately-typed string literal
4722 // - Otherwise, if T is an aggregate, [...] (continue below).
4723 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1 &&
4725 if (DestType->isRecordType()) {
4726 QualType InitType = InitList->getInit(0)->getType();
4728 S.IsDerivedFrom(InitList->getBeginLoc(), InitType, DestType)) {
4738 Expr *SubInit[1] = {InitList->getInit(0)};
4744 InitList->getLBraceLoc(),
4745 InitList->getRBraceLoc())
4752 // the element is not an appropriately-typed string literal, in which
4763 // - If T is an aggregate, aggregate initialization is performed.
4764 if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
4768 // - Otherwise, if the initializer list has no elements and T is a
4770 // value-initialized.
4771 if (InitList->getNumInits() == 0) {
4772 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
4779 // - Otherwise, if T is a specialization of std::initializer_list<E>,
4785 // - Otherwise, if T is a class type, constructors are considered.
4794 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
4795 InitList->getNumInits() == 1) {
4796 Expr *E = InitList->getInit(0);
4798 // - Otherwise, if T is an enumeration with a fixed underlying type,
4799 // the initializer-list has a single element v, and the initialization
4800 // is direct-list-initialization, the object is initialized with the
4802 // the underlying type of T, the program is ill-formed.
4803 auto *ET = DestType->getAs<EnumType>();
4806 ET && ET->getDecl()->isFixed() &&
4807 !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
4808 (E->getType()->isIntegralOrUnscopedEnumerationType() ||
4809 E->getType()->isFloatingType())) {
4813 // Otherwise, if v is of integral, unscoped enumeration, or floating-point
4815 // There is no overlap possible between these two cases (except when the
4817 // case is handled by the general case for single-element lists below.
4821 if (!E->isPRValue())
4823 // If E is of a floating-point type, then the conversion is ill-formed
4826 ICS.Standard.Second = E->getType()->isFloatingType()
4829 ICS.Standard.setFromType(E->getType());
4830 ICS.Standard.setToType(0, E->getType());
4839 // - Otherwise, if the initializer list has a single element of type E
4841 // initialized from that element (by copy-initialization for
4842 // copy-list-initialization, or by direct-initialization for
4843 // direct-list-initialization); if a narrowing conversion is required
4844 // to convert the element to T, the program is ill-formed.
4846 // Per core-24034, this is direct-initialization if we were performing
4847 // direct-list-initialization and copy-initialization otherwise.
4849 // copy-initialization. This only matters if we might use an 'explicit'
4854 Expr *Init = InitList->getInit(0);
4855 if (Init->getType()->isRecordType() ||
4856 (Init->getType()->isNullPtrType() && DestType->isBooleanType())) {
4860 InitList->getLBraceLoc(),
4861 InitList->getRBraceLoc())
4891 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4893 QualType cv2T2 = Initializer->getType();
4896 assert(!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2) &&
4907 // initializing a reference, not even for direct-initialization.
4912 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
4916 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
4923 if (!Info.Constructor->isInvalidDecl() &&
4924 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
4939 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
4943 if ((T2RecordType = T2->getAs<RecordType>()) &&
4947 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
4949 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4952 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4954 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4959 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4967 // candidates with reference-compatible results? That might be needed to
4970 Conv->getConversionType()->isLValueReferenceType())) {
4983 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
4986 SourceLocation DeclLoc = Initializer->getBeginLoc();
4994 FunctionDecl *Function = Best->Function;
4997 Function->setReferenced();
5002 cv3T3 = Function->getReturnType();
5007 if (cv3T3->isLValueReferenceType())
5009 else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
5010 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
5013 // Add the user-defined conversion step.
5015 Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3,
5018 // Determine whether we'll need to perform derived-to-base adjustments or
5031 ICS.Standard = Best->FinalConversion;
5035 // derived-to-base conversion, which we handle below.
5043 // We adjust the cv-qualifications to match the reference regardless of
5077 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
5097 /// Determine whether an expression is a non-referenceable glvalue (one to
5101 return E->refersToBitField() || E->refersToVectorElement() ||
5102 E->refersToMatrixElement();
5120 SourceLocation DeclLoc = Initializer->getBeginLoc();
5123 bool isLValueRef = DestType->isLValueReferenceType();
5125 Expr::Classification InitCategory = Initializer->Classify(S.Context);
5135 // - If the reference is an lvalue reference and the initializer
5138 // there are no function rvalues in C++, rvalue refs to functions are treated
5141 bool T1Function = T1->isFunctionType();
5147 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
5148 // reference-compatible with "cv2 T2," or
5152 // these qualifiers must all be top-level, so just convert to "cv1 T2".
5156 Initializer->getValueKind());
5162 // Perform a (possibly multi-level) qualification conversion.
5164 Initializer->getValueKind());
5170 // bit-field or vector element. Those cases are't supposed to be
5176 // - has a class type (i.e., T2 is a class type), where T1 is not
5177 // reference-related to T2, and can be implicitly converted to an
5178 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
5184 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
5203 // - Otherwise, the reference shall be an lvalue reference to a
5204 // non-volatile const type (i.e., cv1 shall be const), or the reference
5226 if (Initializer->refersToBitField())
5229 else if (Initializer->refersToVectorElement())
5232 else if (Initializer->refersToMatrixElement())
5251 // - If the initializer expression
5252 // - is an
5253 // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
5254 // [1z] rvalue (but not a bit-field) or
5255 // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
5264 (S.getLangOpts().CPlusPlus17 || T2->isRecordType() ||
5265 T2->isArrayType())))) {
5267 if (InitCategory.isPRValue() && T2->isRecordType()) {
5322 // - has a class type (i.e., T2 is a class type), where T1 is not
5323 // reference-related to T2, and can be implicitly converted to an
5325 // where "cv1 T1" is reference-compatible with "cv3 T3",
5328 if (T2->isRecordType()) {
5352 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
5353 // from the initializer expression using the rules for a non-reference
5354 // copy-initialization (8.5). The reference is then bound to the
5368 // copy-initialization?
5396 // [...] If T1 is reference-related to T2, cv1 must be the
5397 // same cv-qualification as, or greater cv-qualification
5398 // than, cv2; otherwise, the program is ill-formed.
5408 // [...] If T1 is reference-related to T2 and the reference is an rvalue
5447 assert((!InitList || InitList->getNumInits() == 0) &&
5448 "Shouldn't use value-init for non-empty init lists");
5452 // To value-initialize an object of type T means:
5455 // -- if T is an array type, then each element is value-initialized;
5458 if (const RecordType *RT = T->getAs<RecordType>()) {
5459 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
5462 // -- if T is a class type (clause 9) with a user-declared constructor
5464 // initialization is ill-formed if T has no accessible default
5467 // -- if T is a class type (clause 9) with either no default constructor
5468 // (12.1 [class.ctor]) or a default constructor that is user-provided
5469 // or deleted, then the object is default-initialized;
5471 // Note that the C++11 rule is the same as the C++98 rule if there are no
5474 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
5477 // -- if T is a (possibly cv-qualified) non-union class type without a
5478 // user-provided or deleted default constructor, then the object is
5479 // zero-initialized and, if T has a non-trivial default constructor,
5480 // default-initialized;
5481 // The 'non-union' here was removed by DR1502. The 'non-trivial default
5487 // -- if T is a non-union class type without a user-declared constructor,
5488 // then every non-static data member and base class component of T is
5489 // value-initialized;
5490 // [...] A program that calls for [...] value-initialization of an
5491 // entity of reference type is ill-formed.
5493 // C++11 doesn't need this handling, because value-initialization does not
5497 ClassDecl->hasUninitializedReferenceMember()) {
5502 // If this is list-value-initialization, pass the empty init list on when
5510 // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
5527 // To default-initialize an object of type T means:
5528 // - if T is an array type, each element is default-initialized;
5531 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
5532 // constructor for T is called (and the initialization is ill-formed if
5533 // T has no accessible default constructor);
5534 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
5540 // - otherwise, no initialization is performed.
5543 // a const-qualified type T, T shall be a class type with a user-provided
5551 // If the destination type has a lifetime property, zero-initialize it.
5606 // follows. Let x1, . . . , xk be the elements of the expression-list. If
5611 ArrayLength = CAT->getZExtSize();
5615 // Braced-initialization of variable array types is not allowed, even if
5619 const Expr *SE = VAT->getSizeExpr();
5620 S.Diag(SE->getBeginLoc(), diag::err_variable_object_no_init)
5621 << SE->getSourceRange();
5624 assert(Entity.getType()->isIncompleteArrayType());
5629 // ...the ith array element is copy-initialized with xi for each
5635 E->getExprLoc(), /*isDirectInit=*/false, E);
5639 // ...and value-initialized for each k < i <= n;
5651 AT->getElementType(), llvm::APInt(/*numBits=*/32, ArrayLength),
5654 } else if (auto *RT = Entity.getType()->getAs<RecordType>()) {
5655 bool IsUnion = RT->isUnionType();
5656 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
5657 if (RD->isInvalidDecl()) {
5667 for (const CXXBaseSpecifier &Base : RD->bases()) {
5674 // the elements of the expression-list...The element ei is
5675 // copy-initialized with xi for 1 <= i <= k.
5678 E->getExprLoc(), /*isDirectInit=*/false, E);
5696 for (FieldDecl *FD : RD->fields()) {
5699 if (FD->isUnnamedBitField())
5706 // ...The element ei is copy-initialized with xi for 1 <= i <= k.
5712 if (FD->getType()->isIncompleteArrayType()) {
5714 S.Diag(E->getBeginLoc(), diag::err_flexible_array_init)
5715 << SourceRange(E->getBeginLoc(), E->getEndLoc());
5716 S.Diag(FD->getLocation(), diag::note_flexible_array_member) << FD;
5724 E->getExprLoc(), /*isDirectInit=*/false, E);
5740 if (FD->hasInClassInitializer()) {
5755 if (FD->getType()->isReferenceType()) {
5761 << FD->getType() << SR;
5762 S.Diag(FD->getLocation(), diag::note_uninit_reference_member);
5783 int InitKind = T->isArrayType() ? 0 : T->isUnionType() ? 3 : 4;
5784 SourceRange ExcessInitSR(Args[EntityIndexToProcess]->getBeginLoc(),
5785 Args.back()->getEndLoc());
5801 CPLIE->setArrayFiller(ArrayFiller);
5803 CPLIE->setInitializedFieldInUnion(InitializedFieldInUnion);
5811 /// Attempt a user-defined conversion between two types (C++ [dcl.init]),
5820 assert(!DestType->isReferenceType() && "References are handled elsewhere");
5821 QualType SourceType = Initializer->getType();
5822 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
5823 "Must have a class type to perform a user-defined conversion");
5835 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
5839 = cast<CXXRecordDecl>(DestRecordType->getDecl());
5848 if (!Info.Constructor->isInvalidDecl() &&
5849 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
5866 SourceLocation DeclLoc = Initializer->getBeginLoc();
5868 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
5876 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
5879 SourceRecordDecl->getVisibleConversionFunctions();
5882 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
5884 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5889 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5913 // In some copy-initialization contexts, a two-stage overload resolution
5923 FunctionDecl *Function = Best->Function;
5924 Function->setReferenced();
5928 // Add the user-defined conversion step. Any cv-qualification conversion is
5930 // cv-unqualified type of the destination.
5931 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
5936 // - if the function is a constructor, the call initializes a temporary
5937 // of the cv-unqualified version of the destination type. The [...]
5938 // temporary [...] is then used to direct-initialize, according to the
5940 // copy-initialization.
5944 // - if the function is a constructor, the call is a prvalue of the
5945 // cv-unqualified version of the destination type whose return object
5947 // direct-initialize, according to the rules above, the object that
5948 // is the destination of the copy-initialization.
5959 // Add the user-defined conversion step that calls the conversion function.
5960 QualType ConvType = Function->getCallResultType();
5961 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
5964 if (ConvType->getAs<RecordType>()) {
5965 // The call is used to direct-initialize [...] the object that is the
5966 // destination of the copy-initialization.
5969 // - If the initializer expression is a prvalue and the cv-unqualified
5975 Function->getReturnType()->isReferenceType() ||
5985 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
5986 Best->FinalConversion.Third) {
5989 ICS.Standard = Best->FinalConversion;
5994 /// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
5999 /// Work around this by treating 'return false;' as zero-initializing the result
6000 /// if it's used in a pointer-returning function in a system header.
6006 Entity.getType()->isPointerType() &&
6008 !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
6009 S.getSourceManager().isInSystemHeader(Init->getExprLoc());
6012 /// The non-zero enum values here are indexes into diagnostic alternatives.
6019 e = e->IgnoreParens();
6021 // Skip address-of nodes.
6023 if (op->getOpcode() == UO_AddrOf)
6024 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
6029 switch (ce->getCastKind()) {
6034 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
6050 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
6055 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
6058 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
6062 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
6066 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
6074 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
6084 assert(src->isPRValue());
6094 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
6095 << ((unsigned) iik - 1) // shift index into diagnostic explanations
6096 << src->getSourceRange();
6100 /// purposes of GNU by-copy array initialization.
6109 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
6114 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
6122 QualType ArgType = Initializer->getType();
6126 ArgPointee = ArgArrayType->getElementType();
6130 // Handle write-back conversion.
6140 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
6143 if (ArrayDecay || Initializer->isGLValue()) {
6154 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
6168 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
6169 (!Initializer->isIntegerConstantExpr(S.Context) &&
6170 !Initializer->getType()->isSamplerT()))
6178 return Initializer->isIntegerConstantExpr(S.getASTContext()) &&
6179 (Initializer->EvaluateKnownConstInt(S.getASTContext()) == 0);
6197 if (DestType->isEventT() || DestType->isQueueT()) {
6210 DestType->isOCLIntelSubgroupAVCType()) {
6211 if (DestType->isOCLIntelSubgroupAVCMcePayloadType() ||
6212 DestType->isOCLIntelSubgroupAVCMceResultType())
6237 if (!DRE || !isa<FunctionDecl>(DRE->getDecl()))
6241 cast<FunctionDecl>(DRE->getDecl()));
6250 // For array members, the array elements are direct-initialized in
6256 // [...] each element is copy-initialized or direct-initialized from the
6257 // corresponding element of the assignment-expression [...]
6262 // - if the member is an array, each element is direct-initialized with
6288 // Eliminate non-overload placeholder types in the arguments. We
6290 // because lowering a pseudo-object expression might well give us
6293 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
6307 // defined when the initializer is a braced-init-list or when it is a
6311 if (DestType->isDependentType() ||
6326 Initializer->getBeginLoc(), DestType, Initializer->getType(),
6332 SourceType = Initializer->getType();
6335 // - If the initializer is a (non-parenthesized) braced-init-list, the
6336 // object is list-initialized (8.5.4).
6345 // - If the destination type is a reference type, see 8.5.3.
6346 if (DestType->isReferenceType()) {
6366 // - If the initializer is (), the object is value-initialized.
6379 // - If the destination type is an array of characters, an array of
6382 // - Otherwise, if the destination type is an array, the program is
6383 // ill-formed.
6384 // - Except in HLSL, where non-decaying array parameters behave like
6385 // non-array types for initialization.
6386 if (DestType->isArrayType() && !DestType->isArrayParameterType()) {
6421 S.Context.hasSameUnqualifiedType(Initializer->getType(),
6425 if (Initializer->isPRValue()) {
6430 // Emit element-at-a-time copy loop.
6434 Context.getAsArrayType(Initializer->getType())->getElementType();
6435 OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT,
6436 Initializer->getValueKind(),
6437 Initializer->getObjectKind());
6448 // type, so long as the initializer has no side effects.
6450 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
6451 Initializer->getType()->isArrayType()) {
6453 = Context.getAsArrayType(Initializer->getType());
6456 else if (Initializer->HasSideEffects(S.Context))
6462 // Note: as a GNU C++ extension, we allow list-initialization of a
6474 else if (DestAT->getElementType()->isCharType())
6476 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
6485 // Objective-C ARC.
6492 // We're at the end of the line for C: it's either a write-back conversion
6493 // or it's a C assignment. There's no need to check anything else.
6495 assert(Initializer && "Initializer must be non-null");
6496 // If allowed, check whether this is an Objective-C writeback conversion.
6513 // - If the destination type is a (possibly cv-qualified) class type:
6514 if (DestType->isRecordType()) {
6515 // - If the initialization is direct-initialization, or if it is
6516 // copy-initialization where the cv-unqualified version of the
6522 (Initializer && S.IsDerivedFrom(Initializer->getBeginLoc(),
6527 // We fall back to the "no matching constructor" path if the
6531 dyn_cast<CXXRecordDecl>(DestType->getAs<RecordType>()->getDecl());
6535 S.getLangOpts().CPlusPlus20 && RD && RD->hasDefinition() &&
6536 RD->isAggregate() && Failed() &&
6542 // a non-trivial copy or move constructor and we call one of those two
6552 // - Otherwise, if no constructor is viable, the destination type is
6555 // expression-list.
6561 // - Otherwise (i.e., for the remaining copy-initialization cases),
6562 // user-defined conversion sequences that can convert from the
6567 assert(Initializer && "Initializer must be non-null");
6574 assert(Args.size() >= 1 && "Zero-argument case handled above");
6579 if (S.getLangOpts().HLSL && Args.size() > 1 && DestType->isExtVectorType() &&
6585 if (Arg->getType()->isExtVectorType()) {
6586 const auto *VTy = Arg->getType()->castAs<ExtVectorType>();
6587 unsigned Elm = VTy->getNumElements();
6594 VTy->getElementType(), Arg->getValueKind(), Arg->getObjectKind(),
6616 // - Otherwise, if the source type is a (possibly cv-qualified) class
6618 if (!SourceType.isNull() && SourceType->isRecordType()) {
6619 assert(Initializer && "Initializer must be non-null");
6623 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
6624 if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
6625 S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType,
6626 Atomic->getValueType())) {
6627 DestType = Atomic->getValueType();
6640 // - Otherwise, if the initialization is direct-initialization, the source
6643 if (!SourceType.isNull() && SourceType->isNullPtrType() &&
6644 DestType->isBooleanType() &&
6648 Initializer->isGLValue()),
6653 // - Otherwise, the initial value of the object being initialized is the
6656 // initializer expression to the cv-unqualified version of the
6657 // destination type; no user-defined conversions are considered.
6669 // Objective-C ARC writeback conversion.
6675 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
6693 Initializer->getType() == Context.OverloadTy &&
6697 else if (Initializer->getType()->isFunctionType() &&
6714 //===----------------------------------------------------------------------===//
6716 //===----------------------------------------------------------------------===//
6729 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
6736 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
6852 return Entity.getDecl()->getLocation();
6873 return Initializer->getBeginLoc();
6882 /// \param S The Sema object used for type-checking.
6908 if (const RecordType *Record = T->getAs<RecordType>())
6909 Class = cast<CXXRecordDecl>(Record->getDecl());
6921 // is direct-initialization.
6941 << (int)Entity.getKind() << CurInitExpr->getType()
6942 << CurInitExpr->getSourceRange()),
6952 << CurInitExpr->getType()
6953 << CurInitExpr->getSourceRange()),
6959 << (int)Entity.getKind() << CurInitExpr->getType()
6960 << CurInitExpr->getSourceRange();
6961 S.NoteDeletedFunction(Best->Function);
6967 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
6971 S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity,
6985 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
6986 ParmVarDecl *Parm = Constructor->getParamDecl(I);
6987 if (S.RequireCompleteType(Loc, Parm->getType(),
7001 // constructor call (we might have derived-to-base conversions, or
7012 // - when a temporary class object that has not been bound to a
7014 // with the same cv-unqualified type, the copy/move operation
7021 // is handled by the run-time.
7027 CurInitExpr->isTemporaryObject(S.Context, Class) &&
7029 Best->Function->getParamDecl(0)->getType().getNonReferenceType(),
7030 CurInitExpr->getType());
7034 Loc, T, Best->FoundDecl, Constructor, Elidable, ConstructorArgs,
7048 /// -Wc++98-compat.
7054 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
7065 S.LookupConstructors(cast<CXXRecordDecl>(Record->getDecl()));
7070 S, Loc, CurInitExpr, CandidateSet, CurInitExpr->getType(), Ctors, Best,
7077 << OR << (int)Entity.getKind() << CurInitExpr->getType()
7078 << CurInitExpr->getSourceRange();
7082 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
7083 Best->FoundDecl, Entity, Diag);
7099 S.NoteDeletedFunction(Best->Function);
7107 if (Entity.getDecl()->getLocation().isInvalid())
7110 if (Entity.getDecl()->getDeclName())
7111 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
7112 << Entity.getDecl()->getDeclName();
7114 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
7118 S.Diag(Entity.getMethodDecl()->getLocation(),
7120 << Entity.getMethodDecl()->getDeclName();
7175 assert(Constructor->getParent() && "No parent class for constructor.");
7176 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
7177 Constructor->isTrivial() && !Constructor->isUsed(false)) {
7187 // - When initializing a temporary to be bound to the first parameter
7188 // of a constructor that takes a reference to possibly cv-qualified
7190 // context of direct-initialization, explicit conversion functions
7200 Entity.getType(), Args.front()->getType(), Kind.getLocation());
7210 // An explicitly-constructed temporary, e.g., X(1, 2).
7241 ConstructKind = Entity.getBaseSpecifier()->isVirtual()
7322 QualType DestType = InitExpr->getType();
7323 if (!DestType->isRecordType())
7329 dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens());
7330 if (!CCE || CCE->getNumArgs() != 1)
7333 if (!CCE->getConstructor()->isCopyOrMoveConstructor())
7336 InitExpr = CCE->getArg(0)->IgnoreImpCasts();
7340 const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens());
7341 if (!CE || !CE->isCallToStdMove())
7344 const Expr *Arg = CE->getArg(0)->IgnoreImplicit();
7347 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts());
7348 if (!DRE || DRE->refersToEnclosingVariableOrCapture())
7351 const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
7352 if (!VD || !VD->hasLocalStorage())
7356 if (VD->hasAttr<BlocksAttr>())
7359 QualType SourceType = VD->getType();
7360 if (!SourceType->isRecordType())
7375 const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();
7376 if (!ArgStripped->isPRValue() || !ArgStripped->getType()->isRecordType())
7380 S.Diag(CE->getBeginLoc(), DiagID);
7382 // Get all the locations for a fix-it. Don't emit the fix-it if any location
7384 SourceLocation CallBegin = CE->getCallee()->getBeginLoc();
7387 SourceLocation RParen = CE->getRParenLoc();
7391 SourceLocation ArgLoc = Arg->getBeginLoc();
7393 // Special testing for the argument location. Since the fix-it needs the
7404 LParen = ArgLoc.getLocWithOffset(-1);
7406 S.Diag(CE->getBeginLoc(), diag::note_remove_move)
7415 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
7416 if (UO->getOpcode() == UO_Deref &&
7417 UO->getSubExpr()->IgnoreParenCasts()->
7419 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
7421 << UO->getSubExpr()->getSourceRange());
7450 if (!E->isPRValue() || !getLangOpts().CPlusPlus11)
7455 // If so, we should check for a non-abstract class type here too.
7456 QualType T = E->getType();
7457 if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type))
7460 return CreateMaterializeTemporaryExpr(E->getType(), E, false);
7470 auto PointeeTy = Ty->getPointeeType();
7471 auto ExprPointeeTy = E->getType()->getPointeeType();
7475 } else if (Ty.getAddressSpace() != E->getType().getAddressSpace()) {
7499 if (!DestType->isRecordType() && VD && VD->isConstexpr()) {
7507 if (S.getLangOpts().MSVCCompat && D && D->hasAttr<SelectAnyAttr>())
7511 << DestType << (bool)DestType->getAs<RecordType>()
7518 // If the declaration is a non-dependent, incomplete array type
7521 if (ResultType && !Entity.getType()->isDependentType() &&
7528 // performing full type-checking of the initializer list
7531 // type a dependently-sized array type with no specified
7538 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
7539 TypeLoc TL = TInfo->getTypeLoc();
7547 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
7549 ArrayT->getSizeModifier(),
7550 ArrayT->getIndexTypeCVRQualifiers(),
7569 // No steps means no initialization.
7573 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
7580 S.Diag(Init->getBeginLoc(), diag::warn_cxx98_compat_reference_list_init)
7581 << Init->getSourceRange();
7585 isa<PredefinedExpr>(Args[0]) && Entity.getType()->isArrayType()) {
7590 S.Diag(Init->getBeginLoc(), diag::ext_init_from_predefined) << Init;
7599 ETy->isAtomicType() && !HasGlobalAS &&
7601 S.Diag(Args[0]->getBeginLoc(), diag::err_opencl_atomic_init)
7603 << SourceRange(Entity.getDecl()->getBeginLoc(), Args[0]->getEndLoc());
7609 // the same as Entity.getDecl()->getType() in cases involving type merging,
7612 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
7619 // use the syntax of a C++-like constructor.
7620 bool IsHLSLVectorInit = S.getLangOpts().HLSL && DestType->isExtVectorType() &&
7676 // C++11 list-initialization; we need to instantiate entities usable in
7683 // no objects of an abstract class can be created except as subobjects
7685 auto checkAbstractType = [&](QualType T) -> bool {
7701 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
7703 switch (Step->Kind) {
7707 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
7708 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
7711 Step->Function.FoundDecl,
7712 Step->Function.Function);
7722 // We have a derived-to-base cast that produces either an rvalue or an
7727 // Casts to inaccessible base classes are allowed with C-style casts.
7730 SourceType, Step->Type, CurInit.get()->getBeginLoc(),
7731 CurInit.get()->getSourceRange(), &BasePath, IgnoreBaseAccess))
7735 Step->Kind == SK_CastDerivedToBaseLValue
7737 : (Step->Kind == SK_CastDerivedToBaseXValue ? VK_XValue
7739 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
7755 if (CurInit.get()->getType()->isFunctionProtoType()) {
7756 if (auto *DRE = dyn_cast<DeclRefExpr>(CurInit.get()->IgnoreParens())) {
7757 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
7759 DRE->getBeginLoc()))
7770 assert(CurInit.get()->isPRValue() && "not a temporary");
7776 QualType MTETy = Step->Type;
7781 if (MTETy->isIncompleteArrayType() &&
7782 !CurInit.get()->getType()->isIncompleteArrayType() &&
7784 MTETy->getPointeeOrArrayElementType(),
7785 CurInit.get()->getType()->getPointeeOrArrayElementType()))
7786 MTETy = CurInit.get()->getType();
7790 MTETy, CurInit.get(), Entity.getType()->isLValueReferenceType());
7793 // If we're extending this temporary to automatic storage duration -- we
7794 // need to register its cleanup during the full-expression's cleanups.
7795 if (MTE->getStorageDuration() == SD_Automatic &&
7796 MTE->getType().isDestructedType())
7802 if (checkAbstractType(Step->Type))
7807 // ultimately initializing a non-temporary), our argument needs to be
7812 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
7817 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
7822 // We have a user-defined conversion that invokes either a constructor
7825 FunctionDecl *Fn = Step->Function.Function;
7826 DeclAccessPair FoundFn = Step->Function.FoundDecl;
7827 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
7832 SourceLocation Loc = CurInit.get()->getBeginLoc();
7837 if (S.CompleteConstructorCall(Constructor, Step->Type,
7844 Loc, Step->Type, FoundFn, Constructor, ConstructorArgs,
7873 CreatedObject = Conversion->getReturnType()->isRecordType();
7876 if (CreatedObject && checkAbstractType(CurInit.get()->getType()))
7880 S.Context, CurInit.get()->getType(), CastKind, CurInit.get(), nullptr,
7881 CurInit.get()->getValueKind(), S.CurFPFeatureOverrides());
7885 // destroyed at the end of its full-expression.
7888 // The object outlasts the full-expression, but we need to prepare for
7890 // FIXME: It makes no sense to do this here. This should happen
7892 QualType T = CurInit.get()->getType();
7893 if (const RecordType *Record = T->getAs<RecordType>()) {
7895 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
7896 S.CheckDestructorAccess(CurInit.get()->getBeginLoc(), Destructor,
7898 S.MarkFunctionReferenced(CurInit.get()->getBeginLoc(), Destructor);
7899 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getBeginLoc()))
7911 Step->Kind == SK_QualificationConversionLValue
7913 : (Step->Kind == SK_QualificationConversionXValue ? VK_XValue
7915 CurInit = S.PerformQualificationConversion(CurInit.get(), Step->Type, VK);
7920 assert(CurInit.get()->isLValue() &&
7923 S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK_LValue);
7927 assert(CurInit.get()->isPRValue() && "cannot convert glvalue to atomic");
7928 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
7936 CurInit.get()->getType()->getAs<PointerType>()) {
7937 if (const auto *ToPtrType = Step->Type->getAs<PointerType>()) {
7938 if (FromPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
7939 !ToPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
7943 S.Diag(CurInit.get()->getExprLoc(),
7945 << CurInit.get()->getSourceRange();
7957 Init, Step->Type, *Step->ICS, getAssignmentAction(Entity), CCK);
7961 S.DiscardMisalignedMemberAddress(Step->Type.getTypePtr(), Init);
7965 if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
7967 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
7974 if (checkAbstractType(Step->Type))
7978 // If we're not initializing the top-level entity, we need to create an
7980 QualType Ty = Step->Type;
7994 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
7995 if ((*ResultType)->isRValueReferenceType())
7997 else if ((*ResultType)->isLValueReferenceType())
7999 (*ResultType)->castAs<LValueReferenceType>()->isSpelledAsLValue());
8013 if (checkAbstractType(Step->Type))
8024 bool UseTemporary = Entity.getType()->isReferenceType();
8027 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
8028 << InitList->getSourceRange();
8029 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
8036 InitList->getLBraceLoc(),
8037 InitList->getRBraceLoc());
8042 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
8047 InitListExpr *Syntactic = Step->WrappingSyntacticList;
8049 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
8050 ILE->setSyntacticForm(Syntactic);
8051 ILE->setType(E->getType());
8052 ILE->setValueKind(E->getValueKind());
8059 if (checkAbstractType(Step->Type))
8070 bool UseTemporary = Entity.getType()->isReferenceType();
8072 Step->Kind == SK_StdInitializerListConstructorCall;
8092 (NextStep->Kind == SK_ConstructorInitialization ||
8093 NextStep->Kind == SK_ConstructorInitializationFromList)) {
8094 // The need for zero-initialization is recorded directly into
8102 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
8109 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
8115 QualType SourceType = CurInit.get()->getType();
8122 S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
8132 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
8143 // C23 6.7.1p6: If an object or subobject declared with storage-class
8149 if (Entity.getType()->getAs<PointerType>() &&
8150 CurInit.get()->EvaluateAsRValue(ER, S.Context) &&
8158 Step->Type, SourceType,
8170 QualType Ty = Step->Type;
8171 bool UpdateType = ResultType && Entity.getType()->isIncompleteArrayType();
8180 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
8182 CurInit.get()->getValueKind());
8188 OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(),
8189 Cur->getValueKind(), Cur->getObjectKind(), Cur);
8202 CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common,
8211 << Step->Type << CurInit.get()->getType()
8212 << CurInit.get()->getSourceRange();
8220 = S.Context.getAsIncompleteArrayType(Step->Type)) {
8222 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
8224 IncompleteDest->getElementType(), ConstantSource->getSize(),
8225 ConstantSource->getSizeExpr(), ArraySizeModifier::Normal, 0);
8235 << CurInit.get()->getSourceRange();
8242 CurInit.get(), Step->Type,
8243 Step->Kind == SK_PassByIndirectCopyRestore);
8248 S.Context, Step->Type, CK_ARCProduceObject, CurInit.get(), nullptr,
8253 S.Diag(CurInit.get()->getExprLoc(),
8255 << CurInit.get()->getSourceRange();
8259 CurInit.get()->getType(), CurInit.get(),
8263 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
8265 if (!Step->Type->isDependentType()) {
8268 S.isStdInitializerList(Step->Type, &ElementType);
8270 "StdInitializerList step to non-std::initializer_list");
8272 Step->Type->getAsCXXRecordDecl()->getDefinition();
8273 assert(Record && Record->isCompleteDefinition() &&
8278 S.Diag(Record->getLocation(),
8280 << Step->Type.getUnqualifiedType();
8284 if (Record->isUnion() || Record->getNumBases() != 0 ||
8285 Record->isPolymorphic())
8288 RecordDecl::field_iterator Field = Record->field_begin();
8289 if (Field == Record->field_end())
8293 if (!Field->getType()->isPointerType() ||
8294 !S.Context.hasSameType(Field->getType()->getPointeeType(),
8298 if (++Field == Record->field_end())
8302 if (const auto *PT = Field->getType()->getAs<PointerType>()) {
8303 if (!S.Context.hasSameType(PT->getPointeeType(),
8307 if (Field->isBitField() ||
8308 !S.Context.hasSameType(Field->getType(), S.Context.getSizeType()))
8312 if (++Field != Record->field_end())
8317 // non-trivial destructor.
8326 // 1a. argument is a file-scope variable
8327 // 1b. argument is a function-scope variable
8330 // 2a. initializing a file-scope variable
8331 // 2b. initializing a function-scope variable
8333 // For file-scope variables, since they cannot be initialized by function
8339 assert(Step->Type->isSamplerT() &&
8340 "Sampler initialization on non-sampler type.");
8341 Expr *Init = CurInit.get()->IgnoreParens();
8342 QualType SourceType = Init->getType();
8345 if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) {
8350 auto Var = cast<VarDecl>(DRE->getDecl());
8352 // No cast from integer to sampler is needed.
8353 if (!Var->hasGlobalStorage()) {
8355 S.Context, Step->Type, CK_LValueToRValue, Init,
8360 // For function call with a file-scope sampler variable as argument,
8362 // Do not diagnose if the file-scope variable does not have initializer
8365 if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit()))
8368 Var->getInit()))->getSubExpr();
8369 SourceType = Init->getType();
8376 if (!Init->isConstantInitializer(S.Context, false))
8379 if (!SourceType->isIntegerType() ||
8387 Init->EvaluateAsInt(EVResult, S.Context);
8390 // 32-bit value of sampler's initializer is interpreted as
8391 // bit-field with the following structure:
8395 // defined in SPIR spec v1.2 and also opencl-c.h
8417 assert((Step->Type->isEventT() || Step->Type->isQueueT() ||
8418 Step->Type->isOCLIntelSubgroupAVCType()) &&
8421 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
8423 CurInit.get()->getValueKind());
8431 *ResultType = CurInit.get()->getType();
8444 // entity, and if not, either lifetime-extend or warn as appropriate.
8447 // Diagnose non-fatal problems with the completed initialization.
8451 cast<FieldDecl>(Entity.getDecl())->isBitField())
8466 if (T->isReferenceType()) {
8472 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
8473 if (!RD || !RD->hasUninitializedReferenceMember())
8476 for (const auto *FI : RD->fields()) {
8477 if (FI->isUnnamedBitField())
8480 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
8486 for (const auto &BI : RD->bases()) {
8497 //===----------------------------------------------------------------------===//
8499 //===----------------------------------------------------------------------===//
8506 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
8507 op->getType()->isObjCObjectPointerType()) {
8518 QualType fromType = op->getType();
8519 QualType fromPointeeType = fromType.getCanonicalType()->getPointeeType();
8520 QualType destPointeeType = destType.getCanonicalType()->getPointeeType();
8521 auto *fromDecl = fromType->getPointeeCXXRecordDecl();
8522 auto *destDecl = destType->getPointeeCXXRecordDecl();
8523 if (fromDecl && destDecl && fromDecl->getDeclKind() == Decl::CXXRecord &&
8524 destDecl->getDeclKind() == Decl::CXXRecord &&
8525 !fromDecl->isInvalidDecl() && !destDecl->isInvalidDecl() &&
8526 !fromDecl->hasDefinition() &&
8529 S.Diag(fromDecl->getLocation(), diag::note_forward_class_conversion)
8543 InitList->getNumInits()),
8550 if (DestType->isReferenceType()) {
8551 // A list-initialization failure for a reference means that we tried to
8554 QualType T = DestType->castAs<ReferenceType>()->getPointeeType();
8556 SourceLocation Loc = InitList->getBeginLoc();
8558 Loc = D->getLocation();
8579 // When we want to diagnose only one element of a braced-init-list,
8584 if (List && List->getNumInits() == 1)
8585 OnlyArg = List->getInit(0);
8589 if (OnlyArg->getType() == S.Context.OverloadTy) {
8608 // If this is value-initialization, this could be nested some way within
8611 DestType->isReferenceType());
8618 << SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
8622 << 1 << Entity.getType() << Args[0]->getSourceRange();
8647 S.Diag(Args.front()->getBeginLoc(),
8649 << FixItHint::CreateInsertion(Args.front()->getBeginLoc(), "u8");
8653 << DestType->isSignedIntegerType() << S.getLangOpts().CPlusPlus20;
8662 << OnlyArg->getType()
8663 << Args[0]->getSourceRange();
8668 << Args[0]->getSourceRange();
8681 auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(OnlyArg)->getDecl());
8683 OnlyArg->getBeginLoc());
8697 << OnlyArg->getType() << DestType
8698 << Args[0]->getSourceRange())
8700 << DestType << OnlyArg->getType()
8701 << Args[0]->getSourceRange())),
8710 OnlyArg->getType(), Args[0]->getSourceRange()))
8713 << OnlyArg->getType() << Args[0]->getSourceRange()
8724 StringLiteral *Msg = Best->Function->getDeletedMessage();
8726 << OnlyArg->getType() << DestType.getNonReferenceType()
8727 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
8728 << Args[0]->getSourceRange();
8730 S.NoteDeletedFunction(Best->Function);
8748 << Args[0]->getSourceRange();
8760 << OnlyArg->getType()
8761 << Args[0]->getSourceRange();
8765 // We don't necessarily have an unambiguous source bit-field.
8766 FieldDecl *BitField = Args[0]->getSourceBitField();
8769 << (BitField ? BitField->getDeclName() : DeclarationName())
8771 << Args[0]->getSourceRange();
8773 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
8780 << Args[0]->getSourceRange();
8785 << DestType.isVolatileQualified() << Args[0]->getSourceRange();
8790 << DestType.getNonReferenceType() << OnlyArg->getType()
8791 << Args[0]->getSourceRange();
8796 << DestType << Args[0]->getSourceRange();
8800 QualType SourceType = OnlyArg->getType();
8803 SourceType.getQualifiers() - NonRefType.getQualifiers();
8809 << Args[0]->getSourceRange();
8814 << DroppedQualifiers.getCVRQualifiers() << Args[0]->getSourceRange();
8820 << Args[0]->getSourceRange();
8827 << DestType.getNonReferenceType()->isIncompleteType()
8828 << OnlyArg->isLValue()
8829 << OnlyArg->getType()
8830 << Args[0]->getSourceRange();
8835 QualType FromType = OnlyArg->getType();
8839 << OnlyArg->isLValue()
8841 << Args[0]->getSourceRange();
8849 // No-op. This error has already been reported.
8856 if (InitList && InitList->getNumInits() >= 1) {
8857 R = SourceRange(InitList->getInit(0)->getEndLoc(), InitList->getEndLoc());
8860 R = SourceRange(Args.front()->getEndLoc(), Args.back()->getEndLoc());
8875 << 0 << Entity.getType() << Args[0]->getSourceRange();
8880 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
8885 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
8893 SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
8899 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
8920 // base within a constructor. If no viable function was
8926 if (auto Inherited = Constructor->getInheritedConstructor())
8927 InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass();
8930 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
8931 << S.Context.getTypeDeclType(Constructor->getParent())
8937 = Entity.getBaseSpecifier()->getType()->castAs<RecordType>()
8938 ->getDecl();
8939 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
8943 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
8944 << S.Context.getTypeDeclType(Constructor->getParent())
8948 S.Diag(Entity.getDecl()->getLocation(),
8952 = Entity.getType()->getAs<RecordType>())
8953 S.Diag(Record->getDecl()->getLocation(),
8955 << S.Context.getTagDeclType(Record->getDecl());
8979 // If this is a defaulted or implicitly-declared function, then
8982 if (S.isImplicitlyDeleted(Best->Function))
8985 S.getSpecialMember(cast<CXXMethodDecl>(Best->Function)))
8988 StringLiteral *Msg = Best->Function->getDeletedMessage();
8991 << (Msg ? Msg->getString() : StringRef()) << ArgsRange;
8994 S.NoteDeletedFunction(Best->Function);
9007 // This is implicit default-initialization of a const member in
9012 << (Constructor->getInheritedConstructor() ? 2 :
9013 Constructor->isImplicit() ? 1 : 0)
9014 << S.Context.getTypeDeclType(Constructor->getParent())
9017 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
9020 VD && VD->isConstexpr()) {
9025 << DestType << (bool)DestType->getAs<RecordType>();
9048 << Args[0]->getSourceRange();
9054 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
9055 S.Diag(CtorDecl->getLocation(),
9068 << Entity.getType() << InitList->getSourceRange();
9076 void InitializationSequence::dump(raw_ostream &OS) const {
9130 OS << "non-constant array initializer";
9142 OS << "non-const lvalue reference bound to temporary";
9146 OS << "non-const lvalue reference bound to bit-field";
9150 OS << "non-const lvalue reference bound to vector element";
9154 OS << "non-const lvalue reference bound to matrix element";
9158 OS << "non-const lvalue reference bound to unrelated type";
9198 OS << "initializer list for non-aggregate, non-scalar type";
9202 OS << "overloading failed for user-defined conversion";
9242 OS << "designated initializer for non-aggregate type";
9260 OS << " -> ";
9263 switch (S->Kind) {
9269 OS << "derived-to-base (prvalue)";
9273 OS << "derived-to-base (xvalue)";
9277 OS << "derived-to-base (lvalue)";
9289 OS << "final copy in class direct-initialization";
9297 OS << "user-defined conversion via " << *S->Function.Function;
9317 OS << "non-atomic-to-atomic conversion";
9322 S->ICS->dump(); // FIXME: use OS
9328 S->ICS->dump(); // FIXME: use OS
9365 OS << "Objective-C object conversion";
9397 OS << "Objective-C object retension";
9420 OS << " [" << S->Type << ']';
9426 void InitializationSequence::dump() const {
9427 dump(llvm::errs());
9459 return S.Diag(PostInit->getBeginLoc(), DiagID)
9460 << PostInit->getSourceRange();
9466 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
9470 // No narrowing occurred.
9474 // This was a floating-to-integer conversion, which is always considered a
9512 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
9517 // getQualifiedNameAsString() includes non-machine-parsable components.
9518 OS << *TT->getDecl();
9519 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
9520 OS << BT->getName(S.getLangOpts());
9522 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
9527 S.Diag(PostInit->getBeginLoc(), diag::note_init_list_narrowing_silence)
9528 << PostInit->getSourceRange()
9529 << FixItHint::CreateInsertion(PostInit->getBeginLoc(), OS.str())
9531 S.getLocForEndOfToken(PostInit->getEndLoc()), ")");
9538 Init->IgnoreParenImpCasts(), ToType, /*SuppressUserConversions*/ false,
9555 S.Diag(Init->getBeginLoc(), diag::err_c23_constexpr_init_not_representable)
9561 S.Diag(Init->getBeginLoc(), diag::err_c23_constexpr_init_type_mismatch)
9578 // character that string literal contains fits into TT - target type.
9580 QualType CharType = AT->getElementType();
9582 bool isUnsigned = CharType->isUnsignedIntegerType();
9584 for (unsigned I = 0, N = SE->getLength(); I != N; ++I) {
9585 int64_t C = SE->getCodeUnitS(I, SemaRef.Context.getCharWidth());
9597 //===----------------------------------------------------------------------===//
9599 //===----------------------------------------------------------------------===//
9607 assert(InitE && "No initialization expression");
9610 InitializationKind::CreateCopy(InitE->getBeginLoc(), SourceLocation());
9625 assert(InitE && "No initialization expression?");
9628 EqualLoc = InitE->getBeginLoc();
9631 InitE->getBeginLoc(), EqualLoc, AllowExplicit);
9634 // Prevent infinite recursion when performing parameter copy-initialization.
9645 const auto LastStep = Seq.step_end() - 1;
9646 assert(LastStep->Kind ==
9648 const FunctionDecl *Function = LastStep->Function.Function;
9651 [Function](const OverloadCandidate &Candidate) -> bool {
9657 Function->getNumParams() > 0) {
9658 Candidate->Viable = false;
9659 Candidate->FailureKind = ovl_fail_bad_conversion;
9660 Candidate->Conversions[0].setBad(BadConversionSequence::no_conversion,
9662 Function->getParamDecl(0)->getType());
9681 return !CTSD || !declaresSameEntity(CTSD->getSpecializedTemplate(), CTD);
9683 return !(NotSpecialization(RD) && RD->forallBases(NotSpecialization));
9690 TSInfo->getType()->getContainedDeducedType());
9693 auto TemplateName = DeducedTST->getTemplateName();
9695 return SubstAutoTypeDependent(TSInfo->getType());
9707 auto UnderlyingType = AliasTemplate->getTemplatedDecl()
9708 ->getUnderlyingType()
9710 // C++ [over.match.class.deduct#3]: ..., the defining-type-id of A must be
9712 // [typename] [nested-name-specifier] [template] simple-template-id
9714 UnderlyingType->getAs<TemplateSpecializationType>()) {
9716 TST->getTemplateName().getAsTemplateDecl());
9717 } else if (const auto *RT = UnderlyingType->getAs<RecordType>()) {
9722 RT->getAsCXXRecordDecl()))
9723 Template = CTSD->getSpecializedTemplate();
9738 Diag(TSInfo->getTypeLoc().getBeginLoc(),
9740 << TSInfo->getTypeLoc().getSourceRange() << 0;
9741 return SubstAutoTypeDependent(TSInfo->getType());
9745 // Or implement this via an implied 'T(T) -> T' deduction guide?
9751 // - For each constructor of the class template designated by the
9752 // template-name, a function template [...]
9753 // - For each deduction-guide, a function or function template [...]
9756 TSInfo->getTypeLoc().getEndLoc());
9758 LookupQualifiedName(Guides, LookupTemplateDecl->getDeclContext());
9764 // Figure out if this is list-initialization.
9791 // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class)
9792 // For copy-initialization, the candidate functions are all the
9794 // C++ [over.match.copy]p1: (non-list copy-initialization from class)
9803 if (GD->getMinRequiredArguments() > 1 ||
9804 (GD->getNumParams() == 0 && !GD->isVariadic()))
9809 // Initially, the candidate functions are the initializer-list
9815 GD->getDeductionCandidateKind() == DeductionCandidate::Aggregate)
9826 // - [over.match.copy] (in all cases)
9831 TmpInits.push_back(DI->getInit());
9849 [&](bool OnlyListConstructors) -> OverloadingResult {
9855 while (Pattern->getInstantiatedFromMemberTemplate()) {
9856 if (Pattern->isMemberSpecialization())
9858 Pattern = Pattern->getInstantiatedFromMemberTemplate();
9861 auto *RD = cast<CXXRecordDecl>(Pattern->getTemplatedDecl());
9862 if (!(RD->getDefinition() && RD->isAggregate()))
9870 // if e_i is of array type and x_i is a braced-init-list, T_i is an
9873 // if e_i is of array type and x_i is a string-literal, T_i is an
9874 // lvalue reference to the const-qualified declared type of e_i and
9877 for (int I = 0, E = ListInit->getNumInits();
9879 if (ElementTypes[I]->isArrayType()) {
9880 if (isa<InitListExpr, DesignatedInitExpr>(ListInit->getInit(I)))
9883 ListInit->getInit(I)->IgnoreParenImpCasts()))
9891 TSInfo->getTypeLoc().getEndLoc())) {
9892 auto *GD = cast<CXXDeductionGuideDecl>(TD->getTemplatedDecl());
9902 NamedDecl *D = (*I)->getUnderlyingDecl();
9903 if (D->isInvalidDecl())
9908 TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D));
9912 if (!GD->isImplicit())
9922 // dependent base class has no virtual functions and no virtual base
9923 // classes, and the initializer is a non-empty braced-init-list or
9924 // parenthesized expression-list, and there are no deduction-guides for
9928 if (ListInit && ListInit->getNumInits()) {
9930 } else if (Inits.size()) { // parenthesized expression-list
9934 InitListExpr TempListInit(getASTContext(), Inits.front()->getBeginLoc(),
9935 Inits, Inits.back()->getEndLoc());
9947 // C++11 [over.match.list]p1, per DR1467: for list-initialization, first
9948 // try initializer-list constructors.
9954 if (!ListInit->getNumInits()) {
9956 auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl());
9957 if (FD && FD->getMinRequiredArguments() == 0) {
9962 } else if (ListInit->getNumInits() == 1) {
9965 // initializer-list constructors) is omitted if the initializer list
9968 Expr *E = ListInit->getInit(0);
9969 auto *RD = E->getType()->getAsCXXRecordDecl();
9971 isCompleteType(Kind.getLocation(), E->getType()) &&
9980 Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits());
9983 // If list-initialization fails, or if we're doing any other kind of
9990 // FIXME: For list-initialization candidates, it'd usually be better to
10003 cast<ClassTemplateDecl>(Template)->getTemplatedDecl();
10017 // FIXME: There are no tests for this diagnostic, and it doesn't seem
10022 NoteDeletedFunction(Best->Function);
10028 // In copy-list-initialization, if an explicit constructor is chosen, the
10029 // initialization is ill-formed.
10031 cast<CXXDeductionGuideDecl>(Best->Function)->isExplicit()) {
10032 bool IsDeductionGuide = !Best->Function->isImplicit();
10035 Diag(Best->Function->getLocation(),
10043 DiagnoseUseOfDecl(Best->FoundDecl, Kind.getLocation());
10044 MarkFunctionReferenced(Kind.getLocation(), Best->Function);
10052 SubstAutoType(TSInfo->getType(), Best->Function->getReturnType());
10053 Diag(TSInfo->getTypeLoc().getBeginLoc(),
10055 << TSInfo->getTypeLoc().getSourceRange() << 1 << DeducedType;
10057 // Warn if CTAD was used on a type that does not have any user-defined
10060 Diag(TSInfo->getTypeLoc().getBeginLoc(),
10063 Diag(Template->getLocation(), diag::note_suppress_ctad_maybe_unsupported);