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

JuliaLang / julia / 1629

17 Nov 2026 09:38PM UTC coverage: 93.211% (+0.002%) from 93.209%
1629

push

buildkite

web-flow
doc: fix dead link to the Fenichel GC paper in embedding.md (#65044)

The cs.purdue.edu copy of Fenichel and Yochelson's "A LISP
garbage-collector for virtual-memory computer systems" now returns
404. Link to the paper's DOI instead.

Assisted-by: Claude Code (Claude Opus 5.5)

100520 of 107841 relevant lines covered (93.21%)

399.26 hits per line

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

97.16
/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}
25
    tt::Type{<:Tuple}
26

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

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

45
function printstyled_ll(io::IO, x, s::Symbol, trailing_spaces="")
10 ✔
46
    printstyled(io, x, bold=llstyle[s][1], color=llstyle[s][2])
10 ✔
47
    print(io, trailing_spaces)
10 ✔
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)
6 ✔
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)
6 ✔
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
14 ✔
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")
3 ✔
99
        sig = mi.def.sig
3 ✔
100
        warn_color = Base.warn_color() # more mild user notification
3 ✔
101
        for i = 1:length(mi.sparam_vals)
3 ✔
102
            sig = sig::UnionAll
3 ✔
103
            name = sig.var.name
3 ✔
104
            val = mi.sparam_vals[i]
3 ✔
105
            # Env entries from intersection may be wrapped as svec(tvar, constrained_bool)
106
            if val isa Core.SimpleVector
3 ✔
107
                val = val[1]
3 ✔
108
            end
109
            print_highlighted(io::IO, v::String, color::Union{Symbol,Int}) =
3 ✔
110
                if highlighting[:warntype]
3 ✔
111
                    Base.printstyled(io, v; color)
3 ✔
112
                else
113
                    Base.print(io, v)
×
114
                end
115
            if val isa TypeVar
3 ✔
116
                if val.lb === Union{}
3 ✔
117
                    print(io, "  ", name, " <: ")
3 ✔
118
                    print_highlighted(io, "$(val.ub)", warn_color)
3 ✔
119
                elseif val.ub === Any
3 ✔
120
                    print(io, "  ", sig.var.name, " >: ")
3 ✔
121
                    print_highlighted(io, "$(val.lb)", warn_color)
3 ✔
122
                else
123
                    print(io, "  ")
3 ✔
124
                    print_highlighted(io, "$(val.lb)", warn_color)
3 ✔
125
                    print(io, " <: ", sig.var.name, " <: ")
3 ✔
126
                    print_highlighted(io, "$(val.ub)", warn_color)
3 ✔
127
                end
128
            elseif val isa typeof(Vararg)
3 ✔
129
                print(io, "  ", name, "::")
3 ✔
130
                print_highlighted(io, "Int", warn_color)
3 ✔
131
            else
132
                print(io, "  ", sig.var.name, " = ")
3 ✔
133
                print_highlighted(io, "$(val)", :cyan) # show the "good" type
3 ✔
134
            end
135
            println(io)
3 ✔
136
            sig = sig.body
3 ✔
137
        end
3 ✔
138
    end
139
end
140

141
"""
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
6 ✔
177
        isa(oc.source, Method) && (nargs = oc.source.nargs)
6 ✔
178
        print_warntype_codeinfo(io, Base.code_typed_opaque_closure(oc, tt; optimize, interp)[1]..., nargs;
6 ✔
179
                                lineprinter, label_dynamic_calls = optimize)
180
        return nothing
6 ✔
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
11 ✔
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...)
3 ✔
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,
50 ✔
219
                        raw::Bool, dump_module::Bool, syntax::Symbol,
220
                        optimize::Bool, debuginfo::Symbol, binary::Bool,
221
                        llvm_options::String="",
222
                        params::CodegenParams=CodegenParams(debug_info_kind=Cint(0), debug_info_level=Cint(2), safepoint_on_entry=raw, gcstack_arg=raw))
223
    ccall(:jl_is_in_pure_context, Bool, ()) && error("code reflection cannot be used from generated functions")
50 ✔
224
    warning = ""
45 ✔
225
    # get the MethodInstance for the method match
226
    if arginfo.oc === nothing
45 ✔
227
        world = Base.get_world_counter()
45 ✔
228
        match = Base._which(arginfo.tt; world)
45 ✔
229
        mi = Base.specialize_method(match)
45 ✔
230
        # TODO: use jl_is_cacheable_sig instead of isdispatchtuple
231
        isdispatchtuple(mi.specTypes) || (warning = GENERIC_SIG_WARNING)
45 ✔
232
    else
233
        (; oc, tt) = arginfo
6 ✔
234
        world = UInt64(oc.world)
6 ✔
235
        if !isdefined(oc.source, :source)
6 ✔
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
6 ✔
239
            mi = oc.source.specializations::Core.MethodInstance
6 ✔
240
            Base.hasintersect(typeof(oc).parameters[1], tt) || (warning = OC_MISMATCH_WARNING)
6 ✔
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
45 ✔
248
        debuginfo = :source
37 ✔
249
    elseif debuginfo !== :source && debuginfo !== :none
16 ✔
250
        throw(ArgumentError("'debuginfo' must be either :source or :none"))
2 ✔
251
    end
252
    if native
45 ✔
253
        if syntax !== :att && syntax !== :intel
13 ✔
254
            throw(ArgumentError("'syntax' must be either :intel or :att"))
2 ✔
255
        end
256
        str = ""
13 ✔
257
        if !dump_module
13 ✔
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)
9 ✔
260
        end
261
        if isempty(str)
13 ✔
262
            # if that failed (or we want metadata), use LLVM to generate more accurate assembly output
263
            if arginfo.oc === nothing
9 ✔
264
                src = Base.invoke_interp_compiler(nothing, :typeinf_code, Base.invoke_default_compiler(:_default_interp, world), mi, true)
9 ✔
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")
9 ✔
269
            str = _dump_function_native_assembly(mi, src, wrapper, syntax, debuginfo, binary, raw, params)
9 ✔
270
        end
271
    else
272
        if arginfo.oc === nothing
41 ✔
273
            src = Base.invoke_interp_compiler(nothing, :typeinf_code, Base.invoke_default_compiler(:_default_interp, world), mi, true)
41 ✔
274
        else
275
            src, _rt = Base.get_oc_code_rt(nothing, arginfo.oc, arginfo.tt, true)
6 ✔
276
        end
277
        src isa Core.CodeInfo || error("failed to infer source for $mi")
41 ✔
278
        str = _dump_function_llvm(mi, src, wrapper, !raw, dump_module, optimize, debuginfo, llvm_options, params)
41 ✔
279
    end
280
    str = warning * fixup_stdlib_paths(str)
45 ✔
281
    return str
45 ✔
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)
45 ✔
286
    Sys.BUILD_STDLIB_PATH == Sys.STDLIB && return str
45 ✔
287
    return replace(str, normpath(Sys.BUILD_STDLIB_PATH) => normpath(Sys.STDLIB))
45 ✔
288
end
289

290
function _dump_function_native_disassembly(mi::Core.MethodInstance, world::UInt,
9 ✔
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,
9 ✔
294
                                    syntax::Ptr{UInt8}, debuginfo::Ptr{UInt8},
295
                                    binary::Bool)::Ref{String}
296
    return str
9 ✔
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,
9 ✔
306
                                        wrapper::Bool, syntax::Symbol, debuginfo::Symbol,
307
                                        binary::Bool, raw::Bool, params::CodegenParams)
308
    llvmf_dump = Ref{LLVMFDump}()
9 ✔
309
    @ccall jl_get_llvmf_defn(llvmf_dump::Ptr{LLVMFDump}, mi::Any, src::Any, wrapper::Bool,
9 ✔
310
                             true::Bool, ""::Cstring, params::CodegenParams)::Cvoid
311
    llvmf_dump[].f == C_NULL && error("could not compile the specified method")
9 ✔
312
    str = @ccall jl_dump_function_asm(llvmf_dump::Ptr{LLVMFDump}, false::Bool,
9 ✔
313
                                      syntax::Ptr{UInt8}, debuginfo::Ptr{UInt8},
314
                                      binary::Bool, raw::Bool)::Ref{String}
315
    return str
9 ✔
316
end
317

318
function _dump_function_llvm(
41 ✔
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}()
41 ✔
325
    @ccall jl_get_llvmf_defn(llvmf_dump::Ptr{LLVMFDump}, mi::Any, src::Any,
41 ✔
326
                             wrapper::Bool, optimize::Bool, llvm_options::Cstring,
327
                             params::CodegenParams)::Cvoid
328
    llvmf_dump[].f == C_NULL && error("could not compile the specified method")
41 ✔
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,
41 ✔
331
                                     dump_module::Bool, debuginfo::Ptr{UInt8})::Ref{String}
332
    return str
41 ✔
333
end
334

335
"""
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;
46 ✔
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)
46 ✔
362
    if highlighting[:llvm] && get(io, :color, false)::Bool
