Skip to content
Draft
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
6 changes: 6 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,9 @@
the addresses a module embeds (the tests check every module); deterministic names and
object order; and the pass pipelines (`JuliaCppPipeline`, `NoPipeline`,
`CustomPipeline`, `run_pipeline!`).
- `emit_into!`: compile a closed set of CodeInstances, with the sources the caller's
interpreter inferred, into the caller's module (the driver for GPUCompiler.jl and
Enzyme.jl, as Julia's `jl_emit_native`), returning each one's jlcall and specsig entries
(`CompiledFunctions`) and the `CodegenOutput`. `CGModule` takes the IR source.
- `CodegenConfig`: `gcstack_arg` (specsig entries without the pgcstack argument, in the C
calling convention) and `safepoint_on_entry`, as Julia's `CodegenParams`.
7 changes: 7 additions & 0 deletions docs/src/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,13 @@ JuliaCodegen.has_backend
JuliaCodegen.AddrSpace
```

## Drivers

```@docs
JuliaCodegen.emit_into!
JuliaCodegen.CompiledFunctions
```

## Output and pipelines

```@docs
Expand Down
1 change: 1 addition & 0 deletions src/JuliaCodegen.jl
Original file line number Diff line number Diff line change
Expand Up @@ -42,5 +42,6 @@ include("specsig.jl")
include("cfunction.jl")
include("ir.jl")
include("output.jl")
include("emit_into.jl")

