17330f729Sjoerg //===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg //
97330f729Sjoerg // This file implements semantic analysis for initializers.
107330f729Sjoerg //
117330f729Sjoerg //===----------------------------------------------------------------------===//
127330f729Sjoerg
137330f729Sjoerg #include "clang/AST/ASTContext.h"
147330f729Sjoerg #include "clang/AST/DeclObjC.h"
157330f729Sjoerg #include "clang/AST/ExprCXX.h"
167330f729Sjoerg #include "clang/AST/ExprObjC.h"
177330f729Sjoerg #include "clang/AST/ExprOpenMP.h"
187330f729Sjoerg #include "clang/AST/TypeLoc.h"
197330f729Sjoerg #include "clang/Basic/CharInfo.h"
20*e038c9c4Sjoerg #include "clang/Basic/SourceManager.h"
217330f729Sjoerg #include "clang/Basic/TargetInfo.h"
227330f729Sjoerg #include "clang/Sema/Designator.h"
237330f729Sjoerg #include "clang/Sema/Initialization.h"
247330f729Sjoerg #include "clang/Sema/Lookup.h"
257330f729Sjoerg #include "clang/Sema/SemaInternal.h"
267330f729Sjoerg #include "llvm/ADT/APInt.h"
27*e038c9c4Sjoerg #include "llvm/ADT/PointerIntPair.h"
287330f729Sjoerg #include "llvm/ADT/SmallString.h"
297330f729Sjoerg #include "llvm/Support/ErrorHandling.h"
307330f729Sjoerg #include "llvm/Support/raw_ostream.h"
317330f729Sjoerg
327330f729Sjoerg using namespace clang;
337330f729Sjoerg
347330f729Sjoerg //===----------------------------------------------------------------------===//
357330f729Sjoerg // Sema Initialization Checking
367330f729Sjoerg //===----------------------------------------------------------------------===//
377330f729Sjoerg
387330f729Sjoerg /// Check whether T is compatible with a wide character type (wchar_t,
397330f729Sjoerg /// char16_t or char32_t).
IsWideCharCompatible(QualType T,ASTContext & Context)407330f729Sjoerg static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
417330f729Sjoerg if (Context.typesAreCompatible(Context.getWideCharType(), T))
427330f729Sjoerg return true;
437330f729Sjoerg if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {
447330f729Sjoerg return Context.typesAreCompatible(Context.Char16Ty, T) ||
457330f729Sjoerg Context.typesAreCompatible(Context.Char32Ty, T);
467330f729Sjoerg }
477330f729Sjoerg return false;
487330f729Sjoerg }
497330f729Sjoerg
507330f729Sjoerg enum StringInitFailureKind {
517330f729Sjoerg SIF_None,
527330f729Sjoerg SIF_NarrowStringIntoWideChar,
537330f729Sjoerg SIF_WideStringIntoChar,
547330f729Sjoerg SIF_IncompatWideStringIntoWideChar,
557330f729Sjoerg SIF_UTF8StringIntoPlainChar,
567330f729Sjoerg SIF_PlainStringIntoUTF8Char,
577330f729Sjoerg SIF_Other
587330f729Sjoerg };
597330f729Sjoerg
607330f729Sjoerg /// Check whether the array of type AT can be initialized by the Init
617330f729Sjoerg /// expression by means of string initialization. Returns SIF_None if so,
627330f729Sjoerg /// otherwise returns a StringInitFailureKind that describes why the
637330f729Sjoerg /// initialization would not work.
IsStringInit(Expr * Init,const ArrayType * AT,ASTContext & Context)647330f729Sjoerg static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT,
657330f729Sjoerg ASTContext &Context) {
667330f729Sjoerg if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
677330f729Sjoerg return SIF_Other;
687330f729Sjoerg
697330f729Sjoerg // See if this is a string literal or @encode.
707330f729Sjoerg Init = Init->IgnoreParens();
717330f729Sjoerg
727330f729Sjoerg // Handle @encode, which is a narrow string.
737330f729Sjoerg if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
747330f729Sjoerg return SIF_None;
757330f729Sjoerg
767330f729Sjoerg // Otherwise we can only handle string literals.
777330f729Sjoerg StringLiteral *SL = dyn_cast<StringLiteral>(Init);
787330f729Sjoerg if (!SL)
797330f729Sjoerg return SIF_Other;
807330f729Sjoerg
817330f729Sjoerg const QualType ElemTy =
827330f729Sjoerg Context.getCanonicalType(AT->getElementType()).getUnqualifiedType();
837330f729Sjoerg
847330f729Sjoerg switch (SL->getKind()) {
857330f729Sjoerg case StringLiteral::UTF8:
867330f729Sjoerg // char8_t array can be initialized with a UTF-8 string.
877330f729Sjoerg if (ElemTy->isChar8Type())
887330f729Sjoerg return SIF_None;
897330f729Sjoerg LLVM_FALLTHROUGH;
907330f729Sjoerg case StringLiteral::Ascii:
917330f729Sjoerg // char array can be initialized with a narrow string.
927330f729Sjoerg // Only allow char x[] = "foo"; not char x[] = L"foo";
937330f729Sjoerg if (ElemTy->isCharType())
947330f729Sjoerg return (SL->getKind() == StringLiteral::UTF8 &&
957330f729Sjoerg Context.getLangOpts().Char8)
967330f729Sjoerg ? SIF_UTF8StringIntoPlainChar
977330f729Sjoerg : SIF_None;
987330f729Sjoerg if (ElemTy->isChar8Type())
997330f729Sjoerg return SIF_PlainStringIntoUTF8Char;
1007330f729Sjoerg if (IsWideCharCompatible(ElemTy, Context))
1017330f729Sjoerg return SIF_NarrowStringIntoWideChar;
1027330f729Sjoerg return SIF_Other;
1037330f729Sjoerg // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
1047330f729Sjoerg // "An array with element type compatible with a qualified or unqualified
1057330f729Sjoerg // version of wchar_t, char16_t, or char32_t may be initialized by a wide
1067330f729Sjoerg // string literal with the corresponding encoding prefix (L, u, or U,
1077330f729Sjoerg // respectively), optionally enclosed in braces.
1087330f729Sjoerg case StringLiteral::UTF16:
1097330f729Sjoerg if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
1107330f729Sjoerg return SIF_None;
1117330f729Sjoerg if (ElemTy->isCharType() || ElemTy->isChar8Type())
1127330f729Sjoerg return SIF_WideStringIntoChar;
1137330f729Sjoerg if (IsWideCharCompatible(ElemTy, Context))
1147330f729Sjoerg return SIF_IncompatWideStringIntoWideChar;
1157330f729Sjoerg return SIF_Other;
1167330f729Sjoerg case StringLiteral::UTF32:
1177330f729Sjoerg if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
1187330f729Sjoerg return SIF_None;
1197330f729Sjoerg if (ElemTy->isCharType() || ElemTy->isChar8Type())
1207330f729Sjoerg return SIF_WideStringIntoChar;
1217330f729Sjoerg if (IsWideCharCompatible(ElemTy, Context))
1227330f729Sjoerg return SIF_IncompatWideStringIntoWideChar;
1237330f729Sjoerg return SIF_Other;
1247330f729Sjoerg case StringLiteral::Wide:
1257330f729Sjoerg if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
1267330f729Sjoerg return SIF_None;
1277330f729Sjoerg if (ElemTy->isCharType() || ElemTy->isChar8Type())
1287330f729Sjoerg return SIF_WideStringIntoChar;
1297330f729Sjoerg if (IsWideCharCompatible(ElemTy, Context))
1307330f729Sjoerg return SIF_IncompatWideStringIntoWideChar;
1317330f729Sjoerg return SIF_Other;
1327330f729Sjoerg }
1337330f729Sjoerg
1347330f729Sjoerg llvm_unreachable("missed a StringLiteral kind?");
1357330f729Sjoerg }
1367330f729Sjoerg
IsStringInit(Expr * init,QualType declType,ASTContext & Context)1377330f729Sjoerg static StringInitFailureKind IsStringInit(Expr *init, QualType declType,
1387330f729Sjoerg ASTContext &Context) {
1397330f729Sjoerg const ArrayType *arrayType = Context.getAsArrayType(declType);
1407330f729Sjoerg if (!arrayType)
1417330f729Sjoerg return SIF_Other;
1427330f729Sjoerg return IsStringInit(init, arrayType, Context);
1437330f729Sjoerg }
1447330f729Sjoerg
IsStringInit(Expr * Init,const ArrayType * AT)145*e038c9c4Sjoerg bool Sema::IsStringInit(Expr *Init, const ArrayType *AT) {
146*e038c9c4Sjoerg return ::IsStringInit(Init, AT, Context) == SIF_None;
147*e038c9c4Sjoerg }
148*e038c9c4Sjoerg
1497330f729Sjoerg /// Update the type of a string literal, including any surrounding parentheses,
1507330f729Sjoerg /// to match the type of the object which it is initializing.
updateStringLiteralType(Expr * E,QualType Ty)1517330f729Sjoerg static void updateStringLiteralType(Expr *E, QualType Ty) {
1527330f729Sjoerg while (true) {
1537330f729Sjoerg E->setType(Ty);
1547330f729Sjoerg E->setValueKind(VK_RValue);
1557330f729Sjoerg if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E)) {
1567330f729Sjoerg break;
1577330f729Sjoerg } else if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
1587330f729Sjoerg E = PE->getSubExpr();
1597330f729Sjoerg } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1607330f729Sjoerg assert(UO->getOpcode() == UO_Extension);
1617330f729Sjoerg E = UO->getSubExpr();
1627330f729Sjoerg } else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E)) {
1637330f729Sjoerg E = GSE->getResultExpr();
1647330f729Sjoerg } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(E)) {
1657330f729Sjoerg E = CE->getChosenSubExpr();
1667330f729Sjoerg } else {
1677330f729Sjoerg llvm_unreachable("unexpected expr in string literal init");
1687330f729Sjoerg }
1697330f729Sjoerg }
1707330f729Sjoerg }
1717330f729Sjoerg
1727330f729Sjoerg /// Fix a compound literal initializing an array so it's correctly marked
1737330f729Sjoerg /// as an rvalue.
updateGNUCompoundLiteralRValue(Expr * E)1747330f729Sjoerg static void updateGNUCompoundLiteralRValue(Expr *E) {
1757330f729Sjoerg while (true) {
1767330f729Sjoerg E->setValueKind(VK_RValue);
1777330f729Sjoerg if (isa<CompoundLiteralExpr>(E)) {
1787330f729Sjoerg break;
1797330f729Sjoerg } else if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
1807330f729Sjoerg E = PE->getSubExpr();
1817330f729Sjoerg } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1827330f729Sjoerg assert(UO->getOpcode() == UO_Extension);
1837330f729Sjoerg E = UO->getSubExpr();
1847330f729Sjoerg } else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E)) {
1857330f729Sjoerg E = GSE->getResultExpr();
1867330f729Sjoerg } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(E)) {
1877330f729Sjoerg E = CE->getChosenSubExpr();
1887330f729Sjoerg } else {
1897330f729Sjoerg llvm_unreachable("unexpected expr in array compound literal init");
1907330f729Sjoerg }
1917330f729Sjoerg }
1927330f729Sjoerg }
1937330f729Sjoerg
CheckStringInit(Expr * Str,QualType & DeclT,const ArrayType * AT,Sema & S)1947330f729Sjoerg static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
1957330f729Sjoerg Sema &S) {
1967330f729Sjoerg // Get the length of the string as parsed.
1977330f729Sjoerg auto *ConstantArrayTy =
1987330f729Sjoerg cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe());
1997330f729Sjoerg uint64_t StrLength = ConstantArrayTy->getSize().getZExtValue();
2007330f729Sjoerg
2017330f729Sjoerg if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
2027330f729Sjoerg // C99 6.7.8p14. We have an array of character type with unknown size
2037330f729Sjoerg // being initialized to a string literal.
2047330f729Sjoerg llvm::APInt ConstVal(32, StrLength);
2057330f729Sjoerg // Return a new array type (C99 6.7.8p22).
2067330f729Sjoerg DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
2077330f729Sjoerg ConstVal, nullptr,
2087330f729Sjoerg ArrayType::Normal, 0);
2097330f729Sjoerg updateStringLiteralType(Str, DeclT);
2107330f729Sjoerg return;
2117330f729Sjoerg }
2127330f729Sjoerg
2137330f729Sjoerg const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
2147330f729Sjoerg
2157330f729Sjoerg // We have an array of character type with known size. However,
2167330f729Sjoerg // the size may be smaller or larger than the string we are initializing.
2177330f729Sjoerg // FIXME: Avoid truncation for 64-bit length strings.
2187330f729Sjoerg if (S.getLangOpts().CPlusPlus) {
2197330f729Sjoerg if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
2207330f729Sjoerg // For Pascal strings it's OK to strip off the terminating null character,
2217330f729Sjoerg // so the example below is valid:
2227330f729Sjoerg //
2237330f729Sjoerg // unsigned char a[2] = "\pa";
2247330f729Sjoerg if (SL->isPascal())
2257330f729Sjoerg StrLength--;
2267330f729Sjoerg }
2277330f729Sjoerg
2287330f729Sjoerg // [dcl.init.string]p2
2297330f729Sjoerg if (StrLength > CAT->getSize().getZExtValue())
2307330f729Sjoerg S.Diag(Str->getBeginLoc(),
2317330f729Sjoerg diag::err_initializer_string_for_char_array_too_long)
2327330f729Sjoerg << Str->getSourceRange();
2337330f729Sjoerg } else {
2347330f729Sjoerg // C99 6.7.8p14.
2357330f729Sjoerg if (StrLength-1 > CAT->getSize().getZExtValue())
2367330f729Sjoerg S.Diag(Str->getBeginLoc(),
2377330f729Sjoerg diag::ext_initializer_string_for_char_array_too_long)
2387330f729Sjoerg << Str->getSourceRange();
2397330f729Sjoerg }
2407330f729Sjoerg
2417330f729Sjoerg // Set the type to the actual size that we are initializing. If we have
2427330f729Sjoerg // something like:
2437330f729Sjoerg // char x[1] = "foo";
2447330f729Sjoerg // then this will set the string literal's type to char[1].
2457330f729Sjoerg updateStringLiteralType(Str, DeclT);
2467330f729Sjoerg }
2477330f729Sjoerg
2487330f729Sjoerg //===----------------------------------------------------------------------===//
2497330f729Sjoerg // Semantic checking for initializer lists.
2507330f729Sjoerg //===----------------------------------------------------------------------===//
2517330f729Sjoerg
2527330f729Sjoerg namespace {
2537330f729Sjoerg
2547330f729Sjoerg /// Semantic checking for initializer lists.
2557330f729Sjoerg ///
2567330f729Sjoerg /// The InitListChecker class contains a set of routines that each
2577330f729Sjoerg /// handle the initialization of a certain kind of entity, e.g.,
2587330f729Sjoerg /// arrays, vectors, struct/union types, scalars, etc. The
2597330f729Sjoerg /// InitListChecker itself performs a recursive walk of the subobject
2607330f729Sjoerg /// structure of the type to be initialized, while stepping through
2617330f729Sjoerg /// the initializer list one element at a time. The IList and Index
2627330f729Sjoerg /// parameters to each of the Check* routines contain the active
2637330f729Sjoerg /// (syntactic) initializer list and the index into that initializer
2647330f729Sjoerg /// list that represents the current initializer. Each routine is
2657330f729Sjoerg /// responsible for moving that Index forward as it consumes elements.
2667330f729Sjoerg ///
2677330f729Sjoerg /// Each Check* routine also has a StructuredList/StructuredIndex
2687330f729Sjoerg /// arguments, which contains the current "structured" (semantic)
2697330f729Sjoerg /// initializer list and the index into that initializer list where we
2707330f729Sjoerg /// are copying initializers as we map them over to the semantic
2717330f729Sjoerg /// list. Once we have completed our recursive walk of the subobject
2727330f729Sjoerg /// structure, we will have constructed a full semantic initializer
2737330f729Sjoerg /// list.
2747330f729Sjoerg ///
2757330f729Sjoerg /// C99 designators cause changes in the initializer list traversal,
2767330f729Sjoerg /// because they make the initialization "jump" into a specific
2777330f729Sjoerg /// subobject and then continue the initialization from that
2787330f729Sjoerg /// point. CheckDesignatedInitializer() recursively steps into the
2797330f729Sjoerg /// designated subobject and manages backing out the recursion to
2807330f729Sjoerg /// initialize the subobjects after the one designated.
2817330f729Sjoerg ///
2827330f729Sjoerg /// If an initializer list contains any designators, we build a placeholder
2837330f729Sjoerg /// structured list even in 'verify only' mode, so that we can track which
2847330f729Sjoerg /// elements need 'empty' initializtion.
2857330f729Sjoerg class InitListChecker {
2867330f729Sjoerg Sema &SemaRef;
2877330f729Sjoerg bool hadError = false;
2887330f729Sjoerg bool VerifyOnly; // No diagnostics.
2897330f729Sjoerg bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode.
2907330f729Sjoerg bool InOverloadResolution;
2917330f729Sjoerg InitListExpr *FullyStructuredList = nullptr;
2927330f729Sjoerg NoInitExpr *DummyExpr = nullptr;
2937330f729Sjoerg
getDummyInit()2947330f729Sjoerg NoInitExpr *getDummyInit() {
2957330f729Sjoerg if (!DummyExpr)
2967330f729Sjoerg DummyExpr = new (SemaRef.Context) NoInitExpr(SemaRef.Context.VoidTy);
2977330f729Sjoerg return DummyExpr;
2987330f729Sjoerg }
2997330f729Sjoerg
3007330f729Sjoerg void CheckImplicitInitList(const InitializedEntity &Entity,
3017330f729Sjoerg InitListExpr *ParentIList, QualType T,
3027330f729Sjoerg unsigned &Index, InitListExpr *StructuredList,
3037330f729Sjoerg unsigned &StructuredIndex);
3047330f729Sjoerg void CheckExplicitInitList(const InitializedEntity &Entity,
3057330f729Sjoerg InitListExpr *IList, QualType &T,
3067330f729Sjoerg InitListExpr *StructuredList,
3077330f729Sjoerg bool TopLevelObject = false);
3087330f729Sjoerg void CheckListElementTypes(const InitializedEntity &Entity,
3097330f729Sjoerg InitListExpr *IList, QualType &DeclType,
3107330f729Sjoerg bool SubobjectIsDesignatorContext,
3117330f729Sjoerg unsigned &Index,
3127330f729Sjoerg InitListExpr *StructuredList,
3137330f729Sjoerg unsigned &StructuredIndex,
3147330f729Sjoerg bool TopLevelObject = false);
3157330f729Sjoerg void CheckSubElementType(const InitializedEntity &Entity,
3167330f729Sjoerg InitListExpr *IList, QualType ElemType,
3177330f729Sjoerg unsigned &Index,
3187330f729Sjoerg InitListExpr *StructuredList,
319*e038c9c4Sjoerg unsigned &StructuredIndex,
320*e038c9c4Sjoerg bool DirectlyDesignated = false);
3217330f729Sjoerg void CheckComplexType(const InitializedEntity &Entity,
3227330f729Sjoerg InitListExpr *IList, QualType DeclType,
3237330f729Sjoerg unsigned &Index,
3247330f729Sjoerg InitListExpr *StructuredList,
3257330f729Sjoerg unsigned &StructuredIndex);
3267330f729Sjoerg void CheckScalarType(const InitializedEntity &Entity,
3277330f729Sjoerg InitListExpr *IList, QualType DeclType,
3287330f729Sjoerg unsigned &Index,
3297330f729Sjoerg InitListExpr *StructuredList,
3307330f729Sjoerg unsigned &StructuredIndex);
3317330f729Sjoerg void CheckReferenceType(const InitializedEntity &Entity,
3327330f729Sjoerg InitListExpr *IList, QualType DeclType,
3337330f729Sjoerg unsigned &Index,
3347330f729Sjoerg InitListExpr *StructuredList,
3357330f729Sjoerg unsigned &StructuredIndex);
3367330f729Sjoerg void CheckVectorType(const InitializedEntity &Entity,
3377330f729Sjoerg InitListExpr *IList, QualType DeclType, unsigned &Index,
3387330f729Sjoerg InitListExpr *StructuredList,
3397330f729Sjoerg unsigned &StructuredIndex);
3407330f729Sjoerg void CheckStructUnionTypes(const InitializedEntity &Entity,
3417330f729Sjoerg InitListExpr *IList, QualType DeclType,
3427330f729Sjoerg CXXRecordDecl::base_class_range Bases,
3437330f729Sjoerg RecordDecl::field_iterator Field,
3447330f729Sjoerg bool SubobjectIsDesignatorContext, unsigned &Index,
3457330f729Sjoerg InitListExpr *StructuredList,
3467330f729Sjoerg unsigned &StructuredIndex,
3477330f729Sjoerg bool TopLevelObject = false);
3487330f729Sjoerg void CheckArrayType(const InitializedEntity &Entity,
3497330f729Sjoerg InitListExpr *IList, QualType &DeclType,
3507330f729Sjoerg llvm::APSInt elementIndex,
3517330f729Sjoerg bool SubobjectIsDesignatorContext, unsigned &Index,
3527330f729Sjoerg InitListExpr *StructuredList,
3537330f729Sjoerg unsigned &StructuredIndex);
3547330f729Sjoerg bool CheckDesignatedInitializer(const InitializedEntity &Entity,
3557330f729Sjoerg InitListExpr *IList, DesignatedInitExpr *DIE,
3567330f729Sjoerg unsigned DesigIdx,
3577330f729Sjoerg QualType &CurrentObjectType,
3587330f729Sjoerg RecordDecl::field_iterator *NextField,
3597330f729Sjoerg llvm::APSInt *NextElementIndex,
3607330f729Sjoerg unsigned &Index,
3617330f729Sjoerg InitListExpr *StructuredList,
3627330f729Sjoerg unsigned &StructuredIndex,
3637330f729Sjoerg bool FinishSubobjectInit,
3647330f729Sjoerg bool TopLevelObject);
3657330f729Sjoerg InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
3667330f729Sjoerg QualType CurrentObjectType,
3677330f729Sjoerg InitListExpr *StructuredList,
3687330f729Sjoerg unsigned StructuredIndex,
3697330f729Sjoerg SourceRange InitRange,
3707330f729Sjoerg bool IsFullyOverwritten = false);
3717330f729Sjoerg void UpdateStructuredListElement(InitListExpr *StructuredList,
3727330f729Sjoerg unsigned &StructuredIndex,
3737330f729Sjoerg Expr *expr);
3747330f729Sjoerg InitListExpr *createInitListExpr(QualType CurrentObjectType,
3757330f729Sjoerg SourceRange InitRange,
3767330f729Sjoerg unsigned ExpectedNumInits);
3777330f729Sjoerg int numArrayElements(QualType DeclType);
3787330f729Sjoerg int numStructUnionElements(QualType DeclType);
3797330f729Sjoerg
3807330f729Sjoerg ExprResult PerformEmptyInit(SourceLocation Loc,
3817330f729Sjoerg const InitializedEntity &Entity);
3827330f729Sjoerg
3837330f729Sjoerg /// Diagnose that OldInit (or part thereof) has been overridden by NewInit.
diagnoseInitOverride(Expr * OldInit,SourceRange NewInitRange,bool FullyOverwritten=true)3847330f729Sjoerg void diagnoseInitOverride(Expr *OldInit, SourceRange NewInitRange,
3857330f729Sjoerg bool FullyOverwritten = true) {
3867330f729Sjoerg // Overriding an initializer via a designator is valid with C99 designated
3877330f729Sjoerg // initializers, but ill-formed with C++20 designated initializers.
3887330f729Sjoerg unsigned DiagID = SemaRef.getLangOpts().CPlusPlus
3897330f729Sjoerg ? diag::ext_initializer_overrides
3907330f729Sjoerg : diag::warn_initializer_overrides;
3917330f729Sjoerg
3927330f729Sjoerg if (InOverloadResolution && SemaRef.getLangOpts().CPlusPlus) {
3937330f729Sjoerg // In overload resolution, we have to strictly enforce the rules, and so
3947330f729Sjoerg // don't allow any overriding of prior initializers. This matters for a
3957330f729Sjoerg // case such as:
3967330f729Sjoerg //
3977330f729Sjoerg // union U { int a, b; };
3987330f729Sjoerg // struct S { int a, b; };
3997330f729Sjoerg // void f(U), f(S);
4007330f729Sjoerg //
4017330f729Sjoerg // Here, f({.a = 1, .b = 2}) is required to call the struct overload. For
4027330f729Sjoerg // consistency, we disallow all overriding of prior initializers in
4037330f729Sjoerg // overload resolution, not only overriding of union members.
4047330f729Sjoerg hadError = true;
4057330f729Sjoerg } else if (OldInit->getType().isDestructedType() && !FullyOverwritten) {
4067330f729Sjoerg // If we'll be keeping around the old initializer but overwriting part of
4077330f729Sjoerg // the object it initialized, and that object is not trivially
4087330f729Sjoerg // destructible, this can leak. Don't allow that, not even as an
4097330f729Sjoerg // extension.
4107330f729Sjoerg //
4117330f729Sjoerg // FIXME: It might be reasonable to allow this in cases where the part of
4127330f729Sjoerg // the initializer that we're overriding has trivial destruction.
4137330f729Sjoerg DiagID = diag::err_initializer_overrides_destructed;
4147330f729Sjoerg } else if (!OldInit->getSourceRange().isValid()) {
4157330f729Sjoerg // We need to check on source range validity because the previous
4167330f729Sjoerg // initializer does not have to be an explicit initializer. e.g.,
4177330f729Sjoerg //
4187330f729Sjoerg // struct P { int a, b; };
4197330f729Sjoerg // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
4207330f729Sjoerg //
4217330f729Sjoerg // There is an overwrite taking place because the first braced initializer
4227330f729Sjoerg // list "{ .a = 2 }" already provides value for .p.b (which is zero).
4237330f729Sjoerg //
4247330f729Sjoerg // Such overwrites are harmless, so we don't diagnose them. (Note that in
4257330f729Sjoerg // C++, this cannot be reached unless we've already seen and diagnosed a
4267330f729Sjoerg // different conformance issue, such as a mixture of designated and
4277330f729Sjoerg // non-designated initializers or a multi-level designator.)
4287330f729Sjoerg return;
4297330f729Sjoerg }
4307330f729Sjoerg
4317330f729Sjoerg if (!VerifyOnly) {
4327330f729Sjoerg SemaRef.Diag(NewInitRange.getBegin(), DiagID)
4337330f729Sjoerg << NewInitRange << FullyOverwritten << OldInit->getType();
4347330f729Sjoerg SemaRef.Diag(OldInit->getBeginLoc(), diag::note_previous_initializer)
4357330f729Sjoerg << (OldInit->HasSideEffects(SemaRef.Context) && FullyOverwritten)
4367330f729Sjoerg << OldInit->getSourceRange();
4377330f729Sjoerg }
4387330f729Sjoerg }
4397330f729Sjoerg
4407330f729Sjoerg // Explanation on the "FillWithNoInit" mode:
4417330f729Sjoerg //
4427330f729Sjoerg // Assume we have the following definitions (Case#1):
4437330f729Sjoerg // struct P { char x[6][6]; } xp = { .x[1] = "bar" };
4447330f729Sjoerg // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' };
4457330f729Sjoerg //
4467330f729Sjoerg // l.lp.x[1][0..1] should not be filled with implicit initializers because the
4477330f729Sjoerg // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf".
4487330f729Sjoerg //
4497330f729Sjoerg // But if we have (Case#2):
4507330f729Sjoerg // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } };
4517330f729Sjoerg //
4527330f729Sjoerg // l.lp.x[1][0..1] are implicitly initialized and do not use values from the
4537330f729Sjoerg // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0".
4547330f729Sjoerg //
4557330f729Sjoerg // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes"
4567330f729Sjoerg // in the InitListExpr, the "holes" in Case#1 are filled not with empty
4577330f729Sjoerg // initializers but with special "NoInitExpr" place holders, which tells the
4587330f729Sjoerg // CodeGen not to generate any initializers for these parts.
4597330f729Sjoerg void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base,
4607330f729Sjoerg const InitializedEntity &ParentEntity,
4617330f729Sjoerg InitListExpr *ILE, bool &RequiresSecondPass,
4627330f729Sjoerg bool FillWithNoInit);
4637330f729Sjoerg void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
4647330f729Sjoerg const InitializedEntity &ParentEntity,
4657330f729Sjoerg InitListExpr *ILE, bool &RequiresSecondPass,
4667330f729Sjoerg bool FillWithNoInit = false);
4677330f729Sjoerg void FillInEmptyInitializations(const InitializedEntity &Entity,
4687330f729Sjoerg InitListExpr *ILE, bool &RequiresSecondPass,
4697330f729Sjoerg InitListExpr *OuterILE, unsigned OuterIndex,
4707330f729Sjoerg bool FillWithNoInit = false);
4717330f729Sjoerg bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
4727330f729Sjoerg Expr *InitExpr, FieldDecl *Field,
4737330f729Sjoerg bool TopLevelObject);
4747330f729Sjoerg void CheckEmptyInitializable(const InitializedEntity &Entity,
4757330f729Sjoerg SourceLocation Loc);
4767330f729Sjoerg
4777330f729Sjoerg public:
4787330f729Sjoerg InitListChecker(Sema &S, const InitializedEntity &Entity, InitListExpr *IL,
4797330f729Sjoerg QualType &T, bool VerifyOnly, bool TreatUnavailableAsInvalid,
4807330f729Sjoerg bool InOverloadResolution = false);
HadError()4817330f729Sjoerg bool HadError() { return hadError; }
4827330f729Sjoerg
4837330f729Sjoerg // Retrieves the fully-structured initializer list used for
4847330f729Sjoerg // semantic analysis and code generation.
getFullyStructuredList() const4857330f729Sjoerg InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
4867330f729Sjoerg };
4877330f729Sjoerg
4887330f729Sjoerg } // end anonymous namespace
4897330f729Sjoerg
PerformEmptyInit(SourceLocation Loc,const InitializedEntity & Entity)4907330f729Sjoerg ExprResult InitListChecker::PerformEmptyInit(SourceLocation Loc,
4917330f729Sjoerg const InitializedEntity &Entity) {
4927330f729Sjoerg InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
4937330f729Sjoerg true);
4947330f729Sjoerg MultiExprArg SubInit;
4957330f729Sjoerg Expr *InitExpr;
4967330f729Sjoerg InitListExpr DummyInitList(SemaRef.Context, Loc, None, Loc);
4977330f729Sjoerg
4987330f729Sjoerg // C++ [dcl.init.aggr]p7:
4997330f729Sjoerg // If there are fewer initializer-clauses in the list than there are
5007330f729Sjoerg // members in the aggregate, then each member not explicitly initialized
5017330f729Sjoerg // ...
5027330f729Sjoerg bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
5037330f729Sjoerg Entity.getType()->getBaseElementTypeUnsafe()->isRecordType();
5047330f729Sjoerg if (EmptyInitList) {
5057330f729Sjoerg // C++1y / DR1070:
5067330f729Sjoerg // shall be initialized [...] from an empty initializer list.
5077330f729Sjoerg //
5087330f729Sjoerg // We apply the resolution of this DR to C++11 but not C++98, since C++98
5097330f729Sjoerg // does not have useful semantics for initialization from an init list.
5107330f729Sjoerg // We treat this as copy-initialization, because aggregate initialization
5117330f729Sjoerg // always performs copy-initialization on its elements.
5127330f729Sjoerg //
5137330f729Sjoerg // Only do this if we're initializing a class type, to avoid filling in
5147330f729Sjoerg // the initializer list where possible.
5157330f729Sjoerg InitExpr = VerifyOnly ? &DummyInitList : new (SemaRef.Context)
5167330f729Sjoerg InitListExpr(SemaRef.Context, Loc, None, Loc);
5177330f729Sjoerg InitExpr->setType(SemaRef.Context.VoidTy);
5187330f729Sjoerg SubInit = InitExpr;
5197330f729Sjoerg Kind = InitializationKind::CreateCopy(Loc, Loc);
5207330f729Sjoerg } else {
5217330f729Sjoerg // C++03:
5227330f729Sjoerg // shall be value-initialized.
5237330f729Sjoerg }
5247330f729Sjoerg
5257330f729Sjoerg InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
5267330f729Sjoerg // libstdc++4.6 marks the vector default constructor as explicit in
5277330f729Sjoerg // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
5287330f729Sjoerg // stlport does so too. Look for std::__debug for libstdc++, and for
5297330f729Sjoerg // std:: for stlport. This is effectively a compiler-side implementation of
5307330f729Sjoerg // LWG2193.
5317330f729Sjoerg if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() ==
5327330f729Sjoerg InitializationSequence::FK_ExplicitConstructor) {
5337330f729Sjoerg OverloadCandidateSet::iterator Best;
5347330f729Sjoerg OverloadingResult O =
5357330f729Sjoerg InitSeq.getFailedCandidateSet()
5367330f729Sjoerg .BestViableFunction(SemaRef, Kind.getLocation(), Best);
5377330f729Sjoerg (void)O;
5387330f729Sjoerg assert(O == OR_Success && "Inconsistent overload resolution");
5397330f729Sjoerg CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
5407330f729Sjoerg CXXRecordDecl *R = CtorDecl->getParent();
5417330f729Sjoerg
5427330f729Sjoerg if (CtorDecl->getMinRequiredArguments() == 0 &&
5437330f729Sjoerg CtorDecl->isExplicit() && R->getDeclName() &&
5447330f729Sjoerg SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
5457330f729Sjoerg bool IsInStd = false;
5467330f729Sjoerg for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
5477330f729Sjoerg ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
5487330f729Sjoerg if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND))
5497330f729Sjoerg IsInStd = true;
5507330f729Sjoerg }
5517330f729Sjoerg
5527330f729Sjoerg if (IsInStd && llvm::StringSwitch<bool>(R->getName())
5537330f729Sjoerg .Cases("basic_string", "deque", "forward_list", true)
5547330f729Sjoerg .Cases("list", "map", "multimap", "multiset", true)
5557330f729Sjoerg .Cases("priority_queue", "queue", "set", "stack", true)
5567330f729Sjoerg .Cases("unordered_map", "unordered_set", "vector", true)
5577330f729Sjoerg .Default(false)) {
5587330f729Sjoerg InitSeq.InitializeFrom(
5597330f729Sjoerg SemaRef, Entity,
5607330f729Sjoerg InitializationKind::CreateValue(Loc, Loc, Loc, true),
5617330f729Sjoerg MultiExprArg(), /*TopLevelOfInitList=*/false,
5627330f729Sjoerg TreatUnavailableAsInvalid);
5637330f729Sjoerg // Emit a warning for this. System header warnings aren't shown
5647330f729Sjoerg // by default, but people working on system headers should see it.
5657330f729Sjoerg if (!VerifyOnly) {
5667330f729Sjoerg SemaRef.Diag(CtorDecl->getLocation(),
5677330f729Sjoerg diag::warn_invalid_initializer_from_system_header);
5687330f729Sjoerg if (Entity.getKind() == InitializedEntity::EK_Member)
5697330f729Sjoerg SemaRef.Diag(Entity.getDecl()->getLocation(),
5707330f729Sjoerg diag::note_used_in_initialization_here);
5717330f729Sjoerg else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
5727330f729Sjoerg SemaRef.Diag(Loc, diag::note_used_in_initialization_here);
5737330f729Sjoerg }
5747330f729Sjoerg }
5757330f729Sjoerg }
5767330f729Sjoerg }
5777330f729Sjoerg if (!InitSeq) {
5787330f729Sjoerg if (!VerifyOnly) {
5797330f729Sjoerg InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
5807330f729Sjoerg if (Entity.getKind() == InitializedEntity::EK_Member)
5817330f729Sjoerg SemaRef.Diag(Entity.getDecl()->getLocation(),
5827330f729Sjoerg diag::note_in_omitted_aggregate_initializer)
5837330f729Sjoerg << /*field*/1 << Entity.getDecl();
5847330f729Sjoerg else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) {
5857330f729Sjoerg bool IsTrailingArrayNewMember =
5867330f729Sjoerg Entity.getParent() &&
5877330f729Sjoerg Entity.getParent()->isVariableLengthArrayNew();
5887330f729Sjoerg SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
5897330f729Sjoerg << (IsTrailingArrayNewMember ? 2 : /*array element*/0)
5907330f729Sjoerg << Entity.getElementIndex();
5917330f729Sjoerg }
5927330f729Sjoerg }
5937330f729Sjoerg hadError = true;
5947330f729Sjoerg return ExprError();
5957330f729Sjoerg }
5967330f729Sjoerg
5977330f729Sjoerg return VerifyOnly ? ExprResult()
5987330f729Sjoerg : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
5997330f729Sjoerg }
6007330f729Sjoerg
CheckEmptyInitializable(const InitializedEntity & Entity,SourceLocation Loc)6017330f729Sjoerg void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
6027330f729Sjoerg SourceLocation Loc) {
6037330f729Sjoerg // If we're building a fully-structured list, we'll check this at the end
6047330f729Sjoerg // once we know which elements are actually initialized. Otherwise, we know
6057330f729Sjoerg // that there are no designators so we can just check now.
6067330f729Sjoerg if (FullyStructuredList)
6077330f729Sjoerg return;
6087330f729Sjoerg PerformEmptyInit(Loc, Entity);
6097330f729Sjoerg }
6107330f729Sjoerg
FillInEmptyInitForBase(unsigned Init,const CXXBaseSpecifier & Base,const InitializedEntity & ParentEntity,InitListExpr * ILE,bool & RequiresSecondPass,bool FillWithNoInit)6117330f729Sjoerg void InitListChecker::FillInEmptyInitForBase(
6127330f729Sjoerg unsigned Init, const CXXBaseSpecifier &Base,
6137330f729Sjoerg const InitializedEntity &ParentEntity, InitListExpr *ILE,
6147330f729Sjoerg bool &RequiresSecondPass, bool FillWithNoInit) {
6157330f729Sjoerg InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
6167330f729Sjoerg SemaRef.Context, &Base, false, &ParentEntity);
6177330f729Sjoerg
6187330f729Sjoerg if (Init >= ILE->getNumInits() || !ILE->getInit(Init)) {
6197330f729Sjoerg ExprResult BaseInit = FillWithNoInit
6207330f729Sjoerg ? new (SemaRef.Context) NoInitExpr(Base.getType())
6217330f729Sjoerg : PerformEmptyInit(ILE->getEndLoc(), BaseEntity);
6227330f729Sjoerg if (BaseInit.isInvalid()) {
6237330f729Sjoerg hadError = true;
6247330f729Sjoerg return;
6257330f729Sjoerg }
6267330f729Sjoerg
6277330f729Sjoerg if (!VerifyOnly) {
6287330f729Sjoerg assert(Init < ILE->getNumInits() && "should have been expanded");
6297330f729Sjoerg ILE->setInit(Init, BaseInit.getAs<Expr>());
6307330f729Sjoerg }
6317330f729Sjoerg } else if (InitListExpr *InnerILE =
6327330f729Sjoerg dyn_cast<InitListExpr>(ILE->getInit(Init))) {
6337330f729Sjoerg FillInEmptyInitializations(BaseEntity, InnerILE, RequiresSecondPass,
6347330f729Sjoerg ILE, Init, FillWithNoInit);
6357330f729Sjoerg } else if (DesignatedInitUpdateExpr *InnerDIUE =
6367330f729Sjoerg dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
6377330f729Sjoerg FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(),
6387330f729Sjoerg RequiresSecondPass, ILE, Init,
6397330f729Sjoerg /*FillWithNoInit =*/true);
6407330f729Sjoerg }
6417330f729Sjoerg }
6427330f729Sjoerg
FillInEmptyInitForField(unsigned Init,FieldDecl * Field,const InitializedEntity & ParentEntity,InitListExpr * ILE,bool & RequiresSecondPass,bool FillWithNoInit)6437330f729Sjoerg void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
6447330f729Sjoerg const InitializedEntity &ParentEntity,
6457330f729Sjoerg InitListExpr *ILE,
6467330f729Sjoerg bool &RequiresSecondPass,
6477330f729Sjoerg bool FillWithNoInit) {
6487330f729Sjoerg SourceLocation Loc = ILE->getEndLoc();
6497330f729Sjoerg unsigned NumInits = ILE->getNumInits();
6507330f729Sjoerg InitializedEntity MemberEntity
6517330f729Sjoerg = InitializedEntity::InitializeMember(Field, &ParentEntity);
6527330f729Sjoerg
6537330f729Sjoerg if (Init >= NumInits || !ILE->getInit(Init)) {
6547330f729Sjoerg if (const RecordType *RType = ILE->getType()->getAs<RecordType>())
6557330f729Sjoerg if (!RType->getDecl()->isUnion())
6567330f729Sjoerg assert((Init < NumInits || VerifyOnly) &&
6577330f729Sjoerg "This ILE should have been expanded");
6587330f729Sjoerg
6597330f729Sjoerg if (FillWithNoInit) {
6607330f729Sjoerg assert(!VerifyOnly && "should not fill with no-init in verify-only mode");
6617330f729Sjoerg Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
6627330f729Sjoerg if (Init < NumInits)
6637330f729Sjoerg ILE->setInit(Init, Filler);
6647330f729Sjoerg else
6657330f729Sjoerg ILE->updateInit(SemaRef.Context, Init, Filler);
6667330f729Sjoerg return;
6677330f729Sjoerg }
6687330f729Sjoerg // C++1y [dcl.init.aggr]p7:
6697330f729Sjoerg // If there are fewer initializer-clauses in the list than there are
6707330f729Sjoerg // members in the aggregate, then each member not explicitly initialized
6717330f729Sjoerg // shall be initialized from its brace-or-equal-initializer [...]
6727330f729Sjoerg if (Field->hasInClassInitializer()) {
6737330f729Sjoerg if (VerifyOnly)
6747330f729Sjoerg return;
6757330f729Sjoerg
6767330f729Sjoerg ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
6777330f729Sjoerg if (DIE.isInvalid()) {
6787330f729Sjoerg hadError = true;
6797330f729Sjoerg return;
6807330f729Sjoerg }
6817330f729Sjoerg SemaRef.checkInitializerLifetime(MemberEntity, DIE.get());
6827330f729Sjoerg if (Init < NumInits)
6837330f729Sjoerg ILE->setInit(Init, DIE.get());
6847330f729Sjoerg else {
6857330f729Sjoerg ILE->updateInit(SemaRef.Context, Init, DIE.get());
6867330f729Sjoerg RequiresSecondPass = true;
6877330f729Sjoerg }
6887330f729Sjoerg return;
6897330f729Sjoerg }
6907330f729Sjoerg
6917330f729Sjoerg if (Field->getType()->isReferenceType()) {
6927330f729Sjoerg if (!VerifyOnly) {
6937330f729Sjoerg // C++ [dcl.init.aggr]p9:
6947330f729Sjoerg // If an incomplete or empty initializer-list leaves a
6957330f729Sjoerg // member of reference type uninitialized, the program is
6967330f729Sjoerg // ill-formed.
6977330f729Sjoerg SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
6987330f729Sjoerg << Field->getType()
6997330f729Sjoerg << ILE->getSyntacticForm()->getSourceRange();
7007330f729Sjoerg SemaRef.Diag(Field->getLocation(),
7017330f729Sjoerg diag::note_uninit_reference_member);
7027330f729Sjoerg }
7037330f729Sjoerg hadError = true;
7047330f729Sjoerg return;
7057330f729Sjoerg }
7067330f729Sjoerg
7077330f729Sjoerg ExprResult MemberInit = PerformEmptyInit(Loc, MemberEntity);
7087330f729Sjoerg if (MemberInit.isInvalid()) {
7097330f729Sjoerg hadError = true;
7107330f729Sjoerg return;
7117330f729Sjoerg }
7127330f729Sjoerg
7137330f729Sjoerg if (hadError || VerifyOnly) {
7147330f729Sjoerg // Do nothing
7157330f729Sjoerg } else if (Init < NumInits) {
7167330f729Sjoerg ILE->setInit(Init, MemberInit.getAs<Expr>());
7177330f729Sjoerg } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
7187330f729Sjoerg // Empty initialization requires a constructor call, so
7197330f729Sjoerg // extend the initializer list to include the constructor
7207330f729Sjoerg // call and make a note that we'll need to take another pass
7217330f729Sjoerg // through the initializer list.
7227330f729Sjoerg ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
7237330f729Sjoerg RequiresSecondPass = true;
7247330f729Sjoerg }
7257330f729Sjoerg } else if (InitListExpr *InnerILE
7267330f729Sjoerg = dyn_cast<InitListExpr>(ILE->getInit(Init))) {
7277330f729Sjoerg FillInEmptyInitializations(MemberEntity, InnerILE,
7287330f729Sjoerg RequiresSecondPass, ILE, Init, FillWithNoInit);
7297330f729Sjoerg } else if (DesignatedInitUpdateExpr *InnerDIUE =
7307330f729Sjoerg dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
7317330f729Sjoerg FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),
7327330f729Sjoerg RequiresSecondPass, ILE, Init,
7337330f729Sjoerg /*FillWithNoInit =*/true);
7347330f729Sjoerg }
7357330f729Sjoerg }
7367330f729Sjoerg
7377330f729Sjoerg /// Recursively replaces NULL values within the given initializer list
7387330f729Sjoerg /// with expressions that perform value-initialization of the
7397330f729Sjoerg /// appropriate type, and finish off the InitListExpr formation.
7407330f729Sjoerg void
FillInEmptyInitializations(const InitializedEntity & Entity,InitListExpr * ILE,bool & RequiresSecondPass,InitListExpr * OuterILE,unsigned OuterIndex,bool FillWithNoInit)7417330f729Sjoerg InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
7427330f729Sjoerg InitListExpr *ILE,
7437330f729Sjoerg bool &RequiresSecondPass,
7447330f729Sjoerg InitListExpr *OuterILE,
7457330f729Sjoerg unsigned OuterIndex,
7467330f729Sjoerg bool FillWithNoInit) {
7477330f729Sjoerg assert((ILE->getType() != SemaRef.Context.VoidTy) &&
7487330f729Sjoerg "Should not have void type");
7497330f729Sjoerg
7507330f729Sjoerg // We don't need to do any checks when just filling NoInitExprs; that can't
7517330f729Sjoerg // fail.
7527330f729Sjoerg if (FillWithNoInit && VerifyOnly)
7537330f729Sjoerg return;
7547330f729Sjoerg
7557330f729Sjoerg // If this is a nested initializer list, we might have changed its contents
7567330f729Sjoerg // (and therefore some of its properties, such as instantiation-dependence)
7577330f729Sjoerg // while filling it in. Inform the outer initializer list so that its state
7587330f729Sjoerg // can be updated to match.
7597330f729Sjoerg // FIXME: We should fully build the inner initializers before constructing
7607330f729Sjoerg // the outer InitListExpr instead of mutating AST nodes after they have
7617330f729Sjoerg // been used as subexpressions of other nodes.
7627330f729Sjoerg struct UpdateOuterILEWithUpdatedInit {
7637330f729Sjoerg InitListExpr *Outer;
7647330f729Sjoerg unsigned OuterIndex;
7657330f729Sjoerg ~UpdateOuterILEWithUpdatedInit() {
7667330f729Sjoerg if (Outer)
7677330f729Sjoerg Outer->setInit(OuterIndex, Outer->getInit(OuterIndex));
7687330f729Sjoerg }
7697330f729Sjoerg } UpdateOuterRAII = {OuterILE, OuterIndex};
7707330f729Sjoerg
7717330f729Sjoerg // A transparent ILE is not performing aggregate initialization and should
7727330f729Sjoerg // not be filled in.
7737330f729Sjoerg if (ILE->isTransparent())
7747330f729Sjoerg return;
7757330f729Sjoerg
7767330f729Sjoerg if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
7777330f729Sjoerg const RecordDecl *RDecl = RType->getDecl();
7787330f729Sjoerg if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
7797330f729Sjoerg FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
7807330f729Sjoerg Entity, ILE, RequiresSecondPass, FillWithNoInit);
7817330f729Sjoerg else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
7827330f729Sjoerg cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
7837330f729Sjoerg for (auto *Field : RDecl->fields()) {
7847330f729Sjoerg if (Field->hasInClassInitializer()) {
7857330f729Sjoerg FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass,
7867330f729Sjoerg FillWithNoInit);
7877330f729Sjoerg break;
7887330f729Sjoerg }
7897330f729Sjoerg }
7907330f729Sjoerg } else {
7917330f729Sjoerg // The fields beyond ILE->getNumInits() are default initialized, so in
7927330f729Sjoerg // order to leave them uninitialized, the ILE is expanded and the extra
7937330f729Sjoerg // fields are then filled with NoInitExpr.
7947330f729Sjoerg unsigned NumElems = numStructUnionElements(ILE->getType());
7957330f729Sjoerg if (RDecl->hasFlexibleArrayMember())
7967330f729Sjoerg ++NumElems;
7977330f729Sjoerg if (!VerifyOnly && ILE->getNumInits() < NumElems)
7987330f729Sjoerg ILE->resizeInits(SemaRef.Context, NumElems);
7997330f729Sjoerg
8007330f729Sjoerg unsigned Init = 0;
8017330f729Sjoerg
8027330f729Sjoerg if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) {
8037330f729Sjoerg for (auto &Base : CXXRD->bases()) {
8047330f729Sjoerg if (hadError)
8057330f729Sjoerg return;
8067330f729Sjoerg
8077330f729Sjoerg FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass,
8087330f729Sjoerg FillWithNoInit);
8097330f729Sjoerg ++Init;
8107330f729Sjoerg }
8117330f729Sjoerg }
8127330f729Sjoerg
8137330f729Sjoerg for (auto *Field : RDecl->fields()) {
8147330f729Sjoerg if (Field->isUnnamedBitfield())
8157330f729Sjoerg continue;
8167330f729Sjoerg
8177330f729Sjoerg if (hadError)
8187330f729Sjoerg return;
8197330f729Sjoerg
8207330f729Sjoerg FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass,
8217330f729Sjoerg FillWithNoInit);
8227330f729Sjoerg if (hadError)
8237330f729Sjoerg return;
8247330f729Sjoerg
8257330f729Sjoerg ++Init;
8267330f729Sjoerg
8277330f729Sjoerg // Only look at the first initialization of a union.
8287330f729Sjoerg if (RDecl->isUnion())
8297330f729Sjoerg break;
8307330f729Sjoerg }
8317330f729Sjoerg }
8327330f729Sjoerg
8337330f729Sjoerg return;
8347330f729Sjoerg }
8357330f729Sjoerg
8367330f729Sjoerg QualType ElementType;
8377330f729Sjoerg
8387330f729Sjoerg InitializedEntity ElementEntity = Entity;
8397330f729Sjoerg unsigned NumInits = ILE->getNumInits();
8407330f729Sjoerg unsigned NumElements = NumInits;
8417330f729Sjoerg if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
8427330f729Sjoerg ElementType = AType->getElementType();
8437330f729Sjoerg if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
8447330f729Sjoerg NumElements = CAType->getSize().getZExtValue();
8457330f729Sjoerg // For an array new with an unknown bound, ask for one additional element
8467330f729Sjoerg // in order to populate the array filler.
8477330f729Sjoerg if (Entity.isVariableLengthArrayNew())
8487330f729Sjoerg ++NumElements;
8497330f729Sjoerg ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
8507330f729Sjoerg 0, Entity);
8517330f729Sjoerg } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
8527330f729Sjoerg ElementType = VType->getElementType();
8537330f729Sjoerg NumElements = VType->getNumElements();
8547330f729Sjoerg ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
8557330f729Sjoerg 0, Entity);
8567330f729Sjoerg } else
8577330f729Sjoerg ElementType = ILE->getType();
8587330f729Sjoerg
8597330f729Sjoerg bool SkipEmptyInitChecks = false;
8607330f729Sjoerg for (unsigned Init = 0; Init != NumElements; ++Init) {
8617330f729Sjoerg if (hadError)
8627330f729Sjoerg return;
8637330f729Sjoerg
8647330f729Sjoerg if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
8657330f729Sjoerg ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
8667330f729Sjoerg ElementEntity.setElementIndex(Init);
8677330f729Sjoerg
8687330f729Sjoerg if (Init >= NumInits && (ILE->hasArrayFiller() || SkipEmptyInitChecks))
8697330f729Sjoerg return;
8707330f729Sjoerg
8717330f729Sjoerg Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
8727330f729Sjoerg if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
8737330f729Sjoerg ILE->setInit(Init, ILE->getArrayFiller());
8747330f729Sjoerg else if (!InitExpr && !ILE->hasArrayFiller()) {
8757330f729Sjoerg // In VerifyOnly mode, there's no point performing empty initialization
8767330f729Sjoerg // more than once.
8777330f729Sjoerg if (SkipEmptyInitChecks)
8787330f729Sjoerg continue;
8797330f729Sjoerg
8807330f729Sjoerg Expr *Filler = nullptr;
8817330f729Sjoerg
8827330f729Sjoerg if (FillWithNoInit)
8837330f729Sjoerg Filler = new (SemaRef.Context) NoInitExpr(ElementType);
8847330f729Sjoerg else {
8857330f729Sjoerg ExprResult ElementInit =
8867330f729Sjoerg PerformEmptyInit(ILE->getEndLoc(), ElementEntity);
8877330f729Sjoerg if (ElementInit.isInvalid()) {
8887330f729Sjoerg hadError = true;
8897330f729Sjoerg return;
8907330f729Sjoerg }
8917330f729Sjoerg
8927330f729Sjoerg Filler = ElementInit.getAs<Expr>();
8937330f729Sjoerg }
8947330f729Sjoerg
8957330f729Sjoerg if (hadError) {
8967330f729Sjoerg // Do nothing
8977330f729Sjoerg } else if (VerifyOnly) {
8987330f729Sjoerg SkipEmptyInitChecks = true;
8997330f729Sjoerg } else if (Init < NumInits) {
9007330f729Sjoerg // For arrays, just set the expression used for value-initialization
9017330f729Sjoerg // of the "holes" in the array.
9027330f729Sjoerg if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
9037330f729Sjoerg ILE->setArrayFiller(Filler);
9047330f729Sjoerg else
9057330f729Sjoerg ILE->setInit(Init, Filler);
9067330f729Sjoerg } else {
9077330f729Sjoerg // For arrays, just set the expression used for value-initialization
9087330f729Sjoerg // of the rest of elements and exit.
9097330f729Sjoerg if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
9107330f729Sjoerg ILE->setArrayFiller(Filler);
9117330f729Sjoerg return;
9127330f729Sjoerg }
9137330f729Sjoerg
9147330f729Sjoerg if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) {
9157330f729Sjoerg // Empty initialization requires a constructor call, so
9167330f729Sjoerg // extend the initializer list to include the constructor
9177330f729Sjoerg // call and make a note that we'll need to take another pass
9187330f729Sjoerg // through the initializer list.
9197330f729Sjoerg ILE->updateInit(SemaRef.Context, Init, Filler);
9207330f729Sjoerg RequiresSecondPass = true;
9217330f729Sjoerg }
9227330f729Sjoerg }
9237330f729Sjoerg } else if (InitListExpr *InnerILE
9247330f729Sjoerg = dyn_cast_or_null<InitListExpr>(InitExpr)) {
9257330f729Sjoerg FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,
9267330f729Sjoerg ILE, Init, FillWithNoInit);
9277330f729Sjoerg } else if (DesignatedInitUpdateExpr *InnerDIUE =
9287330f729Sjoerg dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr)) {
9297330f729Sjoerg FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
9307330f729Sjoerg RequiresSecondPass, ILE, Init,
9317330f729Sjoerg /*FillWithNoInit =*/true);
9327330f729Sjoerg }
9337330f729Sjoerg }
9347330f729Sjoerg }
9357330f729Sjoerg
hasAnyDesignatedInits(const InitListExpr * IL)9367330f729Sjoerg static bool hasAnyDesignatedInits(const InitListExpr *IL) {
9377330f729Sjoerg for (const Stmt *Init : *IL)
9387330f729Sjoerg if (Init && isa<DesignatedInitExpr>(Init))
9397330f729Sjoerg return true;
9407330f729Sjoerg return false;
9417330f729Sjoerg }
9427330f729Sjoerg
InitListChecker(Sema & S,const InitializedEntity & Entity,InitListExpr * IL,QualType & T,bool VerifyOnly,bool TreatUnavailableAsInvalid,bool InOverloadResolution)9437330f729Sjoerg InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
9447330f729Sjoerg InitListExpr *IL, QualType &T, bool VerifyOnly,
9457330f729Sjoerg bool TreatUnavailableAsInvalid,
9467330f729Sjoerg bool InOverloadResolution)
9477330f729Sjoerg : SemaRef(S), VerifyOnly(VerifyOnly),
9487330f729Sjoerg TreatUnavailableAsInvalid(TreatUnavailableAsInvalid),
9497330f729Sjoerg InOverloadResolution(InOverloadResolution) {
9507330f729Sjoerg if (!VerifyOnly || hasAnyDesignatedInits(IL)) {
9517330f729Sjoerg FullyStructuredList =
9527330f729Sjoerg createInitListExpr(T, IL->getSourceRange(), IL->getNumInits());
9537330f729Sjoerg
9547330f729Sjoerg // FIXME: Check that IL isn't already the semantic form of some other
9557330f729Sjoerg // InitListExpr. If it is, we'd create a broken AST.
9567330f729Sjoerg if (!VerifyOnly)
9577330f729Sjoerg FullyStructuredList->setSyntacticForm(IL);
9587330f729Sjoerg }
9597330f729Sjoerg
9607330f729Sjoerg CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
9617330f729Sjoerg /*TopLevelObject=*/true);
9627330f729Sjoerg
9637330f729Sjoerg if (!hadError && FullyStructuredList) {
9647330f729Sjoerg bool RequiresSecondPass = false;
9657330f729Sjoerg FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass,
9667330f729Sjoerg /*OuterILE=*/nullptr, /*OuterIndex=*/0);
9677330f729Sjoerg if (RequiresSecondPass && !hadError)
9687330f729Sjoerg FillInEmptyInitializations(Entity, FullyStructuredList,
9697330f729Sjoerg RequiresSecondPass, nullptr, 0);
9707330f729Sjoerg }
971*e038c9c4Sjoerg if (hadError && FullyStructuredList)
972*e038c9c4Sjoerg FullyStructuredList->markError();
9737330f729Sjoerg }
9747330f729Sjoerg
numArrayElements(QualType DeclType)9757330f729Sjoerg int InitListChecker::numArrayElements(QualType DeclType) {
9767330f729Sjoerg // FIXME: use a proper constant
9777330f729Sjoerg int maxElements = 0x7FFFFFFF;
9787330f729Sjoerg if (const ConstantArrayType *CAT =
9797330f729Sjoerg SemaRef.Context.getAsConstantArrayType(DeclType)) {
9807330f729Sjoerg maxElements = static_cast<int>(CAT->getSize().getZExtValue());
9817330f729Sjoerg }
9827330f729Sjoerg return maxElements;
9837330f729Sjoerg }
9847330f729Sjoerg
numStructUnionElements(QualType DeclType)9857330f729Sjoerg int InitListChecker::numStructUnionElements(QualType DeclType) {
9867330f729Sjoerg RecordDecl *structDecl = DeclType->castAs<RecordType>()->getDecl();
9877330f729Sjoerg int InitializableMembers = 0;
9887330f729Sjoerg if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl))
9897330f729Sjoerg InitializableMembers += CXXRD->getNumBases();
9907330f729Sjoerg for (const auto *Field : structDecl->fields())
9917330f729Sjoerg if (!Field->isUnnamedBitfield())
9927330f729Sjoerg ++InitializableMembers;
9937330f729Sjoerg
9947330f729Sjoerg if (structDecl->isUnion())
9957330f729Sjoerg return std::min(InitializableMembers, 1);
9967330f729Sjoerg return InitializableMembers - structDecl->hasFlexibleArrayMember();
9977330f729Sjoerg }
9987330f729Sjoerg
9997330f729Sjoerg /// Determine whether Entity is an entity for which it is idiomatic to elide
10007330f729Sjoerg /// the braces in aggregate initialization.
isIdiomaticBraceElisionEntity(const InitializedEntity & Entity)10017330f729Sjoerg static bool isIdiomaticBraceElisionEntity(const InitializedEntity &Entity) {
10027330f729Sjoerg // Recursive initialization of the one and only field within an aggregate
10037330f729Sjoerg // class is considered idiomatic. This case arises in particular for
10047330f729Sjoerg // initialization of std::array, where the C++ standard suggests the idiom of
10057330f729Sjoerg //
10067330f729Sjoerg // std::array<T, N> arr = {1, 2, 3};
10077330f729Sjoerg //
10087330f729Sjoerg // (where std::array is an aggregate struct containing a single array field.
10097330f729Sjoerg
1010*e038c9c4Sjoerg if (!Entity.getParent())
10117330f729Sjoerg return false;
10127330f729Sjoerg
1013*e038c9c4Sjoerg // Allows elide brace initialization for aggregates with empty base.
1014*e038c9c4Sjoerg if (Entity.getKind() == InitializedEntity::EK_Base) {
10157330f729Sjoerg auto *ParentRD =
10167330f729Sjoerg Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
1017*e038c9c4Sjoerg CXXRecordDecl *CXXRD = cast<CXXRecordDecl>(ParentRD);
1018*e038c9c4Sjoerg return CXXRD->getNumBases() == 1 && CXXRD->field_empty();
1019*e038c9c4Sjoerg }
10207330f729Sjoerg
1021*e038c9c4Sjoerg // Allow brace elision if the only subobject is a field.
1022*e038c9c4Sjoerg if (Entity.getKind() == InitializedEntity::EK_Member) {
1023*e038c9c4Sjoerg auto *ParentRD =
1024*e038c9c4Sjoerg Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
1025*e038c9c4Sjoerg if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD)) {
1026*e038c9c4Sjoerg if (CXXRD->getNumBases()) {
1027*e038c9c4Sjoerg return false;
1028*e038c9c4Sjoerg }
1029*e038c9c4Sjoerg }
10307330f729Sjoerg auto FieldIt = ParentRD->field_begin();
10317330f729Sjoerg assert(FieldIt != ParentRD->field_end() &&
10327330f729Sjoerg "no fields but have initializer for member?");
10337330f729Sjoerg return ++FieldIt == ParentRD->field_end();
10347330f729Sjoerg }
10357330f729Sjoerg
1036*e038c9c4Sjoerg return false;
1037*e038c9c4Sjoerg }
1038*e038c9c4Sjoerg
10397330f729Sjoerg /// Check whether the range of the initializer \p ParentIList from element
10407330f729Sjoerg /// \p Index onwards can be used to initialize an object of type \p T. Update
10417330f729Sjoerg /// \p Index to indicate how many elements of the list were consumed.
10427330f729Sjoerg ///
10437330f729Sjoerg /// This also fills in \p StructuredList, from element \p StructuredIndex
10447330f729Sjoerg /// onwards, with the fully-braced, desugared form of the initialization.
CheckImplicitInitList(const InitializedEntity & Entity,InitListExpr * ParentIList,QualType T,unsigned & Index,InitListExpr * StructuredList,unsigned & StructuredIndex)10457330f729Sjoerg void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
10467330f729Sjoerg InitListExpr *ParentIList,
10477330f729Sjoerg QualType T, unsigned &Index,
10487330f729Sjoerg InitListExpr *StructuredList,
10497330f729Sjoerg unsigned &StructuredIndex) {
10507330f729Sjoerg int maxElements = 0;
10517330f729Sjoerg
10527330f729Sjoerg if (T->isArrayType())
10537330f729Sjoerg maxElements = numArrayElements(T);
10547330f729Sjoerg else if (T->isRecordType())
10557330f729Sjoerg maxElements = numStructUnionElements(T);
10567330f729Sjoerg else if (T->isVectorType())
10577330f729Sjoerg maxElements = T->castAs<VectorType>()->getNumElements();
10587330f729Sjoerg else
10597330f729Sjoerg llvm_unreachable("CheckImplicitInitList(): Illegal type");
10607330f729Sjoerg
10617330f729Sjoerg if (maxElements == 0) {
10627330f729Sjoerg if (!VerifyOnly)
10637330f729Sjoerg SemaRef.Diag(ParentIList->getInit(Index)->getBeginLoc(),
10647330f729Sjoerg diag::err_implicit_empty_initializer);
10657330f729Sjoerg ++Index;
10667330f729Sjoerg hadError = true;
10677330f729Sjoerg return;
10687330f729Sjoerg }
10697330f729Sjoerg
10707330f729Sjoerg // Build a structured initializer list corresponding to this subobject.
10717330f729Sjoerg InitListExpr *StructuredSubobjectInitList = getStructuredSubobjectInit(
10727330f729Sjoerg ParentIList, Index, T, StructuredList, StructuredIndex,
10737330f729Sjoerg SourceRange(ParentIList->getInit(Index)->getBeginLoc(),
10747330f729Sjoerg ParentIList->getSourceRange().getEnd()));
10757330f729Sjoerg unsigned StructuredSubobjectInitIndex = 0;
10767330f729Sjoerg
10777330f729Sjoerg // Check the element types and build the structural subobject.
10787330f729Sjoerg unsigned StartIndex = Index;
10797330f729Sjoerg CheckListElementTypes(Entity, ParentIList, T,
10807330f729Sjoerg /*SubobjectIsDesignatorContext=*/false, Index,
10817330f729Sjoerg StructuredSubobjectInitList,
10827330f729Sjoerg StructuredSubobjectInitIndex);
10837330f729Sjoerg
10847330f729Sjoerg if (StructuredSubobjectInitList) {
10857330f729Sjoerg StructuredSubobjectInitList->setType(T);
10867330f729Sjoerg
10877330f729Sjoerg unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
10887330f729Sjoerg // Update the structured sub-object initializer so that it's ending
10897330f729Sjoerg // range corresponds with the end of the last initializer it used.
10907330f729Sjoerg if (EndIndex < ParentIList->getNumInits() &&
10917330f729Sjoerg ParentIList->getInit(EndIndex)) {
10927330f729Sjoerg SourceLocation EndLoc
10937330f729Sjoerg = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
10947330f729Sjoerg StructuredSubobjectInitList->setRBraceLoc(EndLoc);
10957330f729Sjoerg }
10967330f729Sjoerg
10977330f729Sjoerg // Complain about missing braces.
10987330f729Sjoerg if (!VerifyOnly && (T->isArrayType() || T->isRecordType()) &&
10997330f729Sjoerg !ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
11007330f729Sjoerg !isIdiomaticBraceElisionEntity(Entity)) {
11017330f729Sjoerg SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
11027330f729Sjoerg diag::warn_missing_braces)
11037330f729Sjoerg << StructuredSubobjectInitList->getSourceRange()
11047330f729Sjoerg << FixItHint::CreateInsertion(
11057330f729Sjoerg StructuredSubobjectInitList->getBeginLoc(), "{")
11067330f729Sjoerg << FixItHint::CreateInsertion(
11077330f729Sjoerg SemaRef.getLocForEndOfToken(
11087330f729Sjoerg StructuredSubobjectInitList->getEndLoc()),
11097330f729Sjoerg "}");
11107330f729Sjoerg }
11117330f729Sjoerg
11127330f729Sjoerg // Warn if this type won't be an aggregate in future versions of C++.
11137330f729Sjoerg auto *CXXRD = T->getAsCXXRecordDecl();
11147330f729Sjoerg if (!VerifyOnly && CXXRD && CXXRD->hasUserDeclaredConstructor()) {
11157330f729Sjoerg SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
1116*e038c9c4Sjoerg diag::warn_cxx20_compat_aggregate_init_with_ctors)
11177330f729Sjoerg << StructuredSubobjectInitList->getSourceRange() << T;
11187330f729Sjoerg }
11197330f729Sjoerg }
11207330f729Sjoerg }
11217330f729Sjoerg
11227330f729Sjoerg /// Warn that \p Entity was of scalar type and was initialized by a
11237330f729Sjoerg /// single-element braced initializer list.
warnBracedScalarInit(Sema & S,const InitializedEntity & Entity,SourceRange Braces)11247330f729Sjoerg static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
11257330f729Sjoerg SourceRange Braces) {
11267330f729Sjoerg // Don't warn during template instantiation. If the initialization was
11277330f729Sjoerg // non-dependent, we warned during the initial parse; otherwise, the
11287330f729Sjoerg // type might not be scalar in some uses of the template.
11297330f729Sjoerg if (S.inTemplateInstantiation())
11307330f729Sjoerg return;
11317330f729Sjoerg
11327330f729Sjoerg unsigned DiagID = 0;
11337330f729Sjoerg
11347330f729Sjoerg switch (Entity.getKind()) {
11357330f729Sjoerg case InitializedEntity::EK_VectorElement:
11367330f729Sjoerg case InitializedEntity::EK_ComplexElement:
11377330f729Sjoerg case InitializedEntity::EK_ArrayElement:
11387330f729Sjoerg case InitializedEntity::EK_Parameter:
11397330f729Sjoerg case InitializedEntity::EK_Parameter_CF_Audited:
1140*e038c9c4Sjoerg case InitializedEntity::EK_TemplateParameter:
11417330f729Sjoerg case InitializedEntity::EK_Result:
11427330f729Sjoerg // Extra braces here are suspicious.
1143*e038c9c4Sjoerg DiagID = diag::warn_braces_around_init;
11447330f729Sjoerg break;
11457330f729Sjoerg
11467330f729Sjoerg case InitializedEntity::EK_Member:
11477330f729Sjoerg // Warn on aggregate initialization but not on ctor init list or
11487330f729Sjoerg // default member initializer.
11497330f729Sjoerg if (Entity.getParent())
1150*e038c9c4Sjoerg DiagID = diag::warn_braces_around_init;
11517330f729Sjoerg break;
11527330f729Sjoerg
11537330f729Sjoerg case InitializedEntity::EK_Variable:
11547330f729Sjoerg case InitializedEntity::EK_LambdaCapture:
11557330f729Sjoerg // No warning, might be direct-list-initialization.
11567330f729Sjoerg // FIXME: Should we warn for copy-list-initialization in these cases?
11577330f729Sjoerg break;
11587330f729Sjoerg
11597330f729Sjoerg case InitializedEntity::EK_New:
11607330f729Sjoerg case InitializedEntity::EK_Temporary:
11617330f729Sjoerg case InitializedEntity::EK_CompoundLiteralInit:
11627330f729Sjoerg // No warning, braces are part of the syntax of the underlying construct.
11637330f729Sjoerg break;
11647330f729Sjoerg
11657330f729Sjoerg case InitializedEntity::EK_RelatedResult:
11667330f729Sjoerg // No warning, we already warned when initializing the result.
11677330f729Sjoerg break;
11687330f729Sjoerg
11697330f729Sjoerg case InitializedEntity::EK_Exception:
11707330f729Sjoerg case InitializedEntity::EK_Base:
11717330f729Sjoerg case InitializedEntity::EK_Delegating:
11727330f729Sjoerg case InitializedEntity::EK_BlockElement:
11737330f729Sjoerg case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
11747330f729Sjoerg case InitializedEntity::EK_Binding:
11757330f729Sjoerg case InitializedEntity::EK_StmtExprResult:
11767330f729Sjoerg llvm_unreachable("unexpected braced scalar init");
11777330f729Sjoerg }
11787330f729Sjoerg
11797330f729Sjoerg if (DiagID) {
11807330f729Sjoerg S.Diag(Braces.getBegin(), DiagID)
1181*e038c9c4Sjoerg << Entity.getType()->isSizelessBuiltinType() << Braces
11827330f729Sjoerg << FixItHint::CreateRemoval(Braces.getBegin())
11837330f729Sjoerg << FixItHint::CreateRemoval(Braces.getEnd());
11847330f729Sjoerg }
11857330f729Sjoerg }
11867330f729Sjoerg
11877330f729Sjoerg /// Check whether the initializer \p IList (that was written with explicit
11887330f729Sjoerg /// braces) can be used to initialize an object of type \p T.
11897330f729Sjoerg ///
11907330f729Sjoerg /// This also fills in \p StructuredList with the fully-braced, desugared
11917330f729Sjoerg /// form of the initialization.
CheckExplicitInitList(const InitializedEntity & Entity,InitListExpr * IList,QualType & T,InitListExpr * StructuredList,bool TopLevelObject)11927330f729Sjoerg void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
11937330f729Sjoerg InitListExpr *IList, QualType &T,
11947330f729Sjoerg InitListExpr *StructuredList,
11957330f729Sjoerg bool TopLevelObject) {
11967330f729Sjoerg unsigned Index = 0, StructuredIndex = 0;
11977330f729Sjoerg CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
11987330f729Sjoerg Index, StructuredList, StructuredIndex, TopLevelObject);
11997330f729Sjoerg if (StructuredList) {
12007330f729Sjoerg QualType ExprTy = T;
12017330f729Sjoerg if (!ExprTy->isArrayType())
12027330f729Sjoerg ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
12037330f729Sjoerg if (!VerifyOnly)
12047330f729Sjoerg IList->setType(ExprTy);
12057330f729Sjoerg StructuredList->setType(ExprTy);
12067330f729Sjoerg }
12077330f729Sjoerg if (hadError)
12087330f729Sjoerg return;
12097330f729Sjoerg
12107330f729Sjoerg // Don't complain for incomplete types, since we'll get an error elsewhere.
12117330f729Sjoerg if (Index < IList->getNumInits() && !T->isIncompleteType()) {
12127330f729Sjoerg // We have leftover initializers
12137330f729Sjoerg bool ExtraInitsIsError = SemaRef.getLangOpts().CPlusPlus ||
12147330f729Sjoerg (SemaRef.getLangOpts().OpenCL && T->isVectorType());
12157330f729Sjoerg hadError = ExtraInitsIsError;
12167330f729Sjoerg if (VerifyOnly) {
12177330f729Sjoerg return;
12187330f729Sjoerg } else if (StructuredIndex == 1 &&
12197330f729Sjoerg IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
12207330f729Sjoerg SIF_None) {
12217330f729Sjoerg unsigned DK =
12227330f729Sjoerg ExtraInitsIsError
12237330f729Sjoerg ? diag::err_excess_initializers_in_char_array_initializer
12247330f729Sjoerg : diag::ext_excess_initializers_in_char_array_initializer;
12257330f729Sjoerg SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
12267330f729Sjoerg << IList->getInit(Index)->getSourceRange();
1227*e038c9c4Sjoerg } else if (T->isSizelessBuiltinType()) {
1228*e038c9c4Sjoerg unsigned DK = ExtraInitsIsError
1229*e038c9c4Sjoerg ? diag::err_excess_initializers_for_sizeless_type
1230*e038c9c4Sjoerg : diag::ext_excess_initializers_for_sizeless_type;
1231*e038c9c4Sjoerg SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1232*e038c9c4Sjoerg << T << IList->getInit(Index)->getSourceRange();
12337330f729Sjoerg } else {
12347330f729Sjoerg int initKind = T->isArrayType() ? 0 :
12357330f729Sjoerg T->isVectorType() ? 1 :
12367330f729Sjoerg T->isScalarType() ? 2 :
12377330f729Sjoerg T->isUnionType() ? 3 :
12387330f729Sjoerg 4;
12397330f729Sjoerg
12407330f729Sjoerg unsigned DK = ExtraInitsIsError ? diag::err_excess_initializers
12417330f729Sjoerg : diag::ext_excess_initializers;
12427330f729Sjoerg SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
12437330f729Sjoerg << initKind << IList->getInit(Index)->getSourceRange();
12447330f729Sjoerg }
12457330f729Sjoerg }
12467330f729Sjoerg
12477330f729Sjoerg if (!VerifyOnly) {
12487330f729Sjoerg if (T->isScalarType() && IList->getNumInits() == 1 &&
12497330f729Sjoerg !isa<InitListExpr>(IList->getInit(0)))
12507330f729Sjoerg warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
12517330f729Sjoerg
12527330f729Sjoerg // Warn if this is a class type that won't be an aggregate in future
12537330f729Sjoerg // versions of C++.
12547330f729Sjoerg auto *CXXRD = T->getAsCXXRecordDecl();
12557330f729Sjoerg if (CXXRD && CXXRD->hasUserDeclaredConstructor()) {
12567330f729Sjoerg // Don't warn if there's an equivalent default constructor that would be
12577330f729Sjoerg // used instead.
12587330f729Sjoerg bool HasEquivCtor = false;
12597330f729Sjoerg if (IList->getNumInits() == 0) {
12607330f729Sjoerg auto *CD = SemaRef.LookupDefaultConstructor(CXXRD);
12617330f729Sjoerg HasEquivCtor = CD && !CD->isDeleted();
12627330f729Sjoerg }
12637330f729Sjoerg
12647330f729Sjoerg if (!HasEquivCtor) {
12657330f729Sjoerg SemaRef.Diag(IList->getBeginLoc(),
1266*e038c9c4Sjoerg diag::warn_cxx20_compat_aggregate_init_with_ctors)
12677330f729Sjoerg << IList->getSourceRange() << T;
12687330f729Sjoerg }
12697330f729Sjoerg }
12707330f729Sjoerg }
12717330f729Sjoerg }
12727330f729Sjoerg
CheckListElementTypes(const InitializedEntity & Entity,InitListExpr * IList,QualType & DeclType,bool SubobjectIsDesignatorContext,unsigned & Index,InitListExpr * StructuredList,unsigned & StructuredIndex,bool TopLevelObject)12737330f729Sjoerg void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
12747330f729Sjoerg InitListExpr *IList,
12757330f729Sjoerg QualType &DeclType,
12767330f729Sjoerg bool SubobjectIsDesignatorContext,
12777330f729Sjoerg unsigned &Index,
12787330f729Sjoerg InitListExpr *StructuredList,
12797330f729Sjoerg unsigned &StructuredIndex,
12807330f729Sjoerg bool TopLevelObject) {
12817330f729Sjoerg if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
12827330f729Sjoerg // Explicitly braced initializer for complex type can be real+imaginary
12837330f729Sjoerg // parts.
12847330f729Sjoerg CheckComplexType(Entity, IList, DeclType, Index,
12857330f729Sjoerg StructuredList, StructuredIndex);
12867330f729Sjoerg } else if (DeclType->isScalarType()) {
12877330f729Sjoerg CheckScalarType(Entity, IList, DeclType, Index,
12887330f729Sjoerg StructuredList, StructuredIndex);
12897330f729Sjoerg } else if (DeclType->isVectorType()) {
12907330f729Sjoerg CheckVectorType(Entity, IList, DeclType, Index,
12917330f729Sjoerg StructuredList, StructuredIndex);
12927330f729Sjoerg } else if (DeclType->isRecordType()) {
12937330f729Sjoerg assert(DeclType->isAggregateType() &&
12947330f729Sjoerg "non-aggregate records should be handed in CheckSubElementType");
12957330f729Sjoerg RecordDecl *RD = DeclType->castAs<RecordType>()->getDecl();
12967330f729Sjoerg auto Bases =
12977330f729Sjoerg CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
12987330f729Sjoerg CXXRecordDecl::base_class_iterator());
12997330f729Sjoerg if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
13007330f729Sjoerg Bases = CXXRD->bases();
13017330f729Sjoerg CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),
13027330f729Sjoerg SubobjectIsDesignatorContext, Index, StructuredList,
13037330f729Sjoerg StructuredIndex, TopLevelObject);
13047330f729Sjoerg } else if (DeclType->isArrayType()) {
13057330f729Sjoerg llvm::APSInt Zero(
13067330f729Sjoerg SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
13077330f729Sjoerg false);
13087330f729Sjoerg CheckArrayType(Entity, IList, DeclType, Zero,
13097330f729Sjoerg SubobjectIsDesignatorContext, Index,
13107330f729Sjoerg StructuredList, StructuredIndex);
13117330f729Sjoerg } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
13127330f729Sjoerg // This type is invalid, issue a diagnostic.
13137330f729Sjoerg ++Index;
13147330f729Sjoerg if (!VerifyOnly)
13157330f729Sjoerg SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
13167330f729Sjoerg << DeclType;
13177330f729Sjoerg hadError = true;
13187330f729Sjoerg } else if (DeclType->isReferenceType()) {
13197330f729Sjoerg CheckReferenceType(Entity, IList, DeclType, Index,
13207330f729Sjoerg StructuredList, StructuredIndex);
13217330f729Sjoerg } else if (DeclType->isObjCObjectType()) {
13227330f729Sjoerg if (!VerifyOnly)
13237330f729Sjoerg SemaRef.Diag(IList->getBeginLoc(), diag::err_init_objc_class) << DeclType;
13247330f729Sjoerg hadError = true;
1325*e038c9c4Sjoerg } else if (DeclType->isOCLIntelSubgroupAVCType() ||
1326*e038c9c4Sjoerg DeclType->isSizelessBuiltinType()) {
13277330f729Sjoerg // Checks for scalar type are sufficient for these types too.
13287330f729Sjoerg CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
13297330f729Sjoerg StructuredIndex);
13307330f729Sjoerg } else {
13317330f729Sjoerg if (!VerifyOnly)
13327330f729Sjoerg SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
13337330f729Sjoerg << DeclType;
13347330f729Sjoerg hadError = true;
13357330f729Sjoerg }
13367330f729Sjoerg }
13377330f729Sjoerg
CheckSubElementType(const InitializedEntity & Entity,InitListExpr * IList,QualType ElemType,unsigned & Index,InitListExpr * StructuredList,unsigned & StructuredIndex,bool DirectlyDesignated)13387330f729Sjoerg void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
13397330f729Sjoerg InitListExpr *IList,
13407330f729Sjoerg QualType ElemType,
13417330f729Sjoerg unsigned &Index,
13427330f729Sjoerg InitListExpr *StructuredList,
1343*e038c9c4Sjoerg unsigned &StructuredIndex,
1344*e038c9c4Sjoerg bool DirectlyDesignated) {
13457330f729Sjoerg Expr *expr = IList->getInit(Index);
13467330f729Sjoerg
13477330f729Sjoerg if (ElemType->isReferenceType())
13487330f729Sjoerg return CheckReferenceType(Entity, IList, ElemType, Index,
13497330f729Sjoerg StructuredList, StructuredIndex);
13507330f729Sjoerg
13517330f729Sjoerg if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
13527330f729Sjoerg if (SubInitList->getNumInits() == 1 &&
13537330f729Sjoerg IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
13547330f729Sjoerg SIF_None) {
13557330f729Sjoerg // FIXME: It would be more faithful and no less correct to include an
13567330f729Sjoerg // InitListExpr in the semantic form of the initializer list in this case.
13577330f729Sjoerg expr = SubInitList->getInit(0);
13587330f729Sjoerg }
13597330f729Sjoerg // Nested aggregate initialization and C++ initialization are handled later.
13607330f729Sjoerg } else if (isa<ImplicitValueInitExpr>(expr)) {
13617330f729Sjoerg // This happens during template instantiation when we see an InitListExpr
13627330f729Sjoerg // that we've already checked once.
13637330f729Sjoerg assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
13647330f729Sjoerg "found implicit initialization for the wrong type");
13657330f729Sjoerg UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
13667330f729Sjoerg ++Index;
13677330f729Sjoerg return;
13687330f729Sjoerg }
13697330f729Sjoerg
13707330f729Sjoerg if (SemaRef.getLangOpts().CPlusPlus || isa<InitListExpr>(expr)) {
13717330f729Sjoerg // C++ [dcl.init.aggr]p2:
13727330f729Sjoerg // Each member is copy-initialized from the corresponding
13737330f729Sjoerg // initializer-clause.
13747330f729Sjoerg
13757330f729Sjoerg // FIXME: Better EqualLoc?
13767330f729Sjoerg InitializationKind Kind =
13777330f729Sjoerg InitializationKind::CreateCopy(expr->getBeginLoc(), SourceLocation());
13787330f729Sjoerg
13797330f729Sjoerg // Vector elements can be initialized from other vectors in which case
13807330f729Sjoerg // we need initialization entity with a type of a vector (and not a vector
13817330f729Sjoerg // element!) initializing multiple vector elements.
13827330f729Sjoerg auto TmpEntity =
13837330f729Sjoerg (ElemType->isExtVectorType() && !Entity.getType()->isExtVectorType())
13847330f729Sjoerg ? InitializedEntity::InitializeTemporary(ElemType)
13857330f729Sjoerg : Entity;
13867330f729Sjoerg
13877330f729Sjoerg InitializationSequence Seq(SemaRef, TmpEntity, Kind, expr,
13887330f729Sjoerg /*TopLevelOfInitList*/ true);
13897330f729Sjoerg
13907330f729Sjoerg // C++14 [dcl.init.aggr]p13:
13917330f729Sjoerg // If the assignment-expression can initialize a member, the member is
13927330f729Sjoerg // initialized. Otherwise [...] brace elision is assumed
13937330f729Sjoerg //
13947330f729Sjoerg // Brace elision is never performed if the element is not an
13957330f729Sjoerg // assignment-expression.
13967330f729Sjoerg if (Seq || isa<InitListExpr>(expr)) {
13977330f729Sjoerg if (!VerifyOnly) {
13987330f729Sjoerg ExprResult Result = Seq.Perform(SemaRef, TmpEntity, Kind, expr);
13997330f729Sjoerg if (Result.isInvalid())
14007330f729Sjoerg hadError = true;
14017330f729Sjoerg
14027330f729Sjoerg UpdateStructuredListElement(StructuredList, StructuredIndex,
14037330f729Sjoerg Result.getAs<Expr>());
14047330f729Sjoerg } else if (!Seq) {
14057330f729Sjoerg hadError = true;
14067330f729Sjoerg } else if (StructuredList) {
14077330f729Sjoerg UpdateStructuredListElement(StructuredList, StructuredIndex,
14087330f729Sjoerg getDummyInit());
14097330f729Sjoerg }
14107330f729Sjoerg ++Index;
14117330f729Sjoerg return;
14127330f729Sjoerg }
14137330f729Sjoerg
14147330f729Sjoerg // Fall through for subaggregate initialization
14157330f729Sjoerg } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
14167330f729Sjoerg // FIXME: Need to handle atomic aggregate types with implicit init lists.
14177330f729Sjoerg return CheckScalarType(Entity, IList, ElemType, Index,
14187330f729Sjoerg StructuredList, StructuredIndex);
14197330f729Sjoerg } else if (const ArrayType *arrayType =
14207330f729Sjoerg SemaRef.Context.getAsArrayType(ElemType)) {
14217330f729Sjoerg // arrayType can be incomplete if we're initializing a flexible
14227330f729Sjoerg // array member. There's nothing we can do with the completed
14237330f729Sjoerg // type here, though.
14247330f729Sjoerg
14257330f729Sjoerg if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
14267330f729Sjoerg // FIXME: Should we do this checking in verify-only mode?
14277330f729Sjoerg if (!VerifyOnly)
14287330f729Sjoerg CheckStringInit(expr, ElemType, arrayType, SemaRef);
14297330f729Sjoerg if (StructuredList)
14307330f729Sjoerg UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
14317330f729Sjoerg ++Index;
14327330f729Sjoerg return;
14337330f729Sjoerg }
14347330f729Sjoerg
14357330f729Sjoerg // Fall through for subaggregate initialization.
14367330f729Sjoerg
14377330f729Sjoerg } else {
14387330f729Sjoerg assert((ElemType->isRecordType() || ElemType->isVectorType() ||
14397330f729Sjoerg ElemType->isOpenCLSpecificType()) && "Unexpected type");
14407330f729Sjoerg
14417330f729Sjoerg // C99 6.7.8p13:
14427330f729Sjoerg //
14437330f729Sjoerg // The initializer for a structure or union object that has
14447330f729Sjoerg // automatic storage duration shall be either an initializer
14457330f729Sjoerg // list as described below, or a single expression that has
14467330f729Sjoerg // compatible structure or union type. In the latter case, the
14477330f729Sjoerg // initial value of the object, including unnamed members, is
14487330f729Sjoerg // that of the expression.
14497330f729Sjoerg ExprResult ExprRes = expr;
14507330f729Sjoerg if (SemaRef.CheckSingleAssignmentConstraints(
14517330f729Sjoerg ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) {
14527330f729Sjoerg if (ExprRes.isInvalid())
14537330f729Sjoerg hadError = true;
14547330f729Sjoerg else {
14557330f729Sjoerg ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
14567330f729Sjoerg if (ExprRes.isInvalid())
14577330f729Sjoerg hadError = true;
14587330f729Sjoerg }
14597330f729Sjoerg UpdateStructuredListElement(StructuredList, StructuredIndex,
14607330f729Sjoerg ExprRes.getAs<Expr>());
14617330f729Sjoerg ++Index;
14627330f729Sjoerg return;
14637330f729Sjoerg }
14647330f729Sjoerg ExprRes.get();
14657330f729Sjoerg // Fall through for subaggregate initialization
14667330f729Sjoerg }
14677330f729Sjoerg
14687330f729Sjoerg // C++ [dcl.init.aggr]p12:
14697330f729Sjoerg //
14707330f729Sjoerg // [...] Otherwise, if the member is itself a non-empty
14717330f729Sjoerg // subaggregate, brace elision is assumed and the initializer is
14727330f729Sjoerg // considered for the initialization of the first member of
14737330f729Sjoerg // the subaggregate.
14747330f729Sjoerg // OpenCL vector initializer is handled elsewhere.
14757330f729Sjoerg if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) ||
14767330f729Sjoerg ElemType->isAggregateType()) {
14777330f729Sjoerg CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
14787330f729Sjoerg StructuredIndex);
14797330f729Sjoerg ++StructuredIndex;
1480*e038c9c4Sjoerg
1481*e038c9c4Sjoerg // In C++20, brace elision is not permitted for a designated initializer.
1482*e038c9c4Sjoerg if (DirectlyDesignated && SemaRef.getLangOpts().CPlusPlus && !hadError) {
1483*e038c9c4Sjoerg if (InOverloadResolution)
1484*e038c9c4Sjoerg hadError = true;
1485*e038c9c4Sjoerg if (!VerifyOnly) {
1486*e038c9c4Sjoerg SemaRef.Diag(expr->getBeginLoc(),
1487*e038c9c4Sjoerg diag::ext_designated_init_brace_elision)
1488*e038c9c4Sjoerg << expr->getSourceRange()
1489*e038c9c4Sjoerg << FixItHint::CreateInsertion(expr->getBeginLoc(), "{")
1490*e038c9c4Sjoerg << FixItHint::CreateInsertion(
1491*e038c9c4Sjoerg SemaRef.getLocForEndOfToken(expr->getEndLoc()), "}");
1492*e038c9c4Sjoerg }
1493*e038c9c4Sjoerg }
14947330f729Sjoerg } else {
14957330f729Sjoerg if (!VerifyOnly) {
14967330f729Sjoerg // We cannot initialize this element, so let PerformCopyInitialization
14977330f729Sjoerg // produce the appropriate diagnostic. We already checked that this
14987330f729Sjoerg // initialization will fail.
14997330f729Sjoerg ExprResult Copy =
15007330f729Sjoerg SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
15017330f729Sjoerg /*TopLevelOfInitList=*/true);
15027330f729Sjoerg (void)Copy;
15037330f729Sjoerg assert(Copy.isInvalid() &&
15047330f729Sjoerg "expected non-aggregate initialization to fail");
15057330f729Sjoerg }
15067330f729Sjoerg hadError = true;
15077330f729Sjoerg ++Index;
15087330f729Sjoerg ++StructuredIndex;
15097330f729Sjoerg }
15107330f729Sjoerg }
15117330f729Sjoerg
CheckComplexType(const InitializedEntity & Entity,InitListExpr * IList,QualType DeclType,unsigned & Index,InitListExpr * StructuredList,unsigned & StructuredIndex)15127330f729Sjoerg void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
15137330f729Sjoerg InitListExpr *IList, QualType DeclType,
15147330f729Sjoerg unsigned &Index,
15157330f729Sjoerg InitListExpr *StructuredList,
15167330f729Sjoerg unsigned &StructuredIndex) {
15177330f729Sjoerg assert(Index == 0 && "Index in explicit init list must be zero");
15187330f729Sjoerg
15197330f729Sjoerg // As an extension, clang supports complex initializers, which initialize
15207330f729Sjoerg // a complex number component-wise. When an explicit initializer list for
15217330f729Sjoerg // a complex number contains two two initializers, this extension kicks in:
15227330f729Sjoerg // it exepcts the initializer list to contain two elements convertible to
15237330f729Sjoerg // the element type of the complex type. The first element initializes
15247330f729Sjoerg // the real part, and the second element intitializes the imaginary part.
15257330f729Sjoerg
15267330f729Sjoerg if (IList->getNumInits() != 2)
15277330f729Sjoerg return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
15287330f729Sjoerg StructuredIndex);
15297330f729Sjoerg
15307330f729Sjoerg // This is an extension in C. (The builtin _Complex type does not exist
15317330f729Sjoerg // in the C++ standard.)
15327330f729Sjoerg if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
15337330f729Sjoerg SemaRef.Diag(IList->getBeginLoc(), diag::ext_complex_component_init)
15347330f729Sjoerg << IList->getSourceRange();
15357330f729Sjoerg
15367330f729Sjoerg // Initialize the complex number.
15377330f729Sjoerg QualType elementType = DeclType->castAs<ComplexType>()->getElementType();
15387330f729Sjoerg InitializedEntity ElementEntity =
15397330f729Sjoerg InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
15407330f729Sjoerg
15417330f729Sjoerg for (unsigned i = 0; i < 2; ++i) {
15427330f729Sjoerg ElementEntity.setElementIndex(Index);
15437330f729Sjoerg CheckSubElementType(ElementEntity, IList, elementType, Index,
15447330f729Sjoerg StructuredList, StructuredIndex);
15457330f729Sjoerg }
15467330f729Sjoerg }
15477330f729Sjoerg
CheckScalarType(const InitializedEntity & Entity,InitListExpr * IList,QualType DeclType,unsigned & Index,InitListExpr * StructuredList,unsigned & StructuredIndex)15487330f729Sjoerg void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
15497330f729Sjoerg InitListExpr *IList, QualType DeclType,
15507330f729Sjoerg unsigned &Index,
15517330f729Sjoerg InitListExpr *StructuredList,
15527330f729Sjoerg unsigned &StructuredIndex) {
15537330f729Sjoerg if (Index >= IList->getNumInits()) {
1554*e038c9c4Sjoerg if (!VerifyOnly) {
1555*e038c9c4Sjoerg if (DeclType->isSizelessBuiltinType())
1556*e038c9c4Sjoerg SemaRef.Diag(IList->getBeginLoc(),
1557*e038c9c4Sjoerg SemaRef.getLangOpts().CPlusPlus11
1558*e038c9c4Sjoerg ? diag::warn_cxx98_compat_empty_sizeless_initializer
1559*e038c9c4Sjoerg : diag::err_empty_sizeless_initializer)
1560*e038c9c4Sjoerg << DeclType << IList->getSourceRange();
1561*e038c9c4Sjoerg else
15627330f729Sjoerg SemaRef.Diag(IList->getBeginLoc(),
15637330f729Sjoerg SemaRef.getLangOpts().CPlusPlus11
15647330f729Sjoerg ? diag::warn_cxx98_compat_empty_scalar_initializer
15657330f729Sjoerg : diag::err_empty_scalar_initializer)
15667330f729Sjoerg << IList->getSourceRange();
1567*e038c9c4Sjoerg }
15687330f729Sjoerg hadError = !SemaRef.getLangOpts().CPlusPlus11;
15697330f729Sjoerg ++Index;
15707330f729Sjoerg ++StructuredIndex;
15717330f729Sjoerg return;
15727330f729Sjoerg }
15737330f729Sjoerg
15747330f729Sjoerg Expr *expr = IList->getInit(Index);
15757330f729Sjoerg if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
15767330f729Sjoerg // FIXME: This is invalid, and accepting it causes overload resolution
15777330f729Sjoerg // to pick the wrong overload in some corner cases.
15787330f729Sjoerg if (!VerifyOnly)
1579*e038c9c4Sjoerg SemaRef.Diag(SubIList->getBeginLoc(), diag::ext_many_braces_around_init)
1580*e038c9c4Sjoerg << DeclType->isSizelessBuiltinType() << SubIList->getSourceRange();
15817330f729Sjoerg
15827330f729Sjoerg CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
15837330f729Sjoerg StructuredIndex);
15847330f729Sjoerg return;
15857330f729Sjoerg } else if (isa<DesignatedInitExpr>(expr)) {
15867330f729Sjoerg if (!VerifyOnly)
1587*e038c9c4Sjoerg SemaRef.Diag(expr->getBeginLoc(),
1588*e038c9c4Sjoerg diag::err_designator_for_scalar_or_sizeless_init)
1589*e038c9c4Sjoerg << DeclType->isSizelessBuiltinType() << DeclType
1590*e038c9c4Sjoerg << expr->getSourceRange();
15917330f729Sjoerg hadError = true;
15927330f729Sjoerg ++Index;
15937330f729Sjoerg ++StructuredIndex;
15947330f729Sjoerg return;
15957330f729Sjoerg }
15967330f729Sjoerg
15977330f729Sjoerg ExprResult Result;
15987330f729Sjoerg if (VerifyOnly) {
15997330f729Sjoerg if (SemaRef.CanPerformCopyInitialization(Entity, expr))
16007330f729Sjoerg Result = getDummyInit();
16017330f729Sjoerg else
16027330f729Sjoerg Result = ExprError();
16037330f729Sjoerg } else {
16047330f729Sjoerg Result =
16057330f729Sjoerg SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
16067330f729Sjoerg /*TopLevelOfInitList=*/true);
16077330f729Sjoerg }
16087330f729Sjoerg
16097330f729Sjoerg Expr *ResultExpr = nullptr;
16107330f729Sjoerg
16117330f729Sjoerg if (Result.isInvalid())
16127330f729Sjoerg hadError = true; // types weren't compatible.
16137330f729Sjoerg else {
16147330f729Sjoerg ResultExpr = Result.getAs<Expr>();
16157330f729Sjoerg
16167330f729Sjoerg if (ResultExpr != expr && !VerifyOnly) {
16177330f729Sjoerg // The type was promoted, update initializer list.
16187330f729Sjoerg // FIXME: Why are we updating the syntactic init list?
16197330f729Sjoerg IList->setInit(Index, ResultExpr);
16207330f729Sjoerg }
16217330f729Sjoerg }
16227330f729Sjoerg UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
16237330f729Sjoerg ++Index;
16247330f729Sjoerg }
16257330f729Sjoerg
CheckReferenceType(const InitializedEntity & Entity,InitListExpr * IList,QualType DeclType,unsigned & Index,InitListExpr * StructuredList,unsigned & StructuredIndex)16267330f729Sjoerg void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
16277330f729Sjoerg InitListExpr *IList, QualType DeclType,
16287330f729Sjoerg unsigned &Index,
16297330f729Sjoerg InitListExpr *StructuredList,
16307330f729Sjoerg unsigned &StructuredIndex) {
16317330f729Sjoerg if (Index >= IList->getNumInits()) {
16327330f729Sjoerg // FIXME: It would be wonderful if we could point at the actual member. In
16337330f729Sjoerg // general, it would be useful to pass location information down the stack,
16347330f729Sjoerg // so that we know the location (or decl) of the "current object" being
16357330f729Sjoerg // initialized.
16367330f729Sjoerg if (!VerifyOnly)
16377330f729Sjoerg SemaRef.Diag(IList->getBeginLoc(),
16387330f729Sjoerg diag::err_init_reference_member_uninitialized)
16397330f729Sjoerg << DeclType << IList->getSourceRange();
16407330f729Sjoerg hadError = true;
16417330f729Sjoerg ++Index;
16427330f729Sjoerg ++StructuredIndex;
16437330f729Sjoerg return;
16447330f729Sjoerg }
16457330f729Sjoerg
16467330f729Sjoerg Expr *expr = IList->getInit(Index);
16477330f729Sjoerg if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
16487330f729Sjoerg if (!VerifyOnly)
16497330f729Sjoerg SemaRef.Diag(IList->getBeginLoc(), diag::err_init_non_aggr_init_list)
16507330f729Sjoerg << DeclType << IList->getSourceRange();
16517330f729Sjoerg hadError = true;
16527330f729Sjoerg ++Index;
16537330f729Sjoerg ++StructuredIndex;
16547330f729Sjoerg return;
16557330f729Sjoerg }
16567330f729Sjoerg
16577330f729Sjoerg ExprResult Result;
16587330f729Sjoerg if (VerifyOnly) {
16597330f729Sjoerg if (SemaRef.CanPerformCopyInitialization(Entity,expr))
16607330f729Sjoerg Result = getDummyInit();
16617330f729Sjoerg else
16627330f729Sjoerg Result = ExprError();
16637330f729Sjoerg } else {
16647330f729Sjoerg Result =
16657330f729Sjoerg SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
16667330f729Sjoerg /*TopLevelOfInitList=*/true);
16677330f729Sjoerg }
16687330f729Sjoerg
16697330f729Sjoerg if (Result.isInvalid())
16707330f729Sjoerg hadError = true;
16717330f729Sjoerg
16727330f729Sjoerg expr = Result.getAs<Expr>();
16737330f729Sjoerg // FIXME: Why are we updating the syntactic init list?
1674*e038c9c4Sjoerg if (!VerifyOnly && expr)
16757330f729Sjoerg IList->setInit(Index, expr);
16767330f729Sjoerg
16777330f729Sjoerg UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
16787330f729Sjoerg ++Index;
16797330f729Sjoerg }
16807330f729Sjoerg
CheckVectorType(const InitializedEntity & Entity,InitListExpr * IList,QualType DeclType,unsigned & Index,InitListExpr * StructuredList,unsigned & StructuredIndex)16817330f729Sjoerg void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
16827330f729Sjoerg InitListExpr *IList, QualType DeclType,
16837330f729Sjoerg unsigned &Index,
16847330f729Sjoerg InitListExpr *StructuredList,
16857330f729Sjoerg unsigned &StructuredIndex) {
16867330f729Sjoerg const VectorType *VT = DeclType->castAs<VectorType>();
16877330f729Sjoerg unsigned maxElements = VT->getNumElements();
16887330f729Sjoerg unsigned numEltsInit = 0;
16897330f729Sjoerg QualType elementType = VT->getElementType();
16907330f729Sjoerg
16917330f729Sjoerg if (Index >= IList->getNumInits()) {
16927330f729Sjoerg // Make sure the element type can be value-initialized.
16937330f729Sjoerg CheckEmptyInitializable(
16947330f729Sjoerg InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
16957330f729Sjoerg IList->getEndLoc());
16967330f729Sjoerg return;
16977330f729Sjoerg }
16987330f729Sjoerg
16997330f729Sjoerg if (!SemaRef.getLangOpts().OpenCL) {
17007330f729Sjoerg // If the initializing element is a vector, try to copy-initialize
17017330f729Sjoerg // instead of breaking it apart (which is doomed to failure anyway).
17027330f729Sjoerg Expr *Init = IList->getInit(Index);
17037330f729Sjoerg if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
17047330f729Sjoerg ExprResult Result;
17057330f729Sjoerg if (VerifyOnly) {
17067330f729Sjoerg if (SemaRef.CanPerformCopyInitialization(Entity, Init))
17077330f729Sjoerg Result = getDummyInit();
17087330f729Sjoerg else
17097330f729Sjoerg Result = ExprError();
17107330f729Sjoerg } else {
17117330f729Sjoerg Result =
17127330f729Sjoerg SemaRef.PerformCopyInitialization(Entity, Init->getBeginLoc(), Init,
17137330f729Sjoerg /*TopLevelOfInitList=*/true);
17147330f729Sjoerg }
17157330f729Sjoerg
17167330f729Sjoerg Expr *ResultExpr = nullptr;
17177330f729Sjoerg if (Result.isInvalid())
17187330f729Sjoerg hadError = true; // types weren't compatible.
17197330f729Sjoerg else {
17207330f729Sjoerg ResultExpr = Result.getAs<Expr>();
17217330f729Sjoerg
17227330f729Sjoerg if (ResultExpr != Init && !VerifyOnly) {
17237330f729Sjoerg // The type was promoted, update initializer list.
17247330f729Sjoerg // FIXME: Why are we updating the syntactic init list?
17257330f729Sjoerg IList->setInit(Index, ResultExpr);
17267330f729Sjoerg }
17277330f729Sjoerg }
1728*e038c9c4Sjoerg UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
17297330f729Sjoerg ++Index;
17307330f729Sjoerg return;
17317330f729Sjoerg }
17327330f729Sjoerg
17337330f729Sjoerg InitializedEntity ElementEntity =
17347330f729Sjoerg InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
17357330f729Sjoerg
17367330f729Sjoerg for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
17377330f729Sjoerg // Don't attempt to go past the end of the init list
17387330f729Sjoerg if (Index >= IList->getNumInits()) {
17397330f729Sjoerg CheckEmptyInitializable(ElementEntity, IList->getEndLoc());
17407330f729Sjoerg break;
17417330f729Sjoerg }
17427330f729Sjoerg
17437330f729Sjoerg ElementEntity.setElementIndex(Index);
17447330f729Sjoerg CheckSubElementType(ElementEntity, IList, elementType, Index,
17457330f729Sjoerg StructuredList, StructuredIndex);
17467330f729Sjoerg }
17477330f729Sjoerg
17487330f729Sjoerg if (VerifyOnly)
17497330f729Sjoerg return;
17507330f729Sjoerg
17517330f729Sjoerg bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
17527330f729Sjoerg const VectorType *T = Entity.getType()->castAs<VectorType>();
17537330f729Sjoerg if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector ||
17547330f729Sjoerg T->getVectorKind() == VectorType::NeonPolyVector)) {
17557330f729Sjoerg // The ability to use vector initializer lists is a GNU vector extension
17567330f729Sjoerg // and is unrelated to the NEON intrinsics in arm_neon.h. On little
17577330f729Sjoerg // endian machines it works fine, however on big endian machines it
17587330f729Sjoerg // exhibits surprising behaviour:
17597330f729Sjoerg //
17607330f729Sjoerg // uint32x2_t x = {42, 64};
17617330f729Sjoerg // return vget_lane_u32(x, 0); // Will return 64.
17627330f729Sjoerg //
17637330f729Sjoerg // Because of this, explicitly call out that it is non-portable.
17647330f729Sjoerg //
17657330f729Sjoerg SemaRef.Diag(IList->getBeginLoc(),
17667330f729Sjoerg diag::warn_neon_vector_initializer_non_portable);
17677330f729Sjoerg
17687330f729Sjoerg const char *typeCode;
17697330f729Sjoerg unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
17707330f729Sjoerg
17717330f729Sjoerg if (elementType->isFloatingType())
17727330f729Sjoerg typeCode = "f";
17737330f729Sjoerg else if (elementType->isSignedIntegerType())
17747330f729Sjoerg typeCode = "s";
17757330f729Sjoerg else if (elementType->isUnsignedIntegerType())
17767330f729Sjoerg typeCode = "u";
17777330f729Sjoerg else
17787330f729Sjoerg llvm_unreachable("Invalid element type!");
17797330f729Sjoerg
17807330f729Sjoerg SemaRef.Diag(IList->getBeginLoc(),
17817330f729Sjoerg SemaRef.Context.getTypeSize(VT) > 64
17827330f729Sjoerg ? diag::note_neon_vector_initializer_non_portable_q
17837330f729Sjoerg : diag::note_neon_vector_initializer_non_portable)
17847330f729Sjoerg << typeCode << typeSize;
17857330f729Sjoerg }
17867330f729Sjoerg
17877330f729Sjoerg return;
17887330f729Sjoerg }
17897330f729Sjoerg
17907330f729Sjoerg InitializedEntity ElementEntity =
17917330f729Sjoerg InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
17927330f729Sjoerg
17937330f729Sjoerg // OpenCL initializers allows vectors to be constructed from vectors.
17947330f729Sjoerg for (unsigned i = 0; i < maxElements; ++i) {
17957330f729Sjoerg // Don't attempt to go past the end of the init list
17967330f729Sjoerg if (Index >= IList->getNumInits())
17977330f729Sjoerg break;
17987330f729Sjoerg
17997330f729Sjoerg ElementEntity.setElementIndex(Index);
18007330f729Sjoerg
18017330f729Sjoerg QualType IType = IList->getInit(Index)->getType();
18027330f729Sjoerg if (!IType->isVectorType()) {
18037330f729Sjoerg CheckSubElementType(ElementEntity, IList, elementType, Index,
18047330f729Sjoerg StructuredList, StructuredIndex);
18057330f729Sjoerg ++numEltsInit;
18067330f729Sjoerg } else {
18077330f729Sjoerg QualType VecType;
18087330f729Sjoerg const VectorType *IVT = IType->castAs<VectorType>();
18097330f729Sjoerg unsigned numIElts = IVT->getNumElements();
18107330f729Sjoerg
18117330f729Sjoerg if (IType->isExtVectorType())
18127330f729Sjoerg VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
18137330f729Sjoerg else
18147330f729Sjoerg VecType = SemaRef.Context.getVectorType(elementType, numIElts,
18157330f729Sjoerg IVT->getVectorKind());
18167330f729Sjoerg CheckSubElementType(ElementEntity, IList, VecType, Index,
18177330f729Sjoerg StructuredList, StructuredIndex);
18187330f729Sjoerg numEltsInit += numIElts;
18197330f729Sjoerg }
18207330f729Sjoerg }
18217330f729Sjoerg
18227330f729Sjoerg // OpenCL requires all elements to be initialized.
18237330f729Sjoerg if (numEltsInit != maxElements) {
18247330f729Sjoerg if (!VerifyOnly)
18257330f729Sjoerg SemaRef.Diag(IList->getBeginLoc(),
18267330f729Sjoerg diag::err_vector_incorrect_num_initializers)
18277330f729Sjoerg << (numEltsInit < maxElements) << maxElements << numEltsInit;
18287330f729Sjoerg hadError = true;
18297330f729Sjoerg }
18307330f729Sjoerg }
18317330f729Sjoerg
18327330f729Sjoerg /// Check if the type of a class element has an accessible destructor, and marks
18337330f729Sjoerg /// it referenced. Returns true if we shouldn't form a reference to the
18347330f729Sjoerg /// destructor.
18357330f729Sjoerg ///
18367330f729Sjoerg /// Aggregate initialization requires a class element's destructor be
18377330f729Sjoerg /// accessible per 11.6.1 [dcl.init.aggr]:
18387330f729Sjoerg ///
18397330f729Sjoerg /// The destructor for each element of class type is potentially invoked
18407330f729Sjoerg /// (15.4 [class.dtor]) from the context where the aggregate initialization
18417330f729Sjoerg /// occurs.
checkDestructorReference(QualType ElementType,SourceLocation Loc,Sema & SemaRef)18427330f729Sjoerg static bool checkDestructorReference(QualType ElementType, SourceLocation Loc,
18437330f729Sjoerg Sema &SemaRef) {
18447330f729Sjoerg auto *CXXRD = ElementType->getAsCXXRecordDecl();
18457330f729Sjoerg if (!CXXRD)
18467330f729Sjoerg return false;
18477330f729Sjoerg
18487330f729Sjoerg CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(CXXRD);
18497330f729Sjoerg SemaRef.CheckDestructorAccess(Loc, Destructor,
18507330f729Sjoerg SemaRef.PDiag(diag::err_access_dtor_temp)
18517330f729Sjoerg << ElementType);
18527330f729Sjoerg SemaRef.MarkFunctionReferenced(Loc, Destructor);
18537330f729Sjoerg return SemaRef.DiagnoseUseOfDecl(Destructor, Loc);
18547330f729Sjoerg }
18557330f729Sjoerg
CheckArrayType(const InitializedEntity & Entity,InitListExpr * IList,QualType & DeclType,llvm::APSInt elementIndex,bool SubobjectIsDesignatorContext,unsigned & Index,InitListExpr * StructuredList,unsigned & StructuredIndex)18567330f729Sjoerg void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
18577330f729Sjoerg InitListExpr *IList, QualType &DeclType,
18587330f729Sjoerg llvm::APSInt elementIndex,
18597330f729Sjoerg bool SubobjectIsDesignatorContext,
18607330f729Sjoerg unsigned &Index,
18617330f729Sjoerg InitListExpr *StructuredList,
18627330f729Sjoerg unsigned &StructuredIndex) {
18637330f729Sjoerg const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
18647330f729Sjoerg
18657330f729Sjoerg if (!VerifyOnly) {
18667330f729Sjoerg if (checkDestructorReference(arrayType->getElementType(),
18677330f729Sjoerg IList->getEndLoc(), SemaRef)) {
18687330f729Sjoerg hadError = true;
18697330f729Sjoerg return;
18707330f729Sjoerg }
18717330f729Sjoerg }
18727330f729Sjoerg
18737330f729Sjoerg // Check for the special-case of initializing an array with a string.
18747330f729Sjoerg if (Index < IList->getNumInits()) {
18757330f729Sjoerg if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
18767330f729Sjoerg SIF_None) {
18777330f729Sjoerg // We place the string literal directly into the resulting
18787330f729Sjoerg // initializer list. This is the only place where the structure
18797330f729Sjoerg // of the structured initializer list doesn't match exactly,
18807330f729Sjoerg // because doing so would involve allocating one character
18817330f729Sjoerg // constant for each string.
18827330f729Sjoerg // FIXME: Should we do these checks in verify-only mode too?
18837330f729Sjoerg if (!VerifyOnly)
18847330f729Sjoerg CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
18857330f729Sjoerg if (StructuredList) {
18867330f729Sjoerg UpdateStructuredListElement(StructuredList, StructuredIndex,
18877330f729Sjoerg IList->getInit(Index));
18887330f729Sjoerg StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
18897330f729Sjoerg }
18907330f729Sjoerg ++Index;
18917330f729Sjoerg return;
18927330f729Sjoerg }
18937330f729Sjoerg }
18947330f729Sjoerg if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
18957330f729Sjoerg // Check for VLAs; in standard C it would be possible to check this
18967330f729Sjoerg // earlier, but I don't know where clang accepts VLAs (gcc accepts
18977330f729Sjoerg // them in all sorts of strange places).
18987330f729Sjoerg if (!VerifyOnly)
18997330f729Sjoerg SemaRef.Diag(VAT->getSizeExpr()->getBeginLoc(),
19007330f729Sjoerg diag::err_variable_object_no_init)
19017330f729Sjoerg << VAT->getSizeExpr()->getSourceRange();
19027330f729Sjoerg hadError = true;
19037330f729Sjoerg ++Index;
19047330f729Sjoerg ++StructuredIndex;
19057330f729Sjoerg return;
19067330f729Sjoerg }
19077330f729Sjoerg
19087330f729Sjoerg // We might know the maximum number of elements in advance.
19097330f729Sjoerg llvm::APSInt maxElements(elementIndex.getBitWidth(),
19107330f729Sjoerg elementIndex.isUnsigned());
19117330f729Sjoerg bool maxElementsKnown = false;
19127330f729Sjoerg if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
19137330f729Sjoerg maxElements = CAT->getSize();
19147330f729Sjoerg elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
19157330f729Sjoerg elementIndex.setIsUnsigned(maxElements.isUnsigned());
19167330f729Sjoerg maxElementsKnown = true;
19177330f729Sjoerg }
19187330f729Sjoerg
19197330f729Sjoerg QualType elementType = arrayType->getElementType();
19207330f729Sjoerg while (Index < IList->getNumInits()) {
19217330f729Sjoerg Expr *Init = IList->getInit(Index);
19227330f729Sjoerg if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
19237330f729Sjoerg // If we're not the subobject that matches up with the '{' for
19247330f729Sjoerg // the designator, we shouldn't be handling the
19257330f729Sjoerg // designator. Return immediately.
19267330f729Sjoerg if (!SubobjectIsDesignatorContext)
19277330f729Sjoerg return;
19287330f729Sjoerg
19297330f729Sjoerg // Handle this designated initializer. elementIndex will be
19307330f729Sjoerg // updated to be the next array element we'll initialize.
19317330f729Sjoerg if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
19327330f729Sjoerg DeclType, nullptr, &elementIndex, Index,
19337330f729Sjoerg StructuredList, StructuredIndex, true,
19347330f729Sjoerg false)) {
19357330f729Sjoerg hadError = true;
19367330f729Sjoerg continue;
19377330f729Sjoerg }
19387330f729Sjoerg
19397330f729Sjoerg if (elementIndex.getBitWidth() > maxElements.getBitWidth())
19407330f729Sjoerg maxElements = maxElements.extend(elementIndex.getBitWidth());
19417330f729Sjoerg else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
19427330f729Sjoerg elementIndex = elementIndex.extend(maxElements.getBitWidth());
19437330f729Sjoerg elementIndex.setIsUnsigned(maxElements.isUnsigned());
19447330f729Sjoerg
19457330f729Sjoerg // If the array is of incomplete type, keep track of the number of
19467330f729Sjoerg // elements in the initializer.
19477330f729Sjoerg if (!maxElementsKnown && elementIndex > maxElements)
19487330f729Sjoerg maxElements = elementIndex;
19497330f729Sjoerg
19507330f729Sjoerg continue;
19517330f729Sjoerg }
19527330f729Sjoerg
19537330f729Sjoerg // If we know the maximum number of elements, and we've already
19547330f729Sjoerg // hit it, stop consuming elements in the initializer list.
19557330f729Sjoerg if (maxElementsKnown && elementIndex == maxElements)
19567330f729Sjoerg break;
19577330f729Sjoerg
19587330f729Sjoerg InitializedEntity ElementEntity =
19597330f729Sjoerg InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
19607330f729Sjoerg Entity);
19617330f729Sjoerg // Check this element.
19627330f729Sjoerg CheckSubElementType(ElementEntity, IList, elementType, Index,
19637330f729Sjoerg StructuredList, StructuredIndex);
19647330f729Sjoerg ++elementIndex;
19657330f729Sjoerg
19667330f729Sjoerg // If the array is of incomplete type, keep track of the number of
19677330f729Sjoerg // elements in the initializer.
19687330f729Sjoerg if (!maxElementsKnown && elementIndex > maxElements)
19697330f729Sjoerg maxElements = elementIndex;
19707330f729Sjoerg }
19717330f729Sjoerg if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
19727330f729Sjoerg // If this is an incomplete array type, the actual type needs to
19737330f729Sjoerg // be calculated here.
19747330f729Sjoerg llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
19757330f729Sjoerg if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {
19767330f729Sjoerg // Sizing an array implicitly to zero is not allowed by ISO C,
19777330f729Sjoerg // but is supported by GNU.
19787330f729Sjoerg SemaRef.Diag(IList->getBeginLoc(), diag::ext_typecheck_zero_array_size);
19797330f729Sjoerg }
19807330f729Sjoerg
19817330f729Sjoerg DeclType = SemaRef.Context.getConstantArrayType(
19827330f729Sjoerg elementType, maxElements, nullptr, ArrayType::Normal, 0);
19837330f729Sjoerg }
19847330f729Sjoerg if (!hadError) {
19857330f729Sjoerg // If there are any members of the array that get value-initialized, check
19867330f729Sjoerg // that is possible. That happens if we know the bound and don't have
19877330f729Sjoerg // enough elements, or if we're performing an array new with an unknown
19887330f729Sjoerg // bound.
19897330f729Sjoerg if ((maxElementsKnown && elementIndex < maxElements) ||
19907330f729Sjoerg Entity.isVariableLengthArrayNew())
19917330f729Sjoerg CheckEmptyInitializable(
19927330f729Sjoerg InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
19937330f729Sjoerg IList->getEndLoc());
19947330f729Sjoerg }
19957330f729Sjoerg }
19967330f729Sjoerg
CheckFlexibleArrayInit(const InitializedEntity & Entity,Expr * InitExpr,FieldDecl * Field,bool TopLevelObject)19977330f729Sjoerg bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
19987330f729Sjoerg Expr *InitExpr,
19997330f729Sjoerg FieldDecl *Field,
20007330f729Sjoerg bool TopLevelObject) {
20017330f729Sjoerg // Handle GNU flexible array initializers.
20027330f729Sjoerg unsigned FlexArrayDiag;
20037330f729Sjoerg if (isa<InitListExpr>(InitExpr) &&
20047330f729Sjoerg cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
20057330f729Sjoerg // Empty flexible array init always allowed as an extension
20067330f729Sjoerg FlexArrayDiag = diag::ext_flexible_array_init;
20077330f729Sjoerg } else if (SemaRef.getLangOpts().CPlusPlus) {
20087330f729Sjoerg // Disallow flexible array init in C++; it is not required for gcc
20097330f729Sjoerg // compatibility, and it needs work to IRGen correctly in general.
20107330f729Sjoerg FlexArrayDiag = diag::err_flexible_array_init;
20117330f729Sjoerg } else if (!TopLevelObject) {
20127330f729Sjoerg // Disallow flexible array init on non-top-level object
20137330f729Sjoerg FlexArrayDiag = diag::err_flexible_array_init;
20147330f729Sjoerg } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
20157330f729Sjoerg // Disallow flexible array init on anything which is not a variable.
20167330f729Sjoerg FlexArrayDiag = diag::err_flexible_array_init;
20177330f729Sjoerg } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
20187330f729Sjoerg // Disallow flexible array init on local variables.
20197330f729Sjoerg FlexArrayDiag = diag::err_flexible_array_init;
20207330f729Sjoerg } else {
20217330f729Sjoerg // Allow other cases.
20227330f729Sjoerg FlexArrayDiag = diag::ext_flexible_array_init;
20237330f729Sjoerg }
20247330f729Sjoerg
20257330f729Sjoerg if (!VerifyOnly) {
20267330f729Sjoerg SemaRef.Diag(InitExpr->getBeginLoc(), FlexArrayDiag)
20277330f729Sjoerg << InitExpr->getBeginLoc();
20287330f729Sjoerg SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
20297330f729Sjoerg << Field;
20307330f729Sjoerg }
20317330f729Sjoerg
20327330f729Sjoerg return FlexArrayDiag != diag::ext_flexible_array_init;
20337330f729Sjoerg }
20347330f729Sjoerg
CheckStructUnionTypes(const InitializedEntity & Entity,InitListExpr * IList,QualType DeclType,CXXRecordDecl::base_class_range Bases,RecordDecl::field_iterator Field,bool SubobjectIsDesignatorContext,unsigned & Index,InitListExpr * StructuredList,unsigned & StructuredIndex,bool TopLevelObject)20357330f729Sjoerg void InitListChecker::CheckStructUnionTypes(
20367330f729Sjoerg const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
20377330f729Sjoerg CXXRecordDecl::base_class_range Bases, RecordDecl::field_iterator Field,
20387330f729Sjoerg bool SubobjectIsDesignatorContext, unsigned &Index,
20397330f729Sjoerg InitListExpr *StructuredList, unsigned &StructuredIndex,
20407330f729Sjoerg bool TopLevelObject) {
20417330f729Sjoerg RecordDecl *structDecl = DeclType->castAs<RecordType>()->getDecl();
20427330f729Sjoerg
20437330f729Sjoerg // If the record is invalid, some of it's members are invalid. To avoid
20447330f729Sjoerg // confusion, we forgo checking the intializer for the entire record.
20457330f729Sjoerg if (structDecl->isInvalidDecl()) {
20467330f729Sjoerg // Assume it was supposed to consume a single initializer.
20477330f729Sjoerg ++Index;
20487330f729Sjoerg hadError = true;
20497330f729Sjoerg return;
20507330f729Sjoerg }
20517330f729Sjoerg
20527330f729Sjoerg if (DeclType->isUnionType() && IList->getNumInits() == 0) {
20537330f729Sjoerg RecordDecl *RD = DeclType->castAs<RecordType>()->getDecl();
20547330f729Sjoerg
20557330f729Sjoerg if (!VerifyOnly)
20567330f729Sjoerg for (FieldDecl *FD : RD->fields()) {
20577330f729Sjoerg QualType ET = SemaRef.Context.getBaseElementType(FD->getType());
20587330f729Sjoerg if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
20597330f729Sjoerg hadError = true;
20607330f729Sjoerg return;
20617330f729Sjoerg }
20627330f729Sjoerg }
20637330f729Sjoerg
20647330f729Sjoerg // If there's a default initializer, use it.
20657330f729Sjoerg if (isa<CXXRecordDecl>(RD) &&
20667330f729Sjoerg cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
20677330f729Sjoerg if (!StructuredList)
20687330f729Sjoerg return;
20697330f729Sjoerg for (RecordDecl::field_iterator FieldEnd = RD->field_end();
20707330f729Sjoerg Field != FieldEnd; ++Field) {
20717330f729Sjoerg if (Field->hasInClassInitializer()) {
20727330f729Sjoerg StructuredList->setInitializedFieldInUnion(*Field);
20737330f729Sjoerg // FIXME: Actually build a CXXDefaultInitExpr?
20747330f729Sjoerg return;
20757330f729Sjoerg }
20767330f729Sjoerg }
20777330f729Sjoerg }
20787330f729Sjoerg
20797330f729Sjoerg // Value-initialize the first member of the union that isn't an unnamed
20807330f729Sjoerg // bitfield.
20817330f729Sjoerg for (RecordDecl::field_iterator FieldEnd = RD->field_end();
20827330f729Sjoerg Field != FieldEnd; ++Field) {
20837330f729Sjoerg if (!Field->isUnnamedBitfield()) {
20847330f729Sjoerg CheckEmptyInitializable(
20857330f729Sjoerg InitializedEntity::InitializeMember(*Field, &Entity),
20867330f729Sjoerg IList->getEndLoc());
20877330f729Sjoerg if (StructuredList)
20887330f729Sjoerg StructuredList->setInitializedFieldInUnion(*Field);
20897330f729Sjoerg break;
20907330f729Sjoerg }
20917330f729Sjoerg }
20927330f729Sjoerg return;
20937330f729Sjoerg }
20947330f729Sjoerg
20957330f729Sjoerg bool InitializedSomething = false;
20967330f729Sjoerg
20977330f729Sjoerg // If we have any base classes, they are initialized prior to the fields.
20987330f729Sjoerg for (auto &Base : Bases) {
20997330f729Sjoerg Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;
21007330f729Sjoerg
21017330f729Sjoerg // Designated inits always initialize fields, so if we see one, all
21027330f729Sjoerg // remaining base classes have no explicit initializer.
21037330f729Sjoerg if (Init && isa<DesignatedInitExpr>(Init))
21047330f729Sjoerg Init = nullptr;
21057330f729Sjoerg
21067330f729Sjoerg SourceLocation InitLoc = Init ? Init->getBeginLoc() : IList->getEndLoc();
21077330f729Sjoerg InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
21087330f729Sjoerg SemaRef.Context, &Base, false, &Entity);
21097330f729Sjoerg if (Init) {
21107330f729Sjoerg CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
21117330f729Sjoerg StructuredList, StructuredIndex);
21127330f729Sjoerg InitializedSomething = true;
21137330f729Sjoerg } else {
21147330f729Sjoerg CheckEmptyInitializable(BaseEntity, InitLoc);
21157330f729Sjoerg }
21167330f729Sjoerg
21177330f729Sjoerg if (!VerifyOnly)
21187330f729Sjoerg if (checkDestructorReference(Base.getType(), InitLoc, SemaRef)) {
21197330f729Sjoerg hadError = true;
21207330f729Sjoerg return;
21217330f729Sjoerg }
21227330f729Sjoerg }
21237330f729Sjoerg
21247330f729Sjoerg // If structDecl is a forward declaration, this loop won't do
21257330f729Sjoerg // anything except look at designated initializers; That's okay,
21267330f729Sjoerg // because an error should get printed out elsewhere. It might be
21277330f729Sjoerg // worthwhile to skip over the rest of the initializer, though.
21287330f729Sjoerg RecordDecl *RD = DeclType->castAs<RecordType>()->getDecl();
21297330f729Sjoerg RecordDecl::field_iterator FieldEnd = RD->field_end();
21307330f729Sjoerg bool CheckForMissingFields =
21317330f729Sjoerg !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts());
21327330f729Sjoerg bool HasDesignatedInit = false;
21337330f729Sjoerg
21347330f729Sjoerg while (Index < IList->getNumInits()) {
21357330f729Sjoerg Expr *Init = IList->getInit(Index);
21367330f729Sjoerg SourceLocation InitLoc = Init->getBeginLoc();
21377330f729Sjoerg
21387330f729Sjoerg if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
21397330f729Sjoerg // If we're not the subobject that matches up with the '{' for
21407330f729Sjoerg // the designator, we shouldn't be handling the
21417330f729Sjoerg // designator. Return immediately.
21427330f729Sjoerg if (!SubobjectIsDesignatorContext)
21437330f729Sjoerg return;
21447330f729Sjoerg
21457330f729Sjoerg HasDesignatedInit = true;
21467330f729Sjoerg
21477330f729Sjoerg // Handle this designated initializer. Field will be updated to
21487330f729Sjoerg // the next field that we'll be initializing.
21497330f729Sjoerg if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
21507330f729Sjoerg DeclType, &Field, nullptr, Index,
21517330f729Sjoerg StructuredList, StructuredIndex,
21527330f729Sjoerg true, TopLevelObject))
21537330f729Sjoerg hadError = true;
21547330f729Sjoerg else if (!VerifyOnly) {
21557330f729Sjoerg // Find the field named by the designated initializer.
21567330f729Sjoerg RecordDecl::field_iterator F = RD->field_begin();
21577330f729Sjoerg while (std::next(F) != Field)
21587330f729Sjoerg ++F;
21597330f729Sjoerg QualType ET = SemaRef.Context.getBaseElementType(F->getType());
21607330f729Sjoerg if (checkDestructorReference(ET, InitLoc, SemaRef)) {
21617330f729Sjoerg hadError = true;
21627330f729Sjoerg return;
21637330f729Sjoerg }
21647330f729Sjoerg }
21657330f729Sjoerg
21667330f729Sjoerg InitializedSomething = true;
21677330f729Sjoerg
21687330f729Sjoerg // Disable check for missing fields when designators are used.
21697330f729Sjoerg // This matches gcc behaviour.
21707330f729Sjoerg CheckForMissingFields = false;
21717330f729Sjoerg continue;
21727330f729Sjoerg }
21737330f729Sjoerg
21747330f729Sjoerg if (Field == FieldEnd) {
21757330f729Sjoerg // We've run out of fields. We're done.
21767330f729Sjoerg break;
21777330f729Sjoerg }
21787330f729Sjoerg
21797330f729Sjoerg // We've already initialized a member of a union. We're done.
21807330f729Sjoerg if (InitializedSomething && DeclType->isUnionType())
21817330f729Sjoerg break;
21827330f729Sjoerg
21837330f729Sjoerg // If we've hit the flexible array member at the end, we're done.
21847330f729Sjoerg if (Field->getType()->isIncompleteArrayType())
21857330f729Sjoerg break;
21867330f729Sjoerg
21877330f729Sjoerg if (Field->isUnnamedBitfield()) {
21887330f729Sjoerg // Don't initialize unnamed bitfields, e.g. "int : 20;"
21897330f729Sjoerg ++Field;
21907330f729Sjoerg continue;
21917330f729Sjoerg }
21927330f729Sjoerg
21937330f729Sjoerg // Make sure we can use this declaration.
21947330f729Sjoerg bool InvalidUse;
21957330f729Sjoerg if (VerifyOnly)
21967330f729Sjoerg InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
21977330f729Sjoerg else
21987330f729Sjoerg InvalidUse = SemaRef.DiagnoseUseOfDecl(
21997330f729Sjoerg *Field, IList->getInit(Index)->getBeginLoc());
22007330f729Sjoerg if (InvalidUse) {
22017330f729Sjoerg ++Index;
22027330f729Sjoerg ++Field;
22037330f729Sjoerg hadError = true;
22047330f729Sjoerg continue;
22057330f729Sjoerg }
22067330f729Sjoerg
22077330f729Sjoerg if (!VerifyOnly) {
22087330f729Sjoerg QualType ET = SemaRef.Context.getBaseElementType(Field->getType());
22097330f729Sjoerg if (checkDestructorReference(ET, InitLoc, SemaRef)) {
22107330f729Sjoerg hadError = true;
22117330f729Sjoerg return;
22127330f729Sjoerg }
22137330f729Sjoerg }
22147330f729Sjoerg
22157330f729Sjoerg InitializedEntity MemberEntity =
22167330f729Sjoerg InitializedEntity::InitializeMember(*Field, &Entity);
22177330f729Sjoerg CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
22187330f729Sjoerg StructuredList, StructuredIndex);
22197330f729Sjoerg InitializedSomething = true;
22207330f729Sjoerg
22217330f729Sjoerg if (DeclType->isUnionType() && StructuredList) {
22227330f729Sjoerg // Initialize the first field within the union.
22237330f729Sjoerg StructuredList->setInitializedFieldInUnion(*Field);
22247330f729Sjoerg }
22257330f729Sjoerg
22267330f729Sjoerg ++Field;
22277330f729Sjoerg }
22287330f729Sjoerg
22297330f729Sjoerg // Emit warnings for missing struct field initializers.
22307330f729Sjoerg if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
22317330f729Sjoerg Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
22327330f729Sjoerg !DeclType->isUnionType()) {
22337330f729Sjoerg // It is possible we have one or more unnamed bitfields remaining.
22347330f729Sjoerg // Find first (if any) named field and emit warning.
22357330f729Sjoerg for (RecordDecl::field_iterator it = Field, end = RD->field_end();
22367330f729Sjoerg it != end; ++it) {
22377330f729Sjoerg if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
22387330f729Sjoerg SemaRef.Diag(IList->getSourceRange().getEnd(),
22397330f729Sjoerg diag::warn_missing_field_initializers) << *it;
22407330f729Sjoerg break;
22417330f729Sjoerg }
22427330f729Sjoerg }
22437330f729Sjoerg }
22447330f729Sjoerg
22457330f729Sjoerg // Check that any remaining fields can be value-initialized if we're not
22467330f729Sjoerg // building a structured list. (If we are, we'll check this later.)
22477330f729Sjoerg if (!StructuredList && Field != FieldEnd && !DeclType->isUnionType() &&
22487330f729Sjoerg !Field->getType()->isIncompleteArrayType()) {
22497330f729Sjoerg for (; Field != FieldEnd && !hadError; ++Field) {
22507330f729Sjoerg if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
22517330f729Sjoerg CheckEmptyInitializable(
22527330f729Sjoerg InitializedEntity::InitializeMember(*Field, &Entity),
22537330f729Sjoerg IList->getEndLoc());
22547330f729Sjoerg }
22557330f729Sjoerg }
22567330f729Sjoerg
22577330f729Sjoerg // Check that the types of the remaining fields have accessible destructors.
22587330f729Sjoerg if (!VerifyOnly) {
22597330f729Sjoerg // If the initializer expression has a designated initializer, check the
22607330f729Sjoerg // elements for which a designated initializer is not provided too.
22617330f729Sjoerg RecordDecl::field_iterator I = HasDesignatedInit ? RD->field_begin()
22627330f729Sjoerg : Field;
22637330f729Sjoerg for (RecordDecl::field_iterator E = RD->field_end(); I != E; ++I) {
22647330f729Sjoerg QualType ET = SemaRef.Context.getBaseElementType(I->getType());
22657330f729Sjoerg if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
22667330f729Sjoerg hadError = true;
22677330f729Sjoerg return;
22687330f729Sjoerg }
22697330f729Sjoerg }
22707330f729Sjoerg }
22717330f729Sjoerg
22727330f729Sjoerg if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
22737330f729Sjoerg Index >= IList->getNumInits())
22747330f729Sjoerg return;
22757330f729Sjoerg
22767330f729Sjoerg if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
22777330f729Sjoerg TopLevelObject)) {
22787330f729Sjoerg hadError = true;
22797330f729Sjoerg ++Index;
22807330f729Sjoerg return;
22817330f729Sjoerg }
22827330f729Sjoerg
22837330f729Sjoerg InitializedEntity MemberEntity =
22847330f729Sjoerg InitializedEntity::InitializeMember(*Field, &Entity);
22857330f729Sjoerg
22867330f729Sjoerg if (isa<InitListExpr>(IList->getInit(Index)))
22877330f729Sjoerg CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
22887330f729Sjoerg StructuredList, StructuredIndex);
22897330f729Sjoerg else
22907330f729Sjoerg CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
22917330f729Sjoerg StructuredList, StructuredIndex);
22927330f729Sjoerg }
22937330f729Sjoerg
22947330f729Sjoerg /// Expand a field designator that refers to a member of an
22957330f729Sjoerg /// anonymous struct or union into a series of field designators that
22967330f729Sjoerg /// refers to the field within the appropriate subobject.
22977330f729Sjoerg ///
ExpandAnonymousFieldDesignator(Sema & SemaRef,DesignatedInitExpr * DIE,unsigned DesigIdx,IndirectFieldDecl * IndirectField)22987330f729Sjoerg static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
22997330f729Sjoerg DesignatedInitExpr *DIE,
23007330f729Sjoerg unsigned DesigIdx,
23017330f729Sjoerg IndirectFieldDecl *IndirectField) {
23027330f729Sjoerg typedef DesignatedInitExpr::Designator Designator;
23037330f729Sjoerg
23047330f729Sjoerg // Build the replacement designators.
23057330f729Sjoerg SmallVector<Designator, 4> Replacements;
23067330f729Sjoerg for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
23077330f729Sjoerg PE = IndirectField->chain_end(); PI != PE; ++PI) {
23087330f729Sjoerg if (PI + 1 == PE)
23097330f729Sjoerg Replacements.push_back(Designator((IdentifierInfo *)nullptr,
23107330f729Sjoerg DIE->getDesignator(DesigIdx)->getDotLoc(),
23117330f729Sjoerg DIE->getDesignator(DesigIdx)->getFieldLoc()));
23127330f729Sjoerg else
23137330f729Sjoerg Replacements.push_back(Designator((IdentifierInfo *)nullptr,
23147330f729Sjoerg SourceLocation(), SourceLocation()));
23157330f729Sjoerg assert(isa<FieldDecl>(*PI));
23167330f729Sjoerg Replacements.back().setField(cast<FieldDecl>(*PI));
23177330f729Sjoerg }
23187330f729Sjoerg
23197330f729Sjoerg // Expand the current designator into the set of replacement
23207330f729Sjoerg // designators, so we have a full subobject path down to where the
23217330f729Sjoerg // member of the anonymous struct/union is actually stored.
23227330f729Sjoerg DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
23237330f729Sjoerg &Replacements[0] + Replacements.size());
23247330f729Sjoerg }
23257330f729Sjoerg
CloneDesignatedInitExpr(Sema & SemaRef,DesignatedInitExpr * DIE)23267330f729Sjoerg static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
23277330f729Sjoerg DesignatedInitExpr *DIE) {
23287330f729Sjoerg unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
23297330f729Sjoerg SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
23307330f729Sjoerg for (unsigned I = 0; I < NumIndexExprs; ++I)
23317330f729Sjoerg IndexExprs[I] = DIE->getSubExpr(I + 1);
23327330f729Sjoerg return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
23337330f729Sjoerg IndexExprs,
23347330f729Sjoerg DIE->getEqualOrColonLoc(),
23357330f729Sjoerg DIE->usesGNUSyntax(), DIE->getInit());
23367330f729Sjoerg }
23377330f729Sjoerg
23387330f729Sjoerg namespace {
23397330f729Sjoerg
23407330f729Sjoerg // Callback to only accept typo corrections that are for field members of
23417330f729Sjoerg // the given struct or union.
23427330f729Sjoerg class FieldInitializerValidatorCCC final : public CorrectionCandidateCallback {
23437330f729Sjoerg public:
FieldInitializerValidatorCCC(RecordDecl * RD)23447330f729Sjoerg explicit FieldInitializerValidatorCCC(RecordDecl *RD)
23457330f729Sjoerg : Record(RD) {}
23467330f729Sjoerg
ValidateCandidate(const TypoCorrection & candidate)23477330f729Sjoerg bool ValidateCandidate(const TypoCorrection &candidate) override {
23487330f729Sjoerg FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
23497330f729Sjoerg return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
23507330f729Sjoerg }
23517330f729Sjoerg
clone()23527330f729Sjoerg std::unique_ptr<CorrectionCandidateCallback> clone() override {
23537330f729Sjoerg return std::make_unique<FieldInitializerValidatorCCC>(*this);
23547330f729Sjoerg }
23557330f729Sjoerg
23567330f729Sjoerg private:
23577330f729Sjoerg RecordDecl *Record;
23587330f729Sjoerg };
23597330f729Sjoerg
23607330f729Sjoerg } // end anonymous namespace
23617330f729Sjoerg
23627330f729Sjoerg /// Check the well-formedness of a C99 designated initializer.
23637330f729Sjoerg ///
23647330f729Sjoerg /// Determines whether the designated initializer @p DIE, which
23657330f729Sjoerg /// resides at the given @p Index within the initializer list @p
23667330f729Sjoerg /// IList, is well-formed for a current object of type @p DeclType
23677330f729Sjoerg /// (C99 6.7.8). The actual subobject that this designator refers to
23687330f729Sjoerg /// within the current subobject is returned in either
23697330f729Sjoerg /// @p NextField or @p NextElementIndex (whichever is appropriate).
23707330f729Sjoerg ///
23717330f729Sjoerg /// @param IList The initializer list in which this designated
23727330f729Sjoerg /// initializer occurs.
23737330f729Sjoerg ///
23747330f729Sjoerg /// @param DIE The designated initializer expression.
23757330f729Sjoerg ///
23767330f729Sjoerg /// @param DesigIdx The index of the current designator.
23777330f729Sjoerg ///
23787330f729Sjoerg /// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
23797330f729Sjoerg /// into which the designation in @p DIE should refer.
23807330f729Sjoerg ///
23817330f729Sjoerg /// @param NextField If non-NULL and the first designator in @p DIE is
23827330f729Sjoerg /// a field, this will be set to the field declaration corresponding
23837330f729Sjoerg /// to the field named by the designator. On input, this is expected to be
23847330f729Sjoerg /// the next field that would be initialized in the absence of designation,
23857330f729Sjoerg /// if the complete object being initialized is a struct.
23867330f729Sjoerg ///
23877330f729Sjoerg /// @param NextElementIndex If non-NULL and the first designator in @p
23887330f729Sjoerg /// DIE is an array designator or GNU array-range designator, this
23897330f729Sjoerg /// will be set to the last index initialized by this designator.
23907330f729Sjoerg ///
23917330f729Sjoerg /// @param Index Index into @p IList where the designated initializer
23927330f729Sjoerg /// @p DIE occurs.
23937330f729Sjoerg ///
23947330f729Sjoerg /// @param StructuredList The initializer list expression that
23957330f729Sjoerg /// describes all of the subobject initializers in the order they'll
23967330f729Sjoerg /// actually be initialized.
23977330f729Sjoerg ///
23987330f729Sjoerg /// @returns true if there was an error, false otherwise.
23997330f729Sjoerg bool
CheckDesignatedInitializer(const InitializedEntity & Entity,InitListExpr * IList,DesignatedInitExpr * DIE,unsigned DesigIdx,QualType & CurrentObjectType,RecordDecl::field_iterator * NextField,llvm::APSInt * NextElementIndex,unsigned & Index,InitListExpr * StructuredList,unsigned & StructuredIndex,bool FinishSubobjectInit,bool TopLevelObject)24007330f729Sjoerg InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
24017330f729Sjoerg InitListExpr *IList,
24027330f729Sjoerg DesignatedInitExpr *DIE,
24037330f729Sjoerg unsigned DesigIdx,
24047330f729Sjoerg QualType &CurrentObjectType,
24057330f729Sjoerg RecordDecl::field_iterator *NextField,
24067330f729Sjoerg llvm::APSInt *NextElementIndex,
24077330f729Sjoerg unsigned &Index,
24087330f729Sjoerg InitListExpr *StructuredList,
24097330f729Sjoerg unsigned &StructuredIndex,
24107330f729Sjoerg bool FinishSubobjectInit,
24117330f729Sjoerg bool TopLevelObject) {
24127330f729Sjoerg if (DesigIdx == DIE->size()) {
24137330f729Sjoerg // C++20 designated initialization can result in direct-list-initialization
24147330f729Sjoerg // of the designated subobject. This is the only way that we can end up
24157330f729Sjoerg // performing direct initialization as part of aggregate initialization, so
24167330f729Sjoerg // it needs special handling.
24177330f729Sjoerg if (DIE->isDirectInit()) {
24187330f729Sjoerg Expr *Init = DIE->getInit();
24197330f729Sjoerg assert(isa<InitListExpr>(Init) &&
24207330f729Sjoerg "designator result in direct non-list initialization?");
24217330f729Sjoerg InitializationKind Kind = InitializationKind::CreateDirectList(
24227330f729Sjoerg DIE->getBeginLoc(), Init->getBeginLoc(), Init->getEndLoc());
24237330f729Sjoerg InitializationSequence Seq(SemaRef, Entity, Kind, Init,
24247330f729Sjoerg /*TopLevelOfInitList*/ true);
24257330f729Sjoerg if (StructuredList) {
24267330f729Sjoerg ExprResult Result = VerifyOnly
24277330f729Sjoerg ? getDummyInit()
24287330f729Sjoerg : Seq.Perform(SemaRef, Entity, Kind, Init);
24297330f729Sjoerg UpdateStructuredListElement(StructuredList, StructuredIndex,
24307330f729Sjoerg Result.get());
24317330f729Sjoerg }
24327330f729Sjoerg ++Index;
24337330f729Sjoerg return !Seq;
24347330f729Sjoerg }
24357330f729Sjoerg
24367330f729Sjoerg // Check the actual initialization for the designated object type.
24377330f729Sjoerg bool prevHadError = hadError;
24387330f729Sjoerg
24397330f729Sjoerg // Temporarily remove the designator expression from the
24407330f729Sjoerg // initializer list that the child calls see, so that we don't try
24417330f729Sjoerg // to re-process the designator.
24427330f729Sjoerg unsigned OldIndex = Index;
24437330f729Sjoerg IList->setInit(OldIndex, DIE->getInit());
24447330f729Sjoerg
2445*e038c9c4Sjoerg CheckSubElementType(Entity, IList, CurrentObjectType, Index, StructuredList,
2446*e038c9c4Sjoerg StructuredIndex, /*DirectlyDesignated=*/true);
24477330f729Sjoerg
24487330f729Sjoerg // Restore the designated initializer expression in the syntactic
24497330f729Sjoerg // form of the initializer list.
24507330f729Sjoerg if (IList->getInit(OldIndex) != DIE->getInit())
24517330f729Sjoerg DIE->setInit(IList->getInit(OldIndex));
24527330f729Sjoerg IList->setInit(OldIndex, DIE);
24537330f729Sjoerg
24547330f729Sjoerg return hadError && !prevHadError;
24557330f729Sjoerg }
24567330f729Sjoerg
24577330f729Sjoerg DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
24587330f729Sjoerg bool IsFirstDesignator = (DesigIdx == 0);
24597330f729Sjoerg if (IsFirstDesignator ? FullyStructuredList : StructuredList) {
24607330f729Sjoerg // Determine the structural initializer list that corresponds to the
24617330f729Sjoerg // current subobject.
24627330f729Sjoerg if (IsFirstDesignator)
24637330f729Sjoerg StructuredList = FullyStructuredList;
24647330f729Sjoerg else {
24657330f729Sjoerg Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
24667330f729Sjoerg StructuredList->getInit(StructuredIndex) : nullptr;
24677330f729Sjoerg if (!ExistingInit && StructuredList->hasArrayFiller())
24687330f729Sjoerg ExistingInit = StructuredList->getArrayFiller();
24697330f729Sjoerg
24707330f729Sjoerg if (!ExistingInit)
24717330f729Sjoerg StructuredList = getStructuredSubobjectInit(
24727330f729Sjoerg IList, Index, CurrentObjectType, StructuredList, StructuredIndex,
24737330f729Sjoerg SourceRange(D->getBeginLoc(), DIE->getEndLoc()));
24747330f729Sjoerg else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
24757330f729Sjoerg StructuredList = Result;
24767330f729Sjoerg else {
24777330f729Sjoerg // We are creating an initializer list that initializes the
24787330f729Sjoerg // subobjects of the current object, but there was already an
24797330f729Sjoerg // initialization that completely initialized the current
24807330f729Sjoerg // subobject, e.g., by a compound literal:
24817330f729Sjoerg //
24827330f729Sjoerg // struct X { int a, b; };
24837330f729Sjoerg // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
24847330f729Sjoerg //
24857330f729Sjoerg // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
24867330f729Sjoerg // designated initializer re-initializes only its current object
24877330f729Sjoerg // subobject [0].b.
24887330f729Sjoerg diagnoseInitOverride(ExistingInit,
24897330f729Sjoerg SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
24907330f729Sjoerg /*FullyOverwritten=*/false);
24917330f729Sjoerg
24927330f729Sjoerg if (!VerifyOnly) {
24937330f729Sjoerg if (DesignatedInitUpdateExpr *E =
24947330f729Sjoerg dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
24957330f729Sjoerg StructuredList = E->getUpdater();
24967330f729Sjoerg else {
24977330f729Sjoerg DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context)
24987330f729Sjoerg DesignatedInitUpdateExpr(SemaRef.Context, D->getBeginLoc(),
24997330f729Sjoerg ExistingInit, DIE->getEndLoc());
25007330f729Sjoerg StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
25017330f729Sjoerg StructuredList = DIUE->getUpdater();
25027330f729Sjoerg }
25037330f729Sjoerg } else {
25047330f729Sjoerg // We don't need to track the structured representation of a
25057330f729Sjoerg // designated init update of an already-fully-initialized object in
25067330f729Sjoerg // verify-only mode. The only reason we would need the structure is
25077330f729Sjoerg // to determine where the uninitialized "holes" are, and in this
25087330f729Sjoerg // case, we know there aren't any and we can't introduce any.
25097330f729Sjoerg StructuredList = nullptr;
25107330f729Sjoerg }
25117330f729Sjoerg }
25127330f729Sjoerg }
25137330f729Sjoerg }
25147330f729Sjoerg
25157330f729Sjoerg if (D->isFieldDesignator()) {
25167330f729Sjoerg // C99 6.7.8p7:
25177330f729Sjoerg //
25187330f729Sjoerg // If a designator has the form
25197330f729Sjoerg //
25207330f729Sjoerg // . identifier
25217330f729Sjoerg //
25227330f729Sjoerg // then the current object (defined below) shall have
25237330f729Sjoerg // structure or union type and the identifier shall be the
25247330f729Sjoerg // name of a member of that type.
25257330f729Sjoerg const RecordType *RT = CurrentObjectType->getAs<RecordType>();
25267330f729Sjoerg if (!RT) {
25277330f729Sjoerg SourceLocation Loc = D->getDotLoc();
25287330f729Sjoerg if (Loc.isInvalid())
25297330f729Sjoerg Loc = D->getFieldLoc();
25307330f729Sjoerg if (!VerifyOnly)
25317330f729Sjoerg SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
25327330f729Sjoerg << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
25337330f729Sjoerg ++Index;
25347330f729Sjoerg return true;
25357330f729Sjoerg }
25367330f729Sjoerg
25377330f729Sjoerg FieldDecl *KnownField = D->getField();
25387330f729Sjoerg if (!KnownField) {
25397330f729Sjoerg IdentifierInfo *FieldName = D->getFieldName();
25407330f729Sjoerg DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
25417330f729Sjoerg for (NamedDecl *ND : Lookup) {
25427330f729Sjoerg if (auto *FD = dyn_cast<FieldDecl>(ND)) {
25437330f729Sjoerg KnownField = FD;
25447330f729Sjoerg break;
25457330f729Sjoerg }
25467330f729Sjoerg if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) {
25477330f729Sjoerg // In verify mode, don't modify the original.
25487330f729Sjoerg if (VerifyOnly)
25497330f729Sjoerg DIE = CloneDesignatedInitExpr(SemaRef, DIE);
25507330f729Sjoerg ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
25517330f729Sjoerg D = DIE->getDesignator(DesigIdx);
25527330f729Sjoerg KnownField = cast<FieldDecl>(*IFD->chain_begin());
25537330f729Sjoerg break;
25547330f729Sjoerg }
25557330f729Sjoerg }
25567330f729Sjoerg if (!KnownField) {
25577330f729Sjoerg if (VerifyOnly) {
25587330f729Sjoerg ++Index;
25597330f729Sjoerg return true; // No typo correction when just trying this out.
25607330f729Sjoerg }
25617330f729Sjoerg
25627330f729Sjoerg // Name lookup found something, but it wasn't a field.
25637330f729Sjoerg if (!Lookup.empty()) {
25647330f729Sjoerg SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
25657330f729Sjoerg << FieldName;
25667330f729Sjoerg SemaRef.Diag(Lookup.front()->getLocation(),
25677330f729Sjoerg diag::note_field_designator_found);
25687330f729Sjoerg ++Index;
25697330f729Sjoerg return true;
25707330f729Sjoerg }
25717330f729Sjoerg
25727330f729Sjoerg // Name lookup didn't find anything.
25737330f729Sjoerg // Determine whether this was a typo for another field name.
25747330f729Sjoerg FieldInitializerValidatorCCC CCC(RT->getDecl());
25757330f729Sjoerg if (TypoCorrection Corrected = SemaRef.CorrectTypo(
25767330f729Sjoerg DeclarationNameInfo(FieldName, D->getFieldLoc()),
25777330f729Sjoerg Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr, CCC,
25787330f729Sjoerg Sema::CTK_ErrorRecovery, RT->getDecl())) {
25797330f729Sjoerg SemaRef.diagnoseTypo(
25807330f729Sjoerg Corrected,
25817330f729Sjoerg SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
25827330f729Sjoerg << FieldName << CurrentObjectType);
25837330f729Sjoerg KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
25847330f729Sjoerg hadError = true;
25857330f729Sjoerg } else {
25867330f729Sjoerg // Typo correction didn't find anything.
25877330f729Sjoerg SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
25887330f729Sjoerg << FieldName << CurrentObjectType;
25897330f729Sjoerg ++Index;
25907330f729Sjoerg return true;
25917330f729Sjoerg }
25927330f729Sjoerg }
25937330f729Sjoerg }
25947330f729Sjoerg
25957330f729Sjoerg unsigned NumBases = 0;
25967330f729Sjoerg if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
25977330f729Sjoerg NumBases = CXXRD->getNumBases();
25987330f729Sjoerg
25997330f729Sjoerg unsigned FieldIndex = NumBases;
26007330f729Sjoerg
26017330f729Sjoerg for (auto *FI : RT->getDecl()->fields()) {
26027330f729Sjoerg if (FI->isUnnamedBitfield())
26037330f729Sjoerg continue;
26047330f729Sjoerg if (declaresSameEntity(KnownField, FI)) {
26057330f729Sjoerg KnownField = FI;
26067330f729Sjoerg break;
26077330f729Sjoerg }
26087330f729Sjoerg ++FieldIndex;
26097330f729Sjoerg }
26107330f729Sjoerg
26117330f729Sjoerg RecordDecl::field_iterator Field =
26127330f729Sjoerg RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
26137330f729Sjoerg
26147330f729Sjoerg // All of the fields of a union are located at the same place in
26157330f729Sjoerg // the initializer list.
26167330f729Sjoerg if (RT->getDecl()->isUnion()) {
26177330f729Sjoerg FieldIndex = 0;
26187330f729Sjoerg if (StructuredList) {
26197330f729Sjoerg FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
26207330f729Sjoerg if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {
26217330f729Sjoerg assert(StructuredList->getNumInits() == 1
26227330f729Sjoerg && "A union should never have more than one initializer!");
26237330f729Sjoerg
26247330f729Sjoerg Expr *ExistingInit = StructuredList->getInit(0);
26257330f729Sjoerg if (ExistingInit) {
26267330f729Sjoerg // We're about to throw away an initializer, emit warning.
26277330f729Sjoerg diagnoseInitOverride(
26287330f729Sjoerg ExistingInit, SourceRange(D->getBeginLoc(), DIE->getEndLoc()));
26297330f729Sjoerg }
26307330f729Sjoerg
26317330f729Sjoerg // remove existing initializer
26327330f729Sjoerg StructuredList->resizeInits(SemaRef.Context, 0);
26337330f729Sjoerg StructuredList->setInitializedFieldInUnion(nullptr);
26347330f729Sjoerg }
26357330f729Sjoerg
26367330f729Sjoerg StructuredList->setInitializedFieldInUnion(*Field);
26377330f729Sjoerg }
26387330f729Sjoerg }
26397330f729Sjoerg
26407330f729Sjoerg // Make sure we can use this declaration.
26417330f729Sjoerg bool InvalidUse;
26427330f729Sjoerg if (VerifyOnly)
26437330f729Sjoerg InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
26447330f729Sjoerg else
26457330f729Sjoerg InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
26467330f729Sjoerg if (InvalidUse) {
26477330f729Sjoerg ++Index;
26487330f729Sjoerg return true;
26497330f729Sjoerg }
26507330f729Sjoerg
26517330f729Sjoerg // C++20 [dcl.init.list]p3:
26527330f729Sjoerg // The ordered identifiers in the designators of the designated-
26537330f729Sjoerg // initializer-list shall form a subsequence of the ordered identifiers
26547330f729Sjoerg // in the direct non-static data members of T.
26557330f729Sjoerg //
26567330f729Sjoerg // Note that this is not a condition on forming the aggregate
26577330f729Sjoerg // initialization, only on actually performing initialization,
26587330f729Sjoerg // so it is not checked in VerifyOnly mode.
26597330f729Sjoerg //
26607330f729Sjoerg // FIXME: This is the only reordering diagnostic we produce, and it only
26617330f729Sjoerg // catches cases where we have a top-level field designator that jumps
26627330f729Sjoerg // backwards. This is the only such case that is reachable in an
26637330f729Sjoerg // otherwise-valid C++20 program, so is the only case that's required for
26647330f729Sjoerg // conformance, but for consistency, we should diagnose all the other
26657330f729Sjoerg // cases where a designator takes us backwards too.
26667330f729Sjoerg if (IsFirstDesignator && !VerifyOnly && SemaRef.getLangOpts().CPlusPlus &&
26677330f729Sjoerg NextField &&
26687330f729Sjoerg (*NextField == RT->getDecl()->field_end() ||
26697330f729Sjoerg (*NextField)->getFieldIndex() > Field->getFieldIndex() + 1)) {
26707330f729Sjoerg // Find the field that we just initialized.
26717330f729Sjoerg FieldDecl *PrevField = nullptr;
26727330f729Sjoerg for (auto FI = RT->getDecl()->field_begin();
26737330f729Sjoerg FI != RT->getDecl()->field_end(); ++FI) {
26747330f729Sjoerg if (FI->isUnnamedBitfield())
26757330f729Sjoerg continue;
26767330f729Sjoerg if (*NextField != RT->getDecl()->field_end() &&
26777330f729Sjoerg declaresSameEntity(*FI, **NextField))
26787330f729Sjoerg break;
26797330f729Sjoerg PrevField = *FI;
26807330f729Sjoerg }
26817330f729Sjoerg
26827330f729Sjoerg if (PrevField &&
26837330f729Sjoerg PrevField->getFieldIndex() > KnownField->getFieldIndex()) {
26847330f729Sjoerg SemaRef.Diag(DIE->getBeginLoc(), diag::ext_designated_init_reordered)
26857330f729Sjoerg << KnownField << PrevField << DIE->getSourceRange();
26867330f729Sjoerg
26877330f729Sjoerg unsigned OldIndex = NumBases + PrevField->getFieldIndex();
26887330f729Sjoerg if (StructuredList && OldIndex <= StructuredList->getNumInits()) {
26897330f729Sjoerg if (Expr *PrevInit = StructuredList->getInit(OldIndex)) {
26907330f729Sjoerg SemaRef.Diag(PrevInit->getBeginLoc(),
26917330f729Sjoerg diag::note_previous_field_init)
26927330f729Sjoerg << PrevField << PrevInit->getSourceRange();
26937330f729Sjoerg }
26947330f729Sjoerg }
26957330f729Sjoerg }
26967330f729Sjoerg }
26977330f729Sjoerg
26987330f729Sjoerg
26997330f729Sjoerg // Update the designator with the field declaration.
27007330f729Sjoerg if (!VerifyOnly)
27017330f729Sjoerg D->setField(*Field);
27027330f729Sjoerg
27037330f729Sjoerg // Make sure that our non-designated initializer list has space
27047330f729Sjoerg // for a subobject corresponding to this field.
27057330f729Sjoerg if (StructuredList && FieldIndex >= StructuredList->getNumInits())
27067330f729Sjoerg StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
27077330f729Sjoerg
27087330f729Sjoerg // This designator names a flexible array member.
27097330f729Sjoerg if (Field->getType()->isIncompleteArrayType()) {
27107330f729Sjoerg bool Invalid = false;
27117330f729Sjoerg if ((DesigIdx + 1) != DIE->size()) {
27127330f729Sjoerg // We can't designate an object within the flexible array
27137330f729Sjoerg // member (because GCC doesn't allow it).
27147330f729Sjoerg if (!VerifyOnly) {
27157330f729Sjoerg DesignatedInitExpr::Designator *NextD
27167330f729Sjoerg = DIE->getDesignator(DesigIdx + 1);
27177330f729Sjoerg SemaRef.Diag(NextD->getBeginLoc(),
27187330f729Sjoerg diag::err_designator_into_flexible_array_member)
27197330f729Sjoerg << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc());
27207330f729Sjoerg SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
27217330f729Sjoerg << *Field;
27227330f729Sjoerg }
27237330f729Sjoerg Invalid = true;
27247330f729Sjoerg }
27257330f729Sjoerg
27267330f729Sjoerg if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
27277330f729Sjoerg !isa<StringLiteral>(DIE->getInit())) {
27287330f729Sjoerg // The initializer is not an initializer list.
27297330f729Sjoerg if (!VerifyOnly) {
27307330f729Sjoerg SemaRef.Diag(DIE->getInit()->getBeginLoc(),
27317330f729Sjoerg diag::err_flexible_array_init_needs_braces)
27327330f729Sjoerg << DIE->getInit()->getSourceRange();
27337330f729Sjoerg SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
27347330f729Sjoerg << *Field;
27357330f729Sjoerg }
27367330f729Sjoerg Invalid = true;
27377330f729Sjoerg }
27387330f729Sjoerg
27397330f729Sjoerg // Check GNU flexible array initializer.
27407330f729Sjoerg if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
27417330f729Sjoerg TopLevelObject))
27427330f729Sjoerg Invalid = true;
27437330f729Sjoerg
27447330f729Sjoerg if (Invalid) {
27457330f729Sjoerg ++Index;
27467330f729Sjoerg return true;
27477330f729Sjoerg }
27487330f729Sjoerg
27497330f729Sjoerg // Initialize the array.
27507330f729Sjoerg bool prevHadError = hadError;
27517330f729Sjoerg unsigned newStructuredIndex = FieldIndex;
27527330f729Sjoerg unsigned OldIndex = Index;
27537330f729Sjoerg IList->setInit(Index, DIE->getInit());
27547330f729Sjoerg
27557330f729Sjoerg InitializedEntity MemberEntity =
27567330f729Sjoerg InitializedEntity::InitializeMember(*Field, &Entity);
27577330f729Sjoerg CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
27587330f729Sjoerg StructuredList, newStructuredIndex);
27597330f729Sjoerg
27607330f729Sjoerg IList->setInit(OldIndex, DIE);
27617330f729Sjoerg if (hadError && !prevHadError) {
27627330f729Sjoerg ++Field;
27637330f729Sjoerg ++FieldIndex;
27647330f729Sjoerg if (NextField)
27657330f729Sjoerg *NextField = Field;
27667330f729Sjoerg StructuredIndex = FieldIndex;
27677330f729Sjoerg return true;
27687330f729Sjoerg }
27697330f729Sjoerg } else {
27707330f729Sjoerg // Recurse to check later designated subobjects.
27717330f729Sjoerg QualType FieldType = Field->getType();
27727330f729Sjoerg unsigned newStructuredIndex = FieldIndex;
27737330f729Sjoerg
27747330f729Sjoerg InitializedEntity MemberEntity =
27757330f729Sjoerg InitializedEntity::InitializeMember(*Field, &Entity);
27767330f729Sjoerg if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
27777330f729Sjoerg FieldType, nullptr, nullptr, Index,
27787330f729Sjoerg StructuredList, newStructuredIndex,
27797330f729Sjoerg FinishSubobjectInit, false))
27807330f729Sjoerg return true;
27817330f729Sjoerg }
27827330f729Sjoerg
27837330f729Sjoerg // Find the position of the next field to be initialized in this
27847330f729Sjoerg // subobject.
27857330f729Sjoerg ++Field;
27867330f729Sjoerg ++FieldIndex;
27877330f729Sjoerg
27887330f729Sjoerg // If this the first designator, our caller will continue checking
27897330f729Sjoerg // the rest of this struct/class/union subobject.
27907330f729Sjoerg if (IsFirstDesignator) {
27917330f729Sjoerg if (NextField)
27927330f729Sjoerg *NextField = Field;
27937330f729Sjoerg StructuredIndex = FieldIndex;
27947330f729Sjoerg return false;
27957330f729Sjoerg }
27967330f729Sjoerg
27977330f729Sjoerg if (!FinishSubobjectInit)
27987330f729Sjoerg return false;
27997330f729Sjoerg
28007330f729Sjoerg // We've already initialized something in the union; we're done.
28017330f729Sjoerg if (RT->getDecl()->isUnion())
28027330f729Sjoerg return hadError;
28037330f729Sjoerg
28047330f729Sjoerg // Check the remaining fields within this class/struct/union subobject.
28057330f729Sjoerg bool prevHadError = hadError;
28067330f729Sjoerg
28077330f729Sjoerg auto NoBases =
28087330f729Sjoerg CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
28097330f729Sjoerg CXXRecordDecl::base_class_iterator());
28107330f729Sjoerg CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
28117330f729Sjoerg false, Index, StructuredList, FieldIndex);
28127330f729Sjoerg return hadError && !prevHadError;
28137330f729Sjoerg }
28147330f729Sjoerg
28157330f729Sjoerg // C99 6.7.8p6:
28167330f729Sjoerg //
28177330f729Sjoerg // If a designator has the form
28187330f729Sjoerg //
28197330f729Sjoerg // [ constant-expression ]
28207330f729Sjoerg //
28217330f729Sjoerg // then the current object (defined below) shall have array
28227330f729Sjoerg // type and the expression shall be an integer constant
28237330f729Sjoerg // expression. If the array is of unknown size, any
28247330f729Sjoerg // nonnegative value is valid.
28257330f729Sjoerg //
28267330f729Sjoerg // Additionally, cope with the GNU extension that permits
28277330f729Sjoerg // designators of the form
28287330f729Sjoerg //
28297330f729Sjoerg // [ constant-expression ... constant-expression ]
28307330f729Sjoerg const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
28317330f729Sjoerg if (!AT) {
28327330f729Sjoerg if (!VerifyOnly)
28337330f729Sjoerg SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
28347330f729Sjoerg << CurrentObjectType;
28357330f729Sjoerg ++Index;
28367330f729Sjoerg return true;
28377330f729Sjoerg }
28387330f729Sjoerg
28397330f729Sjoerg Expr *IndexExpr = nullptr;
28407330f729Sjoerg llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
28417330f729Sjoerg if (D->isArrayDesignator()) {
28427330f729Sjoerg IndexExpr = DIE->getArrayIndex(*D);
28437330f729Sjoerg DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
28447330f729Sjoerg DesignatedEndIndex = DesignatedStartIndex;
28457330f729Sjoerg } else {
28467330f729Sjoerg assert(D->isArrayRangeDesignator() && "Need array-range designator");
28477330f729Sjoerg
28487330f729Sjoerg DesignatedStartIndex =
28497330f729Sjoerg DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
28507330f729Sjoerg DesignatedEndIndex =
28517330f729Sjoerg DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
28527330f729Sjoerg IndexExpr = DIE->getArrayRangeEnd(*D);
28537330f729Sjoerg
28547330f729Sjoerg // Codegen can't handle evaluating array range designators that have side
28557330f729Sjoerg // effects, because we replicate the AST value for each initialized element.
28567330f729Sjoerg // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
28577330f729Sjoerg // elements with something that has a side effect, so codegen can emit an
28587330f729Sjoerg // "error unsupported" error instead of miscompiling the app.
28597330f729Sjoerg if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
28607330f729Sjoerg DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
28617330f729Sjoerg FullyStructuredList->sawArrayRangeDesignator();
28627330f729Sjoerg }
28637330f729Sjoerg
28647330f729Sjoerg if (isa<ConstantArrayType>(AT)) {
28657330f729Sjoerg llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
28667330f729Sjoerg DesignatedStartIndex
28677330f729Sjoerg = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
28687330f729Sjoerg DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
28697330f729Sjoerg DesignatedEndIndex
28707330f729Sjoerg = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
28717330f729Sjoerg DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
28727330f729Sjoerg if (DesignatedEndIndex >= MaxElements) {
28737330f729Sjoerg if (!VerifyOnly)
28747330f729Sjoerg SemaRef.Diag(IndexExpr->getBeginLoc(),
28757330f729Sjoerg diag::err_array_designator_too_large)
28767330f729Sjoerg << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
28777330f729Sjoerg << IndexExpr->getSourceRange();
28787330f729Sjoerg ++Index;
28797330f729Sjoerg return true;
28807330f729Sjoerg }
28817330f729Sjoerg } else {
28827330f729Sjoerg unsigned DesignatedIndexBitWidth =
28837330f729Sjoerg ConstantArrayType::getMaxSizeBits(SemaRef.Context);
28847330f729Sjoerg DesignatedStartIndex =
28857330f729Sjoerg DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
28867330f729Sjoerg DesignatedEndIndex =
28877330f729Sjoerg DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
28887330f729Sjoerg DesignatedStartIndex.setIsUnsigned(true);
28897330f729Sjoerg DesignatedEndIndex.setIsUnsigned(true);
28907330f729Sjoerg }
28917330f729Sjoerg
28927330f729Sjoerg bool IsStringLiteralInitUpdate =
28937330f729Sjoerg StructuredList && StructuredList->isStringLiteralInit();
28947330f729Sjoerg if (IsStringLiteralInitUpdate && VerifyOnly) {
28957330f729Sjoerg // We're just verifying an update to a string literal init. We don't need
28967330f729Sjoerg // to split the string up into individual characters to do that.
28977330f729Sjoerg StructuredList = nullptr;
28987330f729Sjoerg } else if (IsStringLiteralInitUpdate) {
28997330f729Sjoerg // We're modifying a string literal init; we have to decompose the string
29007330f729Sjoerg // so we can modify the individual characters.
29017330f729Sjoerg ASTContext &Context = SemaRef.Context;
29027330f729Sjoerg Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
29037330f729Sjoerg
29047330f729Sjoerg // Compute the character type
29057330f729Sjoerg QualType CharTy = AT->getElementType();
29067330f729Sjoerg
29077330f729Sjoerg // Compute the type of the integer literals.
29087330f729Sjoerg QualType PromotedCharTy = CharTy;
29097330f729Sjoerg if (CharTy->isPromotableIntegerType())
29107330f729Sjoerg PromotedCharTy = Context.getPromotedIntegerType(CharTy);
29117330f729Sjoerg unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
29127330f729Sjoerg
29137330f729Sjoerg if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
29147330f729Sjoerg // Get the length of the string.
29157330f729Sjoerg uint64_t StrLen = SL->getLength();
29167330f729Sjoerg if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
29177330f729Sjoerg StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
29187330f729Sjoerg StructuredList->resizeInits(Context, StrLen);
29197330f729Sjoerg
29207330f729Sjoerg // Build a literal for each character in the string, and put them into
29217330f729Sjoerg // the init list.
29227330f729Sjoerg for (unsigned i = 0, e = StrLen; i != e; ++i) {
29237330f729Sjoerg llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
29247330f729Sjoerg Expr *Init = new (Context) IntegerLiteral(
29257330f729Sjoerg Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
29267330f729Sjoerg if (CharTy != PromotedCharTy)
2927*e038c9c4Sjoerg Init =
2928*e038c9c4Sjoerg ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast, Init,
2929*e038c9c4Sjoerg nullptr, VK_RValue, FPOptionsOverride());
29307330f729Sjoerg StructuredList->updateInit(Context, i, Init);
29317330f729Sjoerg }
29327330f729Sjoerg } else {
29337330f729Sjoerg ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
29347330f729Sjoerg std::string Str;
29357330f729Sjoerg Context.getObjCEncodingForType(E->getEncodedType(), Str);
29367330f729Sjoerg
29377330f729Sjoerg // Get the length of the string.
29387330f729Sjoerg uint64_t StrLen = Str.size();
29397330f729Sjoerg if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
29407330f729Sjoerg StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
29417330f729Sjoerg StructuredList->resizeInits(Context, StrLen);
29427330f729Sjoerg
29437330f729Sjoerg // Build a literal for each character in the string, and put them into
29447330f729Sjoerg // the init list.
29457330f729Sjoerg for (unsigned i = 0, e = StrLen; i != e; ++i) {
29467330f729Sjoerg llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
29477330f729Sjoerg Expr *Init = new (Context) IntegerLiteral(
29487330f729Sjoerg Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
29497330f729Sjoerg if (CharTy != PromotedCharTy)
2950*e038c9c4Sjoerg Init =
2951*e038c9c4Sjoerg ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast, Init,
2952*e038c9c4Sjoerg nullptr, VK_RValue, FPOptionsOverride());
29537330f729Sjoerg StructuredList->updateInit(Context, i, Init);
29547330f729Sjoerg }
29557330f729Sjoerg }
29567330f729Sjoerg }
29577330f729Sjoerg
29587330f729Sjoerg // Make sure that our non-designated initializer list has space
29597330f729Sjoerg // for a subobject corresponding to this array element.
29607330f729Sjoerg if (StructuredList &&
29617330f729Sjoerg DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
29627330f729Sjoerg StructuredList->resizeInits(SemaRef.Context,
29637330f729Sjoerg DesignatedEndIndex.getZExtValue() + 1);
29647330f729Sjoerg
29657330f729Sjoerg // Repeatedly perform subobject initializations in the range
29667330f729Sjoerg // [DesignatedStartIndex, DesignatedEndIndex].
29677330f729Sjoerg
29687330f729Sjoerg // Move to the next designator
29697330f729Sjoerg unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
29707330f729Sjoerg unsigned OldIndex = Index;
29717330f729Sjoerg
29727330f729Sjoerg InitializedEntity ElementEntity =
29737330f729Sjoerg InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
29747330f729Sjoerg
29757330f729Sjoerg while (DesignatedStartIndex <= DesignatedEndIndex) {
29767330f729Sjoerg // Recurse to check later designated subobjects.
29777330f729Sjoerg QualType ElementType = AT->getElementType();
29787330f729Sjoerg Index = OldIndex;
29797330f729Sjoerg
29807330f729Sjoerg ElementEntity.setElementIndex(ElementIndex);
29817330f729Sjoerg if (CheckDesignatedInitializer(
29827330f729Sjoerg ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
29837330f729Sjoerg nullptr, Index, StructuredList, ElementIndex,
29847330f729Sjoerg FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
29857330f729Sjoerg false))
29867330f729Sjoerg return true;
29877330f729Sjoerg
29887330f729Sjoerg // Move to the next index in the array that we'll be initializing.
29897330f729Sjoerg ++DesignatedStartIndex;
29907330f729Sjoerg ElementIndex = DesignatedStartIndex.getZExtValue();
29917330f729Sjoerg }
29927330f729Sjoerg
29937330f729Sjoerg // If this the first designator, our caller will continue checking
29947330f729Sjoerg // the rest of this array subobject.
29957330f729Sjoerg if (IsFirstDesignator) {
29967330f729Sjoerg if (NextElementIndex)
29977330f729Sjoerg *NextElementIndex = DesignatedStartIndex;
29987330f729Sjoerg StructuredIndex = ElementIndex;
29997330f729Sjoerg return false;
30007330f729Sjoerg }
30017330f729Sjoerg
30027330f729Sjoerg if (!FinishSubobjectInit)
30037330f729Sjoerg return false;
30047330f729Sjoerg
30057330f729Sjoerg // Check the remaining elements within this array subobject.
30067330f729Sjoerg bool prevHadError = hadError;
30077330f729Sjoerg CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
30087330f729Sjoerg /*SubobjectIsDesignatorContext=*/false, Index,
30097330f729Sjoerg StructuredList, ElementIndex);
30107330f729Sjoerg return hadError && !prevHadError;
30117330f729Sjoerg }
30127330f729Sjoerg
30137330f729Sjoerg // Get the structured initializer list for a subobject of type
30147330f729Sjoerg // @p CurrentObjectType.
30157330f729Sjoerg InitListExpr *
getStructuredSubobjectInit(InitListExpr * IList,unsigned Index,QualType CurrentObjectType,InitListExpr * StructuredList,unsigned StructuredIndex,SourceRange InitRange,bool IsFullyOverwritten)30167330f729Sjoerg InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
30177330f729Sjoerg QualType CurrentObjectType,
30187330f729Sjoerg InitListExpr *StructuredList,
30197330f729Sjoerg unsigned StructuredIndex,
30207330f729Sjoerg SourceRange InitRange,
30217330f729Sjoerg bool IsFullyOverwritten) {
30227330f729Sjoerg if (!StructuredList)
30237330f729Sjoerg return nullptr;
30247330f729Sjoerg
30257330f729Sjoerg Expr *ExistingInit = nullptr;
30267330f729Sjoerg if (StructuredIndex < StructuredList->getNumInits())
30277330f729Sjoerg ExistingInit = StructuredList->getInit(StructuredIndex);
30287330f729Sjoerg
30297330f729Sjoerg if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
30307330f729Sjoerg // There might have already been initializers for subobjects of the current
30317330f729Sjoerg // object, but a subsequent initializer list will overwrite the entirety
30327330f729Sjoerg // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
30337330f729Sjoerg //
30347330f729Sjoerg // struct P { char x[6]; };
30357330f729Sjoerg // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
30367330f729Sjoerg //
30377330f729Sjoerg // The first designated initializer is ignored, and l.x is just "f".
30387330f729Sjoerg if (!IsFullyOverwritten)
30397330f729Sjoerg return Result;
30407330f729Sjoerg
30417330f729Sjoerg if (ExistingInit) {
30427330f729Sjoerg // We are creating an initializer list that initializes the
30437330f729Sjoerg // subobjects of the current object, but there was already an
30447330f729Sjoerg // initialization that completely initialized the current
30457330f729Sjoerg // subobject:
30467330f729Sjoerg //
30477330f729Sjoerg // struct X { int a, b; };
30487330f729Sjoerg // struct X xs[] = { [0] = { 1, 2 }, [0].b = 3 };
30497330f729Sjoerg //
30507330f729Sjoerg // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
30517330f729Sjoerg // designated initializer overwrites the [0].b initializer
30527330f729Sjoerg // from the prior initialization.
30537330f729Sjoerg //
30547330f729Sjoerg // When the existing initializer is an expression rather than an
30557330f729Sjoerg // initializer list, we cannot decompose and update it in this way.
30567330f729Sjoerg // For example:
30577330f729Sjoerg //
30587330f729Sjoerg // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
30597330f729Sjoerg //
30607330f729Sjoerg // This case is handled by CheckDesignatedInitializer.
30617330f729Sjoerg diagnoseInitOverride(ExistingInit, InitRange);
30627330f729Sjoerg }
30637330f729Sjoerg
30647330f729Sjoerg unsigned ExpectedNumInits = 0;
30657330f729Sjoerg if (Index < IList->getNumInits()) {
30667330f729Sjoerg if (auto *Init = dyn_cast_or_null<InitListExpr>(IList->getInit(Index)))
30677330f729Sjoerg ExpectedNumInits = Init->getNumInits();
30687330f729Sjoerg else
30697330f729Sjoerg ExpectedNumInits = IList->getNumInits() - Index;
30707330f729Sjoerg }
30717330f729Sjoerg
30727330f729Sjoerg InitListExpr *Result =
30737330f729Sjoerg createInitListExpr(CurrentObjectType, InitRange, ExpectedNumInits);
30747330f729Sjoerg
30757330f729Sjoerg // Link this new initializer list into the structured initializer
30767330f729Sjoerg // lists.
30777330f729Sjoerg StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
30787330f729Sjoerg return Result;
30797330f729Sjoerg }
30807330f729Sjoerg
30817330f729Sjoerg InitListExpr *
createInitListExpr(QualType CurrentObjectType,SourceRange InitRange,unsigned ExpectedNumInits)30827330f729Sjoerg InitListChecker::createInitListExpr(QualType CurrentObjectType,
30837330f729Sjoerg SourceRange InitRange,
30847330f729Sjoerg unsigned ExpectedNumInits) {
30857330f729Sjoerg InitListExpr *Result
30867330f729Sjoerg = new (SemaRef.Context) InitListExpr(SemaRef.Context,
30877330f729Sjoerg InitRange.getBegin(), None,
30887330f729Sjoerg InitRange.getEnd());
30897330f729Sjoerg
30907330f729Sjoerg QualType ResultType = CurrentObjectType;
30917330f729Sjoerg if (!ResultType->isArrayType())
30927330f729Sjoerg ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
30937330f729Sjoerg Result->setType(ResultType);
30947330f729Sjoerg
30957330f729Sjoerg // Pre-allocate storage for the structured initializer list.
30967330f729Sjoerg unsigned NumElements = 0;
30977330f729Sjoerg
30987330f729Sjoerg if (const ArrayType *AType
30997330f729Sjoerg = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
31007330f729Sjoerg if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
31017330f729Sjoerg NumElements = CAType->getSize().getZExtValue();
31027330f729Sjoerg // Simple heuristic so that we don't allocate a very large
31037330f729Sjoerg // initializer with many empty entries at the end.
31047330f729Sjoerg if (NumElements > ExpectedNumInits)
31057330f729Sjoerg NumElements = 0;
31067330f729Sjoerg }
31077330f729Sjoerg } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) {
31087330f729Sjoerg NumElements = VType->getNumElements();
31097330f729Sjoerg } else if (CurrentObjectType->isRecordType()) {
31107330f729Sjoerg NumElements = numStructUnionElements(CurrentObjectType);
31117330f729Sjoerg }
31127330f729Sjoerg
31137330f729Sjoerg Result->reserveInits(SemaRef.Context, NumElements);
31147330f729Sjoerg
31157330f729Sjoerg return Result;
31167330f729Sjoerg }
31177330f729Sjoerg
31187330f729Sjoerg /// Update the initializer at index @p StructuredIndex within the
31197330f729Sjoerg /// structured initializer list to the value @p expr.
UpdateStructuredListElement(InitListExpr * StructuredList,unsigned & StructuredIndex,Expr * expr)31207330f729Sjoerg void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
31217330f729Sjoerg unsigned &StructuredIndex,
31227330f729Sjoerg Expr *expr) {
31237330f729Sjoerg // No structured initializer list to update
31247330f729Sjoerg if (!StructuredList)
31257330f729Sjoerg return;
31267330f729Sjoerg
31277330f729Sjoerg if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
31287330f729Sjoerg StructuredIndex, expr)) {
3129*e038c9c4Sjoerg // This initializer overwrites a previous initializer.
3130*e038c9c4Sjoerg // No need to diagnose when `expr` is nullptr because a more relevant
3131*e038c9c4Sjoerg // diagnostic has already been issued and this diagnostic is potentially
3132*e038c9c4Sjoerg // noise.
3133*e038c9c4Sjoerg if (expr)
31347330f729Sjoerg diagnoseInitOverride(PrevInit, expr->getSourceRange());
31357330f729Sjoerg }
31367330f729Sjoerg
31377330f729Sjoerg ++StructuredIndex;
31387330f729Sjoerg }
31397330f729Sjoerg
31407330f729Sjoerg /// Determine whether we can perform aggregate initialization for the purposes
31417330f729Sjoerg /// of overload resolution.
CanPerformAggregateInitializationForOverloadResolution(const InitializedEntity & Entity,InitListExpr * From)31427330f729Sjoerg bool Sema::CanPerformAggregateInitializationForOverloadResolution(
31437330f729Sjoerg const InitializedEntity &Entity, InitListExpr *From) {
31447330f729Sjoerg QualType Type = Entity.getType();
31457330f729Sjoerg InitListChecker Check(*this, Entity, From, Type, /*VerifyOnly=*/true,
31467330f729Sjoerg /*TreatUnavailableAsInvalid=*/false,
31477330f729Sjoerg /*InOverloadResolution=*/true);
31487330f729Sjoerg return !Check.HadError();
31497330f729Sjoerg }
31507330f729Sjoerg
31517330f729Sjoerg /// Check that the given Index expression is a valid array designator
31527330f729Sjoerg /// value. This is essentially just a wrapper around
31537330f729Sjoerg /// VerifyIntegerConstantExpression that also checks for negative values
31547330f729Sjoerg /// and produces a reasonable diagnostic if there is a
31557330f729Sjoerg /// failure. Returns the index expression, possibly with an implicit cast
31567330f729Sjoerg /// added, on success. If everything went okay, Value will receive the
31577330f729Sjoerg /// value of the constant expression.
31587330f729Sjoerg static ExprResult
CheckArrayDesignatorExpr(Sema & S,Expr * Index,llvm::APSInt & Value)31597330f729Sjoerg CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
31607330f729Sjoerg SourceLocation Loc = Index->getBeginLoc();
31617330f729Sjoerg
31627330f729Sjoerg // Make sure this is an integer constant expression.
3163*e038c9c4Sjoerg ExprResult Result =
3164*e038c9c4Sjoerg S.VerifyIntegerConstantExpression(Index, &Value, Sema::AllowFold);
31657330f729Sjoerg if (Result.isInvalid())
31667330f729Sjoerg return Result;
31677330f729Sjoerg
31687330f729Sjoerg if (Value.isSigned() && Value.isNegative())
31697330f729Sjoerg return S.Diag(Loc, diag::err_array_designator_negative)
31707330f729Sjoerg << Value.toString(10) << Index->getSourceRange();
31717330f729Sjoerg
31727330f729Sjoerg Value.setIsUnsigned(true);
31737330f729Sjoerg return Result;
31747330f729Sjoerg }
31757330f729Sjoerg
ActOnDesignatedInitializer(Designation & Desig,SourceLocation EqualOrColonLoc,bool GNUSyntax,ExprResult Init)31767330f729Sjoerg ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
31777330f729Sjoerg SourceLocation EqualOrColonLoc,
31787330f729Sjoerg bool GNUSyntax,
31797330f729Sjoerg ExprResult Init) {
31807330f729Sjoerg typedef DesignatedInitExpr::Designator ASTDesignator;
31817330f729Sjoerg
31827330f729Sjoerg bool Invalid = false;
31837330f729Sjoerg SmallVector<ASTDesignator, 32> Designators;
31847330f729Sjoerg SmallVector<Expr *, 32> InitExpressions;
31857330f729Sjoerg
31867330f729Sjoerg // Build designators and check array designator expressions.
31877330f729Sjoerg for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
31887330f729Sjoerg const Designator &D = Desig.getDesignator(Idx);
31897330f729Sjoerg switch (D.getKind()) {
31907330f729Sjoerg case Designator::FieldDesignator:
31917330f729Sjoerg Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
31927330f729Sjoerg D.getFieldLoc()));
31937330f729Sjoerg break;
31947330f729Sjoerg
31957330f729Sjoerg case Designator::ArrayDesignator: {
31967330f729Sjoerg Expr *Index = static_cast<Expr *>(D.getArrayIndex());
31977330f729Sjoerg llvm::APSInt IndexValue;
31987330f729Sjoerg if (!Index->isTypeDependent() && !Index->isValueDependent())
31997330f729Sjoerg Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
32007330f729Sjoerg if (!Index)
32017330f729Sjoerg Invalid = true;
32027330f729Sjoerg else {
32037330f729Sjoerg Designators.push_back(ASTDesignator(InitExpressions.size(),
32047330f729Sjoerg D.getLBracketLoc(),
32057330f729Sjoerg D.getRBracketLoc()));
32067330f729Sjoerg InitExpressions.push_back(Index);
32077330f729Sjoerg }
32087330f729Sjoerg break;
32097330f729Sjoerg }
32107330f729Sjoerg
32117330f729Sjoerg case Designator::ArrayRangeDesignator: {
32127330f729Sjoerg Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
32137330f729Sjoerg Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
32147330f729Sjoerg llvm::APSInt StartValue;
32157330f729Sjoerg llvm::APSInt EndValue;
32167330f729Sjoerg bool StartDependent = StartIndex->isTypeDependent() ||
32177330f729Sjoerg StartIndex->isValueDependent();
32187330f729Sjoerg bool EndDependent = EndIndex->isTypeDependent() ||
32197330f729Sjoerg EndIndex->isValueDependent();
32207330f729Sjoerg if (!StartDependent)
32217330f729Sjoerg StartIndex =
32227330f729Sjoerg CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
32237330f729Sjoerg if (!EndDependent)
32247330f729Sjoerg EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
32257330f729Sjoerg
32267330f729Sjoerg if (!StartIndex || !EndIndex)
32277330f729Sjoerg Invalid = true;
32287330f729Sjoerg else {
32297330f729Sjoerg // Make sure we're comparing values with the same bit width.
32307330f729Sjoerg if (StartDependent || EndDependent) {
32317330f729Sjoerg // Nothing to compute.
32327330f729Sjoerg } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
32337330f729Sjoerg EndValue = EndValue.extend(StartValue.getBitWidth());
32347330f729Sjoerg else if (StartValue.getBitWidth() < EndValue.getBitWidth())
32357330f729Sjoerg StartValue = StartValue.extend(EndValue.getBitWidth());
32367330f729Sjoerg
32377330f729Sjoerg if (!StartDependent && !EndDependent && EndValue < StartValue) {
32387330f729Sjoerg Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
32397330f729Sjoerg << StartValue.toString(10) << EndValue.toString(10)
32407330f729Sjoerg << StartIndex->getSourceRange() << EndIndex->getSourceRange();
32417330f729Sjoerg Invalid = true;
32427330f729Sjoerg } else {
32437330f729Sjoerg Designators.push_back(ASTDesignator(InitExpressions.size(),
32447330f729Sjoerg D.getLBracketLoc(),
32457330f729Sjoerg D.getEllipsisLoc(),
32467330f729Sjoerg D.getRBracketLoc()));
32477330f729Sjoerg InitExpressions.push_back(StartIndex);
32487330f729Sjoerg InitExpressions.push_back(EndIndex);
32497330f729Sjoerg }
32507330f729Sjoerg }
32517330f729Sjoerg break;
32527330f729Sjoerg }
32537330f729Sjoerg }
32547330f729Sjoerg }
32557330f729Sjoerg
32567330f729Sjoerg if (Invalid || Init.isInvalid())
32577330f729Sjoerg return ExprError();
32587330f729Sjoerg
32597330f729Sjoerg // Clear out the expressions within the designation.
32607330f729Sjoerg Desig.ClearExprs(*this);
32617330f729Sjoerg
32627330f729Sjoerg return DesignatedInitExpr::Create(Context, Designators, InitExpressions,
32637330f729Sjoerg EqualOrColonLoc, GNUSyntax,
32647330f729Sjoerg Init.getAs<Expr>());
32657330f729Sjoerg }
32667330f729Sjoerg
32677330f729Sjoerg //===----------------------------------------------------------------------===//
32687330f729Sjoerg // Initialization entity
32697330f729Sjoerg //===----------------------------------------------------------------------===//
32707330f729Sjoerg
InitializedEntity(ASTContext & Context,unsigned Index,const InitializedEntity & Parent)32717330f729Sjoerg InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
32727330f729Sjoerg const InitializedEntity &Parent)
32737330f729Sjoerg : Parent(&Parent), Index(Index)
32747330f729Sjoerg {
32757330f729Sjoerg if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
32767330f729Sjoerg Kind = EK_ArrayElement;
32777330f729Sjoerg Type = AT->getElementType();
32787330f729Sjoerg } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
32797330f729Sjoerg Kind = EK_VectorElement;
32807330f729Sjoerg Type = VT->getElementType();
32817330f729Sjoerg } else {
32827330f729Sjoerg const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
32837330f729Sjoerg assert(CT && "Unexpected type");
32847330f729Sjoerg Kind = EK_ComplexElement;
32857330f729Sjoerg Type = CT->getElementType();
32867330f729Sjoerg }
32877330f729Sjoerg }
32887330f729Sjoerg
32897330f729Sjoerg InitializedEntity
InitializeBase(ASTContext & Context,const CXXBaseSpecifier * Base,bool IsInheritedVirtualBase,const InitializedEntity * Parent)32907330f729Sjoerg InitializedEntity::InitializeBase(ASTContext &Context,
32917330f729Sjoerg const CXXBaseSpecifier *Base,
32927330f729Sjoerg bool IsInheritedVirtualBase,
32937330f729Sjoerg const InitializedEntity *Parent) {
32947330f729Sjoerg InitializedEntity Result;
32957330f729Sjoerg Result.Kind = EK_Base;
32967330f729Sjoerg Result.Parent = Parent;
3297*e038c9c4Sjoerg Result.Base = {Base, IsInheritedVirtualBase};
32987330f729Sjoerg Result.Type = Base->getType();
32997330f729Sjoerg return Result;
33007330f729Sjoerg }
33017330f729Sjoerg
getName() const33027330f729Sjoerg DeclarationName InitializedEntity::getName() const {
33037330f729Sjoerg switch (getKind()) {
33047330f729Sjoerg case EK_Parameter:
33057330f729Sjoerg case EK_Parameter_CF_Audited: {
3306*e038c9c4Sjoerg ParmVarDecl *D = Parameter.getPointer();
33077330f729Sjoerg return (D ? D->getDeclName() : DeclarationName());
33087330f729Sjoerg }
33097330f729Sjoerg
33107330f729Sjoerg case EK_Variable:
33117330f729Sjoerg case EK_Member:
33127330f729Sjoerg case EK_Binding:
3313*e038c9c4Sjoerg case EK_TemplateParameter:
33147330f729Sjoerg return Variable.VariableOrMember->getDeclName();
33157330f729Sjoerg
33167330f729Sjoerg case EK_LambdaCapture:
33177330f729Sjoerg return DeclarationName(Capture.VarID);
33187330f729Sjoerg
33197330f729Sjoerg case EK_Result:
33207330f729Sjoerg case EK_StmtExprResult:
33217330f729Sjoerg case EK_Exception:
33227330f729Sjoerg case EK_New:
33237330f729Sjoerg case EK_Temporary:
33247330f729Sjoerg case EK_Base:
33257330f729Sjoerg case EK_Delegating:
33267330f729Sjoerg case EK_ArrayElement:
33277330f729Sjoerg case EK_VectorElement:
33287330f729Sjoerg case EK_ComplexElement:
33297330f729Sjoerg case EK_BlockElement:
33307330f729Sjoerg case EK_LambdaToBlockConversionBlockElement:
33317330f729Sjoerg case EK_CompoundLiteralInit:
33327330f729Sjoerg case EK_RelatedResult:
33337330f729Sjoerg return DeclarationName();
33347330f729Sjoerg }
33357330f729Sjoerg
33367330f729Sjoerg llvm_unreachable("Invalid EntityKind!");
33377330f729Sjoerg }
33387330f729Sjoerg
getDecl() const33397330f729Sjoerg ValueDecl *InitializedEntity::getDecl() const {
33407330f729Sjoerg switch (getKind()) {
33417330f729Sjoerg case EK_Variable:
33427330f729Sjoerg case EK_Member:
33437330f729Sjoerg case EK_Binding:
3344*e038c9c4Sjoerg case EK_TemplateParameter:
33457330f729Sjoerg return Variable.VariableOrMember;
33467330f729Sjoerg
33477330f729Sjoerg case EK_Parameter:
33487330f729Sjoerg case EK_Parameter_CF_Audited:
3349*e038c9c4Sjoerg return Parameter.getPointer();
33507330f729Sjoerg
33517330f729Sjoerg case EK_Result:
33527330f729Sjoerg case EK_StmtExprResult:
33537330f729Sjoerg case EK_Exception:
33547330f729Sjoerg case EK_New:
33557330f729Sjoerg case EK_Temporary:
33567330f729Sjoerg case EK_Base:
33577330f729Sjoerg case EK_Delegating:
33587330f729Sjoerg case EK_ArrayElement:
33597330f729Sjoerg case EK_VectorElement:
33607330f729Sjoerg case EK_ComplexElement:
33617330f729Sjoerg case EK_BlockElement:
33627330f729Sjoerg case EK_LambdaToBlockConversionBlockElement:
33637330f729Sjoerg case EK_LambdaCapture:
33647330f729Sjoerg case EK_CompoundLiteralInit:
33657330f729Sjoerg case EK_RelatedResult:
33667330f729Sjoerg return nullptr;
33677330f729Sjoerg }
33687330f729Sjoerg
33697330f729Sjoerg llvm_unreachable("Invalid EntityKind!");
33707330f729Sjoerg }
33717330f729Sjoerg
allowsNRVO() const33727330f729Sjoerg bool InitializedEntity::allowsNRVO() const {
33737330f729Sjoerg switch (getKind()) {
33747330f729Sjoerg case EK_Result:
33757330f729Sjoerg case EK_Exception:
33767330f729Sjoerg return LocAndNRVO.NRVO;
33777330f729Sjoerg
33787330f729Sjoerg case EK_StmtExprResult:
33797330f729Sjoerg case EK_Variable:
33807330f729Sjoerg case EK_Parameter:
33817330f729Sjoerg case EK_Parameter_CF_Audited:
3382*e038c9c4Sjoerg case EK_TemplateParameter:
33837330f729Sjoerg case EK_Member:
33847330f729Sjoerg case EK_Binding:
33857330f729Sjoerg case EK_New:
33867330f729Sjoerg case EK_Temporary:
33877330f729Sjoerg case EK_CompoundLiteralInit:
33887330f729Sjoerg case EK_Base:
33897330f729Sjoerg case EK_Delegating:
33907330f729Sjoerg case EK_ArrayElement:
33917330f729Sjoerg case EK_VectorElement:
33927330f729Sjoerg case EK_ComplexElement:
33937330f729Sjoerg case EK_BlockElement:
33947330f729Sjoerg case EK_LambdaToBlockConversionBlockElement:
33957330f729Sjoerg case EK_LambdaCapture:
33967330f729Sjoerg case EK_RelatedResult:
33977330f729Sjoerg break;
33987330f729Sjoerg }
33997330f729Sjoerg
34007330f729Sjoerg return false;
34017330f729Sjoerg }
34027330f729Sjoerg
dumpImpl(raw_ostream & OS) const34037330f729Sjoerg unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
34047330f729Sjoerg assert(getParent() != this);
34057330f729Sjoerg unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
34067330f729Sjoerg for (unsigned I = 0; I != Depth; ++I)
34077330f729Sjoerg OS << "`-";
34087330f729Sjoerg
34097330f729Sjoerg switch (getKind()) {
34107330f729Sjoerg case EK_Variable: OS << "Variable"; break;
34117330f729Sjoerg case EK_Parameter: OS << "Parameter"; break;
34127330f729Sjoerg case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
34137330f729Sjoerg break;
3414*e038c9c4Sjoerg case EK_TemplateParameter: OS << "TemplateParameter"; break;
34157330f729Sjoerg case EK_Result: OS << "Result"; break;
34167330f729Sjoerg case EK_StmtExprResult: OS << "StmtExprResult"; break;
34177330f729Sjoerg case EK_Exception: OS << "Exception"; break;
34187330f729Sjoerg case EK_Member: OS << "Member"; break;
34197330f729Sjoerg case EK_Binding: OS << "Binding"; break;
34207330f729Sjoerg case EK_New: OS << "New"; break;
34217330f729Sjoerg case EK_Temporary: OS << "Temporary"; break;
34227330f729Sjoerg case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
34237330f729Sjoerg case EK_RelatedResult: OS << "RelatedResult"; break;
34247330f729Sjoerg case EK_Base: OS << "Base"; break;
34257330f729Sjoerg case EK_Delegating: OS << "Delegating"; break;
34267330f729Sjoerg case EK_ArrayElement: OS << "ArrayElement " << Index; break;
34277330f729Sjoerg case EK_VectorElement: OS << "VectorElement " << Index; break;
34287330f729Sjoerg case EK_ComplexElement: OS << "ComplexElement " << Index; break;
34297330f729Sjoerg case EK_BlockElement: OS << "Block"; break;
34307330f729Sjoerg case EK_LambdaToBlockConversionBlockElement:
34317330f729Sjoerg OS << "Block (lambda)";
34327330f729Sjoerg break;
34337330f729Sjoerg case EK_LambdaCapture:
34347330f729Sjoerg OS << "LambdaCapture ";
34357330f729Sjoerg OS << DeclarationName(Capture.VarID);
34367330f729Sjoerg break;
34377330f729Sjoerg }
34387330f729Sjoerg
34397330f729Sjoerg if (auto *D = getDecl()) {
34407330f729Sjoerg OS << " ";
34417330f729Sjoerg D->printQualifiedName(OS);
34427330f729Sjoerg }
34437330f729Sjoerg
34447330f729Sjoerg OS << " '" << getType().getAsString() << "'\n";
34457330f729Sjoerg
34467330f729Sjoerg return Depth + 1;
34477330f729Sjoerg }
34487330f729Sjoerg
dump() const34497330f729Sjoerg LLVM_DUMP_METHOD void InitializedEntity::dump() const {
34507330f729Sjoerg dumpImpl(llvm::errs());
34517330f729Sjoerg }
34527330f729Sjoerg
34537330f729Sjoerg //===----------------------------------------------------------------------===//
34547330f729Sjoerg // Initialization sequence
34557330f729Sjoerg //===----------------------------------------------------------------------===//
34567330f729Sjoerg
Destroy()34577330f729Sjoerg void InitializationSequence::Step::Destroy() {
34587330f729Sjoerg switch (Kind) {
34597330f729Sjoerg case SK_ResolveAddressOfOverloadedFunction:
34607330f729Sjoerg case SK_CastDerivedToBaseRValue:
34617330f729Sjoerg case SK_CastDerivedToBaseXValue:
34627330f729Sjoerg case SK_CastDerivedToBaseLValue:
34637330f729Sjoerg case SK_BindReference:
34647330f729Sjoerg case SK_BindReferenceToTemporary:
34657330f729Sjoerg case SK_FinalCopy:
34667330f729Sjoerg case SK_ExtraneousCopyToTemporary:
34677330f729Sjoerg case SK_UserConversion:
34687330f729Sjoerg case SK_QualificationConversionRValue:
34697330f729Sjoerg case SK_QualificationConversionXValue:
34707330f729Sjoerg case SK_QualificationConversionLValue:
3471*e038c9c4Sjoerg case SK_FunctionReferenceConversion:
34727330f729Sjoerg case SK_AtomicConversion:
34737330f729Sjoerg case SK_ListInitialization:
34747330f729Sjoerg case SK_UnwrapInitList:
34757330f729Sjoerg case SK_RewrapInitList:
34767330f729Sjoerg case SK_ConstructorInitialization:
34777330f729Sjoerg case SK_ConstructorInitializationFromList:
34787330f729Sjoerg case SK_ZeroInitialization:
34797330f729Sjoerg case SK_CAssignment:
34807330f729Sjoerg case SK_StringInit:
34817330f729Sjoerg case SK_ObjCObjectConversion:
34827330f729Sjoerg case SK_ArrayLoopIndex:
34837330f729Sjoerg case SK_ArrayLoopInit:
34847330f729Sjoerg case SK_ArrayInit:
34857330f729Sjoerg case SK_GNUArrayInit:
34867330f729Sjoerg case SK_ParenthesizedArrayInit:
34877330f729Sjoerg case SK_PassByIndirectCopyRestore:
34887330f729Sjoerg case SK_PassByIndirectRestore:
34897330f729Sjoerg case SK_ProduceObjCObject:
34907330f729Sjoerg case SK_StdInitializerList:
34917330f729Sjoerg case SK_StdInitializerListConstructorCall:
34927330f729Sjoerg case SK_OCLSamplerInit:
34937330f729Sjoerg case SK_OCLZeroOpaqueType:
34947330f729Sjoerg break;
34957330f729Sjoerg
34967330f729Sjoerg case SK_ConversionSequence:
34977330f729Sjoerg case SK_ConversionSequenceNoNarrowing:
34987330f729Sjoerg delete ICS;
34997330f729Sjoerg }
35007330f729Sjoerg }
35017330f729Sjoerg
isDirectReferenceBinding() const35027330f729Sjoerg bool InitializationSequence::isDirectReferenceBinding() const {
35037330f729Sjoerg // There can be some lvalue adjustments after the SK_BindReference step.
35047330f729Sjoerg for (auto I = Steps.rbegin(); I != Steps.rend(); ++I) {
35057330f729Sjoerg if (I->Kind == SK_BindReference)
35067330f729Sjoerg return true;
35077330f729Sjoerg if (I->Kind == SK_BindReferenceToTemporary)
35087330f729Sjoerg return false;
35097330f729Sjoerg }
35107330f729Sjoerg return false;
35117330f729Sjoerg }
35127330f729Sjoerg
isAmbiguous() const35137330f729Sjoerg bool InitializationSequence::isAmbiguous() const {
35147330f729Sjoerg if (!Failed())
35157330f729Sjoerg return false;
35167330f729Sjoerg
35177330f729Sjoerg switch (getFailureKind()) {
35187330f729Sjoerg case FK_TooManyInitsForReference:
35197330f729Sjoerg case FK_ParenthesizedListInitForReference:
35207330f729Sjoerg case FK_ArrayNeedsInitList:
35217330f729Sjoerg case FK_ArrayNeedsInitListOrStringLiteral:
35227330f729Sjoerg case FK_ArrayNeedsInitListOrWideStringLiteral:
35237330f729Sjoerg case FK_NarrowStringIntoWideCharArray:
35247330f729Sjoerg case FK_WideStringIntoCharArray:
35257330f729Sjoerg case FK_IncompatWideStringIntoWideChar:
35267330f729Sjoerg case FK_PlainStringIntoUTF8Char:
35277330f729Sjoerg case FK_UTF8StringIntoPlainChar:
35287330f729Sjoerg case FK_AddressOfOverloadFailed: // FIXME: Could do better
35297330f729Sjoerg case FK_NonConstLValueReferenceBindingToTemporary:
35307330f729Sjoerg case FK_NonConstLValueReferenceBindingToBitfield:
35317330f729Sjoerg case FK_NonConstLValueReferenceBindingToVectorElement:
3532*e038c9c4Sjoerg case FK_NonConstLValueReferenceBindingToMatrixElement:
35337330f729Sjoerg case FK_NonConstLValueReferenceBindingToUnrelated:
35347330f729Sjoerg case FK_RValueReferenceBindingToLValue:
35357330f729Sjoerg case FK_ReferenceAddrspaceMismatchTemporary:
35367330f729Sjoerg case FK_ReferenceInitDropsQualifiers:
35377330f729Sjoerg case FK_ReferenceInitFailed:
35387330f729Sjoerg case FK_ConversionFailed:
35397330f729Sjoerg case FK_ConversionFromPropertyFailed:
35407330f729Sjoerg case FK_TooManyInitsForScalar:
35417330f729Sjoerg case FK_ParenthesizedListInitForScalar:
35427330f729Sjoerg case FK_ReferenceBindingToInitList:
35437330f729Sjoerg case FK_InitListBadDestinationType:
35447330f729Sjoerg case FK_DefaultInitOfConst:
35457330f729Sjoerg case FK_Incomplete:
35467330f729Sjoerg case FK_ArrayTypeMismatch:
35477330f729Sjoerg case FK_NonConstantArrayInit:
35487330f729Sjoerg case FK_ListInitializationFailed:
35497330f729Sjoerg case FK_VariableLengthArrayHasInitializer:
35507330f729Sjoerg case FK_PlaceholderType:
35517330f729Sjoerg case FK_ExplicitConstructor:
35527330f729Sjoerg case FK_AddressOfUnaddressableFunction:
35537330f729Sjoerg return false;
35547330f729Sjoerg
35557330f729Sjoerg case FK_ReferenceInitOverloadFailed:
35567330f729Sjoerg case FK_UserConversionOverloadFailed:
35577330f729Sjoerg case FK_ConstructorOverloadFailed:
35587330f729Sjoerg case FK_ListConstructorOverloadFailed:
35597330f729Sjoerg return FailedOverloadResult == OR_Ambiguous;
35607330f729Sjoerg }
35617330f729Sjoerg
35627330f729Sjoerg llvm_unreachable("Invalid EntityKind!");
35637330f729Sjoerg }
35647330f729Sjoerg
isConstructorInitialization() const35657330f729Sjoerg bool InitializationSequence::isConstructorInitialization() const {
35667330f729Sjoerg return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
35677330f729Sjoerg }
35687330f729Sjoerg
35697330f729Sjoerg void
35707330f729Sjoerg InitializationSequence
AddAddressOverloadResolutionStep(FunctionDecl * Function,DeclAccessPair Found,bool HadMultipleCandidates)35717330f729Sjoerg ::AddAddressOverloadResolutionStep(FunctionDecl *Function,
35727330f729Sjoerg DeclAccessPair Found,
35737330f729Sjoerg bool HadMultipleCandidates) {
35747330f729Sjoerg Step S;
35757330f729Sjoerg S.Kind = SK_ResolveAddressOfOverloadedFunction;
35767330f729Sjoerg S.Type = Function->getType();
35777330f729Sjoerg S.Function.HadMultipleCandidates = HadMultipleCandidates;
35787330f729Sjoerg S.Function.Function = Function;
35797330f729Sjoerg S.Function.FoundDecl = Found;
35807330f729Sjoerg Steps.push_back(S);
35817330f729Sjoerg }
35827330f729Sjoerg
AddDerivedToBaseCastStep(QualType BaseType,ExprValueKind VK)35837330f729Sjoerg void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
35847330f729Sjoerg ExprValueKind VK) {
35857330f729Sjoerg Step S;
35867330f729Sjoerg switch (VK) {
35877330f729Sjoerg case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
35887330f729Sjoerg case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
35897330f729Sjoerg case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
35907330f729Sjoerg }
35917330f729Sjoerg S.Type = BaseType;
35927330f729Sjoerg Steps.push_back(S);
35937330f729Sjoerg }
35947330f729Sjoerg
AddReferenceBindingStep(QualType T,bool BindingTemporary)35957330f729Sjoerg void InitializationSequence::AddReferenceBindingStep(QualType T,
35967330f729Sjoerg bool BindingTemporary) {
35977330f729Sjoerg Step S;
35987330f729Sjoerg S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
35997330f729Sjoerg S.Type = T;
36007330f729Sjoerg Steps.push_back(S);
36017330f729Sjoerg }
36027330f729Sjoerg
AddFinalCopy(QualType T)36037330f729Sjoerg void InitializationSequence::AddFinalCopy(QualType T) {
36047330f729Sjoerg Step S;
36057330f729Sjoerg S.Kind = SK_FinalCopy;
36067330f729Sjoerg S.Type = T;
36077330f729Sjoerg Steps.push_back(S);
36087330f729Sjoerg }
36097330f729Sjoerg
AddExtraneousCopyToTemporary(QualType T)36107330f729Sjoerg void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
36117330f729Sjoerg Step S;
36127330f729Sjoerg S.Kind = SK_ExtraneousCopyToTemporary;
36137330f729Sjoerg S.Type = T;
36147330f729Sjoerg Steps.push_back(S);
36157330f729Sjoerg }
36167330f729Sjoerg
36177330f729Sjoerg void
AddUserConversionStep(FunctionDecl * Function,DeclAccessPair FoundDecl,QualType T,bool HadMultipleCandidates)36187330f729Sjoerg InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
36197330f729Sjoerg DeclAccessPair FoundDecl,
36207330f729Sjoerg QualType T,
36217330f729Sjoerg bool HadMultipleCandidates) {
36227330f729Sjoerg Step S;
36237330f729Sjoerg S.Kind = SK_UserConversion;
36247330f729Sjoerg S.Type = T;
36257330f729Sjoerg S.Function.HadMultipleCandidates = HadMultipleCandidates;
36267330f729Sjoerg S.Function.Function = Function;
36277330f729Sjoerg S.Function.FoundDecl = FoundDecl;
36287330f729Sjoerg Steps.push_back(S);
36297330f729Sjoerg }
36307330f729Sjoerg
AddQualificationConversionStep(QualType Ty,ExprValueKind VK)36317330f729Sjoerg void InitializationSequence::AddQualificationConversionStep(QualType Ty,
36327330f729Sjoerg ExprValueKind VK) {
36337330f729Sjoerg Step S;
36347330f729Sjoerg S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
36357330f729Sjoerg switch (VK) {
36367330f729Sjoerg case VK_RValue:
36377330f729Sjoerg S.Kind = SK_QualificationConversionRValue;
36387330f729Sjoerg break;
36397330f729Sjoerg case VK_XValue:
36407330f729Sjoerg S.Kind = SK_QualificationConversionXValue;
36417330f729Sjoerg break;
36427330f729Sjoerg case VK_LValue:
36437330f729Sjoerg S.Kind = SK_QualificationConversionLValue;
36447330f729Sjoerg break;
36457330f729Sjoerg }
36467330f729Sjoerg S.Type = Ty;
36477330f729Sjoerg Steps.push_back(S);
36487330f729Sjoerg }
36497330f729Sjoerg
AddFunctionReferenceConversionStep(QualType Ty)3650*e038c9c4Sjoerg void InitializationSequence::AddFunctionReferenceConversionStep(QualType Ty) {
3651*e038c9c4Sjoerg Step S;
3652*e038c9c4Sjoerg S.Kind = SK_FunctionReferenceConversion;
3653*e038c9c4Sjoerg S.Type = Ty;
3654*e038c9c4Sjoerg Steps.push_back(S);
3655*e038c9c4Sjoerg }
3656*e038c9c4Sjoerg
AddAtomicConversionStep(QualType Ty)36577330f729Sjoerg void InitializationSequence::AddAtomicConversionStep(QualType Ty) {
36587330f729Sjoerg Step S;
36597330f729Sjoerg S.Kind = SK_AtomicConversion;
36607330f729Sjoerg S.Type = Ty;
36617330f729Sjoerg Steps.push_back(S);
36627330f729Sjoerg }
36637330f729Sjoerg
AddConversionSequenceStep(const ImplicitConversionSequence & ICS,QualType T,bool TopLevelOfInitList)36647330f729Sjoerg void InitializationSequence::AddConversionSequenceStep(
36657330f729Sjoerg const ImplicitConversionSequence &ICS, QualType T,
36667330f729Sjoerg bool TopLevelOfInitList) {
36677330f729Sjoerg Step S;
36687330f729Sjoerg S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
36697330f729Sjoerg : SK_ConversionSequence;
36707330f729Sjoerg S.Type = T;
36717330f729Sjoerg S.ICS = new ImplicitConversionSequence(ICS);
36727330f729Sjoerg Steps.push_back(S);
36737330f729Sjoerg }
36747330f729Sjoerg
AddListInitializationStep(QualType T)36757330f729Sjoerg void InitializationSequence::AddListInitializationStep(QualType T) {
36767330f729Sjoerg Step S;
36777330f729Sjoerg S.Kind = SK_ListInitialization;
36787330f729Sjoerg S.Type = T;
36797330f729Sjoerg Steps.push_back(S);
36807330f729Sjoerg }
36817330f729Sjoerg
AddConstructorInitializationStep(DeclAccessPair FoundDecl,CXXConstructorDecl * Constructor,QualType T,bool HadMultipleCandidates,bool FromInitList,bool AsInitList)36827330f729Sjoerg void InitializationSequence::AddConstructorInitializationStep(
36837330f729Sjoerg DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T,
36847330f729Sjoerg bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
36857330f729Sjoerg Step S;
36867330f729Sjoerg S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
36877330f729Sjoerg : SK_ConstructorInitializationFromList
36887330f729Sjoerg : SK_ConstructorInitialization;
36897330f729Sjoerg S.Type = T;
36907330f729Sjoerg S.Function.HadMultipleCandidates = HadMultipleCandidates;
36917330f729Sjoerg S.Function.Function = Constructor;
36927330f729Sjoerg S.Function.FoundDecl = FoundDecl;
36937330f729Sjoerg Steps.push_back(S);
36947330f729Sjoerg }
36957330f729Sjoerg
AddZeroInitializationStep(QualType T)36967330f729Sjoerg void InitializationSequence::AddZeroInitializationStep(QualType T) {
36977330f729Sjoerg Step S;
36987330f729Sjoerg S.Kind = SK_ZeroInitialization;
36997330f729Sjoerg S.Type = T;
37007330f729Sjoerg Steps.push_back(S);
37017330f729Sjoerg }
37027330f729Sjoerg
AddCAssignmentStep(QualType T)37037330f729Sjoerg void InitializationSequence::AddCAssignmentStep(QualType T) {
37047330f729Sjoerg Step S;
37057330f729Sjoerg S.Kind = SK_CAssignment;
37067330f729Sjoerg S.Type = T;
37077330f729Sjoerg Steps.push_back(S);
37087330f729Sjoerg }
37097330f729Sjoerg
AddStringInitStep(QualType T)37107330f729Sjoerg void InitializationSequence::AddStringInitStep(QualType T) {
37117330f729Sjoerg Step S;
37127330f729Sjoerg S.Kind = SK_StringInit;
37137330f729Sjoerg S.Type = T;
37147330f729Sjoerg Steps.push_back(S);
37157330f729Sjoerg }
37167330f729Sjoerg
AddObjCObjectConversionStep(QualType T)37177330f729Sjoerg void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
37187330f729Sjoerg Step S;
37197330f729Sjoerg S.Kind = SK_ObjCObjectConversion;
37207330f729Sjoerg S.Type = T;
37217330f729Sjoerg Steps.push_back(S);
37227330f729Sjoerg }
37237330f729Sjoerg
AddArrayInitStep(QualType T,bool IsGNUExtension)37247330f729Sjoerg void InitializationSequence::AddArrayInitStep(QualType T, bool IsGNUExtension) {
37257330f729Sjoerg Step S;
37267330f729Sjoerg S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
37277330f729Sjoerg S.Type = T;
37287330f729Sjoerg Steps.push_back(S);
37297330f729Sjoerg }
37307330f729Sjoerg
AddArrayInitLoopStep(QualType T,QualType EltT)37317330f729Sjoerg void InitializationSequence::AddArrayInitLoopStep(QualType T, QualType EltT) {
37327330f729Sjoerg Step S;
37337330f729Sjoerg S.Kind = SK_ArrayLoopIndex;
37347330f729Sjoerg S.Type = EltT;
37357330f729Sjoerg Steps.insert(Steps.begin(), S);
37367330f729Sjoerg
37377330f729Sjoerg S.Kind = SK_ArrayLoopInit;
37387330f729Sjoerg S.Type = T;
37397330f729Sjoerg Steps.push_back(S);
37407330f729Sjoerg }
37417330f729Sjoerg
AddParenthesizedArrayInitStep(QualType T)37427330f729Sjoerg void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
37437330f729Sjoerg Step S;
37447330f729Sjoerg S.Kind = SK_ParenthesizedArrayInit;
37457330f729Sjoerg S.Type = T;
37467330f729Sjoerg Steps.push_back(S);
37477330f729Sjoerg }
37487330f729Sjoerg
AddPassByIndirectCopyRestoreStep(QualType type,bool shouldCopy)37497330f729Sjoerg void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
37507330f729Sjoerg bool shouldCopy) {
37517330f729Sjoerg Step s;
37527330f729Sjoerg s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
37537330f729Sjoerg : SK_PassByIndirectRestore);
37547330f729Sjoerg s.Type = type;
37557330f729Sjoerg Steps.push_back(s);
37567330f729Sjoerg }
37577330f729Sjoerg
AddProduceObjCObjectStep(QualType T)37587330f729Sjoerg void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
37597330f729Sjoerg Step S;
37607330f729Sjoerg S.Kind = SK_ProduceObjCObject;
37617330f729Sjoerg S.Type = T;
37627330f729Sjoerg Steps.push_back(S);
37637330f729Sjoerg }
37647330f729Sjoerg
AddStdInitializerListConstructionStep(QualType T)37657330f729Sjoerg void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
37667330f729Sjoerg Step S;
37677330f729Sjoerg S.Kind = SK_StdInitializerList;
37687330f729Sjoerg S.Type = T;
37697330f729Sjoerg Steps.push_back(S);
37707330f729Sjoerg }
37717330f729Sjoerg
AddOCLSamplerInitStep(QualType T)37727330f729Sjoerg void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
37737330f729Sjoerg Step S;
37747330f729Sjoerg S.Kind = SK_OCLSamplerInit;
37757330f729Sjoerg S.Type = T;
37767330f729Sjoerg Steps.push_back(S);
37777330f729Sjoerg }
37787330f729Sjoerg
AddOCLZeroOpaqueTypeStep(QualType T)37797330f729Sjoerg void InitializationSequence::AddOCLZeroOpaqueTypeStep(QualType T) {
37807330f729Sjoerg Step S;
37817330f729Sjoerg S.Kind = SK_OCLZeroOpaqueType;
37827330f729Sjoerg S.Type = T;
37837330f729Sjoerg Steps.push_back(S);
37847330f729Sjoerg }
37857330f729Sjoerg
RewrapReferenceInitList(QualType T,InitListExpr * Syntactic)37867330f729Sjoerg void InitializationSequence::RewrapReferenceInitList(QualType T,
37877330f729Sjoerg InitListExpr *Syntactic) {
37887330f729Sjoerg assert(Syntactic->getNumInits() == 1 &&
37897330f729Sjoerg "Can only rewrap trivial init lists.");
37907330f729Sjoerg Step S;
37917330f729Sjoerg S.Kind = SK_UnwrapInitList;
37927330f729Sjoerg S.Type = Syntactic->getInit(0)->getType();
37937330f729Sjoerg Steps.insert(Steps.begin(), S);
37947330f729Sjoerg
37957330f729Sjoerg S.Kind = SK_RewrapInitList;
37967330f729Sjoerg S.Type = T;
37977330f729Sjoerg S.WrappingSyntacticList = Syntactic;
37987330f729Sjoerg Steps.push_back(S);
37997330f729Sjoerg }
38007330f729Sjoerg
SetOverloadFailure(FailureKind Failure,OverloadingResult Result)38017330f729Sjoerg void InitializationSequence::SetOverloadFailure(FailureKind Failure,
38027330f729Sjoerg OverloadingResult Result) {
38037330f729Sjoerg setSequenceKind(FailedSequence);
38047330f729Sjoerg this->Failure = Failure;
38057330f729Sjoerg this->FailedOverloadResult = Result;
38067330f729Sjoerg }
38077330f729Sjoerg
38087330f729Sjoerg //===----------------------------------------------------------------------===//
38097330f729Sjoerg // Attempt initialization
38107330f729Sjoerg //===----------------------------------------------------------------------===//
38117330f729Sjoerg
38127330f729Sjoerg /// Tries to add a zero initializer. Returns true if that worked.
38137330f729Sjoerg static bool
maybeRecoverWithZeroInitialization(Sema & S,InitializationSequence & Sequence,const InitializedEntity & Entity)38147330f729Sjoerg maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence,
38157330f729Sjoerg const InitializedEntity &Entity) {
38167330f729Sjoerg if (Entity.getKind() != InitializedEntity::EK_Variable)
38177330f729Sjoerg return false;
38187330f729Sjoerg
38197330f729Sjoerg VarDecl *VD = cast<VarDecl>(Entity.getDecl());
38207330f729Sjoerg if (VD->getInit() || VD->getEndLoc().isMacroID())
38217330f729Sjoerg return false;
38227330f729Sjoerg
38237330f729Sjoerg QualType VariableTy = VD->getType().getCanonicalType();
38247330f729Sjoerg SourceLocation Loc = S.getLocForEndOfToken(VD->getEndLoc());
38257330f729Sjoerg std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
38267330f729Sjoerg if (!Init.empty()) {
38277330f729Sjoerg Sequence.AddZeroInitializationStep(Entity.getType());
38287330f729Sjoerg Sequence.SetZeroInitializationFixit(Init, Loc);
38297330f729Sjoerg return true;
38307330f729Sjoerg }
38317330f729Sjoerg return false;
38327330f729Sjoerg }
38337330f729Sjoerg
MaybeProduceObjCObject(Sema & S,InitializationSequence & Sequence,const InitializedEntity & Entity)38347330f729Sjoerg static void MaybeProduceObjCObject(Sema &S,
38357330f729Sjoerg InitializationSequence &Sequence,
38367330f729Sjoerg const InitializedEntity &Entity) {
38377330f729Sjoerg if (!S.getLangOpts().ObjCAutoRefCount) return;
38387330f729Sjoerg
38397330f729Sjoerg /// When initializing a parameter, produce the value if it's marked
38407330f729Sjoerg /// __attribute__((ns_consumed)).
38417330f729Sjoerg if (Entity.isParameterKind()) {
38427330f729Sjoerg if (!Entity.isParameterConsumed())
38437330f729Sjoerg return;
38447330f729Sjoerg
38457330f729Sjoerg assert(Entity.getType()->isObjCRetainableType() &&
38467330f729Sjoerg "consuming an object of unretainable type?");
38477330f729Sjoerg Sequence.AddProduceObjCObjectStep(Entity.getType());
38487330f729Sjoerg
38497330f729Sjoerg /// When initializing a return value, if the return type is a
38507330f729Sjoerg /// retainable type, then returns need to immediately retain the
38517330f729Sjoerg /// object. If an autorelease is required, it will be done at the
38527330f729Sjoerg /// last instant.
38537330f729Sjoerg } else if (Entity.getKind() == InitializedEntity::EK_Result ||
38547330f729Sjoerg Entity.getKind() == InitializedEntity::EK_StmtExprResult) {
38557330f729Sjoerg if (!Entity.getType()->isObjCRetainableType())
38567330f729Sjoerg return;
38577330f729Sjoerg
38587330f729Sjoerg Sequence.AddProduceObjCObjectStep(Entity.getType());
38597330f729Sjoerg }
38607330f729Sjoerg }
38617330f729Sjoerg
38627330f729Sjoerg static void TryListInitialization(Sema &S,
38637330f729Sjoerg const InitializedEntity &Entity,
38647330f729Sjoerg const InitializationKind &Kind,
38657330f729Sjoerg InitListExpr *InitList,
38667330f729Sjoerg InitializationSequence &Sequence,
38677330f729Sjoerg bool TreatUnavailableAsInvalid);
38687330f729Sjoerg
38697330f729Sjoerg /// When initializing from init list via constructor, handle
38707330f729Sjoerg /// initialization of an object of type std::initializer_list<T>.
38717330f729Sjoerg ///
38727330f729Sjoerg /// \return true if we have handled initialization of an object of type
38737330f729Sjoerg /// std::initializer_list<T>, false otherwise.
TryInitializerListConstruction(Sema & S,InitListExpr * List,QualType DestType,InitializationSequence & Sequence,bool TreatUnavailableAsInvalid)38747330f729Sjoerg static bool TryInitializerListConstruction(Sema &S,
38757330f729Sjoerg InitListExpr *List,
38767330f729Sjoerg QualType DestType,
38777330f729Sjoerg InitializationSequence &Sequence,
38787330f729Sjoerg bool TreatUnavailableAsInvalid) {
38797330f729Sjoerg QualType E;
38807330f729Sjoerg if (!S.isStdInitializerList(DestType, &E))
38817330f729Sjoerg return false;
38827330f729Sjoerg
38837330f729Sjoerg if (!S.isCompleteType(List->getExprLoc(), E)) {
38847330f729Sjoerg Sequence.setIncompleteTypeFailure(E);
38857330f729Sjoerg return true;
38867330f729Sjoerg }
38877330f729Sjoerg
38887330f729Sjoerg // Try initializing a temporary array from the init list.
38897330f729Sjoerg QualType ArrayType = S.Context.getConstantArrayType(
38907330f729Sjoerg E.withConst(),
38917330f729Sjoerg llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
38927330f729Sjoerg List->getNumInits()),
38937330f729Sjoerg nullptr, clang::ArrayType::Normal, 0);
38947330f729Sjoerg InitializedEntity HiddenArray =
38957330f729Sjoerg InitializedEntity::InitializeTemporary(ArrayType);
38967330f729Sjoerg InitializationKind Kind = InitializationKind::CreateDirectList(
38977330f729Sjoerg List->getExprLoc(), List->getBeginLoc(), List->getEndLoc());
38987330f729Sjoerg TryListInitialization(S, HiddenArray, Kind, List, Sequence,
38997330f729Sjoerg TreatUnavailableAsInvalid);
39007330f729Sjoerg if (Sequence)
39017330f729Sjoerg Sequence.AddStdInitializerListConstructionStep(DestType);
39027330f729Sjoerg return true;
39037330f729Sjoerg }
39047330f729Sjoerg
39057330f729Sjoerg /// Determine if the constructor has the signature of a copy or move
39067330f729Sjoerg /// constructor for the type T of the class in which it was found. That is,
39077330f729Sjoerg /// determine if its first parameter is of type T or reference to (possibly
39087330f729Sjoerg /// cv-qualified) T.
hasCopyOrMoveCtorParam(ASTContext & Ctx,const ConstructorInfo & Info)39097330f729Sjoerg static bool hasCopyOrMoveCtorParam(ASTContext &Ctx,
39107330f729Sjoerg const ConstructorInfo &Info) {
39117330f729Sjoerg if (Info.Constructor->getNumParams() == 0)
39127330f729Sjoerg return false;
39137330f729Sjoerg
39147330f729Sjoerg QualType ParmT =
39157330f729Sjoerg Info.Constructor->getParamDecl(0)->getType().getNonReferenceType();
39167330f729Sjoerg QualType ClassT =
39177330f729Sjoerg Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext()));
39187330f729Sjoerg
39197330f729Sjoerg return Ctx.hasSameUnqualifiedType(ParmT, ClassT);
39207330f729Sjoerg }
39217330f729Sjoerg
39227330f729Sjoerg static OverloadingResult
ResolveConstructorOverload(Sema & S,SourceLocation DeclLoc,MultiExprArg Args,OverloadCandidateSet & CandidateSet,QualType DestType,DeclContext::lookup_result Ctors,OverloadCandidateSet::iterator & Best,bool CopyInitializing,bool AllowExplicit,bool OnlyListConstructors,bool IsListInit,bool SecondStepOfCopyInit=false)39237330f729Sjoerg ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
39247330f729Sjoerg MultiExprArg Args,
39257330f729Sjoerg OverloadCandidateSet &CandidateSet,
39267330f729Sjoerg QualType DestType,
39277330f729Sjoerg DeclContext::lookup_result Ctors,
39287330f729Sjoerg OverloadCandidateSet::iterator &Best,
39297330f729Sjoerg bool CopyInitializing, bool AllowExplicit,
39307330f729Sjoerg bool OnlyListConstructors, bool IsListInit,
39317330f729Sjoerg bool SecondStepOfCopyInit = false) {
39327330f729Sjoerg CandidateSet.clear(OverloadCandidateSet::CSK_InitByConstructor);
39337330f729Sjoerg CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
39347330f729Sjoerg
39357330f729Sjoerg for (NamedDecl *D : Ctors) {
39367330f729Sjoerg auto Info = getConstructorInfo(D);
39377330f729Sjoerg if (!Info.Constructor || Info.Constructor->isInvalidDecl())
39387330f729Sjoerg continue;
39397330f729Sjoerg
39407330f729Sjoerg if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor))
39417330f729Sjoerg continue;
39427330f729Sjoerg
39437330f729Sjoerg // C++11 [over.best.ics]p4:
39447330f729Sjoerg // ... and the constructor or user-defined conversion function is a
39457330f729Sjoerg // candidate by
39467330f729Sjoerg // - 13.3.1.3, when the argument is the temporary in the second step
39477330f729Sjoerg // of a class copy-initialization, or
39487330f729Sjoerg // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
39497330f729Sjoerg // - the second phase of 13.3.1.7 when the initializer list has exactly
39507330f729Sjoerg // one element that is itself an initializer list, and the target is
39517330f729Sjoerg // the first parameter of a constructor of class X, and the conversion
39527330f729Sjoerg // is to X or reference to (possibly cv-qualified X),
39537330f729Sjoerg // user-defined conversion sequences are not considered.
39547330f729Sjoerg bool SuppressUserConversions =
39557330f729Sjoerg SecondStepOfCopyInit ||
39567330f729Sjoerg (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
39577330f729Sjoerg hasCopyOrMoveCtorParam(S.Context, Info));
39587330f729Sjoerg
39597330f729Sjoerg if (Info.ConstructorTmpl)
39607330f729Sjoerg S.AddTemplateOverloadCandidate(
39617330f729Sjoerg Info.ConstructorTmpl, Info.FoundDecl,
39627330f729Sjoerg /*ExplicitArgs*/ nullptr, Args, CandidateSet, SuppressUserConversions,
39637330f729Sjoerg /*PartialOverloading=*/false, AllowExplicit);
39647330f729Sjoerg else {
39657330f729Sjoerg // C++ [over.match.copy]p1:
39667330f729Sjoerg // - When initializing a temporary to be bound to the first parameter
39677330f729Sjoerg // of a constructor [for type T] that takes a reference to possibly
39687330f729Sjoerg // cv-qualified T as its first argument, called with a single
39697330f729Sjoerg // argument in the context of direct-initialization, explicit
39707330f729Sjoerg // conversion functions are also considered.
39717330f729Sjoerg // FIXME: What if a constructor template instantiates to such a signature?
39727330f729Sjoerg bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
39737330f729Sjoerg Args.size() == 1 &&
39747330f729Sjoerg hasCopyOrMoveCtorParam(S.Context, Info);
39757330f729Sjoerg S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
39767330f729Sjoerg CandidateSet, SuppressUserConversions,
39777330f729Sjoerg /*PartialOverloading=*/false, AllowExplicit,
39787330f729Sjoerg AllowExplicitConv);
39797330f729Sjoerg }
39807330f729Sjoerg }
39817330f729Sjoerg
39827330f729Sjoerg // FIXME: Work around a bug in C++17 guaranteed copy elision.
39837330f729Sjoerg //
39847330f729Sjoerg // When initializing an object of class type T by constructor
39857330f729Sjoerg // ([over.match.ctor]) or by list-initialization ([over.match.list])
39867330f729Sjoerg // from a single expression of class type U, conversion functions of
39877330f729Sjoerg // U that convert to the non-reference type cv T are candidates.
39887330f729Sjoerg // Explicit conversion functions are only candidates during
39897330f729Sjoerg // direct-initialization.
39907330f729Sjoerg //
39917330f729Sjoerg // Note: SecondStepOfCopyInit is only ever true in this case when
39927330f729Sjoerg // evaluating whether to produce a C++98 compatibility warning.
39937330f729Sjoerg if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 &&
39947330f729Sjoerg !SecondStepOfCopyInit) {
39957330f729Sjoerg Expr *Initializer = Args[0];
39967330f729Sjoerg auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
39977330f729Sjoerg if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) {
39987330f729Sjoerg const auto &Conversions = SourceRD->getVisibleConversionFunctions();
39997330f729Sjoerg for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
40007330f729Sjoerg NamedDecl *D = *I;
40017330f729Sjoerg CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
40027330f729Sjoerg D = D->getUnderlyingDecl();
40037330f729Sjoerg
40047330f729Sjoerg FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
40057330f729Sjoerg CXXConversionDecl *Conv;
40067330f729Sjoerg if (ConvTemplate)
40077330f729Sjoerg Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
40087330f729Sjoerg else
40097330f729Sjoerg Conv = cast<CXXConversionDecl>(D);
40107330f729Sjoerg
40117330f729Sjoerg if (ConvTemplate)
40127330f729Sjoerg S.AddTemplateConversionCandidate(
40137330f729Sjoerg ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
40147330f729Sjoerg CandidateSet, AllowExplicit, AllowExplicit,
40157330f729Sjoerg /*AllowResultConversion*/ false);
40167330f729Sjoerg else
40177330f729Sjoerg S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
40187330f729Sjoerg DestType, CandidateSet, AllowExplicit,
40197330f729Sjoerg AllowExplicit,
40207330f729Sjoerg /*AllowResultConversion*/ false);
40217330f729Sjoerg }
40227330f729Sjoerg }
40237330f729Sjoerg }
40247330f729Sjoerg
40257330f729Sjoerg // Perform overload resolution and return the result.
40267330f729Sjoerg return CandidateSet.BestViableFunction(S, DeclLoc, Best);
40277330f729Sjoerg }
40287330f729Sjoerg
40297330f729Sjoerg /// Attempt initialization by constructor (C++ [dcl.init]), which
40307330f729Sjoerg /// enumerates the constructors of the initialized entity and performs overload
40317330f729Sjoerg /// resolution to select the best.
40327330f729Sjoerg /// \param DestType The destination class type.
40337330f729Sjoerg /// \param DestArrayType The destination type, which is either DestType or
40347330f729Sjoerg /// a (possibly multidimensional) array of DestType.
40357330f729Sjoerg /// \param IsListInit Is this list-initialization?
40367330f729Sjoerg /// \param IsInitListCopy Is this non-list-initialization resulting from a
40377330f729Sjoerg /// list-initialization from {x} where x is the same
40387330f729Sjoerg /// type as the entity?
TryConstructorInitialization(Sema & S,const InitializedEntity & Entity,const InitializationKind & Kind,MultiExprArg Args,QualType DestType,QualType DestArrayType,InitializationSequence & Sequence,bool IsListInit=false,bool IsInitListCopy=false)40397330f729Sjoerg static void TryConstructorInitialization(Sema &S,
40407330f729Sjoerg const InitializedEntity &Entity,
40417330f729Sjoerg const InitializationKind &Kind,
40427330f729Sjoerg MultiExprArg Args, QualType DestType,
40437330f729Sjoerg QualType DestArrayType,
40447330f729Sjoerg InitializationSequence &Sequence,
40457330f729Sjoerg bool IsListInit = false,
40467330f729Sjoerg bool IsInitListCopy = false) {
40477330f729Sjoerg assert(((!IsListInit && !IsInitListCopy) ||
40487330f729Sjoerg (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
40497330f729Sjoerg "IsListInit/IsInitListCopy must come with a single initializer list "
40507330f729Sjoerg "argument.");
40517330f729Sjoerg InitListExpr *ILE =
40527330f729Sjoerg (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr;
40537330f729Sjoerg MultiExprArg UnwrappedArgs =
40547330f729Sjoerg ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
40557330f729Sjoerg
40567330f729Sjoerg // The type we're constructing needs to be complete.
40577330f729Sjoerg if (!S.isCompleteType(Kind.getLocation(), DestType)) {
40587330f729Sjoerg Sequence.setIncompleteTypeFailure(DestType);
40597330f729Sjoerg return;
40607330f729Sjoerg }
40617330f729Sjoerg
40627330f729Sjoerg // C++17 [dcl.init]p17:
40637330f729Sjoerg // - If the initializer expression is a prvalue and the cv-unqualified
40647330f729Sjoerg // version of the source type is the same class as the class of the
40657330f729Sjoerg // destination, the initializer expression is used to initialize the
40667330f729Sjoerg // destination object.
40677330f729Sjoerg // Per DR (no number yet), this does not apply when initializing a base
40687330f729Sjoerg // class or delegating to another constructor from a mem-initializer.
40697330f729Sjoerg // ObjC++: Lambda captured by the block in the lambda to block conversion
40707330f729Sjoerg // should avoid copy elision.
40717330f729Sjoerg if (S.getLangOpts().CPlusPlus17 &&
40727330f729Sjoerg Entity.getKind() != InitializedEntity::EK_Base &&
40737330f729Sjoerg Entity.getKind() != InitializedEntity::EK_Delegating &&
40747330f729Sjoerg Entity.getKind() !=
40757330f729Sjoerg InitializedEntity::EK_LambdaToBlockConversionBlockElement &&
40767330f729Sjoerg UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isRValue() &&
40777330f729Sjoerg S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {
40787330f729Sjoerg // Convert qualifications if necessary.
40797330f729Sjoerg Sequence.AddQualificationConversionStep(DestType, VK_RValue);
40807330f729Sjoerg if (ILE)
40817330f729Sjoerg Sequence.RewrapReferenceInitList(DestType, ILE);
40827330f729Sjoerg return;
40837330f729Sjoerg }
40847330f729Sjoerg
40857330f729Sjoerg const RecordType *DestRecordType = DestType->getAs<RecordType>();
40867330f729Sjoerg assert(DestRecordType && "Constructor initialization requires record type");
40877330f729Sjoerg CXXRecordDecl *DestRecordDecl
40887330f729Sjoerg = cast<CXXRecordDecl>(DestRecordType->getDecl());
40897330f729Sjoerg
40907330f729Sjoerg // Build the candidate set directly in the initialization sequence
40917330f729Sjoerg // structure, so that it will persist if we fail.
40927330f729Sjoerg OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
40937330f729Sjoerg
40947330f729Sjoerg // Determine whether we are allowed to call explicit constructors or
40957330f729Sjoerg // explicit conversion operators.
40967330f729Sjoerg bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
40977330f729Sjoerg bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
40987330f729Sjoerg
40997330f729Sjoerg // - Otherwise, if T is a class type, constructors are considered. The
41007330f729Sjoerg // applicable constructors are enumerated, and the best one is chosen
41017330f729Sjoerg // through overload resolution.
41027330f729Sjoerg DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
41037330f729Sjoerg
41047330f729Sjoerg OverloadingResult Result = OR_No_Viable_Function;
41057330f729Sjoerg OverloadCandidateSet::iterator Best;
41067330f729Sjoerg bool AsInitializerList = false;
41077330f729Sjoerg
41087330f729Sjoerg // C++11 [over.match.list]p1, per DR1467:
41097330f729Sjoerg // When objects of non-aggregate type T are list-initialized, such that
41107330f729Sjoerg // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
41117330f729Sjoerg // according to the rules in this section, overload resolution selects
41127330f729Sjoerg // the constructor in two phases:
41137330f729Sjoerg //
41147330f729Sjoerg // - Initially, the candidate functions are the initializer-list
41157330f729Sjoerg // constructors of the class T and the argument list consists of the
41167330f729Sjoerg // initializer list as a single argument.
41177330f729Sjoerg if (IsListInit) {
41187330f729Sjoerg AsInitializerList = true;
41197330f729Sjoerg
41207330f729Sjoerg // If the initializer list has no elements and T has a default constructor,
41217330f729Sjoerg // the first phase is omitted.
4122*e038c9c4Sjoerg if (!(UnwrappedArgs.empty() && S.LookupDefaultConstructor(DestRecordDecl)))
41237330f729Sjoerg Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
41247330f729Sjoerg CandidateSet, DestType, Ctors, Best,
41257330f729Sjoerg CopyInitialization, AllowExplicit,
41267330f729Sjoerg /*OnlyListConstructors=*/true,
41277330f729Sjoerg IsListInit);
41287330f729Sjoerg }
41297330f729Sjoerg
41307330f729Sjoerg // C++11 [over.match.list]p1:
41317330f729Sjoerg // - If no viable initializer-list constructor is found, overload resolution
41327330f729Sjoerg // is performed again, where the candidate functions are all the
41337330f729Sjoerg // constructors of the class T and the argument list consists of the
41347330f729Sjoerg // elements of the initializer list.
41357330f729Sjoerg if (Result == OR_No_Viable_Function) {
41367330f729Sjoerg AsInitializerList = false;
41377330f729Sjoerg Result = ResolveConstructorOverload(S, Kind.getLocation(), UnwrappedArgs,
41387330f729Sjoerg CandidateSet, DestType, Ctors, Best,
41397330f729Sjoerg CopyInitialization, AllowExplicit,
41407330f729Sjoerg /*OnlyListConstructors=*/false,
41417330f729Sjoerg IsListInit);
41427330f729Sjoerg }
41437330f729Sjoerg if (Result) {
4144*e038c9c4Sjoerg Sequence.SetOverloadFailure(
4145*e038c9c4Sjoerg IsListInit ? InitializationSequence::FK_ListConstructorOverloadFailed
4146*e038c9c4Sjoerg : InitializationSequence::FK_ConstructorOverloadFailed,
41477330f729Sjoerg Result);
4148*e038c9c4Sjoerg
4149*e038c9c4Sjoerg if (Result != OR_Deleted)
41507330f729Sjoerg return;
41517330f729Sjoerg }
41527330f729Sjoerg
41537330f729Sjoerg bool HadMultipleCandidates = (CandidateSet.size() > 1);
41547330f729Sjoerg
41557330f729Sjoerg // In C++17, ResolveConstructorOverload can select a conversion function
41567330f729Sjoerg // instead of a constructor.
41577330f729Sjoerg if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
41587330f729Sjoerg // Add the user-defined conversion step that calls the conversion function.
41597330f729Sjoerg QualType ConvType = CD->getConversionType();
41607330f729Sjoerg assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&
41617330f729Sjoerg "should not have selected this conversion function");
41627330f729Sjoerg Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
41637330f729Sjoerg HadMultipleCandidates);
41647330f729Sjoerg if (!S.Context.hasSameType(ConvType, DestType))
41657330f729Sjoerg Sequence.AddQualificationConversionStep(DestType, VK_RValue);
41667330f729Sjoerg if (IsListInit)
41677330f729Sjoerg Sequence.RewrapReferenceInitList(Entity.getType(), ILE);
41687330f729Sjoerg return;
41697330f729Sjoerg }
41707330f729Sjoerg
4171*e038c9c4Sjoerg CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
4172*e038c9c4Sjoerg if (Result != OR_Deleted) {
41737330f729Sjoerg // C++11 [dcl.init]p6:
41747330f729Sjoerg // If a program calls for the default initialization of an object
41757330f729Sjoerg // of a const-qualified type T, T shall be a class type with a
41767330f729Sjoerg // user-provided default constructor.
41777330f729Sjoerg // C++ core issue 253 proposal:
41787330f729Sjoerg // If the implicit default constructor initializes all subobjects, no
41797330f729Sjoerg // initializer should be required.
4180*e038c9c4Sjoerg // The 253 proposal is for example needed to process libstdc++ headers
4181*e038c9c4Sjoerg // in 5.x.
41827330f729Sjoerg if (Kind.getKind() == InitializationKind::IK_Default &&
41837330f729Sjoerg Entity.getType().isConstQualified()) {
41847330f729Sjoerg if (!CtorDecl->getParent()->allowConstDefaultInit()) {
41857330f729Sjoerg if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
41867330f729Sjoerg Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
41877330f729Sjoerg return;
41887330f729Sjoerg }
41897330f729Sjoerg }
41907330f729Sjoerg
41917330f729Sjoerg // C++11 [over.match.list]p1:
41927330f729Sjoerg // In copy-list-initialization, if an explicit constructor is chosen, the
41937330f729Sjoerg // initializer is ill-formed.
41947330f729Sjoerg if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
41957330f729Sjoerg Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
41967330f729Sjoerg return;
41977330f729Sjoerg }
4198*e038c9c4Sjoerg }
4199*e038c9c4Sjoerg
4200*e038c9c4Sjoerg // [class.copy.elision]p3:
4201*e038c9c4Sjoerg // In some copy-initialization contexts, a two-stage overload resolution
4202*e038c9c4Sjoerg // is performed.
4203*e038c9c4Sjoerg // If the first overload resolution selects a deleted function, we also
4204*e038c9c4Sjoerg // need the initialization sequence to decide whether to perform the second
4205*e038c9c4Sjoerg // overload resolution.
4206*e038c9c4Sjoerg // For deleted functions in other contexts, there is no need to get the
4207*e038c9c4Sjoerg // initialization sequence.
4208*e038c9c4Sjoerg if (Result == OR_Deleted && Kind.getKind() != InitializationKind::IK_Copy)
4209*e038c9c4Sjoerg return;
42107330f729Sjoerg
42117330f729Sjoerg // Add the constructor initialization step. Any cv-qualification conversion is
42127330f729Sjoerg // subsumed by the initialization.
42137330f729Sjoerg Sequence.AddConstructorInitializationStep(
42147330f729Sjoerg Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
42157330f729Sjoerg IsListInit | IsInitListCopy, AsInitializerList);
42167330f729Sjoerg }
42177330f729Sjoerg
42187330f729Sjoerg static bool
ResolveOverloadedFunctionForReferenceBinding(Sema & S,Expr * Initializer,QualType & SourceType,QualType & UnqualifiedSourceType,QualType UnqualifiedTargetType,InitializationSequence & Sequence)42197330f729Sjoerg ResolveOverloadedFunctionForReferenceBinding(Sema &S,
42207330f729Sjoerg Expr *Initializer,
42217330f729Sjoerg QualType &SourceType,
42227330f729Sjoerg QualType &UnqualifiedSourceType,
42237330f729Sjoerg QualType UnqualifiedTargetType,
42247330f729Sjoerg InitializationSequence &Sequence) {
42257330f729Sjoerg if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
42267330f729Sjoerg S.Context.OverloadTy) {
42277330f729Sjoerg DeclAccessPair Found;
42287330f729Sjoerg bool HadMultipleCandidates = false;
42297330f729Sjoerg if (FunctionDecl *Fn
42307330f729Sjoerg = S.ResolveAddressOfOverloadedFunction(Initializer,
42317330f729Sjoerg UnqualifiedTargetType,
42327330f729Sjoerg false, Found,
42337330f729Sjoerg &HadMultipleCandidates)) {
42347330f729Sjoerg Sequence.AddAddressOverloadResolutionStep(Fn, Found,
42357330f729Sjoerg HadMultipleCandidates);
42367330f729Sjoerg SourceType = Fn->getType();
42377330f729Sjoerg UnqualifiedSourceType = SourceType.getUnqualifiedType();
42387330f729Sjoerg } else if (!UnqualifiedTargetType->isRecordType()) {
42397330f729Sjoerg Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
42407330f729Sjoerg return true;
42417330f729Sjoerg }
42427330f729Sjoerg }
42437330f729Sjoerg return false;
42447330f729Sjoerg }
42457330f729Sjoerg
42467330f729Sjoerg static void TryReferenceInitializationCore(Sema &S,
42477330f729Sjoerg const InitializedEntity &Entity,
42487330f729Sjoerg const InitializationKind &Kind,
42497330f729Sjoerg Expr *Initializer,
42507330f729Sjoerg QualType cv1T1, QualType T1,
42517330f729Sjoerg Qualifiers T1Quals,
42527330f729Sjoerg QualType cv2T2, QualType T2,
42537330f729Sjoerg Qualifiers T2Quals,
42547330f729Sjoerg InitializationSequence &Sequence);
42557330f729Sjoerg
42567330f729Sjoerg static void TryValueInitialization(Sema &S,
42577330f729Sjoerg const InitializedEntity &Entity,
42587330f729Sjoerg const InitializationKind &Kind,
42597330f729Sjoerg InitializationSequence &Sequence,
42607330f729Sjoerg InitListExpr *InitList = nullptr);
42617330f729Sjoerg
42627330f729Sjoerg /// Attempt list initialization of a reference.
TryReferenceListInitialization(Sema & S,const InitializedEntity & Entity,const InitializationKind & Kind,InitListExpr * InitList,InitializationSequence & Sequence,bool TreatUnavailableAsInvalid)42637330f729Sjoerg static void TryReferenceListInitialization(Sema &S,
42647330f729Sjoerg const InitializedEntity &Entity,
42657330f729Sjoerg const InitializationKind &Kind,
42667330f729Sjoerg InitListExpr *InitList,
42677330f729Sjoerg InitializationSequence &Sequence,
42687330f729Sjoerg bool TreatUnavailableAsInvalid) {
42697330f729Sjoerg // First, catch C++03 where this isn't possible.
42707330f729Sjoerg if (!S.getLangOpts().CPlusPlus11) {
42717330f729Sjoerg Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
42727330f729Sjoerg return;
42737330f729Sjoerg }
42747330f729Sjoerg // Can't reference initialize a compound literal.
42757330f729Sjoerg if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) {
42767330f729Sjoerg Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
42777330f729Sjoerg return;
42787330f729Sjoerg }
42797330f729Sjoerg
42807330f729Sjoerg QualType DestType = Entity.getType();
42817330f729Sjoerg QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
42827330f729Sjoerg Qualifiers T1Quals;
42837330f729Sjoerg QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
42847330f729Sjoerg
42857330f729Sjoerg // Reference initialization via an initializer list works thus:
42867330f729Sjoerg // If the initializer list consists of a single element that is
42877330f729Sjoerg // reference-related to the referenced type, bind directly to that element
42887330f729Sjoerg // (possibly creating temporaries).
42897330f729Sjoerg // Otherwise, initialize a temporary with the initializer list and
42907330f729Sjoerg // bind to that.
42917330f729Sjoerg if (InitList->getNumInits() == 1) {
42927330f729Sjoerg Expr *Initializer = InitList->getInit(0);
4293*e038c9c4Sjoerg QualType cv2T2 = S.getCompletedType(Initializer);
42947330f729Sjoerg Qualifiers T2Quals;
42957330f729Sjoerg QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
42967330f729Sjoerg
42977330f729Sjoerg // If this fails, creating a temporary wouldn't work either.
42987330f729Sjoerg if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
42997330f729Sjoerg T1, Sequence))
43007330f729Sjoerg return;
43017330f729Sjoerg
43027330f729Sjoerg SourceLocation DeclLoc = Initializer->getBeginLoc();
43037330f729Sjoerg Sema::ReferenceCompareResult RefRelationship
4304*e038c9c4Sjoerg = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2);
43057330f729Sjoerg if (RefRelationship >= Sema::Ref_Related) {
43067330f729Sjoerg // Try to bind the reference here.
43077330f729Sjoerg TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
43087330f729Sjoerg T1Quals, cv2T2, T2, T2Quals, Sequence);
43097330f729Sjoerg if (Sequence)
43107330f729Sjoerg Sequence.RewrapReferenceInitList(cv1T1, InitList);
43117330f729Sjoerg return;
43127330f729Sjoerg }
43137330f729Sjoerg
43147330f729Sjoerg // Update the initializer if we've resolved an overloaded function.
43157330f729Sjoerg if (Sequence.step_begin() != Sequence.step_end())
43167330f729Sjoerg Sequence.RewrapReferenceInitList(cv1T1, InitList);
43177330f729Sjoerg }
4318*e038c9c4Sjoerg // Perform address space compatibility check.
4319*e038c9c4Sjoerg QualType cv1T1IgnoreAS = cv1T1;
4320*e038c9c4Sjoerg if (T1Quals.hasAddressSpace()) {
4321*e038c9c4Sjoerg Qualifiers T2Quals;
4322*e038c9c4Sjoerg (void)S.Context.getUnqualifiedArrayType(InitList->getType(), T2Quals);
4323*e038c9c4Sjoerg if (!T1Quals.isAddressSpaceSupersetOf(T2Quals)) {
4324*e038c9c4Sjoerg Sequence.SetFailed(
4325*e038c9c4Sjoerg InitializationSequence::FK_ReferenceInitDropsQualifiers);
4326*e038c9c4Sjoerg return;
4327*e038c9c4Sjoerg }
4328*e038c9c4Sjoerg // Ignore address space of reference type at this point and perform address
4329*e038c9c4Sjoerg // space conversion after the reference binding step.
4330*e038c9c4Sjoerg cv1T1IgnoreAS =
4331*e038c9c4Sjoerg S.Context.getQualifiedType(T1, T1Quals.withoutAddressSpace());
4332*e038c9c4Sjoerg }
43337330f729Sjoerg // Not reference-related. Create a temporary and bind to that.
4334*e038c9c4Sjoerg InitializedEntity TempEntity =
4335*e038c9c4Sjoerg InitializedEntity::InitializeTemporary(cv1T1IgnoreAS);
43367330f729Sjoerg
43377330f729Sjoerg TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
43387330f729Sjoerg TreatUnavailableAsInvalid);
43397330f729Sjoerg if (Sequence) {
43407330f729Sjoerg if (DestType->isRValueReferenceType() ||
4341*e038c9c4Sjoerg (T1Quals.hasConst() && !T1Quals.hasVolatile())) {
4342*e038c9c4Sjoerg Sequence.AddReferenceBindingStep(cv1T1IgnoreAS,
4343*e038c9c4Sjoerg /*BindingTemporary=*/true);
4344*e038c9c4Sjoerg if (T1Quals.hasAddressSpace())
4345*e038c9c4Sjoerg Sequence.AddQualificationConversionStep(
4346*e038c9c4Sjoerg cv1T1, DestType->isRValueReferenceType() ? VK_XValue : VK_LValue);
4347*e038c9c4Sjoerg } else
43487330f729Sjoerg Sequence.SetFailed(
43497330f729Sjoerg InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
43507330f729Sjoerg }
43517330f729Sjoerg }
43527330f729Sjoerg
43537330f729Sjoerg /// Attempt list initialization (C++0x [dcl.init.list])
TryListInitialization(Sema & S,const InitializedEntity & Entity,const InitializationKind & Kind,InitListExpr * InitList,InitializationSequence & Sequence,bool TreatUnavailableAsInvalid)43547330f729Sjoerg static void TryListInitialization(Sema &S,
43557330f729Sjoerg const InitializedEntity &Entity,
43567330f729Sjoerg const InitializationKind &Kind,
43577330f729Sjoerg InitListExpr *InitList,
43587330f729Sjoerg InitializationSequence &Sequence,
43597330f729Sjoerg bool TreatUnavailableAsInvalid) {
43607330f729Sjoerg QualType DestType = Entity.getType();
43617330f729Sjoerg
43627330f729Sjoerg // C++ doesn't allow scalar initialization with more than one argument.
43637330f729Sjoerg // But C99 complex numbers are scalars and it makes sense there.
43647330f729Sjoerg if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
43657330f729Sjoerg !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
43667330f729Sjoerg Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
43677330f729Sjoerg return;
43687330f729Sjoerg }
43697330f729Sjoerg if (DestType->isReferenceType()) {
43707330f729Sjoerg TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
43717330f729Sjoerg TreatUnavailableAsInvalid);
43727330f729Sjoerg return;
43737330f729Sjoerg }
43747330f729Sjoerg
43757330f729Sjoerg if (DestType->isRecordType() &&
43767330f729Sjoerg !S.isCompleteType(InitList->getBeginLoc(), DestType)) {
43777330f729Sjoerg Sequence.setIncompleteTypeFailure(DestType);
43787330f729Sjoerg return;
43797330f729Sjoerg }
43807330f729Sjoerg
43817330f729Sjoerg // C++11 [dcl.init.list]p3, per DR1467:
43827330f729Sjoerg // - If T is a class type and the initializer list has a single element of
43837330f729Sjoerg // type cv U, where U is T or a class derived from T, the object is
43847330f729Sjoerg // initialized from that element (by copy-initialization for
43857330f729Sjoerg // copy-list-initialization, or by direct-initialization for
43867330f729Sjoerg // direct-list-initialization).
43877330f729Sjoerg // - Otherwise, if T is a character array and the initializer list has a
43887330f729Sjoerg // single element that is an appropriately-typed string literal
43897330f729Sjoerg // (8.5.2 [dcl.init.string]), initialization is performed as described
43907330f729Sjoerg // in that section.
43917330f729Sjoerg // - Otherwise, if T is an aggregate, [...] (continue below).
43927330f729Sjoerg if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1) {
43937330f729Sjoerg if (DestType->isRecordType()) {
43947330f729Sjoerg QualType InitType = InitList->getInit(0)->getType();
43957330f729Sjoerg if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
43967330f729Sjoerg S.IsDerivedFrom(InitList->getBeginLoc(), InitType, DestType)) {
43977330f729Sjoerg Expr *InitListAsExpr = InitList;
43987330f729Sjoerg TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
43997330f729Sjoerg DestType, Sequence,
44007330f729Sjoerg /*InitListSyntax*/false,
44017330f729Sjoerg /*IsInitListCopy*/true);
44027330f729Sjoerg return;
44037330f729Sjoerg }
44047330f729Sjoerg }
44057330f729Sjoerg if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
44067330f729Sjoerg Expr *SubInit[1] = {InitList->getInit(0)};
44077330f729Sjoerg if (!isa<VariableArrayType>(DestAT) &&
44087330f729Sjoerg IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
44097330f729Sjoerg InitializationKind SubKind =
44107330f729Sjoerg Kind.getKind() == InitializationKind::IK_DirectList
44117330f729Sjoerg ? InitializationKind::CreateDirect(Kind.getLocation(),
44127330f729Sjoerg InitList->getLBraceLoc(),
44137330f729Sjoerg InitList->getRBraceLoc())
44147330f729Sjoerg : Kind;
44157330f729Sjoerg Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
44167330f729Sjoerg /*TopLevelOfInitList*/ true,
44177330f729Sjoerg TreatUnavailableAsInvalid);
44187330f729Sjoerg
44197330f729Sjoerg // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
44207330f729Sjoerg // the element is not an appropriately-typed string literal, in which
44217330f729Sjoerg // case we should proceed as in C++11 (below).
44227330f729Sjoerg if (Sequence) {
44237330f729Sjoerg Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
44247330f729Sjoerg return;
44257330f729Sjoerg }
44267330f729Sjoerg }
44277330f729Sjoerg }
44287330f729Sjoerg }
44297330f729Sjoerg
44307330f729Sjoerg // C++11 [dcl.init.list]p3:
44317330f729Sjoerg // - If T is an aggregate, aggregate initialization is performed.
44327330f729Sjoerg if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
44337330f729Sjoerg (S.getLangOpts().CPlusPlus11 &&
44347330f729Sjoerg S.isStdInitializerList(DestType, nullptr))) {
44357330f729Sjoerg if (S.getLangOpts().CPlusPlus11) {
44367330f729Sjoerg // - Otherwise, if the initializer list has no elements and T is a
44377330f729Sjoerg // class type with a default constructor, the object is
44387330f729Sjoerg // value-initialized.
44397330f729Sjoerg if (InitList->getNumInits() == 0) {
44407330f729Sjoerg CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
4441*e038c9c4Sjoerg if (S.LookupDefaultConstructor(RD)) {
44427330f729Sjoerg TryValueInitialization(S, Entity, Kind, Sequence, InitList);
44437330f729Sjoerg return;
44447330f729Sjoerg }
44457330f729Sjoerg }
44467330f729Sjoerg
44477330f729Sjoerg // - Otherwise, if T is a specialization of std::initializer_list<E>,
44487330f729Sjoerg // an initializer_list object constructed [...]
44497330f729Sjoerg if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
44507330f729Sjoerg TreatUnavailableAsInvalid))
44517330f729Sjoerg return;
44527330f729Sjoerg
44537330f729Sjoerg // - Otherwise, if T is a class type, constructors are considered.
44547330f729Sjoerg Expr *InitListAsExpr = InitList;
44557330f729Sjoerg TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
44567330f729Sjoerg DestType, Sequence, /*InitListSyntax*/true);
44577330f729Sjoerg } else
44587330f729Sjoerg Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
44597330f729Sjoerg return;
44607330f729Sjoerg }
44617330f729Sjoerg
44627330f729Sjoerg if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
44637330f729Sjoerg InitList->getNumInits() == 1) {
44647330f729Sjoerg Expr *E = InitList->getInit(0);
44657330f729Sjoerg
44667330f729Sjoerg // - Otherwise, if T is an enumeration with a fixed underlying type,
44677330f729Sjoerg // the initializer-list has a single element v, and the initialization
44687330f729Sjoerg // is direct-list-initialization, the object is initialized with the
44697330f729Sjoerg // value T(v); if a narrowing conversion is required to convert v to
44707330f729Sjoerg // the underlying type of T, the program is ill-formed.
44717330f729Sjoerg auto *ET = DestType->getAs<EnumType>();
44727330f729Sjoerg if (S.getLangOpts().CPlusPlus17 &&
44737330f729Sjoerg Kind.getKind() == InitializationKind::IK_DirectList &&
44747330f729Sjoerg ET && ET->getDecl()->isFixed() &&
44757330f729Sjoerg !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
44767330f729Sjoerg (E->getType()->isIntegralOrEnumerationType() ||
44777330f729Sjoerg E->getType()->isFloatingType())) {
44787330f729Sjoerg // There are two ways that T(v) can work when T is an enumeration type.
44797330f729Sjoerg // If there is either an implicit conversion sequence from v to T or
44807330f729Sjoerg // a conversion function that can convert from v to T, then we use that.
44817330f729Sjoerg // Otherwise, if v is of integral, enumeration, or floating-point type,
44827330f729Sjoerg // it is converted to the enumeration type via its underlying type.
44837330f729Sjoerg // There is no overlap possible between these two cases (except when the
44847330f729Sjoerg // source value is already of the destination type), and the first
44857330f729Sjoerg // case is handled by the general case for single-element lists below.
44867330f729Sjoerg ImplicitConversionSequence ICS;
44877330f729Sjoerg ICS.setStandard();
44887330f729Sjoerg ICS.Standard.setAsIdentityConversion();
44897330f729Sjoerg if (!E->isRValue())
44907330f729Sjoerg ICS.Standard.First = ICK_Lvalue_To_Rvalue;
44917330f729Sjoerg // If E is of a floating-point type, then the conversion is ill-formed
44927330f729Sjoerg // due to narrowing, but go through the motions in order to produce the
44937330f729Sjoerg // right diagnostic.
44947330f729Sjoerg ICS.Standard.Second = E->getType()->isFloatingType()
44957330f729Sjoerg ? ICK_Floating_Integral
44967330f729Sjoerg : ICK_Integral_Conversion;
44977330f729Sjoerg ICS.Standard.setFromType(E->getType());
44987330f729Sjoerg ICS.Standard.setToType(0, E->getType());
44997330f729Sjoerg ICS.Standard.setToType(1, DestType);
45007330f729Sjoerg ICS.Standard.setToType(2, DestType);
45017330f729Sjoerg Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
45027330f729Sjoerg /*TopLevelOfInitList*/true);
45037330f729Sjoerg Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
45047330f729Sjoerg return;
45057330f729Sjoerg }
45067330f729Sjoerg
45077330f729Sjoerg // - Otherwise, if the initializer list has a single element of type E
45087330f729Sjoerg // [...references are handled above...], the object or reference is
45097330f729Sjoerg // initialized from that element (by copy-initialization for
45107330f729Sjoerg // copy-list-initialization, or by direct-initialization for
45117330f729Sjoerg // direct-list-initialization); if a narrowing conversion is required
45127330f729Sjoerg // to convert the element to T, the program is ill-formed.
45137330f729Sjoerg //
45147330f729Sjoerg // Per core-24034, this is direct-initialization if we were performing
45157330f729Sjoerg // direct-list-initialization and copy-initialization otherwise.
45167330f729Sjoerg // We can't use InitListChecker for this, because it always performs
45177330f729Sjoerg // copy-initialization. This only matters if we might use an 'explicit'
4518*e038c9c4Sjoerg // conversion operator, or for the special case conversion of nullptr_t to
4519*e038c9c4Sjoerg // bool, so we only need to handle those cases.
4520*e038c9c4Sjoerg //
4521*e038c9c4Sjoerg // FIXME: Why not do this in all cases?
4522*e038c9c4Sjoerg Expr *Init = InitList->getInit(0);
4523*e038c9c4Sjoerg if (Init->getType()->isRecordType() ||
4524*e038c9c4Sjoerg (Init->getType()->isNullPtrType() && DestType->isBooleanType())) {
45257330f729Sjoerg InitializationKind SubKind =
45267330f729Sjoerg Kind.getKind() == InitializationKind::IK_DirectList
45277330f729Sjoerg ? InitializationKind::CreateDirect(Kind.getLocation(),
45287330f729Sjoerg InitList->getLBraceLoc(),
45297330f729Sjoerg InitList->getRBraceLoc())
45307330f729Sjoerg : Kind;
4531*e038c9c4Sjoerg Expr *SubInit[1] = { Init };
45327330f729Sjoerg Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
45337330f729Sjoerg /*TopLevelOfInitList*/true,
45347330f729Sjoerg TreatUnavailableAsInvalid);
45357330f729Sjoerg if (Sequence)
45367330f729Sjoerg Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
45377330f729Sjoerg return;
45387330f729Sjoerg }
45397330f729Sjoerg }
45407330f729Sjoerg
45417330f729Sjoerg InitListChecker CheckInitList(S, Entity, InitList,
45427330f729Sjoerg DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
45437330f729Sjoerg if (CheckInitList.HadError()) {
45447330f729Sjoerg Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
45457330f729Sjoerg return;
45467330f729Sjoerg }
45477330f729Sjoerg
45487330f729Sjoerg // Add the list initialization step with the built init list.
45497330f729Sjoerg Sequence.AddListInitializationStep(DestType);
45507330f729Sjoerg }
45517330f729Sjoerg
45527330f729Sjoerg /// Try a reference initialization that involves calling a conversion
45537330f729Sjoerg /// function.
TryRefInitWithConversionFunction(Sema & S,const InitializedEntity & Entity,const InitializationKind & Kind,Expr * Initializer,bool AllowRValues,bool IsLValueRef,InitializationSequence & Sequence)45547330f729Sjoerg static OverloadingResult TryRefInitWithConversionFunction(
45557330f729Sjoerg Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
45567330f729Sjoerg Expr *Initializer, bool AllowRValues, bool IsLValueRef,
45577330f729Sjoerg InitializationSequence &Sequence) {
45587330f729Sjoerg QualType DestType = Entity.getType();
45597330f729Sjoerg QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
45607330f729Sjoerg QualType T1 = cv1T1.getUnqualifiedType();
45617330f729Sjoerg QualType cv2T2 = Initializer->getType();
45627330f729Sjoerg QualType T2 = cv2T2.getUnqualifiedType();
45637330f729Sjoerg
4564*e038c9c4Sjoerg assert(!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2) &&
45657330f729Sjoerg "Must have incompatible references when binding via conversion");
45667330f729Sjoerg
45677330f729Sjoerg // Build the candidate set directly in the initialization sequence
45687330f729Sjoerg // structure, so that it will persist if we fail.
45697330f729Sjoerg OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
45707330f729Sjoerg CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
45717330f729Sjoerg
45727330f729Sjoerg // Determine whether we are allowed to call explicit conversion operators.
45737330f729Sjoerg // Note that none of [over.match.copy], [over.match.conv], nor
45747330f729Sjoerg // [over.match.ref] permit an explicit constructor to be chosen when
45757330f729Sjoerg // initializing a reference, not even for direct-initialization.
45767330f729Sjoerg bool AllowExplicitCtors = false;
45777330f729Sjoerg bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
45787330f729Sjoerg
45797330f729Sjoerg const RecordType *T1RecordType = nullptr;
45807330f729Sjoerg if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
45817330f729Sjoerg S.isCompleteType(Kind.getLocation(), T1)) {
45827330f729Sjoerg // The type we're converting to is a class type. Enumerate its constructors
45837330f729Sjoerg // to see if there is a suitable conversion.
45847330f729Sjoerg CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
45857330f729Sjoerg
45867330f729Sjoerg for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
45877330f729Sjoerg auto Info = getConstructorInfo(D);
45887330f729Sjoerg if (!Info.Constructor)
45897330f729Sjoerg continue;
45907330f729Sjoerg
45917330f729Sjoerg if (!Info.Constructor->isInvalidDecl() &&
4592*e038c9c4Sjoerg Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
45937330f729Sjoerg if (Info.ConstructorTmpl)
45947330f729Sjoerg S.AddTemplateOverloadCandidate(
45957330f729Sjoerg Info.ConstructorTmpl, Info.FoundDecl,
45967330f729Sjoerg /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
45977330f729Sjoerg /*SuppressUserConversions=*/true,
45987330f729Sjoerg /*PartialOverloading*/ false, AllowExplicitCtors);
45997330f729Sjoerg else
46007330f729Sjoerg S.AddOverloadCandidate(
46017330f729Sjoerg Info.Constructor, Info.FoundDecl, Initializer, CandidateSet,
46027330f729Sjoerg /*SuppressUserConversions=*/true,
46037330f729Sjoerg /*PartialOverloading*/ false, AllowExplicitCtors);
46047330f729Sjoerg }
46057330f729Sjoerg }
46067330f729Sjoerg }
46077330f729Sjoerg if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
46087330f729Sjoerg return OR_No_Viable_Function;
46097330f729Sjoerg
46107330f729Sjoerg const RecordType *T2RecordType = nullptr;
46117330f729Sjoerg if ((T2RecordType = T2->getAs<RecordType>()) &&
46127330f729Sjoerg S.isCompleteType(Kind.getLocation(), T2)) {
46137330f729Sjoerg // The type we're converting from is a class type, enumerate its conversion
46147330f729Sjoerg // functions.
46157330f729Sjoerg CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
46167330f729Sjoerg
46177330f729Sjoerg const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
46187330f729Sjoerg for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
46197330f729Sjoerg NamedDecl *D = *I;
46207330f729Sjoerg CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
46217330f729Sjoerg if (isa<UsingShadowDecl>(D))
46227330f729Sjoerg D = cast<UsingShadowDecl>(D)->getTargetDecl();
46237330f729Sjoerg
46247330f729Sjoerg FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
46257330f729Sjoerg CXXConversionDecl *Conv;
46267330f729Sjoerg if (ConvTemplate)
46277330f729Sjoerg Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
46287330f729Sjoerg else
46297330f729Sjoerg Conv = cast<CXXConversionDecl>(D);
46307330f729Sjoerg
46317330f729Sjoerg // If the conversion function doesn't return a reference type,
46327330f729Sjoerg // it can't be considered for this conversion unless we're allowed to
46337330f729Sjoerg // consider rvalues.
46347330f729Sjoerg // FIXME: Do we need to make sure that we only consider conversion
46357330f729Sjoerg // candidates with reference-compatible results? That might be needed to
46367330f729Sjoerg // break recursion.
4637*e038c9c4Sjoerg if ((AllowRValues ||
46387330f729Sjoerg Conv->getConversionType()->isLValueReferenceType())) {
46397330f729Sjoerg if (ConvTemplate)
46407330f729Sjoerg S.AddTemplateConversionCandidate(
46417330f729Sjoerg ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
46427330f729Sjoerg CandidateSet,
46437330f729Sjoerg /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
46447330f729Sjoerg else
46457330f729Sjoerg S.AddConversionCandidate(
46467330f729Sjoerg Conv, I.getPair(), ActingDC, Initializer, DestType, CandidateSet,
46477330f729Sjoerg /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
46487330f729Sjoerg }
46497330f729Sjoerg }
46507330f729Sjoerg }
46517330f729Sjoerg if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
46527330f729Sjoerg return OR_No_Viable_Function;
46537330f729Sjoerg
46547330f729Sjoerg SourceLocation DeclLoc = Initializer->getBeginLoc();
46557330f729Sjoerg
46567330f729Sjoerg // Perform overload resolution. If it fails, return the failed result.
46577330f729Sjoerg OverloadCandidateSet::iterator Best;
46587330f729Sjoerg if (OverloadingResult Result
46597330f729Sjoerg = CandidateSet.BestViableFunction(S, DeclLoc, Best))
46607330f729Sjoerg return Result;
46617330f729Sjoerg
46627330f729Sjoerg FunctionDecl *Function = Best->Function;
46637330f729Sjoerg // This is the overload that will be used for this initialization step if we
46647330f729Sjoerg // use this initialization. Mark it as referenced.
46657330f729Sjoerg Function->setReferenced();
46667330f729Sjoerg
46677330f729Sjoerg // Compute the returned type and value kind of the conversion.
46687330f729Sjoerg QualType cv3T3;
46697330f729Sjoerg if (isa<CXXConversionDecl>(Function))
46707330f729Sjoerg cv3T3 = Function->getReturnType();
46717330f729Sjoerg else
46727330f729Sjoerg cv3T3 = T1;
46737330f729Sjoerg
46747330f729Sjoerg ExprValueKind VK = VK_RValue;
46757330f729Sjoerg if (cv3T3->isLValueReferenceType())
46767330f729Sjoerg VK = VK_LValue;
46777330f729Sjoerg else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
46787330f729Sjoerg VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
46797330f729Sjoerg cv3T3 = cv3T3.getNonLValueExprType(S.Context);
46807330f729Sjoerg
46817330f729Sjoerg // Add the user-defined conversion step.
46827330f729Sjoerg bool HadMultipleCandidates = (CandidateSet.size() > 1);
46837330f729Sjoerg Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3,
46847330f729Sjoerg HadMultipleCandidates);
46857330f729Sjoerg
46867330f729Sjoerg // Determine whether we'll need to perform derived-to-base adjustments or
46877330f729Sjoerg // other conversions.
4688*e038c9c4Sjoerg Sema::ReferenceConversions RefConv;
46897330f729Sjoerg Sema::ReferenceCompareResult NewRefRelationship =
4690*e038c9c4Sjoerg S.CompareReferenceRelationship(DeclLoc, T1, cv3T3, &RefConv);
46917330f729Sjoerg
46927330f729Sjoerg // Add the final conversion sequence, if necessary.
46937330f729Sjoerg if (NewRefRelationship == Sema::Ref_Incompatible) {
46947330f729Sjoerg assert(!isa<CXXConstructorDecl>(Function) &&
46957330f729Sjoerg "should not have conversion after constructor");
46967330f729Sjoerg
46977330f729Sjoerg ImplicitConversionSequence ICS;
46987330f729Sjoerg ICS.setStandard();
46997330f729Sjoerg ICS.Standard = Best->FinalConversion;
47007330f729Sjoerg Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2));
47017330f729Sjoerg
47027330f729Sjoerg // Every implicit conversion results in a prvalue, except for a glvalue
47037330f729Sjoerg // derived-to-base conversion, which we handle below.
47047330f729Sjoerg cv3T3 = ICS.Standard.getToType(2);
47057330f729Sjoerg VK = VK_RValue;
47067330f729Sjoerg }
47077330f729Sjoerg
47087330f729Sjoerg // If the converted initializer is a prvalue, its type T4 is adjusted to
47097330f729Sjoerg // type "cv1 T4" and the temporary materialization conversion is applied.
47107330f729Sjoerg //
47117330f729Sjoerg // We adjust the cv-qualifications to match the reference regardless of
47127330f729Sjoerg // whether we have a prvalue so that the AST records the change. In this
47137330f729Sjoerg // case, T4 is "cv3 T3".
47147330f729Sjoerg QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers());
47157330f729Sjoerg if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
47167330f729Sjoerg Sequence.AddQualificationConversionStep(cv1T4, VK);
47177330f729Sjoerg Sequence.AddReferenceBindingStep(cv1T4, VK == VK_RValue);
47187330f729Sjoerg VK = IsLValueRef ? VK_LValue : VK_XValue;
47197330f729Sjoerg
4720*e038c9c4Sjoerg if (RefConv & Sema::ReferenceConversions::DerivedToBase)
47217330f729Sjoerg Sequence.AddDerivedToBaseCastStep(cv1T1, VK);
4722*e038c9c4Sjoerg else if (RefConv & Sema::ReferenceConversions::ObjC)
47237330f729Sjoerg Sequence.AddObjCObjectConversionStep(cv1T1);
4724*e038c9c4Sjoerg else if (RefConv & Sema::ReferenceConversions::Function)
4725*e038c9c4Sjoerg Sequence.AddFunctionReferenceConversionStep(cv1T1);
4726*e038c9c4Sjoerg else if (RefConv & Sema::ReferenceConversions::Qualification) {
4727*e038c9c4Sjoerg if (!S.Context.hasSameType(cv1T4, cv1T1))
47287330f729Sjoerg Sequence.AddQualificationConversionStep(cv1T1, VK);
4729*e038c9c4Sjoerg }
47307330f729Sjoerg
47317330f729Sjoerg return OR_Success;
47327330f729Sjoerg }
47337330f729Sjoerg
47347330f729Sjoerg static void CheckCXX98CompatAccessibleCopy(Sema &S,
47357330f729Sjoerg const InitializedEntity &Entity,
47367330f729Sjoerg Expr *CurInitExpr);
47377330f729Sjoerg
47387330f729Sjoerg /// Attempt reference initialization (C++0x [dcl.init.ref])
TryReferenceInitialization(Sema & S,const InitializedEntity & Entity,const InitializationKind & Kind,Expr * Initializer,InitializationSequence & Sequence)47397330f729Sjoerg static void TryReferenceInitialization(Sema &S,
47407330f729Sjoerg const InitializedEntity &Entity,
47417330f729Sjoerg const InitializationKind &Kind,
47427330f729Sjoerg Expr *Initializer,
47437330f729Sjoerg InitializationSequence &Sequence) {
47447330f729Sjoerg QualType DestType = Entity.getType();
47457330f729Sjoerg QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
47467330f729Sjoerg Qualifiers T1Quals;
47477330f729Sjoerg QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4748*e038c9c4Sjoerg QualType cv2T2 = S.getCompletedType(Initializer);
47497330f729Sjoerg Qualifiers T2Quals;
47507330f729Sjoerg QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
47517330f729Sjoerg
47527330f729Sjoerg // If the initializer is the address of an overloaded function, try
47537330f729Sjoerg // to resolve the overloaded function. If all goes well, T2 is the
47547330f729Sjoerg // type of the resulting function.
47557330f729Sjoerg if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
47567330f729Sjoerg T1, Sequence))
47577330f729Sjoerg return;
47587330f729Sjoerg
47597330f729Sjoerg // Delegate everything else to a subfunction.
47607330f729Sjoerg TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
47617330f729Sjoerg T1Quals, cv2T2, T2, T2Quals, Sequence);
47627330f729Sjoerg }
47637330f729Sjoerg
47647330f729Sjoerg /// Determine whether an expression is a non-referenceable glvalue (one to
47657330f729Sjoerg /// which a reference can never bind). Attempting to bind a reference to
47667330f729Sjoerg /// such a glvalue will always create a temporary.
isNonReferenceableGLValue(Expr * E)47677330f729Sjoerg static bool isNonReferenceableGLValue(Expr *E) {
4768*e038c9c4Sjoerg return E->refersToBitField() || E->refersToVectorElement() ||
4769*e038c9c4Sjoerg E->refersToMatrixElement();
47707330f729Sjoerg }
47717330f729Sjoerg
47727330f729Sjoerg /// Reference initialization without resolving overloaded functions.
4773*e038c9c4Sjoerg ///
4774*e038c9c4Sjoerg /// We also can get here in C if we call a builtin which is declared as
4775*e038c9c4Sjoerg /// a function with a parameter of reference type (such as __builtin_va_end()).
TryReferenceInitializationCore(Sema & S,const InitializedEntity & Entity,const InitializationKind & Kind,Expr * Initializer,QualType cv1T1,QualType T1,Qualifiers T1Quals,QualType cv2T2,QualType T2,Qualifiers T2Quals,InitializationSequence & Sequence)47767330f729Sjoerg static void TryReferenceInitializationCore(Sema &S,
47777330f729Sjoerg const InitializedEntity &Entity,
47787330f729Sjoerg const InitializationKind &Kind,
47797330f729Sjoerg Expr *Initializer,
47807330f729Sjoerg QualType cv1T1, QualType T1,
47817330f729Sjoerg Qualifiers T1Quals,
47827330f729Sjoerg QualType cv2T2, QualType T2,
47837330f729Sjoerg Qualifiers T2Quals,
47847330f729Sjoerg InitializationSequence &Sequence) {
47857330f729Sjoerg QualType DestType = Entity.getType();
47867330f729Sjoerg SourceLocation DeclLoc = Initializer->getBeginLoc();
4787*e038c9c4Sjoerg
47887330f729Sjoerg // Compute some basic properties of the types and the initializer.
47897330f729Sjoerg bool isLValueRef = DestType->isLValueReferenceType();
47907330f729Sjoerg bool isRValueRef = !isLValueRef;
47917330f729Sjoerg Expr::Classification InitCategory = Initializer->Classify(S.Context);
4792*e038c9c4Sjoerg
4793*e038c9c4Sjoerg Sema::ReferenceConversions RefConv;
4794*e038c9c4Sjoerg Sema::ReferenceCompareResult RefRelationship =
4795*e038c9c4Sjoerg S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, &RefConv);
47967330f729Sjoerg
47977330f729Sjoerg // C++0x [dcl.init.ref]p5:
47987330f729Sjoerg // A reference to type "cv1 T1" is initialized by an expression of type
47997330f729Sjoerg // "cv2 T2" as follows:
48007330f729Sjoerg //
48017330f729Sjoerg // - If the reference is an lvalue reference and the initializer
48027330f729Sjoerg // expression
48037330f729Sjoerg // Note the analogous bullet points for rvalue refs to functions. Because
48047330f729Sjoerg // there are no function rvalues in C++, rvalue refs to functions are treated
48057330f729Sjoerg // like lvalue refs.
48067330f729Sjoerg OverloadingResult ConvOvlResult = OR_Success;
48077330f729Sjoerg bool T1Function = T1->isFunctionType();
48087330f729Sjoerg if (isLValueRef || T1Function) {
48097330f729Sjoerg if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) &&
48107330f729Sjoerg (RefRelationship == Sema::Ref_Compatible ||
48117330f729Sjoerg (Kind.isCStyleOrFunctionalCast() &&
48127330f729Sjoerg RefRelationship == Sema::Ref_Related))) {
48137330f729Sjoerg // - is an lvalue (but is not a bit-field), and "cv1 T1" is
48147330f729Sjoerg // reference-compatible with "cv2 T2," or
4815*e038c9c4Sjoerg if (RefConv & (Sema::ReferenceConversions::DerivedToBase |
4816*e038c9c4Sjoerg Sema::ReferenceConversions::ObjC)) {
4817*e038c9c4Sjoerg // If we're converting the pointee, add any qualifiers first;
4818*e038c9c4Sjoerg // these qualifiers must all be top-level, so just convert to "cv1 T2".
4819*e038c9c4Sjoerg if (RefConv & (Sema::ReferenceConversions::Qualification))
48207330f729Sjoerg Sequence.AddQualificationConversionStep(
48217330f729Sjoerg S.Context.getQualifiedType(T2, T1Quals),
48227330f729Sjoerg Initializer->getValueKind());
4823*e038c9c4Sjoerg if (RefConv & Sema::ReferenceConversions::DerivedToBase)
48247330f729Sjoerg Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue);
4825*e038c9c4Sjoerg else
48267330f729Sjoerg Sequence.AddObjCObjectConversionStep(cv1T1);
4827*e038c9c4Sjoerg } else if (RefConv & Sema::ReferenceConversions::Qualification) {
4828*e038c9c4Sjoerg // Perform a (possibly multi-level) qualification conversion.
4829*e038c9c4Sjoerg Sequence.AddQualificationConversionStep(cv1T1,
4830*e038c9c4Sjoerg Initializer->getValueKind());
4831*e038c9c4Sjoerg } else if (RefConv & Sema::ReferenceConversions::Function) {
4832*e038c9c4Sjoerg Sequence.AddFunctionReferenceConversionStep(cv1T1);
4833*e038c9c4Sjoerg }
48347330f729Sjoerg
48357330f729Sjoerg // We only create a temporary here when binding a reference to a
48367330f729Sjoerg // bit-field or vector element. Those cases are't supposed to be
48377330f729Sjoerg // handled by this bullet, but the outcome is the same either way.
48387330f729Sjoerg Sequence.AddReferenceBindingStep(cv1T1, false);
48397330f729Sjoerg return;
48407330f729Sjoerg }
48417330f729Sjoerg
48427330f729Sjoerg // - has a class type (i.e., T2 is a class type), where T1 is not
48437330f729Sjoerg // reference-related to T2, and can be implicitly converted to an
48447330f729Sjoerg // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
48457330f729Sjoerg // with "cv3 T3" (this conversion is selected by enumerating the
48467330f729Sjoerg // applicable conversion functions (13.3.1.6) and choosing the best
48477330f729Sjoerg // one through overload resolution (13.3)),
48487330f729Sjoerg // If we have an rvalue ref to function type here, the rhs must be
48497330f729Sjoerg // an rvalue. DR1287 removed the "implicitly" here.
48507330f729Sjoerg if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
48517330f729Sjoerg (isLValueRef || InitCategory.isRValue())) {
4852*e038c9c4Sjoerg if (S.getLangOpts().CPlusPlus) {
4853*e038c9c4Sjoerg // Try conversion functions only for C++.
48547330f729Sjoerg ConvOvlResult = TryRefInitWithConversionFunction(
48557330f729Sjoerg S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,
48567330f729Sjoerg /*IsLValueRef*/ isLValueRef, Sequence);
48577330f729Sjoerg if (ConvOvlResult == OR_Success)
48587330f729Sjoerg return;
48597330f729Sjoerg if (ConvOvlResult != OR_No_Viable_Function)
48607330f729Sjoerg Sequence.SetOverloadFailure(
48617330f729Sjoerg InitializationSequence::FK_ReferenceInitOverloadFailed,
48627330f729Sjoerg ConvOvlResult);
4863*e038c9c4Sjoerg } else {
4864*e038c9c4Sjoerg ConvOvlResult = OR_No_Viable_Function;
4865*e038c9c4Sjoerg }
48667330f729Sjoerg }
48677330f729Sjoerg }
48687330f729Sjoerg
48697330f729Sjoerg // - Otherwise, the reference shall be an lvalue reference to a
48707330f729Sjoerg // non-volatile const type (i.e., cv1 shall be const), or the reference
48717330f729Sjoerg // shall be an rvalue reference.
48727330f729Sjoerg // For address spaces, we interpret this to mean that an addr space
48737330f729Sjoerg // of a reference "cv1 T1" is a superset of addr space of "cv2 T2".
48747330f729Sjoerg if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile() &&
48757330f729Sjoerg T1Quals.isAddressSpaceSupersetOf(T2Quals))) {
48767330f729Sjoerg if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
48777330f729Sjoerg Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
48787330f729Sjoerg else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
48797330f729Sjoerg Sequence.SetOverloadFailure(
48807330f729Sjoerg InitializationSequence::FK_ReferenceInitOverloadFailed,
48817330f729Sjoerg ConvOvlResult);
48827330f729Sjoerg else if (!InitCategory.isLValue())
48837330f729Sjoerg Sequence.SetFailed(
48847330f729Sjoerg T1Quals.isAddressSpaceSupersetOf(T2Quals)
48857330f729Sjoerg ? InitializationSequence::
48867330f729Sjoerg FK_NonConstLValueReferenceBindingToTemporary
48877330f729Sjoerg : InitializationSequence::FK_ReferenceInitDropsQualifiers);
48887330f729Sjoerg else {
48897330f729Sjoerg InitializationSequence::FailureKind FK;
48907330f729Sjoerg switch (RefRelationship) {
48917330f729Sjoerg case Sema::Ref_Compatible:
48927330f729Sjoerg if (Initializer->refersToBitField())
48937330f729Sjoerg FK = InitializationSequence::
48947330f729Sjoerg FK_NonConstLValueReferenceBindingToBitfield;
48957330f729Sjoerg else if (Initializer->refersToVectorElement())
48967330f729Sjoerg FK = InitializationSequence::
48977330f729Sjoerg FK_NonConstLValueReferenceBindingToVectorElement;
4898*e038c9c4Sjoerg else if (Initializer->refersToMatrixElement())
4899*e038c9c4Sjoerg FK = InitializationSequence::
4900*e038c9c4Sjoerg FK_NonConstLValueReferenceBindingToMatrixElement;
49017330f729Sjoerg else
49027330f729Sjoerg llvm_unreachable("unexpected kind of compatible initializer");
49037330f729Sjoerg break;
49047330f729Sjoerg case Sema::Ref_Related:
49057330f729Sjoerg FK = InitializationSequence::FK_ReferenceInitDropsQualifiers;
49067330f729Sjoerg break;
49077330f729Sjoerg case Sema::Ref_Incompatible:
49087330f729Sjoerg FK = InitializationSequence::
49097330f729Sjoerg FK_NonConstLValueReferenceBindingToUnrelated;
49107330f729Sjoerg break;
49117330f729Sjoerg }
49127330f729Sjoerg Sequence.SetFailed(FK);
49137330f729Sjoerg }
49147330f729Sjoerg return;
49157330f729Sjoerg }
49167330f729Sjoerg
49177330f729Sjoerg // - If the initializer expression
49187330f729Sjoerg // - is an
49197330f729Sjoerg // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
49207330f729Sjoerg // [1z] rvalue (but not a bit-field) or
49217330f729Sjoerg // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
49227330f729Sjoerg //
49237330f729Sjoerg // Note: functions are handled above and below rather than here...
49247330f729Sjoerg if (!T1Function &&
49257330f729Sjoerg (RefRelationship == Sema::Ref_Compatible ||
49267330f729Sjoerg (Kind.isCStyleOrFunctionalCast() &&
49277330f729Sjoerg RefRelationship == Sema::Ref_Related)) &&
49287330f729Sjoerg ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) ||
49297330f729Sjoerg (InitCategory.isPRValue() &&
49307330f729Sjoerg (S.getLangOpts().CPlusPlus17 || T2->isRecordType() ||
49317330f729Sjoerg T2->isArrayType())))) {
49327330f729Sjoerg ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_RValue;
49337330f729Sjoerg if (InitCategory.isPRValue() && T2->isRecordType()) {
49347330f729Sjoerg // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
49357330f729Sjoerg // compiler the freedom to perform a copy here or bind to the
49367330f729Sjoerg // object, while C++0x requires that we bind directly to the
49377330f729Sjoerg // object. Hence, we always bind to the object without making an
49387330f729Sjoerg // extra copy. However, in C++03 requires that we check for the
49397330f729Sjoerg // presence of a suitable copy constructor:
49407330f729Sjoerg //
49417330f729Sjoerg // The constructor that would be used to make the copy shall
49427330f729Sjoerg // be callable whether or not the copy is actually done.
49437330f729Sjoerg if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
49447330f729Sjoerg Sequence.AddExtraneousCopyToTemporary(cv2T2);
49457330f729Sjoerg else if (S.getLangOpts().CPlusPlus11)
49467330f729Sjoerg CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
49477330f729Sjoerg }
49487330f729Sjoerg
49497330f729Sjoerg // C++1z [dcl.init.ref]/5.2.1.2:
49507330f729Sjoerg // If the converted initializer is a prvalue, its type T4 is adjusted
49517330f729Sjoerg // to type "cv1 T4" and the temporary materialization conversion is
49527330f729Sjoerg // applied.
49537330f729Sjoerg // Postpone address space conversions to after the temporary materialization
49547330f729Sjoerg // conversion to allow creating temporaries in the alloca address space.
49557330f729Sjoerg auto T1QualsIgnoreAS = T1Quals;
49567330f729Sjoerg auto T2QualsIgnoreAS = T2Quals;
49577330f729Sjoerg if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
49587330f729Sjoerg T1QualsIgnoreAS.removeAddressSpace();
49597330f729Sjoerg T2QualsIgnoreAS.removeAddressSpace();
49607330f729Sjoerg }
49617330f729Sjoerg QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1QualsIgnoreAS);
49627330f729Sjoerg if (T1QualsIgnoreAS != T2QualsIgnoreAS)
49637330f729Sjoerg Sequence.AddQualificationConversionStep(cv1T4, ValueKind);
49647330f729Sjoerg Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_RValue);
49657330f729Sjoerg ValueKind = isLValueRef ? VK_LValue : VK_XValue;
49667330f729Sjoerg // Add addr space conversion if required.
49677330f729Sjoerg if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
49687330f729Sjoerg auto T4Quals = cv1T4.getQualifiers();
49697330f729Sjoerg T4Quals.addAddressSpace(T1Quals.getAddressSpace());
49707330f729Sjoerg QualType cv1T4WithAS = S.Context.getQualifiedType(T2, T4Quals);
49717330f729Sjoerg Sequence.AddQualificationConversionStep(cv1T4WithAS, ValueKind);
4972*e038c9c4Sjoerg cv1T4 = cv1T4WithAS;
49737330f729Sjoerg }
49747330f729Sjoerg
49757330f729Sjoerg // In any case, the reference is bound to the resulting glvalue (or to
49767330f729Sjoerg // an appropriate base class subobject).
4977*e038c9c4Sjoerg if (RefConv & Sema::ReferenceConversions::DerivedToBase)
49787330f729Sjoerg Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind);
4979*e038c9c4Sjoerg else if (RefConv & Sema::ReferenceConversions::ObjC)
49807330f729Sjoerg Sequence.AddObjCObjectConversionStep(cv1T1);
4981*e038c9c4Sjoerg else if (RefConv & Sema::ReferenceConversions::Qualification) {
4982*e038c9c4Sjoerg if (!S.Context.hasSameType(cv1T4, cv1T1))
4983*e038c9c4Sjoerg Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
4984*e038c9c4Sjoerg }
49857330f729Sjoerg return;
49867330f729Sjoerg }
49877330f729Sjoerg
49887330f729Sjoerg // - has a class type (i.e., T2 is a class type), where T1 is not
49897330f729Sjoerg // reference-related to T2, and can be implicitly converted to an
49907330f729Sjoerg // xvalue, class prvalue, or function lvalue of type "cv3 T3",
49917330f729Sjoerg // where "cv1 T1" is reference-compatible with "cv3 T3",
49927330f729Sjoerg //
49937330f729Sjoerg // DR1287 removes the "implicitly" here.
49947330f729Sjoerg if (T2->isRecordType()) {
49957330f729Sjoerg if (RefRelationship == Sema::Ref_Incompatible) {
49967330f729Sjoerg ConvOvlResult = TryRefInitWithConversionFunction(
49977330f729Sjoerg S, Entity, Kind, Initializer, /*AllowRValues*/ true,
49987330f729Sjoerg /*IsLValueRef*/ isLValueRef, Sequence);
49997330f729Sjoerg if (ConvOvlResult)
50007330f729Sjoerg Sequence.SetOverloadFailure(
50017330f729Sjoerg InitializationSequence::FK_ReferenceInitOverloadFailed,
50027330f729Sjoerg ConvOvlResult);
50037330f729Sjoerg
50047330f729Sjoerg return;
50057330f729Sjoerg }
50067330f729Sjoerg
50077330f729Sjoerg if (RefRelationship == Sema::Ref_Compatible &&
50087330f729Sjoerg isRValueRef && InitCategory.isLValue()) {
50097330f729Sjoerg Sequence.SetFailed(
50107330f729Sjoerg InitializationSequence::FK_RValueReferenceBindingToLValue);
50117330f729Sjoerg return;
50127330f729Sjoerg }
50137330f729Sjoerg
50147330f729Sjoerg Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
50157330f729Sjoerg return;
50167330f729Sjoerg }
50177330f729Sjoerg
50187330f729Sjoerg // - Otherwise, a temporary of type "cv1 T1" is created and initialized
50197330f729Sjoerg // from the initializer expression using the rules for a non-reference
50207330f729Sjoerg // copy-initialization (8.5). The reference is then bound to the
50217330f729Sjoerg // temporary. [...]
50227330f729Sjoerg
50237330f729Sjoerg // Ignore address space of reference type at this point and perform address
50247330f729Sjoerg // space conversion after the reference binding step.
50257330f729Sjoerg QualType cv1T1IgnoreAS =
50267330f729Sjoerg T1Quals.hasAddressSpace()
50277330f729Sjoerg ? S.Context.getQualifiedType(T1, T1Quals.withoutAddressSpace())
50287330f729Sjoerg : cv1T1;
50297330f729Sjoerg
50307330f729Sjoerg InitializedEntity TempEntity =
50317330f729Sjoerg InitializedEntity::InitializeTemporary(cv1T1IgnoreAS);
50327330f729Sjoerg
50337330f729Sjoerg // FIXME: Why do we use an implicit conversion here rather than trying
50347330f729Sjoerg // copy-initialization?
50357330f729Sjoerg ImplicitConversionSequence ICS
50367330f729Sjoerg = S.TryImplicitConversion(Initializer, TempEntity.getType(),
50377330f729Sjoerg /*SuppressUserConversions=*/false,
5038*e038c9c4Sjoerg Sema::AllowedExplicit::None,
50397330f729Sjoerg /*FIXME:InOverloadResolution=*/false,
50407330f729Sjoerg /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
50417330f729Sjoerg /*AllowObjCWritebackConversion=*/false);
50427330f729Sjoerg
50437330f729Sjoerg if (ICS.isBad()) {
50447330f729Sjoerg // FIXME: Use the conversion function set stored in ICS to turn
50457330f729Sjoerg // this into an overloading ambiguity diagnostic. However, we need
50467330f729Sjoerg // to keep that set as an OverloadCandidateSet rather than as some
50477330f729Sjoerg // other kind of set.
50487330f729Sjoerg if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
50497330f729Sjoerg Sequence.SetOverloadFailure(
50507330f729Sjoerg InitializationSequence::FK_ReferenceInitOverloadFailed,
50517330f729Sjoerg ConvOvlResult);
50527330f729Sjoerg else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
50537330f729Sjoerg Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
50547330f729Sjoerg else
50557330f729Sjoerg Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
50567330f729Sjoerg return;
50577330f729Sjoerg } else {
50587330f729Sjoerg Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
50597330f729Sjoerg }
50607330f729Sjoerg
50617330f729Sjoerg // [...] If T1 is reference-related to T2, cv1 must be the
50627330f729Sjoerg // same cv-qualification as, or greater cv-qualification
50637330f729Sjoerg // than, cv2; otherwise, the program is ill-formed.
50647330f729Sjoerg unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
50657330f729Sjoerg unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
50667330f729Sjoerg if ((RefRelationship == Sema::Ref_Related &&
50677330f729Sjoerg (T1CVRQuals | T2CVRQuals) != T1CVRQuals) ||
50687330f729Sjoerg !T1Quals.isAddressSpaceSupersetOf(T2Quals)) {
50697330f729Sjoerg Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
50707330f729Sjoerg return;
50717330f729Sjoerg }
50727330f729Sjoerg
50737330f729Sjoerg // [...] If T1 is reference-related to T2 and the reference is an rvalue
50747330f729Sjoerg // reference, the initializer expression shall not be an lvalue.
50757330f729Sjoerg if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
50767330f729Sjoerg InitCategory.isLValue()) {
50777330f729Sjoerg Sequence.SetFailed(
50787330f729Sjoerg InitializationSequence::FK_RValueReferenceBindingToLValue);
50797330f729Sjoerg return;
50807330f729Sjoerg }
50817330f729Sjoerg
50827330f729Sjoerg Sequence.AddReferenceBindingStep(cv1T1IgnoreAS, /*BindingTemporary=*/true);
50837330f729Sjoerg
50847330f729Sjoerg if (T1Quals.hasAddressSpace()) {
50857330f729Sjoerg if (!Qualifiers::isAddressSpaceSupersetOf(T1Quals.getAddressSpace(),
50867330f729Sjoerg LangAS::Default)) {
50877330f729Sjoerg Sequence.SetFailed(
50887330f729Sjoerg InitializationSequence::FK_ReferenceAddrspaceMismatchTemporary);
50897330f729Sjoerg return;
50907330f729Sjoerg }
50917330f729Sjoerg Sequence.AddQualificationConversionStep(cv1T1, isLValueRef ? VK_LValue
50927330f729Sjoerg : VK_XValue);
50937330f729Sjoerg }
50947330f729Sjoerg }
50957330f729Sjoerg
50967330f729Sjoerg /// Attempt character array initialization from a string literal
50977330f729Sjoerg /// (C++ [dcl.init.string], C99 6.7.8).
TryStringLiteralInitialization(Sema & S,const InitializedEntity & Entity,const InitializationKind & Kind,Expr * Initializer,InitializationSequence & Sequence)50987330f729Sjoerg static void TryStringLiteralInitialization(Sema &S,
50997330f729Sjoerg const InitializedEntity &Entity,
51007330f729Sjoerg const InitializationKind &Kind,
51017330f729Sjoerg Expr *Initializer,
51027330f729Sjoerg InitializationSequence &Sequence) {
51037330f729Sjoerg Sequence.AddStringInitStep(Entity.getType());
51047330f729Sjoerg }
51057330f729Sjoerg
51067330f729Sjoerg /// Attempt value initialization (C++ [dcl.init]p7).
TryValueInitialization(Sema & S,const InitializedEntity & Entity,const InitializationKind & Kind,InitializationSequence & Sequence,InitListExpr * InitList)51077330f729Sjoerg static void TryValueInitialization(Sema &S,
51087330f729Sjoerg const InitializedEntity &Entity,
51097330f729Sjoerg const InitializationKind &Kind,
51107330f729Sjoerg InitializationSequence &Sequence,
51117330f729Sjoerg InitListExpr *InitList) {
51127330f729Sjoerg assert((!InitList || InitList->getNumInits() == 0) &&
51137330f729Sjoerg "Shouldn't use value-init for non-empty init lists");
51147330f729Sjoerg
51157330f729Sjoerg // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
51167330f729Sjoerg //
51177330f729Sjoerg // To value-initialize an object of type T means:
51187330f729Sjoerg QualType T = Entity.getType();
51197330f729Sjoerg
51207330f729Sjoerg // -- if T is an array type, then each element is value-initialized;
51217330f729Sjoerg T = S.Context.getBaseElementType(T);
51227330f729Sjoerg
51237330f729Sjoerg if (const RecordType *RT = T->getAs<RecordType>()) {
51247330f729Sjoerg if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
51257330f729Sjoerg bool NeedZeroInitialization = true;
51267330f729Sjoerg // C++98:
51277330f729Sjoerg // -- if T is a class type (clause 9) with a user-declared constructor
51287330f729Sjoerg // (12.1), then the default constructor for T is called (and the
51297330f729Sjoerg // initialization is ill-formed if T has no accessible default
51307330f729Sjoerg // constructor);
51317330f729Sjoerg // C++11:
51327330f729Sjoerg // -- if T is a class type (clause 9) with either no default constructor
51337330f729Sjoerg // (12.1 [class.ctor]) or a default constructor that is user-provided
51347330f729Sjoerg // or deleted, then the object is default-initialized;
51357330f729Sjoerg //
51367330f729Sjoerg // Note that the C++11 rule is the same as the C++98 rule if there are no
51377330f729Sjoerg // defaulted or deleted constructors, so we just use it unconditionally.
51387330f729Sjoerg CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
51397330f729Sjoerg if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
51407330f729Sjoerg NeedZeroInitialization = false;
51417330f729Sjoerg
51427330f729Sjoerg // -- if T is a (possibly cv-qualified) non-union class type without a
51437330f729Sjoerg // user-provided or deleted default constructor, then the object is
51447330f729Sjoerg // zero-initialized and, if T has a non-trivial default constructor,
51457330f729Sjoerg // default-initialized;
51467330f729Sjoerg // The 'non-union' here was removed by DR1502. The 'non-trivial default
51477330f729Sjoerg // constructor' part was removed by DR1507.
51487330f729Sjoerg if (NeedZeroInitialization)
51497330f729Sjoerg Sequence.AddZeroInitializationStep(Entity.getType());
51507330f729Sjoerg
51517330f729Sjoerg // C++03:
51527330f729Sjoerg // -- if T is a non-union class type without a user-declared constructor,
51537330f729Sjoerg // then every non-static data member and base class component of T is
51547330f729Sjoerg // value-initialized;
51557330f729Sjoerg // [...] A program that calls for [...] value-initialization of an
51567330f729Sjoerg // entity of reference type is ill-formed.
51577330f729Sjoerg //
51587330f729Sjoerg // C++11 doesn't need this handling, because value-initialization does not
51597330f729Sjoerg // occur recursively there, and the implicit default constructor is
51607330f729Sjoerg // defined as deleted in the problematic cases.
51617330f729Sjoerg if (!S.getLangOpts().CPlusPlus11 &&
51627330f729Sjoerg ClassDecl->hasUninitializedReferenceMember()) {
51637330f729Sjoerg Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
51647330f729Sjoerg return;
51657330f729Sjoerg }
51667330f729Sjoerg
51677330f729Sjoerg // If this is list-value-initialization, pass the empty init list on when
51687330f729Sjoerg // building the constructor call. This affects the semantics of a few
51697330f729Sjoerg // things (such as whether an explicit default constructor can be called).
51707330f729Sjoerg Expr *InitListAsExpr = InitList;
51717330f729Sjoerg MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
51727330f729Sjoerg bool InitListSyntax = InitList;
51737330f729Sjoerg
51747330f729Sjoerg // FIXME: Instead of creating a CXXConstructExpr of array type here,
51757330f729Sjoerg // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
51767330f729Sjoerg return TryConstructorInitialization(
51777330f729Sjoerg S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax);
51787330f729Sjoerg }
51797330f729Sjoerg }
51807330f729Sjoerg
51817330f729Sjoerg Sequence.AddZeroInitializationStep(Entity.getType());
51827330f729Sjoerg }
51837330f729Sjoerg
51847330f729Sjoerg /// Attempt default initialization (C++ [dcl.init]p6).
TryDefaultInitialization(Sema & S,const InitializedEntity & Entity,const InitializationKind & Kind,InitializationSequence & Sequence)51857330f729Sjoerg static void TryDefaultInitialization(Sema &S,
51867330f729Sjoerg const InitializedEntity &Entity,
51877330f729Sjoerg const InitializationKind &Kind,
51887330f729Sjoerg InitializationSequence &Sequence) {
51897330f729Sjoerg assert(Kind.getKind() == InitializationKind::IK_Default);
51907330f729Sjoerg
51917330f729Sjoerg // C++ [dcl.init]p6:
51927330f729Sjoerg // To default-initialize an object of type T means:
51937330f729Sjoerg // - if T is an array type, each element is default-initialized;
51947330f729Sjoerg QualType DestType = S.Context.getBaseElementType(Entity.getType());
51957330f729Sjoerg
51967330f729Sjoerg // - if T is a (possibly cv-qualified) class type (Clause 9), the default
51977330f729Sjoerg // constructor for T is called (and the initialization is ill-formed if
51987330f729Sjoerg // T has no accessible default constructor);
51997330f729Sjoerg if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
52007330f729Sjoerg TryConstructorInitialization(S, Entity, Kind, None, DestType,
52017330f729Sjoerg Entity.getType(), Sequence);
52027330f729Sjoerg return;
52037330f729Sjoerg }
52047330f729Sjoerg
52057330f729Sjoerg // - otherwise, no initialization is performed.
52067330f729Sjoerg
52077330f729Sjoerg // If a program calls for the default initialization of an object of
52087330f729Sjoerg // a const-qualified type T, T shall be a class type with a user-provided
52097330f729Sjoerg // default constructor.
52107330f729Sjoerg if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
52117330f729Sjoerg if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
52127330f729Sjoerg Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
52137330f729Sjoerg return;
52147330f729Sjoerg }
52157330f729Sjoerg
52167330f729Sjoerg // If the destination type has a lifetime property, zero-initialize it.
52177330f729Sjoerg if (DestType.getQualifiers().hasObjCLifetime()) {
52187330f729Sjoerg Sequence.AddZeroInitializationStep(Entity.getType());
52197330f729Sjoerg return;
52207330f729Sjoerg }
52217330f729Sjoerg }
52227330f729Sjoerg
52237330f729Sjoerg /// Attempt a user-defined conversion between two types (C++ [dcl.init]),
52247330f729Sjoerg /// which enumerates all conversion functions and performs overload resolution
52257330f729Sjoerg /// to select the best.
TryUserDefinedConversion(Sema & S,QualType DestType,const InitializationKind & Kind,Expr * Initializer,InitializationSequence & Sequence,bool TopLevelOfInitList)52267330f729Sjoerg static void TryUserDefinedConversion(Sema &S,
52277330f729Sjoerg QualType DestType,
52287330f729Sjoerg const InitializationKind &Kind,
52297330f729Sjoerg Expr *Initializer,
52307330f729Sjoerg InitializationSequence &Sequence,
52317330f729Sjoerg bool TopLevelOfInitList) {
52327330f729Sjoerg assert(!DestType->isReferenceType() && "References are handled elsewhere");
52337330f729Sjoerg QualType SourceType = Initializer->getType();
52347330f729Sjoerg assert((DestType->isRecordType() || SourceType->isRecordType()) &&
52357330f729Sjoerg "Must have a class type to perform a user-defined conversion");
52367330f729Sjoerg
52377330f729Sjoerg // Build the candidate set directly in the initialization sequence
52387330f729Sjoerg // structure, so that it will persist if we fail.
52397330f729Sjoerg OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
52407330f729Sjoerg CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
52417330f729Sjoerg CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
52427330f729Sjoerg
52437330f729Sjoerg // Determine whether we are allowed to call explicit constructors or
52447330f729Sjoerg // explicit conversion operators.
52457330f729Sjoerg bool AllowExplicit = Kind.AllowExplicit();
52467330f729Sjoerg
52477330f729Sjoerg if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
52487330f729Sjoerg // The type we're converting to is a class type. Enumerate its constructors
52497330f729Sjoerg // to see if there is a suitable conversion.
52507330f729Sjoerg CXXRecordDecl *DestRecordDecl
52517330f729Sjoerg = cast<CXXRecordDecl>(DestRecordType->getDecl());
52527330f729Sjoerg
52537330f729Sjoerg // Try to complete the type we're converting to.
52547330f729Sjoerg if (S.isCompleteType(Kind.getLocation(), DestType)) {
52557330f729Sjoerg for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) {
52567330f729Sjoerg auto Info = getConstructorInfo(D);
52577330f729Sjoerg if (!Info.Constructor)
52587330f729Sjoerg continue;
52597330f729Sjoerg
52607330f729Sjoerg if (!Info.Constructor->isInvalidDecl() &&
5261*e038c9c4Sjoerg Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
52627330f729Sjoerg if (Info.ConstructorTmpl)
52637330f729Sjoerg S.AddTemplateOverloadCandidate(
52647330f729Sjoerg Info.ConstructorTmpl, Info.FoundDecl,
52657330f729Sjoerg /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
52667330f729Sjoerg /*SuppressUserConversions=*/true,
52677330f729Sjoerg /*PartialOverloading*/ false, AllowExplicit);
52687330f729Sjoerg else
52697330f729Sjoerg S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
52707330f729Sjoerg Initializer, CandidateSet,
52717330f729Sjoerg /*SuppressUserConversions=*/true,
52727330f729Sjoerg /*PartialOverloading*/ false, AllowExplicit);
52737330f729Sjoerg }
52747330f729Sjoerg }
52757330f729Sjoerg }
52767330f729Sjoerg }
52777330f729Sjoerg
52787330f729Sjoerg SourceLocation DeclLoc = Initializer->getBeginLoc();
52797330f729Sjoerg
52807330f729Sjoerg if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
52817330f729Sjoerg // The type we're converting from is a class type, enumerate its conversion
52827330f729Sjoerg // functions.
52837330f729Sjoerg
52847330f729Sjoerg // We can only enumerate the conversion functions for a complete type; if
52857330f729Sjoerg // the type isn't complete, simply skip this step.
52867330f729Sjoerg if (S.isCompleteType(DeclLoc, SourceType)) {
52877330f729Sjoerg CXXRecordDecl *SourceRecordDecl
52887330f729Sjoerg = cast<CXXRecordDecl>(SourceRecordType->getDecl());
52897330f729Sjoerg
52907330f729Sjoerg const auto &Conversions =
52917330f729Sjoerg SourceRecordDecl->getVisibleConversionFunctions();
52927330f729Sjoerg for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
52937330f729Sjoerg NamedDecl *D = *I;
52947330f729Sjoerg CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
52957330f729Sjoerg if (isa<UsingShadowDecl>(D))
52967330f729Sjoerg D = cast<UsingShadowDecl>(D)->getTargetDecl();
52977330f729Sjoerg
52987330f729Sjoerg FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
52997330f729Sjoerg CXXConversionDecl *Conv;
53007330f729Sjoerg if (ConvTemplate)
53017330f729Sjoerg Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
53027330f729Sjoerg else
53037330f729Sjoerg Conv = cast<CXXConversionDecl>(D);
53047330f729Sjoerg
53057330f729Sjoerg if (ConvTemplate)
53067330f729Sjoerg S.AddTemplateConversionCandidate(
53077330f729Sjoerg ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
53087330f729Sjoerg CandidateSet, AllowExplicit, AllowExplicit);
53097330f729Sjoerg else
53107330f729Sjoerg S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
53117330f729Sjoerg DestType, CandidateSet, AllowExplicit,
53127330f729Sjoerg AllowExplicit);
53137330f729Sjoerg }
53147330f729Sjoerg }
53157330f729Sjoerg }
53167330f729Sjoerg
53177330f729Sjoerg // Perform overload resolution. If it fails, return the failed result.
53187330f729Sjoerg OverloadCandidateSet::iterator Best;
53197330f729Sjoerg if (OverloadingResult Result
53207330f729Sjoerg = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
53217330f729Sjoerg Sequence.SetOverloadFailure(
5322*e038c9c4Sjoerg InitializationSequence::FK_UserConversionOverloadFailed, Result);
5323*e038c9c4Sjoerg
5324*e038c9c4Sjoerg // [class.copy.elision]p3:
5325*e038c9c4Sjoerg // In some copy-initialization contexts, a two-stage overload resolution
5326*e038c9c4Sjoerg // is performed.
5327*e038c9c4Sjoerg // If the first overload resolution selects a deleted function, we also
5328*e038c9c4Sjoerg // need the initialization sequence to decide whether to perform the second
5329*e038c9c4Sjoerg // overload resolution.
5330*e038c9c4Sjoerg if (!(Result == OR_Deleted &&
5331*e038c9c4Sjoerg Kind.getKind() == InitializationKind::IK_Copy))
53327330f729Sjoerg return;
53337330f729Sjoerg }
53347330f729Sjoerg
53357330f729Sjoerg FunctionDecl *Function = Best->Function;
53367330f729Sjoerg Function->setReferenced();
53377330f729Sjoerg bool HadMultipleCandidates = (CandidateSet.size() > 1);
53387330f729Sjoerg
53397330f729Sjoerg if (isa<CXXConstructorDecl>(Function)) {
53407330f729Sjoerg // Add the user-defined conversion step. Any cv-qualification conversion is
53417330f729Sjoerg // subsumed by the initialization. Per DR5, the created temporary is of the
53427330f729Sjoerg // cv-unqualified type of the destination.
53437330f729Sjoerg Sequence.AddUserConversionStep(Function, Best->FoundDecl,
53447330f729Sjoerg DestType.getUnqualifiedType(),
53457330f729Sjoerg HadMultipleCandidates);
53467330f729Sjoerg
53477330f729Sjoerg // C++14 and before:
53487330f729Sjoerg // - if the function is a constructor, the call initializes a temporary
53497330f729Sjoerg // of the cv-unqualified version of the destination type. The [...]
53507330f729Sjoerg // temporary [...] is then used to direct-initialize, according to the
53517330f729Sjoerg // rules above, the object that is the destination of the
53527330f729Sjoerg // copy-initialization.
53537330f729Sjoerg // Note that this just performs a simple object copy from the temporary.
53547330f729Sjoerg //
53557330f729Sjoerg // C++17:
53567330f729Sjoerg // - if the function is a constructor, the call is a prvalue of the
53577330f729Sjoerg // cv-unqualified version of the destination type whose return object
53587330f729Sjoerg // is initialized by the constructor. The call is used to
53597330f729Sjoerg // direct-initialize, according to the rules above, the object that
53607330f729Sjoerg // is the destination of the copy-initialization.
53617330f729Sjoerg // Therefore we need to do nothing further.
53627330f729Sjoerg //
53637330f729Sjoerg // FIXME: Mark this copy as extraneous.
53647330f729Sjoerg if (!S.getLangOpts().CPlusPlus17)
53657330f729Sjoerg Sequence.AddFinalCopy(DestType);
53667330f729Sjoerg else if (DestType.hasQualifiers())
53677330f729Sjoerg Sequence.AddQualificationConversionStep(DestType, VK_RValue);
53687330f729Sjoerg return;
53697330f729Sjoerg }
53707330f729Sjoerg
53717330f729Sjoerg // Add the user-defined conversion step that calls the conversion function.
53727330f729Sjoerg QualType ConvType = Function->getCallResultType();
53737330f729Sjoerg Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
53747330f729Sjoerg HadMultipleCandidates);
53757330f729Sjoerg
53767330f729Sjoerg if (ConvType->getAs<RecordType>()) {
53777330f729Sjoerg // The call is used to direct-initialize [...] the object that is the
53787330f729Sjoerg // destination of the copy-initialization.
53797330f729Sjoerg //
53807330f729Sjoerg // In C++17, this does not call a constructor if we enter /17.6.1:
53817330f729Sjoerg // - If the initializer expression is a prvalue and the cv-unqualified
53827330f729Sjoerg // version of the source type is the same as the class of the
53837330f729Sjoerg // destination [... do not make an extra copy]
53847330f729Sjoerg //
53857330f729Sjoerg // FIXME: Mark this copy as extraneous.
53867330f729Sjoerg if (!S.getLangOpts().CPlusPlus17 ||
53877330f729Sjoerg Function->getReturnType()->isReferenceType() ||
53887330f729Sjoerg !S.Context.hasSameUnqualifiedType(ConvType, DestType))
53897330f729Sjoerg Sequence.AddFinalCopy(DestType);
53907330f729Sjoerg else if (!S.Context.hasSameType(ConvType, DestType))
53917330f729Sjoerg Sequence.AddQualificationConversionStep(DestType, VK_RValue);
53927330f729Sjoerg return;
53937330f729Sjoerg }
53947330f729Sjoerg
53957330f729Sjoerg // If the conversion following the call to the conversion function
53967330f729Sjoerg // is interesting, add it as a separate step.
53977330f729Sjoerg if (Best->FinalConversion.First || Best->FinalConversion.Second ||
53987330f729Sjoerg Best->FinalConversion.Third) {
53997330f729Sjoerg ImplicitConversionSequence ICS;
54007330f729Sjoerg ICS.setStandard();
54017330f729Sjoerg ICS.Standard = Best->FinalConversion;
54027330f729Sjoerg Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
54037330f729Sjoerg }
54047330f729Sjoerg }
54057330f729Sjoerg
54067330f729Sjoerg /// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
54077330f729Sjoerg /// a function with a pointer return type contains a 'return false;' statement.
54087330f729Sjoerg /// In C++11, 'false' is not a null pointer, so this breaks the build of any
54097330f729Sjoerg /// code using that header.
54107330f729Sjoerg ///
54117330f729Sjoerg /// Work around this by treating 'return false;' as zero-initializing the result
54127330f729Sjoerg /// if it's used in a pointer-returning function in a system header.
isLibstdcxxPointerReturnFalseHack(Sema & S,const InitializedEntity & Entity,const Expr * Init)54137330f729Sjoerg static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
54147330f729Sjoerg const InitializedEntity &Entity,
54157330f729Sjoerg const Expr *Init) {
54167330f729Sjoerg return S.getLangOpts().CPlusPlus11 &&
54177330f729Sjoerg Entity.getKind() == InitializedEntity::EK_Result &&
54187330f729Sjoerg Entity.getType()->isPointerType() &&
54197330f729Sjoerg isa<CXXBoolLiteralExpr>(Init) &&
54207330f729Sjoerg !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
54217330f729Sjoerg S.getSourceManager().isInSystemHeader(Init->getExprLoc());
54227330f729Sjoerg }
54237330f729Sjoerg
54247330f729Sjoerg /// The non-zero enum values here are indexes into diagnostic alternatives.
54257330f729Sjoerg enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
54267330f729Sjoerg
54277330f729Sjoerg /// Determines whether this expression is an acceptable ICR source.
isInvalidICRSource(ASTContext & C,Expr * e,bool isAddressOf,bool & isWeakAccess)54287330f729Sjoerg static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
54297330f729Sjoerg bool isAddressOf, bool &isWeakAccess) {
54307330f729Sjoerg // Skip parens.
54317330f729Sjoerg e = e->IgnoreParens();
54327330f729Sjoerg
54337330f729Sjoerg // Skip address-of nodes.
54347330f729Sjoerg if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
54357330f729Sjoerg if (op->getOpcode() == UO_AddrOf)
54367330f729Sjoerg return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
54377330f729Sjoerg isWeakAccess);
54387330f729Sjoerg
54397330f729Sjoerg // Skip certain casts.
54407330f729Sjoerg } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
54417330f729Sjoerg switch (ce->getCastKind()) {
54427330f729Sjoerg case CK_Dependent:
54437330f729Sjoerg case CK_BitCast:
54447330f729Sjoerg case CK_LValueBitCast:
54457330f729Sjoerg case CK_NoOp:
54467330f729Sjoerg return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
54477330f729Sjoerg
54487330f729Sjoerg case CK_ArrayToPointerDecay:
54497330f729Sjoerg return IIK_nonscalar;
54507330f729Sjoerg
54517330f729Sjoerg case CK_NullToPointer:
54527330f729Sjoerg return IIK_okay;
54537330f729Sjoerg
54547330f729Sjoerg default:
54557330f729Sjoerg break;
54567330f729Sjoerg }
54577330f729Sjoerg
54587330f729Sjoerg // If we have a declaration reference, it had better be a local variable.
54597330f729Sjoerg } else if (isa<DeclRefExpr>(e)) {
54607330f729Sjoerg // set isWeakAccess to true, to mean that there will be an implicit
54617330f729Sjoerg // load which requires a cleanup.
54627330f729Sjoerg if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
54637330f729Sjoerg isWeakAccess = true;
54647330f729Sjoerg
54657330f729Sjoerg if (!isAddressOf) return IIK_nonlocal;
54667330f729Sjoerg
54677330f729Sjoerg VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
54687330f729Sjoerg if (!var) return IIK_nonlocal;
54697330f729Sjoerg
54707330f729Sjoerg return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
54717330f729Sjoerg
54727330f729Sjoerg // If we have a conditional operator, check both sides.
54737330f729Sjoerg } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
54747330f729Sjoerg if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
54757330f729Sjoerg isWeakAccess))
54767330f729Sjoerg return iik;
54777330f729Sjoerg
54787330f729Sjoerg return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
54797330f729Sjoerg
54807330f729Sjoerg // These are never scalar.
54817330f729Sjoerg } else if (isa<ArraySubscriptExpr>(e)) {
54827330f729Sjoerg return IIK_nonscalar;
54837330f729Sjoerg
54847330f729Sjoerg // Otherwise, it needs to be a null pointer constant.
54857330f729Sjoerg } else {
54867330f729Sjoerg return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
54877330f729Sjoerg ? IIK_okay : IIK_nonlocal);
54887330f729Sjoerg }
54897330f729Sjoerg
54907330f729Sjoerg return IIK_nonlocal;
54917330f729Sjoerg }
54927330f729Sjoerg
54937330f729Sjoerg /// Check whether the given expression is a valid operand for an
54947330f729Sjoerg /// indirect copy/restore.
checkIndirectCopyRestoreSource(Sema & S,Expr * src)54957330f729Sjoerg static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
54967330f729Sjoerg assert(src->isRValue());
54977330f729Sjoerg bool isWeakAccess = false;
54987330f729Sjoerg InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
54997330f729Sjoerg // If isWeakAccess to true, there will be an implicit
55007330f729Sjoerg // load which requires a cleanup.
55017330f729Sjoerg if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
55027330f729Sjoerg S.Cleanup.setExprNeedsCleanups(true);
55037330f729Sjoerg
55047330f729Sjoerg if (iik == IIK_okay) return;
55057330f729Sjoerg
55067330f729Sjoerg S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
55077330f729Sjoerg << ((unsigned) iik - 1) // shift index into diagnostic explanations
55087330f729Sjoerg << src->getSourceRange();
55097330f729Sjoerg }
55107330f729Sjoerg
55117330f729Sjoerg /// Determine whether we have compatible array types for the
55127330f729Sjoerg /// purposes of GNU by-copy array initialization.
hasCompatibleArrayTypes(ASTContext & Context,const ArrayType * Dest,const ArrayType * Source)55137330f729Sjoerg static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
55147330f729Sjoerg const ArrayType *Source) {
55157330f729Sjoerg // If the source and destination array types are equivalent, we're
55167330f729Sjoerg // done.
55177330f729Sjoerg if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
55187330f729Sjoerg return true;
55197330f729Sjoerg
55207330f729Sjoerg // Make sure that the element types are the same.
55217330f729Sjoerg if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
55227330f729Sjoerg return false;
55237330f729Sjoerg
55247330f729Sjoerg // The only mismatch we allow is when the destination is an
55257330f729Sjoerg // incomplete array type and the source is a constant array type.
55267330f729Sjoerg return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
55277330f729Sjoerg }
55287330f729Sjoerg
tryObjCWritebackConversion(Sema & S,InitializationSequence & Sequence,const InitializedEntity & Entity,Expr * Initializer)55297330f729Sjoerg static bool tryObjCWritebackConversion(Sema &S,
55307330f729Sjoerg InitializationSequence &Sequence,
55317330f729Sjoerg const InitializedEntity &Entity,
55327330f729Sjoerg Expr *Initializer) {
55337330f729Sjoerg bool ArrayDecay = false;
55347330f729Sjoerg QualType ArgType = Initializer->getType();
55357330f729Sjoerg QualType ArgPointee;
55367330f729Sjoerg if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
55377330f729Sjoerg ArrayDecay = true;
55387330f729Sjoerg ArgPointee = ArgArrayType->getElementType();
55397330f729Sjoerg ArgType = S.Context.getPointerType(ArgPointee);
55407330f729Sjoerg }
55417330f729Sjoerg
55427330f729Sjoerg // Handle write-back conversion.
55437330f729Sjoerg QualType ConvertedArgType;
55447330f729Sjoerg if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
55457330f729Sjoerg ConvertedArgType))
55467330f729Sjoerg return false;
55477330f729Sjoerg
55487330f729Sjoerg // We should copy unless we're passing to an argument explicitly
55497330f729Sjoerg // marked 'out'.
55507330f729Sjoerg bool ShouldCopy = true;
55517330f729Sjoerg if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
55527330f729Sjoerg ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
55537330f729Sjoerg
55547330f729Sjoerg // Do we need an lvalue conversion?
55557330f729Sjoerg if (ArrayDecay || Initializer->isGLValue()) {
55567330f729Sjoerg ImplicitConversionSequence ICS;
55577330f729Sjoerg ICS.setStandard();
55587330f729Sjoerg ICS.Standard.setAsIdentityConversion();
55597330f729Sjoerg
55607330f729Sjoerg QualType ResultType;
55617330f729Sjoerg if (ArrayDecay) {
55627330f729Sjoerg ICS.Standard.First = ICK_Array_To_Pointer;
55637330f729Sjoerg ResultType = S.Context.getPointerType(ArgPointee);
55647330f729Sjoerg } else {
55657330f729Sjoerg ICS.Standard.First = ICK_Lvalue_To_Rvalue;
55667330f729Sjoerg ResultType = Initializer->getType().getNonLValueExprType(S.Context);
55677330f729Sjoerg }
55687330f729Sjoerg
55697330f729Sjoerg Sequence.AddConversionSequenceStep(ICS, ResultType);
55707330f729Sjoerg }
55717330f729Sjoerg
55727330f729Sjoerg Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
55737330f729Sjoerg return true;
55747330f729Sjoerg }
55757330f729Sjoerg
TryOCLSamplerInitialization(Sema & S,InitializationSequence & Sequence,QualType DestType,Expr * Initializer)55767330f729Sjoerg static bool TryOCLSamplerInitialization(Sema &S,
55777330f729Sjoerg InitializationSequence &Sequence,
55787330f729Sjoerg QualType DestType,
55797330f729Sjoerg Expr *Initializer) {
55807330f729Sjoerg if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
55817330f729Sjoerg (!Initializer->isIntegerConstantExpr(S.Context) &&
55827330f729Sjoerg !Initializer->getType()->isSamplerT()))
55837330f729Sjoerg return false;
55847330f729Sjoerg
55857330f729Sjoerg Sequence.AddOCLSamplerInitStep(DestType);
55867330f729Sjoerg return true;
55877330f729Sjoerg }
55887330f729Sjoerg
IsZeroInitializer(Expr * Initializer,Sema & S)55897330f729Sjoerg static bool IsZeroInitializer(Expr *Initializer, Sema &S) {
55907330f729Sjoerg return Initializer->isIntegerConstantExpr(S.getASTContext()) &&
55917330f729Sjoerg (Initializer->EvaluateKnownConstInt(S.getASTContext()) == 0);
55927330f729Sjoerg }
55937330f729Sjoerg
TryOCLZeroOpaqueTypeInitialization(Sema & S,InitializationSequence & Sequence,QualType DestType,Expr * Initializer)55947330f729Sjoerg static bool TryOCLZeroOpaqueTypeInitialization(Sema &S,
55957330f729Sjoerg InitializationSequence &Sequence,
55967330f729Sjoerg QualType DestType,
55977330f729Sjoerg Expr *Initializer) {
55987330f729Sjoerg if (!S.getLangOpts().OpenCL)
55997330f729Sjoerg return false;
56007330f729Sjoerg
56017330f729Sjoerg //
56027330f729Sjoerg // OpenCL 1.2 spec, s6.12.10
56037330f729Sjoerg //
56047330f729Sjoerg // The event argument can also be used to associate the
56057330f729Sjoerg // async_work_group_copy with a previous async copy allowing
56067330f729Sjoerg // an event to be shared by multiple async copies; otherwise
56077330f729Sjoerg // event should be zero.
56087330f729Sjoerg //
56097330f729Sjoerg if (DestType->isEventT() || DestType->isQueueT()) {
56107330f729Sjoerg if (!IsZeroInitializer(Initializer, S))
56117330f729Sjoerg return false;
56127330f729Sjoerg
56137330f729Sjoerg Sequence.AddOCLZeroOpaqueTypeStep(DestType);
56147330f729Sjoerg return true;
56157330f729Sjoerg }
56167330f729Sjoerg
56177330f729Sjoerg // We should allow zero initialization for all types defined in the
56187330f729Sjoerg // cl_intel_device_side_avc_motion_estimation extension, except
56197330f729Sjoerg // intel_sub_group_avc_mce_payload_t and intel_sub_group_avc_mce_result_t.
5620*e038c9c4Sjoerg if (S.getOpenCLOptions().isAvailableOption(
5621*e038c9c4Sjoerg "cl_intel_device_side_avc_motion_estimation", S.getLangOpts()) &&
56227330f729Sjoerg DestType->isOCLIntelSubgroupAVCType()) {
56237330f729Sjoerg if (DestType->isOCLIntelSubgroupAVCMcePayloadType() ||
56247330f729Sjoerg DestType->isOCLIntelSubgroupAVCMceResultType())
56257330f729Sjoerg return false;
56267330f729Sjoerg if (!IsZeroInitializer(Initializer, S))
56277330f729Sjoerg return false;
56287330f729Sjoerg
56297330f729Sjoerg Sequence.AddOCLZeroOpaqueTypeStep(DestType);
56307330f729Sjoerg return true;
56317330f729Sjoerg }
56327330f729Sjoerg
56337330f729Sjoerg return false;
56347330f729Sjoerg }
56357330f729Sjoerg
InitializationSequence(Sema & S,const InitializedEntity & Entity,const InitializationKind & Kind,MultiExprArg Args,bool TopLevelOfInitList,bool TreatUnavailableAsInvalid)5636*e038c9c4Sjoerg InitializationSequence::InitializationSequence(
5637*e038c9c4Sjoerg Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
5638*e038c9c4Sjoerg MultiExprArg Args, bool TopLevelOfInitList, bool TreatUnavailableAsInvalid)
5639*e038c9c4Sjoerg : FailedOverloadResult(OR_Success),
5640*e038c9c4Sjoerg FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
56417330f729Sjoerg InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList,
56427330f729Sjoerg TreatUnavailableAsInvalid);
56437330f729Sjoerg }
56447330f729Sjoerg
56457330f729Sjoerg /// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
56467330f729Sjoerg /// address of that function, this returns true. Otherwise, it returns false.
isExprAnUnaddressableFunction(Sema & S,const Expr * E)56477330f729Sjoerg static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) {
56487330f729Sjoerg auto *DRE = dyn_cast<DeclRefExpr>(E);
56497330f729Sjoerg if (!DRE || !isa<FunctionDecl>(DRE->getDecl()))
56507330f729Sjoerg return false;
56517330f729Sjoerg
56527330f729Sjoerg return !S.checkAddressOfFunctionIsAvailable(
56537330f729Sjoerg cast<FunctionDecl>(DRE->getDecl()));
56547330f729Sjoerg }
56557330f729Sjoerg
56567330f729Sjoerg /// Determine whether we can perform an elementwise array copy for this kind
56577330f729Sjoerg /// of entity.
canPerformArrayCopy(const InitializedEntity & Entity)56587330f729Sjoerg static bool canPerformArrayCopy(const InitializedEntity &Entity) {
56597330f729Sjoerg switch (Entity.getKind()) {
56607330f729Sjoerg case InitializedEntity::EK_LambdaCapture:
56617330f729Sjoerg // C++ [expr.prim.lambda]p24:
56627330f729Sjoerg // For array members, the array elements are direct-initialized in
56637330f729Sjoerg // increasing subscript order.
56647330f729Sjoerg return true;
56657330f729Sjoerg
56667330f729Sjoerg case InitializedEntity::EK_Variable:
56677330f729Sjoerg // C++ [dcl.decomp]p1:
56687330f729Sjoerg // [...] each element is copy-initialized or direct-initialized from the
56697330f729Sjoerg // corresponding element of the assignment-expression [...]
56707330f729Sjoerg return isa<DecompositionDecl>(Entity.getDecl());
56717330f729Sjoerg
56727330f729Sjoerg case InitializedEntity::EK_Member:
56737330f729Sjoerg // C++ [class.copy.ctor]p14:
56747330f729Sjoerg // - if the member is an array, each element is direct-initialized with
56757330f729Sjoerg // the corresponding subobject of x
56767330f729Sjoerg return Entity.isImplicitMemberInitializer();
56777330f729Sjoerg
56787330f729Sjoerg case InitializedEntity::EK_ArrayElement:
56797330f729Sjoerg // All the above cases are intended to apply recursively, even though none
56807330f729Sjoerg // of them actually say that.
56817330f729Sjoerg if (auto *E = Entity.getParent())
56827330f729Sjoerg return canPerformArrayCopy(*E);
56837330f729Sjoerg break;
56847330f729Sjoerg
56857330f729Sjoerg default:
56867330f729Sjoerg break;
56877330f729Sjoerg }
56887330f729Sjoerg
56897330f729Sjoerg return false;
56907330f729Sjoerg }
56917330f729Sjoerg
InitializeFrom(Sema & S,const InitializedEntity & Entity,const InitializationKind & Kind,MultiExprArg Args,bool TopLevelOfInitList,bool TreatUnavailableAsInvalid)56927330f729Sjoerg void InitializationSequence::InitializeFrom(Sema &S,
56937330f729Sjoerg const InitializedEntity &Entity,
56947330f729Sjoerg const InitializationKind &Kind,
56957330f729Sjoerg MultiExprArg Args,
56967330f729Sjoerg bool TopLevelOfInitList,
56977330f729Sjoerg bool TreatUnavailableAsInvalid) {
56987330f729Sjoerg ASTContext &Context = S.Context;
56997330f729Sjoerg
57007330f729Sjoerg // Eliminate non-overload placeholder types in the arguments. We
57017330f729Sjoerg // need to do this before checking whether types are dependent
57027330f729Sjoerg // because lowering a pseudo-object expression might well give us
57037330f729Sjoerg // something of dependent type.
57047330f729Sjoerg for (unsigned I = 0, E = Args.size(); I != E; ++I)
57057330f729Sjoerg if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
57067330f729Sjoerg // FIXME: should we be doing this here?
57077330f729Sjoerg ExprResult result = S.CheckPlaceholderExpr(Args[I]);
57087330f729Sjoerg if (result.isInvalid()) {
57097330f729Sjoerg SetFailed(FK_PlaceholderType);
57107330f729Sjoerg return;
57117330f729Sjoerg }
57127330f729Sjoerg Args[I] = result.get();
57137330f729Sjoerg }
57147330f729Sjoerg
57157330f729Sjoerg // C++0x [dcl.init]p16:
57167330f729Sjoerg // The semantics of initializers are as follows. The destination type is
57177330f729Sjoerg // the type of the object or reference being initialized and the source
57187330f729Sjoerg // type is the type of the initializer expression. The source type is not
57197330f729Sjoerg // defined when the initializer is a braced-init-list or when it is a
57207330f729Sjoerg // parenthesized list of expressions.
57217330f729Sjoerg QualType DestType = Entity.getType();
57227330f729Sjoerg
57237330f729Sjoerg if (DestType->isDependentType() ||
57247330f729Sjoerg Expr::hasAnyTypeDependentArguments(Args)) {
57257330f729Sjoerg SequenceKind = DependentSequence;
57267330f729Sjoerg return;
57277330f729Sjoerg }
57287330f729Sjoerg
57297330f729Sjoerg // Almost everything is a normal sequence.
57307330f729Sjoerg setSequenceKind(NormalSequence);
57317330f729Sjoerg
57327330f729Sjoerg QualType SourceType;
57337330f729Sjoerg Expr *Initializer = nullptr;
57347330f729Sjoerg if (Args.size() == 1) {
57357330f729Sjoerg Initializer = Args[0];
57367330f729Sjoerg if (S.getLangOpts().ObjC) {
57377330f729Sjoerg if (S.CheckObjCBridgeRelatedConversions(Initializer->getBeginLoc(),
57387330f729Sjoerg DestType, Initializer->getType(),
57397330f729Sjoerg Initializer) ||
5740*e038c9c4Sjoerg S.CheckConversionToObjCLiteral(DestType, Initializer))
57417330f729Sjoerg Args[0] = Initializer;
57427330f729Sjoerg }
57437330f729Sjoerg if (!isa<InitListExpr>(Initializer))
57447330f729Sjoerg SourceType = Initializer->getType();
57457330f729Sjoerg }
57467330f729Sjoerg
57477330f729Sjoerg // - If the initializer is a (non-parenthesized) braced-init-list, the
57487330f729Sjoerg // object is list-initialized (8.5.4).
57497330f729Sjoerg if (Kind.getKind() != InitializationKind::IK_Direct) {
57507330f729Sjoerg if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
57517330f729Sjoerg TryListInitialization(S, Entity, Kind, InitList, *this,
57527330f729Sjoerg TreatUnavailableAsInvalid);
57537330f729Sjoerg return;
57547330f729Sjoerg }
57557330f729Sjoerg }
57567330f729Sjoerg
57577330f729Sjoerg // - If the destination type is a reference type, see 8.5.3.
57587330f729Sjoerg if (DestType->isReferenceType()) {
57597330f729Sjoerg // C++0x [dcl.init.ref]p1:
57607330f729Sjoerg // A variable declared to be a T& or T&&, that is, "reference to type T"
57617330f729Sjoerg // (8.3.2), shall be initialized by an object, or function, of type T or
57627330f729Sjoerg // by an object that can be converted into a T.
57637330f729Sjoerg // (Therefore, multiple arguments are not permitted.)
57647330f729Sjoerg if (Args.size() != 1)
57657330f729Sjoerg SetFailed(FK_TooManyInitsForReference);
57667330f729Sjoerg // C++17 [dcl.init.ref]p5:
57677330f729Sjoerg // A reference [...] is initialized by an expression [...] as follows:
57687330f729Sjoerg // If the initializer is not an expression, presumably we should reject,
57697330f729Sjoerg // but the standard fails to actually say so.
57707330f729Sjoerg else if (isa<InitListExpr>(Args[0]))
57717330f729Sjoerg SetFailed(FK_ParenthesizedListInitForReference);
57727330f729Sjoerg else
57737330f729Sjoerg TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
57747330f729Sjoerg return;
57757330f729Sjoerg }
57767330f729Sjoerg
57777330f729Sjoerg // - If the initializer is (), the object is value-initialized.
57787330f729Sjoerg if (Kind.getKind() == InitializationKind::IK_Value ||
57797330f729Sjoerg (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
57807330f729Sjoerg TryValueInitialization(S, Entity, Kind, *this);
57817330f729Sjoerg return;
57827330f729Sjoerg }
57837330f729Sjoerg
57847330f729Sjoerg // Handle default initialization.
57857330f729Sjoerg if (Kind.getKind() == InitializationKind::IK_Default) {
57867330f729Sjoerg TryDefaultInitialization(S, Entity, Kind, *this);
57877330f729Sjoerg return;
57887330f729Sjoerg }
57897330f729Sjoerg
57907330f729Sjoerg // - If the destination type is an array of characters, an array of
57917330f729Sjoerg // char16_t, an array of char32_t, or an array of wchar_t, and the
57927330f729Sjoerg // initializer is a string literal, see 8.5.2.
57937330f729Sjoerg // - Otherwise, if the destination type is an array, the program is
57947330f729Sjoerg // ill-formed.
57957330f729Sjoerg if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
57967330f729Sjoerg if (Initializer && isa<VariableArrayType>(DestAT)) {
57977330f729Sjoerg SetFailed(FK_VariableLengthArrayHasInitializer);
57987330f729Sjoerg return;
57997330f729Sjoerg }
58007330f729Sjoerg
58017330f729Sjoerg if (Initializer) {
58027330f729Sjoerg switch (IsStringInit(Initializer, DestAT, Context)) {
58037330f729Sjoerg case SIF_None:
58047330f729Sjoerg TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
58057330f729Sjoerg return;
58067330f729Sjoerg case SIF_NarrowStringIntoWideChar:
58077330f729Sjoerg SetFailed(FK_NarrowStringIntoWideCharArray);
58087330f729Sjoerg return;
58097330f729Sjoerg case SIF_WideStringIntoChar:
58107330f729Sjoerg SetFailed(FK_WideStringIntoCharArray);
58117330f729Sjoerg return;
58127330f729Sjoerg case SIF_IncompatWideStringIntoWideChar:
58137330f729Sjoerg SetFailed(FK_IncompatWideStringIntoWideChar);
58147330f729Sjoerg return;
58157330f729Sjoerg case SIF_PlainStringIntoUTF8Char:
58167330f729Sjoerg SetFailed(FK_PlainStringIntoUTF8Char);
58177330f729Sjoerg return;
58187330f729Sjoerg case SIF_UTF8StringIntoPlainChar:
58197330f729Sjoerg SetFailed(FK_UTF8StringIntoPlainChar);
58207330f729Sjoerg return;
58217330f729Sjoerg case SIF_Other:
58227330f729Sjoerg break;
58237330f729Sjoerg }
58247330f729Sjoerg }
58257330f729Sjoerg
58267330f729Sjoerg // Some kinds of initialization permit an array to be initialized from
58277330f729Sjoerg // another array of the same type, and perform elementwise initialization.
58287330f729Sjoerg if (Initializer && isa<ConstantArrayType>(DestAT) &&
58297330f729Sjoerg S.Context.hasSameUnqualifiedType(Initializer->getType(),
58307330f729Sjoerg Entity.getType()) &&
58317330f729Sjoerg canPerformArrayCopy(Entity)) {
58327330f729Sjoerg // If source is a prvalue, use it directly.
58337330f729Sjoerg if (Initializer->getValueKind() == VK_RValue) {
58347330f729Sjoerg AddArrayInitStep(DestType, /*IsGNUExtension*/false);
58357330f729Sjoerg return;
58367330f729Sjoerg }
58377330f729Sjoerg
58387330f729Sjoerg // Emit element-at-a-time copy loop.
58397330f729Sjoerg InitializedEntity Element =
58407330f729Sjoerg InitializedEntity::InitializeElement(S.Context, 0, Entity);
58417330f729Sjoerg QualType InitEltT =
58427330f729Sjoerg Context.getAsArrayType(Initializer->getType())->getElementType();
58437330f729Sjoerg OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT,
58447330f729Sjoerg Initializer->getValueKind(),
58457330f729Sjoerg Initializer->getObjectKind());
58467330f729Sjoerg Expr *OVEAsExpr = &OVE;
58477330f729Sjoerg InitializeFrom(S, Element, Kind, OVEAsExpr, TopLevelOfInitList,
58487330f729Sjoerg TreatUnavailableAsInvalid);
58497330f729Sjoerg if (!Failed())
58507330f729Sjoerg AddArrayInitLoopStep(Entity.getType(), InitEltT);
58517330f729Sjoerg return;
58527330f729Sjoerg }
58537330f729Sjoerg
58547330f729Sjoerg // Note: as an GNU C extension, we allow initialization of an
58557330f729Sjoerg // array from a compound literal that creates an array of the same
58567330f729Sjoerg // type, so long as the initializer has no side effects.
58577330f729Sjoerg if (!S.getLangOpts().CPlusPlus && Initializer &&
58587330f729Sjoerg isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
58597330f729Sjoerg Initializer->getType()->isArrayType()) {
58607330f729Sjoerg const ArrayType *SourceAT
58617330f729Sjoerg = Context.getAsArrayType(Initializer->getType());
58627330f729Sjoerg if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
58637330f729Sjoerg SetFailed(FK_ArrayTypeMismatch);
58647330f729Sjoerg else if (Initializer->HasSideEffects(S.Context))
58657330f729Sjoerg SetFailed(FK_NonConstantArrayInit);
58667330f729Sjoerg else {
58677330f729Sjoerg AddArrayInitStep(DestType, /*IsGNUExtension*/true);
58687330f729Sjoerg }
58697330f729Sjoerg }
58707330f729Sjoerg // Note: as a GNU C++ extension, we allow list-initialization of a
58717330f729Sjoerg // class member of array type from a parenthesized initializer list.
58727330f729Sjoerg else if (S.getLangOpts().CPlusPlus &&
58737330f729Sjoerg Entity.getKind() == InitializedEntity::EK_Member &&
58747330f729Sjoerg Initializer && isa<InitListExpr>(Initializer)) {
58757330f729Sjoerg TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
58767330f729Sjoerg *this, TreatUnavailableAsInvalid);
58777330f729Sjoerg AddParenthesizedArrayInitStep(DestType);
58787330f729Sjoerg } else if (DestAT->getElementType()->isCharType())
58797330f729Sjoerg SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
58807330f729Sjoerg else if (IsWideCharCompatible(DestAT->getElementType(), Context))
58817330f729Sjoerg SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
58827330f729Sjoerg else
58837330f729Sjoerg SetFailed(FK_ArrayNeedsInitList);
58847330f729Sjoerg
58857330f729Sjoerg return;
58867330f729Sjoerg }
58877330f729Sjoerg
58887330f729Sjoerg // Determine whether we should consider writeback conversions for
58897330f729Sjoerg // Objective-C ARC.
58907330f729Sjoerg bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
58917330f729Sjoerg Entity.isParameterKind();
58927330f729Sjoerg
58937330f729Sjoerg if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
58947330f729Sjoerg return;
58957330f729Sjoerg
58967330f729Sjoerg // We're at the end of the line for C: it's either a write-back conversion
58977330f729Sjoerg // or it's a C assignment. There's no need to check anything else.
58987330f729Sjoerg if (!S.getLangOpts().CPlusPlus) {
58997330f729Sjoerg // If allowed, check whether this is an Objective-C writeback conversion.
59007330f729Sjoerg if (allowObjCWritebackConversion &&
59017330f729Sjoerg tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
59027330f729Sjoerg return;
59037330f729Sjoerg }
59047330f729Sjoerg
59057330f729Sjoerg if (TryOCLZeroOpaqueTypeInitialization(S, *this, DestType, Initializer))
59067330f729Sjoerg return;
59077330f729Sjoerg
59087330f729Sjoerg // Handle initialization in C
59097330f729Sjoerg AddCAssignmentStep(DestType);
59107330f729Sjoerg MaybeProduceObjCObject(S, *this, Entity);
59117330f729Sjoerg return;
59127330f729Sjoerg }
59137330f729Sjoerg
59147330f729Sjoerg assert(S.getLangOpts().CPlusPlus);
59157330f729Sjoerg
59167330f729Sjoerg // - If the destination type is a (possibly cv-qualified) class type:
59177330f729Sjoerg if (DestType->isRecordType()) {
59187330f729Sjoerg // - If the initialization is direct-initialization, or if it is
59197330f729Sjoerg // copy-initialization where the cv-unqualified version of the
59207330f729Sjoerg // source type is the same class as, or a derived class of, the
59217330f729Sjoerg // class of the destination, constructors are considered. [...]
59227330f729Sjoerg if (Kind.getKind() == InitializationKind::IK_Direct ||
59237330f729Sjoerg (Kind.getKind() == InitializationKind::IK_Copy &&
59247330f729Sjoerg (Context.hasSameUnqualifiedType(SourceType, DestType) ||
59257330f729Sjoerg S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType, DestType))))
59267330f729Sjoerg TryConstructorInitialization(S, Entity, Kind, Args,
59277330f729Sjoerg DestType, DestType, *this);
59287330f729Sjoerg // - Otherwise (i.e., for the remaining copy-initialization cases),
59297330f729Sjoerg // user-defined conversion sequences that can convert from the source
59307330f729Sjoerg // type to the destination type or (when a conversion function is
59317330f729Sjoerg // used) to a derived class thereof are enumerated as described in
59327330f729Sjoerg // 13.3.1.4, and the best one is chosen through overload resolution
59337330f729Sjoerg // (13.3).
59347330f729Sjoerg else
59357330f729Sjoerg TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
59367330f729Sjoerg TopLevelOfInitList);
59377330f729Sjoerg return;
59387330f729Sjoerg }
59397330f729Sjoerg
59407330f729Sjoerg assert(Args.size() >= 1 && "Zero-argument case handled above");
59417330f729Sjoerg
59427330f729Sjoerg // The remaining cases all need a source type.
59437330f729Sjoerg if (Args.size() > 1) {
59447330f729Sjoerg SetFailed(FK_TooManyInitsForScalar);
59457330f729Sjoerg return;
59467330f729Sjoerg } else if (isa<InitListExpr>(Args[0])) {
59477330f729Sjoerg SetFailed(FK_ParenthesizedListInitForScalar);
59487330f729Sjoerg return;
59497330f729Sjoerg }
59507330f729Sjoerg
59517330f729Sjoerg // - Otherwise, if the source type is a (possibly cv-qualified) class
59527330f729Sjoerg // type, conversion functions are considered.
59537330f729Sjoerg if (!SourceType.isNull() && SourceType->isRecordType()) {
59547330f729Sjoerg // For a conversion to _Atomic(T) from either T or a class type derived
59557330f729Sjoerg // from T, initialize the T object then convert to _Atomic type.
59567330f729Sjoerg bool NeedAtomicConversion = false;
59577330f729Sjoerg if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
59587330f729Sjoerg if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
59597330f729Sjoerg S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType,
59607330f729Sjoerg Atomic->getValueType())) {
59617330f729Sjoerg DestType = Atomic->getValueType();
59627330f729Sjoerg NeedAtomicConversion = true;
59637330f729Sjoerg }
59647330f729Sjoerg }
59657330f729Sjoerg
59667330f729Sjoerg TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
59677330f729Sjoerg TopLevelOfInitList);
59687330f729Sjoerg MaybeProduceObjCObject(S, *this, Entity);
59697330f729Sjoerg if (!Failed() && NeedAtomicConversion)
59707330f729Sjoerg AddAtomicConversionStep(Entity.getType());
59717330f729Sjoerg return;
59727330f729Sjoerg }
59737330f729Sjoerg
5974*e038c9c4Sjoerg // - Otherwise, if the initialization is direct-initialization, the source
5975*e038c9c4Sjoerg // type is std::nullptr_t, and the destination type is bool, the initial
5976*e038c9c4Sjoerg // value of the object being initialized is false.
5977*e038c9c4Sjoerg if (!SourceType.isNull() && SourceType->isNullPtrType() &&
5978*e038c9c4Sjoerg DestType->isBooleanType() &&
5979*e038c9c4Sjoerg Kind.getKind() == InitializationKind::IK_Direct) {
5980*e038c9c4Sjoerg AddConversionSequenceStep(
5981*e038c9c4Sjoerg ImplicitConversionSequence::getNullptrToBool(SourceType, DestType,
5982*e038c9c4Sjoerg Initializer->isGLValue()),
5983*e038c9c4Sjoerg DestType);
5984*e038c9c4Sjoerg return;
5985*e038c9c4Sjoerg }
5986*e038c9c4Sjoerg
59877330f729Sjoerg // - Otherwise, the initial value of the object being initialized is the
59887330f729Sjoerg // (possibly converted) value of the initializer expression. Standard
59897330f729Sjoerg // conversions (Clause 4) will be used, if necessary, to convert the
59907330f729Sjoerg // initializer expression to the cv-unqualified version of the
59917330f729Sjoerg // destination type; no user-defined conversions are considered.
59927330f729Sjoerg
59937330f729Sjoerg ImplicitConversionSequence ICS
59947330f729Sjoerg = S.TryImplicitConversion(Initializer, DestType,
59957330f729Sjoerg /*SuppressUserConversions*/true,
5996*e038c9c4Sjoerg Sema::AllowedExplicit::None,
59977330f729Sjoerg /*InOverloadResolution*/ false,
59987330f729Sjoerg /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
59997330f729Sjoerg allowObjCWritebackConversion);
60007330f729Sjoerg
60017330f729Sjoerg if (ICS.isStandard() &&
60027330f729Sjoerg ICS.Standard.Second == ICK_Writeback_Conversion) {
60037330f729Sjoerg // Objective-C ARC writeback conversion.
60047330f729Sjoerg
60057330f729Sjoerg // We should copy unless we're passing to an argument explicitly
60067330f729Sjoerg // marked 'out'.
60077330f729Sjoerg bool ShouldCopy = true;
60087330f729Sjoerg if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
60097330f729Sjoerg ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
60107330f729Sjoerg
60117330f729Sjoerg // If there was an lvalue adjustment, add it as a separate conversion.
60127330f729Sjoerg if (ICS.Standard.First == ICK_Array_To_Pointer ||
60137330f729Sjoerg ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
60147330f729Sjoerg ImplicitConversionSequence LvalueICS;
60157330f729Sjoerg LvalueICS.setStandard();
60167330f729Sjoerg LvalueICS.Standard.setAsIdentityConversion();
60177330f729Sjoerg LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
60187330f729Sjoerg LvalueICS.Standard.First = ICS.Standard.First;
60197330f729Sjoerg AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
60207330f729Sjoerg }
60217330f729Sjoerg
60227330f729Sjoerg AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
60237330f729Sjoerg } else if (ICS.isBad()) {
60247330f729Sjoerg DeclAccessPair dap;
60257330f729Sjoerg if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
60267330f729Sjoerg AddZeroInitializationStep(Entity.getType());
60277330f729Sjoerg } else if (Initializer->getType() == Context.OverloadTy &&
60287330f729Sjoerg !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
60297330f729Sjoerg false, dap))
60307330f729Sjoerg SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
60317330f729Sjoerg else if (Initializer->getType()->isFunctionType() &&
60327330f729Sjoerg isExprAnUnaddressableFunction(S, Initializer))
60337330f729Sjoerg SetFailed(InitializationSequence::FK_AddressOfUnaddressableFunction);
60347330f729Sjoerg else
60357330f729Sjoerg SetFailed(InitializationSequence::FK_ConversionFailed);
60367330f729Sjoerg } else {
60377330f729Sjoerg AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
60387330f729Sjoerg
60397330f729Sjoerg MaybeProduceObjCObject(S, *this, Entity);
60407330f729Sjoerg }
60417330f729Sjoerg }
60427330f729Sjoerg
~InitializationSequence()60437330f729Sjoerg InitializationSequence::~InitializationSequence() {
60447330f729Sjoerg for (auto &S : Steps)
60457330f729Sjoerg S.Destroy();
60467330f729Sjoerg }
60477330f729Sjoerg
60487330f729Sjoerg //===----------------------------------------------------------------------===//
60497330f729Sjoerg // Perform initialization
60507330f729Sjoerg //===----------------------------------------------------------------------===//
60517330f729Sjoerg static Sema::AssignmentAction
getAssignmentAction(const InitializedEntity & Entity,bool Diagnose=false)60527330f729Sjoerg getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
60537330f729Sjoerg switch(Entity.getKind()) {
60547330f729Sjoerg case InitializedEntity::EK_Variable:
60557330f729Sjoerg case InitializedEntity::EK_New:
60567330f729Sjoerg case InitializedEntity::EK_Exception:
60577330f729Sjoerg case InitializedEntity::EK_Base:
60587330f729Sjoerg case InitializedEntity::EK_Delegating:
60597330f729Sjoerg return Sema::AA_Initializing;
60607330f729Sjoerg
60617330f729Sjoerg case InitializedEntity::EK_Parameter:
60627330f729Sjoerg if (Entity.getDecl() &&
60637330f729Sjoerg isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
60647330f729Sjoerg return Sema::AA_Sending;
60657330f729Sjoerg
60667330f729Sjoerg return Sema::AA_Passing;
60677330f729Sjoerg
60687330f729Sjoerg case InitializedEntity::EK_Parameter_CF_Audited:
60697330f729Sjoerg if (Entity.getDecl() &&
60707330f729Sjoerg isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
60717330f729Sjoerg return Sema::AA_Sending;
60727330f729Sjoerg
60737330f729Sjoerg return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
60747330f729Sjoerg
60757330f729Sjoerg case InitializedEntity::EK_Result:
60767330f729Sjoerg case InitializedEntity::EK_StmtExprResult: // FIXME: Not quite right.
60777330f729Sjoerg return Sema::AA_Returning;
60787330f729Sjoerg
60797330f729Sjoerg case InitializedEntity::EK_Temporary:
60807330f729Sjoerg case InitializedEntity::EK_RelatedResult:
60817330f729Sjoerg // FIXME: Can we tell apart casting vs. converting?
60827330f729Sjoerg return Sema::AA_Casting;
60837330f729Sjoerg
6084*e038c9c4Sjoerg case InitializedEntity::EK_TemplateParameter:
6085*e038c9c4Sjoerg // This is really initialization, but refer to it as conversion for
6086*e038c9c4Sjoerg // consistency with CheckConvertedConstantExpression.
6087*e038c9c4Sjoerg return Sema::AA_Converting;
6088*e038c9c4Sjoerg
60897330f729Sjoerg case InitializedEntity::EK_Member:
60907330f729Sjoerg case InitializedEntity::EK_Binding:
60917330f729Sjoerg case InitializedEntity::EK_ArrayElement:
60927330f729Sjoerg case InitializedEntity::EK_VectorElement:
60937330f729Sjoerg case InitializedEntity::EK_ComplexElement:
60947330f729Sjoerg case InitializedEntity::EK_BlockElement:
60957330f729Sjoerg case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
60967330f729Sjoerg case InitializedEntity::EK_LambdaCapture:
60977330f729Sjoerg case InitializedEntity::EK_CompoundLiteralInit:
60987330f729Sjoerg return Sema::AA_Initializing;
60997330f729Sjoerg }
61007330f729Sjoerg
61017330f729Sjoerg llvm_unreachable("Invalid EntityKind!");
61027330f729Sjoerg }
61037330f729Sjoerg
61047330f729Sjoerg /// Whether we should bind a created object as a temporary when
61057330f729Sjoerg /// initializing the given entity.
shouldBindAsTemporary(const InitializedEntity & Entity)61067330f729Sjoerg static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
61077330f729Sjoerg switch (Entity.getKind()) {
61087330f729Sjoerg case InitializedEntity::EK_ArrayElement:
61097330f729Sjoerg case InitializedEntity::EK_Member:
61107330f729Sjoerg case InitializedEntity::EK_Result:
61117330f729Sjoerg case InitializedEntity::EK_StmtExprResult:
61127330f729Sjoerg case InitializedEntity::EK_New:
61137330f729Sjoerg case InitializedEntity::EK_Variable:
61147330f729Sjoerg case InitializedEntity::EK_Base:
61157330f729Sjoerg case InitializedEntity::EK_Delegating:
61167330f729Sjoerg case InitializedEntity::EK_VectorElement:
61177330f729Sjoerg case InitializedEntity::EK_ComplexElement:
61187330f729Sjoerg case InitializedEntity::EK_Exception:
61197330f729Sjoerg case InitializedEntity::EK_BlockElement:
61207330f729Sjoerg case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
61217330f729Sjoerg case InitializedEntity::EK_LambdaCapture:
61227330f729Sjoerg case InitializedEntity::EK_CompoundLiteralInit:
6123*e038c9c4Sjoerg case InitializedEntity::EK_TemplateParameter:
61247330f729Sjoerg return false;
61257330f729Sjoerg
61267330f729Sjoerg case InitializedEntity::EK_Parameter:
61277330f729Sjoerg case InitializedEntity::EK_Parameter_CF_Audited:
61287330f729Sjoerg case InitializedEntity::EK_Temporary:
61297330f729Sjoerg case InitializedEntity::EK_RelatedResult:
61307330f729Sjoerg case InitializedEntity::EK_Binding:
61317330f729Sjoerg return true;
61327330f729Sjoerg }
61337330f729Sjoerg
61347330f729Sjoerg llvm_unreachable("missed an InitializedEntity kind?");
61357330f729Sjoerg }
61367330f729Sjoerg
61377330f729Sjoerg /// Whether the given entity, when initialized with an object
61387330f729Sjoerg /// created for that initialization, requires destruction.
shouldDestroyEntity(const InitializedEntity & Entity)61397330f729Sjoerg static bool shouldDestroyEntity(const InitializedEntity &Entity) {
61407330f729Sjoerg switch (Entity.getKind()) {
61417330f729Sjoerg case InitializedEntity::EK_Result:
61427330f729Sjoerg case InitializedEntity::EK_StmtExprResult:
61437330f729Sjoerg case InitializedEntity::EK_New:
61447330f729Sjoerg case InitializedEntity::EK_Base:
61457330f729Sjoerg case InitializedEntity::EK_Delegating:
61467330f729Sjoerg case InitializedEntity::EK_VectorElement:
61477330f729Sjoerg case InitializedEntity::EK_ComplexElement:
61487330f729Sjoerg case InitializedEntity::EK_BlockElement:
61497330f729Sjoerg case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
61507330f729Sjoerg case InitializedEntity::EK_LambdaCapture:
61517330f729Sjoerg return false;
61527330f729Sjoerg
61537330f729Sjoerg case InitializedEntity::EK_Member:
61547330f729Sjoerg case InitializedEntity::EK_Binding:
61557330f729Sjoerg case InitializedEntity::EK_Variable:
61567330f729Sjoerg case InitializedEntity::EK_Parameter:
61577330f729Sjoerg case InitializedEntity::EK_Parameter_CF_Audited:
6158*e038c9c4Sjoerg case InitializedEntity::EK_TemplateParameter:
61597330f729Sjoerg case InitializedEntity::EK_Temporary:
61607330f729Sjoerg case InitializedEntity::EK_ArrayElement:
61617330f729Sjoerg case InitializedEntity::EK_Exception:
61627330f729Sjoerg case InitializedEntity::EK_CompoundLiteralInit:
61637330f729Sjoerg case InitializedEntity::EK_RelatedResult:
61647330f729Sjoerg return true;
61657330f729Sjoerg }
61667330f729Sjoerg
61677330f729Sjoerg llvm_unreachable("missed an InitializedEntity kind?");
61687330f729Sjoerg }
61697330f729Sjoerg
61707330f729Sjoerg /// Get the location at which initialization diagnostics should appear.
getInitializationLoc(const InitializedEntity & Entity,Expr * Initializer)61717330f729Sjoerg static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
61727330f729Sjoerg Expr *Initializer) {
61737330f729Sjoerg switch (Entity.getKind()) {
61747330f729Sjoerg case InitializedEntity::EK_Result:
61757330f729Sjoerg case InitializedEntity::EK_StmtExprResult:
61767330f729Sjoerg return Entity.getReturnLoc();
61777330f729Sjoerg
61787330f729Sjoerg case InitializedEntity::EK_Exception:
61797330f729Sjoerg return Entity.getThrowLoc();
61807330f729Sjoerg
61817330f729Sjoerg case InitializedEntity::EK_Variable:
61827330f729Sjoerg case InitializedEntity::EK_Binding:
61837330f729Sjoerg return Entity.getDecl()->getLocation();
61847330f729Sjoerg
61857330f729Sjoerg case InitializedEntity::EK_LambdaCapture:
61867330f729Sjoerg return Entity.getCaptureLoc();
61877330f729Sjoerg
61887330f729Sjoerg case InitializedEntity::EK_ArrayElement:
61897330f729Sjoerg case InitializedEntity::EK_Member:
61907330f729Sjoerg case InitializedEntity::EK_Parameter:
61917330f729Sjoerg case InitializedEntity::EK_Parameter_CF_Audited:
6192*e038c9c4Sjoerg case InitializedEntity::EK_TemplateParameter:
61937330f729Sjoerg case InitializedEntity::EK_Temporary:
61947330f729Sjoerg case InitializedEntity::EK_New:
61957330f729Sjoerg case InitializedEntity::EK_Base:
61967330f729Sjoerg case InitializedEntity::EK_Delegating:
61977330f729Sjoerg case InitializedEntity::EK_VectorElement:
61987330f729Sjoerg case InitializedEntity::EK_ComplexElement:
61997330f729Sjoerg case InitializedEntity::EK_BlockElement:
62007330f729Sjoerg case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
62017330f729Sjoerg case InitializedEntity::EK_CompoundLiteralInit:
62027330f729Sjoerg case InitializedEntity::EK_RelatedResult:
62037330f729Sjoerg return Initializer->getBeginLoc();
62047330f729Sjoerg }
62057330f729Sjoerg llvm_unreachable("missed an InitializedEntity kind?");
62067330f729Sjoerg }
62077330f729Sjoerg
62087330f729Sjoerg /// Make a (potentially elidable) temporary copy of the object
62097330f729Sjoerg /// provided by the given initializer by calling the appropriate copy
62107330f729Sjoerg /// constructor.
62117330f729Sjoerg ///
62127330f729Sjoerg /// \param S The Sema object used for type-checking.
62137330f729Sjoerg ///
62147330f729Sjoerg /// \param T The type of the temporary object, which must either be
62157330f729Sjoerg /// the type of the initializer expression or a superclass thereof.
62167330f729Sjoerg ///
62177330f729Sjoerg /// \param Entity The entity being initialized.
62187330f729Sjoerg ///
62197330f729Sjoerg /// \param CurInit The initializer expression.
62207330f729Sjoerg ///
62217330f729Sjoerg /// \param IsExtraneousCopy Whether this is an "extraneous" copy that
62227330f729Sjoerg /// is permitted in C++03 (but not C++0x) when binding a reference to
62237330f729Sjoerg /// an rvalue.
62247330f729Sjoerg ///
62257330f729Sjoerg /// \returns An expression that copies the initializer expression into
62267330f729Sjoerg /// a temporary object, or an error expression if a copy could not be
62277330f729Sjoerg /// created.
CopyObject(Sema & S,QualType T,const InitializedEntity & Entity,ExprResult CurInit,bool IsExtraneousCopy)62287330f729Sjoerg static ExprResult CopyObject(Sema &S,
62297330f729Sjoerg QualType T,
62307330f729Sjoerg const InitializedEntity &Entity,
62317330f729Sjoerg ExprResult CurInit,
62327330f729Sjoerg bool IsExtraneousCopy) {
62337330f729Sjoerg if (CurInit.isInvalid())
62347330f729Sjoerg return CurInit;
62357330f729Sjoerg // Determine which class type we're copying to.
62367330f729Sjoerg Expr *CurInitExpr = (Expr *)CurInit.get();
62377330f729Sjoerg CXXRecordDecl *Class = nullptr;
62387330f729Sjoerg if (const RecordType *Record = T->getAs<RecordType>())
62397330f729Sjoerg Class = cast<CXXRecordDecl>(Record->getDecl());
62407330f729Sjoerg if (!Class)
62417330f729Sjoerg return CurInit;
62427330f729Sjoerg
62437330f729Sjoerg SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
62447330f729Sjoerg
62457330f729Sjoerg // Make sure that the type we are copying is complete.
62467330f729Sjoerg if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
62477330f729Sjoerg return CurInit;
62487330f729Sjoerg
62497330f729Sjoerg // Perform overload resolution using the class's constructors. Per
62507330f729Sjoerg // C++11 [dcl.init]p16, second bullet for class types, this initialization
62517330f729Sjoerg // is direct-initialization.
62527330f729Sjoerg OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
62537330f729Sjoerg DeclContext::lookup_result Ctors = S.LookupConstructors(Class);
62547330f729Sjoerg
62557330f729Sjoerg OverloadCandidateSet::iterator Best;
62567330f729Sjoerg switch (ResolveConstructorOverload(
62577330f729Sjoerg S, Loc, CurInitExpr, CandidateSet, T, Ctors, Best,
62587330f729Sjoerg /*CopyInitializing=*/false, /*AllowExplicit=*/true,
62597330f729Sjoerg /*OnlyListConstructors=*/false, /*IsListInit=*/false,
62607330f729Sjoerg /*SecondStepOfCopyInit=*/true)) {
62617330f729Sjoerg case OR_Success:
62627330f729Sjoerg break;
62637330f729Sjoerg
62647330f729Sjoerg case OR_No_Viable_Function:
62657330f729Sjoerg CandidateSet.NoteCandidates(
62667330f729Sjoerg PartialDiagnosticAt(
62677330f729Sjoerg Loc, S.PDiag(IsExtraneousCopy && !S.isSFINAEContext()
62687330f729Sjoerg ? diag::ext_rvalue_to_reference_temp_copy_no_viable
62697330f729Sjoerg : diag::err_temp_copy_no_viable)
62707330f729Sjoerg << (int)Entity.getKind() << CurInitExpr->getType()
62717330f729Sjoerg << CurInitExpr->getSourceRange()),
62727330f729Sjoerg S, OCD_AllCandidates, CurInitExpr);
62737330f729Sjoerg if (!IsExtraneousCopy || S.isSFINAEContext())
62747330f729Sjoerg return ExprError();
62757330f729Sjoerg return CurInit;
62767330f729Sjoerg
62777330f729Sjoerg case OR_Ambiguous:
62787330f729Sjoerg CandidateSet.NoteCandidates(
62797330f729Sjoerg PartialDiagnosticAt(Loc, S.PDiag(diag::err_temp_copy_ambiguous)
62807330f729Sjoerg << (int)Entity.getKind()
62817330f729Sjoerg << CurInitExpr->getType()
62827330f729Sjoerg << CurInitExpr->getSourceRange()),
62837330f729Sjoerg S, OCD_AmbiguousCandidates, CurInitExpr);
62847330f729Sjoerg return ExprError();
62857330f729Sjoerg
62867330f729Sjoerg case OR_Deleted:
62877330f729Sjoerg S.Diag(Loc, diag::err_temp_copy_deleted)
62887330f729Sjoerg << (int)Entity.getKind() << CurInitExpr->getType()
62897330f729Sjoerg << CurInitExpr->getSourceRange();
62907330f729Sjoerg S.NoteDeletedFunction(Best->Function);
62917330f729Sjoerg return ExprError();
62927330f729Sjoerg }
62937330f729Sjoerg
62947330f729Sjoerg bool HadMultipleCandidates = CandidateSet.size() > 1;
62957330f729Sjoerg
62967330f729Sjoerg CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
62977330f729Sjoerg SmallVector<Expr*, 8> ConstructorArgs;
62987330f729Sjoerg CurInit.get(); // Ownership transferred into MultiExprArg, below.
62997330f729Sjoerg
63007330f729Sjoerg S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity,
63017330f729Sjoerg IsExtraneousCopy);
63027330f729Sjoerg
63037330f729Sjoerg if (IsExtraneousCopy) {
63047330f729Sjoerg // If this is a totally extraneous copy for C++03 reference
63057330f729Sjoerg // binding purposes, just return the original initialization
63067330f729Sjoerg // expression. We don't generate an (elided) copy operation here
63077330f729Sjoerg // because doing so would require us to pass down a flag to avoid
63087330f729Sjoerg // infinite recursion, where each step adds another extraneous,
63097330f729Sjoerg // elidable copy.
63107330f729Sjoerg
63117330f729Sjoerg // Instantiate the default arguments of any extra parameters in
63127330f729Sjoerg // the selected copy constructor, as if we were going to create a
63137330f729Sjoerg // proper call to the copy constructor.
63147330f729Sjoerg for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
63157330f729Sjoerg ParmVarDecl *Parm = Constructor->getParamDecl(I);
63167330f729Sjoerg if (S.RequireCompleteType(Loc, Parm->getType(),
63177330f729Sjoerg diag::err_call_incomplete_argument))
63187330f729Sjoerg break;
63197330f729Sjoerg
63207330f729Sjoerg // Build the default argument expression; we don't actually care
63217330f729Sjoerg // if this succeeds or not, because this routine will complain
63227330f729Sjoerg // if there was a problem.
63237330f729Sjoerg S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
63247330f729Sjoerg }
63257330f729Sjoerg
63267330f729Sjoerg return CurInitExpr;
63277330f729Sjoerg }
63287330f729Sjoerg
63297330f729Sjoerg // Determine the arguments required to actually perform the
63307330f729Sjoerg // constructor call (we might have derived-to-base conversions, or
63317330f729Sjoerg // the copy constructor may have default arguments).
6332*e038c9c4Sjoerg if (S.CompleteConstructorCall(Constructor, T, CurInitExpr, Loc,
6333*e038c9c4Sjoerg ConstructorArgs))
63347330f729Sjoerg return ExprError();
63357330f729Sjoerg
63367330f729Sjoerg // C++0x [class.copy]p32:
63377330f729Sjoerg // When certain criteria are met, an implementation is allowed to
63387330f729Sjoerg // omit the copy/move construction of a class object, even if the
63397330f729Sjoerg // copy/move constructor and/or destructor for the object have
63407330f729Sjoerg // side effects. [...]
63417330f729Sjoerg // - when a temporary class object that has not been bound to a
63427330f729Sjoerg // reference (12.2) would be copied/moved to a class object
63437330f729Sjoerg // with the same cv-unqualified type, the copy/move operation
63447330f729Sjoerg // can be omitted by constructing the temporary object
63457330f729Sjoerg // directly into the target of the omitted copy/move
63467330f729Sjoerg //
63477330f729Sjoerg // Note that the other three bullets are handled elsewhere. Copy
63487330f729Sjoerg // elision for return statements and throw expressions are handled as part
63497330f729Sjoerg // of constructor initialization, while copy elision for exception handlers
63507330f729Sjoerg // is handled by the run-time.
63517330f729Sjoerg //
63527330f729Sjoerg // FIXME: If the function parameter is not the same type as the temporary, we
63537330f729Sjoerg // should still be able to elide the copy, but we don't have a way to
63547330f729Sjoerg // represent in the AST how much should be elided in this case.
63557330f729Sjoerg bool Elidable =
63567330f729Sjoerg CurInitExpr->isTemporaryObject(S.Context, Class) &&
63577330f729Sjoerg S.Context.hasSameUnqualifiedType(
63587330f729Sjoerg Best->Function->getParamDecl(0)->getType().getNonReferenceType(),
63597330f729Sjoerg CurInitExpr->getType());
63607330f729Sjoerg
63617330f729Sjoerg // Actually perform the constructor call.
63627330f729Sjoerg CurInit = S.BuildCXXConstructExpr(Loc, T, Best->FoundDecl, Constructor,
63637330f729Sjoerg Elidable,
63647330f729Sjoerg ConstructorArgs,
63657330f729Sjoerg HadMultipleCandidates,
63667330f729Sjoerg /*ListInit*/ false,
63677330f729Sjoerg /*StdInitListInit*/ false,
63687330f729Sjoerg /*ZeroInit*/ false,
63697330f729Sjoerg CXXConstructExpr::CK_Complete,
63707330f729Sjoerg SourceRange());
63717330f729Sjoerg
63727330f729Sjoerg // If we're supposed to bind temporaries, do so.
63737330f729Sjoerg if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
63747330f729Sjoerg CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
63757330f729Sjoerg return CurInit;
63767330f729Sjoerg }
63777330f729Sjoerg
63787330f729Sjoerg /// Check whether elidable copy construction for binding a reference to
63797330f729Sjoerg /// a temporary would have succeeded if we were building in C++98 mode, for
63807330f729Sjoerg /// -Wc++98-compat.
CheckCXX98CompatAccessibleCopy(Sema & S,const InitializedEntity & Entity,Expr * CurInitExpr)63817330f729Sjoerg static void CheckCXX98CompatAccessibleCopy(Sema &S,
63827330f729Sjoerg const InitializedEntity &Entity,
63837330f729Sjoerg Expr *CurInitExpr) {
63847330f729Sjoerg assert(S.getLangOpts().CPlusPlus11);
63857330f729Sjoerg
63867330f729Sjoerg const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
63877330f729Sjoerg if (!Record)
63887330f729Sjoerg return;
63897330f729Sjoerg
63907330f729Sjoerg SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
63917330f729Sjoerg if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
63927330f729Sjoerg return;
63937330f729Sjoerg
63947330f729Sjoerg // Find constructors which would have been considered.
63957330f729Sjoerg OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
63967330f729Sjoerg DeclContext::lookup_result Ctors =
63977330f729Sjoerg S.LookupConstructors(cast<CXXRecordDecl>(Record->getDecl()));
63987330f729Sjoerg
63997330f729Sjoerg // Perform overload resolution.
64007330f729Sjoerg OverloadCandidateSet::iterator Best;
64017330f729Sjoerg OverloadingResult OR = ResolveConstructorOverload(
64027330f729Sjoerg S, Loc, CurInitExpr, CandidateSet, CurInitExpr->getType(), Ctors, Best,
64037330f729Sjoerg /*CopyInitializing=*/false, /*AllowExplicit=*/true,
64047330f729Sjoerg /*OnlyListConstructors=*/false, /*IsListInit=*/false,
64057330f729Sjoerg /*SecondStepOfCopyInit=*/true);
64067330f729Sjoerg
64077330f729Sjoerg PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
64087330f729Sjoerg << OR << (int)Entity.getKind() << CurInitExpr->getType()
64097330f729Sjoerg << CurInitExpr->getSourceRange();
64107330f729Sjoerg
64117330f729Sjoerg switch (OR) {
64127330f729Sjoerg case OR_Success:
64137330f729Sjoerg S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
64147330f729Sjoerg Best->FoundDecl, Entity, Diag);
64157330f729Sjoerg // FIXME: Check default arguments as far as that's possible.
64167330f729Sjoerg break;
64177330f729Sjoerg
64187330f729Sjoerg case OR_No_Viable_Function:
64197330f729Sjoerg CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
64207330f729Sjoerg OCD_AllCandidates, CurInitExpr);
64217330f729Sjoerg break;
64227330f729Sjoerg
64237330f729Sjoerg case OR_Ambiguous:
64247330f729Sjoerg CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
64257330f729Sjoerg OCD_AmbiguousCandidates, CurInitExpr);
64267330f729Sjoerg break;
64277330f729Sjoerg
64287330f729Sjoerg case OR_Deleted:
64297330f729Sjoerg S.Diag(Loc, Diag);
64307330f729Sjoerg S.NoteDeletedFunction(Best->Function);
64317330f729Sjoerg break;
64327330f729Sjoerg }
64337330f729Sjoerg }
64347330f729Sjoerg
PrintInitLocationNote(Sema & S,const InitializedEntity & Entity)64357330f729Sjoerg void InitializationSequence::PrintInitLocationNote(Sema &S,
64367330f729Sjoerg const InitializedEntity &Entity) {
6437*e038c9c4Sjoerg if (Entity.isParamOrTemplateParamKind() && Entity.getDecl()) {
64387330f729Sjoerg if (Entity.getDecl()->getLocation().isInvalid())
64397330f729Sjoerg return;
64407330f729Sjoerg
64417330f729Sjoerg if (Entity.getDecl()->getDeclName())
64427330f729Sjoerg S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
64437330f729Sjoerg << Entity.getDecl()->getDeclName();
64447330f729Sjoerg else
64457330f729Sjoerg S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
64467330f729Sjoerg }
64477330f729Sjoerg else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
64487330f729Sjoerg Entity.getMethodDecl())
64497330f729Sjoerg S.Diag(Entity.getMethodDecl()->getLocation(),
64507330f729Sjoerg diag::note_method_return_type_change)
64517330f729Sjoerg << Entity.getMethodDecl()->getDeclName();
64527330f729Sjoerg }
64537330f729Sjoerg
64547330f729Sjoerg /// Returns true if the parameters describe a constructor initialization of
64557330f729Sjoerg /// an explicit temporary object, e.g. "Point(x, y)".
isExplicitTemporary(const InitializedEntity & Entity,const InitializationKind & Kind,unsigned NumArgs)64567330f729Sjoerg static bool isExplicitTemporary(const InitializedEntity &Entity,
64577330f729Sjoerg const InitializationKind &Kind,
64587330f729Sjoerg unsigned NumArgs) {
64597330f729Sjoerg switch (Entity.getKind()) {
64607330f729Sjoerg case InitializedEntity::EK_Temporary:
64617330f729Sjoerg case InitializedEntity::EK_CompoundLiteralInit:
64627330f729Sjoerg case InitializedEntity::EK_RelatedResult:
64637330f729Sjoerg break;
64647330f729Sjoerg default:
64657330f729Sjoerg return false;
64667330f729Sjoerg }
64677330f729Sjoerg
64687330f729Sjoerg switch (Kind.getKind()) {
64697330f729Sjoerg case InitializationKind::IK_DirectList:
64707330f729Sjoerg return true;
64717330f729Sjoerg // FIXME: Hack to work around cast weirdness.
64727330f729Sjoerg case InitializationKind::IK_Direct:
64737330f729Sjoerg case InitializationKind::IK_Value:
64747330f729Sjoerg return NumArgs != 1;
64757330f729Sjoerg default:
64767330f729Sjoerg return false;
64777330f729Sjoerg }
64787330f729Sjoerg }
64797330f729Sjoerg
64807330f729Sjoerg static ExprResult
PerformConstructorInitialization(Sema & S,const InitializedEntity & Entity,const InitializationKind & Kind,MultiExprArg Args,const InitializationSequence::Step & Step,bool & ConstructorInitRequiresZeroInit,bool IsListInitialization,bool IsStdInitListInitialization,SourceLocation LBraceLoc,SourceLocation RBraceLoc)64817330f729Sjoerg PerformConstructorInitialization(Sema &S,
64827330f729Sjoerg const InitializedEntity &Entity,
64837330f729Sjoerg const InitializationKind &Kind,
64847330f729Sjoerg MultiExprArg Args,
64857330f729Sjoerg const InitializationSequence::Step& Step,
64867330f729Sjoerg bool &ConstructorInitRequiresZeroInit,
64877330f729Sjoerg bool IsListInitialization,
64887330f729Sjoerg bool IsStdInitListInitialization,
64897330f729Sjoerg SourceLocation LBraceLoc,
64907330f729Sjoerg SourceLocation RBraceLoc) {
64917330f729Sjoerg unsigned NumArgs = Args.size();
64927330f729Sjoerg CXXConstructorDecl *Constructor
64937330f729Sjoerg = cast<CXXConstructorDecl>(Step.Function.Function);
64947330f729Sjoerg bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
64957330f729Sjoerg
64967330f729Sjoerg // Build a call to the selected constructor.
64977330f729Sjoerg SmallVector<Expr*, 8> ConstructorArgs;
64987330f729Sjoerg SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
64997330f729Sjoerg ? Kind.getEqualLoc()
65007330f729Sjoerg : Kind.getLocation();
65017330f729Sjoerg
65027330f729Sjoerg if (Kind.getKind() == InitializationKind::IK_Default) {
65037330f729Sjoerg // Force even a trivial, implicit default constructor to be
65047330f729Sjoerg // semantically checked. We do this explicitly because we don't build
65057330f729Sjoerg // the definition for completely trivial constructors.
65067330f729Sjoerg assert(Constructor->getParent() && "No parent class for constructor.");
65077330f729Sjoerg if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
65087330f729Sjoerg Constructor->isTrivial() && !Constructor->isUsed(false)) {
65097330f729Sjoerg S.runWithSufficientStackSpace(Loc, [&] {
65107330f729Sjoerg S.DefineImplicitDefaultConstructor(Loc, Constructor);
65117330f729Sjoerg });
65127330f729Sjoerg }
65137330f729Sjoerg }
65147330f729Sjoerg
65157330f729Sjoerg ExprResult CurInit((Expr *)nullptr);
65167330f729Sjoerg
65177330f729Sjoerg // C++ [over.match.copy]p1:
65187330f729Sjoerg // - When initializing a temporary to be bound to the first parameter
65197330f729Sjoerg // of a constructor that takes a reference to possibly cv-qualified
65207330f729Sjoerg // T as its first argument, called with a single argument in the
65217330f729Sjoerg // context of direct-initialization, explicit conversion functions
65227330f729Sjoerg // are also considered.
65237330f729Sjoerg bool AllowExplicitConv =
65247330f729Sjoerg Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 &&
65257330f729Sjoerg hasCopyOrMoveCtorParam(S.Context,
65267330f729Sjoerg getConstructorInfo(Step.Function.FoundDecl));
65277330f729Sjoerg
65287330f729Sjoerg // Determine the arguments required to actually perform the constructor
65297330f729Sjoerg // call.
6530*e038c9c4Sjoerg if (S.CompleteConstructorCall(Constructor, Step.Type, Args, Loc,
6531*e038c9c4Sjoerg ConstructorArgs, AllowExplicitConv,
65327330f729Sjoerg IsListInitialization))
65337330f729Sjoerg return ExprError();
65347330f729Sjoerg
65357330f729Sjoerg if (isExplicitTemporary(Entity, Kind, NumArgs)) {
65367330f729Sjoerg // An explicitly-constructed temporary, e.g., X(1, 2).
65377330f729Sjoerg if (S.DiagnoseUseOfDecl(Constructor, Loc))
65387330f729Sjoerg return ExprError();
65397330f729Sjoerg
65407330f729Sjoerg TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
65417330f729Sjoerg if (!TSInfo)
65427330f729Sjoerg TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
65437330f729Sjoerg SourceRange ParenOrBraceRange =
65447330f729Sjoerg (Kind.getKind() == InitializationKind::IK_DirectList)
65457330f729Sjoerg ? SourceRange(LBraceLoc, RBraceLoc)
65467330f729Sjoerg : Kind.getParenOrBraceRange();
65477330f729Sjoerg
6548*e038c9c4Sjoerg CXXConstructorDecl *CalleeDecl = Constructor;
65497330f729Sjoerg if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(
65507330f729Sjoerg Step.Function.FoundDecl.getDecl())) {
6551*e038c9c4Sjoerg CalleeDecl = S.findInheritingConstructor(Loc, Constructor, Shadow);
6552*e038c9c4Sjoerg if (S.DiagnoseUseOfDecl(CalleeDecl, Loc))
65537330f729Sjoerg return ExprError();
65547330f729Sjoerg }
6555*e038c9c4Sjoerg S.MarkFunctionReferenced(Loc, CalleeDecl);
65567330f729Sjoerg
6557*e038c9c4Sjoerg CurInit = S.CheckForImmediateInvocation(
6558*e038c9c4Sjoerg CXXTemporaryObjectExpr::Create(
6559*e038c9c4Sjoerg S.Context, CalleeDecl,
65607330f729Sjoerg Entity.getType().getNonLValueExprType(S.Context), TSInfo,
65617330f729Sjoerg ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates,
65627330f729Sjoerg IsListInitialization, IsStdInitListInitialization,
6563*e038c9c4Sjoerg ConstructorInitRequiresZeroInit),
6564*e038c9c4Sjoerg CalleeDecl);
65657330f729Sjoerg } else {
65667330f729Sjoerg CXXConstructExpr::ConstructionKind ConstructKind =
65677330f729Sjoerg CXXConstructExpr::CK_Complete;
65687330f729Sjoerg
65697330f729Sjoerg if (Entity.getKind() == InitializedEntity::EK_Base) {
65707330f729Sjoerg ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
65717330f729Sjoerg CXXConstructExpr::CK_VirtualBase :
65727330f729Sjoerg CXXConstructExpr::CK_NonVirtualBase;
65737330f729Sjoerg } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
65747330f729Sjoerg ConstructKind = CXXConstructExpr::CK_Delegating;
65757330f729Sjoerg }
65767330f729Sjoerg
65777330f729Sjoerg // Only get the parenthesis or brace range if it is a list initialization or
65787330f729Sjoerg // direct construction.
65797330f729Sjoerg SourceRange ParenOrBraceRange;
65807330f729Sjoerg if (IsListInitialization)
65817330f729Sjoerg ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
65827330f729Sjoerg else if (Kind.getKind() == InitializationKind::IK_Direct)
65837330f729Sjoerg ParenOrBraceRange = Kind.getParenOrBraceRange();
65847330f729Sjoerg
65857330f729Sjoerg // If the entity allows NRVO, mark the construction as elidable
65867330f729Sjoerg // unconditionally.
65877330f729Sjoerg if (Entity.allowsNRVO())
65887330f729Sjoerg CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
65897330f729Sjoerg Step.Function.FoundDecl,
65907330f729Sjoerg Constructor, /*Elidable=*/true,
65917330f729Sjoerg ConstructorArgs,
65927330f729Sjoerg HadMultipleCandidates,
65937330f729Sjoerg IsListInitialization,
65947330f729Sjoerg IsStdInitListInitialization,
65957330f729Sjoerg ConstructorInitRequiresZeroInit,
65967330f729Sjoerg ConstructKind,
65977330f729Sjoerg ParenOrBraceRange);
65987330f729Sjoerg else
65997330f729Sjoerg CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
66007330f729Sjoerg Step.Function.FoundDecl,
66017330f729Sjoerg Constructor,
66027330f729Sjoerg ConstructorArgs,
66037330f729Sjoerg HadMultipleCandidates,
66047330f729Sjoerg IsListInitialization,
66057330f729Sjoerg IsStdInitListInitialization,
66067330f729Sjoerg ConstructorInitRequiresZeroInit,
66077330f729Sjoerg ConstructKind,
66087330f729Sjoerg ParenOrBraceRange);
66097330f729Sjoerg }
66107330f729Sjoerg if (CurInit.isInvalid())
66117330f729Sjoerg return ExprError();
66127330f729Sjoerg
66137330f729Sjoerg // Only check access if all of that succeeded.
66147330f729Sjoerg S.CheckConstructorAccess(Loc, Constructor, Step.Function.FoundDecl, Entity);
66157330f729Sjoerg if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
66167330f729Sjoerg return ExprError();
66177330f729Sjoerg
66187330f729Sjoerg if (const ArrayType *AT = S.Context.getAsArrayType(Entity.getType()))
66197330f729Sjoerg if (checkDestructorReference(S.Context.getBaseElementType(AT), Loc, S))
66207330f729Sjoerg return ExprError();
66217330f729Sjoerg
66227330f729Sjoerg if (shouldBindAsTemporary(Entity))
66237330f729Sjoerg CurInit = S.MaybeBindToTemporary(CurInit.get());
66247330f729Sjoerg
66257330f729Sjoerg return CurInit;
66267330f729Sjoerg }
66277330f729Sjoerg
66287330f729Sjoerg namespace {
66297330f729Sjoerg enum LifetimeKind {
66307330f729Sjoerg /// The lifetime of a temporary bound to this entity ends at the end of the
66317330f729Sjoerg /// full-expression, and that's (probably) fine.
66327330f729Sjoerg LK_FullExpression,
66337330f729Sjoerg
66347330f729Sjoerg /// The lifetime of a temporary bound to this entity is extended to the
66357330f729Sjoerg /// lifeitme of the entity itself.
66367330f729Sjoerg LK_Extended,
66377330f729Sjoerg
66387330f729Sjoerg /// The lifetime of a temporary bound to this entity probably ends too soon,
66397330f729Sjoerg /// because the entity is allocated in a new-expression.
66407330f729Sjoerg LK_New,
66417330f729Sjoerg
66427330f729Sjoerg /// The lifetime of a temporary bound to this entity ends too soon, because
66437330f729Sjoerg /// the entity is a return object.
66447330f729Sjoerg LK_Return,
66457330f729Sjoerg
66467330f729Sjoerg /// The lifetime of a temporary bound to this entity ends too soon, because
66477330f729Sjoerg /// the entity is the result of a statement expression.
66487330f729Sjoerg LK_StmtExprResult,
66497330f729Sjoerg
66507330f729Sjoerg /// This is a mem-initializer: if it would extend a temporary (other than via
66517330f729Sjoerg /// a default member initializer), the program is ill-formed.
66527330f729Sjoerg LK_MemInitializer,
66537330f729Sjoerg };
66547330f729Sjoerg using LifetimeResult =
66557330f729Sjoerg llvm::PointerIntPair<const InitializedEntity *, 3, LifetimeKind>;
66567330f729Sjoerg }
66577330f729Sjoerg
66587330f729Sjoerg /// Determine the declaration which an initialized entity ultimately refers to,
66597330f729Sjoerg /// for the purpose of lifetime-extending a temporary bound to a reference in
66607330f729Sjoerg /// the initialization of \p Entity.
getEntityLifetime(const InitializedEntity * Entity,const InitializedEntity * InitField=nullptr)66617330f729Sjoerg static LifetimeResult getEntityLifetime(
66627330f729Sjoerg const InitializedEntity *Entity,
66637330f729Sjoerg const InitializedEntity *InitField = nullptr) {
66647330f729Sjoerg // C++11 [class.temporary]p5:
66657330f729Sjoerg switch (Entity->getKind()) {
66667330f729Sjoerg case InitializedEntity::EK_Variable:
66677330f729Sjoerg // The temporary [...] persists for the lifetime of the reference
66687330f729Sjoerg return {Entity, LK_Extended};
66697330f729Sjoerg
66707330f729Sjoerg case InitializedEntity::EK_Member:
66717330f729Sjoerg // For subobjects, we look at the complete object.
66727330f729Sjoerg if (Entity->getParent())
66737330f729Sjoerg return getEntityLifetime(Entity->getParent(), Entity);
66747330f729Sjoerg
66757330f729Sjoerg // except:
66767330f729Sjoerg // C++17 [class.base.init]p8:
66777330f729Sjoerg // A temporary expression bound to a reference member in a
66787330f729Sjoerg // mem-initializer is ill-formed.
66797330f729Sjoerg // C++17 [class.base.init]p11:
66807330f729Sjoerg // A temporary expression bound to a reference member from a
66817330f729Sjoerg // default member initializer is ill-formed.
66827330f729Sjoerg //
66837330f729Sjoerg // The context of p11 and its example suggest that it's only the use of a
66847330f729Sjoerg // default member initializer from a constructor that makes the program
66857330f729Sjoerg // ill-formed, not its mere existence, and that it can even be used by
66867330f729Sjoerg // aggregate initialization.
66877330f729Sjoerg return {Entity, Entity->isDefaultMemberInitializer() ? LK_Extended
66887330f729Sjoerg : LK_MemInitializer};
66897330f729Sjoerg
66907330f729Sjoerg case InitializedEntity::EK_Binding:
66917330f729Sjoerg // Per [dcl.decomp]p3, the binding is treated as a variable of reference
66927330f729Sjoerg // type.
66937330f729Sjoerg return {Entity, LK_Extended};
66947330f729Sjoerg
66957330f729Sjoerg case InitializedEntity::EK_Parameter:
66967330f729Sjoerg case InitializedEntity::EK_Parameter_CF_Audited:
66977330f729Sjoerg // -- A temporary bound to a reference parameter in a function call
66987330f729Sjoerg // persists until the completion of the full-expression containing
66997330f729Sjoerg // the call.
67007330f729Sjoerg return {nullptr, LK_FullExpression};
67017330f729Sjoerg
6702*e038c9c4Sjoerg case InitializedEntity::EK_TemplateParameter:
6703*e038c9c4Sjoerg // FIXME: This will always be ill-formed; should we eagerly diagnose it here?
6704*e038c9c4Sjoerg return {nullptr, LK_FullExpression};
6705*e038c9c4Sjoerg
67067330f729Sjoerg case InitializedEntity::EK_Result:
67077330f729Sjoerg // -- The lifetime of a temporary bound to the returned value in a
67087330f729Sjoerg // function return statement is not extended; the temporary is
67097330f729Sjoerg // destroyed at the end of the full-expression in the return statement.
67107330f729Sjoerg return {nullptr, LK_Return};
67117330f729Sjoerg
67127330f729Sjoerg case InitializedEntity::EK_StmtExprResult:
67137330f729Sjoerg // FIXME: Should we lifetime-extend through the result of a statement
67147330f729Sjoerg // expression?
67157330f729Sjoerg return {nullptr, LK_StmtExprResult};
67167330f729Sjoerg
67177330f729Sjoerg case InitializedEntity::EK_New:
67187330f729Sjoerg // -- A temporary bound to a reference in a new-initializer persists
67197330f729Sjoerg // until the completion of the full-expression containing the
67207330f729Sjoerg // new-initializer.
67217330f729Sjoerg return {nullptr, LK_New};
67227330f729Sjoerg
67237330f729Sjoerg case InitializedEntity::EK_Temporary:
67247330f729Sjoerg case InitializedEntity::EK_CompoundLiteralInit:
67257330f729Sjoerg case InitializedEntity::EK_RelatedResult:
67267330f729Sjoerg // We don't yet know the storage duration of the surrounding temporary.
67277330f729Sjoerg // Assume it's got full-expression duration for now, it will patch up our
67287330f729Sjoerg // storage duration if that's not correct.
67297330f729Sjoerg return {nullptr, LK_FullExpression};
67307330f729Sjoerg
67317330f729Sjoerg case InitializedEntity::EK_ArrayElement:
67327330f729Sjoerg // For subobjects, we look at the complete object.
67337330f729Sjoerg return getEntityLifetime(Entity->getParent(), InitField);
67347330f729Sjoerg
67357330f729Sjoerg case InitializedEntity::EK_Base:
67367330f729Sjoerg // For subobjects, we look at the complete object.
67377330f729Sjoerg if (Entity->getParent())
67387330f729Sjoerg return getEntityLifetime(Entity->getParent(), InitField);
67397330f729Sjoerg return {InitField, LK_MemInitializer};
67407330f729Sjoerg
67417330f729Sjoerg case InitializedEntity::EK_Delegating:
67427330f729Sjoerg // We can reach this case for aggregate initialization in a constructor:
67437330f729Sjoerg // struct A { int &&r; };
67447330f729Sjoerg // struct B : A { B() : A{0} {} };
67457330f729Sjoerg // In this case, use the outermost field decl as the context.
67467330f729Sjoerg return {InitField, LK_MemInitializer};
67477330f729Sjoerg
67487330f729Sjoerg case InitializedEntity::EK_BlockElement:
67497330f729Sjoerg case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
67507330f729Sjoerg case InitializedEntity::EK_LambdaCapture:
67517330f729Sjoerg case InitializedEntity::EK_VectorElement:
67527330f729Sjoerg case InitializedEntity::EK_ComplexElement:
67537330f729Sjoerg return {nullptr, LK_FullExpression};
67547330f729Sjoerg
67557330f729Sjoerg case InitializedEntity::EK_Exception:
67567330f729Sjoerg // FIXME: Can we diagnose lifetime problems with exceptions?
67577330f729Sjoerg return {nullptr, LK_FullExpression};
67587330f729Sjoerg }
67597330f729Sjoerg llvm_unreachable("unknown entity kind");
67607330f729Sjoerg }
67617330f729Sjoerg
67627330f729Sjoerg namespace {
67637330f729Sjoerg enum ReferenceKind {
67647330f729Sjoerg /// Lifetime would be extended by a reference binding to a temporary.
67657330f729Sjoerg RK_ReferenceBinding,
67667330f729Sjoerg /// Lifetime would be extended by a std::initializer_list object binding to
67677330f729Sjoerg /// its backing array.
67687330f729Sjoerg RK_StdInitializerList,
67697330f729Sjoerg };
67707330f729Sjoerg
67717330f729Sjoerg /// A temporary or local variable. This will be one of:
67727330f729Sjoerg /// * A MaterializeTemporaryExpr.
67737330f729Sjoerg /// * A DeclRefExpr whose declaration is a local.
67747330f729Sjoerg /// * An AddrLabelExpr.
67757330f729Sjoerg /// * A BlockExpr for a block with captures.
67767330f729Sjoerg using Local = Expr*;
67777330f729Sjoerg
67787330f729Sjoerg /// Expressions we stepped over when looking for the local state. Any steps
67797330f729Sjoerg /// that would inhibit lifetime extension or take us out of subexpressions of
67807330f729Sjoerg /// the initializer are included.
67817330f729Sjoerg struct IndirectLocalPathEntry {
67827330f729Sjoerg enum EntryKind {
67837330f729Sjoerg DefaultInit,
67847330f729Sjoerg AddressOf,
67857330f729Sjoerg VarInit,
67867330f729Sjoerg LValToRVal,
67877330f729Sjoerg LifetimeBoundCall,
6788*e038c9c4Sjoerg TemporaryCopy,
6789*e038c9c4Sjoerg LambdaCaptureInit,
6790*e038c9c4Sjoerg GslReferenceInit,
67917330f729Sjoerg GslPointerInit
67927330f729Sjoerg } Kind;
67937330f729Sjoerg Expr *E;
6794*e038c9c4Sjoerg union {
67957330f729Sjoerg const Decl *D = nullptr;
6796*e038c9c4Sjoerg const LambdaCapture *Capture;
6797*e038c9c4Sjoerg };
IndirectLocalPathEntry__anon778db8540511::IndirectLocalPathEntry67987330f729Sjoerg IndirectLocalPathEntry() {}
IndirectLocalPathEntry__anon778db8540511::IndirectLocalPathEntry67997330f729Sjoerg IndirectLocalPathEntry(EntryKind K, Expr *E) : Kind(K), E(E) {}
IndirectLocalPathEntry__anon778db8540511::IndirectLocalPathEntry68007330f729Sjoerg IndirectLocalPathEntry(EntryKind K, Expr *E, const Decl *D)
68017330f729Sjoerg : Kind(K), E(E), D(D) {}
IndirectLocalPathEntry__anon778db8540511::IndirectLocalPathEntry6802*e038c9c4Sjoerg IndirectLocalPathEntry(EntryKind K, Expr *E, const LambdaCapture *Capture)
6803*e038c9c4Sjoerg : Kind(K), E(E), Capture(Capture) {}
68047330f729Sjoerg };
68057330f729Sjoerg
68067330f729Sjoerg using IndirectLocalPath = llvm::SmallVectorImpl<IndirectLocalPathEntry>;
68077330f729Sjoerg
68087330f729Sjoerg struct RevertToOldSizeRAII {
68097330f729Sjoerg IndirectLocalPath &Path;
68107330f729Sjoerg unsigned OldSize = Path.size();
RevertToOldSizeRAII__anon778db8540511::RevertToOldSizeRAII68117330f729Sjoerg RevertToOldSizeRAII(IndirectLocalPath &Path) : Path(Path) {}
~RevertToOldSizeRAII__anon778db8540511::RevertToOldSizeRAII68127330f729Sjoerg ~RevertToOldSizeRAII() { Path.resize(OldSize); }
68137330f729Sjoerg };
68147330f729Sjoerg
68157330f729Sjoerg using LocalVisitor = llvm::function_ref<bool(IndirectLocalPath &Path, Local L,
68167330f729Sjoerg ReferenceKind RK)>;
68177330f729Sjoerg }
68187330f729Sjoerg
isVarOnPath(IndirectLocalPath & Path,VarDecl * VD)68197330f729Sjoerg static bool isVarOnPath(IndirectLocalPath &Path, VarDecl *VD) {
68207330f729Sjoerg for (auto E : Path)
68217330f729Sjoerg if (E.Kind == IndirectLocalPathEntry::VarInit && E.D == VD)
68227330f729Sjoerg return true;
68237330f729Sjoerg return false;
68247330f729Sjoerg }
68257330f729Sjoerg
pathContainsInit(IndirectLocalPath & Path)68267330f729Sjoerg static bool pathContainsInit(IndirectLocalPath &Path) {
68277330f729Sjoerg return llvm::any_of(Path, [=](IndirectLocalPathEntry E) {
68287330f729Sjoerg return E.Kind == IndirectLocalPathEntry::DefaultInit ||
68297330f729Sjoerg E.Kind == IndirectLocalPathEntry::VarInit;
68307330f729Sjoerg });
68317330f729Sjoerg }
68327330f729Sjoerg
68337330f729Sjoerg static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path,
68347330f729Sjoerg Expr *Init, LocalVisitor Visit,
68357330f729Sjoerg bool RevisitSubinits,
68367330f729Sjoerg bool EnableLifetimeWarnings);
68377330f729Sjoerg
68387330f729Sjoerg static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
68397330f729Sjoerg Expr *Init, ReferenceKind RK,
68407330f729Sjoerg LocalVisitor Visit,
68417330f729Sjoerg bool EnableLifetimeWarnings);
68427330f729Sjoerg
isRecordWithAttr(QualType Type)68437330f729Sjoerg template <typename T> static bool isRecordWithAttr(QualType Type) {
68447330f729Sjoerg if (auto *RD = Type->getAsCXXRecordDecl())
68457330f729Sjoerg return RD->hasAttr<T>();
68467330f729Sjoerg return false;
68477330f729Sjoerg }
68487330f729Sjoerg
68497330f729Sjoerg // Decl::isInStdNamespace will return false for iterators in some STL
68507330f729Sjoerg // implementations due to them being defined in a namespace outside of the std
68517330f729Sjoerg // namespace.
isInStlNamespace(const Decl * D)68527330f729Sjoerg static bool isInStlNamespace(const Decl *D) {
68537330f729Sjoerg const DeclContext *DC = D->getDeclContext();
68547330f729Sjoerg if (!DC)
68557330f729Sjoerg return false;
68567330f729Sjoerg if (const auto *ND = dyn_cast<NamespaceDecl>(DC))
68577330f729Sjoerg if (const IdentifierInfo *II = ND->getIdentifier()) {
68587330f729Sjoerg StringRef Name = II->getName();
68597330f729Sjoerg if (Name.size() >= 2 && Name.front() == '_' &&
68607330f729Sjoerg (Name[1] == '_' || isUppercase(Name[1])))
68617330f729Sjoerg return true;
68627330f729Sjoerg }
68637330f729Sjoerg
68647330f729Sjoerg return DC->isStdNamespace();
68657330f729Sjoerg }
68667330f729Sjoerg
shouldTrackImplicitObjectArg(const CXXMethodDecl * Callee)68677330f729Sjoerg static bool shouldTrackImplicitObjectArg(const CXXMethodDecl *Callee) {
68687330f729Sjoerg if (auto *Conv = dyn_cast_or_null<CXXConversionDecl>(Callee))
68697330f729Sjoerg if (isRecordWithAttr<PointerAttr>(Conv->getConversionType()))
68707330f729Sjoerg return true;
68717330f729Sjoerg if (!isInStlNamespace(Callee->getParent()))
68727330f729Sjoerg return false;
68737330f729Sjoerg if (!isRecordWithAttr<PointerAttr>(Callee->getThisObjectType()) &&
68747330f729Sjoerg !isRecordWithAttr<OwnerAttr>(Callee->getThisObjectType()))
68757330f729Sjoerg return false;
68767330f729Sjoerg if (Callee->getReturnType()->isPointerType() ||
68777330f729Sjoerg isRecordWithAttr<PointerAttr>(Callee->getReturnType())) {
68787330f729Sjoerg if (!Callee->getIdentifier())
68797330f729Sjoerg return false;
68807330f729Sjoerg return llvm::StringSwitch<bool>(Callee->getName())
68817330f729Sjoerg .Cases("begin", "rbegin", "cbegin", "crbegin", true)
68827330f729Sjoerg .Cases("end", "rend", "cend", "crend", true)
68837330f729Sjoerg .Cases("c_str", "data", "get", true)
68847330f729Sjoerg // Map and set types.
68857330f729Sjoerg .Cases("find", "equal_range", "lower_bound", "upper_bound", true)
68867330f729Sjoerg .Default(false);
68877330f729Sjoerg } else if (Callee->getReturnType()->isReferenceType()) {
68887330f729Sjoerg if (!Callee->getIdentifier()) {
68897330f729Sjoerg auto OO = Callee->getOverloadedOperator();
68907330f729Sjoerg return OO == OverloadedOperatorKind::OO_Subscript ||
68917330f729Sjoerg OO == OverloadedOperatorKind::OO_Star;
68927330f729Sjoerg }
68937330f729Sjoerg return llvm::StringSwitch<bool>(Callee->getName())
68947330f729Sjoerg .Cases("front", "back", "at", "top", "value", true)
68957330f729Sjoerg .Default(false);
68967330f729Sjoerg }
68977330f729Sjoerg return false;
68987330f729Sjoerg }
68997330f729Sjoerg
shouldTrackFirstArgument(const FunctionDecl * FD)69007330f729Sjoerg static bool shouldTrackFirstArgument(const FunctionDecl *FD) {
69017330f729Sjoerg if (!FD->getIdentifier() || FD->getNumParams() != 1)
69027330f729Sjoerg return false;
69037330f729Sjoerg const auto *RD = FD->getParamDecl(0)->getType()->getPointeeCXXRecordDecl();
69047330f729Sjoerg if (!FD->isInStdNamespace() || !RD || !RD->isInStdNamespace())
69057330f729Sjoerg return false;
69067330f729Sjoerg if (!isRecordWithAttr<PointerAttr>(QualType(RD->getTypeForDecl(), 0)) &&
69077330f729Sjoerg !isRecordWithAttr<OwnerAttr>(QualType(RD->getTypeForDecl(), 0)))
69087330f729Sjoerg return false;
69097330f729Sjoerg if (FD->getReturnType()->isPointerType() ||
69107330f729Sjoerg isRecordWithAttr<PointerAttr>(FD->getReturnType())) {
69117330f729Sjoerg return llvm::StringSwitch<bool>(FD->getName())
69127330f729Sjoerg .Cases("begin", "rbegin", "cbegin", "crbegin", true)
69137330f729Sjoerg .Cases("end", "rend", "cend", "crend", true)
69147330f729Sjoerg .Case("data", true)
69157330f729Sjoerg .Default(false);
69167330f729Sjoerg } else if (FD->getReturnType()->isReferenceType()) {
69177330f729Sjoerg return llvm::StringSwitch<bool>(FD->getName())
69187330f729Sjoerg .Cases("get", "any_cast", true)
69197330f729Sjoerg .Default(false);
69207330f729Sjoerg }
69217330f729Sjoerg return false;
69227330f729Sjoerg }
69237330f729Sjoerg
handleGslAnnotatedTypes(IndirectLocalPath & Path,Expr * Call,LocalVisitor Visit)69247330f729Sjoerg static void handleGslAnnotatedTypes(IndirectLocalPath &Path, Expr *Call,
69257330f729Sjoerg LocalVisitor Visit) {
6926*e038c9c4Sjoerg auto VisitPointerArg = [&](const Decl *D, Expr *Arg, bool Value) {
69277330f729Sjoerg // We are not interested in the temporary base objects of gsl Pointers:
69287330f729Sjoerg // Temp().ptr; // Here ptr might not dangle.
69297330f729Sjoerg if (isa<MemberExpr>(Arg->IgnoreImpCasts()))
69307330f729Sjoerg return;
6931*e038c9c4Sjoerg // Once we initialized a value with a reference, it can no longer dangle.
6932*e038c9c4Sjoerg if (!Value) {
6933*e038c9c4Sjoerg for (auto It = Path.rbegin(), End = Path.rend(); It != End; ++It) {
6934*e038c9c4Sjoerg if (It->Kind == IndirectLocalPathEntry::GslReferenceInit)
6935*e038c9c4Sjoerg continue;
6936*e038c9c4Sjoerg if (It->Kind == IndirectLocalPathEntry::GslPointerInit)
6937*e038c9c4Sjoerg return;
6938*e038c9c4Sjoerg break;
6939*e038c9c4Sjoerg }
6940*e038c9c4Sjoerg }
6941*e038c9c4Sjoerg Path.push_back({Value ? IndirectLocalPathEntry::GslPointerInit
6942*e038c9c4Sjoerg : IndirectLocalPathEntry::GslReferenceInit,
6943*e038c9c4Sjoerg Arg, D});
69447330f729Sjoerg if (Arg->isGLValue())
69457330f729Sjoerg visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding,
69467330f729Sjoerg Visit,
69477330f729Sjoerg /*EnableLifetimeWarnings=*/true);
69487330f729Sjoerg else
69497330f729Sjoerg visitLocalsRetainedByInitializer(Path, Arg, Visit, true,
69507330f729Sjoerg /*EnableLifetimeWarnings=*/true);
69517330f729Sjoerg Path.pop_back();
69527330f729Sjoerg };
69537330f729Sjoerg
69547330f729Sjoerg if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) {
69557330f729Sjoerg const auto *MD = cast_or_null<CXXMethodDecl>(MCE->getDirectCallee());
69567330f729Sjoerg if (MD && shouldTrackImplicitObjectArg(MD))
6957*e038c9c4Sjoerg VisitPointerArg(MD, MCE->getImplicitObjectArgument(),
6958*e038c9c4Sjoerg !MD->getReturnType()->isReferenceType());
69597330f729Sjoerg return;
69607330f729Sjoerg } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(Call)) {
69617330f729Sjoerg FunctionDecl *Callee = OCE->getDirectCallee();
69627330f729Sjoerg if (Callee && Callee->isCXXInstanceMember() &&
69637330f729Sjoerg shouldTrackImplicitObjectArg(cast<CXXMethodDecl>(Callee)))
6964*e038c9c4Sjoerg VisitPointerArg(Callee, OCE->getArg(0),
6965*e038c9c4Sjoerg !Callee->getReturnType()->isReferenceType());
69667330f729Sjoerg return;
69677330f729Sjoerg } else if (auto *CE = dyn_cast<CallExpr>(Call)) {
69687330f729Sjoerg FunctionDecl *Callee = CE->getDirectCallee();
69697330f729Sjoerg if (Callee && shouldTrackFirstArgument(Callee))
6970*e038c9c4Sjoerg VisitPointerArg(Callee, CE->getArg(0),
6971*e038c9c4Sjoerg !Callee->getReturnType()->isReferenceType());
69727330f729Sjoerg return;
69737330f729Sjoerg }
69747330f729Sjoerg
69757330f729Sjoerg if (auto *CCE = dyn_cast<CXXConstructExpr>(Call)) {
69767330f729Sjoerg const auto *Ctor = CCE->getConstructor();
69777330f729Sjoerg const CXXRecordDecl *RD = Ctor->getParent();
69787330f729Sjoerg if (CCE->getNumArgs() > 0 && RD->hasAttr<PointerAttr>())
6979*e038c9c4Sjoerg VisitPointerArg(Ctor->getParamDecl(0), CCE->getArgs()[0], true);
69807330f729Sjoerg }
69817330f729Sjoerg }
69827330f729Sjoerg
implicitObjectParamIsLifetimeBound(const FunctionDecl * FD)69837330f729Sjoerg static bool implicitObjectParamIsLifetimeBound(const FunctionDecl *FD) {
69847330f729Sjoerg const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
69857330f729Sjoerg if (!TSI)
69867330f729Sjoerg return false;
69877330f729Sjoerg // Don't declare this variable in the second operand of the for-statement;
69887330f729Sjoerg // GCC miscompiles that by ending its lifetime before evaluating the
69897330f729Sjoerg // third operand. See gcc.gnu.org/PR86769.
69907330f729Sjoerg AttributedTypeLoc ATL;
69917330f729Sjoerg for (TypeLoc TL = TSI->getTypeLoc();
69927330f729Sjoerg (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
69937330f729Sjoerg TL = ATL.getModifiedLoc()) {
69947330f729Sjoerg if (ATL.getAttrAs<LifetimeBoundAttr>())
69957330f729Sjoerg return true;
69967330f729Sjoerg }
6997*e038c9c4Sjoerg
6998*e038c9c4Sjoerg // Assume that all assignment operators with a "normal" return type return
6999*e038c9c4Sjoerg // *this, that is, an lvalue reference that is the same type as the implicit
7000*e038c9c4Sjoerg // object parameter (or the LHS for a non-member operator$=).
7001*e038c9c4Sjoerg OverloadedOperatorKind OO = FD->getDeclName().getCXXOverloadedOperator();
7002*e038c9c4Sjoerg if (OO == OO_Equal || isCompoundAssignmentOperator(OO)) {
7003*e038c9c4Sjoerg QualType RetT = FD->getReturnType();
7004*e038c9c4Sjoerg if (RetT->isLValueReferenceType()) {
7005*e038c9c4Sjoerg ASTContext &Ctx = FD->getASTContext();
7006*e038c9c4Sjoerg QualType LHST;
7007*e038c9c4Sjoerg auto *MD = dyn_cast<CXXMethodDecl>(FD);
7008*e038c9c4Sjoerg if (MD && MD->isCXXInstanceMember())
7009*e038c9c4Sjoerg LHST = Ctx.getLValueReferenceType(MD->getThisObjectType());
7010*e038c9c4Sjoerg else
7011*e038c9c4Sjoerg LHST = MD->getParamDecl(0)->getType();
7012*e038c9c4Sjoerg if (Ctx.hasSameType(RetT, LHST))
7013*e038c9c4Sjoerg return true;
7014*e038c9c4Sjoerg }
7015*e038c9c4Sjoerg }
7016*e038c9c4Sjoerg
70177330f729Sjoerg return false;
70187330f729Sjoerg }
70197330f729Sjoerg
visitLifetimeBoundArguments(IndirectLocalPath & Path,Expr * Call,LocalVisitor Visit)70207330f729Sjoerg static void visitLifetimeBoundArguments(IndirectLocalPath &Path, Expr *Call,
70217330f729Sjoerg LocalVisitor Visit) {
70227330f729Sjoerg const FunctionDecl *Callee;
70237330f729Sjoerg ArrayRef<Expr*> Args;
70247330f729Sjoerg
70257330f729Sjoerg if (auto *CE = dyn_cast<CallExpr>(Call)) {
70267330f729Sjoerg Callee = CE->getDirectCallee();
70277330f729Sjoerg Args = llvm::makeArrayRef(CE->getArgs(), CE->getNumArgs());
70287330f729Sjoerg } else {
70297330f729Sjoerg auto *CCE = cast<CXXConstructExpr>(Call);
70307330f729Sjoerg Callee = CCE->getConstructor();
70317330f729Sjoerg Args = llvm::makeArrayRef(CCE->getArgs(), CCE->getNumArgs());
70327330f729Sjoerg }
70337330f729Sjoerg if (!Callee)
70347330f729Sjoerg return;
70357330f729Sjoerg
70367330f729Sjoerg Expr *ObjectArg = nullptr;
70377330f729Sjoerg if (isa<CXXOperatorCallExpr>(Call) && Callee->isCXXInstanceMember()) {
70387330f729Sjoerg ObjectArg = Args[0];
70397330f729Sjoerg Args = Args.slice(1);
70407330f729Sjoerg } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) {
70417330f729Sjoerg ObjectArg = MCE->getImplicitObjectArgument();
70427330f729Sjoerg }
70437330f729Sjoerg
70447330f729Sjoerg auto VisitLifetimeBoundArg = [&](const Decl *D, Expr *Arg) {
70457330f729Sjoerg Path.push_back({IndirectLocalPathEntry::LifetimeBoundCall, Arg, D});
70467330f729Sjoerg if (Arg->isGLValue())
70477330f729Sjoerg visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding,
70487330f729Sjoerg Visit,
70497330f729Sjoerg /*EnableLifetimeWarnings=*/false);
70507330f729Sjoerg else
70517330f729Sjoerg visitLocalsRetainedByInitializer(Path, Arg, Visit, true,
70527330f729Sjoerg /*EnableLifetimeWarnings=*/false);
70537330f729Sjoerg Path.pop_back();
70547330f729Sjoerg };
70557330f729Sjoerg
70567330f729Sjoerg if (ObjectArg && implicitObjectParamIsLifetimeBound(Callee))
70577330f729Sjoerg VisitLifetimeBoundArg(Callee, ObjectArg);
70587330f729Sjoerg
70597330f729Sjoerg for (unsigned I = 0,
70607330f729Sjoerg N = std::min<unsigned>(Callee->getNumParams(), Args.size());
70617330f729Sjoerg I != N; ++I) {
70627330f729Sjoerg if (Callee->getParamDecl(I)->hasAttr<LifetimeBoundAttr>())
70637330f729Sjoerg VisitLifetimeBoundArg(Callee->getParamDecl(I), Args[I]);
70647330f729Sjoerg }
70657330f729Sjoerg }
70667330f729Sjoerg
70677330f729Sjoerg /// Visit the locals that would be reachable through a reference bound to the
70687330f729Sjoerg /// glvalue expression \c Init.
visitLocalsRetainedByReferenceBinding(IndirectLocalPath & Path,Expr * Init,ReferenceKind RK,LocalVisitor Visit,bool EnableLifetimeWarnings)70697330f729Sjoerg static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
70707330f729Sjoerg Expr *Init, ReferenceKind RK,
70717330f729Sjoerg LocalVisitor Visit,
70727330f729Sjoerg bool EnableLifetimeWarnings) {
70737330f729Sjoerg RevertToOldSizeRAII RAII(Path);
70747330f729Sjoerg
70757330f729Sjoerg // Walk past any constructs which we can lifetime-extend across.
70767330f729Sjoerg Expr *Old;
70777330f729Sjoerg do {
70787330f729Sjoerg Old = Init;
70797330f729Sjoerg
70807330f729Sjoerg if (auto *FE = dyn_cast<FullExpr>(Init))
70817330f729Sjoerg Init = FE->getSubExpr();
70827330f729Sjoerg
70837330f729Sjoerg if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
70847330f729Sjoerg // If this is just redundant braces around an initializer, step over it.
70857330f729Sjoerg if (ILE->isTransparent())
70867330f729Sjoerg Init = ILE->getInit(0);
70877330f729Sjoerg }
70887330f729Sjoerg
70897330f729Sjoerg // Step over any subobject adjustments; we may have a materialized
70907330f729Sjoerg // temporary inside them.
70917330f729Sjoerg Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
70927330f729Sjoerg
70937330f729Sjoerg // Per current approach for DR1376, look through casts to reference type
70947330f729Sjoerg // when performing lifetime extension.
70957330f729Sjoerg if (CastExpr *CE = dyn_cast<CastExpr>(Init))
70967330f729Sjoerg if (CE->getSubExpr()->isGLValue())
70977330f729Sjoerg Init = CE->getSubExpr();
70987330f729Sjoerg
70997330f729Sjoerg // Per the current approach for DR1299, look through array element access
71007330f729Sjoerg // on array glvalues when performing lifetime extension.
71017330f729Sjoerg if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Init)) {
71027330f729Sjoerg Init = ASE->getBase();
71037330f729Sjoerg auto *ICE = dyn_cast<ImplicitCastExpr>(Init);
71047330f729Sjoerg if (ICE && ICE->getCastKind() == CK_ArrayToPointerDecay)
71057330f729Sjoerg Init = ICE->getSubExpr();
71067330f729Sjoerg else
71077330f729Sjoerg // We can't lifetime extend through this but we might still find some
71087330f729Sjoerg // retained temporaries.
71097330f729Sjoerg return visitLocalsRetainedByInitializer(Path, Init, Visit, true,
71107330f729Sjoerg EnableLifetimeWarnings);
71117330f729Sjoerg }
71127330f729Sjoerg
71137330f729Sjoerg // Step into CXXDefaultInitExprs so we can diagnose cases where a
71147330f729Sjoerg // constructor inherits one as an implicit mem-initializer.
71157330f729Sjoerg if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) {
71167330f729Sjoerg Path.push_back(
71177330f729Sjoerg {IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()});
71187330f729Sjoerg Init = DIE->getExpr();
71197330f729Sjoerg }
71207330f729Sjoerg } while (Init != Old);
71217330f729Sjoerg
71227330f729Sjoerg if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Init)) {
71237330f729Sjoerg if (Visit(Path, Local(MTE), RK))
7124*e038c9c4Sjoerg visitLocalsRetainedByInitializer(Path, MTE->getSubExpr(), Visit, true,
7125*e038c9c4Sjoerg EnableLifetimeWarnings);
71267330f729Sjoerg }
71277330f729Sjoerg
71287330f729Sjoerg if (isa<CallExpr>(Init)) {
71297330f729Sjoerg if (EnableLifetimeWarnings)
71307330f729Sjoerg handleGslAnnotatedTypes(Path, Init, Visit);
71317330f729Sjoerg return visitLifetimeBoundArguments(Path, Init, Visit);
71327330f729Sjoerg }
71337330f729Sjoerg
71347330f729Sjoerg switch (Init->getStmtClass()) {
71357330f729Sjoerg case Stmt::DeclRefExprClass: {
71367330f729Sjoerg // If we find the name of a local non-reference parameter, we could have a
71377330f729Sjoerg // lifetime problem.
71387330f729Sjoerg auto *DRE = cast<DeclRefExpr>(Init);
71397330f729Sjoerg auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
71407330f729Sjoerg if (VD && VD->hasLocalStorage() &&
71417330f729Sjoerg !DRE->refersToEnclosingVariableOrCapture()) {
71427330f729Sjoerg if (!VD->getType()->isReferenceType()) {
71437330f729Sjoerg Visit(Path, Local(DRE), RK);
71447330f729Sjoerg } else if (isa<ParmVarDecl>(DRE->getDecl())) {
71457330f729Sjoerg // The lifetime of a reference parameter is unknown; assume it's OK
71467330f729Sjoerg // for now.
71477330f729Sjoerg break;
71487330f729Sjoerg } else if (VD->getInit() && !isVarOnPath(Path, VD)) {
71497330f729Sjoerg Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD});
71507330f729Sjoerg visitLocalsRetainedByReferenceBinding(Path, VD->getInit(),
71517330f729Sjoerg RK_ReferenceBinding, Visit,
71527330f729Sjoerg EnableLifetimeWarnings);
71537330f729Sjoerg }
71547330f729Sjoerg }
71557330f729Sjoerg break;
71567330f729Sjoerg }
71577330f729Sjoerg
71587330f729Sjoerg case Stmt::UnaryOperatorClass: {
71597330f729Sjoerg // The only unary operator that make sense to handle here
71607330f729Sjoerg // is Deref. All others don't resolve to a "name." This includes
71617330f729Sjoerg // handling all sorts of rvalues passed to a unary operator.
71627330f729Sjoerg const UnaryOperator *U = cast<UnaryOperator>(Init);
71637330f729Sjoerg if (U->getOpcode() == UO_Deref)
71647330f729Sjoerg visitLocalsRetainedByInitializer(Path, U->getSubExpr(), Visit, true,
71657330f729Sjoerg EnableLifetimeWarnings);
71667330f729Sjoerg break;
71677330f729Sjoerg }
71687330f729Sjoerg
71697330f729Sjoerg case Stmt::OMPArraySectionExprClass: {
71707330f729Sjoerg visitLocalsRetainedByInitializer(Path,
71717330f729Sjoerg cast<OMPArraySectionExpr>(Init)->getBase(),
71727330f729Sjoerg Visit, true, EnableLifetimeWarnings);
71737330f729Sjoerg break;
71747330f729Sjoerg }
71757330f729Sjoerg
71767330f729Sjoerg case Stmt::ConditionalOperatorClass:
71777330f729Sjoerg case Stmt::BinaryConditionalOperatorClass: {
71787330f729Sjoerg auto *C = cast<AbstractConditionalOperator>(Init);
71797330f729Sjoerg if (!C->getTrueExpr()->getType()->isVoidType())
71807330f729Sjoerg visitLocalsRetainedByReferenceBinding(Path, C->getTrueExpr(), RK, Visit,
71817330f729Sjoerg EnableLifetimeWarnings);
71827330f729Sjoerg if (!C->getFalseExpr()->getType()->isVoidType())
71837330f729Sjoerg visitLocalsRetainedByReferenceBinding(Path, C->getFalseExpr(), RK, Visit,
71847330f729Sjoerg EnableLifetimeWarnings);
71857330f729Sjoerg break;
71867330f729Sjoerg }
71877330f729Sjoerg
71887330f729Sjoerg // FIXME: Visit the left-hand side of an -> or ->*.
71897330f729Sjoerg
71907330f729Sjoerg default:
71917330f729Sjoerg break;
71927330f729Sjoerg }
71937330f729Sjoerg }
71947330f729Sjoerg
71957330f729Sjoerg /// Visit the locals that would be reachable through an object initialized by
71967330f729Sjoerg /// the prvalue expression \c Init.
visitLocalsRetainedByInitializer(IndirectLocalPath & Path,Expr * Init,LocalVisitor Visit,bool RevisitSubinits,bool EnableLifetimeWarnings)71977330f729Sjoerg static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path,
71987330f729Sjoerg Expr *Init, LocalVisitor Visit,
71997330f729Sjoerg bool RevisitSubinits,
72007330f729Sjoerg bool EnableLifetimeWarnings) {
72017330f729Sjoerg RevertToOldSizeRAII RAII(Path);
72027330f729Sjoerg
72037330f729Sjoerg Expr *Old;
72047330f729Sjoerg do {
72057330f729Sjoerg Old = Init;
72067330f729Sjoerg
72077330f729Sjoerg // Step into CXXDefaultInitExprs so we can diagnose cases where a
72087330f729Sjoerg // constructor inherits one as an implicit mem-initializer.
72097330f729Sjoerg if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) {
72107330f729Sjoerg Path.push_back({IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()});
72117330f729Sjoerg Init = DIE->getExpr();
72127330f729Sjoerg }
72137330f729Sjoerg
72147330f729Sjoerg if (auto *FE = dyn_cast<FullExpr>(Init))
72157330f729Sjoerg Init = FE->getSubExpr();
72167330f729Sjoerg
72177330f729Sjoerg // Dig out the expression which constructs the extended temporary.
72187330f729Sjoerg Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
72197330f729Sjoerg
72207330f729Sjoerg if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
72217330f729Sjoerg Init = BTE->getSubExpr();
72227330f729Sjoerg
72237330f729Sjoerg Init = Init->IgnoreParens();
72247330f729Sjoerg
72257330f729Sjoerg // Step over value-preserving rvalue casts.
72267330f729Sjoerg if (auto *CE = dyn_cast<CastExpr>(Init)) {
72277330f729Sjoerg switch (CE->getCastKind()) {
72287330f729Sjoerg case CK_LValueToRValue:
72297330f729Sjoerg // If we can match the lvalue to a const object, we can look at its
72307330f729Sjoerg // initializer.
72317330f729Sjoerg Path.push_back({IndirectLocalPathEntry::LValToRVal, CE});
72327330f729Sjoerg return visitLocalsRetainedByReferenceBinding(
72337330f729Sjoerg Path, Init, RK_ReferenceBinding,
72347330f729Sjoerg [&](IndirectLocalPath &Path, Local L, ReferenceKind RK) -> bool {
72357330f729Sjoerg if (auto *DRE = dyn_cast<DeclRefExpr>(L)) {
72367330f729Sjoerg auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
72377330f729Sjoerg if (VD && VD->getType().isConstQualified() && VD->getInit() &&
72387330f729Sjoerg !isVarOnPath(Path, VD)) {
72397330f729Sjoerg Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD});
72407330f729Sjoerg visitLocalsRetainedByInitializer(Path, VD->getInit(), Visit, true,
72417330f729Sjoerg EnableLifetimeWarnings);
72427330f729Sjoerg }
72437330f729Sjoerg } else if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L)) {
72447330f729Sjoerg if (MTE->getType().isConstQualified())
7245*e038c9c4Sjoerg visitLocalsRetainedByInitializer(Path, MTE->getSubExpr(), Visit,
7246*e038c9c4Sjoerg true, EnableLifetimeWarnings);
72477330f729Sjoerg }
72487330f729Sjoerg return false;
72497330f729Sjoerg }, EnableLifetimeWarnings);
72507330f729Sjoerg
72517330f729Sjoerg // We assume that objects can be retained by pointers cast to integers,
72527330f729Sjoerg // but not if the integer is cast to floating-point type or to _Complex.
72537330f729Sjoerg // We assume that casts to 'bool' do not preserve enough information to
72547330f729Sjoerg // retain a local object.
72557330f729Sjoerg case CK_NoOp:
72567330f729Sjoerg case CK_BitCast:
72577330f729Sjoerg case CK_BaseToDerived:
72587330f729Sjoerg case CK_DerivedToBase:
72597330f729Sjoerg case CK_UncheckedDerivedToBase:
72607330f729Sjoerg case CK_Dynamic:
72617330f729Sjoerg case CK_ToUnion:
72627330f729Sjoerg case CK_UserDefinedConversion:
72637330f729Sjoerg case CK_ConstructorConversion:
72647330f729Sjoerg case CK_IntegralToPointer:
72657330f729Sjoerg case CK_PointerToIntegral:
72667330f729Sjoerg case CK_VectorSplat:
72677330f729Sjoerg case CK_IntegralCast:
72687330f729Sjoerg case CK_CPointerToObjCPointerCast:
72697330f729Sjoerg case CK_BlockPointerToObjCPointerCast:
72707330f729Sjoerg case CK_AnyPointerToBlockPointerCast:
72717330f729Sjoerg case CK_AddressSpaceConversion:
72727330f729Sjoerg break;
72737330f729Sjoerg
72747330f729Sjoerg case CK_ArrayToPointerDecay:
72757330f729Sjoerg // Model array-to-pointer decay as taking the address of the array
72767330f729Sjoerg // lvalue.
72777330f729Sjoerg Path.push_back({IndirectLocalPathEntry::AddressOf, CE});
72787330f729Sjoerg return visitLocalsRetainedByReferenceBinding(Path, CE->getSubExpr(),
72797330f729Sjoerg RK_ReferenceBinding, Visit,
72807330f729Sjoerg EnableLifetimeWarnings);
72817330f729Sjoerg
72827330f729Sjoerg default:
72837330f729Sjoerg return;
72847330f729Sjoerg }
72857330f729Sjoerg
72867330f729Sjoerg Init = CE->getSubExpr();
72877330f729Sjoerg }
72887330f729Sjoerg } while (Old != Init);
72897330f729Sjoerg
72907330f729Sjoerg // C++17 [dcl.init.list]p6:
72917330f729Sjoerg // initializing an initializer_list object from the array extends the
72927330f729Sjoerg // lifetime of the array exactly like binding a reference to a temporary.
72937330f729Sjoerg if (auto *ILE = dyn_cast<CXXStdInitializerListExpr>(Init))
72947330f729Sjoerg return visitLocalsRetainedByReferenceBinding(Path, ILE->getSubExpr(),
72957330f729Sjoerg RK_StdInitializerList, Visit,
72967330f729Sjoerg EnableLifetimeWarnings);
72977330f729Sjoerg
72987330f729Sjoerg if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
72997330f729Sjoerg // We already visited the elements of this initializer list while
73007330f729Sjoerg // performing the initialization. Don't visit them again unless we've
73017330f729Sjoerg // changed the lifetime of the initialized entity.
73027330f729Sjoerg if (!RevisitSubinits)
73037330f729Sjoerg return;
73047330f729Sjoerg
73057330f729Sjoerg if (ILE->isTransparent())
73067330f729Sjoerg return visitLocalsRetainedByInitializer(Path, ILE->getInit(0), Visit,
73077330f729Sjoerg RevisitSubinits,
73087330f729Sjoerg EnableLifetimeWarnings);
73097330f729Sjoerg
73107330f729Sjoerg if (ILE->getType()->isArrayType()) {
73117330f729Sjoerg for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
73127330f729Sjoerg visitLocalsRetainedByInitializer(Path, ILE->getInit(I), Visit,
73137330f729Sjoerg RevisitSubinits,
73147330f729Sjoerg EnableLifetimeWarnings);
73157330f729Sjoerg return;
73167330f729Sjoerg }
73177330f729Sjoerg
73187330f729Sjoerg if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
73197330f729Sjoerg assert(RD->isAggregate() && "aggregate init on non-aggregate");
73207330f729Sjoerg
73217330f729Sjoerg // If we lifetime-extend a braced initializer which is initializing an
73227330f729Sjoerg // aggregate, and that aggregate contains reference members which are
73237330f729Sjoerg // bound to temporaries, those temporaries are also lifetime-extended.
73247330f729Sjoerg if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
73257330f729Sjoerg ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
73267330f729Sjoerg visitLocalsRetainedByReferenceBinding(Path, ILE->getInit(0),
73277330f729Sjoerg RK_ReferenceBinding, Visit,
73287330f729Sjoerg EnableLifetimeWarnings);
73297330f729Sjoerg else {
73307330f729Sjoerg unsigned Index = 0;
73317330f729Sjoerg for (; Index < RD->getNumBases() && Index < ILE->getNumInits(); ++Index)
73327330f729Sjoerg visitLocalsRetainedByInitializer(Path, ILE->getInit(Index), Visit,
73337330f729Sjoerg RevisitSubinits,
73347330f729Sjoerg EnableLifetimeWarnings);
73357330f729Sjoerg for (const auto *I : RD->fields()) {
73367330f729Sjoerg if (Index >= ILE->getNumInits())
73377330f729Sjoerg break;
73387330f729Sjoerg if (I->isUnnamedBitfield())
73397330f729Sjoerg continue;
73407330f729Sjoerg Expr *SubInit = ILE->getInit(Index);
73417330f729Sjoerg if (I->getType()->isReferenceType())
73427330f729Sjoerg visitLocalsRetainedByReferenceBinding(Path, SubInit,
73437330f729Sjoerg RK_ReferenceBinding, Visit,
73447330f729Sjoerg EnableLifetimeWarnings);
73457330f729Sjoerg else
73467330f729Sjoerg // This might be either aggregate-initialization of a member or
73477330f729Sjoerg // initialization of a std::initializer_list object. Regardless,
73487330f729Sjoerg // we should recursively lifetime-extend that initializer.
73497330f729Sjoerg visitLocalsRetainedByInitializer(Path, SubInit, Visit,
73507330f729Sjoerg RevisitSubinits,
73517330f729Sjoerg EnableLifetimeWarnings);
73527330f729Sjoerg ++Index;
73537330f729Sjoerg }
73547330f729Sjoerg }
73557330f729Sjoerg }
73567330f729Sjoerg return;
73577330f729Sjoerg }
73587330f729Sjoerg
73597330f729Sjoerg // The lifetime of an init-capture is that of the closure object constructed
73607330f729Sjoerg // by a lambda-expression.
73617330f729Sjoerg if (auto *LE = dyn_cast<LambdaExpr>(Init)) {
7362*e038c9c4Sjoerg LambdaExpr::capture_iterator CapI = LE->capture_begin();
73637330f729Sjoerg for (Expr *E : LE->capture_inits()) {
7364*e038c9c4Sjoerg assert(CapI != LE->capture_end());
7365*e038c9c4Sjoerg const LambdaCapture &Cap = *CapI++;
73667330f729Sjoerg if (!E)
73677330f729Sjoerg continue;
7368*e038c9c4Sjoerg if (Cap.capturesVariable())
7369*e038c9c4Sjoerg Path.push_back({IndirectLocalPathEntry::LambdaCaptureInit, E, &Cap});
73707330f729Sjoerg if (E->isGLValue())
73717330f729Sjoerg visitLocalsRetainedByReferenceBinding(Path, E, RK_ReferenceBinding,
73727330f729Sjoerg Visit, EnableLifetimeWarnings);
73737330f729Sjoerg else
73747330f729Sjoerg visitLocalsRetainedByInitializer(Path, E, Visit, true,
73757330f729Sjoerg EnableLifetimeWarnings);
7376*e038c9c4Sjoerg if (Cap.capturesVariable())
7377*e038c9c4Sjoerg Path.pop_back();
7378*e038c9c4Sjoerg }
7379*e038c9c4Sjoerg }
7380*e038c9c4Sjoerg
7381*e038c9c4Sjoerg // Assume that a copy or move from a temporary references the same objects
7382*e038c9c4Sjoerg // that the temporary does.
7383*e038c9c4Sjoerg if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
7384*e038c9c4Sjoerg if (CCE->getConstructor()->isCopyOrMoveConstructor()) {
7385*e038c9c4Sjoerg if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(CCE->getArg(0))) {
7386*e038c9c4Sjoerg Expr *Arg = MTE->getSubExpr();
7387*e038c9c4Sjoerg Path.push_back({IndirectLocalPathEntry::TemporaryCopy, Arg,
7388*e038c9c4Sjoerg CCE->getConstructor()});
7389*e038c9c4Sjoerg visitLocalsRetainedByInitializer(Path, Arg, Visit, true,
7390*e038c9c4Sjoerg /*EnableLifetimeWarnings*/false);
7391*e038c9c4Sjoerg Path.pop_back();
7392*e038c9c4Sjoerg }
73937330f729Sjoerg }
73947330f729Sjoerg }
73957330f729Sjoerg
73967330f729Sjoerg if (isa<CallExpr>(Init) || isa<CXXConstructExpr>(Init)) {
73977330f729Sjoerg if (EnableLifetimeWarnings)
73987330f729Sjoerg handleGslAnnotatedTypes(Path, Init, Visit);
73997330f729Sjoerg return visitLifetimeBoundArguments(Path, Init, Visit);
74007330f729Sjoerg }
74017330f729Sjoerg
74027330f729Sjoerg switch (Init->getStmtClass()) {
74037330f729Sjoerg case Stmt::UnaryOperatorClass: {
74047330f729Sjoerg auto *UO = cast<UnaryOperator>(Init);
74057330f729Sjoerg // If the initializer is the address of a local, we could have a lifetime
74067330f729Sjoerg // problem.
74077330f729Sjoerg if (UO->getOpcode() == UO_AddrOf) {
74087330f729Sjoerg // If this is &rvalue, then it's ill-formed and we have already diagnosed
74097330f729Sjoerg // it. Don't produce a redundant warning about the lifetime of the
74107330f729Sjoerg // temporary.
74117330f729Sjoerg if (isa<MaterializeTemporaryExpr>(UO->getSubExpr()))
74127330f729Sjoerg return;
74137330f729Sjoerg
74147330f729Sjoerg Path.push_back({IndirectLocalPathEntry::AddressOf, UO});
74157330f729Sjoerg visitLocalsRetainedByReferenceBinding(Path, UO->getSubExpr(),
74167330f729Sjoerg RK_ReferenceBinding, Visit,
74177330f729Sjoerg EnableLifetimeWarnings);
74187330f729Sjoerg }
74197330f729Sjoerg break;
74207330f729Sjoerg }
74217330f729Sjoerg
74227330f729Sjoerg case Stmt::BinaryOperatorClass: {
74237330f729Sjoerg // Handle pointer arithmetic.
74247330f729Sjoerg auto *BO = cast<BinaryOperator>(Init);
74257330f729Sjoerg BinaryOperatorKind BOK = BO->getOpcode();
74267330f729Sjoerg if (!BO->getType()->isPointerType() || (BOK != BO_Add && BOK != BO_Sub))
74277330f729Sjoerg break;
74287330f729Sjoerg
74297330f729Sjoerg if (BO->getLHS()->getType()->isPointerType())
74307330f729Sjoerg visitLocalsRetainedByInitializer(Path, BO->getLHS(), Visit, true,
74317330f729Sjoerg EnableLifetimeWarnings);
74327330f729Sjoerg else if (BO->getRHS()->getType()->isPointerType())
74337330f729Sjoerg visitLocalsRetainedByInitializer(Path, BO->getRHS(), Visit, true,
74347330f729Sjoerg EnableLifetimeWarnings);
74357330f729Sjoerg break;
74367330f729Sjoerg }
74377330f729Sjoerg
74387330f729Sjoerg case Stmt::ConditionalOperatorClass:
74397330f729Sjoerg case Stmt::BinaryConditionalOperatorClass: {
74407330f729Sjoerg auto *C = cast<AbstractConditionalOperator>(Init);
74417330f729Sjoerg // In C++, we can have a throw-expression operand, which has 'void' type
74427330f729Sjoerg // and isn't interesting from a lifetime perspective.
74437330f729Sjoerg if (!C->getTrueExpr()->getType()->isVoidType())
74447330f729Sjoerg visitLocalsRetainedByInitializer(Path, C->getTrueExpr(), Visit, true,
74457330f729Sjoerg EnableLifetimeWarnings);
74467330f729Sjoerg if (!C->getFalseExpr()->getType()->isVoidType())
74477330f729Sjoerg visitLocalsRetainedByInitializer(Path, C->getFalseExpr(), Visit, true,
74487330f729Sjoerg EnableLifetimeWarnings);
74497330f729Sjoerg break;
74507330f729Sjoerg }
74517330f729Sjoerg
74527330f729Sjoerg case Stmt::BlockExprClass:
74537330f729Sjoerg if (cast<BlockExpr>(Init)->getBlockDecl()->hasCaptures()) {
74547330f729Sjoerg // This is a local block, whose lifetime is that of the function.
74557330f729Sjoerg Visit(Path, Local(cast<BlockExpr>(Init)), RK_ReferenceBinding);
74567330f729Sjoerg }
74577330f729Sjoerg break;
74587330f729Sjoerg
74597330f729Sjoerg case Stmt::AddrLabelExprClass:
74607330f729Sjoerg // We want to warn if the address of a label would escape the function.
74617330f729Sjoerg Visit(Path, Local(cast<AddrLabelExpr>(Init)), RK_ReferenceBinding);
74627330f729Sjoerg break;
74637330f729Sjoerg
74647330f729Sjoerg default:
74657330f729Sjoerg break;
74667330f729Sjoerg }
74677330f729Sjoerg }
74687330f729Sjoerg
7469*e038c9c4Sjoerg /// Whether a path to an object supports lifetime extension.
7470*e038c9c4Sjoerg enum PathLifetimeKind {
7471*e038c9c4Sjoerg /// Lifetime-extend along this path.
7472*e038c9c4Sjoerg Extend,
7473*e038c9c4Sjoerg /// We should lifetime-extend, but we don't because (due to technical
7474*e038c9c4Sjoerg /// limitations) we can't. This happens for default member initializers,
7475*e038c9c4Sjoerg /// which we don't clone for every use, so we don't have a unique
7476*e038c9c4Sjoerg /// MaterializeTemporaryExpr to update.
7477*e038c9c4Sjoerg ShouldExtend,
7478*e038c9c4Sjoerg /// Do not lifetime extend along this path.
7479*e038c9c4Sjoerg NoExtend
7480*e038c9c4Sjoerg };
7481*e038c9c4Sjoerg
74827330f729Sjoerg /// Determine whether this is an indirect path to a temporary that we are
7483*e038c9c4Sjoerg /// supposed to lifetime-extend along.
7484*e038c9c4Sjoerg static PathLifetimeKind
shouldLifetimeExtendThroughPath(const IndirectLocalPath & Path)7485*e038c9c4Sjoerg shouldLifetimeExtendThroughPath(const IndirectLocalPath &Path) {
7486*e038c9c4Sjoerg PathLifetimeKind Kind = PathLifetimeKind::Extend;
74877330f729Sjoerg for (auto Elem : Path) {
7488*e038c9c4Sjoerg if (Elem.Kind == IndirectLocalPathEntry::DefaultInit)
7489*e038c9c4Sjoerg Kind = PathLifetimeKind::ShouldExtend;
7490*e038c9c4Sjoerg else if (Elem.Kind != IndirectLocalPathEntry::LambdaCaptureInit)
7491*e038c9c4Sjoerg return PathLifetimeKind::NoExtend;
74927330f729Sjoerg }
7493*e038c9c4Sjoerg return Kind;
74947330f729Sjoerg }
74957330f729Sjoerg
74967330f729Sjoerg /// Find the range for the first interesting entry in the path at or after I.
nextPathEntryRange(const IndirectLocalPath & Path,unsigned I,Expr * E)74977330f729Sjoerg static SourceRange nextPathEntryRange(const IndirectLocalPath &Path, unsigned I,
74987330f729Sjoerg Expr *E) {
74997330f729Sjoerg for (unsigned N = Path.size(); I != N; ++I) {
75007330f729Sjoerg switch (Path[I].Kind) {
75017330f729Sjoerg case IndirectLocalPathEntry::AddressOf:
75027330f729Sjoerg case IndirectLocalPathEntry::LValToRVal:
75037330f729Sjoerg case IndirectLocalPathEntry::LifetimeBoundCall:
7504*e038c9c4Sjoerg case IndirectLocalPathEntry::TemporaryCopy:
7505*e038c9c4Sjoerg case IndirectLocalPathEntry::GslReferenceInit:
75067330f729Sjoerg case IndirectLocalPathEntry::GslPointerInit:
75077330f729Sjoerg // These exist primarily to mark the path as not permitting or
75087330f729Sjoerg // supporting lifetime extension.
75097330f729Sjoerg break;
75107330f729Sjoerg
75117330f729Sjoerg case IndirectLocalPathEntry::VarInit:
75127330f729Sjoerg if (cast<VarDecl>(Path[I].D)->isImplicit())
75137330f729Sjoerg return SourceRange();
75147330f729Sjoerg LLVM_FALLTHROUGH;
75157330f729Sjoerg case IndirectLocalPathEntry::DefaultInit:
75167330f729Sjoerg return Path[I].E->getSourceRange();
7517*e038c9c4Sjoerg
7518*e038c9c4Sjoerg case IndirectLocalPathEntry::LambdaCaptureInit:
7519*e038c9c4Sjoerg if (!Path[I].Capture->capturesVariable())
7520*e038c9c4Sjoerg continue;
7521*e038c9c4Sjoerg return Path[I].E->getSourceRange();
75227330f729Sjoerg }
75237330f729Sjoerg }
75247330f729Sjoerg return E->getSourceRange();
75257330f729Sjoerg }
75267330f729Sjoerg
pathOnlyInitializesGslPointer(IndirectLocalPath & Path)75277330f729Sjoerg static bool pathOnlyInitializesGslPointer(IndirectLocalPath &Path) {
75287330f729Sjoerg for (auto It = Path.rbegin(), End = Path.rend(); It != End; ++It) {
75297330f729Sjoerg if (It->Kind == IndirectLocalPathEntry::VarInit)
75307330f729Sjoerg continue;
75317330f729Sjoerg if (It->Kind == IndirectLocalPathEntry::AddressOf)
75327330f729Sjoerg continue;
7533*e038c9c4Sjoerg if (It->Kind == IndirectLocalPathEntry::LifetimeBoundCall)
7534*e038c9c4Sjoerg continue;
7535*e038c9c4Sjoerg return It->Kind == IndirectLocalPathEntry::GslPointerInit ||
7536*e038c9c4Sjoerg It->Kind == IndirectLocalPathEntry::GslReferenceInit;
75377330f729Sjoerg }
75387330f729Sjoerg return false;
75397330f729Sjoerg }
75407330f729Sjoerg
checkInitializerLifetime(const InitializedEntity & Entity,Expr * Init)75417330f729Sjoerg void Sema::checkInitializerLifetime(const InitializedEntity &Entity,
75427330f729Sjoerg Expr *Init) {
75437330f729Sjoerg LifetimeResult LR = getEntityLifetime(&Entity);
75447330f729Sjoerg LifetimeKind LK = LR.getInt();
75457330f729Sjoerg const InitializedEntity *ExtendingEntity = LR.getPointer();
75467330f729Sjoerg
75477330f729Sjoerg // If this entity doesn't have an interesting lifetime, don't bother looking
75487330f729Sjoerg // for temporaries within its initializer.
75497330f729Sjoerg if (LK == LK_FullExpression)
75507330f729Sjoerg return;
75517330f729Sjoerg
75527330f729Sjoerg auto TemporaryVisitor = [&](IndirectLocalPath &Path, Local L,
75537330f729Sjoerg ReferenceKind RK) -> bool {
75547330f729Sjoerg SourceRange DiagRange = nextPathEntryRange(Path, 0, L);
75557330f729Sjoerg SourceLocation DiagLoc = DiagRange.getBegin();
75567330f729Sjoerg
75577330f729Sjoerg auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L);
75587330f729Sjoerg
75597330f729Sjoerg bool IsGslPtrInitWithGslTempOwner = false;
75607330f729Sjoerg bool IsLocalGslOwner = false;
75617330f729Sjoerg if (pathOnlyInitializesGslPointer(Path)) {
75627330f729Sjoerg if (isa<DeclRefExpr>(L)) {
75637330f729Sjoerg // We do not want to follow the references when returning a pointer originating
75647330f729Sjoerg // from a local owner to avoid the following false positive:
75657330f729Sjoerg // int &p = *localUniquePtr;
75667330f729Sjoerg // someContainer.add(std::move(localUniquePtr));
75677330f729Sjoerg // return p;
75687330f729Sjoerg IsLocalGslOwner = isRecordWithAttr<OwnerAttr>(L->getType());
75697330f729Sjoerg if (pathContainsInit(Path) || !IsLocalGslOwner)
75707330f729Sjoerg return false;
75717330f729Sjoerg } else {
75727330f729Sjoerg IsGslPtrInitWithGslTempOwner = MTE && !MTE->getExtendingDecl() &&
75737330f729Sjoerg isRecordWithAttr<OwnerAttr>(MTE->getType());
75747330f729Sjoerg // Skipping a chain of initializing gsl::Pointer annotated objects.
75757330f729Sjoerg // We are looking only for the final source to find out if it was
75767330f729Sjoerg // a local or temporary owner or the address of a local variable/param.
75777330f729Sjoerg if (!IsGslPtrInitWithGslTempOwner)
75787330f729Sjoerg return true;
75797330f729Sjoerg }
75807330f729Sjoerg }
75817330f729Sjoerg
75827330f729Sjoerg switch (LK) {
75837330f729Sjoerg case LK_FullExpression:
75847330f729Sjoerg llvm_unreachable("already handled this");
75857330f729Sjoerg
75867330f729Sjoerg case LK_Extended: {
75877330f729Sjoerg if (!MTE) {
75887330f729Sjoerg // The initialized entity has lifetime beyond the full-expression,
75897330f729Sjoerg // and the local entity does too, so don't warn.
75907330f729Sjoerg //
75917330f729Sjoerg // FIXME: We should consider warning if a static / thread storage
75927330f729Sjoerg // duration variable retains an automatic storage duration local.
75937330f729Sjoerg return false;
75947330f729Sjoerg }
75957330f729Sjoerg
75967330f729Sjoerg if (IsGslPtrInitWithGslTempOwner && DiagLoc.isValid()) {
75977330f729Sjoerg Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange;
75987330f729Sjoerg return false;
75997330f729Sjoerg }
76007330f729Sjoerg
7601*e038c9c4Sjoerg switch (shouldLifetimeExtendThroughPath(Path)) {
7602*e038c9c4Sjoerg case PathLifetimeKind::Extend:
76037330f729Sjoerg // Update the storage duration of the materialized temporary.
76047330f729Sjoerg // FIXME: Rebuild the expression instead of mutating it.
76057330f729Sjoerg MTE->setExtendingDecl(ExtendingEntity->getDecl(),
76067330f729Sjoerg ExtendingEntity->allocateManglingNumber());
76077330f729Sjoerg // Also visit the temporaries lifetime-extended by this initializer.
76087330f729Sjoerg return true;
76097330f729Sjoerg
7610*e038c9c4Sjoerg case PathLifetimeKind::ShouldExtend:
76117330f729Sjoerg // We're supposed to lifetime-extend the temporary along this path (per
76127330f729Sjoerg // the resolution of DR1815), but we don't support that yet.
76137330f729Sjoerg //
76147330f729Sjoerg // FIXME: Properly handle this situation. Perhaps the easiest approach
76157330f729Sjoerg // would be to clone the initializer expression on each use that would
76167330f729Sjoerg // lifetime extend its temporaries.
76177330f729Sjoerg Diag(DiagLoc, diag::warn_unsupported_lifetime_extension)
76187330f729Sjoerg << RK << DiagRange;
7619*e038c9c4Sjoerg break;
7620*e038c9c4Sjoerg
7621*e038c9c4Sjoerg case PathLifetimeKind::NoExtend:
76227330f729Sjoerg // If the path goes through the initialization of a variable or field,
76237330f729Sjoerg // it can't possibly reach a temporary created in this full-expression.
76247330f729Sjoerg // We will have already diagnosed any problems with the initializer.
76257330f729Sjoerg if (pathContainsInit(Path))
76267330f729Sjoerg return false;
76277330f729Sjoerg
76287330f729Sjoerg Diag(DiagLoc, diag::warn_dangling_variable)
76297330f729Sjoerg << RK << !Entity.getParent()
76307330f729Sjoerg << ExtendingEntity->getDecl()->isImplicit()
76317330f729Sjoerg << ExtendingEntity->getDecl() << Init->isGLValue() << DiagRange;
7632*e038c9c4Sjoerg break;
76337330f729Sjoerg }
76347330f729Sjoerg break;
76357330f729Sjoerg }
76367330f729Sjoerg
76377330f729Sjoerg case LK_MemInitializer: {
76387330f729Sjoerg if (isa<MaterializeTemporaryExpr>(L)) {
76397330f729Sjoerg // Under C++ DR1696, if a mem-initializer (or a default member
76407330f729Sjoerg // initializer used by the absence of one) would lifetime-extend a
76417330f729Sjoerg // temporary, the program is ill-formed.
76427330f729Sjoerg if (auto *ExtendingDecl =
76437330f729Sjoerg ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) {
76447330f729Sjoerg if (IsGslPtrInitWithGslTempOwner) {
76457330f729Sjoerg Diag(DiagLoc, diag::warn_dangling_lifetime_pointer_member)
76467330f729Sjoerg << ExtendingDecl << DiagRange;
76477330f729Sjoerg Diag(ExtendingDecl->getLocation(),
76487330f729Sjoerg diag::note_ref_or_ptr_member_declared_here)
76497330f729Sjoerg << true;
76507330f729Sjoerg return false;
76517330f729Sjoerg }
76527330f729Sjoerg bool IsSubobjectMember = ExtendingEntity != &Entity;
7653*e038c9c4Sjoerg Diag(DiagLoc, shouldLifetimeExtendThroughPath(Path) !=
7654*e038c9c4Sjoerg PathLifetimeKind::NoExtend
76557330f729Sjoerg ? diag::err_dangling_member
76567330f729Sjoerg : diag::warn_dangling_member)
76577330f729Sjoerg << ExtendingDecl << IsSubobjectMember << RK << DiagRange;
76587330f729Sjoerg // Don't bother adding a note pointing to the field if we're inside
76597330f729Sjoerg // its default member initializer; our primary diagnostic points to
76607330f729Sjoerg // the same place in that case.
76617330f729Sjoerg if (Path.empty() ||
76627330f729Sjoerg Path.back().Kind != IndirectLocalPathEntry::DefaultInit) {
76637330f729Sjoerg Diag(ExtendingDecl->getLocation(),
76647330f729Sjoerg diag::note_lifetime_extending_member_declared_here)
76657330f729Sjoerg << RK << IsSubobjectMember;
76667330f729Sjoerg }
76677330f729Sjoerg } else {
76687330f729Sjoerg // We have a mem-initializer but no particular field within it; this
76697330f729Sjoerg // is either a base class or a delegating initializer directly
76707330f729Sjoerg // initializing the base-class from something that doesn't live long
76717330f729Sjoerg // enough.
76727330f729Sjoerg //
76737330f729Sjoerg // FIXME: Warn on this.
76747330f729Sjoerg return false;
76757330f729Sjoerg }
76767330f729Sjoerg } else {
76777330f729Sjoerg // Paths via a default initializer can only occur during error recovery
76787330f729Sjoerg // (there's no other way that a default initializer can refer to a
76797330f729Sjoerg // local). Don't produce a bogus warning on those cases.
76807330f729Sjoerg if (pathContainsInit(Path))
76817330f729Sjoerg return false;
76827330f729Sjoerg
76837330f729Sjoerg // Suppress false positives for code like the one below:
76847330f729Sjoerg // Ctor(unique_ptr<T> up) : member(*up), member2(move(up)) {}
76857330f729Sjoerg if (IsLocalGslOwner && pathOnlyInitializesGslPointer(Path))
76867330f729Sjoerg return false;
76877330f729Sjoerg
76887330f729Sjoerg auto *DRE = dyn_cast<DeclRefExpr>(L);
76897330f729Sjoerg auto *VD = DRE ? dyn_cast<VarDecl>(DRE->getDecl()) : nullptr;
76907330f729Sjoerg if (!VD) {
76917330f729Sjoerg // A member was initialized to a local block.
76927330f729Sjoerg // FIXME: Warn on this.
76937330f729Sjoerg return false;
76947330f729Sjoerg }
76957330f729Sjoerg
76967330f729Sjoerg if (auto *Member =
76977330f729Sjoerg ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) {
76987330f729Sjoerg bool IsPointer = !Member->getType()->isReferenceType();
76997330f729Sjoerg Diag(DiagLoc, IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
77007330f729Sjoerg : diag::warn_bind_ref_member_to_parameter)
77017330f729Sjoerg << Member << VD << isa<ParmVarDecl>(VD) << DiagRange;
77027330f729Sjoerg Diag(Member->getLocation(),
77037330f729Sjoerg diag::note_ref_or_ptr_member_declared_here)
77047330f729Sjoerg << (unsigned)IsPointer;
77057330f729Sjoerg }
77067330f729Sjoerg }
77077330f729Sjoerg break;
77087330f729Sjoerg }
77097330f729Sjoerg
77107330f729Sjoerg case LK_New:
77117330f729Sjoerg if (isa<MaterializeTemporaryExpr>(L)) {
77127330f729Sjoerg if (IsGslPtrInitWithGslTempOwner)
77137330f729Sjoerg Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange;
77147330f729Sjoerg else
77157330f729Sjoerg Diag(DiagLoc, RK == RK_ReferenceBinding
77167330f729Sjoerg ? diag::warn_new_dangling_reference
77177330f729Sjoerg : diag::warn_new_dangling_initializer_list)
77187330f729Sjoerg << !Entity.getParent() << DiagRange;
77197330f729Sjoerg } else {
77207330f729Sjoerg // We can't determine if the allocation outlives the local declaration.
77217330f729Sjoerg return false;
77227330f729Sjoerg }
77237330f729Sjoerg break;
77247330f729Sjoerg
77257330f729Sjoerg case LK_Return:
77267330f729Sjoerg case LK_StmtExprResult:
77277330f729Sjoerg if (auto *DRE = dyn_cast<DeclRefExpr>(L)) {
77287330f729Sjoerg // We can't determine if the local variable outlives the statement
77297330f729Sjoerg // expression.
77307330f729Sjoerg if (LK == LK_StmtExprResult)
77317330f729Sjoerg return false;
77327330f729Sjoerg Diag(DiagLoc, diag::warn_ret_stack_addr_ref)
77337330f729Sjoerg << Entity.getType()->isReferenceType() << DRE->getDecl()
77347330f729Sjoerg << isa<ParmVarDecl>(DRE->getDecl()) << DiagRange;
77357330f729Sjoerg } else if (isa<BlockExpr>(L)) {
77367330f729Sjoerg Diag(DiagLoc, diag::err_ret_local_block) << DiagRange;
77377330f729Sjoerg } else if (isa<AddrLabelExpr>(L)) {
77387330f729Sjoerg // Don't warn when returning a label from a statement expression.
77397330f729Sjoerg // Leaving the scope doesn't end its lifetime.
77407330f729Sjoerg if (LK == LK_StmtExprResult)
77417330f729Sjoerg return false;
77427330f729Sjoerg Diag(DiagLoc, diag::warn_ret_addr_label) << DiagRange;
77437330f729Sjoerg } else {
77447330f729Sjoerg Diag(DiagLoc, diag::warn_ret_local_temp_addr_ref)
77457330f729Sjoerg << Entity.getType()->isReferenceType() << DiagRange;
77467330f729Sjoerg }
77477330f729Sjoerg break;
77487330f729Sjoerg }
77497330f729Sjoerg
77507330f729Sjoerg for (unsigned I = 0; I != Path.size(); ++I) {
77517330f729Sjoerg auto Elem = Path[I];
77527330f729Sjoerg
77537330f729Sjoerg switch (Elem.Kind) {
77547330f729Sjoerg case IndirectLocalPathEntry::AddressOf:
77557330f729Sjoerg case IndirectLocalPathEntry::LValToRVal:
77567330f729Sjoerg // These exist primarily to mark the path as not permitting or
77577330f729Sjoerg // supporting lifetime extension.
77587330f729Sjoerg break;
77597330f729Sjoerg
77607330f729Sjoerg case IndirectLocalPathEntry::LifetimeBoundCall:
7761*e038c9c4Sjoerg case IndirectLocalPathEntry::TemporaryCopy:
77627330f729Sjoerg case IndirectLocalPathEntry::GslPointerInit:
7763*e038c9c4Sjoerg case IndirectLocalPathEntry::GslReferenceInit:
77647330f729Sjoerg // FIXME: Consider adding a note for these.
77657330f729Sjoerg break;
77667330f729Sjoerg
77677330f729Sjoerg case IndirectLocalPathEntry::DefaultInit: {
77687330f729Sjoerg auto *FD = cast<FieldDecl>(Elem.D);
77697330f729Sjoerg Diag(FD->getLocation(), diag::note_init_with_default_member_initalizer)
77707330f729Sjoerg << FD << nextPathEntryRange(Path, I + 1, L);
77717330f729Sjoerg break;
77727330f729Sjoerg }
77737330f729Sjoerg
7774*e038c9c4Sjoerg case IndirectLocalPathEntry::VarInit: {
77757330f729Sjoerg const VarDecl *VD = cast<VarDecl>(Elem.D);
77767330f729Sjoerg Diag(VD->getLocation(), diag::note_local_var_initializer)
77777330f729Sjoerg << VD->getType()->isReferenceType()
77787330f729Sjoerg << VD->isImplicit() << VD->getDeclName()
77797330f729Sjoerg << nextPathEntryRange(Path, I + 1, L);
77807330f729Sjoerg break;
77817330f729Sjoerg }
7782*e038c9c4Sjoerg
7783*e038c9c4Sjoerg case IndirectLocalPathEntry::LambdaCaptureInit:
7784*e038c9c4Sjoerg if (!Elem.Capture->capturesVariable())
7785*e038c9c4Sjoerg break;
7786*e038c9c4Sjoerg // FIXME: We can't easily tell apart an init-capture from a nested
7787*e038c9c4Sjoerg // capture of an init-capture.
7788*e038c9c4Sjoerg const VarDecl *VD = Elem.Capture->getCapturedVar();
7789*e038c9c4Sjoerg Diag(Elem.Capture->getLocation(), diag::note_lambda_capture_initializer)
7790*e038c9c4Sjoerg << VD << VD->isInitCapture() << Elem.Capture->isExplicit()
7791*e038c9c4Sjoerg << (Elem.Capture->getCaptureKind() == LCK_ByRef) << VD
7792*e038c9c4Sjoerg << nextPathEntryRange(Path, I + 1, L);
7793*e038c9c4Sjoerg break;
7794*e038c9c4Sjoerg }
77957330f729Sjoerg }
77967330f729Sjoerg
77977330f729Sjoerg // We didn't lifetime-extend, so don't go any further; we don't need more
77987330f729Sjoerg // warnings or errors on inner temporaries within this one's initializer.
77997330f729Sjoerg return false;
78007330f729Sjoerg };
78017330f729Sjoerg
78027330f729Sjoerg bool EnableLifetimeWarnings = !getDiagnostics().isIgnored(
78037330f729Sjoerg diag::warn_dangling_lifetime_pointer, SourceLocation());
78047330f729Sjoerg llvm::SmallVector<IndirectLocalPathEntry, 8> Path;
78057330f729Sjoerg if (Init->isGLValue())
78067330f729Sjoerg visitLocalsRetainedByReferenceBinding(Path, Init, RK_ReferenceBinding,
78077330f729Sjoerg TemporaryVisitor,
78087330f729Sjoerg EnableLifetimeWarnings);
78097330f729Sjoerg else
78107330f729Sjoerg visitLocalsRetainedByInitializer(Path, Init, TemporaryVisitor, false,
78117330f729Sjoerg EnableLifetimeWarnings);
78127330f729Sjoerg }
78137330f729Sjoerg
78147330f729Sjoerg static void DiagnoseNarrowingInInitList(Sema &S,
78157330f729Sjoerg const ImplicitConversionSequence &ICS,
78167330f729Sjoerg QualType PreNarrowingType,
78177330f729Sjoerg QualType EntityType,
78187330f729Sjoerg const Expr *PostInit);
78197330f729Sjoerg
78207330f729Sjoerg /// Provide warnings when std::move is used on construction.
CheckMoveOnConstruction(Sema & S,const Expr * InitExpr,bool IsReturnStmt)78217330f729Sjoerg static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr,
78227330f729Sjoerg bool IsReturnStmt) {
78237330f729Sjoerg if (!InitExpr)
78247330f729Sjoerg return;
78257330f729Sjoerg
78267330f729Sjoerg if (S.inTemplateInstantiation())
78277330f729Sjoerg return;
78287330f729Sjoerg
78297330f729Sjoerg QualType DestType = InitExpr->getType();
78307330f729Sjoerg if (!DestType->isRecordType())
78317330f729Sjoerg return;
78327330f729Sjoerg
78337330f729Sjoerg unsigned DiagID = 0;
78347330f729Sjoerg if (IsReturnStmt) {
78357330f729Sjoerg const CXXConstructExpr *CCE =
78367330f729Sjoerg dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens());
78377330f729Sjoerg if (!CCE || CCE->getNumArgs() != 1)
78387330f729Sjoerg return;
78397330f729Sjoerg
78407330f729Sjoerg if (!CCE->getConstructor()->isCopyOrMoveConstructor())
78417330f729Sjoerg return;
78427330f729Sjoerg
78437330f729Sjoerg InitExpr = CCE->getArg(0)->IgnoreImpCasts();
78447330f729Sjoerg }
78457330f729Sjoerg
78467330f729Sjoerg // Find the std::move call and get the argument.
78477330f729Sjoerg const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens());
78487330f729Sjoerg if (!CE || !CE->isCallToStdMove())
78497330f729Sjoerg return;
78507330f729Sjoerg
78517330f729Sjoerg const Expr *Arg = CE->getArg(0)->IgnoreImplicit();
78527330f729Sjoerg
78537330f729Sjoerg if (IsReturnStmt) {
78547330f729Sjoerg const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts());
78557330f729Sjoerg if (!DRE || DRE->refersToEnclosingVariableOrCapture())
78567330f729Sjoerg return;
78577330f729Sjoerg
78587330f729Sjoerg const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
78597330f729Sjoerg if (!VD || !VD->hasLocalStorage())
78607330f729Sjoerg return;
78617330f729Sjoerg
78627330f729Sjoerg // __block variables are not moved implicitly.
78637330f729Sjoerg if (VD->hasAttr<BlocksAttr>())
78647330f729Sjoerg return;
78657330f729Sjoerg
78667330f729Sjoerg QualType SourceType = VD->getType();
78677330f729Sjoerg if (!SourceType->isRecordType())
78687330f729Sjoerg return;
78697330f729Sjoerg
78707330f729Sjoerg if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) {
78717330f729Sjoerg return;
78727330f729Sjoerg }
78737330f729Sjoerg
78747330f729Sjoerg // If we're returning a function parameter, copy elision
78757330f729Sjoerg // is not possible.
78767330f729Sjoerg if (isa<ParmVarDecl>(VD))
78777330f729Sjoerg DiagID = diag::warn_redundant_move_on_return;
78787330f729Sjoerg else
78797330f729Sjoerg DiagID = diag::warn_pessimizing_move_on_return;
78807330f729Sjoerg } else {
78817330f729Sjoerg DiagID = diag::warn_pessimizing_move_on_initialization;
78827330f729Sjoerg const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();
78837330f729Sjoerg if (!ArgStripped->isRValue() || !ArgStripped->getType()->isRecordType())
78847330f729Sjoerg return;
78857330f729Sjoerg }
78867330f729Sjoerg
78877330f729Sjoerg S.Diag(CE->getBeginLoc(), DiagID);
78887330f729Sjoerg
78897330f729Sjoerg // Get all the locations for a fix-it. Don't emit the fix-it if any location
78907330f729Sjoerg // is within a macro.
78917330f729Sjoerg SourceLocation CallBegin = CE->getCallee()->getBeginLoc();
78927330f729Sjoerg if (CallBegin.isMacroID())
78937330f729Sjoerg return;
78947330f729Sjoerg SourceLocation RParen = CE->getRParenLoc();
78957330f729Sjoerg if (RParen.isMacroID())
78967330f729Sjoerg return;
78977330f729Sjoerg SourceLocation LParen;
78987330f729Sjoerg SourceLocation ArgLoc = Arg->getBeginLoc();
78997330f729Sjoerg
79007330f729Sjoerg // Special testing for the argument location. Since the fix-it needs the
79017330f729Sjoerg // location right before the argument, the argument location can be in a
79027330f729Sjoerg // macro only if it is at the beginning of the macro.
79037330f729Sjoerg while (ArgLoc.isMacroID() &&
79047330f729Sjoerg S.getSourceManager().isAtStartOfImmediateMacroExpansion(ArgLoc)) {
79057330f729Sjoerg ArgLoc = S.getSourceManager().getImmediateExpansionRange(ArgLoc).getBegin();
79067330f729Sjoerg }
79077330f729Sjoerg
79087330f729Sjoerg if (LParen.isMacroID())
79097330f729Sjoerg return;
79107330f729Sjoerg
79117330f729Sjoerg LParen = ArgLoc.getLocWithOffset(-1);
79127330f729Sjoerg
79137330f729Sjoerg S.Diag(CE->getBeginLoc(), diag::note_remove_move)
79147330f729Sjoerg << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen))
79157330f729Sjoerg << FixItHint::CreateRemoval(SourceRange(RParen, RParen));
79167330f729Sjoerg }
79177330f729Sjoerg
CheckForNullPointerDereference(Sema & S,const Expr * E)79187330f729Sjoerg static void CheckForNullPointerDereference(Sema &S, const Expr *E) {
79197330f729Sjoerg // Check to see if we are dereferencing a null pointer. If so, this is
79207330f729Sjoerg // undefined behavior, so warn about it. This only handles the pattern
79217330f729Sjoerg // "*null", which is a very syntactic check.
79227330f729Sjoerg if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
79237330f729Sjoerg if (UO->getOpcode() == UO_Deref &&
79247330f729Sjoerg UO->getSubExpr()->IgnoreParenCasts()->
79257330f729Sjoerg isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) {
79267330f729Sjoerg S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
79277330f729Sjoerg S.PDiag(diag::warn_binding_null_to_reference)
79287330f729Sjoerg << UO->getSubExpr()->getSourceRange());
79297330f729Sjoerg }
79307330f729Sjoerg }
79317330f729Sjoerg
79327330f729Sjoerg MaterializeTemporaryExpr *
CreateMaterializeTemporaryExpr(QualType T,Expr * Temporary,bool BoundToLvalueReference)79337330f729Sjoerg Sema::CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
79347330f729Sjoerg bool BoundToLvalueReference) {
79357330f729Sjoerg auto MTE = new (Context)
79367330f729Sjoerg MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference);
79377330f729Sjoerg
79387330f729Sjoerg // Order an ExprWithCleanups for lifetime marks.
79397330f729Sjoerg //
79407330f729Sjoerg // TODO: It'll be good to have a single place to check the access of the
79417330f729Sjoerg // destructor and generate ExprWithCleanups for various uses. Currently these
79427330f729Sjoerg // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary,
79437330f729Sjoerg // but there may be a chance to merge them.
79447330f729Sjoerg Cleanup.setExprNeedsCleanups(false);
79457330f729Sjoerg return MTE;
79467330f729Sjoerg }
79477330f729Sjoerg
TemporaryMaterializationConversion(Expr * E)79487330f729Sjoerg ExprResult Sema::TemporaryMaterializationConversion(Expr *E) {
79497330f729Sjoerg // In C++98, we don't want to implicitly create an xvalue.
79507330f729Sjoerg // FIXME: This means that AST consumers need to deal with "prvalues" that
79517330f729Sjoerg // denote materialized temporaries. Maybe we should add another ValueKind
79527330f729Sjoerg // for "xvalue pretending to be a prvalue" for C++98 support.
79537330f729Sjoerg if (!E->isRValue() || !getLangOpts().CPlusPlus11)
79547330f729Sjoerg return E;
79557330f729Sjoerg
79567330f729Sjoerg // C++1z [conv.rval]/1: T shall be a complete type.
79577330f729Sjoerg // FIXME: Does this ever matter (can we form a prvalue of incomplete type)?
79587330f729Sjoerg // If so, we should check for a non-abstract class type here too.
79597330f729Sjoerg QualType T = E->getType();
79607330f729Sjoerg if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type))
79617330f729Sjoerg return ExprError();
79627330f729Sjoerg
79637330f729Sjoerg return CreateMaterializeTemporaryExpr(E->getType(), E, false);
79647330f729Sjoerg }
79657330f729Sjoerg
PerformQualificationConversion(Expr * E,QualType Ty,ExprValueKind VK,CheckedConversionKind CCK)79667330f729Sjoerg ExprResult Sema::PerformQualificationConversion(Expr *E, QualType Ty,
79677330f729Sjoerg ExprValueKind VK,
79687330f729Sjoerg CheckedConversionKind CCK) {
79697330f729Sjoerg
79707330f729Sjoerg CastKind CK = CK_NoOp;
79717330f729Sjoerg
79727330f729Sjoerg if (VK == VK_RValue) {
79737330f729Sjoerg auto PointeeTy = Ty->getPointeeType();
79747330f729Sjoerg auto ExprPointeeTy = E->getType()->getPointeeType();
79757330f729Sjoerg if (!PointeeTy.isNull() &&
79767330f729Sjoerg PointeeTy.getAddressSpace() != ExprPointeeTy.getAddressSpace())
79777330f729Sjoerg CK = CK_AddressSpaceConversion;
79787330f729Sjoerg } else if (Ty.getAddressSpace() != E->getType().getAddressSpace()) {
79797330f729Sjoerg CK = CK_AddressSpaceConversion;
79807330f729Sjoerg }
79817330f729Sjoerg
79827330f729Sjoerg return ImpCastExprToType(E, Ty, CK, VK, /*BasePath=*/nullptr, CCK);
79837330f729Sjoerg }
79847330f729Sjoerg
Perform(Sema & S,const InitializedEntity & Entity,const InitializationKind & Kind,MultiExprArg Args,QualType * ResultType)79857330f729Sjoerg ExprResult InitializationSequence::Perform(Sema &S,
79867330f729Sjoerg const InitializedEntity &Entity,
79877330f729Sjoerg const InitializationKind &Kind,
79887330f729Sjoerg MultiExprArg Args,
79897330f729Sjoerg QualType *ResultType) {
79907330f729Sjoerg if (Failed()) {
79917330f729Sjoerg Diagnose(S, Entity, Kind, Args);
79927330f729Sjoerg return ExprError();
79937330f729Sjoerg }
79947330f729Sjoerg if (!ZeroInitializationFixit.empty()) {
79957330f729Sjoerg unsigned DiagID = diag::err_default_init_const;
79967330f729Sjoerg if (Decl *D = Entity.getDecl())
79977330f729Sjoerg if (S.getLangOpts().MSVCCompat && D->hasAttr<SelectAnyAttr>())
79987330f729Sjoerg DiagID = diag::ext_default_init_const;
79997330f729Sjoerg
80007330f729Sjoerg // The initialization would have succeeded with this fixit. Since the fixit
80017330f729Sjoerg // is on the error, we need to build a valid AST in this case, so this isn't
80027330f729Sjoerg // handled in the Failed() branch above.
80037330f729Sjoerg QualType DestType = Entity.getType();
80047330f729Sjoerg S.Diag(Kind.getLocation(), DiagID)
80057330f729Sjoerg << DestType << (bool)DestType->getAs<RecordType>()
80067330f729Sjoerg << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
80077330f729Sjoerg ZeroInitializationFixit);
80087330f729Sjoerg }
80097330f729Sjoerg
80107330f729Sjoerg if (getKind() == DependentSequence) {
80117330f729Sjoerg // If the declaration is a non-dependent, incomplete array type
80127330f729Sjoerg // that has an initializer, then its type will be completed once
80137330f729Sjoerg // the initializer is instantiated.
80147330f729Sjoerg if (ResultType && !Entity.getType()->isDependentType() &&
80157330f729Sjoerg Args.size() == 1) {
80167330f729Sjoerg QualType DeclType = Entity.getType();
80177330f729Sjoerg if (const IncompleteArrayType *ArrayT
80187330f729Sjoerg = S.Context.getAsIncompleteArrayType(DeclType)) {
80197330f729Sjoerg // FIXME: We don't currently have the ability to accurately
80207330f729Sjoerg // compute the length of an initializer list without
80217330f729Sjoerg // performing full type-checking of the initializer list
80227330f729Sjoerg // (since we have to determine where braces are implicitly
80237330f729Sjoerg // introduced and such). So, we fall back to making the array
80247330f729Sjoerg // type a dependently-sized array type with no specified
80257330f729Sjoerg // bound.
80267330f729Sjoerg if (isa<InitListExpr>((Expr *)Args[0])) {
80277330f729Sjoerg SourceRange Brackets;
80287330f729Sjoerg
80297330f729Sjoerg // Scavange the location of the brackets from the entity, if we can.
80307330f729Sjoerg if (auto *DD = dyn_cast_or_null<DeclaratorDecl>(Entity.getDecl())) {
80317330f729Sjoerg if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
80327330f729Sjoerg TypeLoc TL = TInfo->getTypeLoc();
80337330f729Sjoerg if (IncompleteArrayTypeLoc ArrayLoc =
80347330f729Sjoerg TL.getAs<IncompleteArrayTypeLoc>())
80357330f729Sjoerg Brackets = ArrayLoc.getBracketsRange();
80367330f729Sjoerg }
80377330f729Sjoerg }
80387330f729Sjoerg
80397330f729Sjoerg *ResultType
80407330f729Sjoerg = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
80417330f729Sjoerg /*NumElts=*/nullptr,
80427330f729Sjoerg ArrayT->getSizeModifier(),
80437330f729Sjoerg ArrayT->getIndexTypeCVRQualifiers(),
80447330f729Sjoerg Brackets);
80457330f729Sjoerg }
80467330f729Sjoerg
80477330f729Sjoerg }
80487330f729Sjoerg }
80497330f729Sjoerg if (Kind.getKind() == InitializationKind::IK_Direct &&
80507330f729Sjoerg !Kind.isExplicitCast()) {
80517330f729Sjoerg // Rebuild the ParenListExpr.
80527330f729Sjoerg SourceRange ParenRange = Kind.getParenOrBraceRange();
80537330f729Sjoerg return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
80547330f729Sjoerg Args);
80557330f729Sjoerg }
80567330f729Sjoerg assert(Kind.getKind() == InitializationKind::IK_Copy ||
80577330f729Sjoerg Kind.isExplicitCast() ||
80587330f729Sjoerg Kind.getKind() == InitializationKind::IK_DirectList);
80597330f729Sjoerg return ExprResult(Args[0]);
80607330f729Sjoerg }
80617330f729Sjoerg
80627330f729Sjoerg // No steps means no initialization.
80637330f729Sjoerg if (Steps.empty())
80647330f729Sjoerg return ExprResult((Expr *)nullptr);
80657330f729Sjoerg
80667330f729Sjoerg if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
80677330f729Sjoerg Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
8068*e038c9c4Sjoerg !Entity.isParamOrTemplateParamKind()) {
80697330f729Sjoerg // Produce a C++98 compatibility warning if we are initializing a reference
80707330f729Sjoerg // from an initializer list. For parameters, we produce a better warning
80717330f729Sjoerg // elsewhere.
80727330f729Sjoerg Expr *Init = Args[0];
80737330f729Sjoerg S.Diag(Init->getBeginLoc(), diag::warn_cxx98_compat_reference_list_init)
80747330f729Sjoerg << Init->getSourceRange();
80757330f729Sjoerg }
80767330f729Sjoerg
80777330f729Sjoerg // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope
80787330f729Sjoerg QualType ETy = Entity.getType();
8079*e038c9c4Sjoerg bool HasGlobalAS = ETy.hasAddressSpace() &&
8080*e038c9c4Sjoerg ETy.getAddressSpace() == LangAS::opencl_global;
80817330f729Sjoerg
80827330f729Sjoerg if (S.getLangOpts().OpenCLVersion >= 200 &&
80837330f729Sjoerg ETy->isAtomicType() && !HasGlobalAS &&
80847330f729Sjoerg Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) {
80857330f729Sjoerg S.Diag(Args[0]->getBeginLoc(), diag::err_opencl_atomic_init)
80867330f729Sjoerg << 1
80877330f729Sjoerg << SourceRange(Entity.getDecl()->getBeginLoc(), Args[0]->getEndLoc());
80887330f729Sjoerg return ExprError();
80897330f729Sjoerg }
80907330f729Sjoerg
80917330f729Sjoerg QualType DestType = Entity.getType().getNonReferenceType();
80927330f729Sjoerg // FIXME: Ugly hack around the fact that Entity.getType() is not
80937330f729Sjoerg // the same as Entity.getDecl()->getType() in cases involving type merging,
80947330f729Sjoerg // and we want latter when it makes sense.
80957330f729Sjoerg if (ResultType)
80967330f729Sjoerg *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
80977330f729Sjoerg Entity.getType();
80987330f729Sjoerg
80997330f729Sjoerg ExprResult CurInit((Expr *)nullptr);
81007330f729Sjoerg SmallVector<Expr*, 4> ArrayLoopCommonExprs;
81017330f729Sjoerg
81027330f729Sjoerg // For initialization steps that start with a single initializer,
81037330f729Sjoerg // grab the only argument out the Args and place it into the "current"
81047330f729Sjoerg // initializer.
81057330f729Sjoerg switch (Steps.front().Kind) {
81067330f729Sjoerg case SK_ResolveAddressOfOverloadedFunction:
81077330f729Sjoerg case SK_CastDerivedToBaseRValue:
81087330f729Sjoerg case SK_CastDerivedToBaseXValue:
81097330f729Sjoerg case SK_CastDerivedToBaseLValue:
81107330f729Sjoerg case SK_BindReference:
81117330f729Sjoerg case SK_BindReferenceToTemporary:
81127330f729Sjoerg case SK_FinalCopy:
81137330f729Sjoerg case SK_ExtraneousCopyToTemporary:
81147330f729Sjoerg case SK_UserConversion:
81157330f729Sjoerg case SK_QualificationConversionLValue:
81167330f729Sjoerg case SK_QualificationConversionXValue:
81177330f729Sjoerg case SK_QualificationConversionRValue:
8118*e038c9c4Sjoerg case SK_FunctionReferenceConversion:
81197330f729Sjoerg case SK_AtomicConversion:
81207330f729Sjoerg case SK_ConversionSequence:
81217330f729Sjoerg case SK_ConversionSequenceNoNarrowing:
81227330f729Sjoerg case SK_ListInitialization:
81237330f729Sjoerg case SK_UnwrapInitList:
81247330f729Sjoerg case SK_RewrapInitList:
81257330f729Sjoerg case SK_CAssignment:
81267330f729Sjoerg case SK_StringInit:
81277330f729Sjoerg case SK_ObjCObjectConversion:
81287330f729Sjoerg case SK_ArrayLoopIndex:
81297330f729Sjoerg case SK_ArrayLoopInit:
81307330f729Sjoerg case SK_ArrayInit:
81317330f729Sjoerg case SK_GNUArrayInit:
81327330f729Sjoerg case SK_ParenthesizedArrayInit:
81337330f729Sjoerg case SK_PassByIndirectCopyRestore:
81347330f729Sjoerg case SK_PassByIndirectRestore:
81357330f729Sjoerg case SK_ProduceObjCObject:
81367330f729Sjoerg case SK_StdInitializerList:
81377330f729Sjoerg case SK_OCLSamplerInit:
81387330f729Sjoerg case SK_OCLZeroOpaqueType: {
81397330f729Sjoerg assert(Args.size() == 1);
81407330f729Sjoerg CurInit = Args[0];
81417330f729Sjoerg if (!CurInit.get()) return ExprError();
81427330f729Sjoerg break;
81437330f729Sjoerg }
81447330f729Sjoerg
81457330f729Sjoerg case SK_ConstructorInitialization:
81467330f729Sjoerg case SK_ConstructorInitializationFromList:
81477330f729Sjoerg case SK_StdInitializerListConstructorCall:
81487330f729Sjoerg case SK_ZeroInitialization:
81497330f729Sjoerg break;
81507330f729Sjoerg }
81517330f729Sjoerg
81527330f729Sjoerg // Promote from an unevaluated context to an unevaluated list context in
81537330f729Sjoerg // C++11 list-initialization; we need to instantiate entities usable in
81547330f729Sjoerg // constant expressions here in order to perform narrowing checks =(
81557330f729Sjoerg EnterExpressionEvaluationContext Evaluated(
81567330f729Sjoerg S, EnterExpressionEvaluationContext::InitList,
81577330f729Sjoerg CurInit.get() && isa<InitListExpr>(CurInit.get()));
81587330f729Sjoerg
81597330f729Sjoerg // C++ [class.abstract]p2:
81607330f729Sjoerg // no objects of an abstract class can be created except as subobjects
81617330f729Sjoerg // of a class derived from it
81627330f729Sjoerg auto checkAbstractType = [&](QualType T) -> bool {
81637330f729Sjoerg if (Entity.getKind() == InitializedEntity::EK_Base ||
81647330f729Sjoerg Entity.getKind() == InitializedEntity::EK_Delegating)
81657330f729Sjoerg return false;
81667330f729Sjoerg return S.RequireNonAbstractType(Kind.getLocation(), T,
81677330f729Sjoerg diag::err_allocation_of_abstract_type);
81687330f729Sjoerg };
81697330f729Sjoerg
81707330f729Sjoerg // Walk through the computed steps for the initialization sequence,
81717330f729Sjoerg // performing the specified conversions along the way.
81727330f729Sjoerg bool ConstructorInitRequiresZeroInit = false;
81737330f729Sjoerg for (step_iterator Step = step_begin(), StepEnd = step_end();
81747330f729Sjoerg Step != StepEnd; ++Step) {
81757330f729Sjoerg if (CurInit.isInvalid())
81767330f729Sjoerg return ExprError();
81777330f729Sjoerg
81787330f729Sjoerg QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
81797330f729Sjoerg
81807330f729Sjoerg switch (Step->Kind) {
81817330f729Sjoerg case SK_ResolveAddressOfOverloadedFunction:
81827330f729Sjoerg // Overload resolution determined which function invoke; update the
81837330f729Sjoerg // initializer to reflect that choice.
81847330f729Sjoerg S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
81857330f729Sjoerg if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
81867330f729Sjoerg return ExprError();
81877330f729Sjoerg CurInit = S.FixOverloadedFunctionReference(CurInit,
81887330f729Sjoerg Step->Function.FoundDecl,
81897330f729Sjoerg Step->Function.Function);
81907330f729Sjoerg break;
81917330f729Sjoerg
81927330f729Sjoerg case SK_CastDerivedToBaseRValue:
81937330f729Sjoerg case SK_CastDerivedToBaseXValue:
81947330f729Sjoerg case SK_CastDerivedToBaseLValue: {
81957330f729Sjoerg // We have a derived-to-base cast that produces either an rvalue or an
81967330f729Sjoerg // lvalue. Perform that cast.
81977330f729Sjoerg
81987330f729Sjoerg CXXCastPath BasePath;
81997330f729Sjoerg
82007330f729Sjoerg // Casts to inaccessible base classes are allowed with C-style casts.
82017330f729Sjoerg bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
82027330f729Sjoerg if (S.CheckDerivedToBaseConversion(
82037330f729Sjoerg SourceType, Step->Type, CurInit.get()->getBeginLoc(),
82047330f729Sjoerg CurInit.get()->getSourceRange(), &BasePath, IgnoreBaseAccess))
82057330f729Sjoerg return ExprError();
82067330f729Sjoerg
82077330f729Sjoerg ExprValueKind VK =
82087330f729Sjoerg Step->Kind == SK_CastDerivedToBaseLValue ?
82097330f729Sjoerg VK_LValue :
82107330f729Sjoerg (Step->Kind == SK_CastDerivedToBaseXValue ?
82117330f729Sjoerg VK_XValue :
82127330f729Sjoerg VK_RValue);
8213*e038c9c4Sjoerg CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
8214*e038c9c4Sjoerg CK_DerivedToBase, CurInit.get(),
8215*e038c9c4Sjoerg &BasePath, VK, FPOptionsOverride());
82167330f729Sjoerg break;
82177330f729Sjoerg }
82187330f729Sjoerg
82197330f729Sjoerg case SK_BindReference:
82207330f729Sjoerg // Reference binding does not have any corresponding ASTs.
82217330f729Sjoerg
82227330f729Sjoerg // Check exception specifications
82237330f729Sjoerg if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
82247330f729Sjoerg return ExprError();
82257330f729Sjoerg
82267330f729Sjoerg // We don't check for e.g. function pointers here, since address
82277330f729Sjoerg // availability checks should only occur when the function first decays
82287330f729Sjoerg // into a pointer or reference.
82297330f729Sjoerg if (CurInit.get()->getType()->isFunctionProtoType()) {
82307330f729Sjoerg if (auto *DRE = dyn_cast<DeclRefExpr>(CurInit.get()->IgnoreParens())) {
82317330f729Sjoerg if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
82327330f729Sjoerg if (!S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
82337330f729Sjoerg DRE->getBeginLoc()))
82347330f729Sjoerg return ExprError();
82357330f729Sjoerg }
82367330f729Sjoerg }
82377330f729Sjoerg }
82387330f729Sjoerg
82397330f729Sjoerg CheckForNullPointerDereference(S, CurInit.get());
82407330f729Sjoerg break;
82417330f729Sjoerg
82427330f729Sjoerg case SK_BindReferenceToTemporary: {
82437330f729Sjoerg // Make sure the "temporary" is actually an rvalue.
82447330f729Sjoerg assert(CurInit.get()->isRValue() && "not a temporary");
82457330f729Sjoerg
82467330f729Sjoerg // Check exception specifications
82477330f729Sjoerg if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
82487330f729Sjoerg return ExprError();
82497330f729Sjoerg
8250*e038c9c4Sjoerg QualType MTETy = Step->Type;
8251*e038c9c4Sjoerg
8252*e038c9c4Sjoerg // When this is an incomplete array type (such as when this is
8253*e038c9c4Sjoerg // initializing an array of unknown bounds from an init list), use THAT
8254*e038c9c4Sjoerg // type instead so that we propogate the array bounds.
8255*e038c9c4Sjoerg if (MTETy->isIncompleteArrayType() &&
8256*e038c9c4Sjoerg !CurInit.get()->getType()->isIncompleteArrayType() &&
8257*e038c9c4Sjoerg S.Context.hasSameType(
8258*e038c9c4Sjoerg MTETy->getPointeeOrArrayElementType(),
8259*e038c9c4Sjoerg CurInit.get()->getType()->getPointeeOrArrayElementType()))
8260*e038c9c4Sjoerg MTETy = CurInit.get()->getType();
8261*e038c9c4Sjoerg
82627330f729Sjoerg // Materialize the temporary into memory.
82637330f729Sjoerg MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
8264*e038c9c4Sjoerg MTETy, CurInit.get(), Entity.getType()->isLValueReferenceType());
82657330f729Sjoerg CurInit = MTE;
82667330f729Sjoerg
82677330f729Sjoerg // If we're extending this temporary to automatic storage duration -- we
82687330f729Sjoerg // need to register its cleanup during the full-expression's cleanups.
82697330f729Sjoerg if (MTE->getStorageDuration() == SD_Automatic &&
82707330f729Sjoerg MTE->getType().isDestructedType())
82717330f729Sjoerg S.Cleanup.setExprNeedsCleanups(true);
82727330f729Sjoerg break;
82737330f729Sjoerg }
82747330f729Sjoerg
82757330f729Sjoerg case SK_FinalCopy:
82767330f729Sjoerg if (checkAbstractType(Step->Type))
82777330f729Sjoerg return ExprError();
82787330f729Sjoerg
82797330f729Sjoerg // If the overall initialization is initializing a temporary, we already
82807330f729Sjoerg // bound our argument if it was necessary to do so. If not (if we're
82817330f729Sjoerg // ultimately initializing a non-temporary), our argument needs to be
82827330f729Sjoerg // bound since it's initializing a function parameter.
82837330f729Sjoerg // FIXME: This is a mess. Rationalize temporary destruction.
82847330f729Sjoerg if (!shouldBindAsTemporary(Entity))
82857330f729Sjoerg CurInit = S.MaybeBindToTemporary(CurInit.get());
82867330f729Sjoerg CurInit = CopyObject(S, Step->Type, Entity, CurInit,
82877330f729Sjoerg /*IsExtraneousCopy=*/false);
82887330f729Sjoerg break;
82897330f729Sjoerg
82907330f729Sjoerg case SK_ExtraneousCopyToTemporary:
82917330f729Sjoerg CurInit = CopyObject(S, Step->Type, Entity, CurInit,
82927330f729Sjoerg /*IsExtraneousCopy=*/true);
82937330f729Sjoerg break;
82947330f729Sjoerg
82957330f729Sjoerg case SK_UserConversion: {
82967330f729Sjoerg // We have a user-defined conversion that invokes either a constructor
82977330f729Sjoerg // or a conversion function.
82987330f729Sjoerg CastKind CastKind;
82997330f729Sjoerg FunctionDecl *Fn = Step->Function.Function;
83007330f729Sjoerg DeclAccessPair FoundFn = Step->Function.FoundDecl;
83017330f729Sjoerg bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
83027330f729Sjoerg bool CreatedObject = false;
83037330f729Sjoerg if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
83047330f729Sjoerg // Build a call to the selected constructor.
83057330f729Sjoerg SmallVector<Expr*, 8> ConstructorArgs;
83067330f729Sjoerg SourceLocation Loc = CurInit.get()->getBeginLoc();
83077330f729Sjoerg
83087330f729Sjoerg // Determine the arguments required to actually perform the constructor
83097330f729Sjoerg // call.
83107330f729Sjoerg Expr *Arg = CurInit.get();
8311*e038c9c4Sjoerg if (S.CompleteConstructorCall(Constructor, Step->Type,
8312*e038c9c4Sjoerg MultiExprArg(&Arg, 1), Loc,
8313*e038c9c4Sjoerg ConstructorArgs))
83147330f729Sjoerg return ExprError();
83157330f729Sjoerg
83167330f729Sjoerg // Build an expression that constructs a temporary.
83177330f729Sjoerg CurInit = S.BuildCXXConstructExpr(Loc, Step->Type,
83187330f729Sjoerg FoundFn, Constructor,
83197330f729Sjoerg ConstructorArgs,
83207330f729Sjoerg HadMultipleCandidates,
83217330f729Sjoerg /*ListInit*/ false,
83227330f729Sjoerg /*StdInitListInit*/ false,
83237330f729Sjoerg /*ZeroInit*/ false,
83247330f729Sjoerg CXXConstructExpr::CK_Complete,
83257330f729Sjoerg SourceRange());
83267330f729Sjoerg if (CurInit.isInvalid())
83277330f729Sjoerg return ExprError();
83287330f729Sjoerg
83297330f729Sjoerg S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn,
83307330f729Sjoerg Entity);
83317330f729Sjoerg if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
83327330f729Sjoerg return ExprError();
83337330f729Sjoerg
83347330f729Sjoerg CastKind = CK_ConstructorConversion;
83357330f729Sjoerg CreatedObject = true;
83367330f729Sjoerg } else {
83377330f729Sjoerg // Build a call to the conversion function.
83387330f729Sjoerg CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
83397330f729Sjoerg S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
83407330f729Sjoerg FoundFn);
83417330f729Sjoerg if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
83427330f729Sjoerg return ExprError();
83437330f729Sjoerg
83447330f729Sjoerg CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
83457330f729Sjoerg HadMultipleCandidates);
83467330f729Sjoerg if (CurInit.isInvalid())
83477330f729Sjoerg return ExprError();
83487330f729Sjoerg
83497330f729Sjoerg CastKind = CK_UserDefinedConversion;
83507330f729Sjoerg CreatedObject = Conversion->getReturnType()->isRecordType();
83517330f729Sjoerg }
83527330f729Sjoerg
83537330f729Sjoerg if (CreatedObject && checkAbstractType(CurInit.get()->getType()))
83547330f729Sjoerg return ExprError();
83557330f729Sjoerg
8356*e038c9c4Sjoerg CurInit = ImplicitCastExpr::Create(
8357*e038c9c4Sjoerg S.Context, CurInit.get()->getType(), CastKind, CurInit.get(), nullptr,
8358*e038c9c4Sjoerg CurInit.get()->getValueKind(), S.CurFPFeatureOverrides());
83597330f729Sjoerg
83607330f729Sjoerg if (shouldBindAsTemporary(Entity))
83617330f729Sjoerg // The overall entity is temporary, so this expression should be
83627330f729Sjoerg // destroyed at the end of its full-expression.
83637330f729Sjoerg CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
83647330f729Sjoerg else if (CreatedObject && shouldDestroyEntity(Entity)) {
83657330f729Sjoerg // The object outlasts the full-expression, but we need to prepare for
83667330f729Sjoerg // a destructor being run on it.
83677330f729Sjoerg // FIXME: It makes no sense to do this here. This should happen
83687330f729Sjoerg // regardless of how we initialized the entity.
83697330f729Sjoerg QualType T = CurInit.get()->getType();
83707330f729Sjoerg if (const RecordType *Record = T->getAs<RecordType>()) {
83717330f729Sjoerg CXXDestructorDecl *Destructor
83727330f729Sjoerg = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
83737330f729Sjoerg S.CheckDestructorAccess(CurInit.get()->getBeginLoc(), Destructor,
83747330f729Sjoerg S.PDiag(diag::err_access_dtor_temp) << T);
83757330f729Sjoerg S.MarkFunctionReferenced(CurInit.get()->getBeginLoc(), Destructor);
83767330f729Sjoerg if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getBeginLoc()))
83777330f729Sjoerg return ExprError();
83787330f729Sjoerg }
83797330f729Sjoerg }
83807330f729Sjoerg break;
83817330f729Sjoerg }
83827330f729Sjoerg
83837330f729Sjoerg case SK_QualificationConversionLValue:
83847330f729Sjoerg case SK_QualificationConversionXValue:
83857330f729Sjoerg case SK_QualificationConversionRValue: {
83867330f729Sjoerg // Perform a qualification conversion; these can never go wrong.
83877330f729Sjoerg ExprValueKind VK =
83887330f729Sjoerg Step->Kind == SK_QualificationConversionLValue
83897330f729Sjoerg ? VK_LValue
83907330f729Sjoerg : (Step->Kind == SK_QualificationConversionXValue ? VK_XValue
83917330f729Sjoerg : VK_RValue);
83927330f729Sjoerg CurInit = S.PerformQualificationConversion(CurInit.get(), Step->Type, VK);
83937330f729Sjoerg break;
83947330f729Sjoerg }
83957330f729Sjoerg
8396*e038c9c4Sjoerg case SK_FunctionReferenceConversion:
8397*e038c9c4Sjoerg assert(CurInit.get()->isLValue() &&
8398*e038c9c4Sjoerg "function reference should be lvalue");
8399*e038c9c4Sjoerg CurInit =
8400*e038c9c4Sjoerg S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK_LValue);
8401*e038c9c4Sjoerg break;
8402*e038c9c4Sjoerg
84037330f729Sjoerg case SK_AtomicConversion: {
84047330f729Sjoerg assert(CurInit.get()->isRValue() && "cannot convert glvalue to atomic");
84057330f729Sjoerg CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
84067330f729Sjoerg CK_NonAtomicToAtomic, VK_RValue);
84077330f729Sjoerg break;
84087330f729Sjoerg }
84097330f729Sjoerg
84107330f729Sjoerg case SK_ConversionSequence:
84117330f729Sjoerg case SK_ConversionSequenceNoNarrowing: {
84127330f729Sjoerg if (const auto *FromPtrType =
84137330f729Sjoerg CurInit.get()->getType()->getAs<PointerType>()) {
84147330f729Sjoerg if (const auto *ToPtrType = Step->Type->getAs<PointerType>()) {
84157330f729Sjoerg if (FromPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
84167330f729Sjoerg !ToPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
8417*e038c9c4Sjoerg // Do not check static casts here because they are checked earlier
8418*e038c9c4Sjoerg // in Sema::ActOnCXXNamedCast()
8419*e038c9c4Sjoerg if (!Kind.isStaticCast()) {
84207330f729Sjoerg S.Diag(CurInit.get()->getExprLoc(),
84217330f729Sjoerg diag::warn_noderef_to_dereferenceable_pointer)
84227330f729Sjoerg << CurInit.get()->getSourceRange();
84237330f729Sjoerg }
84247330f729Sjoerg }
84257330f729Sjoerg }
8426*e038c9c4Sjoerg }
84277330f729Sjoerg
84287330f729Sjoerg Sema::CheckedConversionKind CCK
84297330f729Sjoerg = Kind.isCStyleCast()? Sema::CCK_CStyleCast
84307330f729Sjoerg : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
84317330f729Sjoerg : Kind.isExplicitCast()? Sema::CCK_OtherCast
84327330f729Sjoerg : Sema::CCK_ImplicitConversion;
84337330f729Sjoerg ExprResult CurInitExprRes =
84347330f729Sjoerg S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
84357330f729Sjoerg getAssignmentAction(Entity), CCK);
84367330f729Sjoerg if (CurInitExprRes.isInvalid())
84377330f729Sjoerg return ExprError();
84387330f729Sjoerg
84397330f729Sjoerg S.DiscardMisalignedMemberAddress(Step->Type.getTypePtr(), CurInit.get());
84407330f729Sjoerg
84417330f729Sjoerg CurInit = CurInitExprRes;
84427330f729Sjoerg
84437330f729Sjoerg if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
84447330f729Sjoerg S.getLangOpts().CPlusPlus)
84457330f729Sjoerg DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
84467330f729Sjoerg CurInit.get());
84477330f729Sjoerg
84487330f729Sjoerg break;
84497330f729Sjoerg }
84507330f729Sjoerg
84517330f729Sjoerg case SK_ListInitialization: {
84527330f729Sjoerg if (checkAbstractType(Step->Type))
84537330f729Sjoerg return ExprError();
84547330f729Sjoerg
84557330f729Sjoerg InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
84567330f729Sjoerg // If we're not initializing the top-level entity, we need to create an
84577330f729Sjoerg // InitializeTemporary entity for our target type.
84587330f729Sjoerg QualType Ty = Step->Type;
84597330f729Sjoerg bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
84607330f729Sjoerg InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
84617330f729Sjoerg InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
84627330f729Sjoerg InitListChecker PerformInitList(S, InitEntity,
84637330f729Sjoerg InitList, Ty, /*VerifyOnly=*/false,
84647330f729Sjoerg /*TreatUnavailableAsInvalid=*/false);
84657330f729Sjoerg if (PerformInitList.HadError())
84667330f729Sjoerg return ExprError();
84677330f729Sjoerg
84687330f729Sjoerg // Hack: We must update *ResultType if available in order to set the
84697330f729Sjoerg // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
84707330f729Sjoerg // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
84717330f729Sjoerg if (ResultType &&
84727330f729Sjoerg ResultType->getNonReferenceType()->isIncompleteArrayType()) {
84737330f729Sjoerg if ((*ResultType)->isRValueReferenceType())
84747330f729Sjoerg Ty = S.Context.getRValueReferenceType(Ty);
84757330f729Sjoerg else if ((*ResultType)->isLValueReferenceType())
84767330f729Sjoerg Ty = S.Context.getLValueReferenceType(Ty,
84777330f729Sjoerg (*ResultType)->castAs<LValueReferenceType>()->isSpelledAsLValue());
84787330f729Sjoerg *ResultType = Ty;
84797330f729Sjoerg }
84807330f729Sjoerg
84817330f729Sjoerg InitListExpr *StructuredInitList =
84827330f729Sjoerg PerformInitList.getFullyStructuredList();
84837330f729Sjoerg CurInit.get();
84847330f729Sjoerg CurInit = shouldBindAsTemporary(InitEntity)
84857330f729Sjoerg ? S.MaybeBindToTemporary(StructuredInitList)
84867330f729Sjoerg : StructuredInitList;
84877330f729Sjoerg break;
84887330f729Sjoerg }
84897330f729Sjoerg
84907330f729Sjoerg case SK_ConstructorInitializationFromList: {
84917330f729Sjoerg if (checkAbstractType(Step->Type))
84927330f729Sjoerg return ExprError();
84937330f729Sjoerg
84947330f729Sjoerg // When an initializer list is passed for a parameter of type "reference
84957330f729Sjoerg // to object", we don't get an EK_Temporary entity, but instead an
84967330f729Sjoerg // EK_Parameter entity with reference type.
84977330f729Sjoerg // FIXME: This is a hack. What we really should do is create a user
84987330f729Sjoerg // conversion step for this case, but this makes it considerably more
84997330f729Sjoerg // complicated. For now, this will do.
85007330f729Sjoerg InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
85017330f729Sjoerg Entity.getType().getNonReferenceType());
85027330f729Sjoerg bool UseTemporary = Entity.getType()->isReferenceType();
85037330f729Sjoerg assert(Args.size() == 1 && "expected a single argument for list init");
85047330f729Sjoerg InitListExpr *InitList = cast<InitListExpr>(Args[0]);
85057330f729Sjoerg S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
85067330f729Sjoerg << InitList->getSourceRange();
85077330f729Sjoerg MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
85087330f729Sjoerg CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
85097330f729Sjoerg Entity,
85107330f729Sjoerg Kind, Arg, *Step,
85117330f729Sjoerg ConstructorInitRequiresZeroInit,
85127330f729Sjoerg /*IsListInitialization*/true,
85137330f729Sjoerg /*IsStdInitListInit*/false,
85147330f729Sjoerg InitList->getLBraceLoc(),
85157330f729Sjoerg InitList->getRBraceLoc());
85167330f729Sjoerg break;
85177330f729Sjoerg }
85187330f729Sjoerg
85197330f729Sjoerg case SK_UnwrapInitList:
85207330f729Sjoerg CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
85217330f729Sjoerg break;
85227330f729Sjoerg
85237330f729Sjoerg case SK_RewrapInitList: {
85247330f729Sjoerg Expr *E = CurInit.get();
85257330f729Sjoerg InitListExpr *Syntactic = Step->WrappingSyntacticList;
85267330f729Sjoerg InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
85277330f729Sjoerg Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
85287330f729Sjoerg ILE->setSyntacticForm(Syntactic);
85297330f729Sjoerg ILE->setType(E->getType());
85307330f729Sjoerg ILE->setValueKind(E->getValueKind());
85317330f729Sjoerg CurInit = ILE;
85327330f729Sjoerg break;
85337330f729Sjoerg }
85347330f729Sjoerg
85357330f729Sjoerg case SK_ConstructorInitialization:
85367330f729Sjoerg case SK_StdInitializerListConstructorCall: {
85377330f729Sjoerg if (checkAbstractType(Step->Type))
85387330f729Sjoerg return ExprError();
85397330f729Sjoerg
85407330f729Sjoerg // When an initializer list is passed for a parameter of type "reference
85417330f729Sjoerg // to object", we don't get an EK_Temporary entity, but instead an
85427330f729Sjoerg // EK_Parameter entity with reference type.
85437330f729Sjoerg // FIXME: This is a hack. What we really should do is create a user
85447330f729Sjoerg // conversion step for this case, but this makes it considerably more
85457330f729Sjoerg // complicated. For now, this will do.
85467330f729Sjoerg InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
85477330f729Sjoerg Entity.getType().getNonReferenceType());
85487330f729Sjoerg bool UseTemporary = Entity.getType()->isReferenceType();
85497330f729Sjoerg bool IsStdInitListInit =
85507330f729Sjoerg Step->Kind == SK_StdInitializerListConstructorCall;
85517330f729Sjoerg Expr *Source = CurInit.get();
85527330f729Sjoerg SourceRange Range = Kind.hasParenOrBraceRange()
85537330f729Sjoerg ? Kind.getParenOrBraceRange()
85547330f729Sjoerg : SourceRange();
85557330f729Sjoerg CurInit = PerformConstructorInitialization(
85567330f729Sjoerg S, UseTemporary ? TempEntity : Entity, Kind,
85577330f729Sjoerg Source ? MultiExprArg(Source) : Args, *Step,
85587330f729Sjoerg ConstructorInitRequiresZeroInit,
85597330f729Sjoerg /*IsListInitialization*/ IsStdInitListInit,
85607330f729Sjoerg /*IsStdInitListInitialization*/ IsStdInitListInit,
85617330f729Sjoerg /*LBraceLoc*/ Range.getBegin(),
85627330f729Sjoerg /*RBraceLoc*/ Range.getEnd());
85637330f729Sjoerg break;
85647330f729Sjoerg }
85657330f729Sjoerg
85667330f729Sjoerg case SK_ZeroInitialization: {
85677330f729Sjoerg step_iterator NextStep = Step;
85687330f729Sjoerg ++NextStep;
85697330f729Sjoerg if (NextStep != StepEnd &&
85707330f729Sjoerg (NextStep->Kind == SK_ConstructorInitialization ||
85717330f729Sjoerg NextStep->Kind == SK_ConstructorInitializationFromList)) {
85727330f729Sjoerg // The need for zero-initialization is recorded directly into
85737330f729Sjoerg // the call to the object's constructor within the next step.
85747330f729Sjoerg ConstructorInitRequiresZeroInit = true;
85757330f729Sjoerg } else if (Kind.getKind() == InitializationKind::IK_Value &&
85767330f729Sjoerg S.getLangOpts().CPlusPlus &&
85777330f729Sjoerg !Kind.isImplicitValueInit()) {
85787330f729Sjoerg TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
85797330f729Sjoerg if (!TSInfo)
85807330f729Sjoerg TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
85817330f729Sjoerg Kind.getRange().getBegin());
85827330f729Sjoerg
85837330f729Sjoerg CurInit = new (S.Context) CXXScalarValueInitExpr(
85847330f729Sjoerg Entity.getType().getNonLValueExprType(S.Context), TSInfo,
85857330f729Sjoerg Kind.getRange().getEnd());
85867330f729Sjoerg } else {
85877330f729Sjoerg CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
85887330f729Sjoerg }
85897330f729Sjoerg break;
85907330f729Sjoerg }
85917330f729Sjoerg
85927330f729Sjoerg case SK_CAssignment: {
85937330f729Sjoerg QualType SourceType = CurInit.get()->getType();
85947330f729Sjoerg
85957330f729Sjoerg // Save off the initial CurInit in case we need to emit a diagnostic
85967330f729Sjoerg ExprResult InitialCurInit = CurInit;
85977330f729Sjoerg ExprResult Result = CurInit;
85987330f729Sjoerg Sema::AssignConvertType ConvTy =
85997330f729Sjoerg S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
86007330f729Sjoerg Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
86017330f729Sjoerg if (Result.isInvalid())
86027330f729Sjoerg return ExprError();
86037330f729Sjoerg CurInit = Result;
86047330f729Sjoerg
86057330f729Sjoerg // If this is a call, allow conversion to a transparent union.
86067330f729Sjoerg ExprResult CurInitExprRes = CurInit;
86077330f729Sjoerg if (ConvTy != Sema::Compatible &&
86087330f729Sjoerg Entity.isParameterKind() &&
86097330f729Sjoerg S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
86107330f729Sjoerg == Sema::Compatible)
86117330f729Sjoerg ConvTy = Sema::Compatible;
86127330f729Sjoerg if (CurInitExprRes.isInvalid())
86137330f729Sjoerg return ExprError();
86147330f729Sjoerg CurInit = CurInitExprRes;
86157330f729Sjoerg
86167330f729Sjoerg bool Complained;
86177330f729Sjoerg if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
86187330f729Sjoerg Step->Type, SourceType,
86197330f729Sjoerg InitialCurInit.get(),
86207330f729Sjoerg getAssignmentAction(Entity, true),
86217330f729Sjoerg &Complained)) {
86227330f729Sjoerg PrintInitLocationNote(S, Entity);
86237330f729Sjoerg return ExprError();
86247330f729Sjoerg } else if (Complained)
86257330f729Sjoerg PrintInitLocationNote(S, Entity);
86267330f729Sjoerg break;
86277330f729Sjoerg }
86287330f729Sjoerg
86297330f729Sjoerg case SK_StringInit: {
86307330f729Sjoerg QualType Ty = Step->Type;
8631*e038c9c4Sjoerg bool UpdateType = ResultType && Entity.getType()->isIncompleteArrayType();
8632*e038c9c4Sjoerg CheckStringInit(CurInit.get(), UpdateType ? *ResultType : Ty,
86337330f729Sjoerg S.Context.getAsArrayType(Ty), S);
86347330f729Sjoerg break;
86357330f729Sjoerg }
86367330f729Sjoerg
86377330f729Sjoerg case SK_ObjCObjectConversion:
86387330f729Sjoerg CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
86397330f729Sjoerg CK_ObjCObjectLValueCast,
86407330f729Sjoerg CurInit.get()->getValueKind());
86417330f729Sjoerg break;
86427330f729Sjoerg
86437330f729Sjoerg case SK_ArrayLoopIndex: {
86447330f729Sjoerg Expr *Cur = CurInit.get();
86457330f729Sjoerg Expr *BaseExpr = new (S.Context)
86467330f729Sjoerg OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(),
86477330f729Sjoerg Cur->getValueKind(), Cur->getObjectKind(), Cur);
86487330f729Sjoerg Expr *IndexExpr =
86497330f729Sjoerg new (S.Context) ArrayInitIndexExpr(S.Context.getSizeType());
86507330f729Sjoerg CurInit = S.CreateBuiltinArraySubscriptExpr(
86517330f729Sjoerg BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation());
86527330f729Sjoerg ArrayLoopCommonExprs.push_back(BaseExpr);
86537330f729Sjoerg break;
86547330f729Sjoerg }
86557330f729Sjoerg
86567330f729Sjoerg case SK_ArrayLoopInit: {
86577330f729Sjoerg assert(!ArrayLoopCommonExprs.empty() &&
86587330f729Sjoerg "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit");
86597330f729Sjoerg Expr *Common = ArrayLoopCommonExprs.pop_back_val();
86607330f729Sjoerg CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common,
86617330f729Sjoerg CurInit.get());
86627330f729Sjoerg break;
86637330f729Sjoerg }
86647330f729Sjoerg
86657330f729Sjoerg case SK_GNUArrayInit:
86667330f729Sjoerg // Okay: we checked everything before creating this step. Note that
86677330f729Sjoerg // this is a GNU extension.
86687330f729Sjoerg S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
86697330f729Sjoerg << Step->Type << CurInit.get()->getType()
86707330f729Sjoerg << CurInit.get()->getSourceRange();
86717330f729Sjoerg updateGNUCompoundLiteralRValue(CurInit.get());
86727330f729Sjoerg LLVM_FALLTHROUGH;
86737330f729Sjoerg case SK_ArrayInit:
86747330f729Sjoerg // If the destination type is an incomplete array type, update the
86757330f729Sjoerg // type accordingly.
86767330f729Sjoerg if (ResultType) {
86777330f729Sjoerg if (const IncompleteArrayType *IncompleteDest
86787330f729Sjoerg = S.Context.getAsIncompleteArrayType(Step->Type)) {
86797330f729Sjoerg if (const ConstantArrayType *ConstantSource
86807330f729Sjoerg = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
86817330f729Sjoerg *ResultType = S.Context.getConstantArrayType(
86827330f729Sjoerg IncompleteDest->getElementType(),
86837330f729Sjoerg ConstantSource->getSize(),
86847330f729Sjoerg ConstantSource->getSizeExpr(),
86857330f729Sjoerg ArrayType::Normal, 0);
86867330f729Sjoerg }
86877330f729Sjoerg }
86887330f729Sjoerg }
86897330f729Sjoerg break;
86907330f729Sjoerg
86917330f729Sjoerg case SK_ParenthesizedArrayInit:
86927330f729Sjoerg // Okay: we checked everything before creating this step. Note that
86937330f729Sjoerg // this is a GNU extension.
86947330f729Sjoerg S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
86957330f729Sjoerg << CurInit.get()->getSourceRange();
86967330f729Sjoerg break;
86977330f729Sjoerg
86987330f729Sjoerg case SK_PassByIndirectCopyRestore:
86997330f729Sjoerg case SK_PassByIndirectRestore:
87007330f729Sjoerg checkIndirectCopyRestoreSource(S, CurInit.get());
87017330f729Sjoerg CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
87027330f729Sjoerg CurInit.get(), Step->Type,
87037330f729Sjoerg Step->Kind == SK_PassByIndirectCopyRestore);
87047330f729Sjoerg break;
87057330f729Sjoerg
87067330f729Sjoerg case SK_ProduceObjCObject:
8707*e038c9c4Sjoerg CurInit = ImplicitCastExpr::Create(
8708*e038c9c4Sjoerg S.Context, Step->Type, CK_ARCProduceObject, CurInit.get(), nullptr,
8709*e038c9c4Sjoerg VK_RValue, FPOptionsOverride());
87107330f729Sjoerg break;
87117330f729Sjoerg
87127330f729Sjoerg case SK_StdInitializerList: {
87137330f729Sjoerg S.Diag(CurInit.get()->getExprLoc(),
87147330f729Sjoerg diag::warn_cxx98_compat_initializer_list_init)
87157330f729Sjoerg << CurInit.get()->getSourceRange();
87167330f729Sjoerg
87177330f729Sjoerg // Materialize the temporary into memory.
87187330f729Sjoerg MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
87197330f729Sjoerg CurInit.get()->getType(), CurInit.get(),
87207330f729Sjoerg /*BoundToLvalueReference=*/false);
87217330f729Sjoerg
87227330f729Sjoerg // Wrap it in a construction of a std::initializer_list<T>.
87237330f729Sjoerg CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
87247330f729Sjoerg
87257330f729Sjoerg // Bind the result, in case the library has given initializer_list a
87267330f729Sjoerg // non-trivial destructor.
87277330f729Sjoerg if (shouldBindAsTemporary(Entity))
87287330f729Sjoerg CurInit = S.MaybeBindToTemporary(CurInit.get());
87297330f729Sjoerg break;
87307330f729Sjoerg }
87317330f729Sjoerg
87327330f729Sjoerg case SK_OCLSamplerInit: {
87337330f729Sjoerg // Sampler initialization have 5 cases:
87347330f729Sjoerg // 1. function argument passing
87357330f729Sjoerg // 1a. argument is a file-scope variable
87367330f729Sjoerg // 1b. argument is a function-scope variable
87377330f729Sjoerg // 1c. argument is one of caller function's parameters
87387330f729Sjoerg // 2. variable initialization
87397330f729Sjoerg // 2a. initializing a file-scope variable
87407330f729Sjoerg // 2b. initializing a function-scope variable
87417330f729Sjoerg //
87427330f729Sjoerg // For file-scope variables, since they cannot be initialized by function
87437330f729Sjoerg // call of __translate_sampler_initializer in LLVM IR, their references
87447330f729Sjoerg // need to be replaced by a cast from their literal initializers to
87457330f729Sjoerg // sampler type. Since sampler variables can only be used in function
87467330f729Sjoerg // calls as arguments, we only need to replace them when handling the
87477330f729Sjoerg // argument passing.
87487330f729Sjoerg assert(Step->Type->isSamplerT() &&
87497330f729Sjoerg "Sampler initialization on non-sampler type.");
87507330f729Sjoerg Expr *Init = CurInit.get()->IgnoreParens();
87517330f729Sjoerg QualType SourceType = Init->getType();
87527330f729Sjoerg // Case 1
87537330f729Sjoerg if (Entity.isParameterKind()) {
87547330f729Sjoerg if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) {
87557330f729Sjoerg S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
87567330f729Sjoerg << SourceType;
87577330f729Sjoerg break;
87587330f729Sjoerg } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init)) {
87597330f729Sjoerg auto Var = cast<VarDecl>(DRE->getDecl());
87607330f729Sjoerg // Case 1b and 1c
87617330f729Sjoerg // No cast from integer to sampler is needed.
87627330f729Sjoerg if (!Var->hasGlobalStorage()) {
8763*e038c9c4Sjoerg CurInit = ImplicitCastExpr::Create(
8764*e038c9c4Sjoerg S.Context, Step->Type, CK_LValueToRValue, Init,
8765*e038c9c4Sjoerg /*BasePath=*/nullptr, VK_RValue, FPOptionsOverride());
87667330f729Sjoerg break;
87677330f729Sjoerg }
87687330f729Sjoerg // Case 1a
87697330f729Sjoerg // For function call with a file-scope sampler variable as argument,
87707330f729Sjoerg // get the integer literal.
87717330f729Sjoerg // Do not diagnose if the file-scope variable does not have initializer
87727330f729Sjoerg // since this has already been diagnosed when parsing the variable
87737330f729Sjoerg // declaration.
87747330f729Sjoerg if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit()))
87757330f729Sjoerg break;
87767330f729Sjoerg Init = cast<ImplicitCastExpr>(const_cast<Expr*>(
87777330f729Sjoerg Var->getInit()))->getSubExpr();
87787330f729Sjoerg SourceType = Init->getType();
87797330f729Sjoerg }
87807330f729Sjoerg } else {
87817330f729Sjoerg // Case 2
87827330f729Sjoerg // Check initializer is 32 bit integer constant.
87837330f729Sjoerg // If the initializer is taken from global variable, do not diagnose since
87847330f729Sjoerg // this has already been done when parsing the variable declaration.
87857330f729Sjoerg if (!Init->isConstantInitializer(S.Context, false))
87867330f729Sjoerg break;
87877330f729Sjoerg
87887330f729Sjoerg if (!SourceType->isIntegerType() ||
87897330f729Sjoerg 32 != S.Context.getIntWidth(SourceType)) {
87907330f729Sjoerg S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer)
87917330f729Sjoerg << SourceType;
87927330f729Sjoerg break;
87937330f729Sjoerg }
87947330f729Sjoerg
87957330f729Sjoerg Expr::EvalResult EVResult;
87967330f729Sjoerg Init->EvaluateAsInt(EVResult, S.Context);
87977330f729Sjoerg llvm::APSInt Result = EVResult.Val.getInt();
87987330f729Sjoerg const uint64_t SamplerValue = Result.getLimitedValue();
87997330f729Sjoerg // 32-bit value of sampler's initializer is interpreted as
88007330f729Sjoerg // bit-field with the following structure:
88017330f729Sjoerg // |unspecified|Filter|Addressing Mode| Normalized Coords|
88027330f729Sjoerg // |31 6|5 4|3 1| 0|
88037330f729Sjoerg // This structure corresponds to enum values of sampler properties
88047330f729Sjoerg // defined in SPIR spec v1.2 and also opencl-c.h
88057330f729Sjoerg unsigned AddressingMode = (0x0E & SamplerValue) >> 1;
88067330f729Sjoerg unsigned FilterMode = (0x30 & SamplerValue) >> 4;
88077330f729Sjoerg if (FilterMode != 1 && FilterMode != 2 &&
8808*e038c9c4Sjoerg !S.getOpenCLOptions().isAvailableOption(
8809*e038c9c4Sjoerg "cl_intel_device_side_avc_motion_estimation", S.getLangOpts()))
88107330f729Sjoerg S.Diag(Kind.getLocation(),
88117330f729Sjoerg diag::warn_sampler_initializer_invalid_bits)
88127330f729Sjoerg << "Filter Mode";
88137330f729Sjoerg if (AddressingMode > 4)
88147330f729Sjoerg S.Diag(Kind.getLocation(),
88157330f729Sjoerg diag::warn_sampler_initializer_invalid_bits)
88167330f729Sjoerg << "Addressing Mode";
88177330f729Sjoerg }
88187330f729Sjoerg
88197330f729Sjoerg // Cases 1a, 2a and 2b
88207330f729Sjoerg // Insert cast from integer to sampler.
88217330f729Sjoerg CurInit = S.ImpCastExprToType(Init, S.Context.OCLSamplerTy,
88227330f729Sjoerg CK_IntToOCLSampler);
88237330f729Sjoerg break;
88247330f729Sjoerg }
88257330f729Sjoerg case SK_OCLZeroOpaqueType: {
88267330f729Sjoerg assert((Step->Type->isEventT() || Step->Type->isQueueT() ||
88277330f729Sjoerg Step->Type->isOCLIntelSubgroupAVCType()) &&
88287330f729Sjoerg "Wrong type for initialization of OpenCL opaque type.");
88297330f729Sjoerg
88307330f729Sjoerg CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
88317330f729Sjoerg CK_ZeroToOCLOpaqueType,
88327330f729Sjoerg CurInit.get()->getValueKind());
88337330f729Sjoerg break;
88347330f729Sjoerg }
88357330f729Sjoerg }
88367330f729Sjoerg }
88377330f729Sjoerg
88387330f729Sjoerg // Check whether the initializer has a shorter lifetime than the initialized
88397330f729Sjoerg // entity, and if not, either lifetime-extend or warn as appropriate.
88407330f729Sjoerg if (auto *Init = CurInit.get())
88417330f729Sjoerg S.checkInitializerLifetime(Entity, Init);
88427330f729Sjoerg
88437330f729Sjoerg // Diagnose non-fatal problems with the completed initialization.
88447330f729Sjoerg if (Entity.getKind() == InitializedEntity::EK_Member &&
88457330f729Sjoerg cast<FieldDecl>(Entity.getDecl())->isBitField())
88467330f729Sjoerg S.CheckBitFieldInitialization(Kind.getLocation(),
88477330f729Sjoerg cast<FieldDecl>(Entity.getDecl()),
88487330f729Sjoerg CurInit.get());
88497330f729Sjoerg
88507330f729Sjoerg // Check for std::move on construction.
88517330f729Sjoerg if (const Expr *E = CurInit.get()) {
88527330f729Sjoerg CheckMoveOnConstruction(S, E,
88537330f729Sjoerg Entity.getKind() == InitializedEntity::EK_Result);
88547330f729Sjoerg }
88557330f729Sjoerg
88567330f729Sjoerg return CurInit;
88577330f729Sjoerg }
88587330f729Sjoerg
88597330f729Sjoerg /// Somewhere within T there is an uninitialized reference subobject.
88607330f729Sjoerg /// Dig it out and diagnose it.
DiagnoseUninitializedReference(Sema & S,SourceLocation Loc,QualType T)88617330f729Sjoerg static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
88627330f729Sjoerg QualType T) {
88637330f729Sjoerg if (T->isReferenceType()) {
88647330f729Sjoerg S.Diag(Loc, diag::err_reference_without_init)
88657330f729Sjoerg << T.getNonReferenceType();
88667330f729Sjoerg return true;
88677330f729Sjoerg }
88687330f729Sjoerg
88697330f729Sjoerg CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
88707330f729Sjoerg if (!RD || !RD->hasUninitializedReferenceMember())
88717330f729Sjoerg return false;
88727330f729Sjoerg
88737330f729Sjoerg for (const auto *FI : RD->fields()) {
88747330f729Sjoerg if (FI->isUnnamedBitfield())
88757330f729Sjoerg continue;
88767330f729Sjoerg
88777330f729Sjoerg if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
88787330f729Sjoerg S.Diag(Loc, diag::note_value_initialization_here) << RD;
88797330f729Sjoerg return true;
88807330f729Sjoerg }
88817330f729Sjoerg }
88827330f729Sjoerg
88837330f729Sjoerg for (const auto &BI : RD->bases()) {
88847330f729Sjoerg if (DiagnoseUninitializedReference(S, BI.getBeginLoc(), BI.getType())) {
88857330f729Sjoerg S.Diag(Loc, diag::note_value_initialization_here) << RD;
88867330f729Sjoerg return true;
88877330f729Sjoerg }
88887330f729Sjoerg }
88897330f729Sjoerg
88907330f729Sjoerg return false;
88917330f729Sjoerg }
88927330f729Sjoerg
88937330f729Sjoerg
88947330f729Sjoerg //===----------------------------------------------------------------------===//
88957330f729Sjoerg // Diagnose initialization failures
88967330f729Sjoerg //===----------------------------------------------------------------------===//
88977330f729Sjoerg
88987330f729Sjoerg /// Emit notes associated with an initialization that failed due to a
88997330f729Sjoerg /// "simple" conversion failure.
emitBadConversionNotes(Sema & S,const InitializedEntity & entity,Expr * op)89007330f729Sjoerg static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
89017330f729Sjoerg Expr *op) {
89027330f729Sjoerg QualType destType = entity.getType();
89037330f729Sjoerg if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
89047330f729Sjoerg op->getType()->isObjCObjectPointerType()) {
89057330f729Sjoerg
89067330f729Sjoerg // Emit a possible note about the conversion failing because the
89077330f729Sjoerg // operand is a message send with a related result type.
89087330f729Sjoerg S.EmitRelatedResultTypeNote(op);
89097330f729Sjoerg
89107330f729Sjoerg // Emit a possible note about a return failing because we're
89117330f729Sjoerg // expecting a related result type.
89127330f729Sjoerg if (entity.getKind() == InitializedEntity::EK_Result)
89137330f729Sjoerg S.EmitRelatedResultTypeNoteForReturn(destType);
89147330f729Sjoerg }
8915*e038c9c4Sjoerg QualType fromType = op->getType();
8916*e038c9c4Sjoerg auto *fromDecl = fromType.getTypePtr()->getPointeeCXXRecordDecl();
8917*e038c9c4Sjoerg auto *destDecl = destType.getTypePtr()->getPointeeCXXRecordDecl();
8918*e038c9c4Sjoerg if (fromDecl && destDecl && fromDecl->getDeclKind() == Decl::CXXRecord &&
8919*e038c9c4Sjoerg destDecl->getDeclKind() == Decl::CXXRecord &&
8920*e038c9c4Sjoerg !fromDecl->isInvalidDecl() && !destDecl->isInvalidDecl() &&
8921*e038c9c4Sjoerg !fromDecl->hasDefinition())
8922*e038c9c4Sjoerg S.Diag(fromDecl->getLocation(), diag::note_forward_class_conversion)
8923*e038c9c4Sjoerg << S.getASTContext().getTagDeclType(fromDecl)
8924*e038c9c4Sjoerg << S.getASTContext().getTagDeclType(destDecl);
89257330f729Sjoerg }
89267330f729Sjoerg
diagnoseListInit(Sema & S,const InitializedEntity & Entity,InitListExpr * InitList)89277330f729Sjoerg static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
89287330f729Sjoerg InitListExpr *InitList) {
89297330f729Sjoerg QualType DestType = Entity.getType();
89307330f729Sjoerg
89317330f729Sjoerg QualType E;
89327330f729Sjoerg if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
89337330f729Sjoerg QualType ArrayType = S.Context.getConstantArrayType(
89347330f729Sjoerg E.withConst(),
89357330f729Sjoerg llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
89367330f729Sjoerg InitList->getNumInits()),
89377330f729Sjoerg nullptr, clang::ArrayType::Normal, 0);
89387330f729Sjoerg InitializedEntity HiddenArray =
89397330f729Sjoerg InitializedEntity::InitializeTemporary(ArrayType);
89407330f729Sjoerg return diagnoseListInit(S, HiddenArray, InitList);
89417330f729Sjoerg }
89427330f729Sjoerg
89437330f729Sjoerg if (DestType->isReferenceType()) {
89447330f729Sjoerg // A list-initialization failure for a reference means that we tried to
89457330f729Sjoerg // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
89467330f729Sjoerg // inner initialization failed.
89477330f729Sjoerg QualType T = DestType->castAs<ReferenceType>()->getPointeeType();
89487330f729Sjoerg diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), InitList);
89497330f729Sjoerg SourceLocation Loc = InitList->getBeginLoc();
89507330f729Sjoerg if (auto *D = Entity.getDecl())
89517330f729Sjoerg Loc = D->getLocation();
89527330f729Sjoerg S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
89537330f729Sjoerg return;
89547330f729Sjoerg }
89557330f729Sjoerg
89567330f729Sjoerg InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
89577330f729Sjoerg /*VerifyOnly=*/false,
89587330f729Sjoerg /*TreatUnavailableAsInvalid=*/false);
89597330f729Sjoerg assert(DiagnoseInitList.HadError() &&
89607330f729Sjoerg "Inconsistent init list check result.");
89617330f729Sjoerg }
89627330f729Sjoerg
Diagnose(Sema & S,const InitializedEntity & Entity,const InitializationKind & Kind,ArrayRef<Expr * > Args)89637330f729Sjoerg bool InitializationSequence::Diagnose(Sema &S,
89647330f729Sjoerg const InitializedEntity &Entity,
89657330f729Sjoerg const InitializationKind &Kind,
89667330f729Sjoerg ArrayRef<Expr *> Args) {
89677330f729Sjoerg if (!Failed())
89687330f729Sjoerg return false;
89697330f729Sjoerg
89707330f729Sjoerg // When we want to diagnose only one element of a braced-init-list,
89717330f729Sjoerg // we need to factor it out.
89727330f729Sjoerg Expr *OnlyArg;
89737330f729Sjoerg if (Args.size() == 1) {
89747330f729Sjoerg auto *List = dyn_cast<InitListExpr>(Args[0]);
89757330f729Sjoerg if (List && List->getNumInits() == 1)
89767330f729Sjoerg OnlyArg = List->getInit(0);
89777330f729Sjoerg else
89787330f729Sjoerg OnlyArg = Args[0];
89797330f729Sjoerg }
89807330f729Sjoerg else
89817330f729Sjoerg OnlyArg = nullptr;
89827330f729Sjoerg
89837330f729Sjoerg QualType DestType = Entity.getType();
89847330f729Sjoerg switch (Failure) {
89857330f729Sjoerg case FK_TooManyInitsForReference:
89867330f729Sjoerg // FIXME: Customize for the initialized entity?
89877330f729Sjoerg if (Args.empty()) {
89887330f729Sjoerg // Dig out the reference subobject which is uninitialized and diagnose it.
89897330f729Sjoerg // If this is value-initialization, this could be nested some way within
89907330f729Sjoerg // the target type.
89917330f729Sjoerg assert(Kind.getKind() == InitializationKind::IK_Value ||
89927330f729Sjoerg DestType->isReferenceType());
89937330f729Sjoerg bool Diagnosed =
89947330f729Sjoerg DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
89957330f729Sjoerg assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
89967330f729Sjoerg (void)Diagnosed;
89977330f729Sjoerg } else // FIXME: diagnostic below could be better!
89987330f729Sjoerg S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
89997330f729Sjoerg << SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
90007330f729Sjoerg break;
90017330f729Sjoerg case FK_ParenthesizedListInitForReference:
90027330f729Sjoerg S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
90037330f729Sjoerg << 1 << Entity.getType() << Args[0]->getSourceRange();
90047330f729Sjoerg break;
90057330f729Sjoerg
90067330f729Sjoerg case FK_ArrayNeedsInitList:
90077330f729Sjoerg S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
90087330f729Sjoerg break;
90097330f729Sjoerg case FK_ArrayNeedsInitListOrStringLiteral:
90107330f729Sjoerg S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
90117330f729Sjoerg break;
90127330f729Sjoerg case FK_ArrayNeedsInitListOrWideStringLiteral:
90137330f729Sjoerg S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
90147330f729Sjoerg break;
90157330f729Sjoerg case FK_NarrowStringIntoWideCharArray:
90167330f729Sjoerg S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
90177330f729Sjoerg break;
90187330f729Sjoerg case FK_WideStringIntoCharArray:
90197330f729Sjoerg S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
90207330f729Sjoerg break;
90217330f729Sjoerg case FK_IncompatWideStringIntoWideChar:
90227330f729Sjoerg S.Diag(Kind.getLocation(),
90237330f729Sjoerg diag::err_array_init_incompat_wide_string_into_wchar);
90247330f729Sjoerg break;
90257330f729Sjoerg case FK_PlainStringIntoUTF8Char:
90267330f729Sjoerg S.Diag(Kind.getLocation(),
90277330f729Sjoerg diag::err_array_init_plain_string_into_char8_t);
90287330f729Sjoerg S.Diag(Args.front()->getBeginLoc(),
90297330f729Sjoerg diag::note_array_init_plain_string_into_char8_t)
90307330f729Sjoerg << FixItHint::CreateInsertion(Args.front()->getBeginLoc(), "u8");
90317330f729Sjoerg break;
90327330f729Sjoerg case FK_UTF8StringIntoPlainChar:
90337330f729Sjoerg S.Diag(Kind.getLocation(),
90347330f729Sjoerg diag::err_array_init_utf8_string_into_char)
9035*e038c9c4Sjoerg << S.getLangOpts().CPlusPlus20;
90367330f729Sjoerg break;
90377330f729Sjoerg case FK_ArrayTypeMismatch:
90387330f729Sjoerg case FK_NonConstantArrayInit:
90397330f729Sjoerg S.Diag(Kind.getLocation(),
90407330f729Sjoerg (Failure == FK_ArrayTypeMismatch
90417330f729Sjoerg ? diag::err_array_init_different_type
90427330f729Sjoerg : diag::err_array_init_non_constant_array))
90437330f729Sjoerg << DestType.getNonReferenceType()
90447330f729Sjoerg << OnlyArg->getType()
90457330f729Sjoerg << Args[0]->getSourceRange();
90467330f729Sjoerg break;
90477330f729Sjoerg
90487330f729Sjoerg case FK_VariableLengthArrayHasInitializer:
90497330f729Sjoerg S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
90507330f729Sjoerg << Args[0]->getSourceRange();
90517330f729Sjoerg break;
90527330f729Sjoerg
90537330f729Sjoerg case FK_AddressOfOverloadFailed: {
90547330f729Sjoerg DeclAccessPair Found;
90557330f729Sjoerg S.ResolveAddressOfOverloadedFunction(OnlyArg,
90567330f729Sjoerg DestType.getNonReferenceType(),
90577330f729Sjoerg true,
90587330f729Sjoerg Found);
90597330f729Sjoerg break;
90607330f729Sjoerg }
90617330f729Sjoerg
90627330f729Sjoerg case FK_AddressOfUnaddressableFunction: {
90637330f729Sjoerg auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(OnlyArg)->getDecl());
90647330f729Sjoerg S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
90657330f729Sjoerg OnlyArg->getBeginLoc());
90667330f729Sjoerg break;
90677330f729Sjoerg }
90687330f729Sjoerg
90697330f729Sjoerg case FK_ReferenceInitOverloadFailed:
90707330f729Sjoerg case FK_UserConversionOverloadFailed:
90717330f729Sjoerg switch (FailedOverloadResult) {
90727330f729Sjoerg case OR_Ambiguous:
90737330f729Sjoerg
90747330f729Sjoerg FailedCandidateSet.NoteCandidates(
90757330f729Sjoerg PartialDiagnosticAt(
90767330f729Sjoerg Kind.getLocation(),
90777330f729Sjoerg Failure == FK_UserConversionOverloadFailed
90787330f729Sjoerg ? (S.PDiag(diag::err_typecheck_ambiguous_condition)
90797330f729Sjoerg << OnlyArg->getType() << DestType
90807330f729Sjoerg << Args[0]->getSourceRange())
90817330f729Sjoerg : (S.PDiag(diag::err_ref_init_ambiguous)
90827330f729Sjoerg << DestType << OnlyArg->getType()
90837330f729Sjoerg << Args[0]->getSourceRange())),
90847330f729Sjoerg S, OCD_AmbiguousCandidates, Args);
90857330f729Sjoerg break;
90867330f729Sjoerg
90877330f729Sjoerg case OR_No_Viable_Function: {
90887330f729Sjoerg auto Cands = FailedCandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args);
90897330f729Sjoerg if (!S.RequireCompleteType(Kind.getLocation(),
90907330f729Sjoerg DestType.getNonReferenceType(),
90917330f729Sjoerg diag::err_typecheck_nonviable_condition_incomplete,
90927330f729Sjoerg OnlyArg->getType(), Args[0]->getSourceRange()))
90937330f729Sjoerg S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
90947330f729Sjoerg << (Entity.getKind() == InitializedEntity::EK_Result)
90957330f729Sjoerg << OnlyArg->getType() << Args[0]->getSourceRange()
90967330f729Sjoerg << DestType.getNonReferenceType();
90977330f729Sjoerg
90987330f729Sjoerg FailedCandidateSet.NoteCandidates(S, Args, Cands);
90997330f729Sjoerg break;
91007330f729Sjoerg }
91017330f729Sjoerg case OR_Deleted: {
91027330f729Sjoerg S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
91037330f729Sjoerg << OnlyArg->getType() << DestType.getNonReferenceType()
91047330f729Sjoerg << Args[0]->getSourceRange();
91057330f729Sjoerg OverloadCandidateSet::iterator Best;
91067330f729Sjoerg OverloadingResult Ovl
91077330f729Sjoerg = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
91087330f729Sjoerg if (Ovl == OR_Deleted) {
91097330f729Sjoerg S.NoteDeletedFunction(Best->Function);
91107330f729Sjoerg } else {
91117330f729Sjoerg llvm_unreachable("Inconsistent overload resolution?");
91127330f729Sjoerg }
91137330f729Sjoerg break;
91147330f729Sjoerg }
91157330f729Sjoerg
91167330f729Sjoerg case OR_Success:
91177330f729Sjoerg llvm_unreachable("Conversion did not fail!");
91187330f729Sjoerg }
91197330f729Sjoerg break;
91207330f729Sjoerg
91217330f729Sjoerg case FK_NonConstLValueReferenceBindingToTemporary:
91227330f729Sjoerg if (isa<InitListExpr>(Args[0])) {
91237330f729Sjoerg S.Diag(Kind.getLocation(),
91247330f729Sjoerg diag::err_lvalue_reference_bind_to_initlist)
91257330f729Sjoerg << DestType.getNonReferenceType().isVolatileQualified()
91267330f729Sjoerg << DestType.getNonReferenceType()
91277330f729Sjoerg << Args[0]->getSourceRange();
91287330f729Sjoerg break;
91297330f729Sjoerg }
91307330f729Sjoerg LLVM_FALLTHROUGH;
91317330f729Sjoerg
91327330f729Sjoerg case FK_NonConstLValueReferenceBindingToUnrelated:
91337330f729Sjoerg S.Diag(Kind.getLocation(),
91347330f729Sjoerg Failure == FK_NonConstLValueReferenceBindingToTemporary
91357330f729Sjoerg ? diag::err_lvalue_reference_bind_to_temporary
91367330f729Sjoerg : diag::err_lvalue_reference_bind_to_unrelated)
91377330f729Sjoerg << DestType.getNonReferenceType().isVolatileQualified()
91387330f729Sjoerg << DestType.getNonReferenceType()
91397330f729Sjoerg << OnlyArg->getType()
91407330f729Sjoerg << Args[0]->getSourceRange();
91417330f729Sjoerg break;
91427330f729Sjoerg
91437330f729Sjoerg case FK_NonConstLValueReferenceBindingToBitfield: {
91447330f729Sjoerg // We don't necessarily have an unambiguous source bit-field.
91457330f729Sjoerg FieldDecl *BitField = Args[0]->getSourceBitField();
91467330f729Sjoerg S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
91477330f729Sjoerg << DestType.isVolatileQualified()
91487330f729Sjoerg << (BitField ? BitField->getDeclName() : DeclarationName())
91497330f729Sjoerg << (BitField != nullptr)
91507330f729Sjoerg << Args[0]->getSourceRange();
91517330f729Sjoerg if (BitField)
91527330f729Sjoerg S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
91537330f729Sjoerg break;
91547330f729Sjoerg }
91557330f729Sjoerg
91567330f729Sjoerg case FK_NonConstLValueReferenceBindingToVectorElement:
91577330f729Sjoerg S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
91587330f729Sjoerg << DestType.isVolatileQualified()
91597330f729Sjoerg << Args[0]->getSourceRange();
91607330f729Sjoerg break;
91617330f729Sjoerg
9162*e038c9c4Sjoerg case FK_NonConstLValueReferenceBindingToMatrixElement:
9163*e038c9c4Sjoerg S.Diag(Kind.getLocation(), diag::err_reference_bind_to_matrix_element)
9164*e038c9c4Sjoerg << DestType.isVolatileQualified() << Args[0]->getSourceRange();
9165*e038c9c4Sjoerg break;
9166*e038c9c4Sjoerg
91677330f729Sjoerg case FK_RValueReferenceBindingToLValue:
91687330f729Sjoerg S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
91697330f729Sjoerg << DestType.getNonReferenceType() << OnlyArg->getType()
91707330f729Sjoerg << Args[0]->getSourceRange();
91717330f729Sjoerg break;
91727330f729Sjoerg
91737330f729Sjoerg case FK_ReferenceAddrspaceMismatchTemporary:
91747330f729Sjoerg S.Diag(Kind.getLocation(), diag::err_reference_bind_temporary_addrspace)
91757330f729Sjoerg << DestType << Args[0]->getSourceRange();
91767330f729Sjoerg break;
91777330f729Sjoerg
91787330f729Sjoerg case FK_ReferenceInitDropsQualifiers: {
91797330f729Sjoerg QualType SourceType = OnlyArg->getType();
91807330f729Sjoerg QualType NonRefType = DestType.getNonReferenceType();
91817330f729Sjoerg Qualifiers DroppedQualifiers =
91827330f729Sjoerg SourceType.getQualifiers() - NonRefType.getQualifiers();
91837330f729Sjoerg
91847330f729Sjoerg if (!NonRefType.getQualifiers().isAddressSpaceSupersetOf(
91857330f729Sjoerg SourceType.getQualifiers()))
91867330f729Sjoerg S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
91877330f729Sjoerg << NonRefType << SourceType << 1 /*addr space*/
91887330f729Sjoerg << Args[0]->getSourceRange();
9189*e038c9c4Sjoerg else if (DroppedQualifiers.hasQualifiers())
91907330f729Sjoerg S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
91917330f729Sjoerg << NonRefType << SourceType << 0 /*cv quals*/
91927330f729Sjoerg << Qualifiers::fromCVRMask(DroppedQualifiers.getCVRQualifiers())
91937330f729Sjoerg << DroppedQualifiers.getCVRQualifiers() << Args[0]->getSourceRange();
9194*e038c9c4Sjoerg else
9195*e038c9c4Sjoerg // FIXME: Consider decomposing the type and explaining which qualifiers
9196*e038c9c4Sjoerg // were dropped where, or on which level a 'const' is missing, etc.
9197*e038c9c4Sjoerg S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9198*e038c9c4Sjoerg << NonRefType << SourceType << 2 /*incompatible quals*/
9199*e038c9c4Sjoerg << Args[0]->getSourceRange();
92007330f729Sjoerg break;
92017330f729Sjoerg }
92027330f729Sjoerg
92037330f729Sjoerg case FK_ReferenceInitFailed:
92047330f729Sjoerg S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
92057330f729Sjoerg << DestType.getNonReferenceType()
92067330f729Sjoerg << DestType.getNonReferenceType()->isIncompleteType()
92077330f729Sjoerg << OnlyArg->isLValue()
92087330f729Sjoerg << OnlyArg->getType()
92097330f729Sjoerg << Args[0]->getSourceRange();
92107330f729Sjoerg emitBadConversionNotes(S, Entity, Args[0]);
92117330f729Sjoerg break;
92127330f729Sjoerg
92137330f729Sjoerg case FK_ConversionFailed: {
92147330f729Sjoerg QualType FromType = OnlyArg->getType();
92157330f729Sjoerg PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
92167330f729Sjoerg << (int)Entity.getKind()
92177330f729Sjoerg << DestType
92187330f729Sjoerg << OnlyArg->isLValue()
92197330f729Sjoerg << FromType
92207330f729Sjoerg << Args[0]->getSourceRange();
92217330f729Sjoerg S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
92227330f729Sjoerg S.Diag(Kind.getLocation(), PDiag);
92237330f729Sjoerg emitBadConversionNotes(S, Entity, Args[0]);
92247330f729Sjoerg break;
92257330f729Sjoerg }
92267330f729Sjoerg
92277330f729Sjoerg case FK_ConversionFromPropertyFailed:
92287330f729Sjoerg // No-op. This error has already been reported.
92297330f729Sjoerg break;
92307330f729Sjoerg
92317330f729Sjoerg case FK_TooManyInitsForScalar: {
92327330f729Sjoerg SourceRange R;
92337330f729Sjoerg
92347330f729Sjoerg auto *InitList = dyn_cast<InitListExpr>(Args[0]);
92357330f729Sjoerg if (InitList && InitList->getNumInits() >= 1) {
92367330f729Sjoerg R = SourceRange(InitList->getInit(0)->getEndLoc(), InitList->getEndLoc());
92377330f729Sjoerg } else {
92387330f729Sjoerg assert(Args.size() > 1 && "Expected multiple initializers!");
92397330f729Sjoerg R = SourceRange(Args.front()->getEndLoc(), Args.back()->getEndLoc());
92407330f729Sjoerg }
92417330f729Sjoerg
92427330f729Sjoerg R.setBegin(S.getLocForEndOfToken(R.getBegin()));
92437330f729Sjoerg if (Kind.isCStyleOrFunctionalCast())
92447330f729Sjoerg S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
92457330f729Sjoerg << R;
92467330f729Sjoerg else
92477330f729Sjoerg S.Diag(Kind.getLocation(), diag::err_excess_initializers)
92487330f729Sjoerg << /*scalar=*/2 << R;
92497330f729Sjoerg break;
92507330f729Sjoerg }
92517330f729Sjoerg
92527330f729Sjoerg case FK_ParenthesizedListInitForScalar:
92537330f729Sjoerg S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
92547330f729Sjoerg << 0 << Entity.getType() << Args[0]->getSourceRange();
92557330f729Sjoerg break;
92567330f729Sjoerg
92577330f729Sjoerg case FK_ReferenceBindingToInitList:
92587330f729Sjoerg S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
92597330f729Sjoerg << DestType.getNonReferenceType() << Args[0]->getSourceRange();
92607330f729Sjoerg break;
92617330f729Sjoerg
92627330f729Sjoerg case FK_InitListBadDestinationType:
92637330f729Sjoerg S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
92647330f729Sjoerg << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
92657330f729Sjoerg break;
92667330f729Sjoerg
92677330f729Sjoerg case FK_ListConstructorOverloadFailed:
92687330f729Sjoerg case FK_ConstructorOverloadFailed: {
92697330f729Sjoerg SourceRange ArgsRange;
92707330f729Sjoerg if (Args.size())
92717330f729Sjoerg ArgsRange =
92727330f729Sjoerg SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
92737330f729Sjoerg
92747330f729Sjoerg if (Failure == FK_ListConstructorOverloadFailed) {
92757330f729Sjoerg assert(Args.size() == 1 &&
92767330f729Sjoerg "List construction from other than 1 argument.");
92777330f729Sjoerg InitListExpr *InitList = cast<InitListExpr>(Args[0]);
92787330f729Sjoerg Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
92797330f729Sjoerg }
92807330f729Sjoerg
92817330f729Sjoerg // FIXME: Using "DestType" for the entity we're printing is probably
92827330f729Sjoerg // bad.
92837330f729Sjoerg switch (FailedOverloadResult) {
92847330f729Sjoerg case OR_Ambiguous:
92857330f729Sjoerg FailedCandidateSet.NoteCandidates(
92867330f729Sjoerg PartialDiagnosticAt(Kind.getLocation(),
92877330f729Sjoerg S.PDiag(diag::err_ovl_ambiguous_init)
92887330f729Sjoerg << DestType << ArgsRange),
92897330f729Sjoerg S, OCD_AmbiguousCandidates, Args);
92907330f729Sjoerg break;
92917330f729Sjoerg
92927330f729Sjoerg case OR_No_Viable_Function:
92937330f729Sjoerg if (Kind.getKind() == InitializationKind::IK_Default &&
92947330f729Sjoerg (Entity.getKind() == InitializedEntity::EK_Base ||
92957330f729Sjoerg Entity.getKind() == InitializedEntity::EK_Member) &&
92967330f729Sjoerg isa<CXXConstructorDecl>(S.CurContext)) {
92977330f729Sjoerg // This is implicit default initialization of a member or
92987330f729Sjoerg // base within a constructor. If no viable function was
92997330f729Sjoerg // found, notify the user that they need to explicitly
93007330f729Sjoerg // initialize this base/member.
93017330f729Sjoerg CXXConstructorDecl *Constructor
93027330f729Sjoerg = cast<CXXConstructorDecl>(S.CurContext);
93037330f729Sjoerg const CXXRecordDecl *InheritedFrom = nullptr;
93047330f729Sjoerg if (auto Inherited = Constructor->getInheritedConstructor())
93057330f729Sjoerg InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass();
93067330f729Sjoerg if (Entity.getKind() == InitializedEntity::EK_Base) {
93077330f729Sjoerg S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
93087330f729Sjoerg << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
93097330f729Sjoerg << S.Context.getTypeDeclType(Constructor->getParent())
93107330f729Sjoerg << /*base=*/0
93117330f729Sjoerg << Entity.getType()
93127330f729Sjoerg << InheritedFrom;
93137330f729Sjoerg
93147330f729Sjoerg RecordDecl *BaseDecl
93157330f729Sjoerg = Entity.getBaseSpecifier()->getType()->castAs<RecordType>()
93167330f729Sjoerg ->getDecl();
93177330f729Sjoerg S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
93187330f729Sjoerg << S.Context.getTagDeclType(BaseDecl);
93197330f729Sjoerg } else {
93207330f729Sjoerg S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
93217330f729Sjoerg << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
93227330f729Sjoerg << S.Context.getTypeDeclType(Constructor->getParent())
93237330f729Sjoerg << /*member=*/1
93247330f729Sjoerg << Entity.getName()
93257330f729Sjoerg << InheritedFrom;
93267330f729Sjoerg S.Diag(Entity.getDecl()->getLocation(),
93277330f729Sjoerg diag::note_member_declared_at);
93287330f729Sjoerg
93297330f729Sjoerg if (const RecordType *Record
93307330f729Sjoerg = Entity.getType()->getAs<RecordType>())
93317330f729Sjoerg S.Diag(Record->getDecl()->getLocation(),
93327330f729Sjoerg diag::note_previous_decl)
93337330f729Sjoerg << S.Context.getTagDeclType(Record->getDecl());
93347330f729Sjoerg }
93357330f729Sjoerg break;
93367330f729Sjoerg }
93377330f729Sjoerg
93387330f729Sjoerg FailedCandidateSet.NoteCandidates(
93397330f729Sjoerg PartialDiagnosticAt(
93407330f729Sjoerg Kind.getLocation(),
93417330f729Sjoerg S.PDiag(diag::err_ovl_no_viable_function_in_init)
93427330f729Sjoerg << DestType << ArgsRange),
93437330f729Sjoerg S, OCD_AllCandidates, Args);
93447330f729Sjoerg break;
93457330f729Sjoerg
93467330f729Sjoerg case OR_Deleted: {
93477330f729Sjoerg OverloadCandidateSet::iterator Best;
93487330f729Sjoerg OverloadingResult Ovl
93497330f729Sjoerg = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
93507330f729Sjoerg if (Ovl != OR_Deleted) {
93517330f729Sjoerg S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
93527330f729Sjoerg << DestType << ArgsRange;
93537330f729Sjoerg llvm_unreachable("Inconsistent overload resolution?");
93547330f729Sjoerg break;
93557330f729Sjoerg }
93567330f729Sjoerg
93577330f729Sjoerg // If this is a defaulted or implicitly-declared function, then
93587330f729Sjoerg // it was implicitly deleted. Make it clear that the deletion was
93597330f729Sjoerg // implicit.
93607330f729Sjoerg if (S.isImplicitlyDeleted(Best->Function))
93617330f729Sjoerg S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
93627330f729Sjoerg << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
93637330f729Sjoerg << DestType << ArgsRange;
93647330f729Sjoerg else
93657330f729Sjoerg S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
93667330f729Sjoerg << DestType << ArgsRange;
93677330f729Sjoerg
93687330f729Sjoerg S.NoteDeletedFunction(Best->Function);
93697330f729Sjoerg break;
93707330f729Sjoerg }
93717330f729Sjoerg
93727330f729Sjoerg case OR_Success:
93737330f729Sjoerg llvm_unreachable("Conversion did not fail!");
93747330f729Sjoerg }
93757330f729Sjoerg }
93767330f729Sjoerg break;
93777330f729Sjoerg
93787330f729Sjoerg case FK_DefaultInitOfConst:
93797330f729Sjoerg if (Entity.getKind() == InitializedEntity::EK_Member &&
93807330f729Sjoerg isa<CXXConstructorDecl>(S.CurContext)) {
93817330f729Sjoerg // This is implicit default-initialization of a const member in
93827330f729Sjoerg // a constructor. Complain that it needs to be explicitly
93837330f729Sjoerg // initialized.
93847330f729Sjoerg CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
93857330f729Sjoerg S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
93867330f729Sjoerg << (Constructor->getInheritedConstructor() ? 2 :
93877330f729Sjoerg Constructor->isImplicit() ? 1 : 0)
93887330f729Sjoerg << S.Context.getTypeDeclType(Constructor->getParent())
93897330f729Sjoerg << /*const=*/1
93907330f729Sjoerg << Entity.getName();
93917330f729Sjoerg S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
93927330f729Sjoerg << Entity.getName();
93937330f729Sjoerg } else {
93947330f729Sjoerg S.Diag(Kind.getLocation(), diag::err_default_init_const)
93957330f729Sjoerg << DestType << (bool)DestType->getAs<RecordType>();
93967330f729Sjoerg }
93977330f729Sjoerg break;
93987330f729Sjoerg
93997330f729Sjoerg case FK_Incomplete:
94007330f729Sjoerg S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
94017330f729Sjoerg diag::err_init_incomplete_type);
94027330f729Sjoerg break;
94037330f729Sjoerg
94047330f729Sjoerg case FK_ListInitializationFailed: {
94057330f729Sjoerg // Run the init list checker again to emit diagnostics.
94067330f729Sjoerg InitListExpr *InitList = cast<InitListExpr>(Args[0]);
94077330f729Sjoerg diagnoseListInit(S, Entity, InitList);
94087330f729Sjoerg break;
94097330f729Sjoerg }
94107330f729Sjoerg
94117330f729Sjoerg case FK_PlaceholderType: {
94127330f729Sjoerg // FIXME: Already diagnosed!
94137330f729Sjoerg break;
94147330f729Sjoerg }
94157330f729Sjoerg
94167330f729Sjoerg case FK_ExplicitConstructor: {
94177330f729Sjoerg S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
94187330f729Sjoerg << Args[0]->getSourceRange();
94197330f729Sjoerg OverloadCandidateSet::iterator Best;
94207330f729Sjoerg OverloadingResult Ovl
94217330f729Sjoerg = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
94227330f729Sjoerg (void)Ovl;
94237330f729Sjoerg assert(Ovl == OR_Success && "Inconsistent overload resolution");
94247330f729Sjoerg CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
94257330f729Sjoerg S.Diag(CtorDecl->getLocation(),
94267330f729Sjoerg diag::note_explicit_ctor_deduction_guide_here) << false;
94277330f729Sjoerg break;
94287330f729Sjoerg }
94297330f729Sjoerg }
94307330f729Sjoerg
94317330f729Sjoerg PrintInitLocationNote(S, Entity);
94327330f729Sjoerg return true;
94337330f729Sjoerg }
94347330f729Sjoerg
dump(raw_ostream & OS) const94357330f729Sjoerg void InitializationSequence::dump(raw_ostream &OS) const {
94367330f729Sjoerg switch (SequenceKind) {
94377330f729Sjoerg case FailedSequence: {
94387330f729Sjoerg OS << "Failed sequence: ";
94397330f729Sjoerg switch (Failure) {
94407330f729Sjoerg case FK_TooManyInitsForReference:
94417330f729Sjoerg OS << "too many initializers for reference";
94427330f729Sjoerg break;
94437330f729Sjoerg
94447330f729Sjoerg case FK_ParenthesizedListInitForReference:
94457330f729Sjoerg OS << "parenthesized list init for reference";
94467330f729Sjoerg break;
94477330f729Sjoerg
94487330f729Sjoerg case FK_ArrayNeedsInitList:
94497330f729Sjoerg OS << "array requires initializer list";
94507330f729Sjoerg break;
94517330f729Sjoerg
94527330f729Sjoerg case FK_AddressOfUnaddressableFunction:
94537330f729Sjoerg OS << "address of unaddressable function was taken";
94547330f729Sjoerg break;
94557330f729Sjoerg
94567330f729Sjoerg case FK_ArrayNeedsInitListOrStringLiteral:
94577330f729Sjoerg OS << "array requires initializer list or string literal";
94587330f729Sjoerg break;
94597330f729Sjoerg
94607330f729Sjoerg case FK_ArrayNeedsInitListOrWideStringLiteral:
94617330f729Sjoerg OS << "array requires initializer list or wide string literal";
94627330f729Sjoerg break;
94637330f729Sjoerg
94647330f729Sjoerg case FK_NarrowStringIntoWideCharArray:
94657330f729Sjoerg OS << "narrow string into wide char array";
94667330f729Sjoerg break;
94677330f729Sjoerg
94687330f729Sjoerg case FK_WideStringIntoCharArray:
94697330f729Sjoerg OS << "wide string into char array";
94707330f729Sjoerg break;
94717330f729Sjoerg
94727330f729Sjoerg case FK_IncompatWideStringIntoWideChar:
94737330f729Sjoerg OS << "incompatible wide string into wide char array";
94747330f729Sjoerg break;
94757330f729Sjoerg
94767330f729Sjoerg case FK_PlainStringIntoUTF8Char:
94777330f729Sjoerg OS << "plain string literal into char8_t array";
94787330f729Sjoerg break;
94797330f729Sjoerg
94807330f729Sjoerg case FK_UTF8StringIntoPlainChar:
94817330f729Sjoerg OS << "u8 string literal into char array";
94827330f729Sjoerg break;
94837330f729Sjoerg
94847330f729Sjoerg case FK_ArrayTypeMismatch:
94857330f729Sjoerg OS << "array type mismatch";
94867330f729Sjoerg break;
94877330f729Sjoerg
94887330f729Sjoerg case FK_NonConstantArrayInit:
94897330f729Sjoerg OS << "non-constant array initializer";
94907330f729Sjoerg break;
94917330f729Sjoerg
94927330f729Sjoerg case FK_AddressOfOverloadFailed:
94937330f729Sjoerg OS << "address of overloaded function failed";
94947330f729Sjoerg break;
94957330f729Sjoerg
94967330f729Sjoerg case FK_ReferenceInitOverloadFailed:
94977330f729Sjoerg OS << "overload resolution for reference initialization failed";
94987330f729Sjoerg break;
94997330f729Sjoerg
95007330f729Sjoerg case FK_NonConstLValueReferenceBindingToTemporary:
95017330f729Sjoerg OS << "non-const lvalue reference bound to temporary";
95027330f729Sjoerg break;
95037330f729Sjoerg
95047330f729Sjoerg case FK_NonConstLValueReferenceBindingToBitfield:
95057330f729Sjoerg OS << "non-const lvalue reference bound to bit-field";
95067330f729Sjoerg break;
95077330f729Sjoerg
95087330f729Sjoerg case FK_NonConstLValueReferenceBindingToVectorElement:
95097330f729Sjoerg OS << "non-const lvalue reference bound to vector element";
95107330f729Sjoerg break;
95117330f729Sjoerg
9512*e038c9c4Sjoerg case FK_NonConstLValueReferenceBindingToMatrixElement:
9513*e038c9c4Sjoerg OS << "non-const lvalue reference bound to matrix element";
9514*e038c9c4Sjoerg break;
9515*e038c9c4Sjoerg
95167330f729Sjoerg case FK_NonConstLValueReferenceBindingToUnrelated:
95177330f729Sjoerg OS << "non-const lvalue reference bound to unrelated type";
95187330f729Sjoerg break;
95197330f729Sjoerg
95207330f729Sjoerg case FK_RValueReferenceBindingToLValue:
95217330f729Sjoerg OS << "rvalue reference bound to an lvalue";
95227330f729Sjoerg break;
95237330f729Sjoerg
95247330f729Sjoerg case FK_ReferenceInitDropsQualifiers:
95257330f729Sjoerg OS << "reference initialization drops qualifiers";
95267330f729Sjoerg break;
95277330f729Sjoerg
95287330f729Sjoerg case FK_ReferenceAddrspaceMismatchTemporary:
95297330f729Sjoerg OS << "reference with mismatching address space bound to temporary";
95307330f729Sjoerg break;
95317330f729Sjoerg
95327330f729Sjoerg case FK_ReferenceInitFailed:
95337330f729Sjoerg OS << "reference initialization failed";
95347330f729Sjoerg break;
95357330f729Sjoerg
95367330f729Sjoerg case FK_ConversionFailed:
95377330f729Sjoerg OS << "conversion failed";
95387330f729Sjoerg break;
95397330f729Sjoerg
95407330f729Sjoerg case FK_ConversionFromPropertyFailed:
95417330f729Sjoerg OS << "conversion from property failed";
95427330f729Sjoerg break;
95437330f729Sjoerg
95447330f729Sjoerg case FK_TooManyInitsForScalar:
95457330f729Sjoerg OS << "too many initializers for scalar";
95467330f729Sjoerg break;
95477330f729Sjoerg
95487330f729Sjoerg case FK_ParenthesizedListInitForScalar:
95497330f729Sjoerg OS << "parenthesized list init for reference";
95507330f729Sjoerg break;
95517330f729Sjoerg
95527330f729Sjoerg case FK_ReferenceBindingToInitList:
95537330f729Sjoerg OS << "referencing binding to initializer list";
95547330f729Sjoerg break;
95557330f729Sjoerg
95567330f729Sjoerg case FK_InitListBadDestinationType:
95577330f729Sjoerg OS << "initializer list for non-aggregate, non-scalar type";
95587330f729Sjoerg break;
95597330f729Sjoerg
95607330f729Sjoerg case FK_UserConversionOverloadFailed:
95617330f729Sjoerg OS << "overloading failed for user-defined conversion";
95627330f729Sjoerg break;
95637330f729Sjoerg
95647330f729Sjoerg case FK_ConstructorOverloadFailed:
95657330f729Sjoerg OS << "constructor overloading failed";
95667330f729Sjoerg break;
95677330f729Sjoerg
95687330f729Sjoerg case FK_DefaultInitOfConst:
95697330f729Sjoerg OS << "default initialization of a const variable";
95707330f729Sjoerg break;
95717330f729Sjoerg
95727330f729Sjoerg case FK_Incomplete:
95737330f729Sjoerg OS << "initialization of incomplete type";
95747330f729Sjoerg break;
95757330f729Sjoerg
95767330f729Sjoerg case FK_ListInitializationFailed:
95777330f729Sjoerg OS << "list initialization checker failure";
95787330f729Sjoerg break;
95797330f729Sjoerg
95807330f729Sjoerg case FK_VariableLengthArrayHasInitializer:
95817330f729Sjoerg OS << "variable length array has an initializer";
95827330f729Sjoerg break;
95837330f729Sjoerg
95847330f729Sjoerg case FK_PlaceholderType:
95857330f729Sjoerg OS << "initializer expression isn't contextually valid";
95867330f729Sjoerg break;
95877330f729Sjoerg
95887330f729Sjoerg case FK_ListConstructorOverloadFailed:
95897330f729Sjoerg OS << "list constructor overloading failed";
95907330f729Sjoerg break;
95917330f729Sjoerg
95927330f729Sjoerg case FK_ExplicitConstructor:
95937330f729Sjoerg OS << "list copy initialization chose explicit constructor";
95947330f729Sjoerg break;
95957330f729Sjoerg }
95967330f729Sjoerg OS << '\n';
95977330f729Sjoerg return;
95987330f729Sjoerg }
95997330f729Sjoerg
96007330f729Sjoerg case DependentSequence:
96017330f729Sjoerg OS << "Dependent sequence\n";
96027330f729Sjoerg return;
96037330f729Sjoerg
96047330f729Sjoerg case NormalSequence:
96057330f729Sjoerg OS << "Normal sequence: ";
96067330f729Sjoerg break;
96077330f729Sjoerg }
96087330f729Sjoerg
96097330f729Sjoerg for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
96107330f729Sjoerg if (S != step_begin()) {
96117330f729Sjoerg OS << " -> ";
96127330f729Sjoerg }
96137330f729Sjoerg
96147330f729Sjoerg switch (S->Kind) {
96157330f729Sjoerg case SK_ResolveAddressOfOverloadedFunction:
96167330f729Sjoerg OS << "resolve address of overloaded function";
96177330f729Sjoerg break;
96187330f729Sjoerg
96197330f729Sjoerg case SK_CastDerivedToBaseRValue:
96207330f729Sjoerg OS << "derived-to-base (rvalue)";
96217330f729Sjoerg break;
96227330f729Sjoerg
96237330f729Sjoerg case SK_CastDerivedToBaseXValue:
96247330f729Sjoerg OS << "derived-to-base (xvalue)";
96257330f729Sjoerg break;
96267330f729Sjoerg
96277330f729Sjoerg case SK_CastDerivedToBaseLValue:
96287330f729Sjoerg OS << "derived-to-base (lvalue)";
96297330f729Sjoerg break;
96307330f729Sjoerg
96317330f729Sjoerg case SK_BindReference:
96327330f729Sjoerg OS << "bind reference to lvalue";
96337330f729Sjoerg break;
96347330f729Sjoerg
96357330f729Sjoerg case SK_BindReferenceToTemporary:
96367330f729Sjoerg OS << "bind reference to a temporary";
96377330f729Sjoerg break;
96387330f729Sjoerg
96397330f729Sjoerg case SK_FinalCopy:
96407330f729Sjoerg OS << "final copy in class direct-initialization";
96417330f729Sjoerg break;
96427330f729Sjoerg
96437330f729Sjoerg case SK_ExtraneousCopyToTemporary:
96447330f729Sjoerg OS << "extraneous C++03 copy to temporary";
96457330f729Sjoerg break;
96467330f729Sjoerg
96477330f729Sjoerg case SK_UserConversion:
96487330f729Sjoerg OS << "user-defined conversion via " << *S->Function.Function;
96497330f729Sjoerg break;
96507330f729Sjoerg
96517330f729Sjoerg case SK_QualificationConversionRValue:
96527330f729Sjoerg OS << "qualification conversion (rvalue)";
96537330f729Sjoerg break;
96547330f729Sjoerg
96557330f729Sjoerg case SK_QualificationConversionXValue:
96567330f729Sjoerg OS << "qualification conversion (xvalue)";
96577330f729Sjoerg break;
96587330f729Sjoerg
96597330f729Sjoerg case SK_QualificationConversionLValue:
96607330f729Sjoerg OS << "qualification conversion (lvalue)";
96617330f729Sjoerg break;
96627330f729Sjoerg
9663*e038c9c4Sjoerg case SK_FunctionReferenceConversion:
9664*e038c9c4Sjoerg OS << "function reference conversion";
9665*e038c9c4Sjoerg break;
9666*e038c9c4Sjoerg
96677330f729Sjoerg case SK_AtomicConversion:
96687330f729Sjoerg OS << "non-atomic-to-atomic conversion";
96697330f729Sjoerg break;
96707330f729Sjoerg
96717330f729Sjoerg case SK_ConversionSequence:
96727330f729Sjoerg OS << "implicit conversion sequence (";
96737330f729Sjoerg S->ICS->dump(); // FIXME: use OS
96747330f729Sjoerg OS << ")";
96757330f729Sjoerg break;
96767330f729Sjoerg
96777330f729Sjoerg case SK_ConversionSequenceNoNarrowing:
96787330f729Sjoerg OS << "implicit conversion sequence with narrowing prohibited (";
96797330f729Sjoerg S->ICS->dump(); // FIXME: use OS
96807330f729Sjoerg OS << ")";
96817330f729Sjoerg break;
96827330f729Sjoerg
96837330f729Sjoerg case SK_ListInitialization:
96847330f729Sjoerg OS << "list aggregate initialization";
96857330f729Sjoerg break;
96867330f729Sjoerg
96877330f729Sjoerg case SK_UnwrapInitList:
96887330f729Sjoerg OS << "unwrap reference initializer list";
96897330f729Sjoerg break;
96907330f729Sjoerg
96917330f729Sjoerg case SK_RewrapInitList:
96927330f729Sjoerg OS << "rewrap reference initializer list";
96937330f729Sjoerg break;
96947330f729Sjoerg
96957330f729Sjoerg case SK_ConstructorInitialization:
96967330f729Sjoerg OS << "constructor initialization";
96977330f729Sjoerg break;
96987330f729Sjoerg
96997330f729Sjoerg case SK_ConstructorInitializationFromList:
97007330f729Sjoerg OS << "list initialization via constructor";
97017330f729Sjoerg break;
97027330f729Sjoerg
97037330f729Sjoerg case SK_ZeroInitialization:
97047330f729Sjoerg OS << "zero initialization";
97057330f729Sjoerg break;
97067330f729Sjoerg
97077330f729Sjoerg case SK_CAssignment:
97087330f729Sjoerg OS << "C assignment";
97097330f729Sjoerg break;
97107330f729Sjoerg
97117330f729Sjoerg case SK_StringInit:
97127330f729Sjoerg OS << "string initialization";
97137330f729Sjoerg break;
97147330f729Sjoerg
97157330f729Sjoerg case SK_ObjCObjectConversion:
97167330f729Sjoerg OS << "Objective-C object conversion";
97177330f729Sjoerg break;
97187330f729Sjoerg
97197330f729Sjoerg case SK_ArrayLoopIndex:
97207330f729Sjoerg OS << "indexing for array initialization loop";
97217330f729Sjoerg break;
97227330f729Sjoerg
97237330f729Sjoerg case SK_ArrayLoopInit:
97247330f729Sjoerg OS << "array initialization loop";
97257330f729Sjoerg break;
97267330f729Sjoerg
97277330f729Sjoerg case SK_ArrayInit:
97287330f729Sjoerg OS << "array initialization";
97297330f729Sjoerg break;
97307330f729Sjoerg
97317330f729Sjoerg case SK_GNUArrayInit:
97327330f729Sjoerg OS << "array initialization (GNU extension)";
97337330f729Sjoerg break;
97347330f729Sjoerg
97357330f729Sjoerg case SK_ParenthesizedArrayInit:
97367330f729Sjoerg OS << "parenthesized array initialization";
97377330f729Sjoerg break;
97387330f729Sjoerg
97397330f729Sjoerg case SK_PassByIndirectCopyRestore:
97407330f729Sjoerg OS << "pass by indirect copy and restore";
97417330f729Sjoerg break;
97427330f729Sjoerg
97437330f729Sjoerg case SK_PassByIndirectRestore:
97447330f729Sjoerg OS << "pass by indirect restore";
97457330f729Sjoerg break;
97467330f729Sjoerg
97477330f729Sjoerg case SK_ProduceObjCObject:
97487330f729Sjoerg OS << "Objective-C object retension";
97497330f729Sjoerg break;
97507330f729Sjoerg
97517330f729Sjoerg case SK_StdInitializerList:
97527330f729Sjoerg OS << "std::initializer_list from initializer list";
97537330f729Sjoerg break;
97547330f729Sjoerg
97557330f729Sjoerg case SK_StdInitializerListConstructorCall:
97567330f729Sjoerg OS << "list initialization from std::initializer_list";
97577330f729Sjoerg break;
97587330f729Sjoerg
97597330f729Sjoerg case SK_OCLSamplerInit:
97607330f729Sjoerg OS << "OpenCL sampler_t from integer constant";
97617330f729Sjoerg break;
97627330f729Sjoerg
97637330f729Sjoerg case SK_OCLZeroOpaqueType:
97647330f729Sjoerg OS << "OpenCL opaque type from zero";
97657330f729Sjoerg break;
97667330f729Sjoerg }
97677330f729Sjoerg
97687330f729Sjoerg OS << " [" << S->Type.getAsString() << ']';
97697330f729Sjoerg }
97707330f729Sjoerg
97717330f729Sjoerg OS << '\n';
97727330f729Sjoerg }
97737330f729Sjoerg
dump() const97747330f729Sjoerg void InitializationSequence::dump() const {
97757330f729Sjoerg dump(llvm::errs());
97767330f729Sjoerg }
97777330f729Sjoerg
NarrowingErrs(const LangOptions & L)97787330f729Sjoerg static bool NarrowingErrs(const LangOptions &L) {
97797330f729Sjoerg return L.CPlusPlus11 &&
97807330f729Sjoerg (!L.MicrosoftExt || L.isCompatibleWithMSVC(LangOptions::MSVC2015));
97817330f729Sjoerg }
97827330f729Sjoerg
DiagnoseNarrowingInInitList(Sema & S,const ImplicitConversionSequence & ICS,QualType PreNarrowingType,QualType EntityType,const Expr * PostInit)97837330f729Sjoerg static void DiagnoseNarrowingInInitList(Sema &S,
97847330f729Sjoerg const ImplicitConversionSequence &ICS,
97857330f729Sjoerg QualType PreNarrowingType,
97867330f729Sjoerg QualType EntityType,
97877330f729Sjoerg const Expr *PostInit) {
97887330f729Sjoerg const StandardConversionSequence *SCS = nullptr;
97897330f729Sjoerg switch (ICS.getKind()) {
97907330f729Sjoerg case ImplicitConversionSequence::StandardConversion:
97917330f729Sjoerg SCS = &ICS.Standard;
97927330f729Sjoerg break;
97937330f729Sjoerg case ImplicitConversionSequence::UserDefinedConversion:
97947330f729Sjoerg SCS = &ICS.UserDefined.After;
97957330f729Sjoerg break;
97967330f729Sjoerg case ImplicitConversionSequence::AmbiguousConversion:
97977330f729Sjoerg case ImplicitConversionSequence::EllipsisConversion:
97987330f729Sjoerg case ImplicitConversionSequence::BadConversion:
97997330f729Sjoerg return;
98007330f729Sjoerg }
98017330f729Sjoerg
98027330f729Sjoerg // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
98037330f729Sjoerg APValue ConstantValue;
98047330f729Sjoerg QualType ConstantType;
98057330f729Sjoerg switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
98067330f729Sjoerg ConstantType)) {
98077330f729Sjoerg case NK_Not_Narrowing:
98087330f729Sjoerg case NK_Dependent_Narrowing:
98097330f729Sjoerg // No narrowing occurred.
98107330f729Sjoerg return;
98117330f729Sjoerg
98127330f729Sjoerg case NK_Type_Narrowing:
98137330f729Sjoerg // This was a floating-to-integer conversion, which is always considered a
98147330f729Sjoerg // narrowing conversion even if the value is a constant and can be
98157330f729Sjoerg // represented exactly as an integer.
98167330f729Sjoerg S.Diag(PostInit->getBeginLoc(), NarrowingErrs(S.getLangOpts())
98177330f729Sjoerg ? diag::ext_init_list_type_narrowing
98187330f729Sjoerg : diag::warn_init_list_type_narrowing)
98197330f729Sjoerg << PostInit->getSourceRange()
98207330f729Sjoerg << PreNarrowingType.getLocalUnqualifiedType()
98217330f729Sjoerg << EntityType.getLocalUnqualifiedType();
98227330f729Sjoerg break;
98237330f729Sjoerg
98247330f729Sjoerg case NK_Constant_Narrowing:
98257330f729Sjoerg // A constant value was narrowed.
98267330f729Sjoerg S.Diag(PostInit->getBeginLoc(),
98277330f729Sjoerg NarrowingErrs(S.getLangOpts())
98287330f729Sjoerg ? diag::ext_init_list_constant_narrowing
98297330f729Sjoerg : diag::warn_init_list_constant_narrowing)
98307330f729Sjoerg << PostInit->getSourceRange()
98317330f729Sjoerg << ConstantValue.getAsString(S.getASTContext(), ConstantType)
98327330f729Sjoerg << EntityType.getLocalUnqualifiedType();
98337330f729Sjoerg break;
98347330f729Sjoerg
98357330f729Sjoerg case NK_Variable_Narrowing:
98367330f729Sjoerg // A variable's value may have been narrowed.
98377330f729Sjoerg S.Diag(PostInit->getBeginLoc(),
98387330f729Sjoerg NarrowingErrs(S.getLangOpts())
98397330f729Sjoerg ? diag::ext_init_list_variable_narrowing
98407330f729Sjoerg : diag::warn_init_list_variable_narrowing)
98417330f729Sjoerg << PostInit->getSourceRange()
98427330f729Sjoerg << PreNarrowingType.getLocalUnqualifiedType()
98437330f729Sjoerg << EntityType.getLocalUnqualifiedType();
98447330f729Sjoerg break;
98457330f729Sjoerg }
98467330f729Sjoerg
98477330f729Sjoerg SmallString<128> StaticCast;
98487330f729Sjoerg llvm::raw_svector_ostream OS(StaticCast);
98497330f729Sjoerg OS << "static_cast<";
98507330f729Sjoerg if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
98517330f729Sjoerg // It's important to use the typedef's name if there is one so that the
98527330f729Sjoerg // fixit doesn't break code using types like int64_t.
98537330f729Sjoerg //
98547330f729Sjoerg // FIXME: This will break if the typedef requires qualification. But
98557330f729Sjoerg // getQualifiedNameAsString() includes non-machine-parsable components.
98567330f729Sjoerg OS << *TT->getDecl();
98577330f729Sjoerg } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
98587330f729Sjoerg OS << BT->getName(S.getLangOpts());
98597330f729Sjoerg else {
98607330f729Sjoerg // Oops, we didn't find the actual type of the variable. Don't emit a fixit
98617330f729Sjoerg // with a broken cast.
98627330f729Sjoerg return;
98637330f729Sjoerg }
98647330f729Sjoerg OS << ">(";
98657330f729Sjoerg S.Diag(PostInit->getBeginLoc(), diag::note_init_list_narrowing_silence)
98667330f729Sjoerg << PostInit->getSourceRange()
98677330f729Sjoerg << FixItHint::CreateInsertion(PostInit->getBeginLoc(), OS.str())
98687330f729Sjoerg << FixItHint::CreateInsertion(
98697330f729Sjoerg S.getLocForEndOfToken(PostInit->getEndLoc()), ")");
98707330f729Sjoerg }
98717330f729Sjoerg
98727330f729Sjoerg //===----------------------------------------------------------------------===//
98737330f729Sjoerg // Initialization helper functions
98747330f729Sjoerg //===----------------------------------------------------------------------===//
98757330f729Sjoerg bool
CanPerformCopyInitialization(const InitializedEntity & Entity,ExprResult Init)98767330f729Sjoerg Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
98777330f729Sjoerg ExprResult Init) {
98787330f729Sjoerg if (Init.isInvalid())
98797330f729Sjoerg return false;
98807330f729Sjoerg
98817330f729Sjoerg Expr *InitE = Init.get();
98827330f729Sjoerg assert(InitE && "No initialization expression");
98837330f729Sjoerg
98847330f729Sjoerg InitializationKind Kind =
98857330f729Sjoerg InitializationKind::CreateCopy(InitE->getBeginLoc(), SourceLocation());
98867330f729Sjoerg InitializationSequence Seq(*this, Entity, Kind, InitE);
98877330f729Sjoerg return !Seq.Failed();
98887330f729Sjoerg }
98897330f729Sjoerg
98907330f729Sjoerg ExprResult
PerformCopyInitialization(const InitializedEntity & Entity,SourceLocation EqualLoc,ExprResult Init,bool TopLevelOfInitList,bool AllowExplicit)98917330f729Sjoerg Sema::PerformCopyInitialization(const InitializedEntity &Entity,
98927330f729Sjoerg SourceLocation EqualLoc,
98937330f729Sjoerg ExprResult Init,
98947330f729Sjoerg bool TopLevelOfInitList,
98957330f729Sjoerg bool AllowExplicit) {
98967330f729Sjoerg if (Init.isInvalid())
98977330f729Sjoerg return ExprError();
98987330f729Sjoerg
98997330f729Sjoerg Expr *InitE = Init.get();
99007330f729Sjoerg assert(InitE && "No initialization expression?");
99017330f729Sjoerg
99027330f729Sjoerg if (EqualLoc.isInvalid())
99037330f729Sjoerg EqualLoc = InitE->getBeginLoc();
99047330f729Sjoerg
99057330f729Sjoerg InitializationKind Kind = InitializationKind::CreateCopy(
99067330f729Sjoerg InitE->getBeginLoc(), EqualLoc, AllowExplicit);
99077330f729Sjoerg InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
99087330f729Sjoerg
99097330f729Sjoerg // Prevent infinite recursion when performing parameter copy-initialization.
99107330f729Sjoerg const bool ShouldTrackCopy =
99117330f729Sjoerg Entity.isParameterKind() && Seq.isConstructorInitialization();
99127330f729Sjoerg if (ShouldTrackCopy) {
99137330f729Sjoerg if (llvm::find(CurrentParameterCopyTypes, Entity.getType()) !=
99147330f729Sjoerg CurrentParameterCopyTypes.end()) {
99157330f729Sjoerg Seq.SetOverloadFailure(
99167330f729Sjoerg InitializationSequence::FK_ConstructorOverloadFailed,
99177330f729Sjoerg OR_No_Viable_Function);
99187330f729Sjoerg
99197330f729Sjoerg // Try to give a meaningful diagnostic note for the problematic
99207330f729Sjoerg // constructor.
99217330f729Sjoerg const auto LastStep = Seq.step_end() - 1;
99227330f729Sjoerg assert(LastStep->Kind ==
99237330f729Sjoerg InitializationSequence::SK_ConstructorInitialization);
99247330f729Sjoerg const FunctionDecl *Function = LastStep->Function.Function;
99257330f729Sjoerg auto Candidate =
99267330f729Sjoerg llvm::find_if(Seq.getFailedCandidateSet(),
99277330f729Sjoerg [Function](const OverloadCandidate &Candidate) -> bool {
99287330f729Sjoerg return Candidate.Viable &&
99297330f729Sjoerg Candidate.Function == Function &&
99307330f729Sjoerg Candidate.Conversions.size() > 0;
99317330f729Sjoerg });
99327330f729Sjoerg if (Candidate != Seq.getFailedCandidateSet().end() &&
99337330f729Sjoerg Function->getNumParams() > 0) {
99347330f729Sjoerg Candidate->Viable = false;
99357330f729Sjoerg Candidate->FailureKind = ovl_fail_bad_conversion;
99367330f729Sjoerg Candidate->Conversions[0].setBad(BadConversionSequence::no_conversion,
99377330f729Sjoerg InitE,
99387330f729Sjoerg Function->getParamDecl(0)->getType());
99397330f729Sjoerg }
99407330f729Sjoerg }
99417330f729Sjoerg CurrentParameterCopyTypes.push_back(Entity.getType());
99427330f729Sjoerg }
99437330f729Sjoerg
99447330f729Sjoerg ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
99457330f729Sjoerg
99467330f729Sjoerg if (ShouldTrackCopy)
99477330f729Sjoerg CurrentParameterCopyTypes.pop_back();
99487330f729Sjoerg
99497330f729Sjoerg return Result;
99507330f729Sjoerg }
99517330f729Sjoerg
99527330f729Sjoerg /// Determine whether RD is, or is derived from, a specialization of CTD.
isOrIsDerivedFromSpecializationOf(CXXRecordDecl * RD,ClassTemplateDecl * CTD)99537330f729Sjoerg static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl *RD,
99547330f729Sjoerg ClassTemplateDecl *CTD) {
99557330f729Sjoerg auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) {
99567330f729Sjoerg auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Candidate);
99577330f729Sjoerg return !CTSD || !declaresSameEntity(CTSD->getSpecializedTemplate(), CTD);
99587330f729Sjoerg };
99597330f729Sjoerg return !(NotSpecialization(RD) && RD->forallBases(NotSpecialization));
99607330f729Sjoerg }
99617330f729Sjoerg
DeduceTemplateSpecializationFromInitializer(TypeSourceInfo * TSInfo,const InitializedEntity & Entity,const InitializationKind & Kind,MultiExprArg Inits)99627330f729Sjoerg QualType Sema::DeduceTemplateSpecializationFromInitializer(
99637330f729Sjoerg TypeSourceInfo *TSInfo, const InitializedEntity &Entity,
99647330f729Sjoerg const InitializationKind &Kind, MultiExprArg Inits) {
99657330f729Sjoerg auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>(
99667330f729Sjoerg TSInfo->getType()->getContainedDeducedType());
99677330f729Sjoerg assert(DeducedTST && "not a deduced template specialization type");
99687330f729Sjoerg
99697330f729Sjoerg auto TemplateName = DeducedTST->getTemplateName();
99707330f729Sjoerg if (TemplateName.isDependent())
9971*e038c9c4Sjoerg return SubstAutoType(TSInfo->getType(), Context.DependentTy);
99727330f729Sjoerg
99737330f729Sjoerg // We can only perform deduction for class templates.
99747330f729Sjoerg auto *Template =
99757330f729Sjoerg dyn_cast_or_null<ClassTemplateDecl>(TemplateName.getAsTemplateDecl());
99767330f729Sjoerg if (!Template) {
99777330f729Sjoerg Diag(Kind.getLocation(),
99787330f729Sjoerg diag::err_deduced_non_class_template_specialization_type)
99797330f729Sjoerg << (int)getTemplateNameKindForDiagnostics(TemplateName) << TemplateName;
99807330f729Sjoerg if (auto *TD = TemplateName.getAsTemplateDecl())
99817330f729Sjoerg Diag(TD->getLocation(), diag::note_template_decl_here);
99827330f729Sjoerg return QualType();
99837330f729Sjoerg }
99847330f729Sjoerg
99857330f729Sjoerg // Can't deduce from dependent arguments.
99867330f729Sjoerg if (Expr::hasAnyTypeDependentArguments(Inits)) {
99877330f729Sjoerg Diag(TSInfo->getTypeLoc().getBeginLoc(),
99887330f729Sjoerg diag::warn_cxx14_compat_class_template_argument_deduction)
99897330f729Sjoerg << TSInfo->getTypeLoc().getSourceRange() << 0;
9990*e038c9c4Sjoerg return SubstAutoType(TSInfo->getType(), Context.DependentTy);
99917330f729Sjoerg }
99927330f729Sjoerg
99937330f729Sjoerg // FIXME: Perform "exact type" matching first, per CWG discussion?
99947330f729Sjoerg // Or implement this via an implied 'T(T) -> T' deduction guide?
99957330f729Sjoerg
99967330f729Sjoerg // FIXME: Do we need/want a std::initializer_list<T> special case?
99977330f729Sjoerg
99987330f729Sjoerg // Look up deduction guides, including those synthesized from constructors.
99997330f729Sjoerg //
100007330f729Sjoerg // C++1z [over.match.class.deduct]p1:
100017330f729Sjoerg // A set of functions and function templates is formed comprising:
100027330f729Sjoerg // - For each constructor of the class template designated by the
100037330f729Sjoerg // template-name, a function template [...]
100047330f729Sjoerg // - For each deduction-guide, a function or function template [...]
100057330f729Sjoerg DeclarationNameInfo NameInfo(
100067330f729Sjoerg Context.DeclarationNames.getCXXDeductionGuideName(Template),
100077330f729Sjoerg TSInfo->getTypeLoc().getEndLoc());
100087330f729Sjoerg LookupResult Guides(*this, NameInfo, LookupOrdinaryName);
100097330f729Sjoerg LookupQualifiedName(Guides, Template->getDeclContext());
100107330f729Sjoerg
100117330f729Sjoerg // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't
100127330f729Sjoerg // clear on this, but they're not found by name so access does not apply.
100137330f729Sjoerg Guides.suppressDiagnostics();
100147330f729Sjoerg
100157330f729Sjoerg // Figure out if this is list-initialization.
100167330f729Sjoerg InitListExpr *ListInit =
100177330f729Sjoerg (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct)
100187330f729Sjoerg ? dyn_cast<InitListExpr>(Inits[0])
100197330f729Sjoerg : nullptr;
100207330f729Sjoerg
100217330f729Sjoerg // C++1z [over.match.class.deduct]p1:
100227330f729Sjoerg // Initialization and overload resolution are performed as described in
100237330f729Sjoerg // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list]
100247330f729Sjoerg // (as appropriate for the type of initialization performed) for an object
100257330f729Sjoerg // of a hypothetical class type, where the selected functions and function
100267330f729Sjoerg // templates are considered to be the constructors of that class type
100277330f729Sjoerg //
100287330f729Sjoerg // Since we know we're initializing a class type of a type unrelated to that
100297330f729Sjoerg // of the initializer, this reduces to something fairly reasonable.
100307330f729Sjoerg OverloadCandidateSet Candidates(Kind.getLocation(),
100317330f729Sjoerg OverloadCandidateSet::CSK_Normal);
100327330f729Sjoerg OverloadCandidateSet::iterator Best;
100337330f729Sjoerg
100347330f729Sjoerg bool HasAnyDeductionGuide = false;
100357330f729Sjoerg bool AllowExplicit = !Kind.isCopyInit() || ListInit;
100367330f729Sjoerg
100377330f729Sjoerg auto tryToResolveOverload =
100387330f729Sjoerg [&](bool OnlyListConstructors) -> OverloadingResult {
100397330f729Sjoerg Candidates.clear(OverloadCandidateSet::CSK_Normal);
100407330f729Sjoerg HasAnyDeductionGuide = false;
100417330f729Sjoerg
100427330f729Sjoerg for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) {
100437330f729Sjoerg NamedDecl *D = (*I)->getUnderlyingDecl();
100447330f729Sjoerg if (D->isInvalidDecl())
100457330f729Sjoerg continue;
100467330f729Sjoerg
100477330f729Sjoerg auto *TD = dyn_cast<FunctionTemplateDecl>(D);
100487330f729Sjoerg auto *GD = dyn_cast_or_null<CXXDeductionGuideDecl>(
100497330f729Sjoerg TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D));
100507330f729Sjoerg if (!GD)
100517330f729Sjoerg continue;
100527330f729Sjoerg
100537330f729Sjoerg if (!GD->isImplicit())
100547330f729Sjoerg HasAnyDeductionGuide = true;
100557330f729Sjoerg
100567330f729Sjoerg // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class)
100577330f729Sjoerg // For copy-initialization, the candidate functions are all the
100587330f729Sjoerg // converting constructors (12.3.1) of that class.
100597330f729Sjoerg // C++ [over.match.copy]p1: (non-list copy-initialization from class)
100607330f729Sjoerg // The converting constructors of T are candidate functions.
100617330f729Sjoerg if (!AllowExplicit) {
10062*e038c9c4Sjoerg // Overload resolution checks whether the deduction guide is declared
10063*e038c9c4Sjoerg // explicit for us.
100647330f729Sjoerg
100657330f729Sjoerg // When looking for a converting constructor, deduction guides that
100667330f729Sjoerg // could never be called with one argument are not interesting to
100677330f729Sjoerg // check or note.
100687330f729Sjoerg if (GD->getMinRequiredArguments() > 1 ||
100697330f729Sjoerg (GD->getNumParams() == 0 && !GD->isVariadic()))
100707330f729Sjoerg continue;
100717330f729Sjoerg }
100727330f729Sjoerg
100737330f729Sjoerg // C++ [over.match.list]p1.1: (first phase list initialization)
100747330f729Sjoerg // Initially, the candidate functions are the initializer-list
100757330f729Sjoerg // constructors of the class T
100767330f729Sjoerg if (OnlyListConstructors && !isInitListConstructor(GD))
100777330f729Sjoerg continue;
100787330f729Sjoerg
100797330f729Sjoerg // C++ [over.match.list]p1.2: (second phase list initialization)
100807330f729Sjoerg // the candidate functions are all the constructors of the class T
100817330f729Sjoerg // C++ [over.match.ctor]p1: (all other cases)
100827330f729Sjoerg // the candidate functions are all the constructors of the class of
100837330f729Sjoerg // the object being initialized
100847330f729Sjoerg
100857330f729Sjoerg // C++ [over.best.ics]p4:
100867330f729Sjoerg // When [...] the constructor [...] is a candidate by
100877330f729Sjoerg // - [over.match.copy] (in all cases)
100887330f729Sjoerg // FIXME: The "second phase of [over.match.list] case can also
100897330f729Sjoerg // theoretically happen here, but it's not clear whether we can
100907330f729Sjoerg // ever have a parameter of the right type.
100917330f729Sjoerg bool SuppressUserConversions = Kind.isCopyInit();
100927330f729Sjoerg
100937330f729Sjoerg if (TD)
100947330f729Sjoerg AddTemplateOverloadCandidate(TD, I.getPair(), /*ExplicitArgs*/ nullptr,
100957330f729Sjoerg Inits, Candidates, SuppressUserConversions,
100967330f729Sjoerg /*PartialOverloading*/ false,
100977330f729Sjoerg AllowExplicit);
100987330f729Sjoerg else
100997330f729Sjoerg AddOverloadCandidate(GD, I.getPair(), Inits, Candidates,
101007330f729Sjoerg SuppressUserConversions,
101017330f729Sjoerg /*PartialOverloading*/ false, AllowExplicit);
101027330f729Sjoerg }
101037330f729Sjoerg return Candidates.BestViableFunction(*this, Kind.getLocation(), Best);
101047330f729Sjoerg };
101057330f729Sjoerg
101067330f729Sjoerg OverloadingResult Result = OR_No_Viable_Function;
101077330f729Sjoerg
101087330f729Sjoerg // C++11 [over.match.list]p1, per DR1467: for list-initialization, first
101097330f729Sjoerg // try initializer-list constructors.
101107330f729Sjoerg if (ListInit) {
101117330f729Sjoerg bool TryListConstructors = true;
101127330f729Sjoerg
101137330f729Sjoerg // Try list constructors unless the list is empty and the class has one or
101147330f729Sjoerg // more default constructors, in which case those constructors win.
101157330f729Sjoerg if (!ListInit->getNumInits()) {
101167330f729Sjoerg for (NamedDecl *D : Guides) {
101177330f729Sjoerg auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl());
101187330f729Sjoerg if (FD && FD->getMinRequiredArguments() == 0) {
101197330f729Sjoerg TryListConstructors = false;
101207330f729Sjoerg break;
101217330f729Sjoerg }
101227330f729Sjoerg }
101237330f729Sjoerg } else if (ListInit->getNumInits() == 1) {
101247330f729Sjoerg // C++ [over.match.class.deduct]:
101257330f729Sjoerg // As an exception, the first phase in [over.match.list] (considering
101267330f729Sjoerg // initializer-list constructors) is omitted if the initializer list
101277330f729Sjoerg // consists of a single expression of type cv U, where U is a
101287330f729Sjoerg // specialization of C or a class derived from a specialization of C.
101297330f729Sjoerg Expr *E = ListInit->getInit(0);
101307330f729Sjoerg auto *RD = E->getType()->getAsCXXRecordDecl();
101317330f729Sjoerg if (!isa<InitListExpr>(E) && RD &&
101327330f729Sjoerg isCompleteType(Kind.getLocation(), E->getType()) &&
101337330f729Sjoerg isOrIsDerivedFromSpecializationOf(RD, Template))
101347330f729Sjoerg TryListConstructors = false;
101357330f729Sjoerg }
101367330f729Sjoerg
101377330f729Sjoerg if (TryListConstructors)
101387330f729Sjoerg Result = tryToResolveOverload(/*OnlyListConstructor*/true);
101397330f729Sjoerg // Then unwrap the initializer list and try again considering all
101407330f729Sjoerg // constructors.
101417330f729Sjoerg Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits());
101427330f729Sjoerg }
101437330f729Sjoerg
101447330f729Sjoerg // If list-initialization fails, or if we're doing any other kind of
101457330f729Sjoerg // initialization, we (eventually) consider constructors.
101467330f729Sjoerg if (Result == OR_No_Viable_Function)
101477330f729Sjoerg Result = tryToResolveOverload(/*OnlyListConstructor*/false);
101487330f729Sjoerg
101497330f729Sjoerg switch (Result) {
101507330f729Sjoerg case OR_Ambiguous:
101517330f729Sjoerg // FIXME: For list-initialization candidates, it'd usually be better to
101527330f729Sjoerg // list why they were not viable when given the initializer list itself as
101537330f729Sjoerg // an argument.
101547330f729Sjoerg Candidates.NoteCandidates(
101557330f729Sjoerg PartialDiagnosticAt(
101567330f729Sjoerg Kind.getLocation(),
101577330f729Sjoerg PDiag(diag::err_deduced_class_template_ctor_ambiguous)
101587330f729Sjoerg << TemplateName),
101597330f729Sjoerg *this, OCD_AmbiguousCandidates, Inits);
101607330f729Sjoerg return QualType();
101617330f729Sjoerg
101627330f729Sjoerg case OR_No_Viable_Function: {
101637330f729Sjoerg CXXRecordDecl *Primary =
101647330f729Sjoerg cast<ClassTemplateDecl>(Template)->getTemplatedDecl();
101657330f729Sjoerg bool Complete =
101667330f729Sjoerg isCompleteType(Kind.getLocation(), Context.getTypeDeclType(Primary));
101677330f729Sjoerg Candidates.NoteCandidates(
101687330f729Sjoerg PartialDiagnosticAt(
101697330f729Sjoerg Kind.getLocation(),
101707330f729Sjoerg PDiag(Complete ? diag::err_deduced_class_template_ctor_no_viable
101717330f729Sjoerg : diag::err_deduced_class_template_incomplete)
101727330f729Sjoerg << TemplateName << !Guides.empty()),
101737330f729Sjoerg *this, OCD_AllCandidates, Inits);
101747330f729Sjoerg return QualType();
101757330f729Sjoerg }
101767330f729Sjoerg
101777330f729Sjoerg case OR_Deleted: {
101787330f729Sjoerg Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted)
101797330f729Sjoerg << TemplateName;
101807330f729Sjoerg NoteDeletedFunction(Best->Function);
101817330f729Sjoerg return QualType();
101827330f729Sjoerg }
101837330f729Sjoerg
101847330f729Sjoerg case OR_Success:
101857330f729Sjoerg // C++ [over.match.list]p1:
101867330f729Sjoerg // In copy-list-initialization, if an explicit constructor is chosen, the
101877330f729Sjoerg // initialization is ill-formed.
101887330f729Sjoerg if (Kind.isCopyInit() && ListInit &&
101897330f729Sjoerg cast<CXXDeductionGuideDecl>(Best->Function)->isExplicit()) {
101907330f729Sjoerg bool IsDeductionGuide = !Best->Function->isImplicit();
101917330f729Sjoerg Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit)
101927330f729Sjoerg << TemplateName << IsDeductionGuide;
101937330f729Sjoerg Diag(Best->Function->getLocation(),
101947330f729Sjoerg diag::note_explicit_ctor_deduction_guide_here)
101957330f729Sjoerg << IsDeductionGuide;
101967330f729Sjoerg return QualType();
101977330f729Sjoerg }
101987330f729Sjoerg
101997330f729Sjoerg // Make sure we didn't select an unusable deduction guide, and mark it
102007330f729Sjoerg // as referenced.
102017330f729Sjoerg DiagnoseUseOfDecl(Best->Function, Kind.getLocation());
102027330f729Sjoerg MarkFunctionReferenced(Kind.getLocation(), Best->Function);
102037330f729Sjoerg break;
102047330f729Sjoerg }
102057330f729Sjoerg
102067330f729Sjoerg // C++ [dcl.type.class.deduct]p1:
102077330f729Sjoerg // The placeholder is replaced by the return type of the function selected
102087330f729Sjoerg // by overload resolution for class template deduction.
102097330f729Sjoerg QualType DeducedType =
102107330f729Sjoerg SubstAutoType(TSInfo->getType(), Best->Function->getReturnType());
102117330f729Sjoerg Diag(TSInfo->getTypeLoc().getBeginLoc(),
102127330f729Sjoerg diag::warn_cxx14_compat_class_template_argument_deduction)
102137330f729Sjoerg << TSInfo->getTypeLoc().getSourceRange() << 1 << DeducedType;
102147330f729Sjoerg
102157330f729Sjoerg // Warn if CTAD was used on a type that does not have any user-defined
102167330f729Sjoerg // deduction guides.
102177330f729Sjoerg if (!HasAnyDeductionGuide) {
102187330f729Sjoerg Diag(TSInfo->getTypeLoc().getBeginLoc(),
102197330f729Sjoerg diag::warn_ctad_maybe_unsupported)
102207330f729Sjoerg << TemplateName;
102217330f729Sjoerg Diag(Template->getLocation(), diag::note_suppress_ctad_maybe_unsupported);
102227330f729Sjoerg }
102237330f729Sjoerg
102247330f729Sjoerg return DeducedType;
102257330f729Sjoerg }
10226