Skip to content

Instantly share code, notes, and snippets.

@aviatesk
Created July 27, 2022 18:22
Show Gist options
  • Save aviatesk/9b247e5e64f78454a70c3ec94c1ab2ad to your computer and use it in GitHub Desktop.
Save aviatesk/9b247e5e64f78454a70c3ec94c1ab2ad to your computer and use it in GitHub Desktop.
V and S scratched something
import Core: MethodMatch
import Core.Compiler: _methods_by_ftype, InferenceParams, get_world_counter, MethodInstance,
specialize_method, InferenceResult, typeinf, InferenceState, NativeInterpreter,
code_cache
function custominvoke(f, args...)
@nospecialize f args
interp = NativeInterpreter(get_world_counter())
oc = invoke_in_absint(f, interp, args...)
oc(args...)
end
function invoke_in_absint(f, interp, args...)
@nospecialize f args
tt = Base.signature_type(f, Tuple{map(Core.Typeof, args)...})
mm = get_single_method_match(tt, InferenceParams(interp).MAX_METHODS, get_world_counter(interp))
mi = specialize_method(mm.method, mm.spec_types, mm.sparams)::MethodInstance
code = Core.Compiler.get(code_cache(interp), mi, nothing)
if code !== nothing
inf = code.inferred::Vector{UInt8}
ci = Base._uncompressed_ir(code, inf)
return Core.OpaqueClosure(ci)
end
result = InferenceResult(mi)
frame = InferenceState(result, #=cache=# :global, interp)
typeinf(interp, frame)
ci = frame.src
return Core.OpaqueClosure(ci)
end
function get_single_method_match(@nospecialize(tt), lim, world)
mms = _methods_by_ftype(tt, lim, world)
isa(mms, Bool) && single_match_error(tt)
local mm = nothing
for i = 1:length(mms)
mmᵢ = mms[i]::MethodMatch
if tt === mmᵢ.spec_types
mm === nothing || single_match_error(tt)
mm = mmᵢ
end
end
mm isa MethodMatch || single_match_error(tt)
return mm
end
using BenchmarkTools
@btime custominvoke(sin, 10)
@btime sin(10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment