diff options
Diffstat (limited to 'clang/lib/Sema')
| -rw-r--r-- | clang/lib/Sema/Sema.cpp | 42 | ||||
| -rw-r--r-- | clang/lib/Sema/SemaAMDGPU.cpp | 2 | ||||
| -rw-r--r-- | clang/lib/Sema/SemaBoundsSafety.cpp | 23 | ||||
| -rw-r--r-- | clang/lib/Sema/SemaConcept.cpp | 58 | ||||
| -rw-r--r-- | clang/lib/Sema/SemaDecl.cpp | 11 | ||||
| -rw-r--r-- | clang/lib/Sema/SemaExpr.cpp | 20 | ||||
| -rw-r--r-- | clang/lib/Sema/SemaTemplate.cpp | 30 | ||||
| -rw-r--r-- | clang/lib/Sema/SemaTemplateDeduction.cpp | 130 | ||||
| -rw-r--r-- | clang/lib/Sema/SemaTemplateDeductionGuide.cpp | 1 | ||||
| -rw-r--r-- | clang/lib/Sema/SemaTemplateInstantiate.cpp | 182 | ||||
| -rw-r--r-- | clang/lib/Sema/SemaTemplateInstantiateDecl.cpp | 9 | ||||
| -rw-r--r-- | clang/lib/Sema/SemaTemplateVariadic.cpp | 11 | ||||
| -rw-r--r-- | clang/lib/Sema/TreeTransform.h | 25 |
13 files changed, 222 insertions, 322 deletions
diff --git a/clang/lib/Sema/Sema.cpp b/clang/lib/Sema/Sema.cpp index 23bf7f2..46addea 100644 --- a/clang/lib/Sema/Sema.cpp +++ b/clang/lib/Sema/Sema.cpp @@ -321,9 +321,8 @@ Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, static_cast<unsigned>(ComparisonCategoryType::Last) + 1), StdSourceLocationImplDecl(nullptr), CXXTypeInfoDecl(nullptr), GlobalNewDeleteDeclared(false), DisableTypoCorrection(false), - TyposCorrected(0), IsBuildingRecoveryCallExpr(false), NumSFINAEErrors(0), - AccessCheckingSFINAE(false), CurrentInstantiationScope(nullptr), - InNonInstantiationSFINAEContext(false), NonInstantiationEntries(0), + TyposCorrected(0), IsBuildingRecoveryCallExpr(false), + CurrentInstantiationScope(nullptr), NonInstantiationEntries(0), ArgPackSubstIndex(std::nullopt), SatisfactionCache(Context) { assert(pp.TUKind == TUKind); TUScope = nullptr; @@ -670,7 +669,9 @@ void Sema::addExternalSource(IntrusiveRefCntPtr<ExternalSemaSource> E) { void Sema::PrintStats() const { llvm::errs() << "\n*** Semantic Analysis Stats:\n"; - llvm::errs() << NumSFINAEErrors << " SFINAE diagnostics trapped.\n"; + if (SFINAETrap *Trap = getSFINAEContext()) + llvm::errs() << int(Trap->hasErrorOccurred()) + << " SFINAE diagnostics trapped.\n"; BumpAlloc.PrintStats(); AnalysisWarnings.PrintStats(); @@ -1681,7 +1682,8 @@ void Sema::EmitDiagnostic(unsigned DiagID, const DiagnosticBuilder &DB) { // issue I am not seeing yet), then there should at least be a clarifying // comment somewhere. Diagnostic DiagInfo(&Diags, DB); - if (std::optional<TemplateDeductionInfo *> Info = isSFINAEContext()) { + if (SFINAETrap *Trap = getSFINAEContext()) { + sema::TemplateDeductionInfo *Info = Trap->getDeductionInfo(); switch (DiagnosticIDs::getDiagnosticSFINAEResponse(DiagInfo.getID())) { case DiagnosticIDs::SFINAE_Report: // We'll report the diagnostic below. @@ -1690,37 +1692,37 @@ void Sema::EmitDiagnostic(unsigned DiagID, const DiagnosticBuilder &DB) { case DiagnosticIDs::SFINAE_SubstitutionFailure: // Count this failure so that we know that template argument deduction // has failed. - ++NumSFINAEErrors; + Trap->setErrorOccurred(); // Make a copy of this suppressed diagnostic and store it with the // template-deduction information. - if (*Info && !(*Info)->hasSFINAEDiagnostic()) { - (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(), - PartialDiagnostic(DiagInfo, Context.getDiagAllocator())); - } + if (Info && !Info->hasSFINAEDiagnostic()) + Info->addSFINAEDiagnostic( + DiagInfo.getLocation(), + PartialDiagnostic(DiagInfo, Context.getDiagAllocator())); Diags.setLastDiagnosticIgnored(true); return; case DiagnosticIDs::SFINAE_AccessControl: { // Per C++ Core Issue 1170, access control is part of SFINAE. - // Additionally, the AccessCheckingSFINAE flag can be used to temporarily + // Additionally, the WithAccessChecking flag can be used to temporarily // make access control a part of SFINAE for the purposes of checking // type traits. - if (!AccessCheckingSFINAE && !getLangOpts().CPlusPlus11) + if (!Trap->withAccessChecking() && !getLangOpts().CPlusPlus11) break; SourceLocation Loc = DiagInfo.getLocation(); // Suppress this diagnostic. - ++NumSFINAEErrors; + Trap->setErrorOccurred(); // Make a copy of this suppressed diagnostic and store it with the // template-deduction information. - if (*Info && !(*Info)->hasSFINAEDiagnostic()) { - (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(), - PartialDiagnostic(DiagInfo, Context.getDiagAllocator())); - } + if (Info && !Info->hasSFINAEDiagnostic()) + Info->addSFINAEDiagnostic( + DiagInfo.getLocation(), + PartialDiagnostic(DiagInfo, Context.getDiagAllocator())); Diags.setLastDiagnosticIgnored(true); @@ -1740,13 +1742,13 @@ void Sema::EmitDiagnostic(unsigned DiagID, const DiagnosticBuilder &DB) { return; // Make a copy of this suppressed diagnostic and store it with the // template-deduction information; - if (*Info) { - (*Info)->addSuppressedDiagnostic( + if (Info) { + Info->addSuppressedDiagnostic( DiagInfo.getLocation(), PartialDiagnostic(DiagInfo, Context.getDiagAllocator())); if (!Diags.getDiagnosticIDs()->isNote(DiagID)) PrintContextStack([Info](SourceLocation Loc, PartialDiagnostic PD) { - (*Info)->addSuppressedDiagnostic(Loc, std::move(PD)); + Info->addSuppressedDiagnostic(Loc, std::move(PD)); }); } diff --git a/clang/lib/Sema/SemaAMDGPU.cpp b/clang/lib/Sema/SemaAMDGPU.cpp index 139c4ab..cece220 100644 --- a/clang/lib/Sema/SemaAMDGPU.cpp +++ b/clang/lib/Sema/SemaAMDGPU.cpp @@ -558,6 +558,8 @@ AMDGPUMaxNumWorkGroupsAttr *SemaAMDGPU::CreateAMDGPUMaxNumWorkGroupsAttr( const AttributeCommonInfo &CI, Expr *XExpr, Expr *YExpr, Expr *ZExpr) { ASTContext &Context = getASTContext(); AMDGPUMaxNumWorkGroupsAttr TmpAttr(Context, CI, XExpr, YExpr, ZExpr); + assert(!SemaRef.isSFINAEContext() && + "Can't produce SFINAE diagnostic pointing to temporary attribute"); if (checkAMDGPUMaxNumWorkGroupsArguments(SemaRef, XExpr, YExpr, ZExpr, TmpAttr)) diff --git a/clang/lib/Sema/SemaBoundsSafety.cpp b/clang/lib/Sema/SemaBoundsSafety.cpp index 39ab136..de9adf8 100644 --- a/clang/lib/Sema/SemaBoundsSafety.cpp +++ b/clang/lib/Sema/SemaBoundsSafety.cpp @@ -132,9 +132,23 @@ bool Sema::CheckCountedByAttrOnField(FieldDecl *FD, Expr *E, bool CountInBytes, // `BoundsSafetyCheckUseOfCountAttrPtr` // // * When the pointee type is always an incomplete type (e.g. - // `void`) the attribute is disallowed by this method because we know the - // type can never be completed so there's no reason to allow it. - InvalidTypeKind = CountedByInvalidPointeeTypeKind::INCOMPLETE; + // `void` in strict C mode) the attribute is disallowed by this method + // because we know the type can never be completed so there's no reason + // to allow it. + // + // Exception: void has an implicit size of 1 byte for pointer arithmetic + // (following GNU convention). Therefore, counted_by on void* is allowed + // and behaves equivalently to sized_by (treating the count as bytes). + bool IsVoidPtr = PointeeTy->isVoidType(); + if (IsVoidPtr) { + // Emit a warning that this is a GNU extension. + Diag(FD->getBeginLoc(), diag::ext_gnu_counted_by_void_ptr) << Kind; + Diag(FD->getBeginLoc(), diag::note_gnu_counted_by_void_ptr_use_sized_by) + << Kind; + assert(InvalidTypeKind == CountedByInvalidPointeeTypeKind::VALID); + } else { + InvalidTypeKind = CountedByInvalidPointeeTypeKind::INCOMPLETE; + } } else if (PointeeTy->isSizelessType()) { InvalidTypeKind = CountedByInvalidPointeeTypeKind::SIZELESS; } else if (PointeeTy->isFunctionType()) { @@ -272,6 +286,9 @@ GetCountedByAttrOnIncompletePointee(QualType Ty, NamedDecl **ND) { if (!PointeeTy->isIncompleteType(ND)) return {}; + if (PointeeTy->isVoidType()) + return {}; + return {CATy, PointeeTy}; } diff --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp index fb4d0b45..883e341 100644 --- a/clang/lib/Sema/SemaConcept.cpp +++ b/clang/lib/Sema/SemaConcept.cpp @@ -526,12 +526,12 @@ ExprResult ConstraintSatisfactionChecker::EvaluateAtomicConstraint( S, AtomicExpr->getBeginLoc(), Sema::InstantiatingTemplate::ConstraintSubstitution{}, // FIXME: improve const-correctness of InstantiatingTemplate - const_cast<NamedDecl *>(Template), Info, AtomicExpr->getSourceRange()); + const_cast<NamedDecl *>(Template), AtomicExpr->getSourceRange()); if (Inst.isInvalid()) return ExprError(); // We do not want error diagnostics escaping here. - Sema::SFINAETrap Trap(S); + Sema::SFINAETrap Trap(S, Info); SubstitutedExpression = S.SubstConstraintExpr(const_cast<Expr *>(AtomicExpr), MLTAL); @@ -599,16 +599,15 @@ ConstraintSatisfactionChecker::SubstitutionInTemplateArguments( return MultiLevelTemplateArgumentList(); TemplateDeductionInfo Info(Constraint.getBeginLoc()); + Sema::SFINAETrap Trap(S, Info); Sema::InstantiatingTemplate Inst( S, Constraint.getBeginLoc(), Sema::InstantiatingTemplate::ConstraintSubstitution{}, // FIXME: improve const-correctness of InstantiatingTemplate - const_cast<NamedDecl *>(Template), Info, Constraint.getSourceRange()); + const_cast<NamedDecl *>(Template), Constraint.getSourceRange()); if (Inst.isInvalid()) return std::nullopt; - Sema::SFINAETrap Trap(S); - TemplateArgumentListInfo SubstArgs; Sema::ArgPackSubstIndexRAII SubstIndex( S, Constraint.getPackSubstitutionIndex() @@ -778,9 +777,6 @@ ConstraintSatisfactionChecker::EvaluateFoldExpandedConstraintSize( const FoldExpandedConstraint &FE, const MultiLevelTemplateArgumentList &MLTAL) { - // We should ignore errors in the presence of packs of different size. - Sema::SFINAETrap Trap(S); - Expr *Pattern = const_cast<Expr *>(FE.getPattern()); SmallVector<UnexpandedParameterPack, 2> Unexpanded; @@ -792,18 +788,12 @@ ConstraintSatisfactionChecker::EvaluateFoldExpandedConstraintSize( if (S.CheckParameterPacksForExpansion( Pattern->getExprLoc(), Pattern->getSourceRange(), Unexpanded, MLTAL, /*FailOnPackProducingTemplates=*/false, Expand, RetainExpansion, - NumExpansions) || + NumExpansions, /*Diagnose=*/false) || !Expand || RetainExpansion) return std::nullopt; - if (NumExpansions && S.getLangOpts().BracketDepth < *NumExpansions) { - S.Diag(Pattern->getExprLoc(), - clang::diag::err_fold_expression_limit_exceeded) - << *NumExpansions << S.getLangOpts().BracketDepth - << Pattern->getSourceRange(); - S.Diag(Pattern->getExprLoc(), diag::note_bracket_depth); + if (NumExpansions && S.getLangOpts().BracketDepth < *NumExpansions) return std::nullopt; - } return NumExpansions; } @@ -921,7 +911,6 @@ ExprResult ConstraintSatisfactionChecker::EvaluateSlow( return ExprError(); } - Sema::SFINAETrap Trap(S); Sema::ArgPackSubstIndexRAII SubstIndex( S, Constraint.getPackSubstitutionIndex() ? Constraint.getPackSubstitutionIndex() @@ -930,9 +919,10 @@ ExprResult ConstraintSatisfactionChecker::EvaluateSlow( const ASTTemplateArgumentListInfo *Ori = ConceptId->getTemplateArgsAsWritten(); TemplateDeductionInfo Info(TemplateNameLoc); - Sema::InstantiatingTemplate _( + Sema::SFINAETrap Trap(S, Info); + Sema::InstantiatingTemplate _2( S, TemplateNameLoc, Sema::InstantiatingTemplate::ConstraintSubstitution{}, - const_cast<NamedDecl *>(Template), Info, Constraint.getSourceRange()); + const_cast<NamedDecl *>(Template), Constraint.getSourceRange()); TemplateArgumentListInfo OutArgs(Ori->LAngleLoc, Ori->RAngleLoc); if (S.SubstTemplateArguments(Ori->arguments(), *SubstitutedArgs, OutArgs) || @@ -1142,13 +1132,21 @@ static bool CheckConstraintSatisfaction( if (TemplateArgsLists.getNumLevels() != 0) Args = TemplateArgsLists.getInnermost(); - std::optional<Sema::InstantiatingTemplate> SynthesisContext; - if (!TopLevelConceptId) { - SynthesisContext.emplace(S, TemplateIDRange.getBegin(), - Sema::InstantiatingTemplate::ConstraintsCheck{}, - const_cast<NamedDecl *>(Template), Args, + struct SynthesisContextPair { + Sema::InstantiatingTemplate Inst; + Sema::NonSFINAEContext NSC; + SynthesisContextPair(Sema &S, NamedDecl *Template, + ArrayRef<TemplateArgument> TemplateArgs, + SourceRange InstantiationRange) + : Inst(S, InstantiationRange.getBegin(), + Sema::InstantiatingTemplate::ConstraintsCheck{}, Template, + TemplateArgs, InstantiationRange), + NSC(S) {} + }; + std::optional<SynthesisContextPair> SynthesisContext; + if (!TopLevelConceptId) + SynthesisContext.emplace(S, const_cast<NamedDecl *>(Template), Args, TemplateIDRange); - } const NormalizedConstraint *C = S.getNormalizedAssociatedConstraints(Template, AssociatedConstraints); @@ -1478,8 +1476,7 @@ static const Expr *SubstituteConstraintExpressionWithoutSatisfaction( if (MLTAL.getNumSubstitutedLevels() == 0) return ConstrExpr; - Sema::SFINAETrap SFINAE(S); - + Sema::NonSFINAEContext _(S); Sema::InstantiatingTemplate Inst( S, DeclInfo.getLocation(), Sema::InstantiatingTemplate::ConstraintNormalization{}, @@ -1554,7 +1551,7 @@ static const Expr *SubstituteConstraintExpressionWithoutSatisfaction( Sema::ReuseLambdaContextDecl); ExprResult SubstConstr = S.SubstConstraintExprWithoutSatisfaction( const_cast<clang::Expr *>(ConstrExpr), MLTAL); - if (SFINAE.hasErrorOccurred() || !SubstConstr.isUsable()) + if (!SubstConstr.isUsable()) return nullptr; return SubstConstr.get(); } @@ -2104,6 +2101,7 @@ bool SubstituteParameterMappings::substitute( InstLocBegin = SR.getBegin(); InstLocEnd = SR.getEnd(); } + Sema::NonSFINAEContext _(SemaRef); Sema::InstantiatingTemplate Inst( SemaRef, InstLocBegin, Sema::InstantiatingTemplate::ParameterMappingSubstitution{}, @@ -2171,6 +2169,7 @@ bool SubstituteParameterMappings::substitute(ConceptIdConstraint &CC) { InstLocBegin = SR.getBegin(); InstLocEnd = SR.getEnd(); } + Sema::NonSFINAEContext _(SemaRef); // This is useful for name lookup across modules; see Sema::getLookupModules. Sema::InstantiatingTemplate Inst( SemaRef, InstLocBegin, @@ -2311,6 +2310,7 @@ NormalizedConstraint *NormalizedConstraint::fromConstraintExpr( } else if (auto *CSE = dyn_cast<const ConceptSpecializationExpr>(E)) { NormalizedConstraint *SubNF; { + Sema::NonSFINAEContext _(S); Sema::InstantiatingTemplate Inst( S, CSE->getExprLoc(), Sema::InstantiatingTemplate::ConstraintNormalization{}, @@ -2546,8 +2546,6 @@ bool Sema::MaybeEmitAmbiguousAtomicConstraintsDiagnostic( }; { - // The subsumption checks might cause diagnostics - SFINAETrap Trap(*this); auto *Normalized1 = getNormalizedAssociatedConstraints(D1, AC1); if (!Normalized1) return false; diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp index fc3aabf..086dd8b 100644 --- a/clang/lib/Sema/SemaDecl.cpp +++ b/clang/lib/Sema/SemaDecl.cpp @@ -8492,12 +8492,11 @@ void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, DeclContext *NewDC = D->getDeclContext(); if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { - if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) { - // Fields are not shadowed by variables in C++ static methods. - if (MD->isStatic()) - return; - - if (!MD->getParent()->isLambda() && MD->isExplicitObjectMemberFunction()) + if (const auto *MD = + dyn_cast<CXXMethodDecl>(getFunctionLevelDeclContext())) { + // Fields aren't shadowed in C++ static members or in member functions + // with an explicit object parameter. + if (MD->isStatic() || MD->isExplicitObjectMemberFunction()) return; } // Fields shadowed by constructor parameters are a special case. Usually diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp index a50c276..2159a0d 100644 --- a/clang/lib/Sema/SemaExpr.cpp +++ b/clang/lib/Sema/SemaExpr.cpp @@ -12653,10 +12653,10 @@ QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, // This is a gcc extension compatibility comparison. // In a SFINAE context, we treat this as a hard error to maintain // conformance with the C++ standard. - diagnoseFunctionPointerToVoidComparison( - *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); + bool IsError = isSFINAEContext(); + diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, IsError); - if (isSFINAEContext()) + if (IsError) return QualType(); RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); @@ -14598,11 +14598,11 @@ QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { unsigned AddressOfError = AO_No_Error; if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { - bool sfinae = (bool)isSFINAEContext(); - Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary - : diag::ext_typecheck_addrof_temporary) - << op->getType() << op->getSourceRange(); - if (sfinae) + bool IsError = isSFINAEContext(); + Diag(OpLoc, IsError ? diag::err_typecheck_addrof_temporary + : diag::ext_typecheck_addrof_temporary) + << op->getType() << op->getSourceRange(); + if (IsError) return QualType(); // Materialize the temporary as an lvalue so that we can take its address. OrigOp = op = @@ -16185,9 +16185,7 @@ ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, QualType Ty = Context.VoidTy; bool StmtExprMayBindToTemp = false; if (!Compound->body_empty()) { - // For GCC compatibility we get the last Stmt excluding trailing NullStmts. - if (const auto *LastStmt = - dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { + if (const auto *LastStmt = dyn_cast<ValueStmt>(Compound->body_back())) { if (const Expr *Value = LastStmt->getExprStmt()) { StmtExprMayBindToTemp = true; Ty = Value->getType(); diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp index 983a784..4a9e1bc 100644 --- a/clang/lib/Sema/SemaTemplate.cpp +++ b/clang/lib/Sema/SemaTemplate.cpp @@ -3846,13 +3846,14 @@ QualType Sema::CheckTemplateIdType(ElaboratedTypeKeyword Keyword, // within enable_if in a SFINAE context, dig out the specific // enable_if condition that failed and present that instead. if (isEnableIfAliasTemplate(AliasTemplate)) { - if (auto DeductionInfo = isSFINAEContext()) { - if (*DeductionInfo && - (*DeductionInfo)->hasSFINAEDiagnostic() && - (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() == - diag::err_typename_nested_not_found_enable_if && - TemplateArgs[0].getArgument().getKind() - == TemplateArgument::Expression) { + if (SFINAETrap *Trap = getSFINAEContext(); + TemplateDeductionInfo *DeductionInfo = + Trap ? Trap->getDeductionInfo() : nullptr) { + if (DeductionInfo->hasSFINAEDiagnostic() && + DeductionInfo->peekSFINAEDiagnostic().second.getDiagID() == + diag::err_typename_nested_not_found_enable_if && + TemplateArgs[0].getArgument().getKind() == + TemplateArgument::Expression) { Expr *FailedCond; std::string FailedDescription; std::tie(FailedCond, FailedDescription) = @@ -3861,15 +3862,14 @@ QualType Sema::CheckTemplateIdType(ElaboratedTypeKeyword Keyword, // Remove the old SFINAE diagnostic. PartialDiagnosticAt OldDiag = {SourceLocation(), PartialDiagnostic::NullDiagnostic()}; - (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag); + DeductionInfo->takeSFINAEDiagnostic(OldDiag); // Add a new SFINAE diagnostic specifying which condition // failed. - (*DeductionInfo)->addSFINAEDiagnostic( - OldDiag.first, - PDiag(diag::err_typename_nested_not_found_requirement) - << FailedDescription - << FailedCond->getSourceRange()); + DeductionInfo->addSFINAEDiagnostic( + OldDiag.first, + PDiag(diag::err_typename_nested_not_found_requirement) + << FailedDescription << FailedCond->getSourceRange()); } } } @@ -3955,6 +3955,7 @@ QualType Sema::CheckTemplateIdType(ElaboratedTypeKeyword Keyword, if (Decl->getSpecializationKind() == TSK_Undeclared && ClassTemplate->getTemplatedDecl()->hasAttrs()) { + NonSFINAEContext _(*this); InstantiatingTemplate Inst(*this, TemplateLoc, Decl); if (!Inst.isInvalid()) { MultiLevelTemplateArgumentList TemplateArgLists(Template, @@ -5565,12 +5566,11 @@ bool Sema::CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &ArgLoc, auto checkExpr = [&](Expr *E) -> Expr * { TemplateArgument SugaredResult, CanonicalResult; - unsigned CurSFINAEErrors = NumSFINAEErrors; ExprResult Res = CheckTemplateArgument( NTTP, NTTPType, E, SugaredResult, CanonicalResult, /*StrictCheck=*/CTAI.MatchingTTP || CTAI.PartialOrdering, CTAK); // If the current template argument causes an error, give up now. - if (Res.isInvalid() || CurSFINAEErrors < NumSFINAEErrors) + if (Res.isInvalid()) return nullptr; CTAI.SugaredConverted.push_back(SugaredResult); CTAI.CanonicalConverted.push_back(CanonicalResult); diff --git a/clang/lib/Sema/SemaTemplateDeduction.cpp b/clang/lib/Sema/SemaTemplateDeduction.cpp index 6964242..a287319 100644 --- a/clang/lib/Sema/SemaTemplateDeduction.cpp +++ b/clang/lib/Sema/SemaTemplateDeduction.cpp @@ -3239,10 +3239,6 @@ static TemplateDeductionResult FinishTemplateArgumentDeduction( ArrayRef<TemplateArgumentLoc> Ps, ArrayRef<TemplateArgument> As, SmallVectorImpl<DeducedTemplateArgument> &Deduced, TemplateDeductionInfo &Info, bool CopyDeducedArgs) { - // Unevaluated SFINAE context. - EnterExpressionEvaluationContext Unevaluated( - S, Sema::ExpressionEvaluationContext::Unevaluated); - Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Entity)); // C++ [temp.deduct.type]p2: @@ -3380,10 +3376,6 @@ static TemplateDeductionResult FinishTemplateArgumentDeduction( Sema &S, TemplateDecl *TD, SmallVectorImpl<DeducedTemplateArgument> &Deduced, TemplateDeductionInfo &Info) { - // Unevaluated SFINAE context. - EnterExpressionEvaluationContext Unevaluated( - S, Sema::ExpressionEvaluationContext::Unevaluated); - Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(TD)); // C++ [temp.deduct.type]p2: @@ -3423,7 +3415,7 @@ DeduceTemplateArguments(Sema &S, T *Partial, // Unevaluated SFINAE context. EnterExpressionEvaluationContext Unevaluated( S, Sema::ExpressionEvaluationContext::Unevaluated); - Sema::SFINAETrap Trap(S); + Sema::SFINAETrap Trap(S, Info); // This deduction has no relation to any outer instantiation we might be // performing. @@ -3441,8 +3433,7 @@ DeduceTemplateArguments(Sema &S, T *Partial, return Result; SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end()); - Sema::InstantiatingTemplate Inst(S, Info.getLocation(), Partial, DeducedArgs, - Info); + Sema::InstantiatingTemplate Inst(S, Info.getLocation(), Partial, DeducedArgs); if (Inst.isInvalid()) return TemplateDeductionResult::InstantiationDepth; @@ -3497,7 +3488,7 @@ Sema::DeduceTemplateArgumentsFromType(TemplateDecl *TD, QualType FromType, // Unevaluated SFINAE context. EnterExpressionEvaluationContext Unevaluated( *this, Sema::ExpressionEvaluationContext::Unevaluated); - SFINAETrap Trap(*this); + SFINAETrap Trap(*this, Info); // This deduction has no relation to any outer instantiation we might be // performing. @@ -3514,7 +3505,7 @@ Sema::DeduceTemplateArgumentsFromType(TemplateDecl *TD, QualType FromType, } SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end()); - InstantiatingTemplate Inst(*this, Info.getLocation(), TD, DeducedArgs, Info); + InstantiatingTemplate Inst(*this, Info.getLocation(), TD, DeducedArgs); if (Inst.isInvalid()) return TemplateDeductionResult::InstantiationDepth; @@ -3558,6 +3549,9 @@ TemplateDeductionResult Sema::SubstituteExplicitTemplateArguments( SmallVectorImpl<DeducedTemplateArgument> &Deduced, SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType, TemplateDeductionInfo &Info) { + assert(isSFINAEContext()); + assert(isUnevaluatedContext()); + FunctionDecl *Function = FunctionTemplate->getTemplatedDecl(); TemplateParameterList *TemplateParams = FunctionTemplate->getTemplateParameters(); @@ -3573,11 +3567,6 @@ TemplateDeductionResult Sema::SubstituteExplicitTemplateArguments( return TemplateDeductionResult::Success; } - // Unevaluated SFINAE context. - EnterExpressionEvaluationContext Unevaluated( - *this, Sema::ExpressionEvaluationContext::Unevaluated); - SFINAETrap Trap(*this); - // C++ [temp.arg.explicit]p3: // Template arguments that are present shall be specified in the // declaration order of their corresponding template-parameters. The @@ -3590,7 +3579,7 @@ TemplateDeductionResult Sema::SubstituteExplicitTemplateArguments( SmallVector<TemplateArgument, 4> DeducedArgs; InstantiatingTemplate Inst( *this, Info.getLocation(), FunctionTemplate, DeducedArgs, - CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info); + CodeSynthesisContext::ExplicitTemplateArgumentSubstitution); if (Inst.isInvalid()) return TemplateDeductionResult::InstantiationDepth; @@ -3598,8 +3587,7 @@ TemplateDeductionResult Sema::SubstituteExplicitTemplateArguments( if (CheckTemplateArgumentList(FunctionTemplate, SourceLocation(), ExplicitTemplateArgs, /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/true, CTAI, - /*UpdateArgsWithConversions=*/false) || - Trap.hasErrorOccurred()) { + /*UpdateArgsWithConversions=*/false)) { unsigned Index = CTAI.SugaredConverted.size(); if (Index >= TemplateParams->size()) return TemplateDeductionResult::SubstitutionFailure; @@ -3688,7 +3676,7 @@ TemplateDeductionResult Sema::SubstituteExplicitTemplateArguments( ResultType = SubstType(Proto->getReturnType(), MLTAL, Function->getTypeSpecStartLoc(), Function->getDeclName()); - if (ResultType.isNull() || Trap.hasErrorOccurred()) + if (ResultType.isNull()) return TemplateDeductionResult::SubstitutionFailure; // CUDA: Kernel function must have 'void' return type. if (getLangOpts().CUDA) @@ -3714,7 +3702,7 @@ TemplateDeductionResult Sema::SubstituteExplicitTemplateArguments( Function->getLocation(), Function->getDeclName(), EPI); - if (FunctionType->isNull() || Trap.hasErrorOccurred()) + if (FunctionType->isNull()) return TemplateDeductionResult::SubstitutionFailure; } @@ -3912,12 +3900,15 @@ static TemplateDeductionResult instantiateExplicitSpecifierDeferred( if (!ExplicitExpr->isValueDependent()) return TemplateDeductionResult::Success; + // By this point, FinishTemplateArgumentDeduction will have been reverted back + // to a regular non-SFINAE template instantiation context, so setup a new + // SFINAE context. Sema::InstantiatingTemplate Inst( S, Info.getLocation(), FunctionTemplate, DeducedArgs, - Sema::CodeSynthesisContext::DeducedTemplateArgumentSubstitution, Info); + Sema::CodeSynthesisContext::DeducedTemplateArgumentSubstitution); if (Inst.isInvalid()) return TemplateDeductionResult::InstantiationDepth; - Sema::SFINAETrap Trap(S); + Sema::SFINAETrap Trap(S, Info); const ExplicitSpecifier InstantiatedES = S.instantiateExplicitSpecifier(SubstArgs, ES); if (InstantiatedES.isInvalid() || Trap.hasErrorOccurred()) { @@ -3937,17 +3928,12 @@ TemplateDeductionResult Sema::FinishTemplateArgumentDeduction( bool PartialOverloading, bool PartialOrdering, bool ForOverloadSetAddressResolution, llvm::function_ref<bool(bool)> CheckNonDependent) { - // Unevaluated SFINAE context. - EnterExpressionEvaluationContext Unevaluated( - *this, Sema::ExpressionEvaluationContext::Unevaluated); - SFINAETrap Trap(*this); - // Enter a new template instantiation context while we instantiate the // actual function declaration. SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end()); InstantiatingTemplate Inst( *this, Info.getLocation(), FunctionTemplate, DeducedArgs, - CodeSynthesisContext::DeducedTemplateArgumentSubstitution, Info); + CodeSynthesisContext::DeducedTemplateArgumentSubstitution); if (Inst.isInvalid()) return TemplateDeductionResult::InstantiationDepth; @@ -4030,18 +4016,9 @@ TemplateDeductionResult Sema::FinishTemplateArgumentDeduction( // If the template argument list is owned by the function template // specialization, release it. if (Specialization->getTemplateSpecializationArgs() == - CanonicalDeducedArgumentList && - !Trap.hasErrorOccurred()) + CanonicalDeducedArgumentList) Info.takeCanonical(); - // There may have been an error that did not prevent us from constructing a - // declaration. Mark the declaration invalid and return with a substitution - // failure. - if (Trap.hasErrorOccurred()) { - Specialization->setInvalidDecl(true); - return TemplateDeductionResult::SubstitutionFailure; - } - // C++2a [temp.deduct]p5 // [...] When all template arguments have been deduced [...] all uses of // template parameters [...] are replaced with the corresponding deduced @@ -4553,6 +4530,10 @@ TemplateDeductionResult Sema::DeduceTemplateArguments( return TemplateDeductionResult::TooManyArguments; } + EnterExpressionEvaluationContext Unevaluated( + *this, Sema::ExpressionEvaluationContext::Unevaluated); + Sema::SFINAETrap Trap(*this, Info); + // The types of the parameters from which we will perform template argument // deduction. LocalInstantiationScope InstScope(*this); @@ -4570,6 +4551,8 @@ TemplateDeductionResult Sema::DeduceTemplateArguments( }); if (Result != TemplateDeductionResult::Success) return Result; + if (Trap.hasErrorOccurred()) + return TemplateDeductionResult::SubstitutionFailure; NumExplicitlySpecified = Deduced.size(); } else { @@ -4743,6 +4726,11 @@ TemplateDeductionResult Sema::DeduceTemplateArguments( OnlyInitializeNonUserDefinedConversions); }); }); + if (Trap.hasErrorOccurred()) { + if (Specialization) + Specialization->setInvalidDecl(true); + return TemplateDeductionResult::SubstitutionFailure; + } return Result; } @@ -4795,6 +4783,14 @@ TemplateDeductionResult Sema::DeduceTemplateArguments( = FunctionTemplate->getTemplateParameters(); QualType FunctionType = Function->getType(); + bool PotentiallyEvaluated = + currentEvaluationContext().isPotentiallyEvaluated(); + + // Unevaluated SFINAE context. + EnterExpressionEvaluationContext Unevaluated( + *this, Sema::ExpressionEvaluationContext::Unevaluated); + SFINAETrap Trap(*this, Info); + // Substitute any explicit template arguments. LocalInstantiationScope InstScope(*this); SmallVector<DeducedTemplateArgument, 4> Deduced; @@ -4809,6 +4805,8 @@ TemplateDeductionResult Sema::DeduceTemplateArguments( }); if (Result != TemplateDeductionResult::Success) return Result; + if (Trap.hasErrorOccurred()) + return TemplateDeductionResult::SubstitutionFailure; NumExplicitlySpecified = Deduced.size(); } @@ -4820,11 +4818,6 @@ TemplateDeductionResult Sema::DeduceTemplateArguments( ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType, /*AdjustExceptionSpec*/false); - // Unevaluated SFINAE context. - std::optional<EnterExpressionEvaluationContext> Unevaluated( - std::in_place, *this, Sema::ExpressionEvaluationContext::Unevaluated); - SFINAETrap Trap(*this); - Deduced.resize(TemplateParams->size()); // If the function has a deduced return type, substitute it for a dependent @@ -4865,14 +4858,12 @@ TemplateDeductionResult Sema::DeduceTemplateArguments( DeduceReturnType(Specialization, Info.getLocation(), false)) return TemplateDeductionResult::MiscellaneousDeductionFailure; - Unevaluated = std::nullopt; // [C++26][expr.const]/p17 // An expression or conversion is immediate-escalating if it is not initially // in an immediate function context and it is [...] // a potentially-evaluated id-expression that denotes an immediate function. if (IsAddressOfFunction && getLangOpts().CPlusPlus20 && - Specialization->isImmediateEscalating() && - currentEvaluationContext().isPotentiallyEvaluated() && + Specialization->isImmediateEscalating() && PotentiallyEvaluated && CheckIfFunctionSpecializationIsImmediate(Specialization, Info.getLocation())) return TemplateDeductionResult::MiscellaneousDeductionFailure; @@ -4975,7 +4966,7 @@ TemplateDeductionResult Sema::DeduceTemplateArguments( // Unevaluated SFINAE context. EnterExpressionEvaluationContext Unevaluated( *this, Sema::ExpressionEvaluationContext::Unevaluated); - SFINAETrap Trap(*this); + SFINAETrap Trap(*this, Info); // C++ [temp.deduct.conv]p1: // Template argument deduction is done by comparing the return @@ -5614,10 +5605,6 @@ static TemplateDeductionResult FinishTemplateArgumentDeduction( Sema &S, FunctionTemplateDecl *FTD, SmallVectorImpl<DeducedTemplateArgument> &Deduced, TemplateDeductionInfo &Info, T &&CheckDeductionConsistency) { - EnterExpressionEvaluationContext Unevaluated( - S, Sema::ExpressionEvaluationContext::Unevaluated); - Sema::SFINAETrap Trap(S); - Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(FTD)); // C++26 [temp.deduct.type]p2: @@ -5645,13 +5632,7 @@ static TemplateDeductionResult FinishTemplateArgumentDeduction( // and verify that the instantiated argument is both valid // and equivalent to the parameter. LocalInstantiationScope InstScope(S); - - if (auto TDR = CheckDeductionConsistency(S, FTD, CTAI.SugaredConverted); - TDR != TemplateDeductionResult::Success) - return TDR; - - return Trap.hasErrorOccurred() ? TemplateDeductionResult::SubstitutionFailure - : TemplateDeductionResult::Success; + return CheckDeductionConsistency(S, FTD, CTAI.SugaredConverted); } /// Determine whether the function template \p FT1 is at least as @@ -5717,9 +5698,12 @@ static bool isAtLeastAsSpecializedAs( } SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end()); + EnterExpressionEvaluationContext Unevaluated( + S, Sema::ExpressionEvaluationContext::Unevaluated); + Sema::SFINAETrap Trap(S, Info); Sema::InstantiatingTemplate Inst( S, Info.getLocation(), FT2, DeducedArgs, - Sema::CodeSynthesisContext::DeducedTemplateArgumentSubstitution, Info); + Sema::CodeSynthesisContext::DeducedTemplateArgumentSubstitution); if (Inst.isInvalid()) return false; @@ -5765,7 +5749,7 @@ static bool isAtLeastAsSpecializedAs( }); }) == TemplateDeductionResult::Success; }); - if (!AtLeastAsSpecialized) + if (!AtLeastAsSpecialized || Trap.hasErrorOccurred()) return false; // C++0x [temp.deduct.partial]p11: @@ -6241,10 +6225,11 @@ static bool isAtLeastAsSpecializedAs(Sema &S, QualType T1, QualType T2, /*HasDeducedAnyParam=*/nullptr) != TemplateDeductionResult::Success) return false; - SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), - Deduced.end()); - Sema::InstantiatingTemplate Inst(S, Info.getLocation(), P2, DeducedArgs, - Info); + SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end()); + EnterExpressionEvaluationContext Unevaluated( + S, Sema::ExpressionEvaluationContext::Unevaluated); + Sema::SFINAETrap Trap(S, Info); + Sema::InstantiatingTemplate Inst(S, Info.getLocation(), P2, DeducedArgs); if (Inst.isInvalid()) return false; @@ -6252,8 +6237,6 @@ static bool isAtLeastAsSpecializedAs(Sema &S, QualType T1, QualType T2, Ps = cast<TemplateSpecializationType>(T2)->template_arguments(), As = cast<TemplateSpecializationType>(T1)->template_arguments(); - Sema::SFINAETrap Trap(S); - TemplateDeductionResult Result; S.runWithSufficientStackSpace(Info.getLocation(), [&] { Result = ::FinishTemplateArgumentDeduction( @@ -6261,14 +6244,7 @@ static bool isAtLeastAsSpecializedAs(Sema &S, QualType T1, QualType T2, /*IsPartialOrdering=*/true, Ps, As, Deduced, Info, /*CopyDeducedArgs=*/false); }); - - if (Result != TemplateDeductionResult::Success) - return false; - - if (Trap.hasErrorOccurred()) - return false; - - return true; + return Result == TemplateDeductionResult::Success && !Trap.hasErrorOccurred(); } namespace { diff --git a/clang/lib/Sema/SemaTemplateDeductionGuide.cpp b/clang/lib/Sema/SemaTemplateDeductionGuide.cpp index 40811d4..bfb1066 100644 --- a/clang/lib/Sema/SemaTemplateDeductionGuide.cpp +++ b/clang/lib/Sema/SemaTemplateDeductionGuide.cpp @@ -1025,6 +1025,7 @@ BuildDeductionGuideForTypeAlias(Sema &SemaRef, TypeAliasTemplateDecl *AliasTemplate, FunctionTemplateDecl *F, SourceLocation Loc) { LocalInstantiationScope Scope(SemaRef); + Sema::NonSFINAEContext _1(SemaRef); Sema::InstantiatingTemplate BuildingDeductionGuides( SemaRef, AliasTemplate->getLocation(), F, Sema::InstantiatingTemplate::BuildingDeductionGuidesTag{}); diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp b/clang/lib/Sema/SemaTemplateInstantiate.cpp index 5fceacd..35205f4 100644 --- a/clang/lib/Sema/SemaTemplateInstantiate.cpp +++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp @@ -606,8 +606,7 @@ bool Sema::CodeSynthesisContext::isInstantiationRecord() const { Sema::InstantiatingTemplate::InstantiatingTemplate( Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind, SourceLocation PointOfInstantiation, SourceRange InstantiationRange, - Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, - sema::TemplateDeductionInfo *DeductionInfo) + Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs) : SemaRef(SemaRef) { // Don't allow further instantiation if a fatal error and an uncompilable // error have occurred. Any diagnostics we might have raised will not be @@ -625,7 +624,6 @@ Sema::InstantiatingTemplate::InstantiatingTemplate( Inst.Template = Template; Inst.TemplateArgs = TemplateArgs.data(); Inst.NumTemplateArgs = TemplateArgs.size(); - Inst.DeductionInfo = DeductionInfo; Inst.InstantiationRange = InstantiationRange; Inst.InConstraintSubstitution = Inst.Kind == CodeSynthesisContext::ConstraintSubstitution; @@ -671,48 +669,40 @@ Sema::InstantiatingTemplate::InstantiatingTemplate( Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionTemplateDecl *FunctionTemplate, ArrayRef<TemplateArgument> TemplateArgs, - CodeSynthesisContext::SynthesisKind Kind, - sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange) + CodeSynthesisContext::SynthesisKind Kind, SourceRange InstantiationRange) : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation, InstantiationRange, FunctionTemplate, nullptr, - TemplateArgs, &DeductionInfo) { + TemplateArgs) { assert(Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution || Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution || Kind == CodeSynthesisContext::BuildingDeductionGuides); } Sema::InstantiatingTemplate::InstantiatingTemplate( - Sema &SemaRef, SourceLocation PointOfInstantiation, - TemplateDecl *Template, - ArrayRef<TemplateArgument> TemplateArgs, - sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange) + Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template, + ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange) : InstantiatingTemplate( - SemaRef, - CodeSynthesisContext::DeducedTemplateArgumentSubstitution, + SemaRef, CodeSynthesisContext::DeducedTemplateArgumentSubstitution, PointOfInstantiation, InstantiationRange, Template, nullptr, - TemplateArgs, &DeductionInfo) {} + TemplateArgs) {} Sema::InstantiatingTemplate::InstantiatingTemplate( Sema &SemaRef, SourceLocation PointOfInstantiation, ClassTemplatePartialSpecializationDecl *PartialSpec, - ArrayRef<TemplateArgument> TemplateArgs, - sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange) + ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange) : InstantiatingTemplate( - SemaRef, - CodeSynthesisContext::DeducedTemplateArgumentSubstitution, + SemaRef, CodeSynthesisContext::DeducedTemplateArgumentSubstitution, PointOfInstantiation, InstantiationRange, PartialSpec, nullptr, - TemplateArgs, &DeductionInfo) {} + TemplateArgs) {} Sema::InstantiatingTemplate::InstantiatingTemplate( Sema &SemaRef, SourceLocation PointOfInstantiation, VarTemplatePartialSpecializationDecl *PartialSpec, - ArrayRef<TemplateArgument> TemplateArgs, - sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange) + ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange) : InstantiatingTemplate( - SemaRef, - CodeSynthesisContext::DeducedTemplateArgumentSubstitution, + SemaRef, CodeSynthesisContext::DeducedTemplateArgumentSubstitution, PointOfInstantiation, InstantiationRange, PartialSpec, nullptr, - TemplateArgs, &DeductionInfo) {} + TemplateArgs) {} Sema::InstantiatingTemplate::InstantiatingTemplate( Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param, @@ -763,12 +753,11 @@ Sema::InstantiatingTemplate::InstantiatingTemplate( Sema::InstantiatingTemplate::InstantiatingTemplate( Sema &SemaRef, SourceLocation PointOfInstantiation, - concepts::Requirement *Req, sema::TemplateDeductionInfo &DeductionInfo, - SourceRange InstantiationRange) + concepts::Requirement *Req, SourceRange InstantiationRange) : InstantiatingTemplate( SemaRef, CodeSynthesisContext::RequirementInstantiation, PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr, - /*Template=*/nullptr, /*TemplateArgs=*/{}, &DeductionInfo) {} + /*Template=*/nullptr, /*TemplateArgs=*/{}) {} Sema::InstantiatingTemplate::InstantiatingTemplate( Sema &SemaRef, SourceLocation PointOfInstantiation, @@ -781,11 +770,11 @@ Sema::InstantiatingTemplate::InstantiatingTemplate( Sema::InstantiatingTemplate::InstantiatingTemplate( Sema &SemaRef, SourceLocation PointOfInstantiation, const RequiresExpr *RE, - sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange) + SourceRange InstantiationRange) : InstantiatingTemplate( SemaRef, CodeSynthesisContext::RequirementParameterInstantiation, PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr, - /*Template=*/nullptr, /*TemplateArgs=*/{}, &DeductionInfo) {} + /*Template=*/nullptr, /*TemplateArgs=*/{}) {} Sema::InstantiatingTemplate::InstantiatingTemplate( Sema &SemaRef, SourceLocation PointOfInstantiation, @@ -797,13 +786,11 @@ Sema::InstantiatingTemplate::InstantiatingTemplate( TemplateArgs) {} Sema::InstantiatingTemplate::InstantiatingTemplate( - Sema &SemaRef, SourceLocation PointOfInstantiation, - ConstraintSubstitution, NamedDecl *Template, - sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange) + Sema &SemaRef, SourceLocation PointOfInstantiation, ConstraintSubstitution, + NamedDecl *Template, SourceRange InstantiationRange) : InstantiatingTemplate( SemaRef, CodeSynthesisContext::ConstraintSubstitution, - PointOfInstantiation, InstantiationRange, Template, nullptr, - {}, &DeductionInfo) {} + PointOfInstantiation, InstantiationRange, Template, nullptr, {}) {} Sema::InstantiatingTemplate::InstantiatingTemplate( Sema &SemaRef, SourceLocation PointOfInstantiation, @@ -835,9 +822,6 @@ Sema::InstantiatingTemplate::InstantiatingTemplate( ArgLoc, InstantiationRange, PArg) {} bool Sema::pushCodeSynthesisContext(CodeSynthesisContext Ctx) { - Ctx.SavedInNonInstantiationSFINAEContext = InNonInstantiationSFINAEContext; - InNonInstantiationSFINAEContext = false; - if (!Ctx.isInstantiationRecord()) { ++NonInstantiationEntries; } else { @@ -871,8 +855,6 @@ void Sema::popCodeSynthesisContext() { --NonInstantiationEntries; } - InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext; - // Name lookup no longer looks in this template's defining module. assert(CodeSynthesisContexts.size() >= CodeSynthesisContextLookupModules.size() && @@ -1282,93 +1264,6 @@ void Sema::PrintInstantiationStack(InstantiationContextDiagFuncRef DiagFunc) { } } -std::optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const { - if (InNonInstantiationSFINAEContext) - return std::optional<TemplateDeductionInfo *>(nullptr); - - for (SmallVectorImpl<CodeSynthesisContext>::const_reverse_iterator - Active = CodeSynthesisContexts.rbegin(), - ActiveEnd = CodeSynthesisContexts.rend(); - Active != ActiveEnd; - ++Active) - { - switch (Active->Kind) { - case CodeSynthesisContext::TypeAliasTemplateInstantiation: - // An instantiation of an alias template may or may not be a SFINAE - // context, depending on what else is on the stack. - if (isa<TypeAliasTemplateDecl>(Active->Entity)) - break; - [[fallthrough]]; - case CodeSynthesisContext::TemplateInstantiation: - case CodeSynthesisContext::DefaultFunctionArgumentInstantiation: - case CodeSynthesisContext::ExceptionSpecInstantiation: - case CodeSynthesisContext::ConstraintsCheck: - case CodeSynthesisContext::ParameterMappingSubstitution: - case CodeSynthesisContext::ConstraintNormalization: - case CodeSynthesisContext::NestedRequirementConstraintsCheck: - // This is a template instantiation, so there is no SFINAE. - return std::nullopt; - case CodeSynthesisContext::LambdaExpressionSubstitution: - // [temp.deduct]p9 - // A lambda-expression appearing in a function type or a template - // parameter is not considered part of the immediate context for the - // purposes of template argument deduction. - // CWG2672: A lambda-expression body is never in the immediate context. - return std::nullopt; - - case CodeSynthesisContext::DefaultTemplateArgumentInstantiation: - case CodeSynthesisContext::PriorTemplateArgumentSubstitution: - case CodeSynthesisContext::DefaultTemplateArgumentChecking: - case CodeSynthesisContext::RewritingOperatorAsSpaceship: - case CodeSynthesisContext::PartialOrderingTTP: - // A default template argument instantiation and substitution into - // template parameters with arguments for prior parameters may or may - // not be a SFINAE context; look further up the stack. - break; - - case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution: - case CodeSynthesisContext::DeducedTemplateArgumentSubstitution: - // We're either substituting explicitly-specified template arguments, - // deduced template arguments. SFINAE applies unless we are in a lambda - // body, see [temp.deduct]p9. - case CodeSynthesisContext::ConstraintSubstitution: - case CodeSynthesisContext::RequirementInstantiation: - case CodeSynthesisContext::RequirementParameterInstantiation: - // SFINAE always applies in a constraint expression or a requirement - // in a requires expression. - assert(Active->DeductionInfo && "Missing deduction info pointer"); - return Active->DeductionInfo; - - case CodeSynthesisContext::DeclaringSpecialMember: - case CodeSynthesisContext::DeclaringImplicitEqualityComparison: - case CodeSynthesisContext::DefiningSynthesizedFunction: - case CodeSynthesisContext::InitializingStructuredBinding: - case CodeSynthesisContext::MarkingClassDllexported: - case CodeSynthesisContext::BuildingBuiltinDumpStructCall: - case CodeSynthesisContext::BuildingDeductionGuides: - // This happens in a context unrelated to template instantiation, so - // there is no SFINAE. - return std::nullopt; - - case CodeSynthesisContext::ExceptionSpecEvaluation: - // FIXME: This should not be treated as a SFINAE context, because - // we will cache an incorrect exception specification. However, clang - // bootstrap relies this! See PR31692. - break; - - case CodeSynthesisContext::Memoization: - break; - } - - // The inner context was transparent for SFINAE. If it occurred within a - // non-instantiation SFINAE context, then SFINAE applies. - if (Active->SavedInNonInstantiationSFINAEContext) - return std::optional<TemplateDeductionInfo *>(nullptr); - } - - return std::nullopt; -} - //===----------------------------------------------------------------------===/ // Template Instantiation for Types //===----------------------------------------------------------------------===/ @@ -2674,10 +2569,9 @@ ExprResult TemplateInstantiator::TransformRequiresTypeParams( Sema::ExtParameterInfoBuilder &PInfos) { TemplateDeductionInfo Info(KWLoc); - Sema::InstantiatingTemplate TypeInst(SemaRef, KWLoc, - RE, Info, + Sema::InstantiatingTemplate TypeInst(SemaRef, KWLoc, RE, SourceRange{KWLoc, RBraceLoc}); - Sema::SFINAETrap Trap(SemaRef); + Sema::SFINAETrap Trap(SemaRef, Info); unsigned ErrorIdx; if (getDerived().TransformFunctionTypeParams( @@ -2709,10 +2603,10 @@ TemplateInstantiator::TransformTypeRequirement(concepts::TypeRequirement *Req) { return Req; } - Sema::SFINAETrap Trap(SemaRef); TemplateDeductionInfo Info(Req->getType()->getTypeLoc().getBeginLoc()); - Sema::InstantiatingTemplate TypeInst(SemaRef, - Req->getType()->getTypeLoc().getBeginLoc(), Req, Info, + Sema::SFINAETrap Trap(SemaRef, Info); + Sema::InstantiatingTemplate TypeInst( + SemaRef, Req->getType()->getTypeLoc().getBeginLoc(), Req, Req->getType()->getTypeLoc().getSourceRange()); if (TypeInst.isInvalid()) return nullptr; @@ -2730,8 +2624,6 @@ TemplateInstantiator::TransformExprRequirement(concepts::ExprRequirement *Req) { if (!Req->isDependent() && !AlwaysRebuild()) return Req; - Sema::SFINAETrap Trap(SemaRef); - llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *> TransExpr; if (Req->isExprSubstitutionFailure()) @@ -2739,7 +2631,8 @@ TemplateInstantiator::TransformExprRequirement(concepts::ExprRequirement *Req) { else { Expr *E = Req->getExpr(); TemplateDeductionInfo Info(E->getBeginLoc()); - Sema::InstantiatingTemplate ExprInst(SemaRef, E->getBeginLoc(), Req, Info, + Sema::SFINAETrap Trap(SemaRef, Info); + Sema::InstantiatingTemplate ExprInst(SemaRef, E->getBeginLoc(), Req, E->getSourceRange()); if (ExprInst.isInvalid()) return nullptr; @@ -2765,8 +2658,9 @@ TemplateInstantiator::TransformExprRequirement(concepts::ExprRequirement *Req) { TemplateParameterList *OrigTPL = RetReq.getTypeConstraintTemplateParameterList(); TemplateDeductionInfo Info(OrigTPL->getTemplateLoc()); - Sema::InstantiatingTemplate TPLInst(SemaRef, OrigTPL->getTemplateLoc(), - Req, Info, OrigTPL->getSourceRange()); + Sema::SFINAETrap Trap(SemaRef, Info); + Sema::InstantiatingTemplate TPLInst(SemaRef, OrigTPL->getTemplateLoc(), Req, + OrigTPL->getSourceRange()); if (TPLInst.isInvalid()) return nullptr; TemplateParameterList *TPL = TransformTemplateParameterList(OrigTPL); @@ -2830,11 +2724,9 @@ TemplateInstantiator::TransformNestedRequirement( bool Success; Expr *NewConstraint; - TemplateDeductionInfo Info(Constraint->getBeginLoc()); { EnterExpressionEvaluationContext ContextRAII( SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated); - Sema::InstantiatingTemplate ConstrInst( SemaRef, Constraint->getBeginLoc(), Req, Sema::InstantiatingTemplate::ConstraintsCheck(), @@ -2843,16 +2735,10 @@ TemplateInstantiator::TransformNestedRequirement( if (ConstrInst.isInvalid()) return nullptr; - Sema::SFINAETrap Trap(SemaRef); - Success = !SemaRef.CheckConstraintSatisfaction( Req, AssociatedConstraint(Constraint, SemaRef.ArgPackSubstIndex), TemplateArgs, Constraint->getSourceRange(), Satisfaction, /*TopLevelConceptId=*/nullptr, &NewConstraint); - - assert((!Success || !Trap.hasErrorOccurred()) && - "Substitution failures must be handled " - "by CheckConstraintSatisfaction."); } if (!Success || Satisfaction.HasSubstitutionFailure()) @@ -3306,7 +3192,7 @@ bool Sema::SubstDefaultArgument( EnterExpressionEvaluationContext EvalContext( *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); - + NonSFINAEContext _(*this); InstantiatingTemplate Inst(*this, Loc, Param, TemplateArgs.getInnermost()); if (Inst.isInvalid()) return true; @@ -3594,6 +3480,7 @@ bool Sema::InstantiateClassImpl( Spec->setPointOfInstantiation(PointOfInstantiation); } + NonSFINAEContext _(*this); InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation); if (Inst.isInvalid()) return true; @@ -3828,6 +3715,7 @@ bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation, MSInfo->setPointOfInstantiation(PointOfInstantiation); } + NonSFINAEContext _(*this); InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation); if (Inst.isInvalid()) return true; @@ -3892,6 +3780,7 @@ bool Sema::InstantiateInClassInitializer( return true; } + NonSFINAEContext _(*this); InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation); if (Inst.isInvalid()) return true; @@ -3975,6 +3864,7 @@ static ActionResult<CXXRecordDecl *> getPatternForClassTemplateSpecialization( Sema &S, SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool PrimaryStrictPackMatch) { + std::optional<Sema::NonSFINAEContext> NSC(S); Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec); if (Inst.isInvalid()) return {/*Invalid=*/true}; @@ -4076,6 +3966,7 @@ static ActionResult<CXXRecordDecl *> getPatternForClassTemplateSpecialization( if (Ambiguous) { // Partial ordering did not produce a clear winner. Complain. Inst.Clear(); + NSC.reset(); S.Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous) << ClassTemplateSpec; @@ -4507,6 +4398,7 @@ ExprResult Sema::SubstConceptTemplateArguments( TemplateArgumentListInfo SubstArgs(ArgsAsWritten->getLAngleLoc(), ArgsAsWritten->getRAngleLoc()); + NonSFINAEContext _(*this); Sema::InstantiatingTemplate Inst( *this, ArgsAsWritten->arguments().front().getSourceRange().getBegin(), Sema::InstantiatingTemplate::ConstraintNormalization{}, diff --git a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp index 681bfe0..4d58f00 100644 --- a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp +++ b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp @@ -5316,6 +5316,7 @@ void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation, return; } + NonSFINAEContext _(*this); InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl, InstantiatingTemplate::ExceptionSpecification()); if (Inst.isInvalid()) { @@ -5383,6 +5384,7 @@ TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New, if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution || ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) { if (isa<FunctionTemplateDecl>(ActiveInst.Entity)) { + SemaRef.CurrentSFINAEContext = nullptr; atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst); ActiveInst.Kind = ActiveInstType::TemplateInstantiation; ActiveInst.Entity = New; @@ -5493,8 +5495,7 @@ FunctionDecl *Sema::InstantiateFunctionDeclaration( SourceLocation Loc, CodeSynthesisContext::SynthesisKind CSC) { FunctionDecl *FD = FTD->getTemplatedDecl(); - sema::TemplateDeductionInfo Info(Loc); - InstantiatingTemplate Inst(*this, Loc, FTD, Args->asArray(), CSC, Info); + InstantiatingTemplate Inst(*this, Loc, FTD, Args->asArray(), CSC); if (Inst.isInvalid()) return nullptr; @@ -5684,6 +5685,7 @@ void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, } } + NonSFINAEContext _(*this); InstantiatingTemplate Inst(*this, PointOfInstantiation, Function); if (Inst.isInvalid()) return; @@ -5974,6 +5976,7 @@ VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation( if (FromVar->isInvalidDecl()) return nullptr; + NonSFINAEContext _(*this); InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar); if (Inst.isInvalid()) return nullptr; @@ -6281,6 +6284,7 @@ void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation, !Var->hasInit()) { // FIXME: Factor out the duplicated instantiation context setup/tear down // code here. + NonSFINAEContext _(*this); InstantiatingTemplate Inst(*this, PointOfInstantiation, Var); if (Inst.isInvalid()) return; @@ -6385,6 +6389,7 @@ void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation, return; } + NonSFINAEContext _(*this); InstantiatingTemplate Inst(*this, PointOfInstantiation, Var); if (Inst.isInvalid()) return; diff --git a/clang/lib/Sema/SemaTemplateVariadic.cpp b/clang/lib/Sema/SemaTemplateVariadic.cpp index 0f72d6a..5b1aad3 100644 --- a/clang/lib/Sema/SemaTemplateVariadic.cpp +++ b/clang/lib/Sema/SemaTemplateVariadic.cpp @@ -844,7 +844,7 @@ bool Sema::CheckParameterPacksForExpansion( ArrayRef<UnexpandedParameterPack> Unexpanded, const MultiLevelTemplateArgumentList &TemplateArgs, bool FailOnPackProducingTemplates, bool &ShouldExpand, - bool &RetainExpansion, UnsignedOrNone &NumExpansions) { + bool &RetainExpansion, UnsignedOrNone &NumExpansions, bool Diagnose) { ShouldExpand = true; RetainExpansion = false; IdentifierLoc FirstPack; @@ -874,6 +874,9 @@ bool Sema::CheckParameterPacksForExpansion( if (!FailOnPackProducingTemplates) continue; + if (!Diagnose) + return true; + // It is not yet supported in certain contexts. return Diag(PatternRange.getBegin().isValid() ? PatternRange.getBegin() : EllipsisLoc, @@ -1015,7 +1018,9 @@ bool Sema::CheckParameterPacksForExpansion( // C++0x [temp.variadic]p5: // All of the parameter packs expanded by a pack expansion shall have // the same number of arguments specified. - if (HaveFirstPack) + if (!Diagnose) + ; + else if (HaveFirstPack) Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict) << FirstPack.getIdentifierInfo() << Name << *NumExpansions << (LeastNewPackSize != NewPackSize) << LeastNewPackSize @@ -1041,6 +1046,8 @@ bool Sema::CheckParameterPacksForExpansion( if (NumExpansions && *NumExpansions < *NumPartialExpansions) { NamedDecl *PartialPack = CurrentInstantiationScope->getPartiallySubstitutedPack(); + if (!Diagnose) + return true; Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_partial) << PartialPack << *NumPartialExpansions << *NumExpansions << SourceRange(PartiallySubstitutedPackLoc); diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h index dffd7c1..94105f1 100644 --- a/clang/lib/Sema/TreeTransform.h +++ b/clang/lib/Sema/TreeTransform.h @@ -8076,14 +8076,13 @@ TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S, getSema().resetFPOptions( S->getStoredFPFeatures().applyOverrides(getSema().getLangOpts())); - const Stmt *ExprResult = S->getStmtExprResult(); bool SubStmtInvalid = false; bool SubStmtChanged = false; SmallVector<Stmt*, 8> Statements; for (auto *B : S->body()) { StmtResult Result = getDerived().TransformStmt( - B, IsStmtExpr && B == ExprResult ? StmtDiscardKind::StmtExprResult - : StmtDiscardKind::Discarded); + B, IsStmtExpr && B == S->body_back() ? StmtDiscardKind::StmtExprResult + : StmtDiscardKind::Discarded); if (Result.isInvalid()) { // Immediately fail if this was a DeclStmt, since it's very @@ -15824,16 +15823,20 @@ TreeTransform<Derived>::TransformLambdaExpr(LambdaExpr *E) { Sema::ExpressionEvaluationContext::PotentiallyEvaluated, E->getCallOperator()); - Sema::CodeSynthesisContext C; - C.Kind = clang::Sema::CodeSynthesisContext::LambdaExpressionSubstitution; - C.PointOfInstantiation = E->getBody()->getBeginLoc(); - getSema().pushCodeSynthesisContext(C); + StmtResult Body; + { + Sema::NonSFINAEContext _(getSema()); + Sema::CodeSynthesisContext C; + C.Kind = clang::Sema::CodeSynthesisContext::LambdaExpressionSubstitution; + C.PointOfInstantiation = E->getBody()->getBeginLoc(); + getSema().pushCodeSynthesisContext(C); - // Instantiate the body of the lambda expression. - StmtResult Body = - Invalid ? StmtError() : getDerived().TransformLambdaBody(E, E->getBody()); + // Instantiate the body of the lambda expression. + Body = Invalid ? StmtError() + : getDerived().TransformLambdaBody(E, E->getBody()); - getSema().popCodeSynthesisContext(); + getSema().popCodeSynthesisContext(); + } // ActOnLambda* will pop the function scope for us. FuncScopeCleanup.disable(); |