end
3 changes: 2 additions & 1 deletion src/cfunction.jl
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,8 @@ function emit_cfunction_call!(wc::FnCtx, @nospecialize(sigt), @nospecialize(decl
T_size = size_type(cgm)
P = T_ptr()
spec = try
specsig_abi(cgm, Any[sigt.parameters...], declrt)
# (the runtime's convention, which passes the pgcstack)
specsig_abi(cgm, Any[sigt.parameters...], declrt; gcstack_arg=true)
catch err
err isa Unsupported || rethrow()
nothing # (the jlcall convention)
Expand Down
22 changes: 16 additions & 6 deletions src/config.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

"""
JuliaCodegen.CodegenConfig(; target=host_target(), dialect=JuliaIR.Dialect(VERSION),
on_unsupported=:fallback, on_internal_error=:fallback)
on_unsupported=:fallback, on_internal_error=:fallback,
gcstack_arg=true, safepoint_on_entry=true)

The configuration of the code generator, which generates code for the running Julia:

Expand All @@ -12,7 +13,11 @@ The configuration of the code generator, which generates code for the running Ju
(`JuliaIR.Dialect(VERSION; gc_barrier=:snapshot)`);
- `on_unsupported`, `on_internal_error`: what happens when a function uses an unsupported
construct, or the code generator fails: `:fallback` to Julia's code generator (internal
errors are reported), or `:error`. Tests use `:error` for both.
errors are reported), or `:error`. Tests use `:error` for both;
- `gcstack_arg`, `safepoint_on_entry`: as Julia's `CodegenParams`, whether entries in the
specsig convention take the pgcstack as an argument (`swiftself`; without it, they use
the C calling convention), and whether functions poll for a safepoint on entry. Targets
without Julia's runtime, like GPUs, turn both off.

The facts about the running Julia's runtime are `config.runtime`, see
[`RuntimeFacts`](@ref JuliaCodegen.RuntimeFacts).
Expand All @@ -23,20 +28,25 @@ struct CodegenConfig
runtime::RuntimeFacts
on_unsupported::Symbol
on_internal_error::Symbol
gcstack_arg::Bool
safepoint_on_entry::Bool

function CodegenConfig(target::Target, dialect::JuliaIR.Dialect, on_unsupported::Symbol,
on_internal_error::Symbol)
on_internal_error::Symbol, gcstack_arg::Bool, safepoint_on_entry::Bool)
dialect.minor == JuliaIR.Dialect(VERSION).minor ||
throw(ArgumentError("$dialect is not the dialect of the running Julia; code is only generated for the running Julia"))
for (name, value) in ((:on_unsupported, on_unsupported),
(:on_internal_error, on_internal_error))
value in FAILURE_POLICIES ||
throw(ArgumentError("invalid $name policy :$value; expected one of $(join(FAILURE_POLICIES, ", "))"))
end
new(target, dialect, runtime_facts(), on_unsupported, on_internal_error)
new(target, dialect, runtime_facts(), on_unsupported, on_internal_error, gcstack_arg,
safepoint_on_entry)
end
end

CodegenConfig(; target::Target=host_target(), dialect::JuliaIR.Dialect=JuliaIR.Dialect(VERSION),
on_unsupported::Symbol=:fallback, on_internal_error::Symbol=:fallback) =
CodegenConfig(target, dialect, on_unsupported, on_internal_error)
on_unsupported::Symbol=:fallback, on_internal_error::Symbol=:fallback,
gcstack_arg::Bool=true, safepoint_on_entry::Bool=true) =
CodegenConfig(target, dialect, on_unsupported, on_internal_error, gcstack_arg,
safepoint_on_entry)
16 changes: 13 additions & 3 deletions src/context.jl
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,18 @@ struct Entry
end

"""
JuliaCodegen.CGModule(mod::LLVM.Module, config::CodegenConfig; world)
JuliaCodegen.CGModule(mod::LLVM.Module, config::CodegenConfig; world, ir_source=get_ir,
throwing_stubs=true)

The state of generating code into the LLVM module `mod` (in the LLVM context it was
created in): the functions emitted for method instances, the objects the code refers to,
and the per-context type layouts and TBAA metadata. Names are numbered per module, so that
generating the same code twice gives the same IR.

The IR of a function comes from `ir_source(mi, world) -> (ir, rettype)`, by default
Julia's native inference ([`get_ir`](@ref JuliaCodegen.get_ir)); it throws `Unsupported`
for functions it has no IR for. With `throwing_stubs`, functions that always throw (error
paths) call their native code instead of being compiled.
"""
mutable struct CGModule
mod::LLVM.Module
Expand All @@ -51,15 +57,19 @@ mutable struct CGModule
fallbacks::Vector{Pair{Core.MethodInstance,Any}}
"The entry points emitted."
entries::Vector{Entry}
ir_source::Any
throwing_stubs::Bool
counter::Int
end

function CGModule(mod::LLVM.Module, config::CodegenConfig; world::UInt=Base.get_world_counter())
function CGModule(mod::LLVM.Module, config::CodegenConfig; world::UInt=Base.get_world_counter(),
ir_source=get_ir, throwing_stubs::Bool=true)
mod.triple = config.target.triple
mod.datalayout = config.target.datalayout
return CGModule(mod, config, world, Layouts(config), TBAA(config.dialect),
IdDict{Core.MethodInstance,FuncInfo}(), Tuple{FuncInfo,Any}[],
IdDict{Any,LLVM.GlobalVariable}(), Pair{Core.MethodInstance,Any}[], Entry[], 0)
IdDict{Any,LLVM.GlobalVariable}(), Pair{Core.MethodInstance,Any}[], Entry[], ir_source,
throwing_stubs, 0)
end

"A name that is unique in the module, from `prefix` and the function `f` (if any)."
Expand Down
101 changes: 101 additions & 0 deletions src/emit_into.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
# The driver for compilers that infer code themselves (GPUCompiler.jl, Enzyme.jl): compile a
# closed set of CodeInstances, with the IR the caller's interpreter inferred, into a module
# the caller owns. This is what Julia's `jl_emit_native` does for them, and what it returns:
# the functions of each CodeInstance, and the objects the code refers to.

"""
JuliaCodegen.CompiledFunctions

The functions emitted for a CodeInstance by [`emit_into!`](@ref JuliaCodegen.emit_into!):
`func`, its entry in the jlcall convention, and `specfunc`, its entry in the specsig
convention (see [`specsig_abi`](@ref JuliaCodegen.specsig_abi)), or `nothing` when the
signature isn't handled in it.
"""
struct CompiledFunctions
func::String
specfunc::Union{Nothing,String}
end

"""
JuliaCodegen.emit_into!(mod, codeinfos; config=CodegenConfig(), world) -> (compiled, output)
JuliaCodegen.emit_into!(cgm, codeinfos) -> (compiled, output)

Compile the CodeInstances of `codeinfos`, `(ci, src)` pairs whose source `src` (a
`CodeInfo` or `IRCode`, optimized) the caller's interpreter inferred, into the module `mod`
(or the module of `cgm`), as Julia's `jl_emit_native` does:

- the IR of every function comes from `codeinfos`, with the return type of its
CodeInstance; `:invoke`s of the CodeInstances (or method instances) of the set call
their functions, and any other is compiled as a call of native code (a fallback, see
`output.fallbacks`), or throws with `on_unsupported = :error`;
- functions that always throw are compiled too (no native-code stubs for error paths);
- every CodeInstance gets an entry in the jlcall convention and, where its signature is
handled, one in the specsig convention (with the configuration's `gcstack_arg`), named
as native code's (`jfptr_f_N`, and `j_f_N` for the specsig entry of `julia_f_N`); the
functions themselves have internal linkage.

Returns `compiled`, an `IdDict` from each CodeInstance to its
[`CompiledFunctions`](@ref JuliaCodegen.CompiledFunctions), and the module's
[`CodegenOutput`](@ref JuliaCodegen.CodegenOutput), whose `literals` the caller binds to
the objects' addresses (or relocates). The pass pipeline is the caller's to run.
"""
function emit_into!(mod::LLVM.Module, codeinfos; config::CodegenConfig=CodegenConfig(),
world::UInt=Base.get_world_counter())
sources = codeinfo_sources(codeinfos)
cgm = CGModule(mod, config; world, ir_source=closed_ir_source(sources), throwing_stubs=false)
return emit_sources!(cgm, codeinfos, sources)
end

function emit_into!(cgm::CGModule, codeinfos)
sources = codeinfo_sources(codeinfos)
cgm.ir_source = closed_ir_source(sources)
cgm.throwing_stubs = false
return emit_sources!(cgm, codeinfos, sources)
end

# the IR and return type of each method instance of `codeinfos`
function codeinfo_sources(codeinfos)
sources = IdDict{Core.MethodInstance,Tuple{CC.IRCode,Any}}()
for (ci, src) in codeinfos
ci isa Core.CodeInstance || throw(ArgumentError("expected a CodeInstance, got $(typeof(ci))"))
mi = CC.get_ci_mi(ci)
haskey(sources, mi) &&
throw(ArgumentError("two CodeInstances of $mi; pass one per method instance"))
ir = src isa CC.IRCode ? src :
src isa Core.CodeInfo ? CC.inflate_ir(src, mi) :
throw(ArgumentError("expected the CodeInfo or IRCode of $ci, got $(typeof(src))"))
sources[mi] = (ir, ci.rettype)
end
return sources
end

closed_ir_source(sources) = function (mi::Core.MethodInstance, world::UInt)
src = get(sources, mi, nothing)
src === nothing && unsupported("a call of ", mi, ", which is not among the code instances to compile")
return src
end

function emit_sources!(cgm::CGModule, codeinfos, sources)
infos = Pair{Core.CodeInstance,FuncInfo}[]
for (ci, _) in codeinfos
push!(infos, ci => get_function!(cgm, CC.get_ci_mi(ci)))
end
process_worklist!(cgm)
compiled = IdDict{Core.CodeInstance,CompiledFunctions}()
for (ci, info) in infos
# named as native code's functions: the function `julia_f_N` (which other functions
# call), its entries `j_f_N` in the specsig convention (the prefix of native code's
# specsig wrappers) and `jfptr_f_N` in the jlcall one
base = chopprefix(LLVM.name(info.llvmf), "julia_")
func = emit_jlcall_wrapper!(cgm, info, "jfptr_" * base)
push!(cgm.entries, Entry(info.mi, LLVM.name(func), :jlcall))
specfunc = try
LLVM.name(emit_specsig_wrapper!(cgm, info, "j_" * base))
catch err
err isa Unsupported || rethrow()
nothing
end
compiled[ci] = CompiledFunctions(LLVM.name(func), specfunc)
end
return compiled, codegen_output(cgm)
end
13 changes: 10 additions & 3 deletions src/function.jl
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ function emit_prologue!(fc::FnCtx; safepoint::Bool=true)
cfg = config(fc)
fc.pgcstack = get_pgcstack!(b, fc.cgm.mod, cfg.dialect)
fc.current_task = current_task!(b, cfg.runtime, fc.pgcstack)
if safepoint
if safepoint && cfg.safepoint_on_entry
ptls = current_ptls!(b, cfg, fc.cgm.tbaa, fc.current_task)
safepoint_poll!(b, fc.cgm.mod, cfg, fc.cgm.tbaa, ptls)
end
Expand Down Expand Up @@ -305,6 +305,8 @@ function emit_jlcall_wrapper!(cgm::CGModule, info::FuncInfo, name::AbstractStrin
push!(ops, convert_repr(fc, boxed(Any, p), T).V)
end
r = LLVM.call!(b, LLVM.function_type(info.llvmf), info.llvmf, ops)
# (the entry is the function, as native code's: inlined by any pipeline)
push!(LLVM.function_attributes(r), LLVM.EnumAttribute("alwaysinline"))
rt = info.rettype
k = repr_kind(rt)
if k === Bottom
Expand Down Expand Up @@ -338,12 +340,17 @@ function get_function!(cgm::CGModule, mi::Core.MethodInstance)
reason = "a varargs method"
else
try
ir, rt = get_ir(mi, cgm.world)
ir, rt = cgm.ir_source(mi, cgm.world)
catch err
err isa Unsupported || rethrow()
# (calling native code instead follows the configuration's policy)
handle_failure(cgm.config, mi, err, catch_backtrace())
reason = err
end
ir !== nothing && rt === Union{} && (reason = "a method that always throws"; ir = nothing)
if ir !== nothing && rt === Union{} && cgm.throwing_stubs
reason = "a method that always throws"
ir = nothing
end
end
info = declare_function!(cgm, mi, signature_argtypes(mi), ir === nothing ? Any : rt)
push!(cgm.worklist, (info, ir === nothing ? reason : ir))
Expand Down
2 changes: 1 addition & 1 deletion src/ir.jl
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ jlcall entry wrapper named `name`. The entry function itself must be supported:
"""
function emit_entry!(cgm::CGModule, @nospecialize(tt::Type); name::AbstractString=unique_name(cgm, "jfptr"))
mi = method_instance(tt, cgm.world)
ir, rt = get_ir(mi, cgm.world)
ir, rt = cgm.ir_source(mi, cgm.world)
info = declare_function!(cgm, mi, signature_argtypes(mi), rt)
push!(cgm.worklist, (info, ir))
process_worklist!(cgm; strict=mi)
Expand Down
Loading
Loading