https://github.com/cor3ntin created https://github.com/llvm/llvm-project/pull/133426
This implements the same overload resolution behavior as GCC, as described in https://wg21.link/p3606 (sections 1-2, not 3) If, during overload resolution, a non-template candidate is always picked because each argument is a perfect match (i.e., the source and target types are the same), we do not perform deduction for any template candidate that might exist. The goal is to be able to merge #122423 without being too disruptive. This change means that the selection of the best viable candidate and template argument deduction become interleaved. To avoid rewriting half of Clang, we store in `OverloadCandidateSet` enough information to deduce template candidates from `OverloadCandidateSet::BestViableFunction`. This means the lifetime of any object used by the template argument must outlive a call to `Add*Template*Candidate`. This two-phase resolution is not performed for some initialization as there are cases where template candidates are a better match per the standard. It's also bypassed for code completion. The change has a nice impact on compile times https://llvm-compile-time-tracker.com/compare.php?from=719b029c16eeb1035da522fd641dfcc4cee6be74&to=bf7041045c9408490c395230047c5461de72fc39&stat=instructions%3Au . Fixes #62096 Fixes #74581 >From 464aaf0944cac75ccc689ebb82e08554c12c6340 Mon Sep 17 00:00:00 2001 From: Corentin Jabot <corentinja...@gmail.com> Date: Thu, 27 Mar 2025 16:25:07 +0100 Subject: [PATCH] [Clang][WIP][RFC] Bypass TAD during overload resolution if a perfect match exists This implements the same overload resolution behavior as GCC, as described in https://wg21.link/p3606 (section 1-2, not 3) If during overload resolution, there is a non-template candidate that would be always be picked - because each of the argument is a perfect match (ie the source and target types are the same), we do not perform deduction for any template candidate that might exists. The goal is to be able to merge #122423 without being too disruptive. This change means that the selection of the best viable candidate and template argument deduction become interleaved. To avoid rewriting half of Clang we store in `OverloadCandidateSet` enough information to be able to deduce template candidates from `OverloadCandidateSet::BestViableFunction`. Which means the lifetime of any object used by template argument must outlive a call to `Add*Template*Candidate`. This two phase resolution is not performed for some initialization as there are cases where template candidate are better match in these cases per the standard. It's also bypassed for code completion. The change has a nice impact on compile times https://llvm-compile-time-tracker.com/compare.php?from=719b029c16eeb1035da522fd641dfcc4cee6be74&to=bf7041045c9408490c395230047c5461de72fc39&stat=instructions%3Au Fixes #62096 Fixes #74581 --- clang/include/clang/Sema/Overload.h | 130 +++++++++++++- clang/include/clang/Sema/Sema.h | 25 +++ clang/lib/Sema/SemaCodeComplete.cpp | 6 +- clang/lib/Sema/SemaInit.cpp | 11 +- clang/lib/Sema/SemaOverload.cpp | 263 +++++++++++++++++++++++++--- 5 files changed, 395 insertions(+), 40 deletions(-) diff --git a/clang/include/clang/Sema/Overload.h b/clang/include/clang/Sema/Overload.h index 6e08762dcc6d7..2cc7e1809e26c 100644 --- a/clang/include/clang/Sema/Overload.h +++ b/clang/include/clang/Sema/Overload.h @@ -38,6 +38,7 @@ #include <cstddef> #include <cstdint> #include <utility> +#include <variant> namespace clang { @@ -743,6 +744,12 @@ class Sema; Standard.setAllToTypes(T); } + bool isPerfect(const ASTContext &C) const { + return (isStandard() && Standard.isIdentityConversion() && + C.hasSameType(Standard.getFromType(), Standard.getToType(2))) || + getKind() == StaticObjectArgumentConversion; + } + // True iff this is a conversion sequence from an initializer list to an // array or std::initializer. bool hasInitializerListContainerType() const { @@ -979,6 +986,18 @@ class Sema; return false; } + bool isPerfectMatch(const ASTContext &Ctx) const { + if (!Viable) + return false; + for (auto &C : Conversions) { + if (!C.isInitialized()) + return false; + if (!C.isPerfect(Ctx)) + return false; + } + return true; + } + bool TryToFixBadConversion(unsigned Idx, Sema &S) { bool CanFix = Fix.tryToFixConversion( Conversions[Idx].Bad.FromExpr, @@ -1015,6 +1034,61 @@ class Sema; RewriteKind(CRK_None) {} }; + struct NonDeducedConversionTemplateOverloadCandidate { + FunctionTemplateDecl *FunctionTemplate; + DeclAccessPair FoundDecl; + CXXRecordDecl *ActingContext; + Expr *From; + QualType ToType; + + LLVM_PREFERRED_TYPE(bool) + unsigned AllowObjCConversionOnExplicit : 1; + LLVM_PREFERRED_TYPE(bool) + unsigned AllowExplicit : 1; + LLVM_PREFERRED_TYPE(bool) + unsigned AllowResultConversion : 1; + }; + + struct NonDeducedMethodTemplateOverloadCandidate { + FunctionTemplateDecl *FunctionTemplate; + DeclAccessPair FoundDecl; + ArrayRef<Expr *> Args; + CXXRecordDecl *ActingContext; + Expr::Classification ObjectClassification; + QualType ObjectType; + + OverloadCandidateParamOrder PO; + LLVM_PREFERRED_TYPE(bool) + unsigned SuppressUserConversions : 1; + LLVM_PREFERRED_TYPE(bool) + unsigned PartialOverloading : 1; + }; + + struct NonDeducedFunctionTemplateOverloadCandidate { + FunctionTemplateDecl *FunctionTemplate; + DeclAccessPair FoundDecl; + ArrayRef<Expr *> Args; + + CallExpr::ADLCallKind IsADLCandidate; + OverloadCandidateParamOrder PO; + LLVM_PREFERRED_TYPE(bool) + unsigned SuppressUserConversions : 1; + LLVM_PREFERRED_TYPE(bool) + unsigned PartialOverloading : 1; + LLVM_PREFERRED_TYPE(bool) + unsigned AllowExplicit : 1; + LLVM_PREFERRED_TYPE(bool) + unsigned AggregateCandidateDeduction : 1; + }; + + using NonDeducedTemplateOverloadCandidate = + std::variant<NonDeducedConversionTemplateOverloadCandidate, + NonDeducedMethodTemplateOverloadCandidate, + NonDeducedFunctionTemplateOverloadCandidate>; + + static_assert( + std::is_trivially_destructible_v<NonDeducedTemplateOverloadCandidate>); + /// OverloadCandidateSet - A set of overload candidates, used in C++ /// overload resolution (C++ 13.3). class OverloadCandidateSet { @@ -1043,6 +1117,8 @@ class Sema; /// C++ [over.match.call.general] /// Resolve a call through the address of an overload set. CSK_AddressOfOverloadSet, + + CSK_CodeCompletion, }; /// Information about operator rewrites to consider when adding operator @@ -1116,6 +1192,7 @@ class Sema; private: SmallVector<OverloadCandidate, 16> Candidates; llvm::SmallPtrSet<uintptr_t, 16> Functions; + SmallVector<NonDeducedTemplateOverloadCandidate, 8> NonDeducedCandidates; // Allocator for ConversionSequenceLists. We store the first few of these // inline to avoid allocation for small sets. @@ -1126,7 +1203,7 @@ class Sema; OperatorRewriteInfo RewriteInfo; constexpr static unsigned NumInlineBytes = - 24 * sizeof(ImplicitConversionSequence); + 32 * sizeof(ImplicitConversionSequence); unsigned NumInlineBytesUsed = 0; alignas(void *) char InlineSpace[NumInlineBytes]; @@ -1144,8 +1221,8 @@ class Sema; // It's simpler if this doesn't need to consider alignment. static_assert(alignof(T) == alignof(void *), "Only works for pointer-aligned types."); - static_assert(std::is_trivial<T>::value || - std::is_same<ImplicitConversionSequence, T>::value, + static_assert(std::is_trivially_destructible_v<T> || + (std::is_same_v<ImplicitConversionSequence, T>), "Add destruction logic to OverloadCandidateSet::clear()."); unsigned NBytes = sizeof(T) * N; @@ -1199,8 +1276,12 @@ class Sema; iterator begin() { return Candidates.begin(); } iterator end() { return Candidates.end(); } - size_t size() const { return Candidates.size(); } - bool empty() const { return Candidates.empty(); } + size_t size() const { + return Candidates.size() + NonDeducedCandidates.size(); + } + bool empty() const { + return Candidates.empty() && NonDeducedCandidates.empty(); + } /// Allocate storage for conversion sequences for NumConversions /// conversions. @@ -1216,6 +1297,19 @@ class Sema; return ConversionSequenceList(Conversions, NumConversions); } + llvm::MutableArrayRef<Expr *> getPersistentArgsArray(unsigned N) { + Expr **Exprs = slabAllocate<Expr *>(N); + return llvm::MutableArrayRef<Expr *>(Exprs, N); + } + + template <typename... T> + llvm::MutableArrayRef<Expr *> getPersistentArgsArray(T *...Exprs) { + llvm::MutableArrayRef<Expr *> Arr = + getPersistentArgsArray(sizeof...(Exprs)); + llvm::copy(std::initializer_list<Expr *>{Exprs...}, Arr.data()); + return Arr; + } + /// Add a new candidate with NumConversions conversion sequence slots /// to the overload set. OverloadCandidate &addCandidate(unsigned NumConversions = 0, @@ -1231,10 +1325,36 @@ class Sema; return C; } + void AddNonDeducedTemplateCandidate( + FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, + ArrayRef<Expr *> Args, bool SuppressUserConversions, + bool PartialOverloading, bool AllowExplicit, + CallExpr::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO, + bool AggregateCandidateDeduction); + + void AddNonDeducedMethodTemplateCandidate( + FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, + CXXRecordDecl *ActingContext, QualType ObjectType, + Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, + bool SuppressUserConversions, bool PartialOverloading, + OverloadCandidateParamOrder PO); + + void AddNonDeducedConversionTemplateCandidate( + FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, + CXXRecordDecl *ActingContext, Expr *From, QualType ToType, + bool AllowObjCConversionOnExplicit, bool AllowExplicit, + bool AllowResultConversion); + + void InjectNonDeducedTemplateCandidates(Sema &S); + /// Find the best viable function on this overload set, if it exists. OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator& Best); + OverloadingResult + BestViableFunctionImpl(Sema &S, SourceLocation Loc, + OverloadCandidateSet::iterator &Best); + SmallVector<OverloadCandidate *, 32> CompleteCandidates( Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, SourceLocation OpLoc = SourceLocation(), diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h index 066bce61c74c1..90ea990315cff 100644 --- a/clang/include/clang/Sema/Sema.h +++ b/clang/include/clang/Sema/Sema.h @@ -60,6 +60,7 @@ #include "clang/Sema/DeclSpec.h" #include "clang/Sema/ExternalSemaSource.h" #include "clang/Sema/IdentifierResolver.h" +#include "clang/Sema/Overload.h" #include "clang/Sema/Ownership.h" #include "clang/Sema/ParsedAttr.h" #include "clang/Sema/Redeclaration.h" @@ -10342,9 +10343,26 @@ class Sema final : public SemaBase { OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, OverloadCandidateParamOrder PO = {}); + void AddMethodTemplateCandidateImmediately( + OverloadCandidateSet &CandidateSet, FunctionTemplateDecl *MethodTmpl, + DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, + TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, + Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, + bool SuppressUserConversions, bool PartialOverloading, + OverloadCandidateParamOrder PO); + /// Add a C++ function template specialization as a candidate /// in the candidate set, using template argument deduction to produce /// an appropriate function template specialization. + + void AddTemplateOverloadCandidateImmediately( + OverloadCandidateSet &CandidateSet, + FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, + TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, + bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit, + ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO, + bool AggregateCandidateDeduction); + void AddTemplateOverloadCandidate( FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, @@ -10389,6 +10407,13 @@ class Sema final : public SemaBase { OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion = true); + void AddTemplateConversionCandidateImmediately( + OverloadCandidateSet &CandidateSet, + FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, + CXXRecordDecl *ActingContext, Expr *From, QualType ToType, + bool AllowObjCConversionOnExplicit, bool AllowExplicit, + bool AllowResultConversion); + /// AddSurrogateCandidate - Adds a "surrogate" candidate function that /// converts the given @c Object to a function pointer via the /// conversion function @c Conversion, and then attempts to call it diff --git a/clang/lib/Sema/SemaCodeComplete.cpp b/clang/lib/Sema/SemaCodeComplete.cpp index 2003701b65654..e314f6859d71c 100644 --- a/clang/lib/Sema/SemaCodeComplete.cpp +++ b/clang/lib/Sema/SemaCodeComplete.cpp @@ -6364,7 +6364,8 @@ SemaCodeCompletion::ProduceCallSignatureHelp(Expr *Fn, ArrayRef<Expr *> Args, Expr *NakedFn = Fn->IgnoreParenCasts(); // Build an overload candidate set based on the functions we find. SourceLocation Loc = Fn->getExprLoc(); - OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); + OverloadCandidateSet CandidateSet(Loc, + OverloadCandidateSet::CSK_CodeCompletion); if (auto ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn)) { SemaRef.AddOverloadedCallCandidates(ULE, ArgsWithoutDependentTypes, @@ -6567,7 +6568,8 @@ QualType SemaCodeCompletion::ProduceConstructorSignatureHelp( // FIXME: Provide support for variadic template constructors. if (CRD) { - OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); + OverloadCandidateSet CandidateSet(Loc, + OverloadCandidateSet::CSK_CodeCompletion); for (NamedDecl *C : SemaRef.LookupConstructors(CRD)) { if (auto *FD = dyn_cast<FunctionDecl>(C)) { // FIXME: we can't yet provide correct signature help for initializer diff --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp index 9814c3f456f0d..f947b29e16881 100644 --- a/clang/lib/Sema/SemaInit.cpp +++ b/clang/lib/Sema/SemaInit.cpp @@ -10043,12 +10043,15 @@ QualType Sema::DeduceTemplateSpecializationFromInitializer( // When [...] the constructor [...] is a candidate by // - [over.match.copy] (in all cases) if (TD) { - SmallVector<Expr *, 8> TmpInits; - for (Expr *E : Inits) + MutableArrayRef<Expr *> TmpInits = + Candidates.getPersistentArgsArray(Inits.size()); + for (auto [I, E] : llvm::enumerate(Inits)) { if (auto *DI = dyn_cast<DesignatedInitExpr>(E)) - TmpInits.push_back(DI->getInit()); + TmpInits[I] = DI->getInit(); else - TmpInits.push_back(E); + TmpInits[I] = E; + } + AddTemplateOverloadCandidate( TD, FoundDecl, /*ExplicitArgs=*/nullptr, TmpInits, Candidates, /*SuppressUserConversions=*/false, diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp index 6d8006b35dcf4..b2a99de9d38e2 100644 --- a/clang/lib/Sema/SemaOverload.cpp +++ b/clang/lib/Sema/SemaOverload.cpp @@ -31,6 +31,7 @@ #include "clang/Sema/Lookup.h" #include "clang/Sema/Overload.h" #include "clang/Sema/SemaCUDA.h" +#include "clang/Sema/SemaCodeCompletion.h" #include "clang/Sema/SemaObjC.h" #include "clang/Sema/Template.h" #include "clang/Sema/TemplateDeduction.h" @@ -45,6 +46,7 @@ #include <cstddef> #include <cstdlib> #include <optional> +#include <variant> using namespace clang; using namespace sema; @@ -7797,6 +7799,28 @@ void Sema::AddMethodTemplateCandidate( if (!CandidateSet.isNewCandidate(MethodTmpl, PO)) return; + if (CandidateSet.getKind() == OverloadCandidateSet::CSK_CodeCompletion || + ExplicitTemplateArgs) { + AddMethodTemplateCandidateImmediately( + CandidateSet, MethodTmpl, FoundDecl, ActingContext, + ExplicitTemplateArgs, ObjectType, ObjectClassification, Args, + SuppressUserConversions, PartialOverloading, PO); + return; + } + + CandidateSet.AddNonDeducedMethodTemplateCandidate( + MethodTmpl, FoundDecl, ActingContext, ObjectType, ObjectClassification, + Args, SuppressUserConversions, PartialOverloading, PO); +} + +void Sema::AddMethodTemplateCandidateImmediately( + OverloadCandidateSet &CandidateSet, FunctionTemplateDecl *MethodTmpl, + DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, + TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, + Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, + bool SuppressUserConversions, bool PartialOverloading, + OverloadCandidateParamOrder PO) { + // C++ [over.match.funcs]p7: // In each case where a candidate is a function template, candidate // function template specializations are generated using template argument @@ -7826,7 +7850,7 @@ void Sema::AddMethodTemplateCandidate( Candidate.Function = MethodTmpl->getTemplatedDecl(); Candidate.Viable = false; Candidate.RewriteKind = - CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); + CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); Candidate.IsSurrogate = false; Candidate.IgnoreObjectArgument = cast<CXXMethodDecl>(Candidate.Function)->isStatic() || @@ -7836,8 +7860,8 @@ void Sema::AddMethodTemplateCandidate( Candidate.FailureKind = ovl_fail_bad_conversion; else { Candidate.FailureKind = ovl_fail_bad_deduction; - Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, - Info); + Candidate.DeductionFailure = + MakeDeductionFailureInfo(Context, Result, Info); } return; } @@ -7868,6 +7892,28 @@ void Sema::AddTemplateOverloadCandidate( if (!CandidateSet.isNewCandidate(FunctionTemplate, PO)) return; + if (CandidateSet.getKind() == OverloadCandidateSet::CSK_CodeCompletion || + ExplicitTemplateArgs) { + AddTemplateOverloadCandidateImmediately( + CandidateSet, FunctionTemplate, FoundDecl, ExplicitTemplateArgs, Args, + SuppressUserConversions, PartialOverloading, AllowExplicit, + IsADLCandidate, PO, AggregateCandidateDeduction); + return; + } + + CandidateSet.AddNonDeducedTemplateCandidate( + FunctionTemplate, FoundDecl, Args, SuppressUserConversions, + PartialOverloading, AllowExplicit, IsADLCandidate, PO, + AggregateCandidateDeduction); +} + +void Sema::AddTemplateOverloadCandidateImmediately( + OverloadCandidateSet &CandidateSet, FunctionTemplateDecl *FunctionTemplate, + DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, + ArrayRef<Expr *> Args, bool SuppressUserConversions, + bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate, + OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) { + // If the function template has a non-dependent explicit specification, // exclude it now if appropriate; we are not permitted to perform deduction // and substitution in this case. @@ -7911,7 +7957,7 @@ void Sema::AddTemplateOverloadCandidate( Candidate.Function = FunctionTemplate->getTemplatedDecl(); Candidate.Viable = false; Candidate.RewriteKind = - CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); + CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); Candidate.IsSurrogate = false; Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate); // Ignore the object argument if there is one, since we don't have an object @@ -7924,8 +7970,8 @@ void Sema::AddTemplateOverloadCandidate( Candidate.FailureKind = ovl_fail_bad_conversion; else { Candidate.FailureKind = ovl_fail_bad_deduction; - Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, - Info); + Candidate.DeductionFailure = + MakeDeductionFailureInfo(Context, Result, Info); } return; } @@ -8267,6 +8313,25 @@ void Sema::AddTemplateConversionCandidate( if (!CandidateSet.isNewCandidate(FunctionTemplate)) return; + if (CandidateSet.getKind() == OverloadCandidateSet::CSK_CodeCompletion) { + AddTemplateConversionCandidateImmediately( + CandidateSet, FunctionTemplate, FoundDecl, ActingDC, From, ToType, + AllowObjCConversionOnExplicit, AllowExplicit, AllowResultConversion); + + return; + } + + CandidateSet.AddNonDeducedConversionTemplateCandidate( + FunctionTemplate, FoundDecl, ActingDC, From, ToType, + AllowObjCConversionOnExplicit, AllowExplicit, AllowResultConversion); +} + +void Sema::AddTemplateConversionCandidateImmediately( + OverloadCandidateSet &CandidateSet, FunctionTemplateDecl *FunctionTemplate, + DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, + QualType ToType, bool AllowObjCConversionOnExplicit, bool AllowExplicit, + bool AllowResultConversion) { + // If the function template has a non-dependent explicit specification, // exclude it now if appropriate; we are not permitted to perform deduction // and substitution in this case. @@ -8294,15 +8359,15 @@ void Sema::AddTemplateConversionCandidate( Candidate.Viable = false; Candidate.FailureKind = ovl_fail_bad_deduction; Candidate.ExplicitCallArguments = 1; - Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, - Info); + Candidate.DeductionFailure = + MakeDeductionFailureInfo(Context, Result, Info); return; } // Add the conversion function template specialization produced by // template argument deduction as a candidate. assert(Specialization && "Missing function template specialization?"); - AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, + AddConversionCandidate(Specialization, FoundDecl, ActingContext, From, ToType, CandidateSet, AllowObjCConversionOnExplicit, AllowExplicit, AllowResultConversion, Info.hasStrictPackMatch()); @@ -8441,6 +8506,13 @@ void Sema::AddNonMemberOperatorCandidates( NamedDecl *D = F.getDecl()->getUnderlyingDecl(); ArrayRef<Expr *> FunctionArgs = Args; + auto ReversedArgs = [&, Arr = ArrayRef<Expr *>{}]() mutable { + if (Arr.empty()) + Arr = CandidateSet.getPersistentArgsArray(FunctionArgs[1], + FunctionArgs[0]); + return Arr; + }; + FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); FunctionDecl *FD = FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); @@ -8455,18 +8527,18 @@ void Sema::AddNonMemberOperatorCandidates( if (FunTmpl) { AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs, FunctionArgs, CandidateSet); - if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) - AddTemplateOverloadCandidate( - FunTmpl, F.getPair(), ExplicitTemplateArgs, - {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false, - true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed); + if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) { + AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs, + ReversedArgs(), CandidateSet, false, false, + true, ADLCallKind::NotADL, + OverloadCandidateParamOrder::Reversed); + } } else { if (ExplicitTemplateArgs) continue; AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet); if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) - AddOverloadCandidate(FD, F.getPair(), - {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, + AddOverloadCandidate(FD, F.getPair(), ReversedArgs(), CandidateSet, false, false, true, false, ADLCallKind::NotADL, {}, OverloadCandidateParamOrder::Reversed); } @@ -10191,6 +10263,12 @@ Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, // FIXME: Pass in the explicit template arguments? ArgumentDependentLookup(Name, Loc, Args, Fns); + auto ReversedArgs = [&, Arr = ArrayRef<Expr *>{}]() mutable { + if (Arr.empty()) + Arr = CandidateSet.getPersistentArgsArray(Args[1], Args[0]); + return Arr; + }; + // Erase all of the candidates we already knew about. for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), CandEnd = CandidateSet.end(); @@ -10217,7 +10295,7 @@ Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL); if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) { AddOverloadCandidate( - FD, FoundDecl, {Args[1], Args[0]}, CandidateSet, + FD, FoundDecl, ReversedArgs(), CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading, /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL, {}, OverloadCandidateParamOrder::Reversed); @@ -10231,8 +10309,8 @@ Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, if (CandidateSet.getRewriteInfo().shouldAddReversed( *this, Args, FTD->getTemplatedDecl())) { AddTemplateOverloadCandidate( - FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]}, - CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading, + FTD, FoundDecl, ExplicitTemplateArgs, ReversedArgs(), CandidateSet, + /*SuppressUserConversions=*/false, PartialOverloading, /*AllowExplicit=*/true, ADLCallKind::UsesADL, OverloadCandidateParamOrder::Reversed); } @@ -10905,6 +10983,93 @@ bool OverloadCandidate::NotValidBecauseConstraintExprHasError() const { ->Satisfaction.ContainsErrors; } +void OverloadCandidateSet::AddNonDeducedTemplateCandidate( + FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, + ArrayRef<Expr *> Args, bool SuppressUserConversions, + bool PartialOverloading, bool AllowExplicit, + CallExpr::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO, + bool AggregateCandidateDeduction) { + NonDeducedFunctionTemplateOverloadCandidate C{FunctionTemplate, + FoundDecl, + Args, + IsADLCandidate, + PO, + SuppressUserConversions, + PartialOverloading, + AllowExplicit, + AggregateCandidateDeduction}; + NonDeducedCandidates.emplace_back(std::move(C)); +} + +void OverloadCandidateSet::AddNonDeducedMethodTemplateCandidate( + FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, + CXXRecordDecl *ActingContext, QualType ObjectType, + Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, + bool SuppressUserConversions, bool PartialOverloading, + OverloadCandidateParamOrder PO) { + NonDeducedMethodTemplateOverloadCandidate C{ + MethodTmpl, FoundDecl, Args, ActingContext, + ObjectClassification, ObjectType, PO, SuppressUserConversions, + PartialOverloading}; + NonDeducedCandidates.emplace_back(std::move(C)); +} + +void OverloadCandidateSet::AddNonDeducedConversionTemplateCandidate( + FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, + CXXRecordDecl *ActingContext, Expr *From, QualType ToType, + bool AllowObjCConversionOnExplicit, bool AllowExplicit, + bool AllowResultConversion) { + + NonDeducedConversionTemplateOverloadCandidate C{ + FunctionTemplate, FoundDecl, + ActingContext, From, + ToType, AllowObjCConversionOnExplicit, + AllowExplicit, AllowResultConversion}; + + NonDeducedCandidates.emplace_back(std::move(C)); +} + +static void +AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet, + NonDeducedMethodTemplateOverloadCandidate &&C) { + + S.AddMethodTemplateCandidateImmediately( + CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext, + /*ExplicitTemplateArgs=*/nullptr, C.ObjectType, C.ObjectClassification, + C.Args, C.SuppressUserConversions, C.PartialOverloading, C.PO); +} + +static void +AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet, + NonDeducedFunctionTemplateOverloadCandidate &&C) { + S.AddTemplateOverloadCandidateImmediately( + CandidateSet, C.FunctionTemplate, C.FoundDecl, + /*ExplicitTemplateArgs=*/nullptr, C.Args, C.SuppressUserConversions, + C.PartialOverloading, C.AllowExplicit, C.IsADLCandidate, C.PO, + C.AggregateCandidateDeduction); +} + +static void AddTemplateOverloadCandidate( + Sema &S, OverloadCandidateSet &CandidateSet, + NonDeducedConversionTemplateOverloadCandidate &&C) { + return S.AddTemplateConversionCandidateImmediately( + CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext, C.From, + C.ToType, C.AllowObjCConversionOnExplicit, C.AllowExplicit, + C.AllowResultConversion); +} + +void OverloadCandidateSet::InjectNonDeducedTemplateCandidates(Sema &S) { + Candidates.reserve(Candidates.size() + NonDeducedCandidates.size()); + for (auto &&Elem : NonDeducedCandidates) { + std::visit( + [&](auto &&Cand) { + AddTemplateOverloadCandidate(S, *this, std::move(Cand)); + }, + Elem); + } + NonDeducedCandidates.clear(); +} + /// Computes the best viable function (C++ 13.3.3) /// within an overload candidate set. /// @@ -10918,7 +11083,44 @@ bool OverloadCandidate::NotValidBecauseConstraintExprHasError() const { OverloadingResult OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, iterator &Best) { + + bool TwoPhaseResolution = + !NonDeducedCandidates.empty() && Kind != CSK_CodeCompletion && + Kind != CSK_InitByUserDefinedConversion && Kind != CSK_InitByConstructor; + + if (TwoPhaseResolution) { + Best = end(); + for (auto It = begin(); It != end(); ++It) { + if (It->isPerfectMatch(S.getASTContext())) { + if (Best == end()) { + Best = It; + } else { + Best = end(); + break; + } + } + } + if (Best != end()) { + Best->Best = true; + if (Best->Function && Best->Function->isDeleted()) + return OR_Deleted; + if (auto *M = dyn_cast_or_null<CXXMethodDecl>(Best->Function); + Kind == CSK_AddressOfOverloadSet && M && + M->isImplicitObjectMemberFunction()) { + return OR_No_Viable_Function; + } + return OR_Success; + } + } + InjectNonDeducedTemplateCandidates(S); + return BestViableFunctionImpl(S, Loc, Best); +} + +OverloadingResult OverloadCandidateSet::BestViableFunctionImpl( + Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best) { + llvm::SmallVector<OverloadCandidate *, 16> Candidates; + Candidates.reserve(this->Candidates.size()); std::transform(begin(), end(), std::back_inserter(Candidates), [](OverloadCandidate &Cand) { return &Cand; }); @@ -10953,7 +11155,6 @@ OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, } } - // Find the best viable function. Best = end(); for (auto *Cand : Candidates) { Cand->Best = false; @@ -10975,9 +11176,8 @@ OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, if (Best == end()) return OR_No_Viable_Function; + llvm::SmallVector<OverloadCandidate *, 4> PendingBest; llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; - - llvm::SmallVector<OverloadCandidate*, 4> PendingBest; PendingBest.push_back(&*Best); Best->Best = true; @@ -10999,8 +11199,6 @@ OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, } } } - - // If we found more than one best candidate, this is ambiguous. if (Best == end()) return OR_Ambiguous; @@ -11014,10 +11212,9 @@ OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, return OR_No_Viable_Function; } - if (!EquivalentCands.empty()) + if (NonDeducedCandidates.empty() && !EquivalentCands.empty()) S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, EquivalentCands); - return OR_Success; } @@ -12714,6 +12911,9 @@ SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates( Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, SourceLocation OpLoc, llvm::function_ref<bool(OverloadCandidate &)> Filter) { + + InjectNonDeducedTemplateCandidates(S); + // Sort the candidates by viability and position. Sorting directly would // be prohibitive, so we make a set of pointers and sort those. SmallVector<OverloadCandidate*, 32> Cands; @@ -14689,18 +14889,23 @@ void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, // rewritten candidates using these functions if necessary. AddNonMemberOperatorCandidates(Fns, Args, CandidateSet); + auto ReversedArgs = [&, Arr = ArrayRef<Expr *>{}]() mutable { + if (Arr.empty()) + Arr = CandidateSet.getPersistentArgsArray(Args[1], Args[0]); + return Arr; + }; + // Add operator candidates that are member functions. AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); if (CandidateSet.getRewriteInfo().allowsReversed(Op)) - AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet, + AddMemberOperatorCandidates(Op, OpLoc, ReversedArgs(), CandidateSet, OverloadCandidateParamOrder::Reversed); // In C++20, also add any rewritten member candidates. if (ExtraOp) { AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet); if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp)) - AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]}, - CandidateSet, + AddMemberOperatorCandidates(ExtraOp, OpLoc, ReversedArgs(), CandidateSet, OverloadCandidateParamOrder::Reversed); } _______________________________________________ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits