From 04f986be035e14d39c855952020ca256e369b3b7 Mon Sep 17 00:00:00 2001 From: Valentin Churavy Date: Mon, 19 Oct 2026 21:19:38 +0200 Subject: [PATCH 01/27] llvmcall: Ptr values as integers of their size, as native code passes them The IR of `Base.llvmcall` gets `Ptr` arguments, and returns `Ptr` results, as integers of the pointer's size (`inttoptr i64 %0`), as Julia's code generator passes them. They were `ptr`s, so IR written for native code (GPU code's, GPUCompiler's tests) didn't parse. Pointers and integers are converted with ptrtoint/inttoptr. `ccall(..., llvmcall, ...)` keeps pointers. Assisted-by: Claude Code (Opus 5.5) --- src/intrinsics.jl | 24 ++++++++++++++++++------ test/intrinsics.jl | 8 ++++++++ 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/src/intrinsics.jl b/src/intrinsics.jl index 888e535..f259495 100644 --- a/src/intrinsics.jl +++ b/src/intrinsics.jl @@ -400,8 +400,11 @@ end # %1, ...) or a `(module, entry)` pair. The IR is parsed into the module being emitted, # marked `alwaysinline`, and called. -function llvmcall_type(fc::FnCtx, @nospecialize T) +function llvmcall_type(fc::FnCtx, @nospecialize(T); ptr_as_int::Bool=false) (T === Nothing || T === Cvoid) && return LLVM.VoidType() + # (the IR of `Base.llvmcall` gets `Ptr` values as integers of their size, as native + # code passes them) + ptr_as_int && T isa DataType && T <: Ptr && return iptr_type(fc) repr_kind(T) === Inline || unsupported("llvmcall with the type ", T) ty = value_type(fc, T) # (llvmcall passes structs other than tuples as LLVM structs) @@ -424,8 +427,8 @@ function emit_llvmcall(fc::FnCtx, args::Vector{CGVal}, @nospecialize(rt)) vals = args[4:end] ATs = AT isa DataType ? collect(Any, AT.parameters) : Any[] length(ATs) == length(vals) || return nothing - lrt = llvmcall_type(fc, RT) - lats = LLVM.LLVMType[llvmcall_type(fc, T) for T in ATs] + lrt = llvmcall_type(fc, RT; ptr_as_int=true) + lats = LLVM.LLVMType[llvmcall_type(fc, T; ptr_as_int=true) for T in ATs] cgm = fc.cgm if ir isa String name = unique_name(cgm, "jl_llvmcall") @@ -451,12 +454,21 @@ function emit_llvmcall(fc::FnCtx, args::Vector{CGVal}, @nospecialize(rt)) for (v, T, t) in zip(vals, ATs, lats) cv = convert_repr(fc, v, T) cv.kind === Inline || unsupported("an llvmcall argument of type ", T) - push!(ops, LLVM.value_type(cv.V) == t ? cv.V : reinterpret_value(fc, cv.V, t)) + push!(ops, llvmcall_value(fc, cv.V, t)) end r = LLVM.call!(fc.builder, LLVM.function_type(f), f, ops) lrt isa LLVM.VoidType && return ghost(Nothing, nothing) - rty = value_type(fc, RT) - return inline(RT, LLVM.value_type(r) == rty ? r : reinterpret_value(fc, r, rty)) + return inline(RT, llvmcall_value(fc, r, value_type(fc, RT))) +end + +# a value as the LLVM type `ty` of llvmcall: pointers and integers converted, other types +# reinterpreted +function llvmcall_value(fc::FnCtx, v::LLVM.Value, ty::LLVM.LLVMType) + from = LLVM.value_type(v) + from == ty && return v + from isa LLVM.PointerType && ty isa LLVM.IntegerType && return LLVM.ptrtoint!(fc.builder, v, ty) + from isa LLVM.IntegerType && ty isa LLVM.PointerType && return LLVM.inttoptr!(fc.builder, v, ty) + return reinterpret_value(fc, v, ty) end """ diff --git a/test/intrinsics.jl b/test/intrinsics.jl index 0437fc3..edd2d23 100644 --- a/test/intrinsics.jl +++ b/test/intrinsics.jl @@ -22,6 +22,13 @@ i_fence2() = (Core.Intrinsics.atomic_fence(:sequentially_consistent, :system); n # an intrinsic with the wrong number of arguments, which inference knows throws i_bad_intrinsic(x) = Core.Intrinsics.add_int(x) i_llvmcall(x::Int32) = Base.llvmcall("%r = add i32 %0, 1\nret i32 %r", Int32, Tuple{Int32}, x) +# (pointers are integers of their size in the IR, as native code passes them) +i_llvmcall_load(p::Ptr{Int32}) = Base.llvmcall(""" + %p = inttoptr i64 %0 to i32* + %v = load i32, i32* %p, align 4 + ret i32 %v""", Int32, Tuple{Ptr{Int32}}, p) +i_llvmcall_ptr(p::Ptr{Int32}) = Base.llvmcall("%q = add i64 %0, 4\nret i64 %q", Ptr{Int32}, Tuple{Ptr{Int32}}, p) +i_llvmcall_ptrs(v::Vector{Int32}) = GC.@preserve v (i_llvmcall_load(pointer(v)), i_llvmcall_ptr(pointer(v)) - pointer(v)) i_poly(x) = 3x^2 - 2x + 1 i_loop(n) = (s = 0; for i in 1:n; s += i; end; s) i_dynamic(f, x) = f(x) @@ -95,6 +102,7 @@ end @cgtest i_fence2() @cgtest i_bad_intrinsic(1) @cgtest i_llvmcall(Int32(41)) + @cgtest i_llvmcall_ptrs(Int32[7, 8]) end @testset "code" begin From 4d18a1eeaf9941cfcfa3b8666b8437d589458190 Mon Sep 17 00:00:00 2001 From: Valentin Churavy Date: Mon, 19 Oct 2026 21:28:27 +0200 Subject: [PATCH 02/27] llvmcall convention: extern functions, overloads of intrinsics by base name - `ccall("extern name", llvmcall, ...)` calls the external function `name`, as native code does; GPU runtimes call their functions so (`malloc`, AIR's builtins, `deferred_codegen`). - The base name of an overloaded intrinsic (`llvm.powi`) is the overload of the call's signature (`llvm.powi.f64.i32`), as native code mangles it, with LLVM.jl's `Function(mod, intrinsic, ft)`. Assisted-by: Claude Code (Opus 5.5) --- src/ccall.jl | 48 ++++++++++++++++++++++++++++++++---------------- test/ccall.jl | 8 ++++++++ 2 files changed, 40 insertions(+), 16 deletions(-) diff --git a/src/ccall.jl b/src/ccall.jl index ca1d2b0..99642cc 100644 --- a/src/ccall.jl +++ b/src/ccall.jl @@ -565,9 +565,10 @@ end JuliaCodegen.emit_llvmcall_cc(fc, ex, typ) -> CGVal `ccall("llvm.name", llvmcall, rt, argtypes, args...)`: a call of the LLVM function `name` -(an intrinsic, also one that LLVM doesn't know, which back ends and validation report), -declared with the LLVM types of `llvmcall` (tuples of `VecElement`s are vectors), as -native code calls it. +(an intrinsic, also one that LLVM doesn't know, which back ends and validation report; +the base name of an overloaded one is mangled from the call's signature), or with +`"extern name"` of the external function `name`, declared with the LLVM types of +`llvmcall` (tuples of `VecElement`s are vectors), as native code calls it. """ function emit_llvmcall_cc(fc::FnCtx, ex::Expr, @nospecialize(typ)) b = fc.builder @@ -576,26 +577,33 @@ function emit_llvmcall_cc(fc::FnCtx, ex::Expr, @nospecialize(typ)) target isa Tuple && length(target) == 1 && (target = target[1]) target isa Union{Symbol,String} || unsupported("an llvmcall of a name not known at compile time") fname = String(target) - # (native code compiles anything but an intrinsic to an error: "llvmcall only supports - # intrinsic calls") - startswith(fname, "llvm.") || unsupported("an llvmcall of the non-intrinsic ", fname) nargs = length(argtypes) (nreq == 0 || nreq == nargs) || unsupported("a variadic llvmcall") - # (native code mangles the base name of an overloaded intrinsic, e.g. `llvm.powi`, from - # the signature) - intr = tryparse(LLVM.Intrinsic, fname) - intr !== nothing && LLVM.isoverloaded(intr) && LLVM.name(intr) == fname && - unsupported("an llvmcall of the unmangled overloaded intrinsic ", fname) mod = fc.cgm.mod lrt = llvmcall_type(fc, rt) lats = LLVM.LLVMType[llvmcall_type(fc, T) for T in argtypes] ft = LLVM.FunctionType(lrt, lats) - f = if haskey(LLVM.functions(mod), fname) - g = LLVM.functions(mod)[fname] - LLVM.function_type(g) == ft || unsupported("an llvmcall of ", fname, " with another signature") - g + f = if startswith(fname, "extern ") + # `extern name`: an external function of that name, e.g. of a GPU runtime + llvmcall_function(mod, chopprefix(fname, "extern "), ft) + elseif startswith(fname, "llvm.") + intr = tryparse(LLVM.Intrinsic, fname) + if intr !== nothing && LLVM.isoverloaded(intr) && LLVM.name(intr) == fname + # the base name of an overloaded intrinsic (`llvm.powi`): the overload of + # the call's signature (`llvm.powi.f64.i32`), as native code mangles it + try + LLVM.Function(mod, intr, ft) + catch err + err isa ArgumentError || rethrow() + unsupported("an llvmcall of ", fname, " with the signature ", string(ft)) + end + else + llvmcall_function(mod, fname, ft) + end else - LLVM.Function(mod, fname, ft) + # (native code compiles anything but an intrinsic or an `extern` function to an + # error: "llvmcall only supports intrinsic calls") + unsupported("an llvmcall of the non-intrinsic ", fname) end ops = LLVM.Value[] for (i, T) in enumerate(argtypes) @@ -610,6 +618,14 @@ function emit_llvmcall_cc(fc::FnCtx, ex::Expr, @nospecialize(typ)) return inline(rt, LLVM.value_type(r) == rty ? r : reinterpret_value(fc, r, rty)) end +# the function `name` of `mod` with the type `ft`, declared if there is none +function llvmcall_function(mod::LLVM.Module, name::AbstractString, ft::LLVM.FunctionType) + haskey(LLVM.functions(mod), name) || return LLVM.Function(mod, String(name), ft) + f = LLVM.functions(mod)[name] + LLVM.function_type(f) == ft || unsupported("an llvmcall of ", name, " with another signature") + return f +end + # Runtime functions that native code emits inline (`emit_ccall`'s special functions): # calling them would make their argument escape (e.g. the `Ref` of `pointer_from_objref`). function emit_special_ccall(fc::FnCtx, name::Symbol, ex::Expr, @nospecialize(rt), argtypes) diff --git a/test/ccall.jl b/test/ccall.jl index d421c6d..4d1b216 100644 --- a/test/ccall.jl +++ b/test/ccall.jl @@ -59,6 +59,8 @@ cc_fma(a, b, c) = ccall("llvm.fma.v4f32", llvmcall, CC_V4, (CC_V4, CC_V4, CC_V4) cc_donothing(x) = (ccall("llvm.donothing", llvmcall, Cvoid, ()); x) cc_unknown() = (ccall("llvm.jctest.nonexistent", llvmcall, Cvoid, ()); nothing) cc_not_intrinsic(x) = ccall("jctest_function", llvmcall, Int, (Int,), x) +cc_extern(s) = GC.@preserve s Int(ccall("extern strlen", llvmcall, Csize_t, (Ptr{UInt8},), pointer(s))) +cc_powi(x, n) = ccall("llvm.powi", llvmcall, Float64, (Float64, Int32), x, n) @testset "ccall" begin @@ -133,6 +135,12 @@ end test_module_ir(cc_unknown, (); triple=JuliaCodegen.host_target().triple) end @test_throws JuliaCodegen.Unsupported test_ir(cc_not_intrinsic, (Int,)) + # an external function, by name + @cgtest cc_extern("four") + @test occursin("declare i64 @strlen(ptr)", test_ir(cc_extern, (String,))) + # the base name of an overloaded intrinsic: the overload of the signature + @cgtest cc_powi(1.5, Int32(3)) + @test occursin("call double @llvm.powi.f64.i32(double", test_ir(cc_powi, (Float64, Int32))) end end From 7680e02383da927e69a1277932a21596913cd057 Mon Sep 17 00:00:00 2001 From: Valentin Churavy Date: Mon, 19 Oct 2026 21:46:35 +0200 Subject: [PATCH 03/27] Atomic fields: loads with an order, modifications as a cmpxchg loop - `getfield(x, f, order)` of an atomic field of a bits type of 1 to 8 bytes, or a reference, is an atomic load with the order (with the undefined- reference check), as native code; mismatches between the field and the order stay the runtime's ConcurrencyViolationError. - `Expr(:invoke_modify, ci, modifyfield!, obj, field, op, x, order)` (`@atomic x.f += 1`) of such a field is a loop of the field's atomic compare-and- exchange with `op(old, x)`, calling the CodeInstance of `op` directly, with the write barrier for references, returning `old => new`: native code's loop on Julia 1.12 (from 1.13 on, native code emits `julia.atomicmodify` for a pass to expand). A result of a type that can't be stored, and other fields, call `modifyfield!`. Assisted-by: Claude Code (Opus 5.5) --- src/builtins.jl | 130 +++++++++++++++++++++++++++++++++++++++++++++-- src/calls.jl | 8 +-- src/ccall.jl | 2 + test/builtins.jl | 36 +++++++++++++ 4 files changed, 170 insertions(+), 6 deletions(-) diff --git a/src/builtins.jl b/src/builtins.jl index 8f7aa5d..b86b6fc 100644 --- a/src/builtins.jl +++ b/src/builtins.jl @@ -387,12 +387,19 @@ function emit_getfield(fc::FnCtx, args::Vector{CGVal}, @nospecialize(rt)) (T isa DataType && isconcretetype(T)) || return nothing i = field_index(T, args[2]) i === nothing && return nothing - # an explicit order: only the plain access of a non-atomic field here + # an explicit order: the plain access of a non-atomic field, or the atomic load of an + # atomic one (mismatches are the runtime's ConcurrencyViolationError) + order = :not_atomic for a in args[3:end] a.typ === Bool && continue - (isconstant(a) && constant_value(a) === :not_atomic) || return nothing + (isconstant(a) && constant_value(a) isa Symbol) || return nothing + order = constant_value(a) end - ismutabletype(T) && Base.isfieldatomic(T, i) && return nothing + if ismutabletype(T) && Base.isfieldatomic(T, i) + order === :not_atomic && return nothing + return emit_atomic_getfield(fc, x, T, i, order, rt) + end + order === :not_atomic || return nothing FT = fieldtype(T, i) b = fc.builder if x.kind === Ghost @@ -551,6 +558,123 @@ function emit_getglobal(fc::FnCtx, args::Vector{CGVal}, @nospecialize(rt)) return convert_repr(fc, nonconst_global(fc, ref), rt) end +# the atomic load with `order` of the atomic field `i` of the object `x` of type `T`: of a +# bits type of 1 to 8 bytes, or a reference +function emit_atomic_getfield(fc::FnCtx, x::CGVal, @nospecialize(T), i::Int, order::Symbol, + @nospecialize(rt)) + x.kind === Boxed || return nothing + ord = atomic_ordering(order; load=true) + ord === nothing && return nothing + FT = fieldtype(T, i) + s = field_storage(T, i) + b = fc.builder + if s === FieldPointer + ty, W = T_tracked(), config(fc).target.pointer_size + elseif s === FieldInline && isbitstype(FT) && sizeof(FT) in (1, 2, 4, 8) && repr_kind(FT) === Inline + ty, W = LLVM.IntType(8 * sizeof(FT)), sizeof(FT) + else + return nothing + end + v = LLVM.load!(b, ty, field_address(fc, x.V, T, i)) + LLVM.ordering!(v, ord) + LLVM.alignment!(v, W) + tbaa!(fc, v, field_tbaa(fc, T)) + if s === FieldPointer + maybe_undef_field(T, i) && undef_check!(fc, v) + return convert_repr(fc, boxed(FT, v), rt) + end + return convert_repr(fc, inline(FT, llvmcall_value(fc, v, value_type(fc, FT))), rt) +end + +@noinline throw_modify_type(@nospecialize(T), @nospecialize(x)) = + throw(TypeError(:modifyfield!, "", T, x)) + +""" + JuliaCodegen.emit_invoke_modify(fc, ex, typ) -> CGVal + +`Expr(:invoke_modify, ci, modifyfield!, obj, field, op, x, order)`: `modifyfield!` with +the operation `op` known to be the CodeInstance `ci`. For an atomic field of a bits type of +1 to 8 bytes, or of a reference, a loop of the atomic compare-and-exchange of the field +with `op(old, x)`, as native code does; otherwise, the call of `modifyfield!`. +""" +function emit_invoke_modify(fc::FnCtx, ex::Expr, @nospecialize(typ)) + args = CGVal[operand(fc, a) for a in ex.args[2:end]] + any(a -> a.kind === Bottom, args) && return bottom() + # (the operation's result type, of its CodeInstance) + opt = ex.args[1] isa Core.CodeInstance ? ex.args[1].rettype : Any + r = length(args) == 6 ? emit_modify_loop(fc, invoke_target(ex.args[1]), opt, args, typ) : nothing + r === nothing || return r + return emit_dynamic_call(fc, args[1], args[2:end], typ) +end + +function emit_modify_loop(fc::FnCtx, mi::Core.MethodInstance, @nospecialize(opt), + args::Vector{CGVal}, @nospecialize(typ)) + _, obj, fld, op, x, ord = args + T = obj.typ + (obj.kind === Boxed && T isa DataType && ismutabletype(T) && isconcretetype(T)) || return nothing + i = field_index(T, fld) + (i !== nothing && isconstant(ord) && constant_value(ord) isa Symbol) || return nothing + Base.isfieldatomic(T, i) || return nothing + order = constant_value(ord) + success = atomic_ordering(order; load=true) + (success === nothing || order in (:not_atomic, :unordered)) && return nothing + FT = fieldtype(T, i) + # (a result that can't be stored: the runtime's TypeError) + typeintersect(opt, FT) === Union{} && return nothing + s = field_storage(T, i) + b = fc.builder + isref = s === FieldPointer + if isref + ity = T_tracked() + elseif s === FieldInline && isbitstype(FT) && sizeof(FT) in (1, 2, 4, 8) && repr_kind(FT) === Inline + ity = LLVM.IntType(8 * sizeof(FT)) + else + return nothing + end + W = isref ? config(fc).target.pointer_size : sizeof(FT) + addr = field_address(fc, obj.V, T, i) + value_of(v) = isref ? boxed(FT, v) : inline(FT, llvmcall_value(fc, v, value_type(fc, FT))) + bits_of(v::CGVal) = isref ? emit_box(fc, v) : llvmcall_value(fc, convert_repr(fc, v, FT).V, ity) + init = LLVM.load!(b, ity, addr) + LLVM.ordering!(init, LLVM.API.LLVMAtomicOrderingMonotonic) + LLVM.alignment!(init, W) + tbaa!(fc, init, field_tbaa(fc, T)) + f = current_function(fc) + from = current_block(b) + loop = LLVM.BasicBlock(f, "xchg") + done = LLVM.BasicBlock(f, "done_xchg") + LLVM.br!(b, loop) + LLVM.position!(b, LLVM.at_end(loop)) + old = LLVM.phi!(b, ity) + # (a reference field may be undefined: UndefRefError) + isref && undef_check!(fc, old) + oldv = value_of(old) + # the new value: `op(old, x)`, of the field's type + newv = emit_invoke_call(fc, mi, CGVal[op, oldv, x], opt) + newv.kind === Bottom && return newv + if !(newv.typ <: FT) + ok = emit_isa(fc, newv, FT) + ok === nothing && return nothing + emit_guard!(fc, ok, throw_modify_type, const_value(fc, FT), newv) + end + newbits = bits_of(newv) + r = LLVM.atomic_cmpxchg!(b, addr, old, newbits, success, LLVM.API.LLVMAtomicOrderingMonotonic; + align=W) + tbaa!(fc, r, field_tbaa(fc, T)) + loaded = LLVM.extract_value!(b, r, 0) + ok = LLVM.extract_value!(b, r, 1) + tail = current_block(b) + append!(LLVM.incoming(old), [(init, from), (loaded, tail)]) + LLVM.br!(b, ok, done, loop) + LLVM.position!(b, LLVM.at_end(done)) + isref && write_barrier!(b, fc.cgm.mod, dialect(fc), obj.V, LLVM.addrspacecast!(b, addr, T_derived()), newbits) + newfinal = isref ? boxed(FT, newbits) : value_of(newbits) + P = Pair{FT,FT} + pair = repr_kind(P) === Inline ? emit_new_inline(fc, P, CGVal[oldv, newfinal]) : nothing + pair === nothing && return nothing + return convert_repr(fc, pair, typ) +end + # `setglobal!(m, s, x, [order])` of a global of type `Any` with the default (release) order, # through its binding function emit_setglobal!(fc::FnCtx, args::Vector{CGVal}, @nospecialize(rt)) diff --git a/src/calls.jl b/src/calls.jl index 8a4963e..4e0de75 100644 --- a/src/calls.jl +++ b/src/calls.jl @@ -83,9 +83,11 @@ end invoke_target(@nospecialize(x)) = x isa Core.CodeInstance ? CC.get_ci_mi(x) : x::Core.MethodInstance -function emit_invoke!(fc::FnCtx, ex::Expr, @nospecialize(typ)) - mi = invoke_target(ex.args[1]) - args = CGVal[operand(fc, a) for a in ex.args[2:end]] +emit_invoke!(fc::FnCtx, ex::Expr, @nospecialize(typ)) = + emit_invoke_call(fc, invoke_target(ex.args[1]), CGVal[operand(fc, a) for a in ex.args[2:end]], typ) + +# the call `args` (the function first) of the method instance `mi`, a value of type `typ` +function emit_invoke_call(fc::FnCtx, mi::Core.MethodInstance, args::Vector{CGVal}, @nospecialize(typ)) # a call whose arguments may not match the signature (an invoke of a less specific # method with more specific arguments is fine; others are left to the runtime) sig = signature_argtypes(mi) diff --git a/src/ccall.jl b/src/ccall.jl index 99642cc..476ca1c 100644 --- a/src/ccall.jl +++ b/src/ccall.jl @@ -698,6 +698,8 @@ function emit_expr_head!(fc::FnCtx, idx::Int, ex::Expr, @nospecialize(typ)) return emit_foreigncall(fc, ex, typ) elseif head === :cfunction return emit_cfunction(fc, ex, typ) + elseif head === :invoke_modify + return emit_invoke_modify(fc, ex, typ) elseif head === :foreignglobal # (Julia 1.14 and later) return emit_cglobal(fc, ex.args[1], typ) elseif head === :gc_preserve_begin diff --git a/test/builtins.jl b/test/builtins.jl index 4ba6a01..052819d 100644 --- a/test/builtins.jl +++ b/test/builtins.jl @@ -50,6 +50,24 @@ const B_EGAL_PAIRS = Any[ (missing, missing), (BNested(BPoint(0, 1), BRef(2, "x")), BNested(BPoint(0, 1), BRef(2, "x"))), ] +mutable struct B_Atomic + @atomic n::Int + @atomic f::Float64 + @atomic s::Int8 + @atomic r::Any +end +b_new() = B_Atomic(1, 1.5, Int8(3), "x") +b_inc(c) = ((@atomic c.n += 2), (@atomic c.n)) +b_max(c) = ((@atomic c.f max 4.0), (@atomic c.f)) +b_small(c) = ((@atomic c.s *= Int8(2)), (@atomic c.s)) +b_ref(c) = ((@atomic c.r = (@atomic c.r) * "y"), (@atomic c.r)) +b_refmod(c) = ((@atomic c.r *= "z"), (@atomic c.r)) +b_bad(c) = (@atomic c.n += 0.5) # (the result isn't an Int: TypeError) +mutable struct B_Plain; n::Int; end +b_plain(c) = Core.modifyfield!(c, :n, +, 1) # (not atomic: an error from the runtime) +b_orders(c) = (getfield(c, :n, :monotonic), getfield(c, :f, :acquire), getfield(c, :r, :sequentially_consistent), + getfield(c, :s, :not_atomic)) # (the last: ConcurrencyViolationError) + @testset "builtins" begin @testset "===" begin @@ -146,4 +164,22 @@ end end end +@testset "atomic field modifications" begin + @cgtest b_inc(b_new()) + @cgtest b_max(b_new()) + @cgtest b_small(b_new()) + @cgtest b_ref(b_new()) + @cgtest b_refmod(b_new()) + @cgtest b_bad(b_new()) + @cgtest b_plain(B_Plain(1)) + @cgtest b_orders(b_new()) + # a loop of compare-and-exchange calling the operation, as native code + @test @filecheck begin + @check "load atomic i64" + @check "cmpxchg ptr addrspace(11) %{{[0-9]+}}, i64 %{{[0-9]+}}, i64 %{{[0-9]+}} seq_cst monotonic" + @check_not "@ijl_apply_generic" + test_ir(b_inc, (B_Atomic,)) + end +end + end From 147d48c1152610e7ef3680f87b9d43514be241b7 Mon Sep 17 00:00:00 2001 From: Valentin Churavy Date: Mon, 19 Oct 2026 22:03:18 +0200 Subject: [PATCH 04/27] throw through jl_throw also where inference knows the call throws Calls of type `Union{}` went to the runtime's dynamic dispatch, `throw` too, which native code (and so GPU compilers, which lower `jl_throw` to their exception reporting) compiles to `jl_throw`. `throw` now always reaches `emit_throw`. Assisted-by: Claude Code (Opus 5.5) --- src/calls.jl | 11 +++++++++-- test/builtins.jl | 17 +++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/src/calls.jl b/src/calls.jl index 4e0de75..ebe1f79 100644 --- a/src/calls.jl +++ b/src/calls.jl @@ -67,8 +67,15 @@ function emit_call!(fc::FnCtx, f::CGVal, ex::Expr, @nospecialize(typ)) end args = CGVal[operand(fc, a) for a in ex.args[2:end]] # a call that inference found to throw (e.g. of an intrinsic with the wrong number of - # arguments) goes to the runtime, which throws the error - typ === Union{} && return emit_dynamic_call(fc, f, args, typ) + # arguments) goes to the runtime, which throws the error; but `throw` itself, which + # throws through `jl_throw` as native code (which GPU compilers lower) + if typ === Union{} + if isconstant(f) && constant_value(f) === Core.throw + r = emit_builtin(fc, Core.throw, args, typ) + r === nothing || return r + end + return emit_dynamic_call(fc, f, args, typ) + end if isconstant(f) && constant_value(f) isa Core.IntrinsicFunction r = emit_intrinsic(fc, constant_value(f), args, typ) r === nothing || return r diff --git a/test/builtins.jl b/test/builtins.jl index 052819d..004ab76 100644 --- a/test/builtins.jl +++ b/test/builtins.jl @@ -50,6 +50,9 @@ const B_EGAL_PAIRS = Any[ (missing, missing), (BNested(BPoint(0, 1), BRef(2, "x")), BNested(BPoint(0, 1), BRef(2, "x"))), ] +b_throw(x) = throw(ArgumentError(x)) +b_throw_singleton() = throw(DivideError()) + mutable struct B_Atomic @atomic n::Int @atomic f::Float64 @@ -164,6 +167,20 @@ end end end +@testset "throw" begin + @cgtest b_throw("message") + @cgtest b_throw_singleton() + # through the runtime's `jl_throw`, as native code (which GPU compilers lower) + for (f, types) in ((b_throw, (String,)), (b_throw_singleton, ())) + @test @filecheck begin + @check_label "define internal void @julia_" + @check "call void @ijl_throw(ptr addrspace(12)" + @check_not "@ijl_apply_generic" + test_ir(f, types) + end + end +end + @testset "atomic field modifications" begin @cgtest b_inc(b_new()) @cgtest b_max(b_new()) From 059d8bc75c422d7ad1b117ee1b9f43478a42c837 Mon Sep 17 00:00:00 2001 From: Valentin Churavy Date: Mon, 19 Oct 2026 22:15:13 +0200 Subject: [PATCH 05/27] Fast-math flags on the _fast intrinsics, as native code The `_fast` arithmetic and comparison intrinsics, `sqrt_llvm_fast` and the new `min_float_fast`/`max_float_fast` (`llvm.minimum`/`llvm.maximum`) get all fast-math flags, as native code emits them: back ends choose approximate instructions from them (PTX's `div.approx`, `rsqrt.approx`, SPIR-V's `fmin`). Assisted-by: Claude Code (Opus 5.5) --- src/intrinsics.jl | 21 ++++++++++++++------- test/intrinsics.jl | 14 ++++++++++++++ 2 files changed, 28 insertions(+), 7 deletions(-) diff --git a/src/intrinsics.jl b/src/intrinsics.jl index f259495..f3f06e0 100644 --- a/src/intrinsics.jl +++ b/src/intrinsics.jl @@ -63,6 +63,13 @@ const CHECKED_ARITH = Dict{Symbol,String}( const CHECKED_DIVREM = (:checked_sdiv_int, :checked_udiv_int, :checked_srem_int, :checked_urem_int) +# the instruction of the intrinsic `name`, with all fast-math flags for the `_fast` ones, as +# native code +function fast!(name::Symbol, v::LLVM.Value) + endswith(String(name), "_fast") && v isa LLVM.Instruction && (v.fast_math.fast = true) + return v +end + isfloat_type(t::LLVM.LLVMType) = t isa Union{LLVM.HalfType,LLVM.BFloatType,LLVM.FloatType,LLVM.DoubleType} float_bits(t::LLVM.LLVMType) = t isa LLVM.DoubleType ? 64 : t isa LLVM.FloatType ? 32 : 16 @@ -142,17 +149,17 @@ function emit_intrinsic(fc::FnCtx, f::Core.IntrinsicFunction, args::Vector{CGVal if haskey(INT_BINOPS, name) return iresult(fc, INT_BINOPS[name](b, xs[1], xs[2]), rt) elseif haskey(FLOAT_BINOPS, name) - return iresult(fc, FLOAT_BINOPS[name](b, xs[1], xs[2]), rt) + return iresult(fc, fast!(name, FLOAT_BINOPS[name](b, xs[1], xs[2])), rt) elseif haskey(ICMP, name) return iresult(fc, LLVM.icmp!(b, ICMP[name], xs[1], xs[2]), Bool) elseif haskey(FCMP, name) - return iresult(fc, LLVM.fcmp!(b, FCMP[name], xs[1], xs[2]), Bool) + return iresult(fc, fast!(name, LLVM.fcmp!(b, FCMP[name], xs[1], xs[2])), Bool) elseif name === :neg_int return iresult(fc, LLVM.neg!(b, xs[1]), rt) elseif name === :not_int return iresult(fc, LLVM.not!(b, xs[1]), rt) elseif name === :neg_float || name === :neg_float_fast - return iresult(fc, LLVM.fneg!(b, xs[1]), rt) + return iresult(fc, fast!(name, LLVM.fneg!(b, xs[1])), rt) elseif name === :fpiseq return emit_fpiseq(fc, args, xs) elseif name in (:shl_int, :lshr_int, :ashr_int) @@ -162,7 +169,7 @@ function emit_intrinsic(fc::FnCtx, f::Core.IntrinsicFunction, args::Vector{CGVal neg = LLVM.icmp!(b, LLVM.API.LLVMIntSLT, y, LLVM.ConstantInt(LLVM.value_type(y), 0)) return iresult(fc, LLVM.select!(b, neg, LLVM.neg!(b, x), x), rt) elseif haskey(FLOAT_UNARY, name) - return iresult(fc, call_llvm_intrinsic!(fc, FLOAT_UNARY[name], [LLVM.value_type(xs[1])], xs), rt) + return iresult(fc, fast!(name, call_llvm_intrinsic!(fc, FLOAT_UNARY[name], [LLVM.value_type(xs[1])], xs)), rt) elseif name === :copysign_float return iresult(fc, call_llvm_intrinsic!(fc, "llvm.copysign", [LLVM.value_type(xs[1])], xs), rt) elseif name === :fma_float @@ -171,9 +178,9 @@ function emit_intrinsic(fc::FnCtx, f::Core.IntrinsicFunction, args::Vector{CGVal return iresult(fc, call_llvm_intrinsic!(fc, "llvm.fma", [LLVM.value_type(xs[1])], xs), rt) elseif name === :muladd_float return iresult(fc, call_llvm_intrinsic!(fc, "llvm.fmuladd", [LLVM.value_type(xs[1])], xs), rt) - elseif name === :min_float || name === :max_float - nm = name === :min_float ? "llvm.minimum" : "llvm.maximum" - return iresult(fc, call_llvm_intrinsic!(fc, nm, [LLVM.value_type(xs[1])], xs), rt) + elseif name in (:min_float, :max_float, :min_float_fast, :max_float_fast) + nm = name in (:min_float, :min_float_fast) ? "llvm.minimum" : "llvm.maximum" + return iresult(fc, fast!(name, call_llvm_intrinsic!(fc, nm, [LLVM.value_type(xs[1])], xs)), rt) elseif haskey(INT_UNARY, name) return emit_int_unary(fc, name, xs, rt) elseif haskey(CHECKED_ARITH, name) diff --git a/test/intrinsics.jl b/test/intrinsics.jl index edd2d23..d8a49bf 100644 --- a/test/intrinsics.jl +++ b/test/intrinsics.jl @@ -21,6 +21,9 @@ i_fence() = (Core.Intrinsics.atomic_fence(:sequentially_consistent); nothing) i_fence2() = (Core.Intrinsics.atomic_fence(:sequentially_consistent, :system); nothing) # an intrinsic with the wrong number of arguments, which inference knows throws i_bad_intrinsic(x) = Core.Intrinsics.add_int(x) +i_fast(x, y) = (Base.FastMath.mul_fast(x, y), Base.FastMath.div_fast(x, y), + Base.FastMath.min_fast(x, y), Base.FastMath.max_fast(x, y), Base.FastMath.sqrt_fast(x), + Base.FastMath.lt_fast(x, y), Base.FastMath.neg_fast(x)) i_llvmcall(x::Int32) = Base.llvmcall("%r = add i32 %0, 1\nret i32 %r", Int32, Tuple{Int32}, x) # (pointers are integers of their size in the IR, as native code passes them) i_llvmcall_load(p::Ptr{Int32}) = Base.llvmcall(""" @@ -102,6 +105,17 @@ end @cgtest i_fence2() @cgtest i_bad_intrinsic(1) @cgtest i_llvmcall(Int32(41)) + @cgtest i_fast(2.0f0, 8.0f0) + # the fast-math flags of native code + @test @filecheck begin + @check "fmul fast float" + @check "fdiv fast float" + @check "call fast float @llvm.minimum.f32" + @check "call fast float @llvm.maximum.f32" + @check "call fast float @llvm.sqrt.f32" + @check "fcmp fast olt float" + test_ir(i_fast, (Float32, Float32)) + end @cgtest i_llvmcall_ptrs(Int32[7, 8]) end From 3409f165b2901b97c045f1751887a3b10f63fa5f Mon Sep 17 00:00:00 2001 From: Valentin Churavy Date: Mon, 19 Oct 2026 22:36:45 +0200 Subject: [PATCH 06/27] The runtime's objects through its globals, as native code `true`, `false`, `nothing`, `()` and `Core.svec()` are referred to through the runtime's globals (`jl_true`, `jl_false`, `jl_nothing`, `jl_emptytuple`, `jl_emptysvec`), external constants as native code declares them (`global_jlvalue_to_llvm`), rather than literal globals of the module: GPUCompiler relocates them by name, and validates them as libjulia globals. Also: the memory test's allocation count is the least of ten measurements (`@allocated` counts what other threads allocate meanwhile; three still flaked in the full suite). Assisted-by: Claude Code (Opus 5.5) --- src/constants.jl | 25 ++++++++++++++++++++++++- test/builtins.jl | 12 ++++++++++++ test/memory.jl | 4 ++-- 3 files changed, 38 insertions(+), 3 deletions(-) diff --git a/src/constants.jl b/src/constants.jl index 3515093..3a54d97 100644 --- a/src/constants.jl +++ b/src/constants.jl @@ -11,9 +11,12 @@ """ JuliaCodegen.literal_global(cgm, x) -> LLVM.GlobalVariable -The global of `cgm` that holds the address of the object `x`. +The global of `cgm` that holds the address of the object `x`: for `true`, `false`, +`nothing`, `()` and `Core.svec()`, the runtime's own (`jl_true`, ...), as native code's. """ function literal_global(cgm::CGModule, @nospecialize x) + name = runtime_object_name(x) + name === nothing || return runtime_object_global(cgm, name) get!(cgm.literals, x) do gv = LLVM.GlobalVariable(cgm.mod, T_ptr(), unique_name(cgm, "jl_global")) LLVM.linkage!(gv, LLVM.API.LLVMExternalLinkage) @@ -21,6 +24,26 @@ function literal_global(cgm::CGModule, @nospecialize x) end end +# The objects the runtime has globals of, which native code refers to by those +# (`global_jlvalue_to_llvm` in codegen.cpp): GPU compilers relocate them by name. +const RUNTIME_OBJECTS = (true => "jl_true", false => "jl_false", nothing => "jl_nothing", + Core.svec() => "jl_emptysvec", () => "jl_emptytuple") + +function runtime_object_name(@nospecialize x) + for (obj, name) in RUNTIME_OBJECTS + x === obj && return name + end + return nothing +end + +# the runtime's global `name`, which holds the address of its object +function runtime_object_global(cgm::CGModule, name::String) + haskey(LLVM.globals(cgm.mod), name) && return LLVM.globals(cgm.mod)[name] + gv = LLVM.GlobalVariable(cgm.mod, T_ptr(), name) + LLVM.constant!(gv, true) + return gv +end + """ JuliaCodegen.literal_objects(cgm) -> Vector{Pair{String,Any}} diff --git a/test/builtins.jl b/test/builtins.jl index 004ab76..9954d79 100644 --- a/test/builtins.jl +++ b/test/builtins.jl @@ -50,6 +50,7 @@ const B_EGAL_PAIRS = Any[ (missing, missing), (BNested(BPoint(0, 1), BRef(2, "x")), BNested(BPoint(0, 1), BRef(2, "x"))), ] +b_objects(x) = Any[x > 0, nothing, ()] b_throw(x) = throw(ArgumentError(x)) b_throw_singleton() = throw(DivideError()) @@ -167,6 +168,17 @@ end end end +@testset "the runtime's objects" begin + # `true`, `false`, `nothing`, `()` and `Core.svec()` through the runtime's globals, as + # native code refers to them + ir = test_ir(b_objects, (Int,)) + for name in ("jl_true", "jl_false", "jl_nothing", "jl_emptytuple") + @test occursin("@$name = external constant ptr", ir) + end + @cgtest b_objects(1) + @cgtest b_objects(-1) +end + @testset "throw" begin @cgtest b_throw("message") @cgtest b_throw_singleton() diff --git a/test/memory.jl b/test/memory.jl index dd3d33a..a097000 100644 --- a/test/memory.jl +++ b/test/memory.jl @@ -97,8 +97,8 @@ end v = collect(1:100) cgrun(m_sum_found, v), cgrun(m_length, v) # (the least of a few measurements: a GC or another task may allocate meanwhile) - work = minimum(_ -> @allocated(cgrun(m_sum_found, v)), 1:3) - baseline = minimum(_ -> @allocated(cgrun(m_length, v)), 1:3) + work = minimum(_ -> @allocated(cgrun(m_sum_found, v)), 1:10) + baseline = minimum(_ -> @allocated(cgrun(m_length, v)), 1:10) @test work - baseline <= 64 # element accesses are tied to their memory @test @filecheck begin From 00a65cd43f05edbb1393279fed0849d2e08a0372 Mon Sep 17 00:00:00 2001 From: Valentin Churavy Date: Mon, 19 Oct 2026 22:49:07 +0200 Subject: [PATCH 07/27] Unions keep the box of a constant member, or the box it came from A value converted to an unboxed union keeps its box in the union's box slot (with the box marker): the object of a constant, as native code keeps isbits constants in unions boxed (JuliaLang/julia#55045), or the box an inline value came from (when it isn't null). Boxing the union then reuses it instead of allocating, as native code; GPUCompiler relocates such boxes as interior records. Assisted-by: Claude Code (Opus 5.5) --- src/unions.jl | 16 +++++++++++++++- test/unions.jl | 17 +++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/src/unions.jl b/src/unions.jl index 5ee5cf6..274739c 100644 --- a/src/unions.jl +++ b/src/unions.jl @@ -302,7 +302,21 @@ function to_union(fc::FnCtx, v::CGVal, @nospecialize U) v = convert_repr(fc, v, M) end payload, roots = member_parts(fc, U, v) - return make_union(fc, U, payload, i8(union_tindex(U, M)), roots) + t = i8(union_tindex(U, M)) + if union_has_box(U) && v.kind === Inline && M !== Bool + # the box of the value, if it has one: of a constant (native code keeps isbits + # constants in unions boxed, JuliaLang/julia#55045), or the box it came from + if isconstant(v) + return make_union(fc, U, payload, i8(union_tindex(U, M) | UNION_BOX_MARKER), roots; + box=literal_pointer(fc, constant_value(v))) + elseif v.vboxed !== nothing + # (which may be null: then it has none) + t = LLVM.select!(fc.builder, nonnull(fc, v.vboxed), + i8(union_tindex(U, M) | UNION_BOX_MARKER), t) + return make_union(fc, U, payload, t, roots; box=v.vboxed) + end + end + return make_union(fc, U, payload, t, roots) end """ diff --git a/test/unions.jl b/test/unions.jl index 35bc920..97d19f4 100644 --- a/test/unions.jl +++ b/test/unions.jl @@ -37,6 +37,9 @@ function u_sum_found(v::Vector{Int}) return s end +@noinline u_produce(c::Bool, a::Int32) = c ? a : 2.5 +u_box_const(c::Bool) = Any[u_produce(c, Int32(7))][1] + @testset "unions" begin @testset "members" begin @@ -107,4 +110,18 @@ end end end +@testset "constants keep their box" begin + # an isbits constant in a union keeps the object of the constant as its box + # (JuliaLang/julia#55045), as native code: boxing it allocates nothing + @cgtest u_box_const(true) + @cgtest u_box_const(false) + p() = ccall(:jl_value_ptr, Ptr{Cvoid}, (Any,), cgrun(u_box_const, false)) + @test p() == p() + @test @filecheck begin + @check_label "define internal { [8 x i8], i8, ptr addrspace(10) } @julia_u_produce" + @check "insertvalue { [8 x i8], i8, ptr addrspace(10) } %{{[0-9]+}}, i8 -12{{[0-9]}}, 1" + test_ir(u_produce, (Bool, Int32)) + end +end + end From 91c2066c374c7b225f3ea893491d82cefa774c22 Mon Sep 17 00:00:00 2001 From: Valentin Churavy Date: Mon, 19 Oct 2026 23:00:11 +0200 Subject: [PATCH 08/27] llvmcall of unknown names as native code; type checks of pointerset values - An llvmcall of a name that isn't an intrinsic LLVM knows, or an `extern` function, is an error at run time (`jl_error("llvmcall only supports intrinsic calls")`), as native code compiles it, rather than a declaration (or Unsupported): GPUCompiler reports it as an unknown intrinsic. - `pointerset` of a value of another type than the element type checks it (`emit_typecheck!`, as native `emit_typecheck`: `jl_type_error`) and unboxes it, rather than calling the intrinsic through the runtime. Assisted-by: Claude Code (Opus 5.5) --- src/ccall.jl | 22 +++++++++++++--------- src/intrinsics.jl | 44 ++++++++++++++++++++++++++++++++++++++++++++ src/runtime.jl | 8 ++++++++ test/ccall.jl | 11 +++++------ test/intrinsics.jl | 6 ++++++ 5 files changed, 76 insertions(+), 15 deletions(-) diff --git a/src/ccall.jl b/src/ccall.jl index 476ca1c..ca98e8f 100644 --- a/src/ccall.jl +++ b/src/ccall.jl @@ -564,11 +564,12 @@ end """ JuliaCodegen.emit_llvmcall_cc(fc, ex, typ) -> CGVal -`ccall("llvm.name", llvmcall, rt, argtypes, args...)`: a call of the LLVM function `name` -(an intrinsic, also one that LLVM doesn't know, which back ends and validation report; -the base name of an overloaded one is mangled from the call's signature), or with +`ccall("llvm.name", llvmcall, rt, argtypes, args...)`: a call of the LLVM intrinsic `name` +(the base name of an overloaded one is mangled from the call's signature), or with `"extern name"` of the external function `name`, declared with the LLVM types of -`llvmcall` (tuples of `VecElement`s are vectors), as native code calls it. +`llvmcall` (tuples of `VecElement`s are vectors), as native code calls it. Any other name +(also of an intrinsic LLVM doesn't know) is an error at run time ("llvmcall only supports +intrinsic calls"), as in native code. """ function emit_llvmcall_cc(fc::FnCtx, ex::Expr, @nospecialize(typ)) b = fc.builder @@ -586,9 +587,9 @@ function emit_llvmcall_cc(fc::FnCtx, ex::Expr, @nospecialize(typ)) f = if startswith(fname, "extern ") # `extern name`: an external function of that name, e.g. of a GPU runtime llvmcall_function(mod, chopprefix(fname, "extern "), ft) - elseif startswith(fname, "llvm.") + elseif startswith(fname, "llvm.") && tryparse(LLVM.Intrinsic, fname) !== nothing intr = tryparse(LLVM.Intrinsic, fname) - if intr !== nothing && LLVM.isoverloaded(intr) && LLVM.name(intr) == fname + if LLVM.isoverloaded(intr) && LLVM.name(intr) == fname # the base name of an overloaded intrinsic (`llvm.powi`): the overload of # the call's signature (`llvm.powi.f64.i32`), as native code mangles it try @@ -601,9 +602,12 @@ function emit_llvmcall_cc(fc::FnCtx, ex::Expr, @nospecialize(typ)) llvmcall_function(mod, fname, ft) end else - # (native code compiles anything but an intrinsic or an `extern` function to an - # error: "llvmcall only supports intrinsic calls") - unsupported("an llvmcall of the non-intrinsic ", fname) + # anything but an intrinsic LLVM knows or an `extern` function is an error at run + # time, as native code compiles it (which GPU compilers report) + err = declare_runtime(mod, dialect(fc), :jl_error) + LLVM.call!(b, LLVM.function_type(err), err, + LLVM.Value[cstring!(fc.cgm, "llvmcall only supports intrinsic calls")]) + return emit_unreachable!(fc) end ops = LLVM.Value[] for (i, T) in enumerate(argtypes) diff --git a/src/intrinsics.jl b/src/intrinsics.jl index f3f06e0..e32f08d 100644 --- a/src/intrinsics.jl +++ b/src/intrinsics.jl @@ -63,6 +63,40 @@ const CHECKED_ARITH = Dict{Symbol,String}( const CHECKED_DIVREM = (:checked_sdiv_int, :checked_udiv_int, :checked_srem_int, :checked_urem_int) +""" + JuliaCodegen.emit_typecheck!(fc, x, T, context) -> Union{CGVal,Nothing} + +The value `x` as a value of type `T`, checked at run time as native code's +`emit_typecheck`: a `TypeError` from the runtime (`jl_type_error(context, T, x)`) when it +isn't one. `nothing` if the check needs a subtype test. +""" +function emit_typecheck!(fc::FnCtx, x::CGVal, @nospecialize(T), context::String) + x.typ <: T && return convert_repr(fc, x, T) + b = fc.builder + function type_error() + err = declare_runtime(fc.cgm.mod, dialect(fc), :jl_type_error) + rooted(v) = LLVM.addrspacecast!(b, v, LLVM.PointerType(AddrSpace.CalleeRooted)) + LLVM.call!(b, LLVM.function_type(err), err, + LLVM.Value[cstring!(fc.cgm, context), literal_pointer(fc, T), rooted(emit_box(fc, x))]) + LLVM.unreachable!(b) + end + if typeintersect(x.typ, T) === Union{} + type_error() + LLVM.position!(b, LLVM.at_end(LLVM.BasicBlock(current_function(fc), "after_type_error"))) + return bottom() + end + ok = emit_isa(fc, x, T) + ok === nothing && return nothing + f = current_function(fc) + fail = LLVM.BasicBlock(f, "type_error") + pass = LLVM.BasicBlock(f, "pass") + LLVM.br!(b, ok, pass, fail) + LLVM.position!(b, LLVM.at_end(fail)) + type_error() + LLVM.position!(b, LLVM.at_end(pass)) + return convert_repr(fc, x.kind === Boxed ? boxed(T, x.V) : x, T) +end + # the instruction of the intrinsic `name`, with all fast-math flags for the `_fast` ones, as # native code function fast!(name::Symbol, v::LLVM.Value) @@ -137,6 +171,16 @@ function emit_intrinsic(fc::FnCtx, f::Core.IntrinsicFunction, args::Vector{CGVal # `cglobal(target, T)` up to Julia 1.13 (a `:foreignglobal` expression later) name === :cglobal && return nothing (haskey(CASTS, name) || name === :bitcast) && return emit_cast(fc, name, args) + if name === :pointerset && length(args) == 4 && args[1].kind === Inline && args[1].typ <: Ptr + # the value as the element type, with a TypeError for others (as native code) + T = eltype(args[1].typ) + if repr_kind(T) === Inline && args[2].typ !== T + v = emit_typecheck!(fc, args[2], T, "pointerset") + v === nothing && return nothing + v.kind === Bottom && return v + args = CGVal[args[1], v, args[3], args[4]] + end + end any(a -> a.kind !== Inline, args) && return nothing # arithmetic and comparisons of operands of different types are a run-time error if (haskey(INT_BINOPS, name) || haskey(FLOAT_BINOPS, name) || haskey(ICMP, name) || diff --git a/src/runtime.jl b/src/runtime.jl index 5a20571..872d0e0 100644 --- a/src/runtime.jl +++ b/src/runtime.jl @@ -49,6 +49,14 @@ function declare_runtime(mod::LLVM.Module, dialect::JuliaIR.Dialect, name::Symbo push!(f.function_attributes, LLVM.EnumAttribute("willreturn")) elseif name === :jl_current_exception f = LLVM.Function(mod, sym, LLVM.FunctionType(T_tracked(), [T_ptr()])) + elseif name === :jl_type_error + # `void (const char *fname, jl_value_t *expected, jl_value_t *got)` + f = LLVM.Function(mod, sym, LLVM.FunctionType(LLVM.VoidType(), [T_ptr(), T_tracked(), T_rooted])) + push!(f.function_attributes, LLVM.EnumAttribute("noreturn")) + elseif name === :jl_error + # `void (const char *str)` + f = LLVM.Function(mod, sym, LLVM.FunctionType(LLVM.VoidType(), [T_ptr()])) + push!(f.function_attributes, LLVM.EnumAttribute("noreturn")) elseif name === :jl_undefined_var_error # `void (jl_sym_t *var, jl_value_t *scope)` f = LLVM.Function(mod, sym, LLVM.FunctionType(LLVM.VoidType(), [T_rooted, T_rooted])) diff --git a/test/ccall.jl b/test/ccall.jl index 4d1b216..cb9adde 100644 --- a/test/ccall.jl +++ b/test/ccall.jl @@ -129,12 +129,11 @@ end @check "call double @llvm.sqrt.f64(double" test_ir(cc_sqrt, (Float64,)) end - # an intrinsic LLVM doesn't know is declared, and left to back ends and validation - @test @filecheck begin - @check "declare void @llvm.jctest.nonexistent()" - test_module_ir(cc_unknown, (); triple=JuliaCodegen.host_target().triple) - end - @test_throws JuliaCodegen.Unsupported test_ir(cc_not_intrinsic, (Int,)) + # an intrinsic LLVM doesn't know, or not an intrinsic: an error at run time, as native + # code ("llvmcall only supports intrinsic calls") + @cgtest cc_unknown() + @cgtest cc_not_intrinsic(1) + @test occursin("call void @ijl_error(", test_ir(cc_unknown, ())) # an external function, by name @cgtest cc_extern("four") @test occursin("declare i64 @strlen(ptr)", test_ir(cc_extern, (String,))) diff --git a/test/intrinsics.jl b/test/intrinsics.jl index d8a49bf..41a6cc1 100644 --- a/test/intrinsics.jl +++ b/test/intrinsics.jl @@ -21,6 +21,7 @@ i_fence() = (Core.Intrinsics.atomic_fence(:sequentially_consistent); nothing) i_fence2() = (Core.Intrinsics.atomic_fence(:sequentially_consistent, :system); nothing) # an intrinsic with the wrong number of arguments, which inference knows throws i_bad_intrinsic(x) = Core.Intrinsics.add_int(x) +i_store_any(v::Vector{Int}, x) = GC.@preserve v (unsafe_store!(pointer(v), x); v[1]) i_fast(x, y) = (Base.FastMath.mul_fast(x, y), Base.FastMath.div_fast(x, y), Base.FastMath.min_fast(x, y), Base.FastMath.max_fast(x, y), Base.FastMath.sqrt_fast(x), Base.FastMath.lt_fast(x, y), Base.FastMath.neg_fast(x)) @@ -106,6 +107,11 @@ end @cgtest i_bad_intrinsic(1) @cgtest i_llvmcall(Int32(41)) @cgtest i_fast(2.0f0, 8.0f0) + # a value of another type than the element: checked (TypeError), as native code + @cgtest i_store_any([1], Any[5][1]) + @cgtest i_store_any([1], Any[5.5][1]) # (InexactError, from `convert`) + @cgtest i_store_any([1], Any["x"][1]) # (MethodError, from `convert`) + @test occursin("@ijl_type_error(", test_ir(unsafe_store!, (Ptr{Int}, Any, Int))) # the fast-math flags of native code @test @filecheck begin @check "fmul fast float" From f633ae3a957197cb72132d2bd0d04775cdbf24ef Mon Sep 17 00:00:00 2001 From: Valentin Churavy Date: Mon, 19 Oct 2026 23:14:07 +0200 Subject: [PATCH 09/27] ccall: runtime symbols by their ijl_ alias; others lazily bound as native code A C symbol without a library is the runtime's only if libjulia-internal has its `ijl_` alias, as native code decides. Otherwise it's bound lazily on first use from the library `jl_dlfind` finds: - the runtime's own libraries are named by `jl_dlfind`'s sentinels (`JL_EXE_LIBNAME` etc.), which were taken for strings, and are passed with their handle's global (`jl_libjulia_internal_handle`, ...), as native code passes them; - the slot is named as native code's lazily bound functions (`jlplt_name_N_got`), which GPUCompiler reports as such. The check of the library's own symbols called `jl_dlsym` with a `search_deps` argument that Julia 1.12's doesn't have: there it found C library functions (`time`) through the runtime's dependencies. Assisted-by: Claude Code (Opus 5.5) --- src/ccall.jl | 41 ++++++++++++++++++++++++++++++----------- 1 file changed, 30 insertions(+), 11 deletions(-) diff --git a/src/ccall.jl b/src/ccall.jl index ca98e8f..196a4a9 100644 --- a/src/ccall.jl +++ b/src/ccall.jl @@ -262,10 +262,24 @@ function runtime_symbol_name(sym::Symbol) isempty(hs) && return nothing iname = Symbol("i", sym) own_dlsym(hs[1], iname) != C_NULL && return String(iname) - any(h -> own_dlsym(h, sym) != C_NULL, hs) && return String(sym) return nothing end +# the runtime's libraries as `jl_dlfind` names them (pointers that are not strings, +# `JL_EXE_LIBNAME` etc.), with the globals of their handles +const RUNTIME_LIBRARIES = Dict(1 => "jl_exe_handle", 2 => "jl_libjulia_handle", + 3 => "jl_libjulia_internal_handle") + +# the library that defines `sym` as native code finds it (`jl_dlfind`): `nothing` (any +# library), a library name (on Windows, which has no global symbol namespace, the C +# runtime, kernel32, ...), or one of the runtime's libraries (an `Int`, see above) +function find_library(sym::Symbol) + found = ccall(:jl_dlfind, Ptr{UInt8}, (Cstring,), String(sym)) + found == C_NULL && return nothing + haskey(RUNTIME_LIBRARIES, Int(UInt(found))) && return Int(UInt(found)) + return unsafe_string(found) +end + # an external declaration: a function of type `ft`, or without `ft`, a global function declare_symbol(cgm::CGModule, name::String, ft=nothing) mod = cgm.mod @@ -276,8 +290,8 @@ function declare_symbol(cgm::CGModule, name::String, ft=nothing) end # a module-owned `ptr` global, initially null -function symbol_cache!(cgm::CGModule, prefix::String) - gv = LLVM.GlobalVariable(cgm.mod, T_ptr(), unique_name(cgm, prefix)) +function symbol_cache!(cgm::CGModule, prefix::String, suffix::String="") + gv = LLVM.GlobalVariable(cgm.mod, T_ptr(), unique_name(cgm, prefix) * suffix) LLVM.initializer!(gv, LLVM.null(T_ptr())) LLVM.linkage!(gv, LLVM.API.LLVMInternalLinkage) return gv @@ -307,16 +321,14 @@ function emit_symbol_address(fc::FnCtx, sym::Symbol, @nospecialize(lib); ft=noth if lib === nothing && libexpr === nothing rname = runtime_symbol_name(sym) rname === nothing || return declare_symbol(cgm, rname, ft) - # the library that defines it, as native code finds it (`jl_dlfind`): on Windows, - # which has no global symbol namespace, the C runtime, kernel32, ... - found = ccall(:jl_dlfind, Cstring, (Cstring,), String(sym)) - found == C_NULL || (lib = unsafe_string(found)) + lib = find_library(sym) end b = fc.builder P = T_ptr() W = config(fc).target.pointer_size - dynamic = libexpr !== nothing || !(lib === nothing || lib isa Union{String,Symbol}) - cache = symbol_cache!(cgm, "ccall_" * String(sym)) + dynamic = libexpr !== nothing || !(lib === nothing || lib isa Union{String,Symbol,Int}) + # (named as native code's lazily bound functions, `jlplt_name_N_got`) + cache = symbol_cache!(cgm, "jlplt_" * String(sym), "_got") cached = LLVM.load!(b, P, cache; align=W, ordering=LLVM.API.LLVMAtomicOrderingUnordered) from = current_block(b) f = current_function(fc) @@ -330,8 +342,15 @@ function emit_symbol_address(fc::FnCtx, sym::Symbol, @nospecialize(lib); ft=noth LLVM.call!(b, LLVM.function_type(lf), lf, LLVM.Value[libv, literal_pointer(fc, sym)]) else lf = declare_runtime(cgm.mod, dialect(fc), :jl_load_and_lookup) - libname, hnd = lib === nothing ? (LLVM.null(P), declare_symbol(cgm, "jl_RTLD_DEFAULT_handle")) : - (cstring!(cgm, String(lib)), symbol_cache!(cgm, "ccalllib")) + libname, hnd = if lib === nothing + LLVM.null(P), declare_symbol(cgm, "jl_RTLD_DEFAULT_handle") + elseif lib isa Int + # one of the runtime's libraries, by `jl_dlfind`'s name and its handle's global + LLVM.const_inttoptr(LLVM.ConstantInt(iptr_type(fc), lib), P), + declare_symbol(cgm, RUNTIME_LIBRARIES[lib]) + else + cstring!(cgm, String(lib)), symbol_cache!(cgm, "ccalllib") + end LLVM.call!(b, LLVM.function_type(lf), lf, LLVM.Value[libname, cstring!(cgm, String(sym)), hnd]) end LLVM.store!(b, found, cache; align=W, ordering=LLVM.API.LLVMAtomicOrderingRelease) From a922cba1da1749dbdcd728b02f9d0ae80c327cef Mon Sep 17 00:00:00 2001 From: Valentin Churavy Date: Mon, 19 Oct 2026 23:21:17 +0200 Subject: [PATCH 10/27] Globals: other bindings from the runtime, typed assignments through the binding - A global that isn't a plain global of the world of the code (imported, not yet resolved, undefined) is read with `jl_get_binding_value_seqcst` on its binding, with `UndefVarError` when it is null, as native code reads it (GPUCompiler reports it as a delayed binding), rather than through a call of `getglobal`. - An assignment of a global with a declared type of a value of that type goes through the binding (release store, write barrier), as native code; values that need converting still go through `setglobal!`. Assisted-by: Claude Code (Opus 5.5) --- src/builtins.jl | 29 ++++++++++++++++++----------- src/runtime.jl | 5 ++++- test/exceptions.jl | 10 ++++++++-- 3 files changed, 30 insertions(+), 14 deletions(-) diff --git a/src/builtins.jl b/src/builtins.jl index b86b6fc..9fb2952 100644 --- a/src/builtins.jl +++ b/src/builtins.jl @@ -319,16 +319,23 @@ end function nonconst_global(fc::FnCtx, ref::GlobalRef) d = direct_binding(fc, ref) + b = fc.builder if d === nothing - return emit_dynamic_call(fc, const_value(fc, Core.getglobal), - CGVal[const_value(fc, ref.mod), const_value(fc, ref.name)], Any) + # another binding (imported, not yet resolved, undefined): its value from the + # runtime (`jl_get_binding_value_seqcst`), as native code reads it + bnd = convert(Core.Binding, ref) + t = literal_pointer(fc, bnd) + raw = t isa LLVM.AddrSpaceCastInst ? LLVM.operands(t)[1] : LLVM.addrspacecast!(b, t, T_ptr()) + gb = declare_runtime(fc.cgm.mod, dialect(fc), :jl_get_binding_value_seqcst) + v = LLVM.call!(b, LLVM.function_type(gb), gb, LLVM.Value[raw]) + T = Any + else + bnd, T = d + v = LLVM.load!(b, T_tracked(), binding_value_address(fc, bnd)) + LLVM.ordering!(v, LLVM.API.LLVMAtomicOrderingUnordered) + LLVM.alignment!(v, config(fc).target.pointer_size) + tbaa!(fc, v, :binding) end - bnd, T = d - b = fc.builder - v = LLVM.load!(b, T_tracked(), binding_value_address(fc, bnd)) - LLVM.ordering!(v, LLVM.API.LLVMAtomicOrderingUnordered) - LLVM.alignment!(v, config(fc).target.pointer_size) - tbaa!(fc, v, :binding) # undefined: an UndefVarError, from the runtime as native code's f = current_function(fc) err = LLVM.BasicBlock(f, "err") @@ -343,11 +350,11 @@ function nonconst_global(fc::FnCtx, ref::GlobalRef) return boxed(T isa Type ? T : Any, v) end -# `global ref = v` of a global of type `Any` through its binding, as native code does; -# `false` for other bindings +# `global ref = v` of a global through its binding, as native code does, when `v` is of the +# global's type (no conversion); `false` for other bindings function emit_binding_assignment!(fc::FnCtx, ref::GlobalRef, v::CGVal) d = direct_binding(fc, ref) - (d === nothing || d[2] !== Any) && return false + (d === nothing || !(d[2] isa Type && v.typ <: d[2])) && return false bnd, _ = d b = fc.builder p = emit_box(fc, v) diff --git a/src/runtime.jl b/src/runtime.jl index 872d0e0..7e2b490 100644 --- a/src/runtime.jl +++ b/src/runtime.jl @@ -49,6 +49,9 @@ function declare_runtime(mod::LLVM.Module, dialect::JuliaIR.Dialect, name::Symbo push!(f.function_attributes, LLVM.EnumAttribute("willreturn")) elseif name === :jl_current_exception f = LLVM.Function(mod, sym, LLVM.FunctionType(T_tracked(), [T_ptr()])) + elseif name === :jl_get_binding_value_seqcst + # `jl_value_t *(jl_binding_t *b)`, null when undefined + f = LLVM.Function(mod, sym, LLVM.FunctionType(T_tracked(), [T_ptr()])) elseif name === :jl_type_error # `void (const char *fname, jl_value_t *expected, jl_value_t *got)` f = LLVM.Function(mod, sym, LLVM.FunctionType(LLVM.VoidType(), [T_ptr(), T_tracked(), T_rooted])) @@ -97,7 +100,7 @@ end # the exported name of a runtime function: `ijl_` for the `jl_` functions libjulia # exports under both names (not the internal ones, like `jl_egal__unboxed`) -const INTERNAL_RUNTIME = (:jl_egal__unboxed, :jl_alloc_genericmemory) +const INTERNAL_RUNTIME = (:jl_egal__unboxed, :jl_alloc_genericmemory, :jl_get_binding_value_seqcst) runtime_symbol(name::Symbol) = startswith(String(name), "jl_") && !(name in INTERNAL_RUNTIME) ? "i" * String(name) : String(name) diff --git a/test/exceptions.jl b/test/exceptions.jl index d9eac14..35b4b5d 100644 --- a/test/exceptions.jl +++ b/test/exceptions.jl @@ -89,8 +89,14 @@ end @check "call void @ijl_undefined_var_error" test_ir(e_assign, (Int,)) end - # a typed global is assigned through the runtime, which converts the value - @test occursin("@ijl_apply_generic", test_ir(e_typed_assign, (Int,))) + # a typed global with a value of its type through the binding too; one that needs + # converting through the runtime + @test !occursin("@ijl_apply_generic", test_ir(e_typed_assign, (Int,))) + @cgtest e_typed_assign(Int8(3)) + @cgtest e_typed_assign(2.0) + @cgtest e_typed_assign(2.5) # (InexactError) + # undefined names, from the runtime + @test occursin("@jl_get_binding_value_seqcst(", test_ir(e_read_undefined, ())) end @testset "code" begin From cccbdf5e799217deca4c4382593b74cd7fe8ddc0 Mon Sep 17 00:00:00 2001 From: Valentin Churavy Date: Mon, 19 Oct 2026 23:58:08 +0200 Subject: [PATCH 11/27] Calls of specialized varargs methods: compiled, with the varargs packed A varargs method instance's function takes its varargs in a tuple, as its IR has them (`function_argtypes`): - an `:invoke` of a specialized one packs the trailing arguments, as native code calls it; - jlcall entries unpack them from the arguments array: by the signature, or, for a signature ending in `Vararg`, with the runtime's `jl_f_tuple`; - stubs pass them one by one to native code again (splatting a tuple of unknown length). Varargs methods were stubs that called native code. Ones whose signature ends in `Vararg` (as Julia's inference keeps many varargs calls) are still called through `jl_invoke`, with the arguments one by one. The JIT driver collects varargs callees too, and takes the CodeInstances that `:invoke`s refer to as they are: inferring their method instance again can give a CodeInstance of another, normalized, one (`Core.TypeEgal`). Assisted-by: Claude Code (Opus 5.5) --- src/calls.jl | 9 ++- src/function.jl | 138 ++++++++++++++++++++++++++++++++++++++-------- src/ir.jl | 2 +- src/jit.jl | 23 +++++--- test/calls.jl | 22 +++++++- test/emit_into.jl | 11 ++-- test/jitdriver.jl | 2 +- 7 files changed, 167 insertions(+), 40 deletions(-) diff --git a/src/calls.jl b/src/calls.jl index ebe1f79..2923814 100644 --- a/src/calls.jl +++ b/src/calls.jl @@ -98,11 +98,16 @@ function emit_invoke_call(fc::FnCtx, mi::Core.MethodInstance, args::Vector{CGVal # a call whose arguments may not match the signature (an invoke of a less specific # method with more specific arguments is fine; others are left to the runtime) sig = signature_argtypes(mi) - if !(mi.def isa Method) || mi.def.isva || any(T -> T isa Core.TypeofVararg, sig) || - length(args) != length(sig) || !all(i -> args[i].typ <: sig[i], eachindex(args)) + # (a varargs method instance whose signature has a `Vararg`, e.g. of an error path, is + # called through the runtime, with the arguments one by one; specialized ones are + # compiled) + if !(mi.def isa Method) || !args_match(sig, args) || + (!isempty(sig) && last(sig) isa Core.TypeofVararg) return emit_dynamic_call(fc, args[1], args[2:end], typ; invoke=mi) end info = get_function!(fc.cgm, mi) + # (the varargs of a varargs method in the tuple its function takes) + mi.def.isva && (args = pack_varargs(fc, mi, args)) r = emit_call_info(fc, info, args) r.kind === Bottom && return r return convert_repr(fc, r, typ) diff --git a/src/function.jl b/src/function.jl index 0c44a42..a3447d1 100644 --- a/src/function.jl +++ b/src/function.jl @@ -51,6 +51,55 @@ end signature_argtypes(mi::Core.MethodInstance) = Any[Base.unwrap_unionall(mi.specTypes).parameters...] +""" + JuliaCodegen.function_argtypes(mi) -> Vector{Any} + +The argument types of the function of `mi`, as its IR has them: those of its signature, +with the varargs of a varargs method packed into a tuple. +""" +function function_argtypes(mi::Core.MethodInstance) + sig = signature_argtypes(mi) + m = mi.def + (m isa Method && m.isva) || return sig + n = Int(m.nargs) + return Any[sig[1:n-1]..., Tuple{sig[n:end]...}] +end + +""" + JuliaCodegen.pack_varargs(fc, mi, args) -> Vector{CGVal} + +The arguments `args` of a call of the varargs method instance `mi`, one per element of its +signature, with the varargs packed into the tuple its function takes. +""" +function pack_varargs(fc::FnCtx, mi::Core.MethodInstance, args::Vector{CGVal}) + n = Int(mi.def.nargs) + rest = args[n:end] + TT = Tuple{(a.typ for a in rest)...} + PT = function_argtypes(mi)[n] + tup = if repr_kind(TT) === Ghost + ghost(TT, something(ghost_value(TT))) + elseif repr_kind(TT) === Inline + emit_new_inline(fc, TT, CGVal[convert_repr(fc, a, a.typ) for a in rest]) + else + nothing + end + tup === nothing && (tup = emit_dynamic_call(fc, const_value(fc, Core.tuple), rest, TT)) + return CGVal[args[1:n-1]..., convert_repr(fc, tup, PT)] +end + +# whether `args` are of the types of the signature `sig` (whose last element may be a +# `Vararg`) +function args_match(sig::Vector{Any}, args::Vector{CGVal}) + if !isempty(sig) && last(sig) isa Core.TypeofVararg + fixed = sig[1:end-1] + T = Base.unwrapva(last(sig)) + length(args) >= length(fixed) || return false + return all(i -> args[i].typ <: fixed[i], eachindex(fixed)) && + all(a -> a.typ <: T, args[length(fixed)+1:end]) + end + return length(args) == length(sig) && all(i -> args[i].typ <: sig[i], eachindex(args)) +end + # the pgcstack and the current task, and the safepoint on entry function emit_prologue!(fc::FnCtx; safepoint::Bool=true) b = fc.builder @@ -296,16 +345,41 @@ function emit_jlcall_wrapper!(cgm::CGModule, info::FuncInfo, name::AbstractStrin debug_function!(fc, f) emit_prologue!(fc; safepoint=false) F, argv, _ = LLVM.parameters(f) - ops = LLVM.Value[] - for (i, T) in enumerate(info.argtypes) - repr_kind(T) === Ghost && continue + # the arguments, one per element of the signature (the varargs of a varargs method + # packed for its function) + sig = signature_argtypes(info.mi) + m = info.mi.def + nfixed = length(sig) + packed = nothing + if !isempty(sig) && last(sig) isa Core.TypeofVararg + # as many varargs as the call has: packed by the runtime (`jl_f_tuple`, the builtin) + nfixed = Int(m.nargs) - 1 + ft = LLVM.FunctionType(T_tracked(), [T_tracked(), T_ptr(), LLVM.Int32Type()]) + tf = declare_symbol(cgm, "jl_f_tuple", ft) + k = nfixed - 1 # (the function isn't in the array) + rest = LLVM.gep!(b, T_tracked(), argv, [LLVM.ConstantInt(LLVM.Int64Type(), k)]) + n = LLVM.sub!(b, LLVM.parameters(f)[3], LLVM.ConstantInt(LLVM.Int32Type(), k)) + packed = boxed(info.argtypes[end], LLVM.call!(b, ft, tf, LLVM.Value[LLVM.null(T_tracked()), rest, n])) + end + args = CGVal[] + for (i, T) in enumerate(sig[1:nfixed]) p = if i == 1 F else slot = LLVM.gep!(b, T_tracked(), argv, [LLVM.ConstantInt(LLVM.Int64Type(), i - 2)]) tbaa!(fc, LLVM.load!(b, T_tracked(), slot; align=config(fc).target.pointer_size), :const) end - push!(ops, convert_repr(fc, boxed(Any, p), T).V) + push!(args, convert_repr(fc, boxed(Any, p), T)) + end + if packed !== nothing + push!(args, packed) + elseif m isa Method && m.isva + args = pack_varargs(fc, info.mi, args) + end + ops = LLVM.Value[] + for (a, T) in zip(args, info.argtypes) + repr_kind(T) === Ghost && continue + push!(ops, convert_repr(fc, a, T).V) end r = LLVM.call!(b, LLVM.function_type(info.llvmf), info.llvmf, ops) # (the entry is the function, as native code's: inlined by any pipeline) @@ -329,7 +403,7 @@ end The function of `mi` in the module, declared on first use and queued for emission: its body from its IR, or a stub that calls its native code (for methods that always throw, -which are error paths, and varargs methods, for now). +which are error paths). """ function get_function!(cgm::CGModule, mi::Core.MethodInstance) info = get(cgm.funcs, mi, nothing) @@ -339,23 +413,19 @@ function get_function!(cgm::CGModule, mi::Core.MethodInstance) ir = nothing rt = Any reason = nothing - if m.isva - reason = "a varargs method" - else - try - ir, rt = cgm.ir_source(mi, cgm.world) - catch err - err isa Unsupported || rethrow() - # (calling native code instead follows the configuration's policy) - handle_failure(cgm.config, mi, err, catch_backtrace()) - reason = err - end - if ir !== nothing && rt === Union{} && cgm.throwing_stubs - reason = "a method that always throws" - ir = nothing - end + try + ir, rt = cgm.ir_source(mi, cgm.world) + catch err + err isa Unsupported || rethrow() + # (calling native code instead follows the configuration's policy) + handle_failure(cgm.config, mi, err, catch_backtrace()) + reason = err + end + if ir !== nothing && rt === Union{} && cgm.throwing_stubs + reason = "a method that always throws" + ir = nothing end - info = declare_function!(cgm, mi, signature_argtypes(mi), ir === nothing ? Any : rt) + info = declare_function!(cgm, mi, function_argtypes(mi), ir === nothing ? Any : rt) push!(cgm.worklist, (info, ir === nothing ? reason : ir)) return info end @@ -412,7 +482,31 @@ function emit_stub!(cgm::CGModule, info::FuncInfo) 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) + args = fc.args + m = info.mi.def + r = nothing + if m isa Method && m.isva + # the native code of the method takes the varargs one by one + tup = args[end] + PT = tup.typ + elems = PT isa DataType && !Base.isvatuple(PT) ? CGVal[] : nothing + for i in 1:(elems === nothing ? 0 : fieldcount(PT)) + e = emit_builtin(fc, Core.getfield, CGVal[tup, const_value(fc, i)], fieldtype(PT, i)) + e === nothing && (elems = nothing; break) + push!(elems, e) + end + if elems !== nothing + args = CGVal[args[1:end-1]..., elems...] + else + # as many as the tuple has: splat it (`f(fixed..., tup...)`) + fixed = emit_dynamic_call(fc, const_value(fc, Core.tuple), args[2:end-1], + Tuple{(a.typ for a in args[2:end-1])...}) + r = emit_dynamic_call(fc, const_value(fc, Core._apply_iterate), + CGVal[const_value(fc, iterate), args[1], fixed, tup], info.rettype) + end + end + r === nothing && + (r = emit_dynamic_call(fc, args[1], args[2:end], info.rettype; invoke=info.mi)) emit_return!(fc, r) end end diff --git a/src/ir.jl b/src/ir.jl index 4f94ff1..14f63f2 100644 --- a/src/ir.jl +++ b/src/ir.jl @@ -32,7 +32,7 @@ jlcall entry wrapper named `name`. The entry function itself must be supported: function emit_entry!(cgm::CGModule, @nospecialize(tt::Type); name::AbstractString=unique_name(cgm, "jfptr")) mi = method_instance(tt, cgm.world) ir, rt = cgm.ir_source(mi, cgm.world) - info = declare_function!(cgm, mi, signature_argtypes(mi), rt) + info = declare_function!(cgm, mi, function_argtypes(mi), rt) push!(cgm.worklist, (info, ir)) process_worklist!(cgm; strict=mi) f = emit_jlcall_wrapper!(cgm, info, name) diff --git a/src/jit.jl b/src/jit.jl index 0a52e9f..b0519d1 100644 --- a/src/jit.jl +++ b/src/jit.jl @@ -35,24 +35,31 @@ The CodeInstances that `interp` infers for `mi` and, transitively, for what its function collect_codeinfos(interp::CC.AbstractInterpreter, mi::Core.MethodInstance) out = Pair{Core.CodeInstance,Core.CodeInfo}[] seen = IdSet{Core.MethodInstance}() - work = [mi] + # (a method instance, or the CodeInstance an `:invoke` refers to) + work = Any[mi] while !isempty(work) - m = popfirst!(work) + target = popfirst!(work) + m = target isa Core.CodeInstance ? CC.get_ci_mi(target) : target m in seen && continue push!(seen, m) - # (varargs methods are called through the runtime, for now) - m.def isa Method && m !== mi && m.def.isva && continue - ci = CC.typeinf_ext_toplevel(interp, m, CC.SOURCE_MODE_ABI) + ci = target isa Core.CodeInstance && target.inferred isa Core.CodeInfo ? target : + CC.typeinf_ext_toplevel(interp, m, CC.SOURCE_MODE_ABI) + # (inference may give the CodeInstance of another, normalized, method instance) + cm = CC.get_ci_mi(ci) + if cm !== m + cm in seen && continue + push!(seen, cm) + end src = ci.inferred if !(src isa Core.CodeInfo) # (inference keeps no source of functions with a constant result) - src = CC.typeinf_code(interp, m, true) - src isa Core.CodeInfo || unsupported("the code of ", m, ", which inference gives no source of") + src = CC.typeinf_code(interp, cm, true) + src isa Core.CodeInfo || unsupported("the code of ", cm, ", which inference gives no source of") end push!(out, ci => src) for stmt in src.code Meta.isexpr(stmt, :invoke) || continue - push!(work, invoke_target(stmt.args[1])) + push!(work, stmt.args[1]) end end return out diff --git a/test/calls.jl b/test/calls.jl index 30ec60c..cc035b6 100644 --- a/test/calls.jl +++ b/test/calls.jl @@ -15,6 +15,10 @@ c_less_specific(x::Int) = invoke(c_generic, Tuple{Number}, x) c_call_throws(x) = x > 0 ? x : c_throws(x) @noinline c_vararg(xs...) = length(xs) c_call_vararg(x) = c_vararg(x, x, x) +@noinline c_vararg2(x, xs...) = x + sum(xs) +c_call_vararg2(x) = c_vararg2(x, x, 2x) + c_vararg2(x, 1) +@noinline c_vararg_any(xs...) = map(string, xs) +c_call_vararg_any(x) = c_vararg_any(x, "s", 1.5) c_closure(x) = (y -> x + y)(3) # (a calling convention JuliaCodegen doesn't support, which native code only compiles for # x86: LLVM aborts on other targets) @@ -54,12 +58,28 @@ c_run_fallback(f, args...) = cgrun(f, args...; config=C_FALLBACK) @cgtest c_sum_found(collect(1:30)) end +@testset "varargs" begin + # the varargs in the tuple the function takes, as its IR has them + @cgtest c_call_vararg(1) + @cgtest c_call_vararg2(3) + @cgtest c_call_vararg_any(7) + @test !any(((mi, why),) -> mi.def.name in (:c_vararg, :c_vararg2), test_fallbacks(c_call_vararg2, (Int,))) + # a specialized varargs method: called directly, with the varargs in a tuple; one whose + # signature has a `Vararg` (as inference keeps two or more varargs here): through the + # runtime, with the arguments one by one + ir = test_ir(c_call_vararg2, (Int,)) + @test occursin(r"call i64 @julia_c_vararg2_\d+\(i64 %\d+, \[1 x i64\]", ir) + @test occursin("@ijl_invoke", ir) + # a varargs entry + @cgtest c_vararg2(1, 2, 3) + @cgtest c_vararg(1, "two") +end + @testset "stubs" begin # always throws: an error path, called through the runtime @cgtest c_call_throws(1) @cgtest c_call_throws(-1) @test any(((mi, why),) -> mi.def.name === :c_throws, test_fallbacks(c_call_throws, (Int,))) - # varargs methods, for now @cgtest c_call_vararg(1) # a callee with an unsupported construct calls its native code, or throws when the # configuration says so diff --git a/test/emit_into.jl b/test/emit_into.jl index fd4655c..20327ba 100644 --- a/test/emit_into.jl +++ b/test/emit_into.jl @@ -38,17 +38,18 @@ function ei_codeinfos(mi; world=Base.get_world_counter(), exclude=()) interp = EIInterp(world) out = Pair{Core.CodeInstance,Core.CodeInfo}[] seen = IdSet{Core.MethodInstance}() - work = [mi] + work = Any[mi] # (method instances, and the CodeInstances `:invoke`s refer to) while !isempty(work) - m = pop!(work) + t = pop!(work) + m = t isa Core.CodeInstance ? CC.get_ci_mi(t) : t (m in seen || m.def.name in exclude) && continue push!(seen, m) - ci = CC.typeinf_ext_toplevel(interp, m, CC.SOURCE_MODE_ABI) + ci = t isa Core.CodeInstance && t.inferred isa Core.CodeInfo ? t : + CC.typeinf_ext_toplevel(interp, m, CC.SOURCE_MODE_ABI) push!(out, ci => ci.inferred::Core.CodeInfo) for st in ci.inferred.code Meta.isexpr(st, :invoke) || continue - t = st.args[1] - push!(work, t isa Core.CodeInstance ? CC.get_ci_mi(t) : t) + push!(work, st.args[1]) end end return out diff --git a/test/jitdriver.jl b/test/jitdriver.jl index d55ccae..2e23f7b 100644 --- a/test/jitdriver.jl +++ b/test/jitdriver.jl @@ -52,7 +52,7 @@ end @test any(((mi, why),) -> mi.def.name === :jd_stdcall, jf.fallbacks) @test_throws JuliaCodegen.Unsupported jd_run(jd_call_stdcall, "four") end - # varargs callees are called through the runtime + # varargs callees @test jd_run(jd_call_vararg, 3) == 6 end From 6164275c81295b6083aed4d1952ba5421dbda4df Mon Sep 17 00:00:00 2001 From: Valentin Churavy Date: Tue, 20 Oct 2026 00:09:44 +0200 Subject: [PATCH 12/27] Debug information: the statement in the column, names of the specsig entries - The column of a statement's innermost location is the statement's index in the IR, as native code encodes it from Julia 1.14 on: GPUCompiler maps errors in the LLVM IR back to the Julia statement they come from by it. - `emit_into!` names the subprogram of a function by its specsig entry (`cgm.debug_linkage`), by which tools look up the function a location is in. Assisted-by: Claude Code (Opus 5.5) --- src/context.jl | 4 +++- src/debuginfo.jl | 10 +++++++--- src/emit_into.jl | 5 ++++- test/debuginfo.jl | 2 ++ 4 files changed, 16 insertions(+), 5 deletions(-) diff --git a/src/context.jl b/src/context.jl index 8421a0b..603ad23 100644 --- a/src/context.jl +++ b/src/context.jl @@ -61,6 +61,8 @@ mutable struct CGModule throwing_stubs::Bool "The debug information (a `DebugInfo`), created on first use." debuginfo::Any + "The linkage names of the subprograms of functions, if not the functions' names." + debug_linkage::IdDict{LLVM.Function,String} counter::Int end @@ -71,7 +73,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, nothing, 0) + throwing_stubs, nothing, IdDict{LLVM.Function,String}(), 0) end "A name that is unique in the module, from `prefix` and the function `f` (if any)." diff --git a/src/debuginfo.jl b/src/debuginfo.jl index 1b1d66b..4bba173 100644 --- a/src/debuginfo.jl +++ b/src/debuginfo.jl @@ -82,7 +82,8 @@ frame_name(@nospecialize(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 +those of the method being compiled; with the linkage name `cgm.debug_linkage[f]`, if any, +else the function's), 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) @@ -92,7 +93,7 @@ function debug_function!(fc::FnCtx, f::LLVM.Function; name=nothing, file=nothing 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)) + sp = subprogram!(di, name, file, line, get(fc.cgm.debug_linkage, f, LLVM.name(f))) f.subprogram = sp fc.subprogram = sp LLVM.debug_location!(fc.builder, LLVM.DILocation(max(Int(line), 0), 0, sp)) @@ -107,6 +108,7 @@ function statement_location!(fc::FnCtx, idx::Int) frames = Base.IRShow.buildLineInfoNode(fc.ir.debuginfo, fc.info.mi, idx) isempty(frames) && return # (keep the previous location) loc = nothing + n = length(frames) for (k, fr) in enumerate(frames) scope = if k == 1 fc.subprogram @@ -116,7 +118,9 @@ function statement_location!(fc::FnCtx, idx::Int) subprogram!(di, name, fr.file, 0) end end - loc = LLVM.DILocation(max(Int(fr.line), 0), 0, scope, loc) + # (the column of the innermost location is the statement, as native code encodes it + # from Julia 1.14 on: tools map errors in the LLVM IR back to the Julia IR by it) + loc = LLVM.DILocation(max(Int(fr.line), 0), k == n ? idx : 0, scope, loc) end LLVM.debug_location!(fc.builder, loc) end diff --git a/src/emit_into.jl b/src/emit_into.jl index d74d768..5aebaeb 100644 --- a/src/emit_into.jl +++ b/src/emit_into.jl @@ -78,7 +78,10 @@ end function emit_sources!(cgm::CGModule, codeinfos, sources) infos = Pair{Core.CodeInstance,FuncInfo}[] for (ci, _) in codeinfos - push!(infos, ci => get_function!(cgm, CC.get_ci_mi(ci))) + info = get_function!(cgm, CC.get_ci_mi(ci)) + push!(infos, ci => info) + # (debug information names a function by its specsig entry, as tools look it up) + cgm.debug_linkage[info.llvmf] = "j_" * chopprefix(LLVM.name(info.llvmf), "julia_") end process_worklist!(cgm) compiled = IdDict{Core.CodeInstance,CompiledFunctions}() diff --git a/test/debuginfo.jl b/test/debuginfo.jl index 98efc7b..5c337e7 100644 --- a/test/debuginfo.jl +++ b/test/debuginfo.jl @@ -34,6 +34,8 @@ 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) + # the innermost location's column is the statement (as native code from Julia 1.14 on) + @test occursin(r"!DILocation\(line: \d+, column: [1-9]\d*, scope: ", ir) # every function has a subprogram, entries included @test count("distinct !DISubprogram(name: \"d_outer\"", ir) == 2 # without, none From fc3de4943e55d7b66a3902e21624c682dfbac9f9 Mon Sep 17 00:00:00 2001 From: Valentin Churavy Date: Tue, 20 Oct 2026 00:13:21 +0200 Subject: [PATCH 13/27] Debug information: the statement in the column only from Julia 1.14 on, as native code Assisted-by: Claude Code (Opus 5.5) --- src/debuginfo.jl | 7 ++++--- test/debuginfo.jl | 5 +++-- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/src/debuginfo.jl b/src/debuginfo.jl index 4bba173..f62fabc 100644 --- a/src/debuginfo.jl +++ b/src/debuginfo.jl @@ -118,9 +118,10 @@ function statement_location!(fc::FnCtx, idx::Int) subprogram!(di, name, fr.file, 0) end end - # (the column of the innermost location is the statement, as native code encodes it - # from Julia 1.14 on: tools map errors in the LLVM IR back to the Julia IR by it) - loc = LLVM.DILocation(max(Int(fr.line), 0), k == n ? idx : 0, scope, loc) + # (from Julia 1.14 on, the column of the innermost location is the statement, as + # native code encodes it: tools map errors in the LLVM IR back to the Julia IR by it) + col = k == n && config(fc).dialect.minor >= v"1.14" ? idx : 0 + loc = LLVM.DILocation(max(Int(fr.line), 0), col, scope, loc) end LLVM.debug_location!(fc.builder, loc) end diff --git a/test/debuginfo.jl b/test/debuginfo.jl index 5c337e7..585a2cf 100644 --- a/test/debuginfo.jl +++ b/test/debuginfo.jl @@ -34,8 +34,9 @@ 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) - # the innermost location's column is the statement (as native code from Julia 1.14 on) - @test occursin(r"!DILocation\(line: \d+, column: [1-9]\d*, scope: ", ir) + # the innermost location's column is the statement, as native code from Julia 1.14 on + @test occursin(r"!DILocation\(line: \d+, column: [1-9]\d*, scope: ", ir) == + (D_CONFIG.dialect.minor >= v"1.14") # every function has a subprogram, entries included @test count("distinct !DISubprogram(name: \"d_outer\"", ir) == 2 # without, none From 196afc7a50d0a2b5e3084023c2e282bddf8f5e8d Mon Sep 17 00:00:00 2001 From: Valentin Churavy Date: Tue, 20 Oct 2026 00:21:25 +0200 Subject: [PATCH 14/27] specsig: varargs methods, with their arguments one by one The specsig entry of a varargs method instance whose signature doesn't end in `Vararg` takes its arguments one by one, as native code declares it, and packs the varargs for the function. Signatures ending in `Vararg` are called in the jlcall convention, as native code does. GPU kernels with varargs (`kernel(args...)`) get their entry. Assisted-by: Claude Code (Opus 5.5) --- src/specsig.jl | 31 +++++++++++++++++++++++-------- test/specsig.jl | 12 +++++++++++- 2 files changed, 34 insertions(+), 9 deletions(-) diff --git a/src/specsig.jl b/src/specsig.jl index 9e4c72f..7ba2291 100644 --- a/src/specsig.jl +++ b/src/specsig.jl @@ -140,13 +140,19 @@ end The entry of the function `info` in the specsig convention (see [`specsig_abi`](@ref JuliaCodegen.specsig_abi)), named `name`, which natively compiled -code can call directly. Throws `Unsupported` for signatures it doesn't handle, and for -varargs methods, which native code calls in the jlcall convention. +code can call directly. A varargs method takes its arguments one by one, as native code +passes them. Throws `Unsupported` for signatures it doesn't handle, and for signatures +ending in `Vararg`, which native code calls in the jlcall convention. """ function emit_specsig_wrapper!(cgm::CGModule, info::FuncInfo, name::AbstractString) m = info.mi.def - m isa Method && m.isva && unsupported("the specsig convention for the varargs method ", m) - sig = specsig_abi(cgm, info.argtypes, info.rettype) + isva = m isa Method && m.isva + # (a varargs method takes its arguments one by one, as native code passes them, in a + # signature without `Vararg`; others are called in the jlcall convention) + argtypes = isva ? signature_argtypes(info.mi) : info.argtypes + isva && any(T -> T isa Core.TypeofVararg, argtypes) && + unsupported("the specsig convention for the varargs signature of ", info.mi) + sig = specsig_abi(cgm, argtypes, info.rettype) f = LLVM.Function(cgm.mod, String(name), sig.ft) sig.gcstack && LLVM.callconv!(f, LLVM.API.LLVMSwiftCallConv) init_function!(f, cgm.config.target) @@ -162,9 +168,12 @@ function emit_specsig_wrapper!(cgm::CGModule, info::FuncInfo, name::AbstractStri fc.pgcstack = ps[p] p += 1 end - ops = LLVM.Value[] - for (T, k) in zip(info.argtypes, sig.args) - k === nothing && continue + args = CGVal[] + for (T, k) in zip(argtypes, sig.args) + if k === nothing + push!(args, ghost(T, something(ghost_value(T)))) + continue + end v = ps[p] p += 1 cv = if k === SpecByRef @@ -174,7 +183,13 @@ function emit_specsig_wrapper!(cgm::CGModule, info::FuncInfo, name::AbstractStri else CGVal(T, k === SpecBoxed ? Boxed : Inline, v, nothing, nothing) end - push!(ops, convert_repr(fc, cv, T).V) + push!(args, cv) + end + isva && (args = pack_varargs(fc, info.mi, args)) + ops = LLVM.Value[] + for (a, T) in zip(args, info.argtypes) + repr_kind(T) === Ghost && continue + push!(ops, convert_repr(fc, a, T).V) end r = LLVM.call!(b, LLVM.function_type(info.llvmf), info.llvmf, ops) # (the entry is the function, as native code's: inlined by any pipeline) diff --git a/test/specsig.jl b/test/specsig.jl index e3d3c7c..8575b97 100644 --- a/test/specsig.jl +++ b/test/specsig.jl @@ -22,6 +22,7 @@ ss_box(x::Int) = Ref(x) ss_throw(x) = throw(ArgumentError("ss_throw $x")) ss_vec(v::SS_V4) = map(x -> VecElement(x.value * 2f0), v) @noinline ss_vararg(xs...) = length(xs) +ss_vararg2(a, xs...) = a + sum(xs) # The first function definition's header in native code for `f(::types...)`, without # names: the convention, the result and the parameters with their attributes. @@ -119,6 +120,8 @@ const SS_CASES = [ (ss_mix, (Int8, Bool, UInt16, Float32, SS_Pair, Nothing, String)), (ss_fst, (Int, SS_Empty)), (ss_dup, (Int,)), (ss_widen, (Int64,)), (ss_maybe, (Union{Nothing,Int},)), (ss_box, (Int,)), (ss_throw, (Int,)), (ss_vec, (SS_V4,)), + # (varargs methods, with their arguments one by one) + (ss_vararg2, (Int, Float64, Int8)), ] @testset "specsig" begin @@ -147,7 +150,14 @@ end # their payload separately @test_throws JuliaCodegen.Unsupported specsig_header(ss_id, (SS_Ref,)) @test_throws JuliaCodegen.Unsupported specsig_header(ss_id, (Union{Nothing,Int},)) - @test_throws JuliaCodegen.Unsupported specsig_header(ss_vararg, (Int, Int)) + # (a signature that ends in `Vararg`: the jlcall convention) + @dispose ctx=LLVM.Context() mod=LLVM.Module("x") begin + cgm = JuliaCodegen.CGModule(mod, test_config()) + m = only(methods(ss_vararg)) + mi = Base.Compiler.specialize_method(m, Tuple{typeof(ss_vararg), Vararg{Int}}, Core.svec()) + info = JuliaCodegen.get_function!(cgm, mi) + @test_throws JuliaCodegen.Unsupported JuliaCodegen.emit_specsig_wrapper!(cgm, info, "x") + end end @testset "calls through the convention" begin From af9c54f8a6e045b5c4ac2ac73dab26afbbd0622d Mon Sep 17 00:00:00 2001 From: Valentin Churavy Date: Tue, 20 Oct 2026 00:32:03 +0200 Subject: [PATCH 15/27] emit_into!: the jlcall entry calls the specsig entry, as native code's With a specsig entry, the jlcall entry unboxes its arguments and calls it, instead of inlining the function, as native code's jfptr_f_N calls julia_f_N: GPUCompiler's slow ABI (entry_abi=:func) looks for that call. Assisted-by: Claude Code (Opus 5.5) --- src/emit_into.jl | 9 +++++---- src/function.jl | 17 ++++++++++++++--- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/src/emit_into.jl b/src/emit_into.jl index 5aebaeb..663707a 100644 --- a/src/emit_into.jl +++ b/src/emit_into.jl @@ -90,15 +90,16 @@ function emit_sources!(cgm::CGModule, codeinfos, sources) # call), its entries `j_f_N` in the specsig convention (the prefix of native code's # specsig wrappers) and `jfptr_f_N` in the jlcall one base = chopprefix(LLVM.name(info.llvmf), "julia_") - func = emit_jlcall_wrapper!(cgm, info, "jfptr_" * base) - push!(cgm.entries, Entry(info.mi, LLVM.name(func), :jlcall)) specfunc = try - LLVM.name(emit_specsig_wrapper!(cgm, info, "j_" * base)) + emit_specsig_wrapper!(cgm, info, "j_" * base) catch err err isa Unsupported || rethrow() nothing end - compiled[ci] = CompiledFunctions(LLVM.name(func), specfunc) + # (which calls the specsig entry, as native code's) + func = emit_jlcall_wrapper!(cgm, info, "jfptr_" * base; specfunc) + push!(cgm.entries, Entry(info.mi, LLVM.name(func), :jlcall)) + compiled[ci] = CompiledFunctions(LLVM.name(func), specfunc === nothing ? nothing : LLVM.name(specfunc)) end return compiled, codegen_output(cgm) end diff --git a/src/function.jl b/src/function.jl index a3447d1..e9aa232 100644 --- a/src/function.jl +++ b/src/function.jl @@ -328,13 +328,16 @@ end ## the jlcall entry """ - JuliaCodegen.emit_jlcall_wrapper!(cgm, info, name) -> LLVM.Function + JuliaCodegen.emit_jlcall_wrapper!(cgm, info, name; specfunc=nothing) -> LLVM.Function The entry of the function `info` in the jlcall convention, `jl_value_t *name(jl_value_t *F, jl_value_t **args, uint32_t nargs)`: it unboxes the arguments, calls the function, -and boxes the result. +and boxes the result. With `specfunc`, the function's entry in the specsig convention +(see [`emit_specsig_wrapper!`](@ref JuliaCodegen.emit_specsig_wrapper!)), it calls that, +as native code's jlcall entries call their specsig functions. """ -function emit_jlcall_wrapper!(cgm::CGModule, info::FuncInfo, name::AbstractString) +function emit_jlcall_wrapper!(cgm::CGModule, info::FuncInfo, name::AbstractString; + specfunc::Union{Nothing,LLVM.Function}=nothing) ft = LLVM.FunctionType(T_tracked(), [T_tracked(), T_ptr(), LLVM.Int32Type()]) f = LLVM.Function(cgm.mod, String(name), ft) init_function!(f, cgm.config.target) @@ -371,6 +374,14 @@ function emit_jlcall_wrapper!(cgm::CGModule, info::FuncInfo, name::AbstractStrin end push!(args, convert_repr(fc, boxed(Any, p), T)) end + if specfunc !== nothing + # (which takes the arguments of a varargs method one by one) + sig = specsig_abi(cgm, sig, info.rettype) + r = emit_specsig_call!(fc, sig, specfunc, args) + # (after a call that doesn't return, in a block that is never reached) + repr_kind(info.rettype) === Bottom ? LLVM.unreachable!(b) : LLVM.ret!(b, emit_box(fc, r)) + return f + end if packed !== nothing push!(args, packed) elseif m isa Method && m.isva From 888e9121af740025c8a8bb50acc10a4e72832b10 Mon Sep 17 00:00:00 2001 From: Valentin Churavy Date: Tue, 20 Oct 2026 00:46:39 +0200 Subject: [PATCH 16/27] getfield with an index known only at run time As native code's emit_getfield_unknownidx: of the elements of an inline tuple of a single type (extracted from a vector, selected among a few, or loaded from memory: a constant from a private global, which GPU back ends place in constant memory), and of objects whose fields are all references or all of a single type, with the bounds check of the boundscheck argument. These were calls of the runtime's getfield. Assisted-by: Claude Code (Opus 5.5) --- src/builtins.jl | 103 ++++++++++++++++++++++++++++++++++++++++++++++- test/builtins.jl | 28 ++++++++++++- 2 files changed, 129 insertions(+), 2 deletions(-) diff --git a/src/builtins.jl b/src/builtins.jl index 9fb2952..eba7b82 100644 --- a/src/builtins.jl +++ b/src/builtins.jl @@ -393,7 +393,18 @@ function emit_getfield(fc::FnCtx, args::Vector{CGVal}, @nospecialize(rt)) T = x.typ (T isa DataType && isconcretetype(T)) || return nothing i = field_index(T, args[2]) - i === nothing && return nothing + if i === nothing + (args[2].typ === Int && args[2].kind === Inline && !isconstant(args[2])) || return nothing + bc = const_value(fc, true) + for a in args[3:end] + if a.typ === Bool + bc = a + elseif !(isconstant(a) && constant_value(a) === :not_atomic) + return nothing + end + end + return emit_getfield_unknownidx(fc, x, T, args[2], bc, rt) + end # an explicit order: the plain access of a non-atomic field, or the atomic load of an # atomic one (mismatches are the runtime's ConcurrencyViolationError) order = :not_atomic @@ -446,6 +457,96 @@ function emit_getfield(fc::FnCtx, args::Vector{CGVal}, @nospecialize(rt)) return nothing end +# `getfield(x, i)` of the field whose index `i` (an `Int`) is only known at run time, +# with the bounds check of the boundscheck argument `bc` (native code's +# `emit_getfield_unknownidx`): of the fields of an inline tuple of a single type, or of an +# object whose fields are all references or all of a single type +function emit_getfield_unknownidx(fc::FnCtx, x::CGVal, @nospecialize(T), idx::CGVal, bc::CGVal, + @nospecialize(rt)) + n = fieldcount(T) + n == 0 && return nothing + b = fc.builder + types = fieldtypes(T) + FT = types[1] + same = all(t -> t === FT, types) + if n == 1 + lowered = fc -> emit_getfield(fc, CGVal[x, const_value(fc, 1)], rt) + elseif x.kind === Ghost || (same && repr_kind(FT) === Ghost) + same || return nothing + lowered = fc -> convert_repr(fc, ghost(FT, something(ghost_value(FT))), rt) + elseif x.kind === Inline + lay = layout(fc, T) + (same && (lay.llvm isa LLVM.ArrayType || lay.llvm isa LLVM.VectorType)) || return nothing + lowered = fc -> begin + v = inline_element(fc, x, lay, FT, n, idx) + convert_repr(fc, field_storage(FT) === FieldPointer ? boxed(FT, v) : inline(FT, v), rt) + end + elseif x.kind === Boxed + ismutabletype(T) && T.name.atomicfields != C_NULL && return nothing + storage = [field_storage(T, i) for i in 1:n] + if all(==(FieldPointer), storage) + lowered = fc -> begin + p = LLVM.inbounds_gep!(b, T_tracked(), derived(fc, x.V), [LLVM.sub!(b, idx.V, iptr(fc, 1))]) + v = tbaa!(fc, LLVM.load!(b, T_tracked(), p; align=config(fc).target.pointer_size), field_tbaa(fc, T)) + any(i -> maybe_undef_field(T, i), 1:n) && undef_check!(fc, v) + convert_repr(fc, boxed(Union{types...}, v), rt) + end + elseif same && all(==(FieldInline), storage) && + !(has_references(FT) && any(i -> maybe_undef_field(T, i), 1:n)) + stride = fieldoffset(T, 2) - fieldoffset(T, 1) + lowered = fc -> begin + off = LLVM.mul!(b, LLVM.sub!(b, idx.V, iptr(fc, 1)), iptr(fc, stride)) + p = LLVM.inbounds_gep!(b, LLVM.Int8Type(), derived(fc, x.V), [off]) + v = LLVM.load!(b, value_type(fc, FT), p; align=field_alignment(fc, T, FT)) + convert_repr(fc, inline(FT, tbaa!(fc, v, field_tbaa(fc, T))), rt) + end + else + return nothing + end + else + return nothing + end + bounds_check!(fc, LLVM.sub!(b, idx.V, iptr(fc, 1)), iptr(fc, n), bc, x, idx) + return lowered(fc) +end + +# the element `idx` (1-based, in bounds) of the inline homogeneous tuple `x` with the +# layout `lay` (an LLVM array or vector of `n` elements of type `FT`, or of references to +# them): extracted from a vector, selected among a few elements or ones with references, +# or loaded from memory +# (for a constant, a private global, as native code's `value_to_pointer`) +function inline_element(fc::FnCtx, x::CGVal, lay::Layout, @nospecialize(FT), n::Int, idx::CGVal) + b = fc.builder + i0 = LLVM.sub!(b, idx.V, iptr(fc, 1)) + if lay.llvm isa LLVM.VectorType + return LLVM.extract_element!(b, x.V, LLVM.trunc!(b, i0, LLVM.Int32Type())) + elseif n <= 3 || field_storage(FT) === FieldPointer || has_references(FT) + v = LLVM.extract_value!(b, x.V, 0) + for i in 1:n-1 + c = LLVM.icmp!(b, LLVM.API.LLVMIntEQ, i0, iptr(fc, i)) + v = LLVM.select!(b, c, LLVM.extract_value!(b, x.V, i), v) + end + return v + end + align = Base.datatype_alignment(x.typ) + if isconstant(x) && x.V isa LLVM.Constant + mem = LLVM.GlobalVariable(fc.cgm.mod, lay.llvm, unique_name(fc.cgm, "_j_const")) + LLVM.initializer!(mem, x.V) + LLVM.constant!(mem, true) + LLVM.linkage!(mem, LLVM.API.LLVMPrivateLinkage) + LLVM.unnamed_addr!(mem, LLVM.API.LLVMGlobalUnnamedAddr) + LLVM.alignment!(mem, align) + tb = :const + else + mem = entry_alloca!(fc, lay.llvm; align) + tbaa!(fc, LLVM.store!(b, x.V, mem), :stack) + tb = :stack + end + et = LLVM.element_type(lay.llvm) + p = LLVM.inbounds_gep!(b, et, mem, [i0]) + return tbaa!(fc, LLVM.load!(b, et, p; align=Base.datatype_alignment(FT)), tb) +end + # `setfield!(x, f, v, [order])` of a non-atomic field function emit_setfield!(fc::FnCtx, args::Vector{CGVal}) length(args) in (3, 4) || return nothing diff --git a/test/builtins.jl b/test/builtins.jl index 9954d79..059a322 100644 --- a/test/builtins.jl +++ b/test/builtins.jl @@ -40,6 +40,10 @@ b_getglobal() = Core.getglobal(Base, :pi) b_namedtuple(nt) = (nt.a, nt.b) b_const_field(c::BConst) = (c.c, c.v) b_tuple_index(t) = (t[1], t[2]) +b_dynamic_index(t, i) = t[i] +b_dynamic_inbounds(t, i) = @inbounds t[i] +b_dynamic_const(i) = @inbounds (1.0f0, 2.0f0, 3.0f0, 4.0f0)[i] +b_dynamic_field(m, i) = getfield(m, i) const B_EGAL_PAIRS = Any[ (1, 1), (1, 2), (1, 1.0), (NaN, NaN), (0.0, -0.0), (1.0f0, 1.0f0), (true, true), (true, false), @@ -110,6 +114,19 @@ end @cgtest b_namedtuple((a=1, b="b")) @cgtest b_const_field(BConst(1, 2)) @cgtest b_tuple_index((1, "a", 2.0)) + # fields whose index is only known at run time + for t in Any[(1, 2), (1.0f0, 2.0f0, 3.0f0, 4.0f0, 5.0f0), ("a", "b", "c", "d"), ("a", :b, 3), + (BPoint(1, 2), BPoint(3, 4), BPoint(5, 6), BPoint(7, 8)), + ntuple(i -> VecElement(Float32(i)), 4), (nothing, nothing), (7,)], + i in (1, 2, 0, length(t) + 1) # (out of bounds: BoundsError) + @cgtest b_dynamic_index(t, i) + 1 <= i <= length(t) && @cgtest b_dynamic_inbounds(t, i) + end + @cgtest b_dynamic_const(3) + @cgtest b_dynamic_field(BPoint(1, 2), 2) + @cgtest b_dynamic_field(BMutable(1, "a", BRef(2, "b")), 2) + @cgtest b_dynamic_field(BPartial(3), 2) # UndefRefError + @cgtest b_dynamic_field(BPartial(3), 3) # BoundsError # the write barrier: young objects stored into an old one survive collections old = BMutable(0, nothing, BRef(0, "")) GC.gc(); GC.gc() @@ -141,7 +158,9 @@ end for (f, types) in ((b_fields, (BPoint,)), (b_new_point, (Float64, Float64)), (b_new_mutable, (Int, Any, BRef)), (b_mutable_set!, (BMutable, Int, Any, BRef)), (b_egal, (BPoint, BPoint)), (b_egal, (Symbol, Symbol)), - (b_isa_int, (Int,)), (b_tuple, (Int, String)), (b_sizeof, (String,))) + (b_isa_int, (Int,)), (b_tuple, (Int, String)), (b_sizeof, (String,)), + (b_dynamic_inbounds, (NTuple{2,Int}, Int)), (b_dynamic_inbounds, (NTuple{4,Float32}, Int)), + (b_dynamic_inbounds, (NTuple{4,String}, Int))) @test @filecheck begin @check_not "julia.call" print(test_ir(f, types)) @@ -160,6 +179,13 @@ end print(ir) end end + # a constant tuple indexed at run time is loaded from a constant global, as native + # code's (which GPU back ends place in constant memory) + @test @filecheck begin + @check "@_j_const{{.*}} = private unnamed_addr constant [4 x float]" + @check "load float, ptr" + print(test_ir(b_dynamic_const, (Int,))) + end # the box of an object is compared by the runtime only if it isn't identical @test @filecheck begin @check "icmp ne ptr addrspace(10)" From 3a97301f6540910b9961be885eb9ccba9d938ee1 Mon Sep 17 00:00:00 2001 From: Valentin Churavy Date: Tue, 20 Oct 2026 01:19:03 +0200 Subject: [PATCH 17/27] Inline aggregates by reference, as native code's specsig convention Functions take inline aggregates without references by reference to memory that doesn't change (ptr addrspace(11), readonly), as native code's specsig functions, and values keep the memory they were loaded from (a reference argument, an immutable box): calls pass that on rather than copying the value to the stack, and getfield with an index known at run time reads the element where it is. GPUCompiler's back ends then index kernel arguments in place. Assisted-by: Claude Code (Opus 5.5) --- src/boxing.jl | 6 ++-- src/builtins.jl | 19 ++++------- src/context.jl | 5 +-- src/function.jl | 85 ++++++++++++++++++++++++++++++++++++++++-------- src/specsig.jl | 15 ++------- src/values.jl | 14 +++++--- test/builtins.jl | 22 +++++++++++-- test/calls.jl | 2 +- 8 files changed, 118 insertions(+), 50 deletions(-) diff --git a/src/boxing.jl b/src/boxing.jl index c34218d..7a8ef88 100644 --- a/src/boxing.jl +++ b/src/boxing.jl @@ -101,10 +101,12 @@ function convert_repr(fc::FnCtx, v::CGVal, @nospecialize T) v.typ === T && return v # the value is known to be of type T, so representations agree value_type(fc, v.typ) == value_type(fc, T) && - return CGVal(T, Inline, v.V, v.constant, v.vboxed) + return CGVal(T, Inline, v.V, v.constant, v.vboxed, v.mem) unsupported("converting the inline ", v.typ, " to ", T) elseif v.kind === Boxed - return inline(T, emit_unbox(fc, v.V, T); constant=v.constant) + # (an immutable object: its contents never change) + mem = byref(fc.cgm, T) ? derived(fc, v.V) : nothing + return inline(T, emit_unbox(fc, v.V, T); constant=v.constant, mem) end unsupported("converting the ghost ", v.typ, " to the inline ", T) end diff --git a/src/builtins.jl b/src/builtins.jl index eba7b82..54d9d4e 100644 --- a/src/builtins.jl +++ b/src/builtins.jl @@ -513,8 +513,8 @@ end # the element `idx` (1-based, in bounds) of the inline homogeneous tuple `x` with the # layout `lay` (an LLVM array or vector of `n` elements of type `FT`, or of references to # them): extracted from a vector, selected among a few elements or ones with references, -# or loaded from memory -# (for a constant, a private global, as native code's `value_to_pointer`) +# or loaded from memory (the memory it was loaded from; for a constant, a private global, +# as native code's `value_to_pointer`; or a stack slot) function inline_element(fc::FnCtx, x::CGVal, lay::Layout, @nospecialize(FT), n::Int, idx::CGVal) b = fc.builder i0 = LLVM.sub!(b, idx.V, iptr(fc, 1)) @@ -529,18 +529,13 @@ function inline_element(fc::FnCtx, x::CGVal, lay::Layout, @nospecialize(FT), n:: return v end align = Base.datatype_alignment(x.typ) - if isconstant(x) && x.V isa LLVM.Constant - mem = LLVM.GlobalVariable(fc.cgm.mod, lay.llvm, unique_name(fc.cgm, "_j_const")) - LLVM.initializer!(mem, x.V) - LLVM.constant!(mem, true) - LLVM.linkage!(mem, LLVM.API.LLVMPrivateLinkage) - LLVM.unnamed_addr!(mem, LLVM.API.LLVMGlobalUnnamedAddr) - LLVM.alignment!(mem, align) - tb = :const + if x.mem !== nothing + mem, tb = x.mem, :const + elseif isconstant(x) && x.V isa LLVM.Constant + mem, tb = constant_memory!(fc.cgm, x.V, align), :const else - mem = entry_alloca!(fc, lay.llvm; align) + mem, tb = entry_alloca!(fc, lay.llvm; align), :stack tbaa!(fc, LLVM.store!(b, x.V, mem), :stack) - tb = :stack end et = LLVM.element_type(lay.llvm) p = LLVM.inbounds_gep!(b, et, mem, [i0]) diff --git a/src/context.jl b/src/context.jl index 603ad23..5185704 100644 --- a/src/context.jl +++ b/src/context.jl @@ -5,8 +5,9 @@ An LLVM function emitted for a `MethodInstance`, in JuliaCodegen's internal calling convention: ghost arguments are dropped, the others are passed in their representation -(inline values by value, boxed ones as tracked pointers, unboxed unions as their union -type), and the result is returned in the representation of the inferred return type +(inline values by value, but aggregates without references by reference to memory that +doesn't change, `ptr addrspace(11)`, as native code's specsig convention; boxed ones as +tracked pointers, unboxed unions as their union type), and the result is returned in the representation of the inferred return type (`void` for ghosts and `Union{}`). """ struct FuncInfo diff --git a/src/function.jl b/src/function.jl index e9aa232..f8f281c 100644 --- a/src/function.jl +++ b/src/function.jl @@ -31,14 +31,25 @@ Declare the function of `mi` in JuliaCodegen's internal convention (see function declare_function!(cgm::CGModule, mi::Core.MethodInstance, argtypes::Vector{Any}, @nospecialize(rettype)) params = LLVM.LLVMType[] + attrs = Vector{LLVM.Attribute}[] for T in argtypes t = value_type(cgm.layouts, T) - t === nothing || push!(params, t) + t === nothing && continue + if byref(cgm, T) + push!(params, T_derived()) + push!(attrs, LLVM.Attribute[attr("readonly"), ref_attributes(T)...]) + else + push!(params, t) + push!(attrs, LLVM.Attribute[]) + end end ret = something(value_type(cgm.layouts, rettype), LLVM.VoidType()) f = mi.def isa Method ? mi.specTypes.parameters[1] : nothing fobj = f isa DataType && isdefined(f, :instance) ? f.instance : nothing llvmf = LLVM.Function(cgm.mod, unique_name(cgm, "julia", fobj), LLVM.FunctionType(ret, params)) + for (i, as) in enumerate(attrs), a in as + push!(LLVM.parameter_attributes(llvmf)[i], a) + end LLVM.linkage!(llvmf, LLVM.API.LLVMInternalLinkage) init_function!(llvmf, cgm.config.target) rettype === Union{} && push!(llvmf.function_attributes, LLVM.EnumAttribute("noreturn")) @@ -47,6 +58,61 @@ function declare_function!(cgm::CGModule, mi::Core.MethodInstance, argtypes::Vec return info end +""" + JuliaCodegen.byref(cgm, T) -> Bool + +Whether functions take arguments of the inline type `T` by reference (see +[`FuncInfo`](@ref JuliaCodegen.FuncInfo)): aggregates without references. +""" +byref(cgm::CGModule, @nospecialize(T)) = + repr_kind(T) === Inline && !has_references(T) && is_aggregate(layout(cgm.layouts, T).llvm) + +# the operand that passes the inline value `v` of type `T` by reference: the memory it +# was loaded from, a constant global for a constant, or a stack slot +function byref_operand(fc::FnCtx, v::CGVal, @nospecialize(T)) + v.mem === nothing || return derived(fc, v.mem) + lay = layout(fc, T) + mem = if isconstant(v) && v.V isa LLVM.Constant + constant_memory!(fc.cgm, v.V, Base.datatype_alignment(T)) + else + slot = entry_alloca!(fc, lay.llvm; align=Base.datatype_alignment(T)) + st = LLVM.store!(fc.builder, v.V, slot) + LLVM.alignment!(st, Base.datatype_alignment(T)) + tbaa!(fc, st, :stack) + slot + end + return derived(fc, mem) +end + +# a private constant global with the value `c` (native code's `get_pointer_to_constant`) +function constant_memory!(cgm::CGModule, c::LLVM.Constant, align::Integer) + gv = LLVM.GlobalVariable(cgm.mod, LLVM.value_type(c), unique_name(cgm, "_j_const")) + LLVM.initializer!(gv, c) + LLVM.constant!(gv, true) + LLVM.linkage!(gv, LLVM.API.LLVMPrivateLinkage) + LLVM.unnamed_addr!(gv, LLVM.API.LLVMGlobalUnnamedAddr) + LLVM.alignment!(gv, align) + return gv +end + +# the operands of a call of the function `info` with the values `args` +function call_operands(fc::FnCtx, info::FuncInfo, args::Vector{CGVal}) + ops = LLVM.Value[] + for (a, T) in zip(args, info.argtypes) + v = convert_repr(fc, a, T) + v.kind === Ghost && continue + push!(ops, byref(fc.cgm, T) ? byref_operand(fc, v, T) : v.V) + end + return ops +end + +# a reference argument of type `T`: its value, loaded, and the memory +function byref_argument(fc::FnCtx, @nospecialize(T), p::LLVM.Value) + ld = LLVM.load!(fc.builder, layout(fc, T).llvm, p) + LLVM.alignment!(ld, Base.datatype_alignment(T)) + return inline(T, tbaa!(fc, ld, :const); mem=p) +end + "The Julia argument types of the function of `mi`, from its signature." signature_argtypes(mi::Core.MethodInstance) = Any[Base.unwrap_unionall(mi.specTypes).parameters...] @@ -120,7 +186,8 @@ function bind_arguments!(fc::FnCtx) if repr_kind(T) === Ghost push!(fc.args, ghost(T, something(ghost_value(T)))) else - push!(fc.args, CGVal(T, repr_kind(T), params[p], nothing, nothing)) + push!(fc.args, byref(fc.cgm, T) ? byref_argument(fc, T, params[p]) : + CGVal(T, repr_kind(T), params[p], nothing, nothing)) p += 1 end end @@ -387,12 +454,7 @@ function emit_jlcall_wrapper!(cgm::CGModule, info::FuncInfo, name::AbstractStrin elseif m isa Method && m.isva args = pack_varargs(fc, info.mi, args) end - ops = LLVM.Value[] - for (a, T) in zip(args, info.argtypes) - repr_kind(T) === Ghost && continue - push!(ops, convert_repr(fc, a, T).V) - end - r = LLVM.call!(b, LLVM.function_type(info.llvmf), info.llvmf, ops) + r = LLVM.call!(b, LLVM.function_type(info.llvmf), info.llvmf, call_operands(fc, info, args)) # (the entry is the function, as native code's: inlined by any pipeline) push!(LLVM.function_attributes(r), LLVM.EnumAttribute("alwaysinline")) rt = info.rettype @@ -528,12 +590,7 @@ end Call the function `info` with the values `args` (converted to its argument types). """ function emit_call_info(fc::FnCtx, info::FuncInfo, args::Vector{CGVal}) - ops = LLVM.Value[] - for (a, T) in zip(args, info.argtypes) - v = convert_repr(fc, a, T) - v.kind === Ghost || push!(ops, v.V) - end - r = LLVM.call!(fc.builder, LLVM.function_type(info.llvmf), info.llvmf, ops) + r = LLVM.call!(fc.builder, LLVM.function_type(info.llvmf), info.llvmf, call_operands(fc, info, args)) rt = info.rettype k = repr_kind(rt) k === Bottom && return emit_unreachable!(fc) diff --git a/src/specsig.jl b/src/specsig.jl index 7ba2291..8791dfe 100644 --- a/src/specsig.jl +++ b/src/specsig.jl @@ -177,21 +177,14 @@ function emit_specsig_wrapper!(cgm::CGModule, info::FuncInfo, name::AbstractStri v = ps[p] p += 1 cv = if k === SpecByRef - ld = LLVM.load!(b, layout(fc, T).llvm, v) - LLVM.alignment!(ld, Base.datatype_alignment(T)) - inline(T, tbaa!(fc, ld, :const)) + byref_argument(fc, T, v) else CGVal(T, k === SpecBoxed ? Boxed : Inline, v, nothing, nothing) end push!(args, cv) end isva && (args = pack_varargs(fc, info.mi, args)) - ops = LLVM.Value[] - for (a, T) in zip(args, info.argtypes) - repr_kind(T) === Ghost && continue - push!(ops, convert_repr(fc, a, T).V) - end - r = LLVM.call!(b, LLVM.function_type(info.llvmf), info.llvmf, ops) + r = LLVM.call!(b, LLVM.function_type(info.llvmf), info.llvmf, call_operands(fc, info, args)) # (the entry is the function, as native code's: inlined by any pipeline) push!(LLVM.function_attributes(r), LLVM.EnumAttribute("alwaysinline")) if sig.ret === :sret @@ -234,9 +227,7 @@ function emit_specsig_call!(fc::FnCtx, sig::SpecSig, callee::LLVM.Value, args::V elseif k === SpecValue push!(ops, convert_repr(fc, a, T).V) else - arg = entry_alloca!(fc, layout(fc, T).llvm; align=Base.datatype_alignment(T)) - tbaa!(fc, LLVM.store!(b, convert_repr(fc, a, T).V, arg), :stack) - push!(ops, LLVM.addrspacecast!(b, arg, T_derived())) + push!(ops, byref_operand(fc, convert_repr(fc, a, T), T)) end end r = LLVM.call!(b, sig.ft, callee, ops) diff --git a/src/values.jl b/src/values.jl index b9e3e7e..d5e45e5 100644 --- a/src/values.jl +++ b/src/values.jl @@ -8,7 +8,9 @@ A value in generated code: its Julia type `typ` (widened), its representation `k (see [`Repr`](@ref JuliaCodegen.Repr)), the LLVM value `V` (`nothing` for ghosts and `Bottom`), the value itself when it is known at compile time (`constant`), and for inline values that may also exist as a box (null at run time if not), that box (`vboxed`, -native `Vboxed`), which boxing the value again reuses. +native `Vboxed`), which boxing the value again reuses, and for inline values loaded from +memory that never changes (a reference argument, a box), a pointer to it (`mem`), which +calls pass by reference and dynamic indices index. Use the constructors [`ghost`](@ref JuliaCodegen.ghost), [`inline`](@ref JuliaCodegen.inline), [`boxed`](@ref JuliaCodegen.boxed), [`unboxed_union`](@ref @@ -20,8 +22,12 @@ struct CGVal V::Union{Nothing,LLVM.Value} constant::Union{Nothing,Some{Any}} vboxed::Union{Nothing,LLVM.Value} + mem::Union{Nothing,LLVM.Value} end +CGVal(@nospecialize(typ), kind::Repr, V, constant, vboxed) = + CGVal(typ, kind, V, constant, vboxed, nothing) + "The ghost value `v` of type `T`." ghost(@nospecialize(T), @nospecialize(v)) = CGVal(T, Ghost, nothing, Some{Any}(v), nothing) @@ -29,14 +35,14 @@ ghost(@nospecialize(T), @nospecialize(v)) = CGVal(T, Ghost, nothing, Some{Any}(v bottom() = CGVal(Union{}, Bottom, nothing, nothing, nothing) """ - inline(T, V; constant, vboxed) + inline(T, V; constant, vboxed, mem) An inline value of type `T`, the LLVM value `V` of its layout. """ function inline(@nospecialize(T), V::LLVM.Value; constant::Union{Nothing,Some}=nothing, - vboxed::Union{Nothing,LLVM.Value}=nothing) + vboxed::Union{Nothing,LLVM.Value}=nothing, mem::Union{Nothing,LLVM.Value}=nothing) return CGVal(T, Inline, V, constant === nothing ? nothing : Some{Any}(something(constant)), - vboxed) + vboxed, mem) end """ diff --git a/test/builtins.jl b/test/builtins.jl index 059a322..a273a6d 100644 --- a/test/builtins.jl +++ b/test/builtins.jl @@ -158,14 +158,30 @@ end for (f, types) in ((b_fields, (BPoint,)), (b_new_point, (Float64, Float64)), (b_new_mutable, (Int, Any, BRef)), (b_mutable_set!, (BMutable, Int, Any, BRef)), (b_egal, (BPoint, BPoint)), (b_egal, (Symbol, Symbol)), - (b_isa_int, (Int,)), (b_tuple, (Int, String)), (b_sizeof, (String,)), - (b_dynamic_inbounds, (NTuple{2,Int}, Int)), (b_dynamic_inbounds, (NTuple{4,Float32}, Int)), - (b_dynamic_inbounds, (NTuple{4,String}, Int))) + (b_isa_int, (Int,)), (b_tuple, (Int, String)), (b_sizeof, (String,))) @test @filecheck begin @check_not "julia.call" print(test_ir(f, types)) end end + # (unless --check-bounds=yes checks bounds in `@inbounds` too, throwing through a call) + if Base.JLOptions().check_bounds != 1 + for types in ((NTuple{2,Int}, Int), (NTuple{4,Float32}, Int), (NTuple{4,String}, Int)) + @test @filecheck begin + @check_not "julia.call" + print(test_ir(b_dynamic_inbounds, types)) + end + end + end + # an inline argument indexed at run time is read where it is, from the memory it is + # passed in + @test @filecheck begin + @check_label "define internal float @julia_b_dynamic_inbounds" + @check "ptr addrspace(11)" + @check_not "alloca" + @check "getelementptr inbounds float, ptr addrspace(11)" + print(test_ir(b_dynamic_inbounds, (NTuple{8,Float32}, Int))) + end # a write barrier for each reference stored into an object ir = test_ir(b_mutable_set!, (BMutable, Int, Any, BRef)) if JuliaCodegen.CodegenConfig().dialect.barrier_flavour === :write_barrier diff --git a/test/calls.jl b/test/calls.jl index cc035b6..05ce602 100644 --- a/test/calls.jl +++ b/test/calls.jl @@ -68,7 +68,7 @@ end # signature has a `Vararg` (as inference keeps two or more varargs here): through the # runtime, with the arguments one by one ir = test_ir(c_call_vararg2, (Int,)) - @test occursin(r"call i64 @julia_c_vararg2_\d+\(i64 %\d+, \[1 x i64\]", ir) + @test occursin(r"call i64 @julia_c_vararg2_\d+\(i64 %\d+, ptr addrspace\(11\)", ir) @test occursin("@ijl_invoke", ir) # a varargs entry @cgtest c_vararg2(1, 2, 3) From a4ff09fe203320999ffa9a9e178deade61670cec Mon Sep 17 00:00:00 2001 From: Valentin Churavy Date: Tue, 20 Oct 2026 01:19:03 +0200 Subject: [PATCH 18/27] emit_into!: jlcall entries with the attributes of native code's nonnull results, and a noalias nocapture noundef readonly argument array, as jfptr_f_N has them (GPUCompiler's slow ABI test checks the declaration). Assisted-by: Claude Code (Opus 5.5) --- src/function.jl | 4 ++++ test/calls.jl | 2 +- test/unions.jl | 2 +- 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/function.jl b/src/function.jl index f8f281c..9063719 100644 --- a/src/function.jl +++ b/src/function.jl @@ -408,6 +408,10 @@ function emit_jlcall_wrapper!(cgm::CGModule, info::FuncInfo, name::AbstractStrin ft = LLVM.FunctionType(T_tracked(), [T_tracked(), T_ptr(), LLVM.Int32Type()]) f = LLVM.Function(cgm.mod, String(name), ft) init_function!(f, cgm.config.target) + # (as native code's) + push!(f.return_attributes, attr("nonnull")) + foreach(a -> push!(f.parameter_attributes[2], a), + (attr("noalias"), nocapture(), attr("noundef"), attr("readonly"))) @dispose b=LLVM.IRBuilder() begin top = LLVM.BasicBlock(f, "top") LLVM.position!(b, LLVM.at_end(top)) diff --git a/test/calls.jl b/test/calls.jl index 05ce602..bd7fba9 100644 --- a/test/calls.jl +++ b/test/calls.jl @@ -97,7 +97,7 @@ end @check "define internal i64 @julia_c_fib_[[N:[0-9]+]](" @check "call i64 @julia_c_fib_[[N]](" @check_not "julia.call" - @check "define ptr addrspace(10) @jctest_entry" + @check "define nonnull ptr addrspace(10) @jctest_entry" print(test_ir(c_fib, (Int,))) end # a union-returning callee is called directly, with the union by value diff --git a/test/unions.jl b/test/unions.jl index 97d19f4..8ea3abf 100644 --- a/test/unions.jl +++ b/test/unions.jl @@ -101,7 +101,7 @@ end @test @filecheck begin @check_label "define internal" @check_not "julia.gc_alloc_obj" - @check_label "define ptr addrspace(10) @jctest_entry" + @check_label "define nonnull ptr addrspace(10) @jctest_entry" print(test_ir(u_maybe, (Bool, Int))) end @test @filecheck begin From 3a963610ff784c0c217d7f9f56f3685242551485 Mon Sep 17 00:00:00 2001 From: Valentin Churavy Date: Tue, 20 Oct 2026 01:27:41 +0200 Subject: [PATCH 19/27] Functions of @noinline methods are noinline, as native code's Assisted-by: Claude Code (Opus 5.5) --- src/function.jl | 9 +++++++++ test/calls.jl | 6 ++++++ 2 files changed, 15 insertions(+) diff --git a/src/function.jl b/src/function.jl index 9063719..18ea618 100644 --- a/src/function.jl +++ b/src/function.jl @@ -53,11 +53,20 @@ function declare_function!(cgm::CGModule, mi::Core.MethodInstance, argtypes::Vec LLVM.linkage!(llvmf, LLVM.API.LLVMInternalLinkage) init_function!(llvmf, cgm.config.target) rettype === Union{} && push!(llvmf.function_attributes, LLVM.EnumAttribute("noreturn")) + # (as native code's, for methods declared `@noinline`) + is_noinline(mi) && push!(llvmf.function_attributes, LLVM.EnumAttribute("noinline")) info = FuncInfo(mi, llvmf, argtypes, rettype) cgm.funcs[mi] = info return info end +# whether the method of `mi` is declared `@noinline` (its source's inlining flag) +function is_noinline(mi::Core.MethodInstance) + m = mi.def + (m isa Method && m.source !== nothing) || return false + return ccall(:jl_ir_flag_inlining, UInt8, (Any,), m.source) == 2 +end + """ JuliaCodegen.byref(cgm, T) -> Bool diff --git a/test/calls.jl b/test/calls.jl index bd7fba9..9c5e9bb 100644 --- a/test/calls.jl +++ b/test/calls.jl @@ -105,6 +105,12 @@ end @check "call { [8 x i8], i8, ptr addrspace(10) } @julia_c_maybe_" print(test_ir(c_use_maybe, (Int,))) end + # a function of a method declared `@noinline` isn't inlined, as native code's + @test @filecheck begin + @check "define internal i64 @julia_c_add_{{[0-9]+}}(i64 %0, i64 %1) [[ATTRS:#[0-9]+]]" + @check "attributes [[ATTRS]] = { noinline" + print(test_ir(c_calls, (Int,))) + end end end From 55f4574da86c88fd056daf5065ed5524dba569cb Mon Sep 17 00:00:00 2001 From: Valentin Churavy Date: Tue, 20 Oct 2026 01:48:11 +0200 Subject: [PATCH 20/27] Error paths through the runtime, as native code's Bounds errors call jl_bounds_error_int with the boxed value, or jl_bounds_error_unboxed_int with the data of an inline one without references (as emit_bounds_check), undefined references and division by zero throw the runtime's exception objects through jl_throw (raise_exception_unless), and undefined local variables call jl_undefined_var_error: rather than calls of Julia functions that construct the exceptions, which allocate on GPU back ends, where these throws lower to traps. getfield with an index known at run time also reads constant tuples from memory, as native code, and selects among the references of inline tuples of different types. Assisted-by: Claude Code (Opus 5.5) --- src/boxing.jl | 4 ++++ src/builtins.jl | 42 ++++++++++++++++++++++-------------------- src/calls.jl | 20 +++++++++++++++++++- src/constants.jl | 10 ++++++++++ src/exceptions.jl | 19 ++++++++++++++----- src/intrinsics.jl | 5 ++--- src/memory.jl | 35 +++++++++++++++++++++++++++++++---- src/runtime.jl | 18 ++++++++++++++---- test/builtins.jl | 24 ++++++++++++++++++++++++ 9 files changed, 140 insertions(+), 37 deletions(-) diff --git a/src/boxing.jl b/src/boxing.jl index 7a8ef88..efdfa1f 100644 --- a/src/boxing.jl +++ b/src/boxing.jl @@ -31,6 +31,10 @@ end derived(fc::FnCtx, v::LLVM.Value) = LLVM.addrspacecast!(fc.builder, v, T_derived()) +# a tracked pointer passed to a function that roots it (`mark_callee_rooted`) +callee_rooted(fc::FnCtx, v::LLVM.Value) = + LLVM.addrspacecast!(fc.builder, v, LLVM.PointerType(AddrSpace.CalleeRooted)) + """ JuliaCodegen.emit_allocation(fc, T) -> LLVM.Value diff --git a/src/builtins.jl b/src/builtins.jl index 54d9d4e..54a461a 100644 --- a/src/builtins.jl +++ b/src/builtins.jl @@ -381,10 +381,8 @@ function field_index(@nospecialize(T), f::CGVal) return nothing end -@noinline throw_undefref() = throw(UndefRefError()) - -# a null check of a reference that is undefined when null: UndefRefError -undef_check!(fc::FnCtx, p::LLVM.Value) = emit_guard!(fc, nonnull(fc, p), throw_undefref) +# a null check of a reference that is undefined when null: the runtime's UndefRefError +undef_check!(fc::FnCtx, p::LLVM.Value) = emit_raise_unless!(fc, nonnull(fc, p), UndefRefError()) # `getfield(x, f, [order], [boundscheck])` function emit_getfield(fc::FnCtx, args::Vector{CGVal}, @nospecialize(rt)) @@ -476,10 +474,13 @@ function emit_getfield_unknownidx(fc::FnCtx, x::CGVal, @nospecialize(T), idx::CG lowered = fc -> convert_repr(fc, ghost(FT, something(ghost_value(FT))), rt) elseif x.kind === Inline lay = layout(fc, T) - (same && (lay.llvm isa LLVM.ArrayType || lay.llvm isa LLVM.VectorType)) || return nothing + (lay.llvm isa LLVM.ArrayType || lay.llvm isa LLVM.VectorType) || return nothing + # (references, of any types, or values of a single type) + refs = all(i -> field_storage(T, i) === FieldPointer, 1:n) + (refs || same) || return nothing lowered = fc -> begin - v = inline_element(fc, x, lay, FT, n, idx) - convert_repr(fc, field_storage(FT) === FieldPointer ? boxed(FT, v) : inline(FT, v), rt) + v = inline_element(fc, x, lay, refs, n, idx; align=Base.datatype_alignment(FT)) + convert_repr(fc, refs ? boxed(Union{types...}, v) : inline(FT, v), rt) end elseif x.kind === Boxed ismutabletype(T) && T.name.atomicfields != C_NULL && return nothing @@ -506,21 +507,23 @@ function emit_getfield_unknownidx(fc::FnCtx, x::CGVal, @nospecialize(T), idx::CG else return nothing end - bounds_check!(fc, LLVM.sub!(b, idx.V, iptr(fc, 1)), iptr(fc, n), bc, x, idx) + bounds_check!(fc, LLVM.sub!(b, idx.V, iptr(fc, 1)), iptr(fc, n), bc, x, idx; unboxed=true) return lowered(fc) end -# the element `idx` (1-based, in bounds) of the inline homogeneous tuple `x` with the -# layout `lay` (an LLVM array or vector of `n` elements of type `FT`, or of references to -# them): extracted from a vector, selected among a few elements or ones with references, -# or loaded from memory (the memory it was loaded from; for a constant, a private global, -# as native code's `value_to_pointer`; or a stack slot) -function inline_element(fc::FnCtx, x::CGVal, lay::Layout, @nospecialize(FT), n::Int, idx::CGVal) +# the element `idx` (1-based, in bounds) of the inline tuple `x` with the layout `lay` (an +# LLVM array or vector of `n` elements, references if `refs`, aligned to `align`): +# extracted from a vector, selected among references or a few values not in memory, or +# loaded from memory (the memory it was loaded from; for a constant, a private global, as +# native code's `value_to_pointer`; or a stack slot) +function inline_element(fc::FnCtx, x::CGVal, lay::Layout, refs::Bool, n::Int, idx::CGVal; + align::Integer) b = fc.builder i0 = LLVM.sub!(b, idx.V, iptr(fc, 1)) if lay.llvm isa LLVM.VectorType return LLVM.extract_element!(b, x.V, LLVM.trunc!(b, i0, LLVM.Int32Type())) - elseif n <= 3 || field_storage(FT) === FieldPointer || has_references(FT) + elseif refs || has_references(x.typ) || + (n <= 3 && x.mem === nothing && !(isconstant(x) && x.V isa LLVM.Constant)) v = LLVM.extract_value!(b, x.V, 0) for i in 1:n-1 c = LLVM.icmp!(b, LLVM.API.LLVMIntEQ, i0, iptr(fc, i)) @@ -528,18 +531,17 @@ function inline_element(fc::FnCtx, x::CGVal, lay::Layout, @nospecialize(FT), n:: end return v end - align = Base.datatype_alignment(x.typ) if x.mem !== nothing mem, tb = x.mem, :const elseif isconstant(x) && x.V isa LLVM.Constant - mem, tb = constant_memory!(fc.cgm, x.V, align), :const + mem, tb = constant_memory!(fc.cgm, x.V, Base.datatype_alignment(x.typ)), :const else - mem, tb = entry_alloca!(fc, lay.llvm; align), :stack + mem, tb = entry_alloca!(fc, lay.llvm; align=Base.datatype_alignment(x.typ)), :stack tbaa!(fc, LLVM.store!(b, x.V, mem), :stack) end et = LLVM.element_type(lay.llvm) p = LLVM.inbounds_gep!(b, et, mem, [i0]) - return tbaa!(fc, LLVM.load!(b, et, p; align=Base.datatype_alignment(FT)), tb) + return tbaa!(fc, LLVM.load!(b, et, p; align), tb) end # `setfield!(x, f, v, [order])` of a non-atomic field @@ -626,7 +628,7 @@ function emit_throw(fc::FnCtx, args::Vector{CGVal}, @nospecialize(rt)) length(args) == 1 || return nothing b = fc.builder f = runtime_function(fc, :jl_throw) - p = LLVM.addrspacecast!(b, emit_box(fc, args[1]), LLVM.PointerType(AddrSpace.CalleeRooted)) + p = callee_rooted(fc, emit_box(fc, args[1])) LLVM.call!(b, LLVM.function_type(f), f, LLVM.Value[p]) return emit_unreachable!(fc) end diff --git a/src/calls.jl b/src/calls.jl index 2923814..6e7b5b7 100644 --- a/src/calls.jl +++ b/src/calls.jl @@ -54,8 +54,26 @@ function emit_guard!(fc::FnCtx, cond::LLVM.Value, f::Function, args::CGVal...) return nothing end +""" + JuliaCodegen.emit_raise_unless!(fc, cond, exc) + +If `cond` (an `i1`) is false, throw the exception object `exc` through the runtime +(`jl_throw`), as native code's `raise_exception_unless`. +""" +function emit_raise_unless!(fc::FnCtx, cond::LLVM.Value, @nospecialize(exc)) + b = fc.builder + fail = LLVM.BasicBlock(current_function(fc), "fail") + pass = LLVM.BasicBlock(current_function(fc), "pass") + LLVM.br!(b, cond, pass, fail) + LLVM.position!(b, LLVM.at_end(fail)) + f = runtime_function(fc, :jl_throw) + LLVM.call!(b, LLVM.function_type(f), f, LLVM.Value[callee_rooted(fc, literal_pointer(fc, exc))]) + LLVM.unreachable!(b) + LLVM.position!(b, LLVM.at_end(pass)) + return nothing +end + # error paths, which construct the exceptions in Julia -@noinline throw_divide_error() = throw(DivideError()) @noinline throw_error_message(msg::String) = throw(ErrorException(msg)) ## walker hooks diff --git a/src/constants.jl b/src/constants.jl index 3a54d97..8c6cfbf 100644 --- a/src/constants.jl +++ b/src/constants.jl @@ -71,6 +71,16 @@ function literal_pointer(fc::FnCtx, @nospecialize x) end end +# an untracked pointer to the object `x` (native code's `literal_pointer_val`), for the +# runtime functions that take one, loaded where it is used +function literal_pointer_raw(fc::FnCtx, @nospecialize x) + p = LLVM.load!(fc.builder, T_ptr(), literal_global(fc.cgm, x); align=config(fc).target.pointer_size) + tbaa!(fc, p, :const) + p.metadata[LLVM.MD_invariant_load] = LLVM.MDNode(LLVM.Metadata[]) + p.metadata[LLVM.MD_nonnull] = LLVM.MDNode(LLVM.Metadata[]) + return p +end + # where loads of objects go: the start of the entry block, which dominates every use function top_insertion_point(fc::FnCtx) insts = LLVM.instructions(fc.top) diff --git a/src/exceptions.jl b/src/exceptions.jl index 0f71117..d449cda 100644 --- a/src/exceptions.jl +++ b/src/exceptions.jl @@ -200,8 +200,6 @@ end ## statements that throw, and assignments of globals -@noinline throw_undefvar(@nospecialize(s)) = ccall(:jl_undefined_var_error, Union{}, (Any, Any), s, :local) - function emit_exception_head!(fc::FnCtx, idx::Int, ex::Expr, @nospecialize(typ)) head = ex.head if head === :leave @@ -220,10 +218,21 @@ function emit_exception_head!(fc::FnCtx, idx::Int, ex::Expr, @nospecialize(typ)) ok = LLVM.trunc!(fc.builder, c.V, LLVM.Int1Type()) var = ex.args[1] if var === :getfield_undefref || var === Symbol("##getfield##") - emit_guard!(fc, ok, throw_undefref) + emit_raise_unless!(fc, ok, UndefRefError()) else - # (a Symbol, or a GlobalRef in a module context; passed to UndefVarError as is) - emit_guard!(fc, ok, throw_undefvar, const_value(fc, var)) + # the runtime's UndefVarError of the local variable (`undef_var_error_ifnot`; a + # Symbol, or a GlobalRef in a module context, passed to UndefVarError as is) + b = fc.builder + fail = LLVM.BasicBlock(current_function(fc), "err") + pass = LLVM.BasicBlock(current_function(fc), "ok") + LLVM.br!(b, ok, pass, fail) + LLVM.position!(b, LLVM.at_end(fail)) + f = runtime_function(fc, :jl_undefined_var_error) + LLVM.call!(b, LLVM.function_type(f), f, + LLVM.Value[callee_rooted(fc, literal_pointer(fc, var)), + callee_rooted(fc, literal_pointer(fc, :local))]) + LLVM.unreachable!(b) + LLVM.position!(b, LLVM.at_end(pass)) end return ghost(Nothing, nothing) elseif head === :(=) diff --git a/src/intrinsics.jl b/src/intrinsics.jl index e32f08d..74c0673 100644 --- a/src/intrinsics.jl +++ b/src/intrinsics.jl @@ -75,9 +75,8 @@ function emit_typecheck!(fc::FnCtx, x::CGVal, @nospecialize(T), context::String) b = fc.builder function type_error() err = declare_runtime(fc.cgm.mod, dialect(fc), :jl_type_error) - rooted(v) = LLVM.addrspacecast!(b, v, LLVM.PointerType(AddrSpace.CalleeRooted)) LLVM.call!(b, LLVM.function_type(err), err, - LLVM.Value[cstring!(fc.cgm, context), literal_pointer(fc, T), rooted(emit_box(fc, x))]) + LLVM.Value[cstring!(fc.cgm, context), literal_pointer(fc, T), callee_rooted(fc, emit_box(fc, x))]) LLVM.unreachable!(b) end if typeintersect(x.typ, T) === Union{} @@ -354,7 +353,7 @@ function emit_checked_divrem(fc::FnCtx, name::Symbol, xs::Vector{LLVM.Value}, @n ismin = LLVM.icmp!(b, LLVM.API.LLVMIntEQ, x, tmin) ok = LLVM.and!(b, ok, LLVM.not!(b, LLVM.and!(b, isneg1, ismin))) end - emit_guard!(fc, ok, throw_divide_error) + emit_raise_unless!(fc, ok, DivideError()) r = if name === :checked_sdiv_int LLVM.sdiv!(b, x, y) elseif name === :checked_udiv_int diff --git a/src/memory.jl b/src/memory.jl index cf9fdb0..1899bf3 100644 --- a/src/memory.jl +++ b/src/memory.jl @@ -37,7 +37,6 @@ memory_elsize(@nospecialize R) = Int(unsafe_load(Ptr{Base.DataTypeLayout}( GenericMemory{R.parameters[1], R.parameters[2], R.parameters[3]}.layout)).size) -@noinline throw_boundserror(a, i) = throw(BoundsError(a, i)) memory_length(fc::FnCtx, mem::LLVM.Value) = tbaa!(fc, LLVM.load!(fc.builder, iptr_type(fc), derived(fc, mem); align=config(fc).target.pointer_size), @@ -67,13 +66,41 @@ function memory_owner(fc::FnCtx, mem::LLVM.Value) end # a bounds check of the 0-based index `i0` against the length `len`, unless the -# boundscheck argument `bc` is false -function bounds_check!(fc::FnCtx, i0::LLVM.Value, len::LLVM.Value, bc::CGVal, x::CGVal, idx::CGVal) +# boundscheck argument `bc` is false: out of bounds, the runtime throws the BoundsError of +# `x` and the index `idx` (`emit_bounds_check`), of `x` boxed (`jl_bounds_error_int`), or +# with `unboxed`, of an inline `x` without references by its data +# (`jl_bounds_error_unboxed_int`) +function bounds_check!(fc::FnCtx, i0::LLVM.Value, len::LLVM.Value, bc::CGVal, x::CGVal, idx::CGVal; + unboxed::Bool=false) (isconstant(bc) && constant_value(bc) === false) && return b = fc.builder inb = LLVM.icmp!(b, LLVM.API.LLVMIntULT, i0, len) isconstant(bc) || (inb = LLVM.or!(b, inb, LLVM.not!(b, LLVM.trunc!(b, bc.V, LLVM.Int1Type())))) - emit_guard!(fc, inb, throw_boundserror, x, idx) + fail = LLVM.BasicBlock(current_function(fc), "oob") + pass = LLVM.BasicBlock(current_function(fc), "idxend") + LLVM.br!(b, inb, pass, fail) + LLVM.position!(b, LLVM.at_end(fail)) + # (a value with references boxed, so that they are rooted while the runtime allocates) + if unboxed && x.kind !== Boxed && !has_references(x.typ) + data = if x.kind === Ghost + LLVM.null(T_derived()) + elseif x.mem !== nothing + derived(fc, x.mem) + else + # (on the error path) + slot = LLVM.alloca!(b, LLVM.value_type(x.V)) + LLVM.store!(b, x.V, slot) + derived(fc, slot) + end + f = runtime_function(fc, :jl_bounds_error_unboxed_int) + LLVM.call!(b, LLVM.function_type(f), f, LLVM.Value[data, literal_pointer_raw(fc, x.typ), idx.V]) + else + f = runtime_function(fc, :jl_bounds_error_int) + LLVM.call!(b, LLVM.function_type(f), f, LLVM.Value[callee_rooted(fc, emit_box(fc, x)), idx.V]) + end + LLVM.unreachable!(b) + LLVM.position!(b, LLVM.at_end(pass)) + return end function emit_memoryrefnew(fc::FnCtx, args::Vector{CGVal}, @nospecialize(rt)) diff --git a/src/runtime.jl b/src/runtime.jl index 7e2b490..4252023 100644 --- a/src/runtime.jl +++ b/src/runtime.jl @@ -3,12 +3,13 @@ # an image, binds them. """ - JuliaCodegen.declare_runtime(mod, dialect, name) -> LLVM.Function + JuliaCodegen.declare_runtime(mod, dialect, name; T_size) -> LLVM.Function The declaration of the runtime function `name` (e.g. `:jl_apply_generic`) in `mod`, as the -dialect's code generator declares it. +dialect's code generator declares it, with `T_size` the target's `size_t`. """ -function declare_runtime(mod::LLVM.Module, dialect::JuliaIR.Dialect, name::Symbol) +function declare_runtime(mod::LLVM.Module, dialect::JuliaIR.Dialect, name::Symbol; + T_size::LLVM.IntegerType=LLVM.Int64Type()) sym = runtime_symbol(name) haskey(mod.functions, sym) && return mod.functions[sym] T_rooted = LLVM.PointerType(AddrSpace.CalleeRooted) @@ -67,6 +68,14 @@ function declare_runtime(mod::LLVM.Module, dialect::JuliaIR.Dialect, name::Symbo elseif name === :jl_throw f = LLVM.Function(mod, sym, LLVM.FunctionType(LLVM.VoidType(), [T_rooted])) push!(f.function_attributes, LLVM.EnumAttribute("noreturn")) + elseif name === :jl_bounds_error_int + # `void (jl_value_t *v, size_t i)` + f = LLVM.Function(mod, sym, LLVM.FunctionType(LLVM.VoidType(), [T_rooted, T_size])) + push!(f.function_attributes, LLVM.EnumAttribute("noreturn")) + elseif name === :jl_bounds_error_unboxed_int + # `void (void *data, jl_value_t *vt, size_t i)` + f = LLVM.Function(mod, sym, LLVM.FunctionType(LLVM.VoidType(), [T_derived(), T_ptr(), T_size])) + push!(f.function_attributes, LLVM.EnumAttribute("noreturn")) elseif name === :jl_subtype f = LLVM.Function(mod, sym, LLVM.FunctionType(LLVM.Int32Type(), [T_tracked(), T_tracked()])) elseif name === :jl_egal__unboxed @@ -105,4 +114,5 @@ runtime_symbol(name::Symbol) = startswith(String(name), "jl_") && !(name in INTERNAL_RUNTIME) ? "i" * String(name) : String(name) "The address of the runtime function `name` as an LLVM value." -runtime_function(fc::FnCtx, name::Symbol) = declare_runtime(fc.cgm.mod, dialect(fc), name) +runtime_function(fc::FnCtx, name::Symbol) = + declare_runtime(fc.cgm.mod, dialect(fc), name; T_size=iptr_type(fc)) diff --git a/test/builtins.jl b/test/builtins.jl index a273a6d..15a1303 100644 --- a/test/builtins.jl +++ b/test/builtins.jl @@ -44,6 +44,12 @@ b_dynamic_index(t, i) = t[i] b_dynamic_inbounds(t, i) = @inbounds t[i] b_dynamic_const(i) = @inbounds (1.0f0, 2.0f0, 3.0f0, 4.0f0)[i] b_dynamic_field(m, i) = getfield(m, i) +b_div(x, y) = div(x, y) +b_memoryref(m, i) = Core.memoryrefnew(Core.memoryrefnew(m), i, true) +function b_undefvar(c) + c && (x = 1) + return x +end const B_EGAL_PAIRS = Any[ (1, 1), (1, 2), (1, 1.0), (NaN, NaN), (0.0, -0.0), (1.0f0, 1.0f0), (true, true), (true, false), @@ -127,6 +133,10 @@ end @cgtest b_dynamic_field(BMutable(1, "a", BRef(2, "b")), 2) @cgtest b_dynamic_field(BPartial(3), 2) # UndefRefError @cgtest b_dynamic_field(BPartial(3), 3) # BoundsError + @cgtest b_memoryref(Memory{Int}(1:3), 4) # BoundsError + @cgtest b_div(1, 0) # DivideError + @cgtest b_undefvar(true) + @cgtest b_undefvar(false) # UndefVarError # the write barrier: young objects stored into an old one survive collections old = BMutable(0, nothing, BRef(0, "")) GC.gc(); GC.gc() @@ -202,6 +212,20 @@ end @check "load float, ptr" print(test_ir(b_dynamic_const, (Int,))) end + # error paths throw through the runtime, as native code's (which GPU back ends lower), + # rather than construct their exceptions + for (f, types, callee) in ((b_dynamic_index, (NTuple{4,Float32}, Int), "@ijl_bounds_error_unboxed_int("), + (b_dynamic_index, (Tuple{String,Symbol}, Int), "@ijl_bounds_error_int("), + (b_memoryref, (Memory{Int}, Int), "@ijl_bounds_error_int("), + (b_partial_get, (BPartial,), "@ijl_throw("), + (b_div, (Int, Int), "@ijl_throw("), + (b_undefvar, (Bool,), "@ijl_undefined_var_error(")) + @test @filecheck begin + @check_not "julia.call" + @check "call void $callee" + print(test_ir(f, types)) + end + end # the box of an object is compared by the runtime only if it isn't identical @test @filecheck begin @check "icmp ne ptr addrspace(10)" From e0ca3524c09cc0bccfaf5e7f64abb2300522434b Mon Sep 17 00:00:00 2001 From: Valentin Churavy Date: Tue, 20 Oct 2026 01:55:28 +0200 Subject: [PATCH 21/27] Core.svec and Core._svec_len, as native code svec allocates the vector inline (as native code from Julia 1.12 on), with the elements boxed first, stored with release ordering and write barriers; _svec_len loads the length. These were calls of the runtime, which GPU back ends reject as dynamic calls rather than as unsupported allocations. Assisted-by: Claude Code (Opus 5.5) --- src/builtins.jl | 34 ++++++++++++++++++++++++++++++++++ test/builtins.jl | 8 +++++++- 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/src/builtins.jl b/src/builtins.jl index 54a461a..902e8de 100644 --- a/src/builtins.jl +++ b/src/builtins.jl @@ -812,6 +812,38 @@ function emit_isdefined(fc::FnCtx, args::Vector{CGVal}, @nospecialize(rt)) return nothing end +# `Core.svec(xs...)`: allocated inline, as native code (from Julia 1.12 on), with the +# elements boxed first +function emit_svec(fc::FnCtx, args::Vector{CGVal}, @nospecialize(rt)) + isempty(args) && return const_value(fc, Core.svec()) + b = fc.builder + W = config(fc).target.pointer_size + elems = LLVM.Value[emit_box(fc, a) for a in args] + sv = call_op!(fc, "julia.gc_alloc_obj", fc.current_task, + LLVM.ConstantInt(LLVM.Int64Type(), W * (length(args) + 1)), + type_tag(fc, Core.SimpleVector)) + data = derived(fc, sv) + LLVM.store!(b, iptr(fc, length(args)), data; align=W) + for (i, e) in enumerate(elems) + addr = LLVM.inbounds_gep!(b, LLVM.Int8Type(), data, [iptr(fc, W * i)]) + st = LLVM.store!(b, e, addr; align=W) + LLVM.ordering!(st, LLVM.API.LLVMAtomicOrderingRelease) + write_barrier!(b, fc.cgm.mod, dialect(fc), sv, addr, e) + end + return boxed(Core.SimpleVector, sv) +end + +# `Core._svec_len(sv)`: the length, the first word +function emit_svec_len(fc::FnCtx, args::Vector{CGVal}, @nospecialize(rt)) + length(args) == 1 || return nothing + sv = args[1] + isconstant(sv) && constant_value(sv) isa Core.SimpleVector && + return const_value(fc, length(constant_value(sv))) + sv.typ === Core.SimpleVector || return nothing + W = config(fc).target.pointer_size + return inline(Int, LLVM.load!(fc.builder, iptr_type(fc), derived(fc, emit_box(fc, sv)); align=W)) +end + const BUILTINS = IdDict{Any,Function}( Core.:(===) => (fc, args, rt) -> length(args) == 2 ? emit_egal(fc, args[1], args[2]) : nothing, Core.ifelse => emit_ifelse, @@ -826,6 +858,8 @@ const BUILTINS = IdDict{Any,Function}( Core.sizeof => emit_sizeof, Core.getglobal => emit_getglobal, Core.setglobal! => emit_setglobal!, + Core.svec => emit_svec, + Core._svec_len => emit_svec_len, ) """ diff --git a/test/builtins.jl b/test/builtins.jl index 15a1303..0d19477 100644 --- a/test/builtins.jl +++ b/test/builtins.jl @@ -45,6 +45,8 @@ b_dynamic_inbounds(t, i) = @inbounds t[i] b_dynamic_const(i) = @inbounds (1.0f0, 2.0f0, 3.0f0, 4.0f0)[i] b_dynamic_field(m, i) = getfield(m, i) b_div(x, y) = div(x, y) +b_svec(x, y) = Core.svec(x, y, 1) +b_svec_len(s) = length(s) b_memoryref(m, i) = Core.memoryrefnew(Core.memoryrefnew(m), i, true) function b_undefvar(c) c && (x = 1) @@ -161,6 +163,9 @@ end @cgtest b_sizeof("abcd") @cgtest b_sizeof(1.0) @cgtest b_getglobal() + @cgtest b_svec("a", 2.0) + @cgtest b_svec_len(Core.svec(1, "b", :c)) + @cgtest b_svec_len(Core.svec()) end @testset "code" begin @@ -168,7 +173,8 @@ end for (f, types) in ((b_fields, (BPoint,)), (b_new_point, (Float64, Float64)), (b_new_mutable, (Int, Any, BRef)), (b_mutable_set!, (BMutable, Int, Any, BRef)), (b_egal, (BPoint, BPoint)), (b_egal, (Symbol, Symbol)), - (b_isa_int, (Int,)), (b_tuple, (Int, String)), (b_sizeof, (String,))) + (b_isa_int, (Int,)), (b_tuple, (Int, String)), (b_sizeof, (String,)), + (b_svec, (String, Float64)), (b_svec_len, (Core.SimpleVector,))) @test @filecheck begin @check_not "julia.call" print(test_ir(f, types)) From e1f194abaf5b81a8d569aef6a3e601de7f406c5d Mon Sep 17 00:00:00 2001 From: Valentin Churavy Date: Tue, 20 Oct 2026 02:00:21 +0200 Subject: [PATCH 22/27] Debug information: the NoDebug emission kind, with locations debug_info=:no_debug emits the locations in a compile unit of the emission kind NoDebug, as native code for debug_info_kind NoDebug unless Julia runs with -g0: GPUCompiler's error messages read backtraces from them for targets without debug information, then strip them. Assisted-by: Claude Code (Opus 5.5) --- src/config.jl | 8 +++++--- src/debuginfo.jl | 4 ++-- test/debuginfo.jl | 8 ++++++++ 3 files changed, 15 insertions(+), 5 deletions(-) diff --git a/src/config.jl b/src/config.jl index dc481e9..dfe77fb 100644 --- a/src/config.jl +++ b/src/config.jl @@ -22,7 +22,9 @@ The configuration of the code generator, which generates code for the running Ju - `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`. + `:line_tables`, `:directives` or `:full`, or `:no_debug`, which native code emits for + the kind `NoDebug` (unless Julia runs with `-g0`): for tools reading locations, like + GPUCompiler's error messages, which strip them later. The facts about the running Julia's runtime are `config.runtime`, see [`RuntimeFacts`](@ref JuliaCodegen.RuntimeFacts). @@ -47,8 +49,8 @@ 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")) + debug_info in (:none, :no_debug, :line_tables, :directives, :full) || + throw(ArgumentError("invalid debug_info :$debug_info; expected none, no_debug, line_tables, directives or full")) new(target, dialect, runtime_facts(), on_unsupported, on_internal_error, gcstack_arg, safepoint_on_entry, debug_info) end diff --git a/src/debuginfo.jl b/src/debuginfo.jl index f62fabc..88b33cf 100644 --- a/src/debuginfo.jl +++ b/src/debuginfo.jl @@ -1,11 +1,11 @@ -# Debug information: the line tables of native code (`debug_info_kind` above `NoDebug`): +# Debug information: the line tables of native code (`debug_info_level` above 0): # 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) +const DEBUG_EMISSION_KINDS = (no_debug=0, full=1, line_tables=2, directives=3) """ JuliaCodegen.DebugInfo diff --git a/test/debuginfo.jl b/test/debuginfo.jl index 585a2cf..57877a8 100644 --- a/test/debuginfo.jl +++ b/test/debuginfo.jl @@ -54,6 +54,14 @@ end debug_info=kind) @test occursin("emissionKind: $name", d_ir(d_inner, (Int,); config)) end + # without debug information, but with the locations + config = JuliaCodegen.CodegenConfig(; on_unsupported=:error, on_internal_error=:error, + debug_info=:no_debug) + @test @filecheck begin + @check "!dbg" + @check "emissionKind: NoDebug" + d_ir(d_inner, (Int,); config) + end @test_throws "invalid debug_info" JuliaCodegen.CodegenConfig(; debug_info=:lines) end From 399b4ebb1b9e525068945243a8bde4d1116a2515 Mon Sep 17 00:00:00 2001 From: Valentin Churavy Date: Tue, 20 Oct 2026 02:06:55 +0200 Subject: [PATCH 23/27] Base.llvmcall passes structs of fields of one type as arrays As native code, which lays out structs as LLVM structs only for ccall with the llvmcall convention (julia_struct_to_llvm for llvmcall); the conversion also took the length of an array type with length (GPUCompiler's kernel state, a struct of one Int). Assisted-by: Claude Code (Opus 5.5) --- src/intrinsics.jl | 17 ++++++++++------- test/intrinsics.jl | 8 ++++++++ 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/src/intrinsics.jl b/src/intrinsics.jl index 74c0673..116c328 100644 --- a/src/intrinsics.jl +++ b/src/intrinsics.jl @@ -450,16 +450,19 @@ end # %1, ...) or a `(module, entry)` pair. The IR is parsed into the module being emitted, # marked `alwaysinline`, and called. -function llvmcall_type(fc::FnCtx, @nospecialize(T); ptr_as_int::Bool=false) +# the LLVM type of values of type `T` in an llvmcall: of `ccall(..., llvmcall, ...)`, or +# with `base`, of `Base.llvmcall` +function llvmcall_type(fc::FnCtx, @nospecialize(T); base::Bool=false) (T === Nothing || T === Cvoid) && return LLVM.VoidType() # (the IR of `Base.llvmcall` gets `Ptr` values as integers of their size, as native # code passes them) - ptr_as_int && T isa DataType && T <: Ptr && return iptr_type(fc) + base && T isa DataType && T <: Ptr && return iptr_type(fc) repr_kind(T) === Inline || unsupported("llvmcall with the type ", T) ty = value_type(fc, T) - # (llvmcall passes structs other than tuples as LLVM structs) - if ty isa LLVM.ArrayType && !(T <: Tuple) - return LLVM.StructType(fill(ty.element_type, Int(length(ty)))) + # (`ccall` passes structs other than tuples as LLVM structs, `julia_struct_to_llvm` + # for llvmcall) + if !base && ty isa LLVM.ArrayType && !(T <: Tuple) + return LLVM.StructType(fill(ty.element_type, LLVM.array_length(ty))) end return ty end @@ -477,8 +480,8 @@ function emit_llvmcall(fc::FnCtx, args::Vector{CGVal}, @nospecialize(rt)) vals = args[4:end] ATs = AT isa DataType ? collect(Any, AT.parameters) : Any[] length(ATs) == length(vals) || return nothing - lrt = llvmcall_type(fc, RT; ptr_as_int=true) - lats = LLVM.LLVMType[llvmcall_type(fc, T; ptr_as_int=true) for T in ATs] + lrt = llvmcall_type(fc, RT; base=true) + lats = LLVM.LLVMType[llvmcall_type(fc, T; base=true) for T in ATs] cgm = fc.cgm if ir isa String name = unique_name(cgm, "jl_llvmcall") diff --git a/test/intrinsics.jl b/test/intrinsics.jl index 41a6cc1..468912f 100644 --- a/test/intrinsics.jl +++ b/test/intrinsics.jl @@ -32,6 +32,13 @@ i_llvmcall_load(p::Ptr{Int32}) = Base.llvmcall(""" %v = load i32, i32* %p, align 4 ret i32 %v""", Int32, Tuple{Ptr{Int32}}, p) i_llvmcall_ptr(p::Ptr{Int32}) = Base.llvmcall("%q = add i64 %0, 4\nret i64 %q", Ptr{Int32}, Tuple{Ptr{Int32}}, p) +# (a struct of fields of one type, which Base.llvmcall passes as an LLVM array) +struct IPair; a::Int64; b::Int64; end +i_llvmcall_struct(p::IPair) = Base.llvmcall(""" + %a = extractvalue [2 x i64] %0, 0 + %b = extractvalue [2 x i64] %0, 1 + %s = add i64 %a, %b + ret i64 %s""", Int64, Tuple{IPair}, p) i_llvmcall_ptrs(v::Vector{Int32}) = GC.@preserve v (i_llvmcall_load(pointer(v)), i_llvmcall_ptr(pointer(v)) - pointer(v)) i_poly(x) = 3x^2 - 2x + 1 i_loop(n) = (s = 0; for i in 1:n; s += i; end; s) @@ -123,6 +130,7 @@ end test_ir(i_fast, (Float32, Float32)) end @cgtest i_llvmcall_ptrs(Int32[7, 8]) + @cgtest i_llvmcall_struct(IPair(3, 4)) end @testset "code" begin From 6c0cce746edcd12cbb1fe00a582ac613d057a759 Mon Sep 17 00:00:00 2001 From: Valentin Churavy Date: Tue, 20 Oct 2026 02:14:32 +0200 Subject: [PATCH 24/27] Objects' globals named as native code's, small-tag types from jl_small_typeof The globals that hold the addresses of objects are named as native code's (julia_pgv): +Mod.T# for types, -Mod.f# for methods and method instances, jl_sym#s# for symbols and jl_global# for others, numbered, and carry the julia.constgv metadata; types with a small tag are read from their entry in the runtime's jl_small_typeof (literal_pointer_val_slot). GPUCompiler derives its relocation names from these, and resolves the small type table. Assisted-by: Claude Code (Opus 5.5) --- src/constants.jl | 37 +++++++++++++++++++++++++++++++++---- test/walker.jl | 2 +- 2 files changed, 34 insertions(+), 5 deletions(-) diff --git a/src/constants.jl b/src/constants.jl index 8c6cfbf..1c865a1 100644 --- a/src/constants.jl +++ b/src/constants.jl @@ -9,21 +9,50 @@ # addresses of objects. """ - JuliaCodegen.literal_global(cgm, x) -> LLVM.GlobalVariable + JuliaCodegen.literal_global(cgm, x) -> LLVM.Constant -The global of `cgm` that holds the address of the object `x`: for `true`, `false`, -`nothing`, `()` and `Core.svec()`, the runtime's own (`jl_true`, ...), as native code's. +The global of `cgm` that holds the address of the object `x`, as native code's +(`literal_pointer_val_slot`): for `true`, `false`, `nothing`, `()` and `Core.svec()`, the +runtime's own (`jl_true`, ...); for types with a small tag, their entry in the runtime's +`jl_small_typeof`; for other objects, a global of the module, named as native code's. """ function literal_global(cgm::CGModule, @nospecialize x) name = runtime_object_name(x) name === nothing || return runtime_object_global(cgm, name) + st = smalltag(cgm.config, x) + if x isa DataType && st != 0 + table = runtime_global(cgm.mod, :jl_small_typeof, LLVM.Int8Type()) + return LLVM.const_inbounds_gep(LLVM.Int8Type(), table, + LLVM.Constant[LLVM.ConstantInt(LLVM.Int32Type(), st << 4)]) + end get!(cgm.literals, x) do - gv = LLVM.GlobalVariable(cgm.mod, T_ptr(), unique_name(cgm, "jl_global")) + gv = LLVM.GlobalVariable(cgm.mod, T_ptr(), literal_name(cgm, x)) LLVM.linkage!(gv, LLVM.API.LLVMExternalLinkage) + gv.metadata["julia.constgv"] = LLVM.MDNode(LLVM.Metadata[]) gv end end +# the name of the global of the object `x`, as native code's (`julia_pgv`): `+Mod.T#` for +# types, `-Mod.f#` for methods and their instances, `jl_sym#s#` for symbols and +# `jl_global#` for other objects, numbered +function literal_name(cgm::CGModule, @nospecialize x) + qualified(mod, name) = join((fullname(mod)..., name), '.') + prefix = if x isa DataType + string("+", qualified(x.name.module, x.name.name), "#") + elseif x isa Method + string("-", qualified(x.module, x.name), "#") + elseif x isa Core.MethodInstance && x.def isa Method + string("-", qualified(x.def.module, x.def.name), "#") + elseif x isa Symbol + string("jl_sym#", x, "#") + else + "jl_global#" + end + cgm.counter += 1 + return string(prefix, cgm.counter) +end + # The objects the runtime has globals of, which native code refers to by those # (`global_jlvalue_to_llvm` in codegen.cpp): GPU compilers relocate them by name. const RUNTIME_OBJECTS = (true => "jl_true", false => "jl_false", nothing => "jl_nothing", diff --git a/test/walker.jl b/test/walker.jl index 043c1c5..5521dcc 100644 --- a/test/walker.jl +++ b/test/walker.jl @@ -56,7 +56,7 @@ end # objects are referenced through globals, not by address ir = test_ir(w_constant_string, ()) @test @filecheck begin - @check "@jl_global_{{[0-9]+}} = external global ptr" + @check "@\"jl_global#{{[0-9]+}}\" = external global ptr" @check_not "inttoptr (i64 {{[0-9]+}} to ptr)" print(ir) end From e04207a58b11a1f8e9d0091c1623c79d7e055405 Mon Sep 17 00:00:00 2001 From: Valentin Churavy Date: Tue, 20 Oct 2026 02:45:35 +0200 Subject: [PATCH 25/27] specsig: union results, as native code A union whose members carry data is returned as native code's union results: the box, or for a member without references the type index and its data in the buffer union_bytes_return (with UNION_BOX_MARKER for a box); a union of singletons as its type index; others boxed. Both the specsig entries and calls of specsig functions (native code's, from cfunction and jlcall entries) use it. From Julia 1.14 on, native code also returns members with references unboxed, with their roots (JuliaLang/julia#55045): such unions are Unsupported, called in the jlcall convention. Assisted-by: Claude Code (Opus 5.5) --- src/specsig.jl | 104 ++++++++++++++++++++++++++++++++++++++++++++-- test/cfunction.jl | 5 ++- test/specsig.jl | 23 ++++++++-- 3 files changed, 124 insertions(+), 8 deletions(-) diff --git a/src/specsig.jl b/src/specsig.jl index 8791dfe..e17cc2f 100644 --- a/src/specsig.jl +++ b/src/specsig.jl @@ -21,7 +21,8 @@ A function signature in Julia's native specialized calling convention: how each argument is passed (`nothing` for ghosts, which aren't), how the result is returned (`:void`, -`:value`, `:boxed` or `:sret`), whether the pgcstack is passed (`gcstack`, then in the +`:value`, `:boxed`, `:sret`, or for unions, `:union`, the box or the type index and the +data in a buffer, or `:ghosts`, the type index of a union of singletons), whether the pgcstack is passed (`gcstack`, then in the Swift calling convention), the LLVM function type and the return and parameter attributes. """ @@ -44,6 +45,20 @@ ref_attributes(@nospecialize T) = LLVM.Attribute[nocapture(), attr("noundef"), attr("nonnull"), attr("align", Base.datatype_alignment(T)), attr("dereferenceable", sizeof(T))] +# The members of the union `U` that native code's union results return unboxed, in the +# order of their type indices (from 1): those without references (`for_each_uniontype_small`) +union_return_members(@nospecialize U) = Any[M for M in Base.uniontypes(U) if union_member_ok(M; bits=true)] + +# the size and alignment of the buffer of a union result of type `U`, and whether all its +# members are returned unboxed (native `union_alloca_type`) +function union_return_layout(@nospecialize U) + ms = union_return_members(U) + data = filter(M -> !is_singleton_type(M), ms) + nbytes = maximum(sizeof, data; init=0) + align = min(maximum(Base.datatype_alignment, data; init=0), 16) + return nbytes, align, length(ms) == length(Base.uniontypes(U)) && length(ms) < 128 +end + # as native `deserves_sret` deserves_sret(cgm::CGModule, @nospecialize(T), ty::LLVM.LLVMType) = sizeof(T) > cgm.config.target.pointer_size && @@ -77,7 +92,27 @@ function specsig_abi(cgm::CGModule, argtypes::Vector{Any}, @nospecialize(rettype ret, rty = :boxed, T_tracked() push!(retattrs, attr("nonnull")) elseif rk === UnionVal - unsupported("the specsig convention for a result of the union ", rettype) + # (from Julia 1.14 on, native code also returns members with references unboxed, + # with their roots, JuliaLang/julia#55045) + cgm.config.dialect.minor >= v"1.14" && + any(M -> !union_member_ok(M; bits=true), union_members(rettype)) && + unsupported("the specsig convention for a result of the union ", rettype, + ", whose members have references") + nbytes, align, allunbox = union_return_layout(rettype) + if nbytes > 0 + # `{box or null, type index}`, the data of an unboxed member in the buffer + # `union_bytes_return` + ret, rty = :union, LLVM.StructType([T_tracked(), LLVM.Int8Type()]) + push!(params, T_ptr()) + push!(paramattrs, LLVM.Attribute[attr("noalias"), nocapture(), attr("noundef"), + attr("nonnull"), attr("align", align), + attr("dereferenceable", nbytes)]) + elseif allunbox + ret, rty = :ghosts, LLVM.Int8Type() + else + ret, rty = :boxed, T_tracked() + push!(retattrs, attr("nonnull")) + end else has_references(rettype) && unsupported("the specsig convention for a result of ", rettype, ", which has references") @@ -163,7 +198,7 @@ function emit_specsig_wrapper!(cgm::CGModule, info::FuncInfo, name::AbstractStri fc = FnCtx(cgm, info, nothing, b, top) debug_function!(fc, f) ps = LLVM.parameters(f) - p = sig.ret === :sret ? 2 : 1 + p = sig.ret in (:sret, :union) ? 2 : 1 if sig.gcstack fc.pgcstack = ps[p] p += 1 @@ -196,6 +231,15 @@ function emit_specsig_wrapper!(cgm::CGModule, info::FuncInfo, name::AbstractStri repr_kind(info.rettype) === Bottom ? LLVM.unreachable!(b) : LLVM.ret!(b) elseif repr_kind(info.rettype) === Ghost LLVM.ret!(b, emit_box(fc, ghost(info.rettype, something(ghost_value(info.rettype))))) + elseif repr_kind(info.rettype) === UnionVal + # (which may box the result) + if sig.gcstack + fc.current_task = current_task!(b, config(fc).runtime, fc.pgcstack) + else + emit_prologue!(fc; safepoint=false) + end + LLVM.ret!(b, union_return(fc, sig, unboxed_union(info.rettype, r), + sig.ret === :union ? ps[1] : nothing)) else LLVM.ret!(b, r) end @@ -218,6 +262,10 @@ function emit_specsig_call!(fc::FnCtx, sig::SpecSig, callee::LLVM.Value, args::V if sig.ret === :sret slot = entry_alloca!(fc, layout(fc, rt).llvm; align=Base.datatype_alignment(rt)) push!(ops, slot) + elseif sig.ret === :union + nbytes, align, _ = union_return_layout(rt) + slot = entry_alloca!(fc, LLVM.ArrayType(LLVM.Int8Type(), nbytes); align) + push!(ops, slot) end sig.gcstack && push!(ops, fc.pgcstack) for (a, T, k) in zip(args, sig.argtypes, sig.args) @@ -237,6 +285,56 @@ function emit_specsig_call!(fc::FnCtx, sig::SpecSig, callee::LLVM.Value, args::V k === Bottom && return emit_unreachable!(fc) k === Ghost && return ghost(rt, something(ghost_value(rt))) sig.ret === :boxed && return boxed(rt, r) + sig.ret in (:union, :ghosts) && return union_result(fc, sig, r, slot) sig.ret === :sret && return inline(rt, tbaa!(fc, LLVM.load!(b, layout(fc, rt).llvm, slot), :stack)) return inline(rt, r) end + +# the union value `v` returned in the convention of `sig`, with the buffer `buf` of the +# data of `:union`: of a member returned unboxed, its type index (and data), else its box +# and `UNION_BOX_MARKER` +function union_return(fc::FnCtx, sig::SpecSig, v::CGVal, buf) + b = fc.builder + U = v.typ + sig.ret === :boxed && return emit_box(fc, v) + ms = union_return_members(U) + # (the type indices of `v` and of the result agree when every member is returned + # unboxed) + sig.ret === :ghosts && return union_tindex_value(fc, v) + rty = LLVM.return_type(sig.ft) + pack(data, t) = LLVM.insert_value!(b, LLVM.insert_value!(b, LLVM.UndefValue(rty), data, 0), t, 1) + return union_switch(fc, v, rty; boxed=() -> pack(union_box_value(fc, v), i8(UNION_BOX_MARKER))) do M + k = findfirst(m -> m === M, ms) + k === nothing && return pack(emit_box(fc, union_member(fc, v, M)), i8(UNION_BOX_MARKER)) + if !is_singleton_type(M) + st = LLVM.store!(b, union_member(fc, v, M).V, buf) + LLVM.alignment!(st, Base.datatype_alignment(M)) + end + pack(LLVM.null(T_tracked()), i8(k)) + end +end + +# the union value of the result `r` of a call in the convention of `sig`, with the buffer +# `buf` of the data of `:union` (the inverse of `union_return`) +function union_result(fc::FnCtx, sig::SpecSig, r::LLVM.Value, buf) + b = fc.builder + U = sig.rettype + ms = union_return_members(U) + unboxed(t) = tindex_switch(fc, t, ms, union_type(U); name="union_result") do _, M + v = if is_singleton_type(M) + ghost(M, something(ghost_value(M))) + else + ld = LLVM.load!(b, value_type(fc, M), buf) + LLVM.alignment!(ld, Base.datatype_alignment(M)) + inline(M, ld) + end + to_union(fc, v, U).V + end + sig.ret === :ghosts && return unboxed_union(U, unboxed(r)) + data = LLVM.extract_value!(b, r, 0) + t = LLVM.extract_value!(b, r, 1) + isboxed = LLVM.icmp!(b, LLVM.API.LLVMIntNE, LLVM.and!(b, t, i8(UNION_BOX_MARKER)), i8(0)) + v = emit_if(() -> unbox_union(fc, data, U).V, fc, isboxed, union_type(U); + name="union_result", otherwise=() -> unboxed(t)) + return unboxed_union(U, v) +end diff --git a/test/cfunction.jl b/test/cfunction.jl index 345d79c..c9dcdb9 100644 --- a/test/cfunction.jl +++ b/test/cfunction.jl @@ -83,11 +83,12 @@ end @check "ret double" ir end - # the jlcall convention for results it doesn't call in the specsig convention + # a union result in the specsig convention, as native code's: the type index, and the + # box or the data in a buffer @test @filecheck begin @check_label "define internal ptr addrspace(10) @jlcapi_cf_maybe" @check "@jl_get_abi_converter" - @check "call ptr addrspace(10) (ptr, ptr addrspace(10), ...) @julia.call(ptr %" + @check "call swiftcc { ptr addrspace(10), i8 } %" test_ir(cf_call_maybe, (Int,)) end end diff --git a/test/specsig.jl b/test/specsig.jl index 8575b97..9117c74 100644 --- a/test/specsig.jl +++ b/test/specsig.jl @@ -23,6 +23,10 @@ ss_throw(x) = throw(ArgumentError("ss_throw $x")) ss_vec(v::SS_V4) = map(x -> VecElement(x.value * 2f0), v) @noinline ss_vararg(xs...) = length(xs) ss_vararg2(a, xs...) = a + sum(xs) +# unions: data and singletons unboxed, other members boxed +ss_pick(c::Bool) = c ? 1 : "s" +ss_pick_refs(c::Bool) = c ? 1.5 : (1, "a") +ss_pick_boxed(c::Bool) = c ? nothing : "s" # The first function definition's header in native code for `f(::types...)`, without # names: the convention, the result and the parameters with their attributes. @@ -122,6 +126,11 @@ const SS_CASES = [ (ss_box, (Int,)), (ss_throw, (Int,)), (ss_vec, (SS_V4,)), # (varargs methods, with their arguments one by one) (ss_vararg2, (Int, Float64, Int8)), + # (union results) + (ss_id, (Union{Nothing,Int},)), (ss_id, (Union{Nothing,Missing},)), (ss_pick, (Bool,)), + (ss_pick_boxed, (Bool,)), + # (from Julia 1.14 on, native code returns members with references with their roots) + (VERSION < v"1.14-" ? [(ss_pick_refs, (Bool,))] : [])..., ] @testset "specsig" begin @@ -146,10 +155,11 @@ const SS_CASES = [ end @testset "unsupported" begin - # inline values with references are passed with their roots, unions returned with - # their payload separately + # inline values with references are passed with their roots, and from Julia 1.14 on, + # unions of them returned with their roots @test_throws JuliaCodegen.Unsupported specsig_header(ss_id, (SS_Ref,)) - @test_throws JuliaCodegen.Unsupported specsig_header(ss_id, (Union{Nothing,Int},)) + VERSION >= v"1.14-" && + @test_throws JuliaCodegen.Unsupported specsig_header(ss_pick_refs, (Bool,)) # (a signature that ends in `Vararg`: the jlcall convention) @dispose ctx=LLVM.Context() mod=LLVM.Module("x") begin cgm = JuliaCodegen.CGModule(mod, test_config()) @@ -180,7 +190,14 @@ end @cgtest run=run ss_box(10) @cgtest run=run ss_throw(11) @cgtest run=run ss_vec(map(VecElement, (1f0, 2f0, 3f0, 4f0))) + for c in (true, false) + @cgtest run=run ss_pick(c) + VERSION < v"1.14-" && @cgtest run=run ss_pick_refs(c) + @cgtest run=run ss_pick_boxed(c) + end end + @cgtest run=run_through_specsig ss_id(Union{Nothing,Int}[3][1]) + @cgtest run=run_through_specsig ss_id(Union{Nothing,Missing}[missing][1]) # (native code for these returns a constant, without code in the convention) @cgtest run=run_through_specsig ss_id(SS_Empty()) @cgtest run=run_through_specsig ss_id(nothing) From 46e3675c0d02634efcab846f1bd53137c6f11c98 Mon Sep 17 00:00:00 2001 From: Valentin Churavy Date: Tue, 20 Oct 2026 02:57:46 +0200 Subject: [PATCH 26/27] specsig: a union result keeps its box As native code, a union value that has a box (a constant, which unions keep boxed, JuliaLang/julia#55045) is returned as that box, with UNION_BOX_MARKER and its type index, rather than unboxed: jlcall entries returned new boxes of such constants. Assisted-by: Claude Code (Opus 5.5) --- src/specsig.jl | 18 +++++++++++++++--- test/specsig.jl | 4 +++- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/src/specsig.jl b/src/specsig.jl index e17cc2f..100cabe 100644 --- a/src/specsig.jl +++ b/src/specsig.jl @@ -291,8 +291,9 @@ function emit_specsig_call!(fc::FnCtx, sig::SpecSig, callee::LLVM.Value, args::V end # the union value `v` returned in the convention of `sig`, with the buffer `buf` of the -# data of `:union`: of a member returned unboxed, its type index (and data), else its box -# and `UNION_BOX_MARKER` +# data of `:union`: its box if it has one, else for a member returned unboxed, its type +# index (and data), else its box; a box with `UNION_BOX_MARKER` and the type index of its +# member, if returned unboxed (0 if not) function union_return(fc::FnCtx, sig::SpecSig, v::CGVal, buf) b = fc.builder U = v.typ @@ -303,7 +304,7 @@ function union_return(fc::FnCtx, sig::SpecSig, v::CGVal, buf) sig.ret === :ghosts && return union_tindex_value(fc, v) rty = LLVM.return_type(sig.ft) pack(data, t) = LLVM.insert_value!(b, LLVM.insert_value!(b, LLVM.UndefValue(rty), data, 0), t, 1) - return union_switch(fc, v, rty; boxed=() -> pack(union_box_value(fc, v), i8(UNION_BOX_MARKER))) do M + unboxed() = union_switch(fc, v, rty; boxed=() -> pack(union_box_value(fc, v), i8(UNION_BOX_MARKER))) do M k = findfirst(m -> m === M, ms) k === nothing && return pack(emit_box(fc, union_member(fc, v, M)), i8(UNION_BOX_MARKER)) if !is_singleton_type(M) @@ -312,6 +313,17 @@ function union_return(fc::FnCtx, sig::SpecSig, v::CGVal, buf) end pack(LLVM.null(T_tracked()), i8(k)) end + union_has_box(U) || return unboxed() + return emit_if(fc, union_isboxed(fc, v), rty; name="union_return", otherwise=unboxed) do + t = union_tindex_value(fc, v) + k = i8(0) + for (i, M) in enumerate(union_members(U)) + j = findfirst(m -> m === M, ms) + j === nothing && continue + k = LLVM.select!(b, LLVM.icmp!(b, LLVM.API.LLVMIntEQ, t, i8(i)), i8(j), k) + end + pack(union_box_value(fc, v), LLVM.or!(b, k, i8(UNION_BOX_MARKER))) + end end # the union value of the result `r` of a call in the convention of `sig`, with the buffer diff --git a/test/specsig.jl b/test/specsig.jl index 9117c74..ca66394 100644 --- a/test/specsig.jl +++ b/test/specsig.jl @@ -27,6 +27,7 @@ ss_vararg2(a, xs...) = a + sum(xs) ss_pick(c::Bool) = c ? 1 : "s" ss_pick_refs(c::Bool) = c ? 1.5 : (1, "a") ss_pick_boxed(c::Bool) = c ? nothing : "s" +ss_pick_const(c::Bool) = c ? 2.5 : nothing # (the constant keeps its box) # The first function definition's header in native code for `f(::types...)`, without # names: the convention, the result and the parameters with their attributes. @@ -128,7 +129,7 @@ const SS_CASES = [ (ss_vararg2, (Int, Float64, Int8)), # (union results) (ss_id, (Union{Nothing,Int},)), (ss_id, (Union{Nothing,Missing},)), (ss_pick, (Bool,)), - (ss_pick_boxed, (Bool,)), + (ss_pick_boxed, (Bool,)), (ss_pick_const, (Bool,)), # (from Julia 1.14 on, native code returns members with references with their roots) (VERSION < v"1.14-" ? [(ss_pick_refs, (Bool,))] : [])..., ] @@ -194,6 +195,7 @@ end @cgtest run=run ss_pick(c) VERSION < v"1.14-" && @cgtest run=run ss_pick_refs(c) @cgtest run=run ss_pick_boxed(c) + @cgtest run=run ss_pick_const(c) end end @cgtest run=run_through_specsig ss_id(Union{Nothing,Int}[3][1]) From d58890bc1257a5aad647a4b279649a7727cae526 Mon Sep 17 00:00:00 2001 From: Valentin Churavy Date: Tue, 20 Oct 2026 10:26:35 +0200 Subject: [PATCH 27/27] specsig: union results with their roots, as native code from Julia 1.14 on From Julia 1.14 on (JuliaLang/julia#55045), native code's union results also return members with references unboxed: their bytes but the references in the `union_bytes_return` buffer, their references (in the order of their offsets) in a `return_roots` argument with the `julia.return_roots` attribute, which GC lowering roots in the caller's null-initialized stack slots. A member that is only references is returned in the roots alone, with a buffer of their size. The type indices are those of all inline members. Keyed on the dialect's `gc_return_roots === :attribute`, as JuliaIR.jl's GC lowering reads that attribute. Such unions were `Unsupported` on Julia 1.14 and later. Assisted-by: Claude Code (Opus 5.5) --- src/specsig.jl | 133 +++++++++++++++++++++++++++++++++++------------- test/specsig.jl | 29 +++++++---- 2 files changed, 118 insertions(+), 44 deletions(-) diff --git a/src/specsig.jl b/src/specsig.jl index 100cabe..c47a291 100644 --- a/src/specsig.jl +++ b/src/specsig.jl @@ -9,9 +9,12 @@ # and other inline values by a `ptr addrspace(11)` reference. Inline results larger than # a pointer (but floating point and vector values) are returned through `sret`. # +# Union results are returned as `{box or null, type index}`, with the data of a member +# returned unboxed in a buffer argument (and from Julia 1.14 on, its references in a +# separate roots argument). +# # Not handled yet: inline values with references to objects, which native code passes and -# returns with their roots in separate arguments, and union results, which it returns as -# a union struct with the payload in a separate argument. +# returns with their roots in separate arguments. "How an argument is passed in the specsig convention." @enum SpecArg SpecValue SpecBoxed SpecByRef @@ -22,15 +25,17 @@ A function signature in Julia's native specialized calling convention: how each argument is passed (`nothing` for ghosts, which aren't), how the result is returned (`:void`, `:value`, `:boxed`, `:sret`, or for unions, `:union`, the box or the type index and the -data in a buffer, or `:ghosts`, the type index of a union of singletons), whether the pgcstack is passed (`gcstack`, then in the -Swift calling convention), the LLVM function type and the return and parameter -attributes. +data in a buffer, or `:ghosts`, the type index of a union of singletons), the number of +references of a union member returned in the roots argument (`return_roots`, 0 without +one), whether the pgcstack is passed (`gcstack`, then in the Swift calling convention), +the LLVM function type and the return and parameter attributes. """ struct SpecSig argtypes::Vector{Any} rettype::Any args::Vector{Union{Nothing,SpecArg}} ret::Symbol + return_roots::Int gcstack::Bool ft::LLVM.FunctionType retattrs::Vector{LLVM.Attribute} @@ -45,18 +50,33 @@ ref_attributes(@nospecialize T) = LLVM.Attribute[nocapture(), attr("noundef"), attr("nonnull"), attr("align", Base.datatype_alignment(T)), attr("dereferenceable", sizeof(T))] +# Whether union results return members with references unboxed, their references in a +# roots argument (from Julia 1.14 on, JuliaLang/julia#55045, with the attribute that tells +# GC lowering about them) +union_returns_roots(cgm::CGModule) = cgm.config.dialect.gc_return_roots === :attribute + # The members of the union `U` that native code's union results return unboxed, in the -# order of their type indices (from 1): those without references (`for_each_uniontype_small`) -union_return_members(@nospecialize U) = Any[M for M in Base.uniontypes(U) if union_member_ok(M; bits=true)] +# order of their type indices (from 1; `for_each_uniontype_small`): the inline ones, or +# before Julia 1.14, those without references +union_return_members(cgm::CGModule, @nospecialize U) = + union_returns_roots(cgm) ? union_members(U) : + Any[M for M in Base.uniontypes(U) if union_member_ok(M; bits=true)] -# the size and alignment of the buffer of a union result of type `U`, and whether all its -# members are returned unboxed (native `union_alloca_type`) -function union_return_layout(@nospecialize U) - ms = union_return_members(U) - data = filter(M -> !is_singleton_type(M), ms) +# the size and alignment of the buffer of a union result of type `U`, the number of roots +# of its members, and whether all its members are returned unboxed (native +# `union_alloca_type`, and `get_specsig_function`'s buffer for members that are only +# references) +function union_return_layout(cgm::CGModule, @nospecialize U) + ms = union_return_members(cgm, U) + data = filter(M -> !is_singleton_type(M) && !allpointers(M), ms) nbytes = maximum(sizeof, data; init=0) align = min(maximum(Base.datatype_alignment, data; init=0), 16) - return nbytes, align, length(ms) == length(Base.uniontypes(U)) && length(ms) < 128 + nroots = maximum((npointers(M) for M in ms if !is_singleton_type(M)); init=0) + if nbytes == 0 && nroots > 0 + nbytes = nroots * cgm.config.target.pointer_size + align = cgm.config.target.pointer_size + end + return nbytes, align, nroots, length(ms) == length(Base.uniontypes(U)) && length(ms) < 128 end # as native `deserves_sret` @@ -84,6 +104,7 @@ function specsig_abi(cgm::CGModule, argtypes::Vector{Any}, @nospecialize(rettype paramattrs = Vector{LLVM.Attribute}[] retattrs = LLVM.Attribute[] rk = repr_kind(rettype) + return_roots = 0 # (a ghost that isn't a singleton object, a `Type{T}` with a unique representation, is # returned boxed) if rk === Bottom || (rk === Ghost && is_singleton_type(rettype)) @@ -92,13 +113,7 @@ function specsig_abi(cgm::CGModule, argtypes::Vector{Any}, @nospecialize(rettype ret, rty = :boxed, T_tracked() push!(retattrs, attr("nonnull")) elseif rk === UnionVal - # (from Julia 1.14 on, native code also returns members with references unboxed, - # with their roots, JuliaLang/julia#55045) - cgm.config.dialect.minor >= v"1.14" && - any(M -> !union_member_ok(M; bits=true), union_members(rettype)) && - unsupported("the specsig convention for a result of the union ", rettype, - ", whose members have references") - nbytes, align, allunbox = union_return_layout(rettype) + nbytes, align, nroots, allunbox = union_return_layout(cgm, rettype) if nbytes > 0 # `{box or null, type index}`, the data of an unboxed member in the buffer # `union_bytes_return` @@ -107,6 +122,16 @@ function specsig_abi(cgm::CGModule, argtypes::Vector{Any}, @nospecialize(rettype push!(paramattrs, LLVM.Attribute[attr("noalias"), nocapture(), attr("noundef"), attr("nonnull"), attr("align", align), attr("dereferenceable", nbytes)]) + if nroots > 0 + # the references of an unboxed member, in the order of their offsets + return_roots = nroots + ps = cgm.config.target.pointer_size + push!(params, T_ptr()) + push!(paramattrs, LLVM.Attribute[attr("noalias"), nocapture(), attr("noundef"), + LLVM.StringAttribute("julia.return_roots", string(nroots)), + attr("nonnull"), attr("align", ps), + attr("dereferenceable", nroots * ps)]) + end elseif allunbox ret, rty = :ghosts, LLVM.Int8Type() else @@ -158,7 +183,7 @@ function specsig_abi(cgm::CGModule, argtypes::Vector{Any}, @nospecialize(rettype push!(paramattrs, ext === nothing ? LLVM.Attribute[] : LLVM.Attribute[attr(ext)]) end end - return SpecSig(argtypes, rettype, args, ret, gcstack_arg, LLVM.FunctionType(rty, params), + return SpecSig(argtypes, rettype, args, ret, return_roots, gcstack_arg, LLVM.FunctionType(rty, params), retattrs, paramattrs) end @@ -198,7 +223,7 @@ function emit_specsig_wrapper!(cgm::CGModule, info::FuncInfo, name::AbstractStri fc = FnCtx(cgm, info, nothing, b, top) debug_function!(fc, f) ps = LLVM.parameters(f) - p = sig.ret in (:sret, :union) ? 2 : 1 + p = 1 + (sig.ret in (:sret, :union)) + (sig.return_roots > 0) if sig.gcstack fc.pgcstack = ps[p] p += 1 @@ -239,7 +264,8 @@ function emit_specsig_wrapper!(cgm::CGModule, info::FuncInfo, name::AbstractStri emit_prologue!(fc; safepoint=false) end LLVM.ret!(b, union_return(fc, sig, unboxed_union(info.rettype, r), - sig.ret === :union ? ps[1] : nothing)) + sig.ret === :union ? ps[1] : nothing, + sig.return_roots > 0 ? ps[2] : nothing)) else LLVM.ret!(b, r) end @@ -258,14 +284,18 @@ function emit_specsig_call!(fc::FnCtx, sig::SpecSig, callee::LLVM.Value, args::V b = fc.builder ops = LLVM.Value[] rt = sig.rettype - slot = nothing + slot = roots = nothing if sig.ret === :sret slot = entry_alloca!(fc, layout(fc, rt).llvm; align=Base.datatype_alignment(rt)) push!(ops, slot) elseif sig.ret === :union - nbytes, align, _ = union_return_layout(rt) + nbytes, align, _ = union_return_layout(fc.cgm, rt) slot = entry_alloca!(fc, LLVM.ArrayType(LLVM.Int8Type(), nbytes); align) push!(ops, slot) + if sig.return_roots > 0 + roots = roots_alloca!(fc, sig.return_roots) + push!(ops, roots) + end end sig.gcstack && push!(ops, fc.pgcstack) for (a, T, k) in zip(args, sig.argtypes, sig.args) @@ -285,20 +315,33 @@ function emit_specsig_call!(fc::FnCtx, sig::SpecSig, callee::LLVM.Value, args::V k === Bottom && return emit_unreachable!(fc) k === Ghost && return ghost(rt, something(ghost_value(rt))) sig.ret === :boxed && return boxed(rt, r) - sig.ret in (:union, :ghosts) && return union_result(fc, sig, r, slot) + sig.ret in (:union, :ghosts) && return union_result(fc, sig, r, slot, roots) sig.ret === :sret && return inline(rt, tbaa!(fc, LLVM.load!(b, layout(fc, rt).llvm, slot), :stack)) return inline(rt, r) end +# a stack slot for `n` references returned by a call, null-initialized (a GC frame slot +# for GC lowering, native `emit_static_roots`) +function roots_alloca!(fc::FnCtx, n::Int) + b = fc.builder + ps = config(fc).target.pointer_size + LLVM.position!(b, top_insertion_point(fc)) do + a = LLVM.array_alloca!(b, T_tracked(), LLVM.ConstantInt(LLVM.Int32Type(), n)) + LLVM.alignment!(a, ps) + tbaa!(fc, LLVM.memset!(b, a, i8(0), LLVM.ConstantInt(iptr_type(fc), n * ps), ps), :gcframe) + a + end +end + # the union value `v` returned in the convention of `sig`, with the buffer `buf` of the -# data of `:union`: its box if it has one, else for a member returned unboxed, its type -# index (and data), else its box; a box with `UNION_BOX_MARKER` and the type index of its -# member, if returned unboxed (0 if not) -function union_return(fc::FnCtx, sig::SpecSig, v::CGVal, buf) +# data of `:union` and the roots argument `roots`: its box if it has one, else for a +# member returned unboxed, its type index (and data and references), else its box; a box +# with `UNION_BOX_MARKER` and the type index of its member, if returned unboxed (0 if not) +function union_return(fc::FnCtx, sig::SpecSig, v::CGVal, buf, roots) b = fc.builder U = v.typ sig.ret === :boxed && return emit_box(fc, v) - ms = union_return_members(U) + ms = union_return_members(fc.cgm, U) # (the type indices of `v` and of the result agree when every member is returned # unboxed) sig.ret === :ghosts && return union_tindex_value(fc, v) @@ -307,7 +350,18 @@ function union_return(fc::FnCtx, sig::SpecSig, v::CGVal, buf) unboxed() = union_switch(fc, v, rty; boxed=() -> pack(union_box_value(fc, v), i8(UNION_BOX_MARKER))) do M k = findfirst(m -> m === M, ms) k === nothing && return pack(emit_box(fc, union_member(fc, v, M)), i8(UNION_BOX_MARKER)) - if !is_singleton_type(M) + if is_singleton_type(M) + elseif npointers(M) > 0 + # (a split value: its bytes but the references, then the references) + rs = LLVM.Value[] + split_store!(fc, union_member(fc, v, M).V, M, allpointers(M) ? nothing : buf, rs) + ps = config(fc).target.pointer_size + for (i, r) in enumerate(rs) + st = LLVM.store!(b, r, LLVM.gep!(b, LLVM.Int8Type(), roots, [iptr(fc, (i - 1) * ps)])) + LLVM.alignment!(st, ps) + tbaa!(fc, st, :gcframe) + end + else st = LLVM.store!(b, union_member(fc, v, M).V, buf) LLVM.alignment!(st, Base.datatype_alignment(M)) end @@ -327,14 +381,23 @@ function union_return(fc::FnCtx, sig::SpecSig, v::CGVal, buf) end # the union value of the result `r` of a call in the convention of `sig`, with the buffer -# `buf` of the data of `:union` (the inverse of `union_return`) -function union_result(fc::FnCtx, sig::SpecSig, r::LLVM.Value, buf) +# `buf` of the data of `:union` and the roots `roots` (the inverse of `union_return`) +function union_result(fc::FnCtx, sig::SpecSig, r::LLVM.Value, buf, roots) b = fc.builder U = sig.rettype - ms = union_return_members(U) + ms = union_return_members(fc.cgm, U) unboxed(t) = tindex_switch(fc, t, ms, union_type(U); name="union_result") do _, M v = if is_singleton_type(M) ghost(M, something(ghost_value(M))) + elseif npointers(M) > 0 + ps = config(fc).target.pointer_size + rs = LLVM.Value[] + for i in 1:npointers(M) + ld = LLVM.load!(b, T_tracked(), LLVM.gep!(b, LLVM.Int8Type(), roots, [iptr(fc, (i - 1) * ps)])) + LLVM.alignment!(ld, ps) + push!(rs, tbaa!(fc, ld, :gcframe)) + end + inline(M, split_load(fc, M, allpointers(M) ? nothing : buf, rs)) else ld = LLVM.load!(b, value_type(fc, M), buf) LLVM.alignment!(ld, Base.datatype_alignment(M)) diff --git a/test/specsig.jl b/test/specsig.jl index ca66394..fc090e6 100644 --- a/test/specsig.jl +++ b/test/specsig.jl @@ -23,9 +23,12 @@ ss_throw(x) = throw(ArgumentError("ss_throw $x")) ss_vec(v::SS_V4) = map(x -> VecElement(x.value * 2f0), v) @noinline ss_vararg(xs...) = length(xs) ss_vararg2(a, xs...) = a + sum(xs) -# unions: data and singletons unboxed, other members boxed +# unions: data and singletons unboxed, other members boxed (before Julia 1.14, also +# those with references) ss_pick(c::Bool) = c ? 1 : "s" ss_pick_refs(c::Bool) = c ? 1.5 : (1, "a") +ss_pick_mid(c::Bool) = c ? Int8(1) : (Int8(2), "a", Int16(3)) # (a reference between data) +ss_pick_ptrs(c::Bool) = c ? nothing : ("a", :b) # (only references) ss_pick_boxed(c::Bool) = c ? nothing : "s" ss_pick_const(c::Bool) = c ? 2.5 : nothing # (the constant keeps its box) @@ -129,9 +132,8 @@ const SS_CASES = [ (ss_vararg2, (Int, Float64, Int8)), # (union results) (ss_id, (Union{Nothing,Int},)), (ss_id, (Union{Nothing,Missing},)), (ss_pick, (Bool,)), - (ss_pick_boxed, (Bool,)), (ss_pick_const, (Bool,)), - # (from Julia 1.14 on, native code returns members with references with their roots) - (VERSION < v"1.14-" ? [(ss_pick_refs, (Bool,))] : [])..., + (ss_pick_boxed, (Bool,)), (ss_pick_const, (Bool,)), (ss_pick_refs, (Bool,)), + (ss_pick_mid, (Bool,)), (ss_pick_ptrs, (Bool,)), ] @testset "specsig" begin @@ -153,14 +155,21 @@ const SS_CASES = [ ir end end + # from Julia 1.14 on, the references of a union member are returned in a roots + # argument, which GC lowering knows by its attribute + if test_config().dialect.gc_return_roots === :attribute + @test @filecheck begin + @check "define swiftcc { ptr addrspace(10), i8 } @ss_entry(ptr {{.*}}dereferenceable(16) %0, ptr {{.*}}dereferenceable(16) \"julia.return_roots\"=\"2\" %1," + @check "store ptr addrspace(10) {{%.*}}, ptr {{%.*}}" + @check "store ptr addrspace(10) {{%.*}}, ptr {{%.*}}" + specsig_ir(ss_pick_ptrs, (Bool,)) + end + end end @testset "unsupported" begin - # inline values with references are passed with their roots, and from Julia 1.14 on, - # unions of them returned with their roots + # inline values with references are passed with their roots @test_throws JuliaCodegen.Unsupported specsig_header(ss_id, (SS_Ref,)) - VERSION >= v"1.14-" && - @test_throws JuliaCodegen.Unsupported specsig_header(ss_pick_refs, (Bool,)) # (a signature that ends in `Vararg`: the jlcall convention) @dispose ctx=LLVM.Context() mod=LLVM.Module("x") begin cgm = JuliaCodegen.CGModule(mod, test_config()) @@ -193,7 +202,9 @@ end @cgtest run=run ss_vec(map(VecElement, (1f0, 2f0, 3f0, 4f0))) for c in (true, false) @cgtest run=run ss_pick(c) - VERSION < v"1.14-" && @cgtest run=run ss_pick_refs(c) + @cgtest run=run ss_pick_refs(c) + @cgtest run=run ss_pick_mid(c) + @cgtest run=run ss_pick_ptrs(c) @cgtest run=run ss_pick_boxed(c) @cgtest run=run ss_pick_const(c) end