Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ensure we are adding T : Differentiable conformance from protocol conditional conformance #77446

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions lib/SILGen/SILGenPoly.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7043,6 +7043,14 @@ void SILGenFunction::emitProtocolWitness(
FullExpr scope(Cleanups, cleanupLoc);
FormalEvaluationScope formalEvalScope(*this);

// The protocol conditional conformance itself might bring some T :
// Differentiable conformances. They are already added to the derivative
// generic signature. Update witness substitution map generic signature to
// have them as well.
if (auto *derivativeId = witness.getDerivativeFunctionIdentifier())
witnessSubs = SubstitutionMap::get(derivativeId->getDerivativeGenericSignature(),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should the correct witnessSubs be computed in Sema? See lib/AST/RequirementEnvironment.cpp

Copy link
Contributor Author

@asl asl Nov 8, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems to be calculated correctly there:
<τ_0_0 where τ_0_0 : Differentiable> is a witness generic thunk signature and the corresponding requirement-to-witness substitution map is:

(substitution_map generic_signature=<Self where Self : P>
  (substitution Self ->
    (bound_generic_struct_type decl="main.(file)[email protected]:3:8"
      (generic_type_param_type depth=0 index=0 param_kind=type)))
  (conformance type="Self"
    (normal_conformance type="Wrapper<T>" protocol="P"
      (assoc_type req="T" type="T")
      (assoc_conformance type="Self" proto="Copyable"
        (builtin_conformance type="Wrapper<T>" protocol="Copyable"))
      (assoc_conformance type="Self" proto="Escapable"
        (builtin_conformance type="Wrapper<T>" protocol="Escapable"))
      (assoc_conformance type="Self.T" proto="Differentiable"
        (abstract_conformance protocol="Differentiable"))
      (requirement "T" conforms_to "Differentiable"))))

However, witnessSubs here is:

(substitution_map generic_signature=<T where T : Copyable, T : Escapable>
  (substitution T ->
    (primary_archetype_type address=0x15c9d8c18 conforms_to="_Differentiation.(file).Differentiable" name="\xCF\x84_0_0"
      (interface_type=generic_type_param_type depth=0 index=0 param_kind=type)))
  (conformance type="T"
    (abstract_conformance protocol="Copyable"))
  (conformance type="T"
    (abstract_conformance protocol="Escapable")))

So T : Differentiable comes from conditional conformance via substitution and is not part of generic signature.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@slavapestov So, what do you think about this? Should we change the calculation somehow? For now I just made it conditional for autodiff and only adding T : Differentiable requirement. W/o this we are unable to calculate derivative function type in protocol conformance as we need to have corresponding associated types etc.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@slavapestov Any further suggestions here?

witnessSubs);

auto thunkTy = F.getLoweredFunctionType();

SmallVector<ManagedValue, 8> origParams;
Expand Down
26 changes: 26 additions & 0 deletions lib/Sema/TypeCheckProtocol.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,29 @@ static ValueDecl *getStandinForAccessor(AbstractStorageDecl *witness,
return witness;
}

static GenericSignature maybeAddDifferentiableFromContext(DeclContext *dc,
GenericSignature derivativeGenSig) {
auto conformanceGenSig = dc->getGenericSignatureOfContext();
if (!conformanceGenSig)
return derivativeGenSig;

// The protocol conditional conformance itself might bring some T :
// Differentiable conformances. Add them the the derivative generic signature.
SmallVector<Requirement, 4> diffRequirements;
llvm::copy_if(conformanceGenSig.getRequirements(),
std::back_inserter(diffRequirements),
[](const Requirement &requirement) {
if (requirement.getKind() != RequirementKind::Conformance)
return false;

auto protoKind = requirement.getProtocolDecl()->getKnownProtocolKind();
return protoKind && *protoKind == KnownProtocolKind::Differentiable;
});

return buildGenericSignature(dc->getASTContext(), derivativeGenSig,
{}, std::move(diffRequirements), /*allowInverses=*/true);
}

/// Given a witness, a requirement, and an existing `RequirementMatch` result,
/// check if the requirement's `@differentiable` attributes are met by the
/// witness.
Expand Down Expand Up @@ -425,6 +448,9 @@ matchWitnessDifferentiableAttr(DeclContext *dc, ValueDecl *req,
auto derivativeGenSig = witnessAFD->getGenericSignature();
if (supersetConfig)
derivativeGenSig = supersetConfig->derivativeGenericSignature;

derivativeGenSig = maybeAddDifferentiableFromContext(dc, derivativeGenSig);

// Use source location of the witness declaration as the source location
// of the implicit `@differentiable` attribute.
auto *newAttr = DifferentiableAttr::create(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// RUN: %target-swift-frontend -emit-sil -verify %s

// https://github.com/swiftlang/swift/issues/75711

// Ensure we propagate T : Differentiable conditional conformance

import _Differentiation

struct Wrapper<T> {
func read(_ t: T) -> T {
return t
}
}

protocol P {
associatedtype T: Differentiable

@differentiable(reverse)
func read(_: T) -> T
}

extension Wrapper: P where T: Differentiable {}