diff --git a/NEWS.md b/NEWS.md index faaa081..9cbe5c2 100644 --- a/NEWS.md +++ b/NEWS.md @@ -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. diff --git a/docs/src/internals.md b/docs/src/internals.md index 8b241e8..c5876d0 100644 --- a/docs/src/internals.md +++ b/docs/src/internals.md @@ -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 diff --git a/src/JuliaCodegen.jl b/src/JuliaCodegen.jl index 5de3a4e..bd7df99 100644 --- a/src/JuliaCodegen.jl +++ b/src/JuliaCodegen.jl @@ -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") diff --git a/src/cfunction.jl b/src/cfunction.jl index 64f27a0..6ae65e4 100644 --- a/src/cfunction.jl +++ b/src/cfunction.jl @@ -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) diff --git a/src/config.jl b/src/config.jl index f0c96b3..dc481e9 100644 --- a/src/config.jl +++ b/src/config.jl @@ -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: @@ -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). @@ -30,9 +35,11 @@ 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), @@ -40,13 +47,16 @@ struct CodegenConfig 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) diff --git a/src/context.jl b/src/context.jl index 9c69b15..8421a0b 100644 --- a/src/context.jl +++ b/src/context.jl @@ -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 @@ -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)." @@ -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) @@ -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 diff --git a/src/debuginfo.jl b/src/debuginfo.jl new file mode 100644 index 0000000..1b1d66b --- /dev/null +++ b/src/debuginfo.jl @@ -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 diff --git a/src/function.jl b/src/function.jl index 40977f3..0c44a42 100644 --- a/src/function.jl +++ b/src/function.jl @@ -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) @@ -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). @@ -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[] @@ -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) diff --git a/src/output.jl b/src/output.jl index 2df0cfa..ce810b2 100644 --- a/src/output.jl +++ b/src/output.jl @@ -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)) diff --git a/src/specsig.jl b/src/specsig.jl index 378a899..9e4c72f 100644 --- a/src/specsig.jl +++ b/src/specsig.jl @@ -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 diff --git a/test/debuginfo.jl b/test/debuginfo.jl new file mode 100644 index 0000000..98efc7b --- /dev/null +++ b/test/debuginfo.jl @@ -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 diff --git a/test/runtests.jl b/test/runtests.jl index 58054e9..b2f426b 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -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