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
4 changes: 4 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,3 +80,7 @@
for `getglobal` and `setglobal!` with constant arguments.
- `ccall` in the `llvmcall` convention: calls of LLVM intrinsics (also ones LLVM doesn't
know, left to back ends and validation), as GPU code uses them.
- Debug information (`CodegenConfig(; debug_info)`, as Julia's `debug_info_kind`): line
tables, with a compile unit of the file `julia` as native code's, a subprogram for every
function (entries and wrappers included) and the location of every statement, with the
functions inlined at it as inlined frames.
3 changes: 3 additions & 0 deletions docs/src/internals.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,9 @@ JuliaCodegen.emit_specsig_wrapper!
JuliaCodegen.emit_specsig_call!
JuliaCodegen.emit_cfunction
JuliaCodegen.emit_llvmcall_cc
JuliaCodegen.DebugInfo
JuliaCodegen.debug_function!
JuliaCodegen.finalize_debuginfo!
JuliaCodegen.Entry
JuliaCodegen.literal_global
JuliaCodegen.literal_objects
Expand Down
1 change: 1 addition & 0 deletions src/JuliaCodegen.jl
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ include("context.jl")
include("constants.jl")
include("boxing.jl")
include("function.jl")
include("debuginfo.jl")
include("runtime.jl")
include("calls.jl")
include("intrinsics.jl")
Expand Down
1 change: 1 addition & 0 deletions src/cfunction.jl
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@ function emit_cfunction_wrapper!(cgm::CGModule, info::FuncInfo, @nospecialize(fo
top = LLVM.BasicBlock(w, "top")
LLVM.position!(b, LLVM.at_end(top))
wc = FnCtx(cgm, info, nothing, b, top)
debug_function!(wc, w)
facts = cgm.config.runtime
wc.pgcstack = call_op!(wc, "julia.get_pgcstack_or_new"; name="pgcstack")
wc.current_task = current_task!(b, facts, wc.pgcstack)
Expand Down
22 changes: 16 additions & 6 deletions src/config.jl
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
"""
JuliaCodegen.CodegenConfig(; target=host_target(), dialect=JuliaIR.Dialect(VERSION),
on_unsupported=:fallback, on_internal_error=:fallback,
gcstack_arg=true, safepoint_on_entry=true)
gcstack_arg=true, safepoint_on_entry=true,
debug_info=:none)

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

Expand All @@ -17,7 +18,11 @@ The configuration of the code generator, which generates code for the running Ju
- `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.
without Julia's runtime, like GPUs, turn both off;
- `debug_info`: the debug information to emit, as the `debug_info_kind` of Julia's
`CodegenParams`: `:none`, or line tables (a subprogram per function and the location
of every statement, with inlined frames) in a compile unit of the emission kind
`:line_tables`, `:directives` or `:full`.

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

function CodegenConfig(target::Target, dialect::JuliaIR.Dialect, on_unsupported::Symbol,
on_internal_error::Symbol, gcstack_arg::Bool, safepoint_on_entry::Bool)
on_internal_error::Symbol, gcstack_arg::Bool, safepoint_on_entry::Bool,
debug_info::Symbol)
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
debug_info in (:none, :line_tables, :directives, :full) ||
throw(ArgumentError("invalid debug_info :$debug_info; expected none, line_tables, directives or full"))
new(target, dialect, runtime_facts(), on_unsupported, on_internal_error, gcstack_arg,
safepoint_on_entry)
safepoint_on_entry, debug_info)
end
end

CodegenConfig(; target::Target=host_target(), dialect::JuliaIR.Dialect=JuliaIR.Dialect(VERSION),
on_unsupported::Symbol=:fallback, on_internal_error::Symbol=:fallback,
gcstack_arg::Bool=true, safepoint_on_entry::Bool=true) =
gcstack_arg::Bool=true, safepoint_on_entry::Bool=true,
debug_info::Symbol=:none) =
CodegenConfig(target, dialect, on_unsupported, on_internal_error, gcstack_arg,
safepoint_on_entry)
safepoint_on_entry, debug_info)
9 changes: 7 additions & 2 deletions src/context.jl
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ mutable struct CGModule
entries::Vector{Entry}
ir_source::Any
throwing_stubs::Bool
"The debug information (a `DebugInfo`), created on first use."
debuginfo::Any
counter::Int
end

Expand All @@ -69,7 +71,7 @@ function CGModule(mod::LLVM.Module, config::CodegenConfig; world::UInt=Base.get_
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[], ir_source,
throwing_stubs, 0)
throwing_stubs, nothing, 0)
end

"A name that is unique in the module, from `prefix` and the function `f` (if any)."
Expand Down Expand Up @@ -115,6 +117,8 @@ mutable struct FnCtx <: AbstractFnCtx
"The stack slot of each PhiC, and the PhiC each Upsilon feeds."
phic_slots::Dict{Int,LLVM.Value}
upsilon_to_phic::Dict{Int,Int}
"The subprogram of the function, with debug information."
subprogram::Union{Nothing,LLVM.DISubprogram}
end

function FnCtx(cgm::CGModule, info::FuncInfo, ir, builder::LLVM.IRBuilder, top::LLVM.BasicBlock)
Expand All @@ -124,7 +128,8 @@ function FnCtx(cgm::CGModule, info::FuncInfo, ir, builder::LLVM.IRBuilder, top::
LLVM.BasicBlock[], [Tuple{Int,LLVM.BasicBlock}[] for _ in 1:nb],
Tuple{Int,Int,LLVM.Instruction}[], 0, top, nothing, nothing, IdDict{Any,LLVM.Value}(),
Dict{Int,LLVM.Value}(), Dict{Int,LLVM.Value}(),
Dict{Int,Tuple{LLVM.Value,LLVM.Value}}(), Dict{Int,LLVM.Value}(), Dict{Int,Int}())
Dict{Int,Tuple{LLVM.Value,LLVM.Value}}(), Dict{Int,LLVM.Value}(), Dict{Int,Int}(),
nothing)
end

config(fc::FnCtx) = fc.cgm.config
Expand Down
122 changes: 122 additions & 0 deletions src/debuginfo.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
# Debug information: the line tables of native code (`debug_info_kind` above `NoDebug`):
# a compile unit for the module, a subprogram for every function, and for every
# statement the location of its line, with the functions inlined into it as inlined frames
# (from the IR's line information). Tools (and GPUCompiler's error messages) read
# backtraces from them. There is no information about variables or types.

# the emission kinds of `debug_info` (`DICompileUnit::DebugEmissionKind`)
const DEBUG_EMISSION_KINDS = (none=0, full=1, line_tables=2, directives=3)

"""
JuliaCodegen.DebugInfo

The debug information of a module: its `DIBuilder`, the compile unit (of the file
`julia`, as native code's) and the files and subprograms created.
"""
mutable struct DebugInfo
builder::LLVM.DIBuilder
cu::LLVM.DICompileUnit
files::Dict{String,LLVM.DIFile}
"The subprograms of inlined functions, by name and file."
inlined::Dict{Tuple{String,String},LLVM.DISubprogram}
subroutine::LLVM.DISubroutineType
finalized::Bool
end

function DebugInfo(mod::LLVM.Module, config::CodegenConfig)
flags = mod.flags
haskey(flags, "Debug Info Version") ||
(flags["Debug Info Version", LLVM.ModuleFlagBehavior.Warning] =
LLVM.Metadata(LLVM.ConstantInt(Int32(LLVM.DEBUG_METADATA_VERSION()))))
haskey(flags, "Dwarf Version") ||
(flags["Dwarf Version", LLVM.ModuleFlagBehavior.Warning] =
LLVM.Metadata(LLVM.ConstantInt(Int32(4))))
dib = LLVM.DIBuilder(mod)
file = LLVM.file!(dib, "julia", ".")
kind = reinterpret(LLVM.API.LLVMDWARFEmissionKind,
UInt32(DEBUG_EMISSION_KINDS[config.debug_info]))
cu = LLVM.compile_unit!(dib, LLVM.API.LLVMDWARFSourceLanguageJulia, file, "julia";
optimized=true, emission_kind=kind)
subroutine = LLVM.subroutine_type!(dib, file, nothing)
return DebugInfo(dib, cu, Dict("julia" => file), Dict{Tuple{String,String},LLVM.DISubprogram}(),
subroutine, false)
end

# the debug information of the module of `cgm`, `nothing` without it
function debuginfo(cgm::CGModule)
cgm.config.debug_info === :none && return nothing
if cgm.debuginfo === nothing
cgm.debuginfo = DebugInfo(cgm.mod, cgm.config)
end
return cgm.debuginfo
end

"Finish the debug information of the module of `cgm`, before it is used."
function finalize_debuginfo!(cgm::CGModule)
di = cgm.debuginfo
(di === nothing || di.finalized) && return
LLVM.finalize!(di.builder)
LLVM.dispose(di.builder)
di.finalized = true
end

function difile(di::DebugInfo, file)
name = string(file)
get!(() -> LLVM.file!(di.builder, name, "."), di.files, name)
end

function subprogram!(di::DebugInfo, name::AbstractString, file, line::Integer,
linkage_name::AbstractString="")
f = difile(di, file)
return LLVM.subprogram!(di.builder, f, name, f, max(Int(line), 0), di.subroutine;
linkage_name, optimized=true)
end

# the name and file of a frame of the IR's line information
frame_name(@nospecialize(m)) =
m isa Core.MethodInstance ? frame_name(m.def) :
m isa Method ? String(m.name) :
m isa Module ? "top-level scope" : string(m)

"""
JuliaCodegen.debug_function!(fc, f; name, file, line)

Give the function `f` that `fc` emits a subprogram (`name` at `file:line`, by default
those of the method being compiled), and the builder its location, for the instructions
emitted before the first statement and in functions without IR (entries, stubs).
"""
function debug_function!(fc::FnCtx, f::LLVM.Function; name=nothing, file=nothing, line=nothing)
di = debuginfo(fc.cgm)
di === nothing && return nothing
m = fc.info.mi.def
name = something(name, frame_name(m))
file = something(file, m isa Method ? m.file : :none)
line = something(line, m isa Method ? m.line : 0)
sp = subprogram!(di, name, file, line, LLVM.name(f))
f.subprogram = sp
fc.subprogram = sp
LLVM.debug_location!(fc.builder, LLVM.DILocation(max(Int(line), 0), 0, sp))
return sp
end

# the location of the statement `idx` of the IR: its line in the function, inlined into
# which the lines of the functions inlined at it
function statement_location!(fc::FnCtx, idx::Int)
di = debuginfo(fc.cgm)
(di === nothing || fc.subprogram === nothing) && return
frames = Base.IRShow.buildLineInfoNode(fc.ir.debuginfo, fc.info.mi, idx)
isempty(frames) && return # (keep the previous location)
loc = nothing
for (k, fr) in enumerate(frames)
scope = if k == 1
fc.subprogram
else
name = frame_name(fr.method)
get!(di.inlined, (name, string(fr.file))) do
subprogram!(di, name, fr.file, 0)
end
end
loc = LLVM.DILocation(max(Int(fr.line), 0), 0, scope, loc)
end
LLVM.debug_location!(fc.builder, loc)
end
4 changes: 4 additions & 0 deletions src/function.jl
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ function emit_body!(cgm::CGModule, info::FuncInfo, ir::CC.IRCode)
top = LLVM.BasicBlock(info.llvmf, "top")
LLVM.position!(b, LLVM.at_end(top))
fc = FnCtx(cgm, info, ir, b, top)
debug_function!(fc, info.llvmf)
emit_prologue!(fc)
bind_arguments!(fc)
for i in 1:length(ir.cfg.blocks)
Expand All @@ -109,6 +110,7 @@ end
## walker hooks

begin_block!(fc::FnCtx, bi::Int) = LLVM.position!(fc.builder, LLVM.at_end(fc.blocks[bi]))
begin_stmt!(fc::FnCtx, idx::Int) = statement_location!(fc, idx)

# A block is dead when no edge into it was emitted and every predecessor has been
# emitted already (an earlier block in the IR's order).
Expand Down Expand Up @@ -291,6 +293,7 @@ function emit_jlcall_wrapper!(cgm::CGModule, info::FuncInfo, name::AbstractStrin
top = LLVM.BasicBlock(f, "top")
LLVM.position!(b, LLVM.at_end(top))
fc = FnCtx(cgm, info, nothing, b, top)
debug_function!(fc, f)
emit_prologue!(fc; safepoint=false)
F, argv, _ = LLVM.parameters(f)
ops = LLVM.Value[]
Expand Down Expand Up @@ -406,6 +409,7 @@ function emit_stub!(cgm::CGModule, info::FuncInfo)
top = LLVM.BasicBlock(info.llvmf, "top")
LLVM.position!(b, LLVM.at_end(top))
fc = FnCtx(cgm, info, nothing, b, top)
debug_function!(fc, info.llvmf)
emit_prologue!(fc; safepoint=false)
bind_arguments!(fc)
r = emit_dynamic_call(fc, fc.args[1], fc.args[2:end], info.rettype; invoke=info.mi)
Expand Down
1 change: 1 addition & 0 deletions src/output.jl
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ What the module of `cgm` contains and refers to, see
[`CodegenOutput`](@ref JuliaCodegen.CodegenOutput).
"""
function codegen_output(cgm::CGModule)
finalize_debuginfo!(cgm)
literals = sort!(literal_objects(cgm); by=first)
return CodegenOutput(copy(cgm.entries), literals, external_symbols(cgm.mod, literals),
copy(cgm.fallbacks))
Expand Down
1 change: 1 addition & 0 deletions src/specsig.jl
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,7 @@ function emit_specsig_wrapper!(cgm::CGModule, info::FuncInfo, name::AbstractStri
top = LLVM.BasicBlock(f, "top")
LLVM.position!(b, LLVM.at_end(top))
fc = FnCtx(cgm, info, nothing, b, top)
debug_function!(fc, f)
ps = LLVM.parameters(f)
p = sig.ret === :sret ? 2 : 1
if sig.gcstack
Expand Down
57 changes: 57 additions & 0 deletions test/debuginfo.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# Debug information: line tables.

@noinline d_inner(x) = x * 2
d_outer(x) = d_inner(x) + sin(x)
d_entry(x) = d_outer(x)

const D_CONFIG = JuliaCodegen.CodegenConfig(; on_unsupported=:error, on_internal_error=:error,
debug_info=:line_tables)
d_run(f, args...) = cgrun(f, args...; config=D_CONFIG)

function d_ir(f, types; config=D_CONFIG)
@dispose ctx=LLVM.Context() mod=LLVM.Module("jcdebug") begin
cgm = JuliaCodegen.CGModule(mod, config)
JuliaCodegen.emit_entry!(cgm, Tuple{Core.Typeof(f), types...}; name="d_entry")
JuliaCodegen.codegen_output(cgm)
verify_ir(mod)
return string(mod)
end
end

@testset "debug info" begin

@testset "line tables" begin
ir = d_ir(d_outer, (Float64,))
@test @filecheck begin
@check "define internal double @julia_d_outer_{{[0-9]+}}(double %0) #{{[0-9]+}} !dbg ![[SP:[0-9]+]]"
@check "call double @julia_d_inner_{{[0-9]+}}(double %{{[0-9]+}}){{.*}}, !dbg ![[CALL:[0-9]+]]"
@check "!llvm.dbg.cu = !{![[CU:[0-9]+]]}"
@check "![[CU]] = distinct !DICompileUnit(language: DW_LANG_Julia, file: ![[FILE:[0-9]+]], producer: \"julia\", isOptimized: true, runtimeVersion: 0, emissionKind: LineTablesOnly"
@check "![[FILE]] = !DIFile(filename: \"julia\", directory: \".\")"
@check "![[SP]] = distinct !DISubprogram(name: \"d_outer\", linkageName: \"julia_d_outer_{{[0-9]+}}\""
ir
end
# the lines of the functions inlined into a statement: inlined frames
@test occursin(r"!DILocation\(line: \d+, scope: ![0-9]+, inlinedAt: ![0-9]+\)", ir)
@test occursin("!DISubprogram(name: \"sin\"", ir) || occursin("!DISubprogram(name: \"+\"", ir)
# every function has a subprogram, entries included
@test count("distinct !DISubprogram(name: \"d_outer\"", ir) == 2
# without, none
@test !occursin("!dbg", d_ir(d_outer, (Float64,); config=test_config()))
end

@testset "code with it" begin
@cgtest run=d_run d_entry(0.5)
@cgtest run=d_run d_outer(2.0)
end

@testset "emission kinds" begin
for (kind, name) in ((:directives, "DebugDirectivesOnly"), (:full, "FullDebug"))
config = JuliaCodegen.CodegenConfig(; on_unsupported=:error, on_internal_error=:error,
debug_info=kind)
@test occursin("emissionKind: $name", d_ir(d_inner, (Int,); config))
end
@test_throws "invalid debug_info" JuliaCodegen.CodegenConfig(; debug_info=:lines)
end

end
1 change: 1 addition & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ include("cfunction.jl")
include("output.jl")
include("emit_into.jl")
include("jitdriver.jl")
include("debuginfo.jl")
include("cabi_targets.jl")

@testset "Aqua" begin
Expand Down
Loading