Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 15 additions & 10 deletions src/mcgen.jl
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,27 @@
# Finalize the module for backend emission by collecting and lowering all live relocations.
function prepare_execution!(@nospecialize(job::CompilerJob), mod::LLVM.Module,
relocs::Relocations=Relocations())
# Clean up first so only live relocations get lowered.
function cleanup(; fold_instructions=false)
# This runs after target finalization (`finish_ir!`), whose output must reach the back-end
# as it is: e.g. index narrowing would be undone by InstCombine widening the arithmetic
# again. So only fold the loads from relocation slots (see `fold_merged_constant_loads!`),
# simplify instructions to existing values or constants, and drop what is dead (with ADCE,
# as the address `phi`s and `select`s of folded loads can form dead cycles that would keep
# the slots alive); nothing combines or canonicalizes instructions here.
function cleanup(; simplify=false)
@dispose pb=PassBuilder() begin
if fold_instructions
if simplify
add!(pb, FunctionPassManager()) do fpm
add!(fpm, instcombine_pass(job))
add!(fpm, InstSimplifyPass())
add!(fpm, ADCEPass())
end
end
add!(pb, RecomputeGlobalsAAPass())
add!(pb, GlobalOptPass())
add!(pb, GlobalDCEPass())
add!(pb, StripDeadPrototypesPass())
with_llvm_machine(job.config.target) do tm
run!(pb, mod, tm)
end
run!(pb, mod)
end
end

# Clean up first so only live relocations get lowered.
cleanup()
prune_dead_relocations!(mod, relocs)

