Skip to content

Commit 1bfe1ca

Browse files
committed
[Distributed] make witness be the distributed thunk
1 parent 0dae896 commit 1bfe1ca

File tree

8 files changed

+250
-11
lines changed

8 files changed

+250
-11
lines changed

include/swift/SIL/SILDeclRef.h

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -414,8 +414,7 @@ struct SILDeclRef {
414414
defaultArgIndex,
415415
pointer.get<AutoDiffDerivativeFunctionIdentifier *>());
416416
}
417-
/// Returns the distributed entry point corresponding to the same
418-
/// decl.
417+
/// Returns the distributed entry point corresponding to the same decl.
419418
SILDeclRef asDistributed(bool distributed = true) const {
420419
return SILDeclRef(loc.getOpaqueValue(), kind,
421420
/*foreign=*/false,

lib/SIL/IR/SILDeclRef.cpp

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1052,6 +1052,8 @@ bool SILDeclRef::requiresNewVTableEntry() const {
10521052
return true;
10531053
if (!hasDecl())
10541054
return false;
1055+
// if (isDistributedThunk())
1056+
// return false;
10551057
if (isBackDeploymentThunk())
10561058
return false;
10571059
auto fnDecl = dyn_cast<AbstractFunctionDecl>(getDecl());

lib/SILGen/SILGenPoly.cpp

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4442,12 +4442,14 @@ void SILGenFunction::emitProtocolWitness(
44424442
// If the witness is isolated to a distributed actor, but the requirement is
44434443
// not, go through the distributed thunk.
44444444
if (witness.hasDecl() &&
4445-
getActorIsolation(witness.getDecl()).isDistributedActor() &&
4446-
requirement.hasDecl() &&
4447-
!getActorIsolation(requirement.getDecl()).isDistributedActor()) {
4448-
witness = SILDeclRef(
4449-
cast<AbstractFunctionDecl>(witness.getDecl())->getDistributedThunk())
4450-
.asDistributed();
4445+
getActorIsolation(witness.getDecl()).isDistributedActor()) {
4446+
if ((requirement.hasDecl() && !getActorIsolation(requirement.getDecl()).isDistributedActor()) ||
4447+
(requirement.hasDecl() && isa<FuncDecl>(requirement.getDecl()) && witness.getFuncDecl()->isDistributed())) {
4448+
fprintf(stderr, "[%s:%d] (%s) witness thunk\n", __FILE__, __LINE__, __FUNCTION__);
4449+
auto thunk = cast<AbstractFunctionDecl>(witness.getDecl())->getDistributedThunk();
4450+
thunk->dump();
4451+
witness = SILDeclRef(thunk) .asDistributed();
4452+
}
44514453
} else if (enterIsolation) {
44524454
// If we are supposed to enter the actor, do so now by hopping to the
44534455
// actor.

lib/Sema/CodeSynthesisDistributedActor.cpp

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -648,8 +648,13 @@ static FuncDecl *createDistributedThunkFunction(FuncDecl *func) {
648648
auto &C = func->getASTContext();
649649
auto DC = func->getDeclContext();
650650

651-
auto systemTy = getConcreteReplacementForProtocolActorSystemType(func);
652-
assert(systemTy &&
651+
// NOTE: So we don't need a thunk in the protocol, we should call the underlying
652+
// thing instead, which MUST have a thunk, since it must be a distributed func as well...
653+
if (dyn_cast<ProtocolDecl>(DC)) {
654+
return nullptr;
655+
}
656+
657+
assert(getConcreteReplacementForProtocolActorSystemType(func) &&
653658
"Thunk synthesis must have concrete actor system type available");
654659

655660
DeclName thunkName = func->getName();

lib/Sema/TypeCheckDistributed.cpp

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -503,7 +503,11 @@ bool CheckDistributedFunctionRequest::evaluate(
503503
serializationRequirements = getDistributedSerializationRequirementProtocols(
504504
getDistributedActorSystemType(actor)->getAnyNominal(),
505505
C.getProtocol(KnownProtocolKind::DistributedActorSystem));
506+
} else if (auto proto = dyn_cast<ProtocolDecl>(DC)) {
507+
// FIXME: if it has a n AS defined, we can do checks based on that, otherwise, don't
508+
return false;
506509
} else {
510+
func->dump();
507511
llvm_unreachable("Cannot handle types other than extensions and actor "
508512
"declarations in distributed function checking.");
509513
}

lib/Sema/TypeCheckProtocol.cpp

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1401,9 +1401,25 @@ bool WitnessChecker::findBestWitness(
14011401
attempt = static_cast<Attempt>(attempt + 1)) {
14021402
SmallVector<ValueDecl *, 4> witnesses;
14031403
switch (attempt) {
1404-
case Regular:
1404+
case Regular: {
14051405
witnesses = lookupValueWitnesses(requirement, ignoringNames);
1406+
1407+
// ValueDecl* thunk = nullptr;
1408+
// for (auto witness : witnesses) {
1409+
// if (auto func = dyn_cast<FuncDecl>(witness)) {
1410+
// if (func->isDistributed()) {
1411+
// thunk = func->getDistributedThunk();
1412+
// fprintf(stderr, "[%s:%d] (%s) ALSO CONSIDER THUNK!!!\n", __FILE__, __LINE__, __FUNCTION__);
1413+
// }
1414+
// }
1415+
// }
1416+
// if (thunk) {
1417+
// witnesses.clear();
1418+
// witnesses.push_back(thunk);
1419+
// }
1420+
14061421
break;
1422+
}
14071423
case OperatorsFromOverlay: {
14081424
// If we have a Clang declaration, the matching operator might be in the
14091425
// overlay for that module.
Lines changed: 165 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,165 @@
1+
// RUN: %empty-directory(%t)
2+
// RUN: %target-swift-frontend-emit-module -emit-module-path %t/FakeDistributedActorSystems.swiftmodule -module-name FakeDistributedActorSystems -disable-availability-checking %S/../Inputs/FakeDistributedActorSystems.swift
3+
// RUN: %target-build-swift -module-name main -Xfrontend -disable-availability-checking -j2 -parse-as-library -I %t %s %S/../Inputs/FakeDistributedActorSystems.swift -o %t/a.out
4+
// RUN: %target-run %t/a.out | %FileCheck %s --color --dump-input=always
5+
6+
// REQUIRES: executable_test
7+
// REQUIRES: concurrency
8+
// REQUIRES: distributed
9+
10+
// rdar://76038845
11+
// UNSUPPORTED: use_os_stdlib
12+
// UNSUPPORTED: back_deployment_runtime
13+
14+
// FIXME(distributed): Distributed actors currently have some issues on windows, isRemote always returns false. rdar://82593574
15+
// UNSUPPORTED: OS=windows-msvc
16+
17+
import Distributed
18+
import FakeDistributedActorSystems
19+
20+
21+
typealias DefaultDistributedActorSystem = FakeRoundtripActorSystem
22+
23+
protocol DistributedWorker: DistributedActor where ActorSystem == DefaultDistributedActorSystem {
24+
associatedtype WorkItem: Sendable & Codable
25+
associatedtype WorkResult: Sendable & Codable
26+
27+
// distributed requirement currently is forced to be `async throws`...
28+
// FIXME(distributed): requirements don't have to be async throws,
29+
// distributed makes them implicitly async throws anyway...
30+
distributed func submit(work: WorkItem) async throws -> WorkResult
31+
32+
// non distributed requirements can be witnessed with _normal_ functions
33+
func sync(work: WorkItem) -> WorkResult
34+
func async(work: WorkItem) async -> WorkResult
35+
func syncThrows(work: WorkItem) throws -> WorkResult
36+
func asyncThrows(work: WorkItem) async throws -> WorkResult
37+
}
38+
39+
distributed actor TheWorker: DistributedWorker {
40+
typealias ActorSystem = DefaultDistributedActorSystem
41+
typealias WorkItem = String
42+
typealias WorkResult = String
43+
44+
distributed func submit(work: WorkItem) async throws -> WorkResult {
45+
"\(#function): \(work)"
46+
}
47+
48+
func sync(work: WorkItem) -> WorkResult {
49+
return "\(#function): \(work)"
50+
}
51+
func async(work: WorkItem) async -> WorkResult {
52+
return "\(#function): \(work)"
53+
}
54+
func syncThrows(work: WorkItem) throws -> WorkResult {
55+
return "\(#function): \(work)"
56+
}
57+
func asyncThrows(work: WorkItem) async throws -> WorkResult {
58+
return "\(#function): \(work)"
59+
}
60+
}
61+
62+
func test_generic(system: DefaultDistributedActorSystem) async throws {
63+
let localW = TheWorker(actorSystem: system)
64+
let remoteW = try! TheWorker.resolve(id: localW.id, using: system)
65+
precondition(__isRemoteActor(remoteW))
66+
67+
// direct calls work ok:
68+
let replyDirect = try await remoteW.submit(work: "Direct")
69+
print("reply direct: \(replyDirect)")
70+
// CHECK: >> remoteCall: on:main.TheWorker, target:main.TheWorker.submit(work:), invocation:FakeInvocationEncoder(genericSubs: [], arguments: ["Direct"], returnType: Optional(Swift.String), errorType: Optional(Swift.Error)), throwing:Swift.Error, returning:Swift.String
71+
// CHECK: reply direct: submit(work:): Direct
72+
73+
func callWorker<W: DistributedWorker>(w: W) async throws -> String where W.WorkItem == String, W.WorkResult == String {
74+
try await w.submit(work: "Hello")
75+
}
76+
let reply = try await callWorker(w: remoteW)
77+
print("reply (remote): \(reply)")
78+
// CHECK: >> remoteCall: on:main.TheWorker, target:main.TheWorker.submit(work:), invocation:FakeInvocationEncoder(genericSubs: [], arguments: ["Hello"], returnType: Optional(Swift.String), errorType: Optional(Swift.Error)), throwing:Swift.Error, returning:Swift.String
79+
// CHECK: << remoteCall return: submit(work:): Hello
80+
// CHECK: reply (remote): submit(work:): Hello
81+
82+
let replyLocal = try await callWorker(w: localW)
83+
print("reply (local): \(replyLocal)")
84+
// CHECK-NOT: >> remoteCall
85+
// CHECK: reply (local): submit(work:): Hello
86+
}
87+
88+
func test_whenLocal(system: DefaultDistributedActorSystem) async throws {
89+
let localW = TheWorker(actorSystem: system)
90+
let remoteW = try! TheWorker.resolve(id: localW.id, using: system)
91+
precondition(__isRemoteActor(remoteW))
92+
93+
do {
94+
let replySync = await remoteW.whenLocal { __secretlyKnownToBeLocal in
95+
__secretlyKnownToBeLocal.sync(work: "test")
96+
}
97+
print("replySync (remote): \(replySync)")
98+
// CHECK: replySync (remote): nil
99+
100+
let replySyncThrows = try await remoteW.whenLocal { __secretlyKnownToBeLocal in
101+
try __secretlyKnownToBeLocal.syncThrows(work: "test")
102+
}
103+
print("replySyncThrows (remote): \(replySyncThrows)")
104+
// CHECK: replySyncThrows (remote): nil
105+
106+
let replyAsync = await remoteW.whenLocal { __secretlyKnownToBeLocal in
107+
await __secretlyKnownToBeLocal.async(work: "test")
108+
}
109+
print("replyAsync (remote): \(replyAsync)")
110+
// CHECK: replyAsync (remote): nil
111+
112+
let replyAsyncThrows = try await remoteW.whenLocal { __secretlyKnownToBeLocal in
113+
try await __secretlyKnownToBeLocal.asyncThrows(work: "test")
114+
}
115+
print("replyAsyncThrows (remote): \(replyAsyncThrows)")
116+
// CHECK: replyAsyncThrows (remote): nil
117+
}
118+
// ==== ----------------------------------------------------------------------
119+
120+
do {
121+
let replyDistSubmit = try await localW.whenLocal { __secretlyKnownToBeLocal in
122+
try await __secretlyKnownToBeLocal.submit(work: "local-test")
123+
}
124+
print("replyDistSubmit (local): \(replyDistSubmit ?? "nil")")
125+
// CHECK-NOT: >> remoteCall
126+
// CHECK: replyDistSubmit (local): submit(work:): local-test
127+
128+
let replySyncLocal = await localW.whenLocal { __secretlyKnownToBeLocal in
129+
__secretlyKnownToBeLocal.sync(work: "local-test")
130+
}
131+
print("replySyncLocal (local): \(replySyncLocal ?? "nil")")
132+
// CHECK-NOT: >> remoteCall
133+
// CHECK: replySyncLocal (local): sync(work:): local-test
134+
135+
let replySyncThrowsLocal = try await localW.whenLocal { __secretlyKnownToBeLocal in
136+
try __secretlyKnownToBeLocal.syncThrows(work: "local-test")
137+
}
138+
print("replySyncThrowsLocal (local): \(replySyncThrowsLocal ?? "nil")")
139+
// CHECK-NOT: >> remoteCall
140+
// CHECK: replySyncThrowsLocal (local): syncThrows(work:): local-test
141+
142+
let replyAsyncLocal = await localW.whenLocal { __secretlyKnownToBeLocal in
143+
await __secretlyKnownToBeLocal.async(work: "local-test")
144+
}
145+
print("replyAsyncLocal (local): \(replyAsyncLocal ?? "nil")")
146+
// CHECK-NOT: >> remoteCall
147+
// CHECK: replyAsyncLocal (local): async(work:): local-test
148+
149+
let replyAsyncThrowsLocal = try await localW.whenLocal { __secretlyKnownToBeLocal in
150+
try await __secretlyKnownToBeLocal.asyncThrows(work: "local-test")
151+
}
152+
print("replyAsyncThrowsLocal (local): \(replyAsyncThrowsLocal ?? "nil")")
153+
// CHECK-NOT: >> remoteCall
154+
// CHECK: replyAsyncThrowsLocal (local): asyncThrows(work:): local-test
155+
}
156+
}
157+
158+
@main struct Main {
159+
static func main() async {
160+
let system = DefaultDistributedActorSystem()
161+
try! await test_generic(system: system)
162+
print("==== ---------------------------------------------------")
163+
try! await test_whenLocal(system: system)
164+
}
165+
}
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
// RUN: %empty-directory(%t)
2+
// RUN: %target-swift-frontend-emit-module -emit-module-path %t/FakeDistributedActorSystems.swiftmodule -module-name FakeDistributedActorSystems -disable-availability-checking %S/Inputs/FakeDistributedActorSystems.swift
3+
// RUN: %target-swift-frontend -typecheck -verify -disable-availability-checking -I %t 2>&1 %s
4+
// REQUIRES: concurrency
5+
// REQUIRES: distributed
6+
7+
import Distributed
8+
import FakeDistributedActorSystems
9+
10+
@available(SwiftStdlib 5.5, *)
11+
typealias DefaultDistributedActorSystem = FakeActorSystem
12+
13+
import Distributed
14+
15+
protocol DistributedWorker: DistributedActor {
16+
associatedtype WorkItem: Sendable & Codable
17+
associatedtype WorkResult: Sendable & Codable
18+
19+
distributed func submit(work: WorkItem) async throws -> WorkResult
20+
}
21+
22+
distributed actor TheWorker: DistributedWorker {
23+
typealias ActorSystem = FakeActorSystem
24+
typealias WorkItem = String
25+
typealias WorkResult = String
26+
27+
distributed func submit(work: WorkItem) async throws -> WorkResult {
28+
work
29+
}
30+
}
31+
32+
distributed actor WorkerPool<Worker: DistributedWorker> {
33+
typealias ActorSystem = FakeActorSystem
34+
typealias WorkItem = Worker.WorkItem
35+
typealias WorkResult = Worker.WorkResult
36+
37+
func submit(work: WorkItem) async throws -> WorkResult {
38+
let worker = try await self.selectWorker()
39+
return try await worker.submit(work: work)
40+
// return try await TheWorker(actorSystem: actorSystem).submit(work: "X")
41+
}
42+
43+
func selectWorker() async throws -> Worker {
44+
fatalError()
45+
}
46+
}

0 commit comments

Comments
 (0)