41 ✔
363
        print_llvm(io, d)
6 ✔
364
    else
365
        print(io, d)
38 ✔
366
    end
367
end
368
code_llvm(io::IO, @nospecialize(argtypes::Union{Tuple,Type{<:Tuple}}); kwargs...) = code_llvm(io, ArgInfo(argtypes); kwargs...)
3 ✔
369
code_llvm(io::IO, @nospecialize(f), @nospecialize(types=Base.default_tt(f)); kwargs...) = code_llvm(io, ArgInfo(f, types); kwargs...)
46 ✔
370
code_llvm(args...; kwargs...) = (@nospecialize; code_llvm(stdout, args...; kwargs...))
12 ✔
371

372
"""
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;
19 ✔
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)
19 ✔
392
    if highlighting[:native] && get(io, :color, false)::Bool
13 ✔
393
        print_native(io, d)
7 ✔
394
    else
395
        print(io, d)
9 ✔
396
    end
397
end
398
code_native(io::IO, @nospecialize(argtypes::Union{Tuple,Type{<:Tuple}}); kwargs...) = code_native(io, ArgInfo(argtypes); kwargs...)
3 ✔
399
code_native(io::IO, @nospecialize(f), @nospecialize(types=Base.default_tt(f)); kwargs...) = code_native(io, ArgInfo(f, types); kwargs...)
19 ✔
400
code_native(args...; kwargs...) = (@nospecialize; code_native(stdout, args...; kwargs...))
9 ✔
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}
412
    captures::Vector{Union{Nothing,SubString{S}}}
10 ✔
413
end
414
function Base.iterate(rc::RequiredCaptures{S}, i::Int=1) where S<:AbstractString
10 ✔
415
    i > length(rc.captures) && return nothing
10 ✔
416
    capture = rc.captures[i]
10 ✔
417
    capture === nothing && error("capture group $i did not take part in the match")
10 ✔
418
    return capture, i+1
10 ✔
419
end
420
required_captures(m::RegexMatch{S}) where S<:AbstractString = RequiredCaptures{S}(m.captures)
10 ✔
421

422
function print_llvm(io::IO, code::String)
6 ✔
423
    buf = IOBuffer(code)
6 ✔
424
    for line in eachline(buf)
6 ✔
425
        m = match(r"^(\s*)((?:[^;]|;\")*)(.*)$", line)
6 ✔
426
        m === nothing && continue
6 ✔
427
        indent, tokens, comment = required_captures(m)
6 ✔
428
        print(io, indent)
6 ✔
429
        print_llvm_tokens(io, tokens)
6 ✔
430
        printstyled_ll(io, comment, :comment)
6 ✔
431
        println(io)
6 ✔
432
    end
6 ✔
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)
6 ✔
440
    m = match(r"^((?:[^\"\s:]+:|\"[^\"]*\":)?)(\s*)(.*)", tokens)
6 ✔
441
    if m !== nothing
6 ✔
442
        label, spaces, tokens = required_captures(m)
6 ✔
443
        printstyled_ll(io, label, :label, spaces)
6 ✔
444
    end
445
    m = match(r"^(%[^\s=]+)(\s*)=(\s*)(.*)", tokens)
6 ✔
446
    if m !== nothing
6 ✔
447
        result, spaces, spaces2, tokens = required_captures(m)
6 ✔
448
        printstyled_ll(io, result, :variable, spaces)
6 ✔
449
        printstyled_ll(io, '=', :default, spaces2)
6 ✔
450
    end
451
    m = match(r"^([a-z]\w*)(\s*)(.*)", tokens)
6 ✔
452
    if m !== nothing
6 ✔
453
        inst, spaces, tokens = required_captures(m)
6 ✔
454
        iskeyword = occursin(r"^(?:define|declare|type)$", inst) || occursin("=", tokens)
6 ✔
455
        printstyled_ll(io, inst, iskeyword ? :keyword : :instruction, spaces)
6 ✔
456
    end
457

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

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

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

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

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

543
function sys_arch_category()
7 ✔
544
    if Sys.ARCH === :x86_64 || Sys.ARCH === :i686
7 ✔
545
        :x86
6 ✔
546
    elseif Sys.ARCH === :aarch64 || startswith(string(Sys.ARCH), "arm")
1 ✔
547
        :arm
1 ✔
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)
3 ✔
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}})
7 ✔
565
    x86 = arch isa Val{:x86}
7 ✔
566
    arm = arch isa Val{:arm}
7 ✔
567
    riscv = arch isa Val{:riscv}
7 ✔
568
    m = match(r"^((?:[^\s:]+:|\"[^\"]+\":)?)(\s*)(.*)", tokens)
7 ✔
569
    if m !== nothing
7 ✔
570
        label, spaces, tokens = required_captures(m)
7 ✔
571
        printstyled_ll(io, label, :label, spaces)
7 ✔
572
    end
573
    haslabel = false
7 ✔
574
    m = match(r"^([a-z][\w.]*)(\s*)(.*)", tokens)
7 ✔
575
    if m !== nothing
7 ✔
576
        instruction, spaces, tokens = required_captures(m)
7 ✔
577
        printstyled_ll(io, instruction, :instruction, spaces)
7 ✔
578
        haslabel = riscv ? occursin(r"^(?:b(?:eqz?|nez?|(?:lt|ge|gt|le)[uz]?)|j|jal|call|tail|c\.(?:beqz|bnez|j))$", instruction) :
7 ✔
579
                           occursin(r"^(?:bl?|bl?\.\w{2,5}|[ct]bn?z)?$", instruction)
580
    end
581

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

604
        m = match(r"^([^\s,:*(){}\[\]][^\s,:*/(){}\[\]]*)(\s*)(.*)", tokens)
7 ✔
605
        m === nothing && break
7 ✔
606
        token, spaces, tokens = required_captures(m)
7 ✔
607
        if occursin(num_regex, token)
7 ✔
608
            printstyled_ll(io, token, :number)
7 ✔
609
        elseif x86 && occursin(x86_ptr, token) || occursin(avx512flags, token)
7 ✔
610
            printstyled_ll(io, token, :keyword)
7 ✔
611
            isfuncname = token == "offset"
7 ✔
612
        elseif arm && (occursin(arm_keywords, token) || occursin(arm_cond, token))
7 ✔
613
            printstyled_ll(io, token, :keyword)
3 ✔
614
        elseif riscv && (occursin(riscv_keywords, token) || occursin(r"^%\w+$", token))
7 ✔
615
            # relocation specifiers such as `%pcrel_hi`, `%pcrel_lo` or `%got_pcrel_hi`
616
            printstyled_ll(io, token, :keyword)
3 ✔
617
        elseif riscv && occursin(r"^\.L.+$", token)
7 ✔
618
            printstyled_ll(io, token, :label)
3 ✔
619
        elseif occursin(r"^L.+$", token)
7 ✔
620
            printstyled_ll(io, token, :label)
3 ✔
621
        elseif occursin(r"^\$.+$", token)
7 ✔
622
            printstyled_ll(io, token, :funcname)
3 ✔
623
        elseif occursin(r"^%?(?:[a-z][\w.]+|\"[^\"]+\")$", token)
7 ✔
624
            islabel = haslabel & !occursin(',', tokens)
7 ✔
625
            printstyled_ll(io, token, islabel ? :label : isfuncname ? :funcname : :variable)
7 ✔
626
            isfuncname = false
7 ✔
627
        else
628
            printstyled_ll(io, token, :default)
7 ✔
629
        end
630
        print(io, spaces)
7 ✔
631
    end
7 ✔
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