Skip to content

Commit b625c13

Browse files
authored
Fix constructing a ThreadSafeModule from a Module in a different Ctx. (#474)
1 parent 121a4eb commit b625c13

File tree

2 files changed

+33
-4
lines changed

2 files changed

+33
-4
lines changed

src/executionengine/ts_module.jl

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,23 @@ end
3737
Base.unsafe_convert(::Type{API.LLVMOrcThreadSafeModuleRef}, mod::ThreadSafeModule) = mod.ref
3838

3939
function ThreadSafeModule(mod::Module)
40+
if context(mod) != context(ts_context())
41+
# XXX: the C API doesn't expose the convenience method to create a TSModule from a
42+
# Module and a regular Context, only a method to create one from a Module
43+
# and a pre-existing TSContext, which isn't useful...
44+
# TODO: expose the other convenience method?
45+
# XXX: work around this by serializing/deserializing the module in the correct contex
46+
bitcode = convert(MemoryBuffer, mod)
47+
mod = context!(context(ts_context())) do
48+
parse(Module, bitcode)
49+
end
50+
end
51+
@assert context(mod) == context(ts_context())
52+
4053
ref = API.LLVMOrcCreateNewThreadSafeModule(mod, ts_context())
41-
ThreadSafeModule(ref)
54+
tsm = ThreadSafeModule(ref)
55+
mark_dispose(mod)
56+
return tsm
4257
end
4358

4459
function ThreadSafeModule(name::String)
@@ -48,9 +63,7 @@ function ThreadSafeModule(name::String)
4863
mod = context!(ctx) do
4964
Module(name)
5065
end
51-
tsm = ThreadSafeModule(mod)
52-
mark_dispose(mod)
53-
return tsm
66+
ThreadSafeModule(mod)
5467
end
5568

5669
function dispose(mod::ThreadSafeModule)

test/orc_tests.jl

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,22 @@ end
2424
true
2525
end
2626
end
27+
28+
@dispose ctx=Context() ts_ctx=ThreadSafeContext() begin
29+
src_mod = LLVM.Module("SomeModule")
30+
ts_mod = ThreadSafeModule(src_mod)
31+
ts_mod() do copied_mod
32+
# XXX: this is a very specific test to check the current implementation of the
33+
# ThreadSafeModule constructor, which currently copies the source module
34+
# from its context into the thread safe one. This is questionable; maybe
35+
# it should create a ThreadSafeModule in a ThreadSafeContext matching the
36+
# source context. However, that would result in a TSMod that doesn't match
37+
# the currently-active ts_context()...
38+
@test context(copied_mod) != context(src_mod)
39+
@test context(copied_mod) == context(ts_context())
40+
end
41+
dispose(ts_mod)
42+
end
2743
end
2844

2945
@testset "JITDylib" begin

0 commit comments

Comments
 (0)