Skip to content
Closed
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
2 changes: 2 additions & 0 deletions src/GPUCompiler.jl
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,8 @@ include("precompile.jl")
function __init__()
STDERR_HAS_COLOR[] = get(stderr, :color, false)
empty!(session_results_cache)
# world ages from the session that generated the package image are meaningless here
@atomic overlay_miss_cache.entries = IdDict{Any,OverlayMissesRef}()

@static if !HAS_INTEGRATED_CACHE
# CodeInstances created by GPUCompiler's precompile workload are process-local.
Expand Down
5 changes: 3 additions & 2 deletions src/driver.jl
Original file line number Diff line number Diff line change
Expand Up @@ -259,8 +259,9 @@ const __llvm_initialized = Ref(false)
dyn_val
else
ft, tt = dyn_val
dyn_src = methodinstance(ft, tt, job.world)
CompilerJob(dyn_src, job.config, job.world)
dyn_job = CompilerJob(methodinstance(ft, tt, job.world), job.config,
job.world)
CompilerJob(dyn_job; source=methodinstance(dyn_job))
end

push!(get!(worklist, dyn_job, LLVM.CallInst[]), call)
Expand Down
115 changes: 113 additions & 2 deletions src/jlgen.jl
Original file line number Diff line number Diff line change
Expand Up @@ -105,10 +105,17 @@ end
sig = signature_type_by_tt(ft, tt)
@assert Base.isdispatchtuple(sig) # JuliaLang/julia#52233

