• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

JuliaLang / julia / 1774

24 Nov 2026 09:02PM UTC coverage: 93.051% (+0.4%) from 92.634%
1774

push

buildkite

web-flow
cgmemmgr: CodeModel-aware memory management (#60915)

As described in #60245, we're unable to use the optimized memory manager
on architectures where the default CodeModel is not `Large`.  Since
`mmap()` will generally put new mappings close to each other,
allocations will succeed until the address space becomes fragmented
enough that an RW allocation lands sufficiently far from the
corresponding RX allocation, such that a relocation in the code fails.

This PR implements a new `JLJITLinkMemoryManager`, which is intended to
have lower memory use than `orc::MapperJITLinkMemoryManager` and support
non-large code models, unlike the old Julia CG memory manager.  We
accomplish this by reserving a block in the address space that is
smaller than the maximum distance for relocations on the current
architecture, putting the code and data sections inside this block:

```
    v-- 2^JULIA_CGMEM_BLOCK_SIZE --v

 ---+---------------------+--------+----
    | RX                  | RW     |
 ---+---------------------+--------+----
```

We make allocations inside the RX and RW regions (read-only data goes
into the RX region for compactness) until one or the other is full, then
we unmap unused pages and make a new block elsewhere.  The size of a
block can be set with `JULIA_CGMEM_BLOCK_SIZE`, while the ratio of RX to
RW within the block is fixed, based on empirical measurements.  If an
allocation requires more space than is available in a single block,
contiguous pages are allocated at an arbitrary address for it.

Assisted-by: Claude Code (Fable 5.2)

102479 of 110132 relevant lines covered (93.05%)

447.04 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

96.68
/stdlib/InteractiveUtils/src/codeview.jl
1
# This file is a part of Julia. License is MIT: https://julialang.org/license
2

3
# highlighting settings
4
const highlighting = Dict{Symbol, Bool}(
5
    :warntype => true,
6
    :llvm => true,
7
    :native => true,
8
)
9

10
const llstyle = Dict{Symbol, Tuple{Bool, Union{Symbol, Int}}}(
11
    :default     => (false, :normal), # e.g. comma, equal sign, unknown token
12
    :comment     => (false, :light_black),
13
    :label       => (false, :light_red),
14
    :instruction => ( true, :light_cyan),
15
    :type        => (false, :cyan),
16
    :number      => (false, :yellow),
17
    :bracket     => (false, :yellow),
18
    :variable    => (false, :normal), # e.g. variable, register
19
    :keyword     => (false, :light_magenta),
20
    :funcname    => (false, :light_yellow),
21
)
22

23
struct ArgInfo
24
    oc::Union{Core.OpaqueClosure,Nothing}
52 ✔
25
    tt::Type{<:Tuple}
60 ✔
26

27
    # Construct from a function object + argtypes
28
    function ArgInfo(@nospecialize(f), @nospecialize(t))
60 ✔
29
        if isa(f, Core.Builtin)
52 ✔
30
            throw(ArgumentError("argument is not a generic function"))
2 ✔
31
        elseif f isa Core.OpaqueClosure
52 ✔
32
            return new(f, Base.to_tuple_type(t))
5 ✔
33
        else
34
            return new(nothing, signature_type(f, t))
55 ✔
35
        end
36
    end
37

38
    # Construct from argtypes (incl. arg0)
39
    function ArgInfo(@nospecialize(argtypes::Union{Tuple,Type{<:Tuple}}))
2 ✔
40
        tt = Base.to_tuple_type(argtypes)
2 ✔
41
        return new(nothing, tt)
2 ✔
42
    end
43
end
44

45
function printstyled_ll(io::IO, x, s::Symbol, trailing_spaces="")
9 ✔
46
    printstyled(io, x, bold=llstyle[s][1], color=llstyle[s][2])
9 ✔
47
    print(io, trailing_spaces)
9 ✔
48
end
49

50
# displaying type warnings
51

52
function warntype_type_printer(io::IO; @nospecialize(type), used::Bool, show_type::Bool=true, _...)
14 ✔
53
    (show_type && used) || return nothing
14 ✔
54
    str = "::$type"
14 ✔
55
    cls = Base.Compiler.IRShow.warntype_type_class(type)
14 ✔
56
    if !highlighting[:warntype]
14 ✔
57
        print(io, str)
5 ✔
58
    elseif cls === Base.Compiler.IRShow.SSA_WARN_TYPE_MILD
14 ✔
59
        Base.emphasize(io, str, Base.warn_color()) # more mild user notification
8 ✔
60
    elseif cls === Base.Compiler.IRShow.SSA_WARN_TYPE_STRONG
14 ✔
61
        Base.emphasize(io, str)
5 ✔
62
    else
63
        Base.printstyled(io, str, color=:cyan) # show the "good" type
14 ✔
64
    end
65
    return nothing
14 ✔
66
end
67

68
function print_warntype_codeinfo(io::IO, src::Core.CodeInfo, @nospecialize(rettype), nargs::Int; lineprinter, label_dynamic_calls)
14 ✔
69
    if src.slotnames !== nothing
14 ✔
70
        slotnames = Base.sourceinfo_slotnames(src)
14 ✔
71
        io = IOContext(io, :SOURCE_SLOTNAMES => slotnames)
14 ✔
72
        slottypes = src.slottypes
14 ✔
73
        nargs > 0 && println(io, "Arguments")
14 ✔
74
        for i = 1:length(slotnames)
14 ✔
75
            if i == nargs + 1
14 ✔
76
                println(io, "Locals")
8 ✔
77
            end
78
            print(io, "  ", slotnames[i])
14 ✔
79
            if isa(slottypes, Vector{Any})
14 ✔
80
                warntype_type_printer(io; type=slottypes[i], used=true)
14 ✔
81
            end
82
            println(io)
14 ✔
83
        end
84
    end
85
    print(io, "Body")
14 ✔
86
    warntype_type_printer(io; type=rettype, used=true)
14 ✔
87
    println(io)
14 ✔
88
    irshow_config = Base.IRShow.IRShowConfig(lineprinter(src), warntype_type_printer; label_dynamic_calls, color_warntype=highlighting[:warntype])
14 ✔
89
    Base.IRShow.show_ir(io, src, irshow_config)
14 ✔
90
    println(io)
14 ✔
91
end
92

93
function print_warntype_mi(io::IO, mi::Core.MethodInstance)
11 ✔
94
    println(io, mi)
11 ✔
95
    print(io, "  from ")
11 ✔
96
    println(io, mi.def)
11 ✔
97
    if !isempty(mi.sparam_vals)
11 ✔
98
        println(io, "Static Parameters")
2 ✔
99
        sig = mi.def.sig
2 ✔
100
        warn_color = Base.warn_color() # more mild user notification
2 ✔
101
        for i = 1:length(mi.sparam_vals)
2 ✔
102
            sig = sig::UnionAll
2 ✔
103
            name = sig.var.name
2 ✔
104
            val = mi.sparam_vals[i]
2 ✔
105
            # Env entries from intersection may be wrapped as svec(tvar, constrained_bool)
106
            if val isa Core.SimpleVector
2 ✔
107
                val = val[1]
2 ✔
108
            end
109
            print_highlighted(io::IO, v::String, color::Union{Symbol,Int}) =
2 ✔
110
                if highlighting[:warntype]
2 ✔
111
                    Base.printstyled(io, v; color)
2 ✔
112
                else
113
                    Base.print(io, v)
×
114
                end
115
            if val isa TypeVar
2 ✔
116
                if val.lb === Union{}
2 ✔
117
                    print(io, "  ", name, " <: ")
2 ✔
118
                    print_highlighted(io, "$(val.ub)", warn_color)
2 ✔
119
                elseif val.ub === Any
2 ✔
120
                    print(io, "  ", sig.var.name, " >: ")
2 ✔
121
                    print_highlighted(io, "$(val.lb)", warn_color)
2 ✔
122
                else
123
                    print(io, "  ")
2 ✔
124
                    print_highlighted(io, "$(val.lb)", warn_color)
2 ✔
125
                    print(io, " <: ", sig.var.name, " <: ")
2 ✔
126
                    print_highlighted(io, "$(val.ub)", warn_color)
2 ✔
127
                end
128
            elseif val isa typeof(Vararg)
2 ✔
129
                print(io, "  ", name, "::")
2 ✔
130
                print_highlighted(io, "Int", warn_color)
2 ✔
131
            else
132
                print(io, "  ", sig.var.name, " = ")
2 ✔
133
                print_highlighted(io, "$(val)", :cyan) # show the "good" type
2 ✔
134
            end
135
            println(io)
2 ✔
136
            sig = sig.body
2 ✔
137
        end
138
    end
139
end
140

141
"""
14 ✔
142
    code_warntype([io::IO], f, types; debuginfo=:default, optimize=false)
143

144
Prints lowered and type-inferred ASTs for the methods matching the given generic function
145
and type signature to `io` which defaults to `stdout`. The ASTs are annotated in such a way
146
as to cause non-concrete types which may be problematic for performance to be emphasized
147
(if color is available, displayed in red). This serves as a warning of potential type instability.
148

149
Not all non-concrete types are particularly problematic for performance, and the performance
150
characteristics of a particular type is an implementation detail of the compiler.
151
`code_warntype` will err on the side of coloring types red if they might be a performance
152
concern, so some types may be colored red even if they do not impact performance.
153
Small unions of concrete types are usually not a concern, so these are highlighted in yellow.
154

155
Keyword argument `debuginfo` may be one of `:source`, `:none` or `:default`, to specify the verbosity of code comments.
156
Unless the user changes `Base.IRShow.default_debuginfo[]`, the value `:default` is equivalent to `:source`.
157

158
Keyword argument `optimize` controls whether additional optimizations, such as inlining, are also
159
applied (as for [`code_typed`](@ref)). It defaults to `false`, which is usually easier to relate to
160
the source code.
161

162
See the [`@code_warntype`](@ref man-code-warntype) section in the Performance Tips page of the manual for more information.
163

164
See also: [`@code_warntype`](@ref), [`code_typed`](@ref), [`code_lowered`](@ref), [`code_llvm`](@ref), [`code_native`](@ref).
165
"""
166
function code_warntype(io::IO, arginfo::ArgInfo;
14 ✔
167
                       world=Base.get_world_counter(),
168
                       interp::Union{Nothing,Base.Compiler.AbstractInterpreter}=nothing,
169
                       debuginfo::Symbol=:default, optimize::Bool=false, _kwargs...)
170
    (ccall(:jl_is_in_pure_context, Bool, ()) || world == typemax(UInt)) &&
14 ✔
171
        error("code reflection cannot be used from generated functions")
172
    debuginfo = Base.IRShow.debuginfo(debuginfo)
14 ✔
173
    lineprinter = Base.IRShow.__debuginfo[debuginfo]
14 ✔
174
    nargs::Int = 0
14 ✔
175
    if arginfo.oc !== nothing
14 ✔
176
        (; oc, tt) = arginfo
5 ✔
177
        isa(oc.source, Method) && (nargs = oc.source.nargs)
5 ✔
178
        print_warntype_codeinfo(io, Base.code_typed_opaque_closure(oc, tt; optimize, interp)[1]..., nargs;
5 ✔
179
                                lineprinter, label_dynamic_calls = optimize)
180
        return nothing
5 ✔
181
    end
182
    tt = arginfo.tt
11 ✔
183
    passed_interp = interp
11 ✔
184
    interp = passed_interp === nothing ? Base.invoke_default_compiler(:_default_interp, world) : interp
11 ✔
185
    matches = Base.invoke_interp_compiler(passed_interp, :_findall_matches, interp, tt)
11 ✔
186
    matches === nothing && Base.raise_match_failure(:code_warntype, tt)
11 ✔
187
    for match in matches.matches
11 ✔
188
        match = match::Core.MethodMatch
11 ✔
189
        src = Base.invoke_interp_compiler(passed_interp, :typeinf_code, interp, match, optimize)
11 ✔
190
        mi = Base.specialize_method(match)
11 ✔
191
        mi.def isa Method && (nargs = (mi.def::Method).nargs)
11 ✔
192
        print_warntype_mi(io, mi)
11 ✔
193
        if src isa Core.CodeInfo
11 ✔
194
            print_warntype_codeinfo(io, src, src.rettype, nargs;
11 ✔
195
                                    lineprinter, label_dynamic_calls = optimize)
196
        else
197
            println(io, "  inference not successful")
×
198
        end
199
    end
200
    nothing
11 ✔
201
end
202
code_warntype(io::IO, @nospecialize(f), @nospecialize(tt=Base.default_tt(f)); kwargs...) = code_warntype(io, ArgInfo(f, tt); kwargs...)
14 ✔
203
code_warntype(io::IO, @nospecialize(argtypes::Union{Tuple,Type{<:Tuple}}); kwargs...) = code_warntype(io, ArgInfo(argtypes); kwargs...)
2 ✔
204
code_warntype(f; kwargs...) = (@nospecialize; code_warntype(stdout, f; kwargs...))
×
205
code_warntype(f, argtypes; kwargs...) = (@nospecialize; code_warntype(stdout, f, argtypes; kwargs...))
×
206

207
using Base: CodegenParams
208

209
const GENERIC_SIG_WARNING = "; WARNING: This code may not match what actually runs.\n"
210
const OC_MISMATCH_WARNING =
211
"""
212
; WARNING: The pre-inferred opaque closure is not callable with the given arguments
213
;          and will error on dispatch with this signature.
214
"""
215

216
# Printing code representations in IR and assembly
217

218
function _dump_function(arginfo::ArgInfo, native::Bool, wrapper::Bool,
57 ✔
219
                        raw::Bool, dump_module::Bool, syntax::Symbol,
220
                        optimize::Bool, debuginfo::Symbol, binary::Bool,
57 ✔
221
                        llvm_options::String="",
3 ✔
222
                        params::CodegenParams=CodegenParams(debug_info_kind=Cint(0), debug_info_level=Cint(2), safepoint_on_entry=raw, gcstack_arg=raw))
57 ✔
223
    ccall(:jl_is_in_pure_context, Bool, ()) && error("code reflection cannot be used from generated functions")
57 ✔
224
    warning = ""
51 ✔
225
    # get the MethodInstance for the method match
226
    if arginfo.oc === nothing
51 ✔
227
        world = Base.get_world_counter()
51 ✔
228
        match = Base._which(arginfo.tt; world)
51 ✔
229
        mi = Base.specialize_method(match)
51 ✔
230
        # TODO: use jl_is_cacheable_sig instead of isdispatchtuple
231
        isdispatchtuple(mi.specTypes) || (warning = GENERIC_SIG_WARNING)
51 ✔
232
    else
233
        (; oc, tt) = arginfo
5 ✔
234
        world = UInt64(oc.world)
5 ✔
235
        if !isdefined(oc.source, :source)
5 ✔
236
            # OC was constructed from inferred source. There's only one
237
            # specialization and we can't infer anything more precise either.
238
            world = oc.source.primary_world
5 ✔
239
            mi = oc.source.specializations::Core.MethodInstance
5 ✔
240
            Base.hasintersect(typeof(oc).parameters[1], tt) || (warning = OC_MISMATCH_WARNING)
5 ✔
241
        else
242
            mi = Base.specialize_method(oc.source, Tuple{typeof(oc.captures), tt.parameters...}, Core.svec())
×
243
            isdispatchtuple(mi.specTypes) || (warning = GENERIC_SIG_WARNING)
×
244
        end
245
    end
246
    # get the code for it
247
    if debuginfo === :default
51 ✔
248
        debuginfo = :source
41 ✔
249
    elseif debuginfo !== :source && debuginfo !== :none
21 ✔
250
        throw(ArgumentError("'debuginfo' must be either :source or :none"))
2 ✔
251
    end
252
    if native
51 ✔
253
        if syntax !== :att && syntax !== :intel
12 ✔
254
            throw(ArgumentError("'syntax' must be either :intel or :att"))
2 ✔
255
        end
256
        str = ""
12 ✔
257
        if !dump_module
12 ✔
258
            # if we don't want the module metadata, attempt to disassemble what our JIT has
259
            str = _dump_function_native_disassembly(mi, world, wrapper, syntax, debuginfo, binary)
8 ✔
260
        end
261
        if isempty(str)
12 ✔
262
            # if that failed (or we want metadata), use LLVM to generate more accurate assembly output
263
            if arginfo.oc === nothing
8 ✔
264
                src = Base.invoke_interp_compiler(nothing, :typeinf_code, Base.invoke_default_compiler(:_default_interp, world), mi, true)
8 ✔
265
            else
266
                src, _rt = Base.get_oc_code_rt(nothing, arginfo.oc, arginfo.tt, true)
×
267
            end
268
            src isa Core.CodeInfo || error("failed to infer source for $mi")
8 ✔
269
            str = _dump_function_native_assembly(mi, src, wrapper, syntax, debuginfo, binary, raw, params)
8 ✔
270
        end
271
    else
272
        if arginfo.oc === nothing
47 ✔
273
            src = Base.invoke_interp_compiler(nothing, :typeinf_code, Base.invoke_default_compiler(:_default_interp, world), mi, true)
47 ✔
274
        else
275
            src, _rt = Base.get_oc_code_rt(nothing, arginfo.oc, arginfo.tt, true)
5 ✔
276
        end
277
        src isa Core.CodeInfo || error("failed to infer source for $mi")
47 ✔
278
        str = _dump_function_llvm(mi, src, wrapper, !raw, dump_module, optimize, debuginfo, llvm_options, params)
47 ✔
279
    end
280
    str = warning * fixup_stdlib_paths(str)
51 ✔
281
    return str
51 ✔
282
end
283

284
# Debug info printed by codegen refers to stdlib files by their build-time location
285
function fixup_stdlib_paths(str::String)
51 ✔
286
    Sys.BUILD_STDLIB_PATH == Sys.STDLIB && return str
51 ✔
287
    return replace(str, normpath(Sys.BUILD_STDLIB_PATH) => normpath(Sys.STDLIB))
51 ✔
288
end
289

290
function _dump_function_native_disassembly(mi::Core.MethodInstance, world::UInt,
8 ✔
291
                                           wrapper::Bool, syntax::Symbol,
292
                                           debuginfo::Symbol, binary::Bool)
293
    str = @ccall jl_dump_method_asm(mi::Any, world::UInt, false::Bool, wrapper::Bool,
8 ✔
294
                                    syntax::Ptr{UInt8}, debuginfo::Ptr{UInt8},
8 ✔
295
                                    binary::Bool)::Ref{String}
8 ✔
296
    return str
8 ✔
297
end
298

299
struct LLVMFDump
300
    tsm::Ptr{Cvoid} # opaque
301
    f::Ptr{Cvoid} # opaque
302
    pass_output::Cstring # LLVM pass instrumentation output (lifetime managed by jl_dump_function_ir or jl_dump_function_asm)
303
end
304

305
function _dump_function_native_assembly(mi::Core.MethodInstance, src::Core.CodeInfo,
8 ✔
306
                                        wrapper::Bool, syntax::Symbol, debuginfo::Symbol,
307
                                        binary::Bool, raw::Bool, params::CodegenParams)
308
    llvmf_dump = Ref{LLVMFDump}()
8 ✔
309
    @ccall jl_get_llvmf_defn(llvmf_dump::Ptr{LLVMFDump}, mi::Any, src::Any, wrapper::Bool,
8 ✔
310
                             true::Bool, ""::Cstring, params::CodegenParams)::Cvoid
8 ✔
311
    llvmf_dump[].f == C_NULL && error("could not compile the specified method")
8 ✔
312
    str = @ccall jl_dump_function_asm(llvmf_dump::Ptr{LLVMFDump}, false::Bool,
8 ✔
313
                                      syntax::Ptr{UInt8}, debuginfo::Ptr{UInt8},
8 ✔
314
                                      binary::Bool, raw::Bool)::Ref{String}
8 ✔
315
    return str
8 ✔
316
end
317

318
function _dump_function_llvm(
47 ✔
319
        mi::Core.MethodInstance, src::Core.CodeInfo, wrapper::Bool,
320
        strip_ir_metadata::Bool, dump_module::Bool,
321
        optimize::Bool, debuginfo::Symbol,
322
        llvm_options::String,
323
        params::CodegenParams)
324
    llvmf_dump = Ref{LLVMFDump}()
47 ✔
325
    @ccall jl_get_llvmf_defn(llvmf_dump::Ptr{LLVMFDump}, mi::Any, src::Any,
47 ✔
326
                             wrapper::Bool, optimize::Bool, llvm_options::Cstring,
47 ✔
327
                             params::CodegenParams)::Cvoid
47 ✔
328
    llvmf_dump[].f == C_NULL && error("could not compile the specified method")
47 ✔
329
    # jl_dump_function_ir handles pass_output internally (prepends it and frees it)
330
    str = @ccall jl_dump_function_ir(llvmf_dump::Ptr{LLVMFDump}, strip_ir_metadata::Bool,
47 ✔
331
                                     dump_module::Bool, debuginfo::Ptr{UInt8})::Ref{String}
47 ✔
332
    return str
47 ✔
333
end
334

335
"""
53 ✔
336
    code_llvm([io=stdout,], f, types; raw=false, dump_module=false, optimize=true, debuginfo=:default, llvm_options="")
337

338
Prints the LLVM bitcodes generated for running the method matching the given generic
339
function and type signature to `io`.
340

341
If the `optimize` keyword is `false`, the code will be shown before LLVM optimizations.
342
All metadata and dbg.* calls are removed from the printed bitcode. For the full IR, set the `raw` keyword to true.
343
To dump the entire module that encapsulates the function (with declarations), set the `dump_module` keyword to true.
344
Keyword argument `debuginfo` may be one of source (default) or none, to specify the verbosity of code comments.
345

346
The `llvm_options` keyword argument allows passing LLVM options to control the optimization pipeline output.
347
Supported options include:
348
- `-print-after-all`: Print IR after each pass
349
- `-print-before-all`: Print IR before each pass
350
- `-print-after=<passname>`: Print IR after a specific pass (e.g., `-print-after=InstCombinePass`). Comma-separated lists and repeated flags are supported.
351
- `-print-before=<passname>`: Print IR before a specific pass. Comma-separated lists and repeated flags are supported.
352
- `-print-module-scope`: Print entire module instead of just the function
353
- `-filter-print-funcs=<name>`: Only print IR for functions matching the name
354

355
See also: [`@code_llvm`](@ref), [`code_warntype`](@ref), [`code_typed`](@ref), [`code_lowered`](@ref), [`code_native`](@ref).
356
"""
357
function code_llvm(io::IO, arginfo::ArgInfo;
53 ✔
358
                   raw::Bool=false, dump_module::Bool=false, optimize::Bool=true, debuginfo::Symbol=:default,
359
                   llvm_options::String="",
360
                   params::CodegenParams=CodegenParams(debug_info_kind=Cint(0), debug_info_level=Cint(2), safepoint_on_entry=raw, gcstack_arg=raw))
361
    d = _dump_function(arginfo, false, false, raw, dump_module, :intel, optimize, debuginfo, false, llvm_options, params)
53 ✔
362
    if highlighting[:llvm] && get(io, :color, false)::Bool
47 ✔
363
        print_llvm(io, d)
5 ✔
364
    else
365
        print(io, d)
44 ✔
366
    end
367
end
368
code_llvm(io::IO, @nospecialize(argtypes::Union{Tuple,Type{<:Tuple}}); kwargs...) = code_llvm(io, ArgInfo(argtypes); kwargs...)
2 ✔
369
code_llvm(io::IO, @nospecialize(f), @nospecialize(types=Base.default_tt(f)); kwargs...) = code_llvm(io, ArgInfo(f, types); kwargs...)
53 ✔
370
code_llvm(args...; kwargs...) = (@nospecialize; code_llvm(stdout, args...; kwargs...))
11 ✔
371

372
"""
18 ✔
373
    code_native([io=stdout,], f, types; syntax=:intel, debuginfo=:default, binary=false, dump_module=true, raw=false)
374

375
Prints the native assembly instructions generated for running the method matching the given
376
generic function and type signature to `io`.
377

378
* Set assembly syntax by setting `syntax` to `:intel` (default) for intel syntax or `:att` for AT&T syntax.
379
* Specify verbosity of code comments by setting `debuginfo` to `:source` (equivalently, `:default`) or `:none`.
380
* If `binary` is `true`, also print the binary machine code for each instruction preceded by an abbreviated address.
381
* If `dump_module` is `false`, do not print metadata such as rodata or directives.
382
* If `raw` is `false` (default), uninteresting instructions (like the safepoint function prologue) are elided.
383

384
See also: [`@code_native`](@ref), [`code_warntype`](@ref), [`code_typed`](@ref), [`code_lowered`](@ref), [`code_llvm`](@ref).
385
"""
386
function code_native(io::IO, arginfo::ArgInfo;
18 ✔
387
                     dump_module::Bool=true, syntax::Symbol=:intel, raw::Bool=false,
388
                     debuginfo::Symbol=:default, binary::Bool=false,
389
                     llvm_options::String="",
390
                     params::CodegenParams=CodegenParams(debug_info_kind=Cint(0), debug_info_level=Cint(2), safepoint_on_entry=raw, gcstack_arg=raw))
391
    d = _dump_function(arginfo, true, false, raw, dump_module, syntax, true, debuginfo, binary, llvm_options, params)
18 ✔
392
    if highlighting[:native] && get(io, :color, false)::Bool
12 ✔
393
        print_native(io, d)
6 ✔
394
    else
395
        print(io, d)
8 ✔
396
    end
397
end
398
code_native(io::IO, @nospecialize(argtypes::Union{Tuple,Type{<:Tuple}}); kwargs...) = code_native(io, ArgInfo(argtypes); kwargs...)
2 ✔
399
code_native(io::IO, @nospecialize(f), @nospecialize(types=Base.default_tt(f)); kwargs...) = code_native(io, ArgInfo(f, types); kwargs...)
18 ✔
400
code_native(args...; kwargs...) = (@nospecialize; code_native(stdout, args...; kwargs...))
8 ✔
401

402
## colorized IR and assembly printing
403

404
const num_regex = r"^(?:\$?-?\d+|0x[0-9A-Fa-f]+|-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?)$"
405

406
# Iterates the captures of a regex match as `SubString`s, for destructuring them without
407
# the `nothing` that the element type of `RegexMatch.captures` allows for.
408
# Use this only with a regex whose capture groups all take part in every match.
409
# A group that can be skipped, as in `(a)?` or `(a)|(b)`, captures `nothing`, which
410
# is an error here; write `(a?)` to capture an empty string instead.
411
struct RequiredCaptures{S<:AbstractString}
9 ✔
412
    captures::Vector{Union{Nothing,SubString{S}}}
413
end
414
function Base.iterate(rc::RequiredCaptures{S}, i::Int=1) where S<:AbstractString
9 ✔
415
    i > length(rc.captures) && return nothing
9 ✔
416
    capture = rc.captures[i]
9 ✔
417
    capture === nothing && error("capture group $i did not take part in the match")
9 ✔
418
    return capture, i+1
9 ✔
419
end
420
required_captures(m::RegexMatch{S}) where S<:AbstractString = RequiredCaptures{S}(m.captures)
9 ✔
421

422
function print_llvm(io::IO, code::String)
5 ✔
423
    buf = IOBuffer(code)
5 ✔
424
    for line in eachline(buf)
5 ✔
425
        m = match(r"^(\s*)((?:[^;]|;\")*)(.*)$", line)
5 ✔
426
        m === nothing && continue
5 ✔
427
        indent, tokens, comment = required_captures(m)
5 ✔
428
        print(io, indent)
5 ✔
429
        print_llvm_tokens(io, tokens)
5 ✔
430
        printstyled_ll(io, comment, :comment)
5 ✔
431
        println(io)
5 ✔
432
    end
433
end
434

435
const llvm_types =
436
    r"^(?:void|half|float|double|x86_\w+|ppc_\w+|label|metadata|type|opaque|token|i\d+)$"
437
const llvm_cond = r"^(?:[ou]?eq|[ou]?ne|[uso][gl][te]|ord|uno)$" # true|false
438

439
function print_llvm_tokens(io::IO, tokens::AbstractString)
5 ✔
440
    m = match(r"^((?:[^\"\s:]+:|\"[^\"]*\":)?)(\s*)(.*)", tokens)
5 ✔
441
    if m !== nothing
5 ✔
442
        label, spaces, tokens = required_captures(m)
5 ✔
443
        printstyled_ll(io, label, :label, spaces)
5 ✔
444
    end
445
    m = match(r"^(%[^\s=]+)(\s*)=(\s*)(.*)", tokens)
5 ✔
446
    if m !== nothing
5 ✔
447
        result, spaces, spaces2, tokens = required_captures(m)
5 ✔
448
        printstyled_ll(io, result, :variable, spaces)
5 ✔
449
        printstyled_ll(io, '=', :default, spaces2)
5 ✔
450
    end
451
    m = match(r"^([a-z]\w*)(\s*)(.*)", tokens)
5 ✔
452
    if m !== nothing
5 ✔
453
        inst, spaces, tokens = required_captures(m)
5 ✔
454
        iskeyword = occursin(r"^(?:define|declare|type)$", inst) || occursin("=", tokens)
5 ✔
455
        printstyled_ll(io, inst, iskeyword ? :keyword : :instruction, spaces)
5 ✔
456
    end
457

458
    print_llvm_operands(io, tokens)
5 ✔
459
end
460

461
function print_llvm_operands(io::IO, tokens::AbstractString)
5 ✔
462
    while !isempty(tokens)
5 ✔
463
        tokens = print_llvm_operand(io, tokens)
5 ✔
464
    end
465
    return tokens
5 ✔
466
end
467

468
function print_llvm_operand(io::IO, tokens::AbstractString)
5 ✔
469
    islabel = false
5 ✔
470
    while !isempty(tokens)
5 ✔
471
        m = match(r"^,(\s*)(.*)", tokens)
5 ✔
472
        if m !== nothing
5 ✔
473
            spaces, tokens = required_captures(m)
5 ✔
474
            printstyled_ll(io, ',', :default, spaces)
5 ✔
475
            break
5 ✔
476
        end
477
        m = match(r"^(\*+|=)(\s*)(.*)", tokens)
5 ✔
478
        if m !== nothing
5 ✔
479
            sym, spaces, tokens = required_captures(m)
2 ✔
480
            printstyled_ll(io, sym, :default, spaces)
2 ✔
481
            continue
2 ✔
482
        end
483
        m = match(r"^(\"[^\"]*\")(\s*)(.*)", tokens)
5 ✔
484
        if m !== nothing
5 ✔
485
            str, spaces, tokens = required_captures(m)
4 ✔
486
            printstyled_ll(io, str, :variable, spaces)
4 ✔
487
            continue
4 ✔
488
        end
489
        m = match(r"^([({\[<])(\s*)(.*)", tokens)
5 ✔
490
        if m !== nothing
5 ✔
491
            bracket, spaces, tokens = required_captures(m)
5 ✔
492
            printstyled_ll(io, bracket, :bracket, spaces)
5 ✔
493
            tokens = print_llvm_operands(io, tokens) # enter
5 ✔
494
            continue
5 ✔
495
        end
496
        m = match(r"^([)}\]>])(\s*)(.*)", tokens)
5 ✔
497
        if m !== nothing
5 ✔
498
            bracket, spaces, tokens = required_captures(m)
5 ✔
499
            printstyled_ll(io, bracket, :bracket, spaces)
5 ✔
500
            break # leave
5 ✔
501
        end
502

503
        m = match(r"^([^\s,*=(){}\[\]<>]+)(\s*)(.*)", tokens)
5 ✔
504
        m === nothing && break
5 ✔
505
        token, spaces, tokens = required_captures(m)
5 ✔
506
        if occursin(llvm_types, token)
5 ✔
507
            printstyled_ll(io, token, :type)
5 ✔
508
            islabel = token == "label"
5 ✔
509
        elseif occursin(llvm_cond, token) # condition code is instruction-level
5 ✔
510
            printstyled_ll(io, token, :instruction)
5 ✔
511
        elseif occursin(num_regex, token)
5 ✔
512
            printstyled_ll(io, token, :number)
5 ✔
513
        elseif occursin(r"^@.+$", token)
5 ✔
514
            printstyled_ll(io, token, :funcname)
5 ✔
515
        elseif occursin(r"^%.+$", token)
5 ✔
516
            islabel |= occursin(r"^%[^\d].*$", token) & occursin(r"^\]", tokens)
5 ✔
517
            printstyled_ll(io, token, islabel ? :label : :variable)
5 ✔
518
            islabel = false
5 ✔
519
        elseif occursin(r"^[a-z]\w+$", token)
5 ✔
520
            printstyled_ll(io, token, :keyword)
5 ✔
521
        else
522
            printstyled_ll(io, token, :default)
5 ✔
523
        end
524
        print(io, spaces)
5 ✔
525
    end
526
    return tokens
5 ✔
527
end
528

529
function print_native(io::IO, code::String, arch::Symbol=sys_arch_category())
6 ✔
530
    archv = Val(arch)
6 ✔
531
    buf = IOBuffer(code)
6 ✔
532
    for line in eachline(buf)
6 ✔
533
        m = match(r"^(\s*)((?:[^;#/]|#\S|;\"|/[^/])*)(.*)$", line)
6 ✔
534
        m === nothing && continue
6 ✔
535
        indent, tokens, comment = required_captures(m)
6 ✔
536
        print(io, indent)
6 ✔
537
        print_native_tokens(io, tokens, archv)
6 ✔
538
        printstyled_ll(io, comment, :comment)
6 ✔
539
        println(io)
6 ✔
540
    end
541
end
542

543
function sys_arch_category()
6 ✔
544
    if Sys.ARCH === :x86_64 || Sys.ARCH === :i686
6 ✔
545
        :x86
6 ✔
546
    elseif Sys.ARCH === :aarch64 || startswith(string(Sys.ARCH), "arm")
×
547
        :arm
×
548
    elseif Sys.ARCH === :riscv64
×
549
        :riscv
×
550
    else
551
        :unsupported
×
552
    end
553
end
554

555
print_native_tokens(io, line, ::Val) = print(io, line)
2 ✔
556

557
const x86_ptr = r"^(?:(?:[xyz]mm|[dq])?word|byte|ptr|offset)$"
558
const avx512flags = r"^(?:z|r[nduz]-sae|sae|1to1?\d)$"
559
const arm_cond = r"^(?:eq|ne|cs|ho|cc|lo|mi|pl|vs|vc|hi|ls|[lg][te]|al|nv)$"
560
const arm_keywords = r"^(?:lsl|lsr|asr|ror|rrx|!|/[zm])$"
561
# rounding modes and fence orderings
562
const riscv_keywords = r"^(?:rne|rtz|rdn|rup|rmm|dyn|[iorw]{1,4})$"
563

564
function print_native_tokens(io::IO, tokens::AbstractString, arch::Union{Val{:x86}, Val{:arm}, Val{:riscv}})
6 ✔
565
    x86 = arch isa Val{:x86}
6 ✔
566
    arm = arch isa Val{:arm}
6 ✔
567
    riscv = arch isa Val{:riscv}
6 ✔
568
    m = match(r"^((?:[^\s:]+:|\"[^\"]+\":)?)(\s*)(.*)", tokens)
6 ✔
569
    if m !== nothing
6 ✔
570
        label, spaces, tokens = required_captures(m)
6 ✔
571
        printstyled_ll(io, label, :label, spaces)
6 ✔
572
    end
573
    haslabel = false
6 ✔
574
    m = match(r"^([a-z][\w.]*)(\s*)(.*)", tokens)
6 ✔
575
    if m !== nothing
6 ✔
576
        instruction, spaces, tokens = required_captures(m)
6 ✔
577
        printstyled_ll(io, instruction, :instruction, spaces)
6 ✔
578
        haslabel = riscv ? occursin(r"^(?:b(?:eqz?|nez?|(?:lt|ge|gt|le)[uz]?)|j|jal|call|tail|c\.(?:beqz|bnez|j))$", instruction) :
6 ✔
579
                           occursin(r"^(?:bl?|bl?\.\w{2,5}|[ct]bn?z)?$", instruction)
6 ✔
580
    end
581

582
    isfuncname = false
6 ✔
583
    while !isempty(tokens)
6 ✔
584
        m = match(r"^([,:*])(\s*)(.*)", tokens)
6 ✔
585
        if m !== nothing
6 ✔
586
            sym, spaces, tokens = required_captures(m)
6 ✔
587
            printstyled_ll(io, sym, :default, spaces)
6 ✔
588
            isfuncname = false
6 ✔
589
            continue
6 ✔
590
        end
591
        m = match(r"^([(){}\[\]])(\s*)(.*)", tokens)
6 ✔
592
        if m !== nothing
6 ✔
593
            bracket, spaces, tokens = required_captures(m)
6 ✔
594
            printstyled_ll(io, bracket, :bracket, spaces)
6 ✔
595
            continue
6 ✔
596
        end
597
        m = match(r"^#([0-9a-fx.-]+)(\s*)(.*)", tokens)
6 ✔
598
        if arm && m !== nothing && occursin(num_regex, m.captures[1]::AbstractString)
6 ✔
599
            num, spaces, tokens = required_captures(m)
2 ✔
600
            printstyled_ll(io, "#" * num, :number, spaces)
2 ✔
601
            continue
2 ✔
602
        end
603

604
        m = match(r"^([^\s,:*(){}\[\]][^\s,:*/(){}\[\]]*)(\s*)(.*)", tokens)
6 ✔
605
        m === nothing && break
6 ✔
606
        token, spaces, tokens = required_captures(m)
6 ✔
607
        if occursin(num_regex, token)
6 ✔
608
            printstyled_ll(io, token, :number)
6 ✔
609
        elseif x86 && occursin(x86_ptr, token) || occursin(avx512flags, token)
6 ✔
610
            printstyled_ll(io, token, :keyword)
6 ✔
611
            isfuncname = token == "offset"
6 ✔
612
        elseif arm && (occursin(arm_keywords, token) || occursin(arm_cond, token))
6 ✔
613
            printstyled_ll(io, token, :keyword)
2 ✔
614
        elseif riscv && (occursin(riscv_keywords, token) || occursin(r"^%\w+$", token))
6 ✔
615
            # relocation specifiers such as `%pcrel_hi`, `%pcrel_lo` or `%got_pcrel_hi`
616
            printstyled_ll(io, token, :keyword)
2 ✔
617
        elseif riscv && occursin(r"^\.L.+$", token)
6 ✔
618
            printstyled_ll(io, token, :label)
2 ✔
619
        elseif occursin(r"^L.+$", token)
6 ✔
620
            printstyled_ll(io, token, :label)
2 ✔
621
        elseif occursin(r"^\$.+$", token)
6 ✔
622
            printstyled_ll(io, token, :funcname)
2 ✔
623
        elseif occursin(r"^%?(?:[a-z][\w.]+|\"[^\"]+\")$", token)
6 ✔
624
            islabel = haslabel & !occursin(',', tokens)
6 ✔
625
            printstyled_ll(io, token, islabel ? :label : isfuncname ? :funcname : :variable)
6 ✔
626
            isfuncname = false
6 ✔
627
        else
628
            printstyled_ll(io, token, :default)
6 ✔
629
        end
630
        print(io, spaces)
6 ✔
631
    end
632
end
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc