diff --git a/.github/workflows/Test.yml b/.github/workflows/Test.yml index d0491497..e5e96919 100644 --- a/.github/workflows/Test.yml +++ b/.github/workflows/Test.yml @@ -85,3 +85,38 @@ jobs: token: ${{ secrets.CODECOV_TOKEN }} fail_ci_if_error: false files: lcov.info + + handoff_test: + # the late hand-off to libLLVMGPU, for the targets that support it (the others are + # tested as usual) + name: Julia ${{ matrix.version }} with libLLVMGPU - ${{ matrix.os }} + runs-on: ${{ matrix.os }} + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + version: ['1.12', '1.13'] + os: [ubuntu-24.04] + steps: + - uses: actions/checkout@v7 + + - name: Install Julia + uses: julia-actions/setup-julia@v3 + with: + version: ${{ matrix.version }} + + - name: Set-up cache + uses: julia-actions/cache@v3 + + - name: Select the late hand-off + run: | + julia --project=test -e 'using Pkg; Pkg.add(name="LLVMGPU_jll", version="1")' + for dir in . test; do + printf '[GPUCompiler]\nhandoff = "late"\n' >> $dir/LocalPreferences.toml + done + + - name: Run tests + uses: julia-actions/julia-runtest@v1 + env: + # (checked by the tests, so that they don't silently test without the hand-off) + GPUCOMPILER_TEST_HANDOFF: late diff --git a/src/GPUCompiler.jl b/src/GPUCompiler.jl index 800c8820..456b0647 100644 --- a/src/GPUCompiler.jl +++ b/src/GPUCompiler.jl @@ -61,6 +61,7 @@ include("mangling.jl") # compiler interface and implementations include("interface.jl") +include("handoff.jl") include("relocation.jl") include("atomics.jl") include("error.jl") diff --git a/src/driver.jl b/src/driver.jl index 5661bc74..12357bc4 100644 --- a/src/driver.jl +++ b/src/driver.jl @@ -20,17 +20,25 @@ export JuliaContext # this helper to a regular `Context()` call. function JuliaContext(; opaque_pointers=nothing) # XXX: remove - ThreadSafeContext(; opaque_pointers) + ThreadSafeContext(; opaque_pointers, library=:julia) end function JuliaContext(f; kwargs...) - ThreadSafeContext(; kwargs...) do ts_ctx + ThreadSafeContext(; library=:julia, kwargs...) do ts_ctx # for now, also activate the underlying context # XXX: this is wrong; we can't expose the underlying LLVM context, but should # instead always go through the callback in order to unlock it properly. # rework this once we depend on Julia 1.9 or later. ctx = context(ts_ctx) - context!(ctx) do - f(ctx) + # the block also owns the context of the late hand-off's library, if it's used + owner = ContextOwner(current_task(), nothing) + try + with(context_owner => owner) do + context!(ctx) do + f(ctx) + end + end + finally + dispose_handoff_context(owner) end end end @@ -83,7 +91,9 @@ The default [`relocation_lowering`](@ref) strategy resolves Julia-value relocati The IR in the result (the `:llvm` module, or `meta.ir` and `meta.entry`) lives in the LLVM context of the enclosing [`JuliaContext`](@ref) block, and is freed with it. Use it, -and dispose of it, within that block. +and dispose of it, within that block. With the late hand-off (see [`CompilerConfig`](@ref)), +it belongs to another LLVM library than Julia's, in a context that the block also owns: +work with it inside `context!(context(ir)) do ... end`. """ function compile(target::Symbol, @nospecialize(job::CompilerJob)) run_compile_hook(job) @@ -368,7 +378,7 @@ const __llvm_initialized = Ref(false) end end - exception_sites = ExceptionSite[] + resolve_early = false @tracepoint "IR post-processing" begin # mark the kernel entry-point functions (optimization may need it) if job.config.kernel @@ -452,11 +462,36 @@ const __llvm_initialized = Ref(false) end end end + end + end + # the rest of the pipeline runs with the LLVM library that generates code: Julia's, + # or after the late hand-off, a newer one (see `handoff.jl`) + if job.config.handoff === :late + # (in a new variable, which the closures above don't capture) + handed_off = @tracepoint "hand-off" late_handoff(job, ir) + return finish_llvm_in!(context(handed_off), job, handed_off, entry_fn, entry, + entrypoints, compiled, relocations, resolve_early) + else + return finish_llvm!(job, ir, entry_fn, entry, entrypoints, compiled, relocations, + resolve_early) + end +end + +finish_llvm_in!(ctx::LLVM.Context, args...) = context!(() -> finish_llvm!(args...), ctx) + +# finalize the IR for the target, validate it and collect its relocations +function finish_llvm!(@nospecialize(job::CompilerJob), ir::LLVM.Module, entry_fn::String, + entry::LLVM.Function, entrypoints, compiled, relocations::Relocations, + resolve_early::Bool) + exception_sites = ExceptionSite[] + @tracepoint "IR finalization" begin + if job.config.toplevel # Do not expose dead sites to loaders. resolve_early || prune_dead_relocations!(ir, relocations) - # optimization may have replaced functions, so look the entry point up again + # optimization (or the hand-off) may have replaced functions, so look the + # entry point up again entry = ir.functions[entry_fn] # finish the module @@ -543,10 +578,13 @@ emit_asm(@nospecialize(job::CompilerJob), ir::LLVM.Module, @tracepoint "Debug info removal" strip_debuginfo!(ir) end - @tracepoint "LLVM back-end" begin - @tracepoint "preparation" prepare_execution!(job, ir, relocs) + # (the module may belong to another library than Julia's, after the late hand-off) + code = context!(context(ir)) do + @tracepoint "LLVM back-end" begin + @tracepoint "preparation" prepare_execution!(job, ir, relocs) - code = @tracepoint "machine-code generation" mcgen(job, ir, format) + @tracepoint "machine-code generation" mcgen(job, ir, format) + end end return code, (;) diff --git a/src/gcn.jl b/src/gcn.jl index 0ce8c34e..d9f4c4ef 100644 --- a/src/gcn.jl +++ b/src/gcn.jl @@ -33,7 +33,11 @@ llvm_triple(::GCNCompilerTarget) = "amdgcn-amd-amdhsa" source_code(target::GCNCompilerTarget) = "gcn" +# the hand-off replaces the external back-end, whose datalayout it shares +supports_handoff(@nospecialize(target::GCNCompilerTarget)) = target.backend === :external + function llvm_machine(target::GCNCompilerTarget) + is_handoff_library() && return handoff_machine(target) @static if :AMDGPU ∉ LLVM.backends() return nothing end @@ -49,6 +53,61 @@ function llvm_machine(target::GCNCompilerTarget) return tm end +# the processors that the AMDGPU back-end of LLVM 23.1 knows (GCNProcessors.td) +const gcn_processors = Set([ + "generic", "generic-hsa", "gfx600", "tahiti", "gfx601", "pitcairn", "verde", "gfx602", + "hainan", "oland", "gfx700", "kaveri", "gfx701", "hawaii", "gfx702", "gfx703", + "kabini", "mullins", "gfx704", "bonaire", "gfx705", "gfx801", "carrizo", "gfx802", + "iceland", "tonga", "gfx803", "fiji", "polaris10", "polaris11", "gfx805", "tongapro", + "gfx810", "stoney", "gfx900", "gfx902", "gfx904", "gfx906", "gfx908", "gfx909", + "gfx90a", "gfx90c", "gfx942", "gfx950", "gfx9-generic", "gfx9-4-generic", "gfx1010", + "gfx1011", "gfx1012", "gfx1013", "gfx1030", "gfx1031", "gfx1032", "gfx1033", "gfx1034", + "gfx1035", "gfx1036", "gfx10-1-generic", "gfx10-3-generic", "gfx1100", "gfx1101", + "gfx1102", "gfx1103", "gfx1150", "gfx1151", "gfx1152", "gfx1153", "gfx1154", "gfx1170", + "gfx1171", "gfx1172", "gfx11-generic", "gfx11-7-generic", "gfx1200", "gfx1201", + "gfx12-generic", "gfx1250", "gfx1251", "gfx12-5-generic", "gfx1310", "gfx13-generic"]) + +# after the hand-off, a target machine of the library that generates code. like +# AMDGPU_LLVM_Backend_jll did, reject processors and features that LLVM would only warn +# about, and keep the 8-byte alignment of i128 that Julia needs before 1.12. +function handoff_machine(target::GCNCompilerTarget) + triple = llvm_triple(target) + t = LLVM.Target(; triple) + cpu = target.dev_isa + features = target.features + # (LLVM only warns about unknown processors, and falls back to the oldest one) + cpu in gcn_processors || error("Unsupported processor $cpu for the AMDGPU back-end") + @dispose sti=LLVM.SubtargetInfo(t, triple; cpu) begin + try + LLVM.hasfeatures(sti, features) + catch err + err isa ArgumentError || rethrow() + error("Unsupported features $(repr(features)) for the AMDGPU back-end: $(err.msg)") + end + end + + tm = if Base.datatype_alignment(Int128) == 8 + # the ABI name selects that alignment (a patch of the library's AMDGPU back-end), + # which LLVM.jl's `TargetMachine` constructor cannot set + lib = LLVM.library() + options = LLVM.API.LLVMCreateTargetMachineOptions(lib) + try + LLVM.API.LLVMTargetMachineOptionsSetCPU(lib, options, cpu) + LLVM.API.LLVMTargetMachineOptionsSetFeatures(lib, options, features) + LLVM.API.LLVMTargetMachineOptionsSetRelocMode(lib, options, LLVM.API.LLVMRelocPIC) + LLVM.API.LLVMTargetMachineOptionsSetABI(lib, options, "i128:64") + ref = LLVM.API.LLVMCreateTargetMachineWithOptions(lib, t, triple, options) + LLVM.mark_alloc(LLVM.TargetMachine(ref; library=lib)) + finally + LLVM.API.LLVMDisposeTargetMachineOptions(lib, options) + end + else + LLVM.TargetMachine(t, triple; cpu, features, reloc=LLVM.RelocMode.PIC) + end + LLVM.asm_verbosity!(tm, true) + return tm +end + # the external back-end replaces the module's datalayout with its own, which aligns i128 to # 16 bytes. it does keep a 64-bit alignment if the module asks for one (since # AMDGPU_LLVM_Backend_jll 23.1.1+4), which Julia needs before 1.12 to lay out kernel @@ -257,7 +316,9 @@ const AMDGPUObjectFile = Cint(1) mod::LLVM.Module, format=LLVM.CodeGenFileType.Assembly) target = job.config.target - if target.backend === :inprocess + if is_handoff_library(mod.library) + return String(handoff_mcgen(job, mod, format)) + elseif target.backend === :inprocess if :AMDGPU ∉ LLVM.backends() error("The in-process LLVM lacks the AMDGPU target; cannot compile to GCN. " * "Load AMDGPU_LLVM_Backend_jll and use `backend=:external` instead.") @@ -301,7 +362,7 @@ end # the version of the LLVM that generates code for the target, which can differ from the one # GPUCompiler runs in. only the release matters, so JLL rebuilds are ignored. function backend_llvm_version(target::GCNCompilerTarget) - target.backend === :external || return LLVM.version() + (target.backend === :external && !is_handoff_library()) || return LLVM.version() jll = get(Base.loaded_modules, getfield(AMDGPU_LLVM_Backend_jll, :pkg), nothing) # (without the back-end, `mcgen` reports a clearer error) jll === nothing && return LLVM.version() diff --git a/src/handoff.jl b/src/handoff.jl new file mode 100644 index 00000000..86b9fd9b --- /dev/null +++ b/src/handoff.jl @@ -0,0 +1,355 @@ +# hand-off of optimized code to a newer, standalone LLVM library +# +# With `handoff=:late`, optimization runs as usual with Julia's LLVM, after which the module +# is transferred as bitcode to a standalone LLVM library with GPU back-ends (libLLVMGPU), +# where it is optimized again. Target finalization (`finish_ir!`), validation, relocation +# collection, and code generation then all happen with that library, which takes the place +# of the per-target back-end libraries (e.g. NVPTX_LLVM_Backend_jll). + +export supports_handoff + + +## mode + +""" + supports_handoff(target::AbstractCompilerTarget) -> Bool + +Whether jobs for `target` support the late hand-off to a standalone LLVM library +(`CompilerConfig(...; handoff=:late)`). +""" +supports_handoff(@nospecialize(target::AbstractCompilerTarget)) = false + +# the default for `CompilerConfig(...; handoff)`, from the `handoff` preference +const handoff_preference = Ref{Union{Nothing,Symbol}}(nothing) +function default_handoff() + mode = handoff_preference[] + if mode === nothing + mode = Symbol(load_preference(@__MODULE__, "handoff", "none")) + mode in (:none, :late) || + error("Unknown value $(repr(String(mode))) for GPUCompiler's `handoff` preference; expected \"none\" or \"late\"") + handoff_preference[] = mode + end + return mode +end + +# the hand-off mode of a job: one that is inherited from the preference only applies to +# targets that support it, and nested jobs are linked into a parent before its hand-off +function resolve_handoff(@nospecialize(target::AbstractCompilerTarget), + handoff::Union{Nothing,Symbol}, toplevel::Bool) + if handoff === nothing + handoff = supports_handoff(target) ? default_handoff() : :none + elseif handoff ∉ (:none, :late) + error("Unknown handoff=$(repr(handoff)); expected :none or :late") + end + toplevel || return :none + if handoff === :late && !supports_handoff(target) + error("$(nameof(typeof(target))) does not support the late hand-off (handoff=:late)") + end + return handoff +end + + +## library + +const LLVMGPU_jll = LazyModule("LLVMGPU_jll", UUID("a5c41ef1-0fc2-5e62-838b-0d6f5f7d5115")) + +# the state of a library that code is handed off to +struct HandoffLibrary + library::LLVM.Library + + # protects the library's command-line options, along with the creation of the target + # machines that read them, and code generation (which the back-end libraries serialized) + lock::ReentrantLock + + # the SPIR-V extensions that are currently enabled through `--spirv-ext` + spirv_extensions::Set{String} +end + +const handoff_libraries = Dict{LLVM.Library,HandoffLibrary}() +const handoff_libraries_lock = ReentrantLock() + +# the library to hand off to: whichever is registered with LLVM.jl as `:gpu`, or else the +# one LLVMGPU_jll provides (which isn't loaded here, only used once it is) +function handoff_library() + lib = try + LLVM.Library(:gpu) + catch err + err isa ErrorException || rethrow() + isavailable(LLVMGPU_jll) || + error("""The late hand-off needs a standalone LLVM library with GPU back-ends: + load LLVMGPU_jll, or register a library as `:gpu` using `LLVM.register_library!`.""") + LLVM.register_library!(:gpu, LLVMGPU_jll.libLLVMGPU) + end + @lock handoff_libraries_lock begin + get!(handoff_libraries, lib) do + initialize_handoff_library(lib) + end + end +end + +function initialize_handoff_library(lib::LLVM.Library) + # the target and extension tables below are those of LLVM 23 + LLVM.version(lib).major == 23 || + error("The late hand-off supports LLVM 23 libraries, not LLVM $(LLVM.version(lib)) ($(lib.path))") + + # LLVM.jl does not know every back-end, e.g. SPIR-V, so look up the initializers + handle = Libdl.dlopen(lib.path) + for backend in ("NVPTX", "AMDGPU", "SPIRV"), + component in ("TargetInfo", "Target", "TargetMC", "AsmPrinter", "AsmParser") + f = Libdl.dlsym(handle, "LLVMInitialize$(backend)$(component)"; throw_error=false) + f === nothing || ccall(f, Cvoid, ()) + end + + LLVM.library!(lib) do + # like NVPTX_LLVM_Backend_jll did, leave eligible multiply-add pairs contractible + # for ptxas, like nvcc does + LLVM.clopts("-nvptx-fma-level=1") + end + + return HandoffLibrary(lib, ReentrantLock(), Set{String}()) +end + +# whether `lib` is a library that code is handed off to +is_handoff_library(lib::LLVM.Library=LLVM.library()) = + @lock handoff_libraries_lock haskey(handoff_libraries, lib) + +# the state of the library that the current library is handed off to +function current_handoff_library() + lib = LLVM.library() + @lock handoff_libraries_lock begin + state = get(handoff_libraries, lib, nothing) + state === nothing && error("LLVM library :$(lib.name) is not used for the late hand-off") + return state + end +end + + +## contexts + +# The IR that `compile` returns lives in the context of the enclosing `JuliaContext` block, +# so after a hand-off, that block owns the context of the other library too. Contexts are +# not thread safe, so it belongs to the task that runs the block. +mutable struct ContextOwner + const task::Task + handoff_context::Union{Nothing,LLVM.Context} +end + +const context_owner = ScopedValue{Union{Nothing,ContextOwner}}(nothing) + +function handoff_context(lib::LLVM.Library) + owner = context_owner[] + if owner === nothing + error("The late hand-off (handoff=:late) needs to be used inside a `JuliaContext() do ... end` block, which owns the resulting IR") + elseif owner.task !== current_task() + error("The late hand-off can only be used by the task that runs the enclosing `JuliaContext` block; use a block in every task instead") + end + ctx = owner.handoff_context + if ctx === nothing + ctx = LLVM.Context(; library=lib) + # (only activated when used, by `context!`) + deactivate(ctx) + owner.handoff_context = ctx + elseif ctx.library !== lib + error("The late hand-off library changed from :$(ctx.library.name) to :$(lib.name) within one `JuliaContext` block") + end + return ctx +end + +function dispose_handoff_context(owner::ContextOwner) + ctx = owner.handoff_context + ctx === nothing && return + owner.handoff_context = nothing + activate(ctx) + dispose(ctx) + return +end + + +## transfer + +# Transfer the optimized module `ir` to the hand-off library, returning the new module +# (in a context owned by the enclosing `JuliaContext` block). The original is disposed of. +function late_handoff(@nospecialize(job::CompilerJob), ir::LLVM.Module) + state = handoff_library() + ctx = handoff_context(state.library) + + # bitcode is forward compatible, so the newer library can read it + input = bitcode(ir) + mod = context!(() -> transfer(job, input), ctx) + dispose(ir) + return mod +end + +function transfer(@nospecialize(job::CompilerJob), input::Vector{UInt8}) + mod = parse(LLVM.Module, input) + try + with_llvm_machine(job.config.target) do tm + prepare_handoff!(mod, tm) + end + if job.config.optimize + @tracepoint "reoptimization" reoptimize!(job, mod) + end + catch + dispose(mod) + rethrow() + end + return mod +end + +function prepare_handoff!(mod::LLVM.Module, tm::Union{Nothing,LLVM.TargetMachine}) + tm === nothing && return + + # what the module was optimized for so far should match what code is generated for: + # the target machine replaces the module's layout when generating code anyway, but + # the optimizer of the new library should already use it + LLVM.DataLayout(tm) do dl + mod.datalayout = dl + end + return +end + +# optimize again with the standard pipeline of the new library, to benefit from its +# improvements. it cannot express the restrictions that some targets put on GPUCompiler's +# own pipeline (see `optimization_options`), so those jobs are not optimized again. +function reoptimize!(@nospecialize(job::CompilerJob), mod::LLVM.Module) + all(==(true), values(optimization_options(job))) || return + vectorize = can_vectorize(job) + with_llvm_machine(job.config.target) do tm + @dispose pb=PassBuilder(; loop_vectorization=vectorize, + slp_vectorization=vectorize) begin + add!(pb, "default") + run!(pb, mod, tm) + end + end + return +end + + +## code generation + +# generate code for `mod` from the late hand-off, with the hand-off library's back-end +function handoff_mcgen(@nospecialize(job::CompilerJob), mod::LLVM.Module, + format::LLVM.CodeGenFileType.T) + # a module that does not verify is a fatal error in code generation + verify(mod) + + state = current_handoff_library() + @lock state.lock begin + with_llvm_machine(job.config.target) do tm + tm === nothing && error("No target machine for $(job.config.target)") + set_subtarget_attributes!(mod, tm) + LLVM.emit(tm, mod, format) + end + end +end + +# like `llc` and the back-end libraries did, make the functions use the target machine's +# processor and features, unless they specify their own. only when generating code: the +# attributes keep functions without them from being inlined. +function set_subtarget_attributes!(mod::LLVM.Module, tm::LLVM.TargetMachine) + cpu = tm.cpu + features = tm.features + for f in mod.functions + isdeclaration(f) && continue + attrs = f.function_attributes + if !isempty(cpu) && !haskey(attrs, "target-cpu") + push!(attrs, StringAttribute("target-cpu", cpu)) + end + if !isempty(features) && !haskey(attrs, "target-features") + push!(attrs, StringAttribute("target-features", features)) + end + end + return +end + +# Set the SPIR-V extensions that target machines created afterwards enable to exactly +# `extensions`, a specifier like "+SPV_KHR_bfloat16,-SPV_KHR_float_controls". The SPIR-V +# back-end reads them from its `--spirv-ext` option when a target machine is created. Every +# use of the option replaces the set of extensions, but the ones it disables (with `-NAME`) +# stay disabled for good, so only ever enable the exact set. Must be called with +# `state.lock` held, through the creation of the target machine. +function set_spirv_extensions!(state::HandoffLibrary, extensions::AbstractString) + wanted = Set{String}() + for entry in split(extensions, ','; keepempty=false) + entry = strip(entry) + flag, name = entry[1], entry[2:end] + flag in ('+', '-') || + error("Invalid SPIR-V extension $(repr(entry)) in $(repr(extensions)); expected +NAME or -NAME") + names = if name == "all" + spirv_extension_names + elseif name in spirv_extension_names + (name,) + else + error("Unknown SPIR-V extension $(repr(name)) in $(repr(extensions))") + end + flag == '+' ? union!(wanted, names) : setdiff!(wanted, names) + end + + if wanted != state.spirv_extensions + spec = join(("+" * name for name in sort!(collect(wanted))), ',') + LLVM.library!(state.library) do + LLVM.clopts("--spirv-ext=" * spec) + end + empty!(state.spirv_extensions) + union!(state.spirv_extensions, wanted) + end + return +end + +# the extensions that the SPIR-V back-end of LLVM 23.1 knows (`SPIRVExtensionMap` in +# SPIRVCommandLine.cpp). it ignores unknown ones, so they are rejected here. +const spirv_extension_names = ( + "SPV_ALTERA_arbitrary_precision_fixed_point", "SPV_ALTERA_arbitrary_precision_floating_point", + "SPV_ALTERA_arbitrary_precision_integers", "SPV_ALTERA_blocking_pipes", + "SPV_AMD_weak_linkage", "SPV_EXT_arithmetic_fence", "SPV_EXT_demote_to_helper_invocation", + "SPV_EXT_descriptor_indexing", "SPV_EXT_fragment_fully_covered", + "SPV_EXT_fragment_invocation_density", "SPV_EXT_fragment_shader_interlock", + "SPV_EXT_image_raw10_raw12", "SPV_EXT_mesh_shader", "SPV_EXT_optnone", + "SPV_EXT_relaxed_printf_string_address_space", "SPV_EXT_shader_atomic_float16_add", + "SPV_EXT_shader_atomic_float_add", "SPV_EXT_shader_atomic_float_min_max", + "SPV_EXT_shader_image_int64", "SPV_EXT_shader_stencil_export", + "SPV_EXT_shader_viewport_index_layer", "SPV_GOOGLE_hlsl_functionality1", + "SPV_GOOGLE_user_type", "SPV_INTEL_16bit_atomics", "SPV_INTEL_2d_block_io", + "SPV_INTEL_bfloat16_arithmetic", "SPV_INTEL_bfloat16_conversion", + "SPV_INTEL_bindless_images", "SPV_INTEL_cache_controls", "SPV_INTEL_float_controls2", + "SPV_INTEL_fp_max_error", "SPV_INTEL_function_pointers", + "SPV_INTEL_global_variable_fpga_decorations", "SPV_INTEL_global_variable_host_access", + "SPV_INTEL_inline_assembly", "SPV_INTEL_int4", "SPV_INTEL_joint_matrix", + "SPV_INTEL_kernel_attributes", "SPV_INTEL_long_composites", + "SPV_INTEL_masked_gather_scatter", "SPV_INTEL_media_block_io", + "SPV_INTEL_memory_access_aliasing", "SPV_INTEL_optnone", "SPV_INTEL_predicated_io", + "SPV_INTEL_split_barrier", "SPV_INTEL_subgroup_matrix_multiply_accumulate", + "SPV_INTEL_subgroups", "SPV_INTEL_tensor_float32_conversion", + "SPV_INTEL_ternary_bitwise_function", "SPV_INTEL_unstructured_loop_controls", + "SPV_INTEL_usm_storage_classes", "SPV_INTEL_variable_length_array", + "SPV_KHR_16bit_storage", "SPV_KHR_abort", "SPV_KHR_bfloat16", "SPV_KHR_bit_instructions", + "SPV_KHR_cooperative_matrix", "SPV_KHR_device_group", "SPV_KHR_expect_assume", + "SPV_KHR_float_controls", "SPV_KHR_float_controls2", "SPV_KHR_fma", + "SPV_KHR_fragment_shader_barycentric", "SPV_KHR_fragment_shading_rate", + "SPV_KHR_integer_dot_product", "SPV_KHR_linkonce_odr", "SPV_KHR_maximal_reconvergence", + "SPV_KHR_multiview", "SPV_KHR_no_integer_wrap_decoration", "SPV_KHR_non_semantic_info", + "SPV_KHR_physical_storage_buffer", "SPV_KHR_poison_freeze", "SPV_KHR_post_depth_coverage", + "SPV_KHR_ray_query", "SPV_KHR_ray_tracing", "SPV_KHR_shader_clock", + "SPV_KHR_shader_draw_parameters", "SPV_KHR_subgroup_rotate", + "SPV_KHR_uniform_group_instructions", "SPV_KHR_vulkan_memory_model", + "SPV_NV_shader_atomic_fp16_vector", "SPV_NV_shader_subgroup_partitioned") + + +## Julia types + +# Lower a Julia type to LLVM in the current context, also when that context belongs to +# another library than Julia's, whose code generator lowers types. The type is lowered in a +# Julia context, and transferred through a bitcode module holding a global of that type. +function julia_llvm_type(@nospecialize(T::Type)) + ctx = context() + ctx.library === LLVM.Library(:julia) && return convert(LLVMType, T) + input = LLVM.Context(; library=:julia) do _ + @dispose mod=LLVM.Module("type") begin + GlobalVariable(mod, convert(LLVMType, T), "value") + bitcode(mod) + end + end + @dispose mod=parse(LLVM.Module, input) begin + mod.globals["value"].global_value_type + end +end diff --git a/src/interface.jl b/src/interface.jl index da286ff8..23b0406f 100644 --- a/src/interface.jl +++ b/src/interface.jl @@ -143,7 +143,8 @@ else end const CONFIG_KWARGS = [:kernel, :name, :entry_abi, :always_inline, :opt_level, - :debug_level, :libraries, :optimize, :cleanup, :validate, :strip] + :debug_level, :libraries, :optimize, :cleanup, :validate, :strip, + :handoff] """ CompilerConfig(target, params; kernel=true, entry_abi=:specfunc, name=nothing, @@ -177,6 +178,13 @@ Several keyword arguments can be used to customize the compilation process: - `cleanup`: run cleanup passes on the code (default: true) - `validate`: enable optional validation of input and outputs (default: true) - `strip`: strip non-functional metadata and debug information (default: false) +- `handoff`: `:late` to optimize with Julia's LLVM, and then hand the code off to a newer, + standalone LLVM library (registered with LLVM.jl as `:gpu`, or provided by LLVMGPU_jll) + that optimizes it again, finalizes it for the target and generates code; the IR that + `compile` returns then belongs to that library. `:none` to use Julia's LLVM throughout. + Only for targets that [`supports_handoff`](@ref), and only applies to top-level jobs. + The default is GPUCompiler's `handoff` preference (`"none"` if unset) for targets that + support the hand-off, and `:none` for other targets. Experimental. """ struct CompilerConfig{T,P} target::T @@ -193,6 +201,7 @@ struct CompilerConfig{T,P} cleanup::Bool validate::Bool strip::Bool + handoff::Symbol # internal toplevel::Bool @@ -206,10 +215,11 @@ struct CompilerConfig{T,P} always_inline=false, opt_level=2, debug_level=Base.JLOptions().debug_level, optimize=toplevel, libraries=toplevel, cleanup=toplevel, validate=toplevel, - strip=false, only_entry=false) + strip=false, handoff=nothing, only_entry=false) if entry_abi ∉ (:specfunc, :func) error("Unknown entry_abi=$entry_abi") end + handoff = resolve_handoff(target, handoff, toplevel) owner = @static if HAS_INTEGRATED_CACHE cache_owner(target, params, always_inline) else @@ -217,8 +227,8 @@ struct CompilerConfig{T,P} end new{typeof(target), typeof(params)}(target, params, kernel, name, entry_abi, always_inline, opt_level, debug_level, libraries, - optimize, cleanup, validate, strip, toplevel, - only_entry, owner) + optimize, cleanup, validate, strip, handoff, + toplevel, only_entry, owner) end end @@ -228,8 +238,8 @@ function CompilerConfig(cfg::CompilerConfig; target=cfg.target, params=cfg.param always_inline=cfg.always_inline, opt_level=cfg.opt_level, debug_level=cfg.debug_level, libraries=cfg.libraries, optimize=cfg.optimize, cleanup=cfg.cleanup, - validate=cfg.validate, strip=cfg.strip, toplevel=cfg.toplevel, - only_entry=cfg.only_entry) + validate=cfg.validate, strip=cfg.strip, handoff=cfg.handoff, + toplevel=cfg.toplevel, only_entry=cfg.only_entry) # deriving a non-toplevel job disables certain features # XXX: should we keep track if any of these were set explicitly in the first place? # see how PkgEval does that. @@ -240,8 +250,8 @@ function CompilerConfig(cfg::CompilerConfig; target=cfg.target, params=cfg.param validate = false end CompilerConfig(target, params; kernel, entry_abi, name, always_inline, opt_level, - debug_level, libraries, optimize, cleanup, validate, strip, toplevel, - only_entry) + debug_level, libraries, optimize, cleanup, validate, strip, handoff, + toplevel, only_entry) end function Base.show(io::IO, @nospecialize(cfg::CompilerConfig{T})) where {T} @@ -263,6 +273,7 @@ function Base.hash(cfg::CompilerConfig, h::UInt) h = hash(cfg.cleanup, h) h = hash(cfg.validate, h) h = hash(cfg.strip, h) + h = hash(cfg.handoff, h) h = hash(cfg.toplevel, h) h = hash(cfg.only_entry, h) # `cache_owner` deliberately is not hashed: its target/params/inlining components were @@ -520,7 +531,9 @@ function session_results(::Type{V}, ci::CodeInstance, config::CompilerConfig) wh end function can_persist_results(@nospecialize(job::CompilerJob)) - supports_relocatable_ir() && relocation_lowering(job) in (:patch, :table) + # results of the hand-off depend on a library that package images don't track + supports_relocatable_ir() && relocation_lowering(job) in (:patch, :table) && + job.config.handoff === :none end """ diff --git a/src/irgen.jl b/src/irgen.jl index a6162e97..fead19ee 100644 --- a/src/irgen.jl +++ b/src/irgen.jl @@ -1342,8 +1342,10 @@ end # the kernel state argument is always passed by value to avoid codegen issues with byval. # some back-ends however do not support passing kernel arguments by value, so this pass # serves to convert that argument (and is conceptually the inverse of `lower_byval`). +# with `byval`, the reference is marked `byval` (for back-ends that pass it by value after +# all). there's only a kernel state parameter to convert after optimization added it. function kernel_state_to_reference!(@nospecialize(job::CompilerJob), mod::LLVM.Module, - f::LLVM.Function) + f::LLVM.Function; byval::Bool=false) ft = f.function_type # check if we even need a kernel state argument @@ -1352,7 +1354,7 @@ function kernel_state_to_reference!(@nospecialize(job::CompilerJob), mod::LLVM.M return f end - T_state = convert(LLVMType, state) + T_state = julia_llvm_type(state) # find the kernel state parameter (should be the first argument) if isempty(ft.parameters) || f.parameters[1].value_type != T_state @@ -1378,6 +1380,7 @@ function kernel_state_to_reference!(@nospecialize(job::CompilerJob), mod::LLVM.M push!(attrs, EnumAttribute(:noalias)) # the state is read-only push!(attrs, EnumAttribute(:readonly)) + byval && push!(attrs, TypeAttribute(:byval, T_state)) # remove the old function replace_function!(f, new_f) diff --git a/src/ptx.jl b/src/ptx.jl index 80ed8cc8..18a366f5 100644 --- a/src/ptx.jl +++ b/src/ptx.jl @@ -72,7 +72,10 @@ source_code(target::PTXCompilerTarget) = "ptx" llvm_triple(target::PTXCompilerTarget) = Int===Int64 ? "nvptx64-nvidia-cuda" : "nvptx-nvidia-cuda" +supports_handoff(@nospecialize(target::PTXCompilerTarget)) = true + function llvm_machine(target::PTXCompilerTarget) + is_handoff_library() && return handoff_machine(target) @static if :NVPTX ∉ LLVM.backends() return nothing end @@ -109,6 +112,50 @@ llvm_datalayout(target::PTXCompilerTarget) = # native integer widths "n16:32:64" +# the minimum PTX ISA version of every processor the NVPTX back-end of LLVM 23.1 knows +# (`getMinPTXVersionForSM` in NVPTXSubtarget.cpp) +const ptx_minimum_versions = let + versions = Dict{String,VersionNumber}() + for (ptx, sms) in ((v"3.2", ["20", "21", "30", "35"]), (v"4.0", ["32", "50"]), + (v"4.1", ["37", "52"]), (v"4.2", ["53"]), + (v"5.0", ["60", "61", "62"]), (v"6.0", ["70"]), (v"6.1", ["72"]), + (v"6.3", ["75"]), (v"7.0", ["80"]), (v"7.1", ["86"]), + (v"7.4", ["87"]), (v"7.8", ["89", "90"]), (v"8.0", ["90a"]), + (v"8.6", ["100", "100a", "101", "101a"]), (v"8.7", ["120", "120a"]), + (v"8.8", ["100f", "101f", "103", "103f", "103a", "120f", "121", + "121f", "121a"]), + (v"9.0", ["88", "110", "110f", "110a"])) + for sm in sms + versions["sm_$sm"] = ptx + end + end + versions +end + +# after the hand-off, the library generating code also drives the middle end, so use the +# actual target. like NVPTX_LLVM_Backend_jll did, reject processors and PTX versions that +# LLVM would otherwise only warn about (or abort on). +function handoff_machine(target::PTXCompilerTarget) + triple = llvm_triple(target) + t = LLVM.Target(; triple) + cpu = cpu_name(target) + ptx = "ptx$(target.ptx.major)$(target.ptx.minor)" + @dispose sti=LLVM.SubtargetInfo(t, triple; cpu) begin + # NVPTX also has a feature for every processor and PTX version + features = LLVM.processor_features(sti) + cpu in features || error("Unsupported processor $cpu for the NVPTX back-end") + ptx in features || error("Unsupported PTX ISA version $(target.ptx) for the NVPTX back-end") + end + # (LLVM aborts on a PTX version that's too old for the processor) + required = get(ptx_minimum_versions, cpu, nothing) + required === nothing && error("Unknown minimum PTX ISA version for processor $cpu") + target.ptx < required && + error("Processor $cpu needs at least PTX ISA version $required, not $(target.ptx)") + tm = LLVM.TargetMachine(t, triple; cpu, features="+$ptx") + LLVM.asm_verbosity!(tm, true) + return tm +end + have_fma(@nospecialize(target::PTXCompilerTarget), T::Type) = true dwarf_version(target::PTXCompilerTarget) = Int32(2) # Cuda only supports dwarfv2 @@ -324,12 +371,15 @@ end @unlocked function mcgen(@nospecialize(job::CompilerJob{PTXCompilerTarget}), mod::LLVM.Module, format=LLVM.CodeGenFileType.Assembly) - if !isavailable(NVPTX_LLVM_Backend_jll) || !NVPTX_LLVM_Backend_jll.is_available() - error("NVPTX LLVM back-end not loaded; cannot compile to PTX.") - end if format != LLVM.CodeGenFileType.Assembly error("Unsupported PTX output format $format; the NVPTX back-end only emits PTX assembly.") end + if is_handoff_library(mod.library) + return String(handoff_mcgen(job, mod, format)) + end + if !isavailable(NVPTX_LLVM_Backend_jll) || !NVPTX_LLVM_Backend_jll.is_available() + error("NVPTX LLVM back-end not loaded; cannot compile to PTX.") + end backend = ExternalBackend(NVPTX_LLVM_Backend_jll.libnvptx, "NVPTX") # the back-end derives the triple and datalayout from these options; unlike `llc`, diff --git a/src/reflection.jl b/src/reflection.jl index d86170ad..df222746 100644 --- a/src/reflection.jl +++ b/src/reflection.jl @@ -258,6 +258,14 @@ function code_llvm(io::IO, @nospecialize(job::CompilerJob); optimize::Bool=job.c config = CompilerConfig(job.config; validate=false, strip=false, optimize) str = JuliaContext() do ctx ir, meta = compile(:llvm, CompilerJob(job; config)) + if is_handoff_library(ir.library) + # Julia's printer only works with its own LLVM. LLVM's always prints all + # metadata, and debug information unless it's disabled. + return context!(context(ir)) do + debuginfo === :none && strip_debuginfo!(ir) + dump_module ? string(ir) : string(meta.entry) + end + end ts_mod = ThreadSafeModule(ir) entry_fn = meta.entry GC.@preserve ts_mod entry_fn begin diff --git a/src/spirv.jl b/src/spirv.jl index ddf89b21..b200dace 100644 --- a/src/spirv.jl +++ b/src/spirv.jl @@ -93,8 +93,25 @@ function llvm_triple(target::SPIRVCompilerTarget) end end -# SPIRV is not supported by our LLVM builds, so we can't get a target machine -llvm_machine(::SPIRVCompilerTarget) = nothing +supports_handoff(@nospecialize(target::SPIRVCompilerTarget)) = true + +# Julia's LLVM does not have the SPIR-V target, so we can't get a target machine, except +# from the library of the late hand-off. the Khronos translator takes `spir` modules, for +# which there's no target machine at all. +function llvm_machine(target::SPIRVCompilerTarget) + (is_handoff_library() && target.backend === :llvm) || return nothing + if target.version !== nothing && !(v"1.0" <= target.version <= v"1.6") + error("Unsupported SPIR-V version $(target.version) for the SPIR-V back-end") + end + triple = llvm_triple(target) + t = LLVM.Target(; triple) + # the extensions are taken from a global option when creating the target machine + state = current_handoff_library() + @lock state.lock begin + set_spirv_extensions!(state, spirv_extensions(target)) + LLVM.TargetMachine(t, triple) + end +end function runtime_cstring_type(job::CompilerJob{SPIRVCompilerTarget}) LLVM.DataLayout(llvm_datalayout(job.config.target)) do dl @@ -255,15 +272,7 @@ function finish_ir!(job::CompilerJob{SPIRVCompilerTarget}, mod::LLVM.Module, if job.config.kernel state = kernel_state_type(job) if state !== Nothing - new_entry = kernel_state_to_reference!(job, mod, entry) - - # only if there was a kernel state parameter to convert, which optimization adds - # (so not when emitting unoptimized IR) - if new_entry != entry - entry = new_entry - T_state = convert(LLVMType, state) - push!(entry.parameter_attributes[1], TypeAttribute(:byval, T_state)) - end + entry = kernel_state_to_reference!(job, mod, entry; byval=true) end end @@ -342,7 +351,9 @@ end # translate to SPIR-V input = bitcode(mod) - spirv = if target.backend === :llvm + spirv = if is_handoff_library(mod.library) && target.backend === :llvm + handoff_mcgen(job, mod, LLVM.CodeGenFileType.Object) + elseif target.backend === :llvm # compile in-process through libspirv. the back-end derives the triple from the # options; unlike `llc`, it rejects unknown extensions instead of ignoring them. backend = ExternalBackend(SPIRV_LLVM_Backend_jll.libspirv, "SPIRV") diff --git a/test/gcn.jl b/test/gcn.jl index 5b64d107..13b54b66 100644 --- a/test/gcn.jl +++ b/test/gcn.jl @@ -265,8 +265,8 @@ end @test @filecheck begin @check_not "{{julia_throw_boundserror_[0-9]+}}" - @check "@gpu_report_exception" - @check "@gpu_signal_exception" + @check cond=!late_handoff "@gpu_report_exception" + @check cond=!late_handoff "@gpu_signal_exception" GCN.code_llvm(mod.kernel, Tuple{}) end end @@ -386,7 +386,8 @@ end kernel=true) JuliaContext() do ctx ir, meta = GPUCompiler.compile(:llvm, job) - @dispose ir=ir begin + # (with the late hand-off, the IR belongs to another LLVM library) + context!(context(ir)) do entry = meta.entry ft = entry.function_type params = ft.parameters @@ -404,6 +405,7 @@ end ir_str = string(ir) @test occursin("byref", ir_str) end + dispose(ir) end end @@ -582,6 +584,7 @@ end script = """ using GPUCompiler, LLVM include($(repr(joinpath(@__DIR__, "helpers", "runtime.jl")))) + include($(repr(joinpath(@__DIR__, "helpers", "handoff.jl")))) include($(repr(joinpath(@__DIR__, "helpers", "gcn.jl")))) kernel_i8(p::Core.LLVMPtr{Int8,1}, x::Int8) = (Base.llvmcall(($(repr(rmw_source("i8", "add"; as=1))), "entry"), Nothing, @@ -946,7 +949,8 @@ end @test @filecheck begin @check_label "define float @{{(julia|j)_scratch_[0-9]+}}" @check "alloca [8 x i32], align 4, addrspace(5)" - @check_not "addrspacecast" + # (Julia's IR printer hides the casts to Julia's address spaces, LLVM's doesn't) + @check_not cond=!late_handoff "addrspacecast" @check_not "julia.gpu.alloca" GCN.code_llvm(mod.scratch, Tuple{Float32}; optimize=false, dump_module=true) end diff --git a/test/handoff.jl b/test/handoff.jl new file mode 100644 index 00000000..6042c69d --- /dev/null +++ b/test/handoff.jl @@ -0,0 +1,154 @@ +# the late hand-off to a standalone LLVM library (see helpers/handoff.jl for how to select one) + +@testset "configuration" begin + if haskey(ENV, "GPUCOMPILER_TEST_HANDOFF") + @test GPUCompiler.default_handoff() === Symbol(ENV["GPUCOMPILER_TEST_HANDOFF"]) + end + + source = methodinstance(typeof(identity), Tuple{Nothing}) + native = NativeCompilerTarget() + ptx = PTXCompilerTarget(; cap=v"7.0") + + @test CompilerConfig(native, PTX.CompilerParams(); handoff=:none).handoff === :none + @test_throws "does not support the late hand-off" CompilerConfig(native, PTX.CompilerParams(); handoff=:late) + @test_throws "Unknown handoff" CompilerConfig(ptx, PTX.CompilerParams(); handoff=:early) + + # nested jobs are linked into their parent before it is handed off + config = CompilerConfig(ptx, PTX.CompilerParams(); handoff=:late) + @test config.handoff === :late + @test CompilerConfig(config; toplevel=false).handoff === :none + @test CompilerConfig(config; toplevel=false, target=native).handoff === :none + + # the preference only applies to targets that support the hand-off + @test CompilerConfig(native, PTX.CompilerParams()).handoff === :none + @test CompilerConfig(ptx, PTX.CompilerParams()).handoff === GPUCompiler.default_handoff() + + # the results of the hand-off depend on a library that package images don't track + job = CompilerJob(source, CompilerConfig(ptx, PTX.CompilerParams(true); handoff=:late)) + @test !GPUCompiler.can_persist_results(job) +end + +const library_available = + GPUCompiler.isavailable(GPUCompiler.LLVMGPU_jll) || haskey(ENV, "GPUCOMPILER_LIBLLVMGPU") +haskey(ENV, "GPUCOMPILER_TEST_HANDOFF") && @test library_available + +if library_available + +kernel(p::Core.LLVMPtr{Float32,1}, x::Float32) = + (unsafe_store!(p, unsafe_load(p) * x + 1f0); return) +const tt = Tuple{Core.LLVMPtr{Float32,1}, Float32} + +@testset "IR" begin + is_handoff = GPUCompiler.default_handoff() === :late + job, _ = PTX.create_job(kernel, tt; kernel=true, handoff=:late) + JuliaContext() do ctx + ir, meta = GPUCompiler.compile(:llvm, job) + @test ir.library === LLVM.Library(:gpu) + @test LLVM.version(ir) >= v"23" + + # owning objects are usable as is, values in the context of the library + @test occursin("ptx_kernel", string(ir)) + context!(context(ir)) do + @test meta.entry in ir.functions + @test meta.entry.callconv == LLVM.CallConv.PTXKernel + end + + # by default, as the preference says + default_job, _ = PTX.create_job(kernel, tt; kernel=true) + ir2, _ = GPUCompiler.compile(:llvm, default_job) + @test is_handoff == (ir2.library === LLVM.Library(:gpu)) + dispose(ir2) + + # the IR can be compiled after the fact, also when its library is the current one + ir2, meta2 = GPUCompiler.compile(:llvm, job) + asm, _ = GPUCompiler.emit_asm(job, ir, meta.relocations, + LLVM.CodeGenFileType.Assembly) + @test occursin(".entry", asm) + LLVM.library!(ir2.library) do + asm, _ = GPUCompiler.emit_asm(job, ir2, meta2.relocations, + LLVM.CodeGenFileType.Assembly) + @test occursin(".entry", asm) + end + dispose(ir2) + + # the block owns one context of the library, for all its compilations + ir2, _ = GPUCompiler.compile(:llvm, job) + @test context(ir2) == context(ir) + dispose(ir2) + dispose(ir) + end + + # that context is owned by the `JuliaContext` block + ThreadSafeContext() do ts_ctx + context!(context(ts_ctx)) do + @test_throws "inside a `JuliaContext() do ... end` block" GPUCompiler.compile(:llvm, job) + end + end + + # reflection prints the IR of the library + ir = sprint(io -> PTX.code_llvm(io, kernel, tt; kernel=true, handoff=:late)) + @test occursin("define ptx_kernel void", ir) +end + +@testset "code generation" begin + # PTX + asm = sprint(io -> PTX.code_native(io, kernel, tt; kernel=true, handoff=:late, cap=v"8.0", + ptx=v"7.8")) + @test occursin(".target sm_80", asm) + @test occursin(".version 7.8", asm) + @test occursin("fma.rn.f32", asm) + @test_throws "Unsupported processor sm_12" PTX.code_native(devnull, kernel, tt; + kernel=true, handoff=:late, cap=v"1.2") + @test_throws "Unsupported PTX ISA version 1.0" PTX.code_native(devnull, kernel, tt; + kernel=true, handoff=:late, ptx=v"1.0") + @test_throws "needs at least PTX ISA version 7.8" PTX.code_native(devnull, kernel, tt; + kernel=true, handoff=:late, cap=v"9.0", ptx=v"7.0") + + # GCN + asm = sprint(io -> GCN.code_native(io, kernel, tt; kernel=true, handoff=:late)) + @test occursin("amdhsa.kernels", asm) + @test_throws "Unsupported processor gfx1" GCN.code_native(devnull, kernel, tt; + kernel=true, handoff=:late, dev_isa="gfx1") + + # SPIR-V, with both back-ends + for backend in (:llvm, :khronos) + asm = sprint(io -> SPIRV.code_native(io, kernel, tt; kernel=true, handoff=:late, backend)) + @test occursin("OpEntryPoint Kernel", asm) + end +end + +@testset "SPIR-V extensions" begin + # every target machine gets exactly the extensions of its job, regardless of what the + # jobs before it enabled + fadd(p::Core.LLVMPtr{Float32,1}) = (SPIRV.Atomics.modify!(p, 1f0, + Val(SPIRV.Atomics.Op.FAdd), Val(SPIRV.Atomics.Ordering.Monotonic), Val(:device)); return) + native(atomics) = sprint(io -> SPIRV.code_native(io, fadd, Tuple{Core.LLVMPtr{Float32,1}}; + kernel=true, handoff=:late, backend=:llvm, + atomics)) + with_fadd = SPIRVAtomics(; fadd_f32_global=true) + with_both = SPIRVAtomics(; fadd_f16_global=true, fadd_f32_global=true) + for atomics in (with_fadd, SPIRVAtomics(), with_fadd, with_both, SPIRVAtomics(), with_fadd) + asm = native(atomics) + @test occursin("OpAtomicFAddEXT", asm) == (atomics != SPIRVAtomics()) + end + + @test_throws "Unknown SPIR-V extension \"SPV_FOO\"" SPIRV.code_native(devnull, kernel, tt; + kernel=true, handoff=:late, backend=:llvm, extensions="+SPV_FOO") +end + +@testset "relocations" begin + # relocations are recorded by name, so they survive the hand-off + sym_kernel(p::Core.LLVMPtr{Int,1}, s::Symbol) = (unsafe_store!(p, s === :foo ? 1 : 2); return) + job, _ = PTX.create_job(sym_kernel, Tuple{Core.LLVMPtr{Int,1}, Symbol}; kernel=true, + handoff=:late, patch=true) + JuliaContext() do ctx + asm, meta = GPUCompiler.compile(:asm, job) + @test !isempty(meta.relocations.records) + for rec in meta.relocations.records + @test occursin(rec.name, asm) + end + dispose(meta.ir) + end +end + +end diff --git a/test/helpers/handoff.jl b/test/helpers/handoff.jl new file mode 100644 index 00000000..65e36442 --- /dev/null +++ b/test/helpers/handoff.jl @@ -0,0 +1,12 @@ +# the late hand-off (with GPUCompiler's `handoff` preference set to "late") uses the LLVM +# library registered as `:gpu`: a local build at `GPUCOMPILER_LIBLLVMGPU`, or LLVMGPU_jll's +if haskey(ENV, "GPUCOMPILER_LIBLLVMGPU") + LLVM.register_library!(:gpu, ENV["GPUCOMPILER_LIBLLVMGPU"]) +elseif Base.find_package("LLVMGPU_jll") !== nothing + @eval using LLVMGPU_jll +end + +# whether jobs for targets that support it are handed off, and optimized a second time, +# which changes some of the IR tests look at: e.g., the test runtimes' empty exception +# reporting functions are inlined then +const late_handoff = GPUCompiler.default_handoff() === :late diff --git a/test/ptx.jl b/test/ptx.jl index 5c1cc4d7..6c55982c 100644 --- a/test/ptx.jl +++ b/test/ptx.jl @@ -5,7 +5,7 @@ # jl_throw referencing a jl_value_t representing the exception @test @filecheck PTX.code_llvm(Tuple{}; dump_module=true) do @check_not "jl_throw" - @check "gpu_report_exception" + @check cond=!late_handoff "gpu_report_exception" throw(DivideError()) end end @@ -37,7 +37,7 @@ end @test @filecheck begin @check_label "define void @{{(julia|j)_kernel[0-9_]*}}" @check_not "atomic_error" - @check "gpu_report_exception" + @check cond=!late_handoff "gpu_report_exception" PTX.code_llvm(mod.kernel, Tuple{Ptr{Int},mod.Atomic}) end end @@ -96,7 +96,7 @@ end _, meta = PTX.code_execution(mod.kernel, types; debug_level=1, validate=false) @test !haskey(meta, :exception_sites) @test @filecheck begin - @check "gpu_report_exception" + @check cond=!late_handoff "gpu_report_exception" @check_not "gpu_exception_site" PTX.code_llvm(mod.kernel, types; kernel=true, debug_level=1) end @@ -117,7 +117,8 @@ end end _, meta = PTX.code_execution(mod.kernel, Tuple{Ptr{Int},Int}; exception_sites=true, debug_level=1) - @test length(meta.exception_sites) == 2 + # (the second optimization sees that the test runtime's allocator never fails) + @test length(meta.exception_sites) == (late_handoff ? 1 : 2) @test GPUCompiler.ExceptionSite("Error", "reason", []) in meta.exception_sites end @@ -440,7 +441,7 @@ end ir = sprint() do io PTX.code_llvm(io, mod.kernel, Tuple{Int}; kernel=true, dump_module=true) end - @test occursin("gpu_report_exception", ir) + @test occursin("gpu_report_exception", ir) skip=late_handoff @test occursin("[1 x i64] %state", ir) end @@ -629,8 +630,9 @@ end ir = sprint(io->PTX.code_llvm(io, dkernel, Tuple{Ptr{Float64}}; debuginfo=:none, dump_module=true, kernel=true)) @test !occursin("deferred_codegen", ir) - @test occursin(r"define internal .*@enzyme_(julia|j)_kernel", ir) - @test occursin(r"call .*@(julia|j)_kernel", ir) + # (the second optimization inlines the deferred function) + @test occursin(r"define internal .*@enzyme_(julia|j)_kernel", ir) skip=late_handoff + @test occursin(r"call .*@(julia|j)_kernel", ir) skip=late_handoff end end @@ -946,7 +948,7 @@ end @check_not "julia.pop_gc_frame" @check_not "julia.get_gc_frame_slot" @check_not "julia.new_gc_frame" - @check "gpu_gc_pool_alloc" + @check cond=!late_handoff "gpu_gc_pool_alloc" PTX.code_native(mod.kernel, Tuple{Int}) end @@ -1122,7 +1124,9 @@ end @check_not cond=!fastmath "denormal-fp-math-f32" @check cond=!fastmath "call float @llvm.sqrt.f32" @check cond=fastmath "call fast float @llvm.sqrt.f32" - @check cond=fastmath "\"denormal-fp-math-f32\"=\"preserve-sign,preserve-sign\"" + # (LLVM 23 upgrades the attribute to `denormal_fpenv` when reading bitcode) + @check cond=fastmath && !late_handoff "\"denormal-fp-math-f32\"=\"preserve-sign,preserve-sign\"" + @check cond=fastmath && late_handoff "denormal_fpenv(float: preservesign)" @check cond=fastmath "\"unsafe-fp-math\"=\"true\"" unsafe_store!(out, sqrt(unsafe_load(x))) return diff --git a/test/spirv.jl b/test/spirv.jl index 3e5fd536..882d2c16 100644 --- a/test/spirv.jl +++ b/test/spirv.jl @@ -348,8 +348,11 @@ end kernel=true, backend) JuliaContext() do ctx ir, meta = GPUCompiler.compile(:llvm, job; kwargs...) - @test all(!endswith(gv.name, "_box") for gv in ir.globals) - @test [f for f in ir.functions if !LLVM.isdeclaration(f)] == [meta.entry] + # (with the late hand-off, the IR belongs to another LLVM library) + context!(context(ir)) do + @test all(!endswith(gv.name, "_box") for gv in ir.globals) + @test [f for f in ir.functions if !LLVM.isdeclaration(f)] == [meta.entry] + end dispose(ir) end diff --git a/test/spirv/atomics.jl b/test/spirv/atomics.jl index f1ca7f37..d2342798 100644 --- a/test/spirv/atomics.jl +++ b/test/spirv/atomics.jl @@ -681,6 +681,7 @@ end script = """ using GPUCompiler, LLVM, SPIRV_LLVM_Translator_jll, SPIRV_Tools_jll include($(repr(joinpath(@__DIR__, "..", "helpers", "runtime.jl")))) + include($(repr(joinpath(@__DIR__, "..", "helpers", "handoff.jl")))) include($(repr(joinpath(@__DIR__, "..", "helpers", "spirv.jl")))) failures, rejected = SPIRV.check_atomics_matrix(:khronos) foreach(println, failures) @@ -719,6 +720,7 @@ end script = """ using GPUCompiler, LLVM include($(repr(joinpath(@__DIR__, "..", "helpers", "runtime.jl")))) + include($(repr(joinpath(@__DIR__, "..", "helpers", "handoff.jl")))) include($(repr(joinpath(@__DIR__, "..", "helpers", "spirv.jl")))) import .SPIRV: Atomics diff --git a/test/spirv/imaging.jl b/test/spirv/imaging.jl index 17639fbb..0d330506 100644 --- a/test/spirv/imaging.jl +++ b/test/spirv/imaging.jl @@ -5,6 +5,7 @@ script = """ using GPUCompiler, LLVM, LLVM.IR include($(repr(joinpath(@__DIR__, "..", "helpers", "runtime.jl")))) + include($(repr(joinpath(@__DIR__, "..", "helpers", "handoff.jl")))) include($(repr(joinpath(@__DIR__, "..", "helpers", "spirv.jl")))) function kernel(out::Core.LLVMPtr{UInt,1})