From d567afeac8b4ea285e8801aac5502092bd710d58 Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Mon, 23 Nov 2026 23:00:15 +0100 Subject: [PATCH] Narrow Julia's signed-remainder guard to the overflowing pair Julia's codegen branches around `srem` for every divisor of -1, so that `typemin(T) % -1` returns 0. Keeping the `srem` conditional can block CSE, hoisting, and pairing with an `sdiv` of the same operands. Only `(typemin(T), -1)` overflows, so rewrite the guard on the unoptimized IR to test for that pair; LLVM then removes it whenever either operand rules the pair out, e.g. for a zero-extended index. Julia 1.15 does this itself since JuliaLang/julia#65218 (1.15.0-DEV.1007), so the rewrite only runs on older versions. In AcceleratedKernels' merge sort, merge_tile_kernel! goes from four `rem.s64` to one (451 -> 332 SASS instructions on sm_120) and merge_pass_kernel!'s remainder pairs with its division (400 -> 305). --- src/irgen.jl | 99 ++++++++++++++++++++++++++++++++++++++++++++++++++ test/native.jl | 80 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 179 insertions(+) diff --git a/src/irgen.jl b/src/irgen.jl index 6fafe3cc..15bdbcd1 100644 --- a/src/irgen.jl +++ b/src/irgen.jl @@ -165,6 +165,11 @@ function irgen(@nospecialize(job::CompilerJob)) # materialize `GPUCompiler.alloca` intrinsics as real entry-block allocas, before the # optimizer runs so the slots can be promoted (see `lower_alloca!`). lower_alloca!(job, mod) + + # Julia 1.15 emits the narrowed guard itself (JuliaLang/julia#65218) + @static if VERSION < v"1.15.0-DEV.1007" + narrow_srem_guards!(mod) + end end return mod, compiled, relocations @@ -1230,6 +1235,100 @@ function lower_debug_level!(@nospecialize(job::CompilerJob), mod::LLVM.Module) end +## signed remainder + +# `rem(x, y)` on signed integers must return 0 for `typemin(T) % -1`, where LLVM's `srem` +# overflows. Julia's codegen (`emit_checked_srem_int`) therefore skips the `srem` for every +# divisor of -1: +# +# %m1 = icmp eq iN %y, -1 +# br i1 %m1, label %minus1, label %oksrem +# minus1: +# br label %after +# oksrem: +# %r = srem iN %x, %y +# br label %after +# after: +# %v = phi iN [ 0, %minus1 ], [ %r, %oksrem ] +# +# Keeping the `srem` conditional can block CSE of identical remainders, hoisting, and pairing +# with an `sdiv` of the same operands. Only `(typemin(T), -1)` overflows, and +# `x % -1 == 0` for every other `x`, so we narrow the guard to that pair. LLVM then drops it +# whenever either operand rules the pair out (e.g. a zero-extended index), leaving a plain +# `srem`. This runs on Julia's unoptimized IR, where the pattern is still intact. +# +# Julia 1.15 emits the narrowed guard itself (JuliaLang/julia#65218), so this pass only runs +# on older versions and can go once those are no longer supported. +function narrow_srem_guards!(mod::LLVM.Module) + changed = false + @dispose builder=IRBuilder() begin + for f in mod.functions, bb in f.blocks + br = LLVM.terminator(bb) + br isa LLVM.BrInst && LLVM.isconditional(br) || continue + cond = LLVM.condition(br) + cond isa LLVM.ICmpInst && LLVM.predicate(cond) == LLVM.API.LLVMIntEQ || continue + y, minus1 = LLVM.operands(cond) + T = LLVM.value_type(y) + T isa LLVM.IntegerType && minus1 == LLVM.all_ones(T) || continue + + # the remainder block: only the `srem`, falling through to the join block + succ_m1, succ_rem = LLVM.successors(br) + insts = collect(LLVM.instructions(succ_rem)) + length(insts) == 2 || continue + r, jump = insts + r isa LLVM.Instruction && LLVM.opcode(r) == LLVM.API.LLVMSRem || continue + LLVM.operands(r)[2] == y || continue + jump isa LLVM.BrInst && !LLVM.isconditional(jump) || continue + join = only(LLVM.successors(jump)) + length(LLVM.predecessors(succ_rem)) == 1 || continue + + # the -1 edge reaches the join block directly or through an empty block + if succ_m1 == join + m1_pred = bb + elseif length(collect(LLVM.instructions(succ_m1))) == 1 && + LLVM.terminator(succ_m1) isa LLVM.BrInst && + !LLVM.isconditional(LLVM.terminator(succ_m1)) && + only(LLVM.successors(LLVM.terminator(succ_m1))) == join + m1_pred = succ_m1 + else + continue + end + + # the join block may only distinguish the two paths by the remainder, + # which is 0 on the -1 edge + ok = true + for phi in LLVM.instructions(join) + phi isa LLVM.PHIInst || break + v_m1 = v_rem = nothing + for (val, blk) in LLVM.incoming(phi) + blk == m1_pred && (v_m1 = val) + blk == succ_rem && (v_rem = val) + end + if v_m1 === nothing || v_rem === nothing + ok = false + elseif v_rem == r + ok &= v_m1 == LLVM.null(T) + else + ok &= v_m1 == v_rem + end + end + ok || continue + + # the -1 path didn't use `x`, which may thus be poison there, and branching on + # poison is UB. freeze it, and have the `srem` use the frozen value too. + position!(builder, LLVM.before(br)) + x = LLVM.freeze!(builder, LLVM.operands(r)[1]) + LLVM.operands(r)[1] = x + tmin = ConstantInt(T, big(1) << (LLVM.width(T) - 1)) + overflows = and!(builder, cond, icmp!(builder, LLVM.API.LLVMIntEQ, x, tmin)) + LLVM.condition!(br, overflows) + changed = true + end + end + return changed +end + + ## stack allocation # device code can request a fixed-size, per-workitem stack scratch buffer via diff --git a/test/native.jl b/test/native.jl index 380c96aa..64587c53 100644 --- a/test/native.jl +++ b/test/native.jl @@ -1268,6 +1268,86 @@ end end end +@testset "signed remainder" begin + mod = @eval module $(gensym()) + # an index is never `typemin`, so nothing guards the remainder + index_rem(i::UInt32, y::Int64) = rem(Int64(i), y) + + function rems!(out::Ptr{T}, xs::Ptr{T}, ys::Ptr{T}, n::Int) where {T} + for i in 1:n + unsafe_store!(out, rem(unsafe_load(xs, i), unsafe_load(ys, i)), i) + end + return + end + end + + @test @filecheck begin + @check_label "define {{.*}}index_rem" + @check_not "-1" + @check "srem i64" + @check_not "phi" + @check "ret i64" + Native.code_llvm(mod.index_rem, Tuple{UInt32, Int64}) + end + + # the rewrite itself: the guard tests the frozen numerator that the `srem` divides, and + # a join block that tells the two paths apart by anything else is left alone + function narrowed(extra_phi) + Context() do ctx + ir = parse(LLVM.Module, """ + define i64 @f(i64 %x, i64 %y, i64 %z) { + top: + %m1 = icmp eq i64 %y, -1 + br i1 %m1, label %minus1, label %oksrem + minus1: + br label %after + oksrem: + %r = srem i64 %x, %y + br label %after + after: + %v = phi i64 [ 0, %minus1 ], [ %r, %oksrem ] + $(extra_phi ? "%w = phi i64 [ %z, %minus1 ], [ 0, %oksrem ]" : "") + ret i64 %v + }""") + GPUCompiler.narrow_srem_guards!(ir) + string(ir) + end + end + @test @filecheck begin + @check "%[[X:.+]] = freeze i64 %x" + @check "icmp eq i64 %[[X]], -9223372036854775808" + @check "srem i64 %[[X]], %y" + narrowed(false) + end + @test @filecheck begin + @check_not "freeze" + @check "br i1 %m1" + narrowed(true) + end + + # only `typemin(T) % -1` overflows `srem`, and must still return 0 + for T in (Int8, Int16, Int32, Int64, Int128) + vals = T[typemin(T), typemin(T) + 1, -7, -1, 0, 1, 7, typemax(T)] + divs = filter(!iszero, vals) + xs = repeat(vals, outer=length(divs)) + ys = repeat(divs, inner=length(vals)) + out = similar(xs) + + job, _ = Native.create_job(mod.rems!, Tuple{Ptr{T}, Ptr{T}, Ptr{T}, Int}; + validate=false) + obj, entry = GPUCompiler.compile(:obj, job) do obj, meta + Vector{UInt8}(codeunits(obj)), meta.entry.name + end + fptr, lljit, _ = Native.load(obj, entry, GPUCompiler.Relocations()) + @dispose lljit=lljit begin + GC.@preserve out xs ys ccall(fptr, Cvoid, + (Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Int), + out, xs, ys, length(xs)) + end + @test out == rem.(xs, ys) + end +end + @testset "bounds checks against a fresh array" begin # the bound of a loop over a fresh array is the product of the sizes its constructor # stored; those have to be forwarded into the bounds checks before IndVarSimplify