mi = method_lookup_by_tt(sig, world, #=method_table=# nothing)
mi === nothing && throw(MethodError(ft, tt, world))
return mi
end

@inline function method_lookup_by_tt(@nospecialize(sig::Type), world::Integer,
mt::Union{Nothing,Core.MethodTable})
mi = ccall(:jl_method_lookup_by_tt, Any,
(Any, Csize_t, Any),
sig, world, #=method_table=# nothing)
mi === nothing && throw(MethodError(ft, tt, world))
sig, world, mt)
mi === nothing && return nothing
mi = mi::MethodInstance

# `jl_method_lookup_by_tt` and `jl_method_lookup` can return a unspecialized mi
Expand All @@ -125,6 +132,110 @@ else
const methodinstance = generic_methodinstance
end

# `jl_method_lookup_by_tt` supports overlay tables since JuliaLang/julia#60718
const HAS_OVERLAY_LOOKUP_BY_TT = v"1.11.9" <= VERSION < v"1.12-" ||
v"1.12.5" <= VERSION < v"1.13-" ||
VERSION >= v"1.13.0-beta2"

"""
methodinstance(job::CompilerJob)

Look up the method instance that `job` should compile: the one for the signature of
`job.source` in the method tables of the job (see [`method_table_view`](@ref)). This
differs from `job.source` when those tables contain an overlay method for the function
itself, which `methodinstance(ft, tt)` does not know about. Back-ends that support such
overlays should construct their jobs as follows:

```julia
job = CompilerJob(methodinstance(ft, tt), config)
job = CompilerJob(job; source=methodinstance(job))
```
"""
# specialized on the job type, as back-ends call this on every kernel launch
function methodinstance(job::CompilerJob)
sig = dispatch_signature(job.source.specTypes)
mtv = method_table_view(job)
@static if HAS_OVERLAY_LOOKUP_BY_TT
tables = overlay_tables(mtv)
if tables !== nothing
for mt in tables
overlay_missed(sig, job.world, mt) && continue
mi = method_lookup_by_tt(sig, job.world, mt)
mi === nothing || return mi
overlay_missed!(sig, job.world, mt)
end
mi = method_lookup_by_tt(sig, job.world, nothing)
mi === nothing && throw(signature_method_error(sig, job.world))
return mi
end
end
match = first(CC.findsup(sig, mtv))
match === nothing && throw(signature_method_error(sig, job.world))
return CC.specialize_method(match)::MethodInstance
end

# Julia does not cache failed lookups, which makes them several times slower than ones that
# succeed. Kernels rarely have an overlay method, so remember the misses. A lookup always
# has the same result in a given world, so a miss is valid in the world it happened in.
struct OverlayMisses
world::UInt
tables::Vector{Core.MethodTable} # not modified once published
end
mutable struct OverlayMissesRef
@atomic misses::OverlayMisses
end
mutable struct OverlayMissCache
# copied when adding a signature, so that lookups do not need to take the lock
@atomic entries::IdDict{Any,OverlayMissesRef}
const lock::ReentrantLock
end
const overlay_miss_cache = OverlayMissCache(IdDict{Any,OverlayMissesRef}(), ReentrantLock())

function overlay_missed(@nospecialize(sig::Type), world::UInt, mt::Core.MethodTable)
ref = get(@atomic(:acquire, overlay_miss_cache.entries), sig, nothing)
ref === nothing && return false
misses = @atomic :acquire ref.misses
misses.world == world || return false
for table in misses.tables
table === mt && return true
end
return false
end

function overlay_missed!(@nospecialize(sig::Type), world::UInt, mt::Core.MethodTable)
# lookups in future worlds fail, but may not later
world <= Base.get_world_counter() || return
@lock overlay_miss_cache.lock begin
entries = @atomic :monotonic overlay_miss_cache.entries
ref = get(entries, sig, nothing)
if ref === nothing
entries = copy(entries)
entries[sig] = OverlayMissesRef(OverlayMisses(world, [mt]))
@atomic :release overlay_miss_cache.entries = entries
else
misses = ref.misses
tables = misses.world == world ? [misses.tables; mt] : [mt]
@atomic :release ref.misses = OverlayMisses(world, tables)
end
end
return
end

@static if isdefined(Core, :TypeEgal)
function dispatch_signature(@nospecialize(sig::Type))
u = Base.unwrap_unionall(sig)::DataType
any(Base.isType, u.parameters) || return sig
return Base.rewrap_unionall(Tuple{(dispatch_key(p) for p in u.parameters)...}, sig)
end
else
dispatch_signature(@nospecialize(sig::Type)) = sig
end

function signature_method_error(@nospecialize(sig::Type), world::Integer)
params = (Base.unwrap_unionall(sig)::DataType).parameters
return MethodError(params[1], Tuple{params[2:end]...}, world)
end


## method overrides

Expand Down
19 changes: 7 additions & 12 deletions src/reflection.jl
Original file line number Diff line number Diff line change
Expand Up @@ -201,30 +201,25 @@ function descend(@nospecialize(sig); kwargs...)
end

function code_lowered(@nospecialize(job::CompilerJob); kwargs...)
sig = job.source.specTypes # XXX: can we just use the method instance?
code_lowered_by_type(sig; kwargs...)
code_lowered_by_mi(job.source; kwargs...)
end

function code_typed(@nospecialize(job::CompilerJob); interactive::Bool=false, kwargs...)
sig = job.source.specTypes # XXX: can we just use the method instance?
interp = get_interpreter(job)
if interactive
interp = get_interpreter(job)
descend(sig; warntype=false, interp, kwargs...)
descend(job.source.specTypes; warntype=false, interp, kwargs...)
else
interp = get_interpreter(job)
Base.code_typed_by_type(sig; interp, kwargs...)
code_typed_by_mi(job.source; interp, kwargs...)
end
end

function code_warntype(io::IO, @nospecialize(job::CompilerJob); interactive::Bool=false, kwargs...)
sig = job.source.specTypes # XXX: can we just use the method instance?
interp = get_interpreter(job)
if interactive
@assert io == stdout
interp = get_interpreter(job)
descend(sig; warntype=true, interp, kwargs...)
descend(job.source.specTypes; warntype=true, interp, kwargs...)
else
interp = get_interpreter(job)
code_warntype_by_type(io, sig; interp, kwargs...)
code_warntype_by_mi(io, job.source; interp, kwargs...)
end
end
code_warntype(@nospecialize(job::CompilerJob); kwargs...) = code_warntype(stdout, job; kwargs...)
Expand Down
52 changes: 31 additions & 21 deletions src/reflection_compat.jl
Original file line number Diff line number Diff line change
Expand Up @@ -3,35 +3,45 @@
using InteractiveUtils: highlighting
using Base: hasgenerator

function method_instances(@nospecialize(tt::Type), world::UInt=Base.get_world_counter())
return map(Core.Compiler.specialize_method, method_matches(tt; world))
end

function code_lowered_by_type(@nospecialize(tt); generated::Bool=true, debuginfo::Symbol=:default)

# like `Base.code_lowered`, but for a specific method instance
function code_lowered_by_mi(mi::MethodInstance; generated::Bool=true,
debuginfo::Symbol=:default)
debuginfo = Base.IRShow.debuginfo(debuginfo)
if debuginfo !== :source && debuginfo !== :none
throw(ArgumentError("'debuginfo' must be either :source or :none"))
end
return map(method_instances(tt)) do m
if generated && hasgenerator(m)
if Base.may_invoke_generator(m)
return ccall(:jl_code_for_staged, Any, (Any,), m)::CodeInfo
else
error("Could not expand generator for `@generated` method ", m, ". ",
"This can happen if the provided argument types (", t, ") are ",
"not leaf types, but the `generated` argument is `true`.")
end
if generated && hasgenerator(mi)
if Base.may_invoke_generator(mi)
return Any[ccall(:jl_code_for_staged, Any, (Any,), mi)::CodeInfo]
else
error("Could not expand generator for `@generated` method ", mi, ". ",
"This can happen if the provided argument types (", mi.specTypes, ") are ",
"not leaf types, but the `generated` argument is `true`.")
end
code = Base.uncompressed_ir(m.def::Method)
debuginfo === :none && Base.remove_linenums!(code)
return code
end
code = Base.uncompressed_ir(mi.def::Method)
debuginfo === :none && Base.remove_linenums!(code)
return Any[code]
end

# like `Base.code_typed_by_type`, but for a specific method instance
function code_typed_by_mi(mi::MethodInstance; interp::CC.AbstractInterpreter,
optimize::Bool=true, debuginfo::Symbol=:default)
debuginfo = Base.IRShow.debuginfo(debuginfo)
if debuginfo !== :source && debuginfo !== :none
throw(ArgumentError("'debuginfo' must be either :source or :none"))
end
ret = CC.typeinf_code(interp, mi.def::Method, mi.specTypes, mi.sparam_vals, optimize)
# 1.10/1.11 return the code and its return type, later versions only the code
code, rt = ret isa Tuple ? ret : (ret, ret === nothing ? Any : ret.rettype)
code === nothing && return Any[mi.def => Any]
debuginfo === :none && Base.remove_linenums!(code)
return Any[code => rt]
end

function code_warntype_by_type(io::IO, @nospecialize(tt);
debuginfo::Symbol=:default, optimize::Bool=false, kwargs...)
for (src, rettype) in Base.code_typed_by_type(tt; optimize, kwargs...)
function code_warntype_by_mi(io::IO, mi::MethodInstance;
debuginfo::Symbol=:default, optimize::Bool=false, kwargs...)
for (src, rettype) in code_typed_by_mi(mi; optimize, kwargs...)
if src isa Core.CodeInfo
code_warntype(io, src, rettype; debuginfo)
else
Expand Down
3 changes: 2 additions & 1 deletion test/helpers/native.jl
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,8 @@ function create_job(@nospecialize(func), @nospecialize(types);
target = NativeCompilerTarget(;jlruntime)
params = CompilerParams(entry_safepoint, method_table, relocations)
config = CompilerConfig(target, params; kernel=false, config_kwargs...)
CompilerJob(source, config), kwargs
job = CompilerJob(source, config)
CompilerJob(job; source=methodinstance(job)), kwargs
end

# Add an object to a fresh ORC JIT and supply its relocation words, the loader in miniature.
Expand Down
68 changes: 68 additions & 0 deletions test/native.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2872,6 +2872,74 @@ end
end
end

@testset "kernel overrides" begin
mod = @eval module $(gensym())
Base.Experimental.@MethodTable(method_table)

kernel() = 0
Base.Experimental.@overlay method_table kernel() = 1
end

@test @filecheck begin
# before 1.12, overlay methods are named `julia__kernel_N`
@check_label "@{{(julia|j)_+kernel_[0-9]+}}"
@check "ret i64 1"
Native.code_llvm(mod.kernel, Tuple{}; mod.method_table)
end

# reflection shows the method instance that is compiled
job, _ = Native.create_job(mod.kernel, (); mod.method_table)
@test job.source.def.external_mt === mod.method_table
lowered = only(GPUCompiler.code_lowered(job))
@test lowered.code[end] == Core.ReturnNode(1)
src, rt = only(GPUCompiler.code_typed(job))
@test src.code[end] == Core.ReturnNode(1)
@test rt === Int
@test occursin("return 1", sprint(GPUCompiler.code_warntype, job))

# ... also when that is not the method the job's tables would select
job = CompilerJob(job; source=methodinstance(typeof(mod.kernel), Tuple{}))
lowered = only(GPUCompiler.code_lowered(job))
@test lowered.code[end] == Core.ReturnNode(0)
src, _ = only(GPUCompiler.code_typed(job))
@test src.code[end] == Core.ReturnNode(0)

# the overlay is picked up when it is added after compiling the function
mod = @eval module $(gensym())
Base.Experimental.@MethodTable(method_table)
kernel() = 0
end
@test @filecheck begin
@check_label "@julia_kernel"
@check "ret i64 0"
Native.code_llvm(mod.kernel, Tuple{}; mod.method_table)
end
@eval mod Base.Experimental.@overlay method_table kernel() = 1
@test @filecheck begin
# before 1.12, overlay methods are named `julia__kernel_N`
@check_label "@{{(julia|j)_+kernel_[0-9]+}}"
@check "ret i64 1"
Native.code_llvm(mod.kernel, Tuple{}; mod.method_table)
end

# ... and for deferred compilation
mod = @eval module $(gensym())
using ..GPUCompiler
Base.Experimental.@MethodTable(method_table)
@noinline child() = 0
Base.Experimental.@overlay method_table @noinline child() = 1
function kernel()
ptr = GPUCompiler.deferred_codegen(Val(typeof(child)), Val(Tuple{}))
ccall(ptr, Int, ())
end
end
@test @filecheck begin
@check_label "define {{.*}} @{{(julia|j)_+child_[0-9]+}}"
@check "ret i64 1"
Native.code_llvm(mod.kernel, Tuple{}; mod.method_table, dump_module=true)
end
end

@testset "runtime functions from overlay methods" begin
# runtime library functions (`signal_exception`, `malloc`, ...) should be resolved
# through the job's method table, so that back-ends can keep GPU-only code out of
Expand Down
Loading