Expand All @@ -43,7 +47,8 @@ function prepare_execution!(@nospecialize(job::CompilerJob), mod::LLVM.Module,
freeze!(relocs)

# Fold constants exposed by eager lowering, and drop globals the lowering left dead.
cleanup(; fold_instructions=true)
fold_merged_constant_loads!(mod)
cleanup(; simplify=true)

has_unresolved_cglobal_loads(mod, relocs) &&
error("Unresolved cglobal load after relocation lowering")
Expand Down
126 changes: 123 additions & 3 deletions src/relocation.jl
Original file line number Diff line number Diff line change
Expand Up @@ -585,13 +585,45 @@ function demote_boxed_constants!(@nospecialize(job::CompilerJob), mod::LLVM.Modu
can only be kept on the stack of a kernel.""")
box_alloca!(f, gv)
end
demoted = Set{LLVM.Function}()
for gv in boxes
slots = Dict{LLVM.Function, LLVM.Value}()
replace_global_with_local!(gv, f -> get!(() -> slot(f, gv), slots, f))
union!(demoted, keys(slots))
end

# A copy often only feeds the pointer half of an isbits union whose selector says it is
# unused, which back-ends then reject as a reference to a dead stack slot. Fold those
# away here, as nothing combines instructions after target finalization. This runs once:
# there are no boxes left for a later `finish_ir!` of another entry point.
combine_instructions!(job, demoted)
return true
end

# Fold away the references to boxed constants that are dead, e.g. in the pointer half of an
# isbits union whose selector says it is unused, for back-ends that cannot refer to them but
# where `demote_boxed_constants!` does not work (SPIR-V before LLVM 17). The boxes stay in
# the module, so with several entry points this runs again on their users for each.
function fold_dead_box_references!(@nospecialize(job::CompilerJob), mod::LLVM.Module)
users = Set{LLVM.Function}()
for gv in boxed_constants(mod)
using_functions!(users, gv)
end
combine_instructions!(job, users)
return
end

function combine_instructions!(@nospecialize(job::CompilerJob), fns)
isempty(fns) && return
@dispose pb=PassBuilder() begin
add!(pb, instcombine_pass(job))
for f in fns
run!(pb, f)
end
end
return
end

# Return the byte offset added by a constant cast or GEP, or `nothing` if it is not static.
function constexpr_byte_offset(ce::LLVM.ConstantExpr, dl::LLVM.DataLayout)
op = ce.opcode
Expand Down Expand Up @@ -851,6 +883,95 @@ function bake_relocations!(mod::LLVM.Module, relocs::Relocations)
return
end

# Fold the loads from constant globals that go through a `select` or `phi` of their addresses,
# as of relocation slots that `bake_relocations!` resolved, by selecting between the values.
# InstSimplify only folds loads that are direct; this runs after target finalization, where
# InstCombine (which would fold them all) must not, and back-ends cannot always take the
# loaded globals (e.g., the Khronos translator rejects private globals in address space 0).
function fold_merged_constant_loads!(mod::LLVM.Module)
changed = false
@dispose builder=IRBuilder() begin
for f in mod.functions, bb in f.blocks, inst in collect(bb.instructions)
inst isa LLVM.LoadInst && !inst.volatile || continue
T = inst.value_type
addr = inst.pointer_operand
addr isa LLVM.Instruction && forwarded_addresses(addr) !== nothing || continue
# (check everything first, so that nothing needs to be undone)
folds_to_constants(T, addr) || continue
value = merged_constant_value!(builder, T, addr, Dict{LLVM.Value,LLVM.Value}())
replace_uses!(inst, value)
erase!(inst)
changed = true
end
end
return changed
end

# The constant a load of type `T` from `gv` yields, if `gv` has an initializer that cannot
# be overridden (like a baked relocation slot), and holds a word of that type.
function constant_word(T::LLVMType, gv::LLVM.GlobalVariable)
gv.constant && !isdeclaration(gv) && !gv.externally_initialized || return nothing
gv.linkage in (LLVM.Linkage.Private, LLVM.Linkage.Internal) || return nothing
init = gv.initializer
S = init.value_type
S == T && is_word_type(T) && return init
if T isa LLVM.PointerType && S isa LLVM.IntegerType && is_word_type(S)
return const_inttoptr(init, T)
elseif T isa LLVM.IntegerType && S isa LLVM.PointerType && is_word_type(T)
return const_ptrtoint(init, T)
end
return nothing
end

# Whether every address that `addr` picks from is such a global.
function folds_to_constants(T::LLVMType, @nospecialize(addr), seen=Set{LLVM.Value}())
addr in seen && return true
push!(seen, addr)
if addr isa LLVM.ConstantExpr
addr.opcode in (LLVM.Opcode.BitCast, LLVM.Opcode.AddrSpaceCast) || return false
return folds_to_constants(T, addr.operands[1], seen)
elseif addr isa LLVM.GlobalVariable
return constant_word(T, addr) !== nothing
elseif addr isa LLVM.Instruction
forwarded = forwarded_addresses(addr)
forwarded === nothing && return false
return all(a -> folds_to_constants(T, a, seen), forwarded)
end
return false
end

# The value of type `T` loaded from `addr`, built with `select`s and `phi`s next to those of
# the addresses. Requires `folds_to_constants(T, addr)`.
function merged_constant_value!(builder::IRBuilder, T::LLVMType, @nospecialize(addr),
values::Dict{LLVM.Value,LLVM.Value})
haskey(values, addr) && return values[addr]
if addr isa LLVM.ConstantExpr || addr isa LLVM.BitCastInst ||
addr isa LLVM.AddrSpaceCastInst
return merged_constant_value!(builder, T, addr.operands[1], values)
elseif addr isa LLVM.GlobalVariable
return constant_word(T, addr)
elseif addr isa LLVM.SelectInst
# (create the select first, as cycles make it an operand of itself, with a placeholder
# that is not a constant so that the builder cannot fold it away)
position!(builder, LLVM.after(addr))
placeholder = LLVM.freeze!(builder, UndefValue(T))
sel = values[addr] = select!(builder, addr.operands[1], placeholder, placeholder)
sel.operands[2] = merged_constant_value!(builder, T, addr.operands[2], values)
sel.operands[3] = merged_constant_value!(builder, T, addr.operands[3], values)
erase!(placeholder)
return sel
elseif addr isa LLVM.PHIInst
# (create the phi first, as loops make it an incoming value of itself)
position!(builder, LLVM.before(addr))
phi = values[addr] = phi!(builder, T)
for (incoming, block) in addr.incoming
push!(phi.incoming, (merged_constant_value!(builder, T, incoming, values), block))
end
return phi
end
error("Unexpected address $addr")
end

"""
emit_patchable_relocations!(mod, relocs)

Expand Down Expand Up @@ -1095,9 +1216,8 @@ end

# Load the slots' values as the words the table holds. A pointer-typed load would read a
# host address as a pointer into the target's default address space, which on Metal is
# thread memory, and shader validation does not preserve such a value's bits. Converting
# the word back with `inttoptr` keeps the IR valid for existing users, while comparisons
# fold to integer ones.
# thread memory, and shader validation does not preserve such a value's bits. The word is
# converted back with `inttoptr`, which keeps the IR valid for existing users.
function load_relocation_words!(loads::Vector{LLVM.LoadInst}, T_word::LLVMType)
@dispose builder=IRBuilder() begin
for load in loads
Expand Down
18 changes: 11 additions & 7 deletions src/spirv.jl
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,11 @@ function finish_ir!(job::CompilerJob{SPIRVCompilerTarget}, mod::LLVM.Module,

# a module-scope SPIR-V variable cannot live in the address space of the pointers that
# refer to Julia's boxed constants (the Function storage class)
LLVM.version() >= v"17" && demote_boxed_constants!(job, mod)
if LLVM.version() >= v"17"
demote_boxed_constants!(job, mod)
else
fold_dead_box_references!(job, mod)
end

# SPIR-V cannot express atomic loads and stores of pointers, which is what Julia's
# `unordered` heap-reference accesses are (see `demote_unordered_atomics!`)
Expand Down Expand Up @@ -319,10 +323,10 @@ end
format=LLVM.CodeGenFileType.Assembly)
target = job.config.target

# (after `prepare_execution!`, whose InstCombine would narrow the widened operations)
# (after the last InstCombine, which would narrow the widened operations)
widen_bfloat16!(job, mod)

# (after `prepare_execution!` too, whose InstCombine can form overflow intrinsics)
# (after the last InstCombine too, which can form overflow intrinsics)
lower_mul_with_overflow!(mod)

# The SPIRV Tools don't handle Julia's debug info, rejecting DW_LANG_Julia...
Expand Down Expand Up @@ -932,8 +936,8 @@ end
# e.g., storing `(flag::Bool, (a, b))` built by inserting `flag`, `a` and `b`, loses `flag`
# (intel/intel-graphics-compiler#378, JuliaGPU/OpenCL.jl#502, JuliaGPU/oneAPI.jl#259).
# this runs after optimization, where SROA introduces these `insertvalue`s when splitting
# aggregate loads. the InstCombine run in `prepare_execution!` doesn't reconstruct them
# from the flattened form.
# aggregate loads. nothing combines instructions after finalization, which could
# reconstruct them from the flattened form.
function flatten_nested_insertvalue!(mod::LLVM.Module)
changed = false
@tracepoint "flatten nested insertvalue" begin
Expand Down Expand Up @@ -1160,8 +1164,8 @@ const MUL_HI_TYPES = Dict(8 => ("c", "h"), 16 => ("s", "t"), 32 => ("i", "j"),
# which rounding to `bfloat` is correct.
#
# Julia's `DemoteFloat16` pass widens arithmetic on CPUs, but leaves fast-math instructions,
# intrinsics and conversions alone. This has to run after `prepare_execution!`, whose
# InstCombine narrows `fptrunc(op(fpext x, fpext y))` back to a `bfloat` operation.
# intrinsics and conversions alone. This has to run after the last InstCombine, which
# narrows `fptrunc(op(fpext x, fpext y))` back to a `bfloat` operation.
function widen_bfloat16!(@nospecialize(job::CompilerJob{SPIRVCompilerTarget}),
mod::LLVM.Module)
changed = false
Expand Down
100 changes: 100 additions & 0 deletions test/finalization.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
# Nothing may combine or canonicalize instructions after target finalization (`finish_ir!`),
# as back-ends rely on its output reaching code generation as it is. Check that for every
# GPU target with a canary added at the end of `finish_ir!`, an exported function multiplying
# by two, which InstCombine would turn into a shift: it has to reach `mcgen` unchanged.

module Finalization

using GPUCompiler, LLVM, LLVM.IR, LLVM.Build, Test
using NVPTX_LLVM_Backend_jll, AMDGPU_LLVM_Backend_jll
using SPIRV_LLVM_Backend_jll, SPIRV_LLVM_Translator_jll, SPIRV_Tools_jll
import ..TestRuntime

struct CanaryParams <: AbstractCompilerParams end
GPUCompiler.runtime_module(::CompilerJob{<:Any,CanaryParams}) = TestRuntime

const canary = "gpucompiler_canary"
const canary_reached_mcgen = Ref(false)

function add_canary!(mod::LLVM.Module)
context!(context(mod)) do
T = LLVM.Int32Type()
f = LLVM.Function(mod, canary, LLVM.FunctionType(T, [T]))
@dispose builder=IRBuilder() begin
position!(builder, LLVM.at_end(BasicBlock(f, "entry")))
ret!(builder, mul!(builder, f.parameters[1], ConstantInt(T, 2)))
end
end
end

has_canary(mod::LLVM.Module) =
haskey(mod.functions, canary) &&
any(inst -> LLVM.opcode(inst) == LLVM.Opcode.Mul,
only(mod.functions[canary].blocks).instructions)

for T in (PTXCompilerTarget, GCNCompilerTarget, SPIRVCompilerTarget, MetalCompilerTarget)
@eval begin
function GPUCompiler.finish_ir!(job::CompilerJob{$T,CanaryParams},
mod::LLVM.Module, entry::LLVM.Function)
entry = invoke(GPUCompiler.finish_ir!,
Tuple{CompilerJob{$T}, LLVM.Module, LLVM.Function},
job, mod, entry)
haskey(mod.functions, canary) || add_canary!(mod)
return entry
end
function GPUCompiler.mcgen(job::CompilerJob{$T,CanaryParams}, mod::LLVM.Module,
format)
canary_reached_mcgen[] = has_canary(mod)
invoke(GPUCompiler.mcgen, Tuple{CompilerJob{$T}, LLVM.Module, typeof(format)},
job, mod, format)
end
end
end

function kernel(out::Core.LLVMPtr{Int32,1}, x::Int32)
unsafe_store!(out, x)
return
end

# an isbits union whose boxed constant SPIR-V and Metal demote onto the stack during
# finalization, which then cleans up after itself
@noinline produce(cond::Bool, value::Int32) = cond ? value : 1.5
function union_kernel(out::Core.LLVMPtr{Int32,1}, cond::Bool, value::Int32)
x = produce(cond, value)
unsafe_store!(out, Int32(x isa Float64))
return
end

targets = Pair{String,Any}["Metal" => MetalCompilerTarget(; macos=v"12.2", metal=v"3.0", air=v"3.0")]
NVPTX_LLVM_Backend_jll.is_available() && push!(targets, "PTX" => PTXCompilerTarget(; cap=v"7.0"))
if SPIRV_LLVM_Backend_jll.is_available() && SPIRV_LLVM_Translator_jll.is_available() &&
SPIRV_Tools_jll.is_available()
push!(targets, "SPIR-V (LLVM)" => SPIRVCompilerTarget(; backend=:llvm),
"SPIR-V (Khronos)" => SPIRVCompilerTarget(; backend=:khronos))
end
if AMDGPU_LLVM_Backend_jll.is_available() && !LLVM.is_asserts()
push!(targets, "GCN" => GCNCompilerTarget(; dev_isa="gfx900"))
end

@testset "$name" for (name, target) in targets, f in (kernel, union_kernel),
optimize in (true, false)
# (Metal rejects boxed constants before LLVM 17, and SPIR-V unoptimized ones)
f === union_kernel && !(LLVM.version() >= v"17" && target isa MetalCompilerTarget ||
(optimize || LLVM.version() >= v"17") &&
target isa SPIRVCompilerTarget) &&
continue
tt = f === kernel ? Tuple{Core.LLVMPtr{Int32,1}, Int32} :
Tuple{Core.LLVMPtr{Int32,1}, Bool, Int32}
source = methodinstance(typeof(f), tt)
# (unoptimized code still contains calls that validation rejects, e.g. on 1.13)
config = CompilerConfig(target, CanaryParams(); kernel=true, optimize, validate=optimize)
job = CompilerJob(source, config)
canary_reached_mcgen[] = false
JuliaContext() do ctx
_, meta = GPUCompiler.compile(:asm, job)
dispose(meta.ir)
end
@test canary_reached_mcgen[]
end

end
5 changes: 0 additions & 5 deletions test/metal.jl
Original file line number Diff line number Diff line change
Expand Up @@ -974,11 +974,6 @@ end
air = sprint(io -> Metal.code_native_table(io, mod.kernel, tt; kernel=true))
@test occursin("reloc_table", air)
@test !occursin("load ptr, ptr addrspace(1)", air)
# LLVM 20 folds the comparison of the converted words into one of the words
if LLVM.version() >= v"20"
@test occursin("icmp eq i64", air)
@test !occursin("icmp eq ptr", air)
end
end
end

Expand Down
Loading
Loading