From 43401153b061761a44aa18050da46a09c3a9a040 Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Tue, 24 Nov 2026 15:03:52 +0100 Subject: [PATCH 1/6] Keep the target's non-integral address spaces when removing Julia's GPUCompiler adds Julia's non-integral address spaces to the target's datalayout, and removes them again after optimization with Julia's RemoveNI pass. That pass removes the first `ni` component of the layout, which for targets with non-integral address spaces of their own, like AMDGPU, was the target's: those were lost before code generation, and Julia's kept. Julia's now come first. --- src/interface.jl | 8 ++++++-- test/gcn.jl | 18 ++++++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/src/interface.jl b/src/interface.jl index ac764f5d..dd3960e8 100644 --- a/src/interface.jl +++ b/src/interface.jl @@ -59,11 +59,15 @@ end llvm_targetinfo(@nospecialize(target::AbstractCompilerTarget)) = nothing # the target's datalayout, with Julia's non-integral address spaces added to it, as a -# `DataLayout` the caller owns (or `nothing`) +# `DataLayout` the caller owns (or `nothing`). they come before the target's own +# non-integral address spaces (e.g. AMDGPU's), as `RemoveNIPass` removes the first set. function julia_datalayout(@nospecialize(target::AbstractCompilerTarget)) dl = llvm_datalayout(target)::Union{Nothing,String} dl === nothing && return nothing - LLVM.DataLayout(dl * "-ni:10:11:12:13") + components = split(dl, '-') + i = something(findfirst(startswith("ni:"), components), length(components) + 1) + insert!(components, i, "ni:10:11:12:13") + LLVM.DataLayout(join(components, '-')) end have_fma(@nospecialize(target::AbstractCompilerTarget), T::Type) = false diff --git a/test/gcn.jl b/test/gcn.jl index 84c43b41..40f6fb34 100644 --- a/test/gcn.jl +++ b/test/gcn.jl @@ -41,6 +41,24 @@ end @testset "IR" begin +@testset "non-integral address spaces" begin + # Julia's are removed after optimization, AMDGPU's are kept for its back-end + mod = @eval module $(gensym()) + kernel() = return + end + job, _ = GCN.create_job(mod.kernel, Tuple{}; kernel=true) + JuliaContext() do ctx + target_ni = filter(startswith("ni:"), + split(GPUCompiler.llvm_datalayout(job.config.target), '-')) + @test !isempty(target_ni) + ir, _ = GPUCompiler.compile(:llvm, job) + layout = string(LLVM.datalayout(ir)) + @test all(ni -> occursin("-$ni", layout), target_ni) + @test !occursin("ni:10:11:12:13", layout) + dispose(ir) + end +end + @testset "runtime symbol lookup" begin # A libjulia ccall emits a lookup through jl_libjulia_internal_handle. Its global # lives in AS1 on GCN, while jl_load_and_lookup takes a generic pointer. From 02827868f37bcbafae3f6b67164dee706dc4fa04 Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Tue, 24 Nov 2026 13:54:46 +0100 Subject: [PATCH 2/6] Split optimization and target finalization out of `emit_llvm` `emit_llvm` generates the IR, links what it needs, and then optimizes, finalizes and validates it. Moving the second half into `finish_llvm!` gives that part a single entry point, so that it can run in another LLVM context than the first. --- src/driver.jl | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/src/driver.jl b/src/driver.jl index 8e9ed0b1..7878106b 100644 --- a/src/driver.jl +++ b/src/driver.jl @@ -562,7 +562,7 @@ end 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 @@ -605,7 +605,21 @@ end prune_dead_relocations!(ir, relocations) bake_relocations!(ir, relocations) end + end + end + return finish_llvm!(job, ir, entry, entry_fn, entrypoints, compiled, relocations, + has_deferred_jobs, resolve_early) +end + +# optimize the linked IR, finalize it for the target, validate it and collect relocations +function finish_llvm!(@nospecialize(job::CompilerJob), ir::LLVM.Module, + entry::LLVM.Function, entry_fn::String, entrypoints, compiled, + relocations::Relocations, has_deferred_jobs::Bool, + resolve_early::Bool) + exception_sites = ExceptionSite[] + @tracepoint "IR finalization" begin + if job.config.toplevel if job.config.optimize @tracepoint "optimization" begin optimize!(job, ir, relocations; job.config.opt_level) From 0c341faa37f897887790da4ce043da6c0055aacb Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Thu, 26 Nov 2026 13:16:39 +0100 Subject: [PATCH 3/6] Return no target machine when LLVM lacks the target `llvm_machine` is documented to return `nothing` for targets the LLVM library doesn't support, but the default method and BPF's threw instead, so compiling for BPF failed with a Julia whose LLVM lacks that back-end, already during IR generation. Look the target up without throwing, like the PTX and GCN methods check for their back-ends. --- src/bpf.jl | 3 ++- src/interface.jl | 16 ++++++++++++++-- test/utils.jl | 10 ++++++++++ 3 files changed, 26 insertions(+), 3 deletions(-) diff --git a/src/bpf.jl b/src/bpf.jl index 75ac16b8..089cdc2c 100644 --- a/src/bpf.jl +++ b/src/bpf.jl @@ -13,7 +13,8 @@ llvm_datalayout(::BPFCompilerTarget) = "e-m:e-p:64:64-i64:64-n32:64-S128" function llvm_machine(target::BPFCompilerTarget) triple = llvm_triple(target) - t = LLVM.Target(;triple=triple) + t = lookup_target(triple) + t === nothing && return nothing cpu = "" feat = "" diff --git a/src/interface.jl b/src/interface.jl index dd3960e8..9e1aa33c 100644 --- a/src/interface.jl +++ b/src/interface.jl @@ -23,12 +23,13 @@ source_code(@nospecialize(target::AbstractCompilerTarget)) = "text" llvm_triple(@nospecialize(target::AbstractCompilerTarget)) = error("Not implemented") -# may return nothing if the target is not support by the current version of LLVM. +# may return nothing if the target is not supported by the active LLVM library. # the caller owns the returned target machine; see `with_llvm_machine`. function llvm_machine(@nospecialize(target::AbstractCompilerTarget)) triple = llvm_triple(target) - t = LLVM.Target(triple=triple) + t = lookup_target(triple) + t === nothing && return nothing tm = LLVM.TargetMachine(t, triple) LLVM.asm_verbosity!(tm, true) @@ -36,6 +37,17 @@ function llvm_machine(@nospecialize(target::AbstractCompilerTarget)) return tm end +# the target of the active LLVM library for `triple`, or `nothing` if it lacks one +function lookup_target(triple::String) + t = Ref{LLVM.API.LLVMTargetRef}() + message = Ref{Cstring}(C_NULL) + if LLVM.API.LLVMGetTargetFromTriple(triple, t, message) |> Bool + message[] == C_NULL || LLVM.API.LLVMDisposeMessage(message[]) + return nothing + end + return LLVM.Target(t[]) +end + # call `f` with a target machine for `target`, or with `nothing` if there is none, and dispose # of the target machine afterwards function with_llvm_machine(f, @nospecialize(target::AbstractCompilerTarget)) diff --git a/test/utils.jl b/test/utils.jl index 8af8ae55..d83860b2 100644 --- a/test/utils.jl +++ b/test/utils.jl @@ -379,3 +379,13 @@ end @test GPUCompiler.deserves_argbox(BigWithPointer) @test !GPUCompiler.deserves_argbox(NTuple{4100, Float64}) end + +# a target that no LLVM library has +struct UnknownTarget <: GPUCompiler.AbstractCompilerTarget end +GPUCompiler.llvm_triple(::UnknownTarget) = "unknown-unknown-unknown" + +@testset "target machines" begin + # targets that the LLVM library lacks have no target machine + @test GPUCompiler.llvm_machine(UnknownTarget()) === nothing + @test GPUCompiler.with_llvm_machine(tm -> tm isa LLVM.TargetMachine, NativeCompilerTarget()) +end From 9950431ecbac8abee41479f59bb894cd270ba5f2 Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Wed, 25 Nov 2026 15:42:37 +0100 Subject: [PATCH 4/6] Ask the back-ends for the version of their LLVM `backend_llvm_version` derived the version of the external GCN back-end's LLVM from the version of AMDGPU_LLVM_Backend_jll, which will stop matching LLVM's once that package is versioned independently (JuliaGPU/AMDGPU.jl#1247). The back-end libraries report it through `GetLLVMVersion`, every build of them since they became libraries. Make the query generic and public, so that downstream packages can ask it instead of looking at package versions (e.g. CUDA.jl for the PTX ISA versions the back-end supports): it returns the version of the LLVM that generates the target's machine code, from NVPTX_LLVM_Backend_jll, SPIRV_LLVM_Backend_jll or AMDGPU_LLVM_Backend_jll, or `nothing` when that is not LLVM (libNVVM, the Khronos translator, Apple's Metal compiler). --- src/gcn.jl | 13 +++++-------- src/interface.jl | 12 ++++++++++++ src/metal.jl | 3 +++ src/ptx.jl | 9 +++++++++ src/spirv.jl | 9 +++++++++ src/utils.jl | 8 ++++++++ test/gcn.jl | 9 +++++++++ test/utils.jl | 27 +++++++++++++++++++++++++++ 8 files changed, 82 insertions(+), 8 deletions(-) diff --git a/src/gcn.jl b/src/gcn.jl index 0ce8c34e..c9aa94f5 100644 --- a/src/gcn.jl +++ b/src/gcn.jl @@ -298,18 +298,15 @@ const AMDGPUObjectFile = Cint(1) return String(code) 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() - 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() - version = pkgversion(jll) - return VersionNumber(version.major, version.minor, version.patch) + if target.backend === :external && + isavailable(AMDGPU_LLVM_Backend_jll) && AMDGPU_LLVM_Backend_jll.is_available() + return llvm_version(ExternalBackend(AMDGPU_LLVM_Backend_jll.libamdgpu, "AMDGPU")) + end + return @invoke backend_llvm_version(target::AbstractCompilerTarget) end - ## validation # Atomic operations and fences come from many front-ends (AMDGPU.jl's atomic functions, diff --git a/src/interface.jl b/src/interface.jl index 9e1aa33c..18ed105f 100644 --- a/src/interface.jl +++ b/src/interface.jl @@ -58,6 +58,18 @@ function with_llvm_machine(f, @nospecialize(target::AbstractCompilerTarget)) end end +""" + backend_llvm_version(target::AbstractCompilerTarget)::Union{VersionNumber,Nothing} + +The version of the LLVM that generates machine code for `target`, which can differ from +the one GPUCompiler runs in, or `nothing` when code is not generated by LLVM (e.g. by +libNVVM, or Apple's Metal compiler). Without the back-end library that a target needs (e.g. +NVPTX_LLVM_Backend_jll), which code generation then reports, it is the version of the LLVM +GPUCompiler runs in. +""" +backend_llvm_version(@nospecialize(target::AbstractCompilerTarget)) = LLVM.version() +@public backend_llvm_version + # the target's datalayout as a string, or `nothing` llvm_datalayout(target::AbstractCompilerTarget) = with_llvm_machine(target) do tm tm === nothing && return nothing diff --git a/src/metal.jl b/src/metal.jl index 2363f986..606c793c 100644 --- a/src/metal.jl +++ b/src/metal.jl @@ -94,6 +94,9 @@ source_code(target::MetalCompilerTarget) = "llvm" # Metal is not supported by our LLVM builds, so we can't get a target machine llvm_machine(::MetalCompilerTarget) = nothing +# Apple's compiler generates code from the AIR +backend_llvm_version(::MetalCompilerTarget) = nothing + # Apple's toolchain encodes the AIR version in the architecture component of the triple, as # `air64_v` (e.g. `air64_v26` for AIR 2.6). Tools like metal-opt derive the # expected AIR version from the triple and complain when the `air.version` module metadata diff --git a/src/ptx.jl b/src/ptx.jl index f13350db..8d06a4b8 100644 --- a/src/ptx.jl +++ b/src/ptx.jl @@ -102,6 +102,15 @@ function llvm_machine(target::PTXCompilerTarget) return LLVM.TargetMachine(t, triple) end +function backend_llvm_version(target::PTXCompilerTarget) + target.backend === :nvvm && return nothing + # (without the back-end, `mcgen` reports a clearer error) + if isavailable(NVPTX_LLVM_Backend_jll) && NVPTX_LLVM_Backend_jll.is_available() + return llvm_version(ExternalBackend(NVPTX_LLVM_Backend_jll.libnvptx, "NVPTX")) + end + return @invoke backend_llvm_version(target::AbstractCompilerTarget) +end + # match the layout computed by the NVPTX back-end (computeNVPTXDataLayout); components # that match LLVM's defaults (small integers, floats, common vectors) are left implicit. # note that the external back-end ignores the module datalayout and recomputes it from diff --git a/src/spirv.jl b/src/spirv.jl index 8c5b591c..d4fa14c9 100644 --- a/src/spirv.jl +++ b/src/spirv.jl @@ -96,6 +96,15 @@ end # SPIRV is not supported by our LLVM builds, so we can't get a target machine llvm_machine(::SPIRVCompilerTarget) = nothing +function backend_llvm_version(target::SPIRVCompilerTarget) + target.backend === :khronos && return nothing + # (without the back-end, `mcgen` reports a clearer error) + if isavailable(SPIRV_LLVM_Backend_jll) && SPIRV_LLVM_Backend_jll.is_available() + return llvm_version(ExternalBackend(SPIRV_LLVM_Backend_jll.libspirv, "SPIRV")) + end + return @invoke backend_llvm_version(target::AbstractCompilerTarget) +end + function runtime_cstring_type(job::CompilerJob{SPIRVCompilerTarget}) LLVM.DataLayout(llvm_datalayout(job.config.target)) do dl Core.LLVMPtr{Cchar, dl.globals_addrspace} diff --git a/src/utils.jl b/src/utils.jl index 3c95c3ab..73d093a1 100644 --- a/src/utils.jl +++ b/src/utils.jl @@ -82,6 +82,14 @@ function api(backend::ExternalBackend, name::String) Libdl.dlsym(Libdl.dlopen(backend.library), Symbol(backend.prefix * name)) end +# the version of the LLVM that the back-end is built on +function llvm_version(backend::ExternalBackend) + major, minor, patch = Ref{Cuint}(), Ref{Cuint}(), Ref{Cuint}() + @ccall $(api(backend, "GetLLVMVersion"))(major::Ptr{Cuint}, minor::Ptr{Cuint}, + patch::Ptr{Cuint})::Cvoid + return VersionNumber(major[], minor[], patch[]) +end + function external_diagnostic(severity::Cint, message::Cstring, ctx::Ptr{Cvoid}) diagnostics = unsafe_pointer_to_objref(ctx)::Vector{String} # errors are folded into the failure message by the back-end; only keep what would diff --git a/test/gcn.jl b/test/gcn.jl index 40f6fb34..44874cac 100644 --- a/test/gcn.jl +++ b/test/gcn.jl @@ -37,6 +37,15 @@ sink_gcn(i) = sink(i, Val(5)) # an unknown back-end is rejected at machine-code generation @test_throws "Unsupported GCN back-end" GCN.code_native(devnull, mod.kernel, Tuple{}; backend=:bogus) + + # the external back-end reports the version of its LLVM + major, minor, patch = Ref{Cuint}(), Ref{Cuint}(), Ref{Cuint}() + ccall((:AMDGPUGetLLVMVersion, AMDGPU_LLVM_Backend_jll.libamdgpu), Cvoid, + (Ref{Cuint}, Ref{Cuint}, Ref{Cuint}), major, minor, patch) + @test GPUCompiler.backend_llvm_version(GCNCompilerTarget("gfx900"; backend=:external)) == + VersionNumber(major[], minor[], patch[]) + @test GPUCompiler.backend_llvm_version(GCNCompilerTarget("gfx900"; backend=:inprocess)) == + LLVM.version() end @testset "IR" begin diff --git a/test/utils.jl b/test/utils.jl index d83860b2..3da5e3bf 100644 --- a/test/utils.jl +++ b/test/utils.jl @@ -389,3 +389,30 @@ GPUCompiler.llvm_triple(::UnknownTarget) = "unknown-unknown-unknown" @test GPUCompiler.llvm_machine(UnknownTarget()) === nothing @test GPUCompiler.with_llvm_machine(tm -> tm isa LLVM.TargetMachine, NativeCompilerTarget()) end + +@testset "back-end LLVM versions" begin + # the back-end libraries report the version of their LLVM + function library_version(library, prefix) + major, minor, patch = Ref{Cuint}(), Ref{Cuint}(), Ref{Cuint}() + Libdl = GPUCompiler.Libdl + f = Libdl.dlsym(Libdl.dlopen(library), "$(prefix)GetLLVMVersion") + ccall(f, Cvoid, (Ref{Cuint}, Ref{Cuint}, Ref{Cuint}), major, minor, patch) + VersionNumber(major[], minor[], patch[]) + end + if NVPTX_LLVM_Backend_jll.is_available() + @test GPUCompiler.backend_llvm_version(PTXCompilerTarget(; cap=v"7.0")) == + library_version(NVPTX_LLVM_Backend_jll.libnvptx, "NVPTX") + end + if SPIRV_LLVM_Backend_jll.is_available() + @test GPUCompiler.backend_llvm_version(SPIRVCompilerTarget(; backend=:llvm)) == + library_version(SPIRV_LLVM_Backend_jll.libspirv, "SPIRV") + end + @test GPUCompiler.backend_llvm_version(NativeCompilerTarget()) == LLVM.version() + + # code generators that aren't LLVM + @test GPUCompiler.backend_llvm_version(PTXCompilerTarget(; cap=v"7.0", backend=:nvvm)) === + nothing + @test GPUCompiler.backend_llvm_version(SPIRVCompilerTarget(; backend=:khronos)) === nothing + @test GPUCompiler.backend_llvm_version( + MetalCompilerTarget(; macos=v"15", metal=v"3.2", air=v"2.7")) === nothing +end From 7f043a447094c1ed13ee75f19b0fea13ec02aa01 Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Thu, 26 Nov 2026 13:18:16 +0100 Subject: [PATCH 5/6] Add an llvmgpu toolchain, optimizing with a newer LLVM GPUCompiler optimizes code with Julia's LLVM, which is old and fixed for each Julia release, so improvements to LLVM's optimizer reach GPU code a year or more late, and GPU code depends on Julia's LLVM keeping back-ends that Julia itself doesn't need. The `toolchain` preference now selects between that default (`"julia"`) and `"llvmgpu"`, which moves the linked and post-processed module of every top-level job for a GPU target as bitcode to libLLVMGPU, a standalone LLVM 23 from LLVMGPU_jll. Optimization, target finalization, validation and code generation then happen there: libLLVMGPU's back-ends generate PTX, GCN, SPIR-V and BPF code, libNVVM gets the optimized code downgraded to the newest bitcode it reads, the Khronos translator gets it as is, and Metal code is downgraded to AIR as before. Julia's code generator keeps emitting into Julia's LLVM. The library that optimizes a target's code is `llvm_library(target)`. It defaults to Julia's LLVM, so the host target and targets defined elsewhere (Enzyme's, CPU targets) keep their behavior; GPUCompiler's PTX, GCN, SPIR-V, Metal and BPF targets return `toolchain_library()`, libLLVMGPU under the preference, which other targets can opt into. Passes follow the module's library: Julia's C++ passes in Julia's LLVM, JuliaIR.jl's ports of them in libLLVMGPU, so contexts of Julia's LLVM keep using typed pointers on Julia 1.10 and 1.11. `backend_llvm_version` defaults to the version of that library, and GCN targets only support `backend=:external` under the preference. The preference is read when GPUCompiler is compiled, so changing it recompiles GPUCompiler and the packages that depend on it, and caches never mix code of both toolchains. With llvmgpu, `JuliaContext() do ... end` also creates a context of libLLVMGPU, which owns the IR of the jobs that move. The do-block form of `compile` runs its block in the context of the IR; other callers have to work with it inside `context!(context(ir))`, as LLVM.jl passes values to the current library. Hooks that run during or after optimization run in that context too, including `link_libraries!` when optimization calls it again, and `convert(LLVMType, T)` lowers Julia types in it (since LLVM.jl 10.8). libNVVM reads bitcode of LLVM 22 at most, so newer bitcode is downgraded to the newest format LLVMDowngrader_jll emits up to that (LLVM 22 with 0.13, 20 before), which also covers a future Julia on LLVM 23 with the default toolchain. --- .gitignore | 2 +- Project.toml | 8 +- README.md | 49 ++++++++ src/GPUCompiler.jl | 2 + src/bpf.jl | 2 + src/driver.jl | 85 +++++++++---- src/gcn.jl | 59 +++++++-- src/interface.jl | 66 ++++++++-- src/mcgen.jl | 1 + src/metal.jl | 13 ++ src/optim.jl | 48 +++---- src/ptx.jl | 84 +++++++++++-- src/reflection.jl | 11 +- src/spirv.jl | 33 ++++- src/toolchain.jl | 191 ++++++++++++++++++++++++++++ test/gcn.jl | 61 ++++++--- test/helpers/toolchain.jl | 12 ++ test/metal.jl | 52 ++++---- test/ptx.jl | 14 ++- test/runtests.jl | 3 +- test/spirv.jl | 19 +-- test/toolchain.jl | 256 ++++++++++++++++++++++++++++++++++++++ test/utils.jl | 7 +- 23 files changed, 944 insertions(+), 134 deletions(-) create mode 100644 src/toolchain.jl create mode 100644 test/helpers/toolchain.jl create mode 100644 test/toolchain.jl diff --git a/.gitignore b/.gitignore index 22936030..9a664541 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,4 @@ test/Manifest.toml -test/LocalPreferences.toml +LocalPreferences.toml Manifest.toml Manifest-*.toml diff --git a/Project.toml b/Project.toml index 48ba3a47..866868e3 100644 --- a/Project.toml +++ b/Project.toml @@ -10,7 +10,9 @@ projects = ["test"] CompilerCaching = "9db33cc3-5358-4881-8759-fa4194144afd" ExprTools = "e2ba6199-217a-4e67-a87a-7c52f15ade04" InteractiveUtils = "b77e0a4c-d291-57a0-90e8-8db25a27a240" +JuliaIR = "3913dba9-7ba9-44aa-bf76-1cfa3b3073b1" LLVM = "929cbde3-209d-540e-8aea-75f648917ca0" +LLVMGPU_jll = "a5c41ef1-0fc2-5e62-838b-0d6f5f7d5115" Libdl = "8f399da3-3557-5675-b5ff-fb832c97cbdb" Logging = "56ddb016-857b-54e1-b83d-db4d58db5568" PrecompileTools = "aea7be01-6a6a-4083-8856-8a6e6704d82a" @@ -46,8 +48,10 @@ Cthulhu = "2, 3" ExprTools = "0.1" Highlights = "0.6" InteractiveUtils = "1" -LLVM = "10.4" -LLVMDowngrader_jll = "0.11, 0.12" +JuliaIR = "0.2" +LLVM = "10.8.1" +LLVMGPU_jll = "1.5" +LLVMDowngrader_jll = "0.11, 0.12, 0.13" Libdl = "1" Logging = "1" NVPTX_LLVM_Backend_jll = "23" diff --git a/README.md b/README.md index fc8988a2..cbb62197 100644 --- a/README.md +++ b/README.md @@ -51,3 +51,52 @@ last commit of a pull request: Back-ends are named `cuda`, `amdgpu`, `metal`, `oneapi` and `opencl` (all lowercase), or by their target: `ptx` for CUDA.jl, `gcn` for AMDGPU.jl, and `spirv` for both oneAPI.jl and OpenCL.jl. + + +## LLVM toolchain + +By default, GPUCompiler optimizes code with Julia's own LLVM, including the LLVM passes of +Julia's code generator, and generates code with back-end libraries (e.g. +NVPTX_LLVM_Backend_jll). The experimental `llvmgpu` toolchain instead moves the code of +every top-level job for a GPU target (PTX, GCN, SPIR-V, Metal and BPF) to libLLVMGPU, a +newer, standalone LLVM from LLVMGPU_jll, once it is linked and post-processed (e.g. by +`finish_linked_module!`), and optimizes it there with +[JuliaIR.jl](https://github.com/JuliaLLVM/JuliaIR.jl)'s ports of Julia's passes. +libLLVMGPU then also generates code for the PTX, GCN, SPIR-V and BPF targets, except for +the alternative code generators: libNVVM (`backend=:nvvm`), which gets the optimized code +downgraded with LLVMDowngrader_jll, and the Khronos SPIR-V translator (`backend=:khronos`). +Metal code is optimized there too, and downgraded to AIR as before. The toolchain is +selected with a preference, which takes effect after restarting Julia: + +```julia +using Preferences, GPUCompiler +set_preferences!(GPUCompiler, "toolchain" => "llvmgpu") +``` + +The IR that `GPUCompiler.compile` returns for jobs that moved to libLLVMGPU (the module, +`meta.ir` and `meta.entry`) then belongs to that library, and LLVM.jl only works with it +in its own context. The do-block form of `compile` takes care of that, with either +toolchain: it compiles in contexts of its own, runs the block in the context of the IR, +and frees both afterwards. + +```julia +entry = GPUCompiler.compile(:obj, job) do obj, meta + meta.entry.name +end +``` + +Code that calls `compile(target, job)` inside a `JuliaContext() do ... end` block, which +owns and frees the contexts, has to work with the IR inside +`LLVM.context!(LLVM.context(ir)) do ... end`. (As with Julia's LLVM, the IR belongs to the +context of libLLVMGPU that was activated last, normally the block's.) Hooks that run during or after optimization +run in that context too: e.g. `optimize_module!`, `finish_ir!`, and `link_libraries!`, +which optimization can call again after it ran with Julia's LLVM. `code_llvm` prints that +IR with LLVM's printer, which shows all metadata. + +Code for other targets, like the host's or ones defined elsewhere, stays with Julia's LLVM. +Targets defined elsewhere can move to libLLVMGPU too, by defining +`GPUCompiler.llvm_library(::MyTarget) = GPUCompiler.toolchain_library()`. +`GPUCompiler.backend_llvm_version(target)` tells which LLVM generates the machine code. + +To run the test suite with the llvmgpu toolchain, set the preference in +`test/LocalPreferences.toml` (on Julia 1.10 and 1.11, in `LocalPreferences.toml`). diff --git a/src/GPUCompiler.jl b/src/GPUCompiler.jl index 1d990120..98df0342 100644 --- a/src/GPUCompiler.jl +++ b/src/GPUCompiler.jl @@ -61,6 +61,7 @@ include("mangling.jl") # compiler interface and implementations include("interface.jl") +include("toolchain.jl") include("relocation.jl") include("atomics.jl") include("error.jl") @@ -96,6 +97,7 @@ include("precompile.jl") function __init__() STDERR_HAS_COLOR[] = get(stderr, :color, false) empty!(session_results_cache) + llvmgpu_state_ref[] = nothing @static if !HAS_INTEGRATED_CACHE # CodeInstances created by GPUCompiler's precompile workload are process-local. diff --git a/src/bpf.jl b/src/bpf.jl index 089cdc2c..9fa5f736 100644 --- a/src/bpf.jl +++ b/src/bpf.jl @@ -11,6 +11,8 @@ end llvm_triple(::BPFCompilerTarget) = "bpf-bpf-bpf" llvm_datalayout(::BPFCompilerTarget) = "e-m:e-p:64:64-i64:64-n32:64-S128" +llvm_library(::BPFCompilerTarget) = toolchain_library() + function llvm_machine(target::BPFCompilerTarget) triple = llvm_triple(target) t = lookup_target(triple) diff --git a/src/driver.jl b/src/driver.jl index 7878106b..02d433ef 100644 --- a/src/driver.jl +++ b/src/driver.jl @@ -18,19 +18,28 @@ export JuliaContext # JuliaContext helper below, which returns a local context on Julia 1.9, and the global # unique context on all other versions. Once we only support Julia 1.9, we'll deprecate # this helper to a regular `Context()` call. +# +# The context always belongs to Julia's LLVM, whose code generator GPUCompiler uses, also +# when it is created while another library is active (e.g. to inspect IR that the +# `llvmgpu` toolchain returned). With that toolchain, the do-block form also owns a context +# of libLLVMGPU, which the modules of top-level jobs move to. 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) + TOOLCHAIN === :llvmgpu || return f(ctx) + # (activated without switching the current library) + @dispose gpu_ctx=Context(; library=llvmgpu_state().library) begin + f(ctx) + end end end end @@ -83,8 +92,13 @@ 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. The do-block form, `compile(f, target, job)`, takes -care of both. +and dispose of it, within that block. With the `llvmgpu` toolchain (see the README), that +context can belong to libLLVMGPU rather than Julia's LLVM: work with the module and its +values inside `context!(context(ir)) do ... end`. As with Julia's LLVM, the context is the +one of that library that the task activated last, which is the block's unless the caller +created one inside it. The do-block form, +`compile(f, target, job)`, takes care of all of this, and is the preferred way to use the +IR. """ function compile(target::Symbol, @nospecialize(job::CompilerJob)) run_compile_hook(job) @@ -99,9 +113,10 @@ end Compile `job` as `compile(target, job)` does, in an LLVM context of its own, and return `f(result, meta)`. `result` is the module for `:llvm`, and the code otherwise. -`f` runs with the context of the IR active, so it can work with the module and its values -directly. The IR and its context are freed when `f` returns: return only values that don't -refer to them, e.g., strings, or the code. +`f` runs with the context of the IR active, whichever LLVM library it belongs to (see the +`llvmgpu` toolchain in the README), so it can work with the module and its values +directly. The IR and its context are freed when `f` returns: return only values that +don't refer to them, e.g., strings, or the code. ```julia compile(:obj, job) do obj, meta @@ -113,10 +128,12 @@ function compile(f, target::Symbol, @nospecialize(job::CompilerJob)) return JuliaContext() do _ result, meta = compile(target, job) ir = target === :llvm ? result : meta.ir - try - f(result, meta) - finally - dispose(ir) + in_context(ir) do + try + f(result, meta) + finally + dispose(ir) + end end end end @@ -137,6 +154,11 @@ function compile_unhooked(output::Symbol, @nospecialize(job::CompilerJob); if context(; throw_error=false) === nothing error("No active LLVM context. Use `JuliaContext()` do-block syntax to create one.") end + # Julia's code generator only works with Julia's LLVM (e.g. not in the context of IR + # that the `llvmgpu` toolchain returned) + if context().library !== LLVM.Library(:julia) + error("Julia code can only be compiled in a context of Julia's LLVM, not of LLVM library :$(context().library.name); use a `JuliaContext()` block") + end @tracepoint "Validation" begin check_method(job) # not optional @@ -152,7 +174,7 @@ function compile_unhooked(output::Symbol, @nospecialize(job::CompilerJob); if output == :llvm if job.config.strip - @tracepoint "strip debug info" strip_debuginfo!(ir) + @tracepoint "strip debug info" in_context(() -> strip_debuginfo!(ir), ir) end return ir, ir_meta @@ -608,8 +630,24 @@ end end end - return finish_llvm!(job, ir, entry, entry_fn, entrypoints, compiled, relocations, - has_deferred_jobs, resolve_early) + # the rest of the pipeline runs with the LLVM library that optimizes the code (see + # `llvm_library`) + if uses_llvmgpu(job) + # (in a new variable, which the closures above don't capture) + moved = @tracepoint "move to libLLVMGPU" move_to_llvmgpu!(ir) + # (rebound, as capturing variables that are assigned more than once boxes them) + let entry_fn = entry_fn, resolve_early = resolve_early + return context!(context(moved)) do + # (by name, as `finish_linked_module!` may have replaced `entry`) + finish_llvm!(job, moved, moved.functions[entry_fn], entry_fn, + entrypoints, compiled, relocations, has_deferred_jobs, + resolve_early) + end + end + else + return finish_llvm!(job, ir, entry, entry_fn, entrypoints, compiled, relocations, + has_deferred_jobs, resolve_early) + end end # optimize the linked IR, finalize it for the target, validate it and collect relocations @@ -746,15 +784,18 @@ emit_asm(@nospecialize(job::CompilerJob), ir::LLVM.Module, @locked function emit_asm(@nospecialize(job::CompilerJob), ir::LLVM.Module, relocs::Relocations, format::LLVM.CodeGenFileType.T) - # NOTE: strip after validation to get better errors - if job.config.strip - @tracepoint "Debug info removal" strip_debuginfo!(ir) - end + # (the module may belong to libLLVMGPU, with the `llvmgpu` toolchain) + code = in_context(ir) do + # NOTE: strip after validation to get better errors + if job.config.strip + @tracepoint "Debug info removal" strip_debuginfo!(ir) + end - @tracepoint "LLVM back-end" begin - @tracepoint "preparation" prepare_execution!(job, ir, relocs) + @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 c9aa94f5..cab7d170 100644 --- a/src/gcn.jl +++ b/src/gcn.jl @@ -12,11 +12,21 @@ Base.@kwdef struct GCNCompilerTarget <: AbstractCompilerTarget dev_isa::String features::String="" - backend::Symbol = isavailable(AMDGPU_LLVM_Backend_jll) ? :external : :inprocess + # the LLVM that generates code: an external one (`:external`; AMDGPU_LLVM_Backend_jll, + # or libLLVMGPU with the `llvmgpu` toolchain) or Julia's (`:inprocess`) + backend::Symbol = TOOLCHAIN === :llvmgpu || isavailable(AMDGPU_LLVM_Backend_jll) ? + :external : :inprocess # optional launch bounds (scalar or per-dimension; flattened to their product) minthreads::Union{Nothing,Int,NTuple{<:Any,Int}} = nothing maxthreads::Union{Nothing,Int,NTuple{<:Any,Int}} = nothing + + function GCNCompilerTarget(dev_isa, features, backend, minthreads, maxthreads) + if TOOLCHAIN === :llvmgpu && backend !== :external + error("The llvmgpu toolchain generates GCN code with libLLVMGPU, so it only supports `backend=:external`, not $(repr(backend)).") + end + new(dev_isa, features, backend, minthreads, maxthreads) + end end function Base.hash(target::GCNCompilerTarget, h::UInt) @@ -33,7 +43,10 @@ llvm_triple(::GCNCompilerTarget) = "amdgcn-amd-amdhsa" source_code(target::GCNCompilerTarget) = "gcn" +llvm_library(::GCNCompilerTarget) = toolchain_library() + function llvm_machine(target::GCNCompilerTarget) + is_llvmgpu() && return llvmgpu_machine(target) @static if :AMDGPU ∉ LLVM.backends() return nothing end @@ -49,9 +62,38 @@ function llvm_machine(target::GCNCompilerTarget) 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 +# a target machine of libLLVMGPU. 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 llvmgpu_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) + @dispose sti=LLVM.SubtargetInfo(t, triple) begin + LLVM.isprocessor(sti, cpu) || + error("Unsupported processor $cpu for the AMDGPU back-end") + 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 + + # (the ABI name selects that alignment, a patch of the library's AMDGPU back-end) + abi = Base.datatype_alignment(Int128) == 8 ? "i128:64" : "" + tm = LLVM.TargetMachine(t, triple; cpu, features, reloc=LLVM.RelocMode.PIC, abi) + LLVM.asm_verbosity!(tm, true) + return tm +end + +# the external back-end and libLLVMGPU replace the module's datalayout with their own, +# which aligns i128 to 16 bytes. they do 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 # arguments like the host does. function llvm_datalayout(target::GCNCompilerTarget) dl = @invoke llvm_datalayout(target::AbstractCompilerTarget) @@ -257,7 +299,9 @@ const AMDGPUObjectFile = Cint(1) mod::LLVM.Module, format=LLVM.CodeGenFileType.Assembly) target = job.config.target - if target.backend === :inprocess + if is_llvmgpu(mod.library) + return String(llvmgpu_emit(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.") @@ -300,13 +344,14 @@ end function backend_llvm_version(target::GCNCompilerTarget) # (without the back-end, `mcgen` reports a clearer error) - if target.backend === :external && + if TOOLCHAIN === :julia && target.backend === :external && isavailable(AMDGPU_LLVM_Backend_jll) && AMDGPU_LLVM_Backend_jll.is_available() return llvm_version(ExternalBackend(AMDGPU_LLVM_Backend_jll.libamdgpu, "AMDGPU")) end return @invoke backend_llvm_version(target::AbstractCompilerTarget) end + ## validation # Atomic operations and fences come from many front-ends (AMDGPU.jl's atomic functions, @@ -409,7 +454,7 @@ function needs_cmpxchg_expansion(target::GCNCompilerTarget, version::VersionNumb # flat memory, and for local memory before gfx12, failing with "Cannot select" # (llvm/llvm-project#229442). Expand it on flat memory on every target, where LLVM # otherwise expands it depending on the scope and metadata. AMDGPU_LLVM_Backend_jll - # carries the fix since 23.1.3, so only Julia's own LLVM needs this. + # (since 23.1.3) and libLLVMGPU carry the fix, so only Julia's own LLVM needs this. if target.backend === :inprocess && version >= v"22" && inst.binop == LLVM.AtomicRMWBinOp.USubSat && T isa LLVM.IntegerType && T.width == 32 as == 0 && return true diff --git a/src/interface.jl b/src/interface.jl index 18ed105f..ea3a5376 100644 --- a/src/interface.jl +++ b/src/interface.jl @@ -58,23 +58,66 @@ function with_llvm_machine(f, @nospecialize(target::AbstractCompilerTarget)) end end +""" + llvm_library(target::AbstractCompilerTarget)::LLVM.Library + +The LLVM library that optimizes the code of top-level jobs for `target`, and generates +machine code for it unless another code generator does (e.g. libNVVM). Julia's code +generator always emits IR into Julia's LLVM; the module moves to this library after +linking. The default is Julia's LLVM. GPUCompiler's GPU targets (PTX, GCN, SPIR-V, Metal +and BPF) use `GPUCompiler.toolchain_library()` instead: Julia's LLVM with the default +`julia` toolchain, and libLLVMGPU with the `llvmgpu` toolchain. Other targets can opt into +that too. Those are the only two libraries supported. A target that forwards +`llvm_datalayout` or `llvm_machine` to another target should forward this as well, so +that its layout comes from the library that optimizes its code. +""" +llvm_library(@nospecialize(target::AbstractCompilerTarget)) = LLVM.Library(:julia) +@public llvm_library + +""" + toolchain_library()::LLVM.Library + +The LLVM library that the selected toolchain optimizes GPU code with: Julia's LLVM, or +libLLVMGPU with the `llvmgpu` toolchain. See [`llvm_library`](@ref). +""" +toolchain_library() = TOOLCHAIN === :llvmgpu ? llvmgpu_state().library : LLVM.Library(:julia) +@public toolchain_library + +# `llvm_library(target)`, which has to be one that the toolchain supports +function checked_llvm_library(@nospecialize(target::AbstractCompilerTarget)) + lib = llvm_library(target) + lib === LLVM.Library(:julia) || is_llvmgpu(lib) || + error("Unsupported LLVM library :$(lib.name) for $target; `llvm_library` can only return Julia's LLVM, or with the llvmgpu toolchain, libLLVMGPU") + return lib +end + """ backend_llvm_version(target::AbstractCompilerTarget)::Union{VersionNumber,Nothing} The version of the LLVM that generates machine code for `target`, which can differ from -the one GPUCompiler runs in, or `nothing` when code is not generated by LLVM (e.g. by -libNVVM, or Apple's Metal compiler). Without the back-end library that a target needs (e.g. -NVPTX_LLVM_Backend_jll), which code generation then reports, it is the version of the LLVM -GPUCompiler runs in. +the one GPUCompiler runs in and the one that optimizes the code (see [`llvm_library`](@ref)), +or `nothing` when code is not generated by LLVM (e.g. by libNVVM, or Apple's Metal +compiler). Without the back-end library that a target needs (e.g. NVPTX_LLVM_Backend_jll), +which code generation then reports, it is the version of the library that optimizes. """ -backend_llvm_version(@nospecialize(target::AbstractCompilerTarget)) = LLVM.version() +backend_llvm_version(@nospecialize(target::AbstractCompilerTarget)) = + LLVM.version(checked_llvm_library(target)) @public backend_llvm_version -# the target's datalayout as a string, or `nothing` -llvm_datalayout(target::AbstractCompilerTarget) = with_llvm_machine(target) do tm - tm === nothing && return nothing - LLVM.DataLayout(tm) do dl - string(dl) +# the target's datalayout as a string, or `nothing`. that of the target machine of the +# library that optimizes the code, also before the module moves there. +function llvm_datalayout(target::AbstractCompilerTarget) + lib = checked_llvm_library(target) + if lib !== LLVM.library() + return LLVM.library!(lib) do + @invoke llvm_datalayout(target::AbstractCompilerTarget) + end + end + with_llvm_machine(target) do tm + tm === nothing && return nothing + LLVM.DataLayout(tm) do dl + string(dl) + end end end @@ -401,6 +444,9 @@ Both relocatable strategies produce session-portable results, enabling persisten relocations permanently roots the referenced Julia values in the process (mirroring Julia's own codegen), so loaders need no GC bookkeeping of their own. +The strategy is selected before the module moves to the library that optimizes it (see +[`llvm_library`](@ref)) and again afterwards, so it must not depend on the active library. + When [`supports_relocatable_ir`](@ref) is false, Julia may still embed unrecorded addresses. A back-end may lower the records it does receive with any strategy, but the result remains session-local regardless. diff --git a/src/mcgen.jl b/src/mcgen.jl index 657ccac9..5691588b 100644 --- a/src/mcgen.jl +++ b/src/mcgen.jl @@ -56,6 +56,7 @@ function prepare_execution!(@nospecialize(job::CompilerJob), mod::LLVM.Module, end function mcgen(@nospecialize(job::CompilerJob), mod::LLVM.Module, format=LLVM.CodeGenFileType.Assembly) + is_llvmgpu(mod.library) && return String(llvmgpu_emit(job, mod, format)) with_llvm_machine(job.config.target) do tm String(LLVM.emit(tm, mod, format)) end diff --git a/src/metal.jl b/src/metal.jl index 606c793c..c7e91653 100644 --- a/src/metal.jl +++ b/src/metal.jl @@ -94,6 +94,8 @@ source_code(target::MetalCompilerTarget) = "llvm" # Metal is not supported by our LLVM builds, so we can't get a target machine llvm_machine(::MetalCompilerTarget) = nothing +llvm_library(::MetalCompilerTarget) = toolchain_library() + # Apple's compiler generates code from the AIR backend_llvm_version(::MetalCompilerTarget) = nothing @@ -1598,6 +1600,17 @@ end end # downgrade bitcode to the format of an older LLVM through libllvm_downgrade +# the newest bitcode format, up to that of LLVM `major`, that LLVMDowngrader_jll emits +function downgrade_target(major::Integer) + backend = ExternalBackend(LLVMDowngrader_jll.libllvm_downgrade, "LLVMDG") + count = Ref{Csize_t}() + names = @ccall $(api(backend, "GetTargets"))(count::Ptr{Csize_t})::Ptr{Cstring} + versions = [VersionNumber(unsafe_string(unsafe_load(names, i))) for i in 1:count[]] + filter!(v -> v.major <= major, versions) + isempty(versions) && error("LLVMDowngrader_jll cannot downgrade bitcode to LLVM $major or older") + return maximum(versions) +end + function downgrade(input::Vector{UInt8}, version::VersionNumber) backend = ExternalBackend(LLVMDowngrader_jll.libllvm_downgrade, "LLVMDG") buffer = Ref{Ptr{Cvoid}}(C_NULL) diff --git a/src/optim.jl b/src/optim.jl index af54a228..66fd68bb 100644 --- a/src/optim.jl +++ b/src/optim.jl @@ -57,6 +57,10 @@ function optimize!(@nospecialize(job::CompilerJob), mod::LLVM.Module, @dispose pb=PassBuilder() begin tti === nothing || LLVM.target_transform_info!(pb, tti) + # Julia's passes (`JuliaIR.AllocOptPass()` etc.) are its C++ passes when + # constructed in Julia's LLVM, and JuliaIR.jl's ports of them in another library + # (where the module optimized here may live, see `llvm_library`) + JuliaIR.register!(pb) register!(pb, GPULowerCPUFeaturesPass(job)) register!(pb, GPULowerPTLSPass(job)) register!(pb, GPULowerGCFramePass(job, relocs)) @@ -127,7 +131,7 @@ end function buildEarlySimplificationPipeline(mpm, @nospecialize(job::CompilerJob), opt_level) if should_verify() add!(mpm, FunctionPassManager()) do fpm - add!(fpm, GCInvariantVerifierPass()) + add!(fpm, JuliaIR.GCInvariantVerifierPass()) end add!(mpm, VerifierPass()) end @@ -141,7 +145,7 @@ function buildEarlySimplificationPipeline(mpm, @nospecialize(job::CompilerJob), add!(fpm, LowerExpectIntrinsicPass()) add!(fpm, AnnotateThrowBranchesPass()) if opt_level >= 2 - add!(fpm, PropagateJuliaAddrspacesPass()) + add!(fpm, JuliaIR.PropagateJuliaAddrspacesPass()) end # DCE must come before simplifycfg: codegen can generate unused # statements that would otherwise alter how simplifycfg optimizes the CFG. @@ -174,7 +178,7 @@ function buildEarlyOptimizerPipeline(mpm, @nospecialize(job::CompilerJob), opt_l end if opt_level >= 2 add!(cgpm, FunctionPassManager()) do fpm - add!(fpm, AllocOptPass()) + add!(fpm, JuliaIR.AllocOptPass()) end end end @@ -192,7 +196,7 @@ function buildEarlyOptimizerPipeline(mpm, @nospecialize(job::CompilerJob), opt_l add!(fpm, LibCallsShrinkWrapPass()) add!(fpm, ReassociatePass()) add!(fpm, ConstraintEliminationPass()) - add!(fpm, AllocOptPass()) + add!(fpm, JuliaIR.AllocOptPass()) else add!(fpm, EarlyCSEPass()) add!(fpm, instcombine_pass(job)) @@ -273,17 +277,17 @@ AnnotateThrowBranchesPass() = FunctionPass("GPUAnnotateThrowBranches", annotate_ function buildLoopOptimizerPipeline(fpm, @nospecialize(job::CompilerJob), opt_level) add!(fpm, LoopPassManager(; use_memory_ssa=true)) do lpm - add!(lpm, LowerSIMDLoopPass()) + add!(lpm, JuliaIR.LowerSIMDLoopPass()) if opt_level >= 2 add!(lpm, LoopInstSimplifyPass()) add!(lpm, LoopSimplifyCFGPass()) # run LICM with AllowSpeculation=false before rotation to avoid # speculating loads that rotation can hoist more precisely. add!(lpm, LICMPass(; allowspeculation=false)) - add!(lpm, JuliaLICMPass()) + add!(lpm, JuliaIR.JuliaLICMPass()) add!(lpm, LoopRotatePass()) add!(lpm, LICMPass()) - add!(lpm, JuliaLICMPass()) + add!(lpm, JuliaIR.JuliaLICMPass()) add!(lpm, SimpleLoopUnswitchPass(nontrivial=true, trivial=true)) end if LLVM.version() >= v"17" @@ -330,7 +334,7 @@ end function buildScalarOptimizerPipeline(fpm, @nospecialize(job::CompilerJob), opt_level) if opt_level >= 2 - add!(fpm, AllocOptPass()) + add!(fpm, JuliaIR.AllocOptPass()) add!(fpm, SROAPass()) if can_vectorize(job) add!(fpm, VectorCombinePass()) @@ -348,7 +352,7 @@ function buildScalarOptimizerPipeline(fpm, @nospecialize(job::CompilerJob), opt_ add!(fpm, JumpThreadingPass()) add!(fpm, ConstraintEliminationPass()) elseif opt_level >= 1 - add!(fpm, AllocOptPass()) + add!(fpm, JuliaIR.AllocOptPass()) add!(fpm, SROAPass()) add!(fpm, MemCpyOptPass()) add!(fpm, SCCPPass()) @@ -361,10 +365,10 @@ function buildScalarOptimizerPipeline(fpm, @nospecialize(job::CompilerJob), opt_ add!(fpm, PeepholeCallbacks(; opt_level)) end add!(fpm, simplifycfg_pass(job, AggressiveSimplifyCFGOptions)) - add!(fpm, AllocOptPass()) + add!(fpm, JuliaIR.AllocOptPass()) add!(fpm, LoopPassManager(; use_memory_ssa=true)) do lpm add!(lpm, LICMPass()) - add!(lpm, JuliaLICMPass()) + add!(lpm, JuliaIR.JuliaLICMPass()) end add!(fpm, simplifycfg_pass(job, AggressiveSimplifyCFGOptions)) add!(fpm, instcombine_pass(job)) @@ -420,7 +424,7 @@ function buildVectorPipeline(fpm, @nospecialize(job::CompilerJob), opt_level) end function buildIntrinsicLoweringPipeline(mpm, @nospecialize(job::CompilerJob), opt_level) - add!(mpm, RemoveNIPass()) + add!(mpm, JuliaIR.RemoveNIPass()) # lower GC intrinsics if !uses_julia_runtime(job) @@ -458,24 +462,24 @@ function buildIntrinsicLoweringPipeline(mpm, @nospecialize(job::CompilerJob), op add!(mpm, FunctionPassManager()) do fpm # lower exception handling if uses_julia_runtime(job) && VERSION < v"1.13.0-DEV.36" - add!(fpm, LowerExcHandlersPass()) + add!(fpm, JuliaIR.LowerExcHandlersPass()) end - add!(fpm, GCInvariantVerifierPass()) - add!(fpm, LateLowerGCPass()) + add!(fpm, JuliaIR.GCInvariantVerifierPass()) + add!(fpm, JuliaIR.LateLowerGCPass()) # FinalLowerGCPass moved from a module pass to a function pass in # JuliaLang/julia#51081 (1.11.0-DEV.208). if uses_julia_runtime(job) && VERSION >= v"1.11.0-DEV.208" - add!(fpm, FinalLowerGCPass()) + add!(fpm, JuliaIR.FinalLowerGCPass(; kind=:function)) end # codegen emits atomic modifications (e.g. `@atomic x.f += 1`) as calls to the # `julia.atomicmodify` pseudo-intrinsic, which Julia expands after GC lowering # (JuliaLang/julia#57010) @static if VERSION >= v"1.13.0-DEV.321" - add!(fpm, ExpandAtomicModifyPass()) + add!(fpm, JuliaIR.ExpandAtomicModifyPass()) end end if uses_julia_runtime(job) && VERSION < v"1.11.0-DEV.208" - add!(mpm, FinalLowerGCPass()) + add!(mpm, JuliaIR.FinalLowerGCPass(; kind=:module)) end if opt_level >= 2 @@ -489,7 +493,7 @@ function buildIntrinsicLoweringPipeline(mpm, @nospecialize(job::CompilerJob), op # lower PTLS intrinsics if uses_julia_runtime(job) - add!(mpm, LowerPTLSPass()) + add!(mpm, JuliaIR.LowerPTLSPass()) end if opt_level >= 1 @@ -507,7 +511,7 @@ function buildIntrinsicLoweringPipeline(mpm, @nospecialize(job::CompilerJob), op end # remove Julia address spaces - add!(mpm, RemoveJuliaAddrspacesPass()) + add!(mpm, JuliaIR.RemoveJuliaAddrspacesPass()) # Julia's operand bundles confuse the inliner, so repeat here now they are gone. # FIXME: we should fix the inliner so that inlined code gets optimized early-on @@ -521,7 +525,7 @@ function buildCleanupPipeline(mpm, @nospecialize(job::CompilerJob), opt_level) if opt_level >= 2 add!(mpm, FunctionPassManager()) do fpm if VERSION < v"1.12.0-DEV.1390" - add!(fpm, CombineMulAddPass()) + add!(fpm, JuliaIR.CombineMulAddPass()) end add!(fpm, DivRemPairsPass()) end @@ -533,7 +537,7 @@ function buildCleanupPipeline(mpm, @nospecialize(job::CompilerJob), opt_level) add!(fpm, AnnotationRemarksPass()) end add!(mpm, FunctionPassManager()) do fpm - add!(fpm, DemoteFloat16Pass()) + add!(fpm, JuliaIR.DemoteFloat16Pass()) end end diff --git a/src/ptx.jl b/src/ptx.jl index 8d06a4b8..53f68d7e 100644 --- a/src/ptx.jl +++ b/src/ptx.jl @@ -87,8 +87,13 @@ source_code(target::PTXCompilerTarget) = "ptx" llvm_triple(target::PTXCompilerTarget) = Int===Int64 ? "nvptx64-nvidia-cuda" : "nvptx-nvidia-cuda" +llvm_library(::PTXCompilerTarget) = toolchain_library() + function llvm_machine(target::PTXCompilerTarget) - @static if :NVPTX ∉ LLVM.backends() + if is_llvmgpu() + # (libNVVM generates code for the actual target, so it only uses the machine below) + target.backend === :nvvm || return llvmgpu_machine(target) + elseif :NVPTX ∉ LLVM.backends() return nothing end triple = llvm_triple(target) @@ -105,12 +110,55 @@ end function backend_llvm_version(target::PTXCompilerTarget) target.backend === :nvvm && return nothing # (without the back-end, `mcgen` reports a clearer error) - if isavailable(NVPTX_LLVM_Backend_jll) && NVPTX_LLVM_Backend_jll.is_available() + if TOOLCHAIN === :julia && + isavailable(NVPTX_LLVM_Backend_jll) && NVPTX_LLVM_Backend_jll.is_available() return llvm_version(ExternalBackend(NVPTX_LLVM_Backend_jll.libnvptx, "NVPTX")) end return @invoke backend_llvm_version(target::AbstractCompilerTarget) end +# the minimum PTX ISA version that the NVPTX back-end of `state.library` accepts for `cpu`. +# since LLVM 22, it aborts on older versions, and targets this one when none is requested, +# so ask it by generating code for an empty module. +function ptx_minimum_version(state::LLVMGPUState, triple::String, cpu::String) + @lock state.lock get!(state.ptx_minimum_versions, cpu) do + LLVM.library!(state.library) do + t = LLVM.Target(; triple) + @dispose ctx=Context() tm=LLVM.TargetMachine(t, triple; cpu) mod=LLVM.Module("") begin + LLVM.triple!(mod, triple) + asm = String(LLVM.emit(tm, mod, LLVM.CodeGenFileType.Assembly)) + m = match(r"^\.version (\d+)\.(\d+)$"m, asm) + VersionNumber(parse(Int, m[1]), parse(Int, m[2])) + end + end + end +end + +# a target machine of libLLVMGPU, which also generates code, so for 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 llvmgpu_machine(target::PTXCompilerTarget) + triple = llvm_triple(target) + t = LLVM.Target(; triple) + cpu = cpu_name(target) + ptx = "ptx$(target.ptx.major)$(target.ptx.minor)" + # (checked without selecting the processor, since LLVM only warns about unknown ones) + @dispose sti=LLVM.SubtargetInfo(t, triple) begin + LLVM.isprocessor(sti, cpu) || + error("Unsupported processor $cpu for the NVPTX back-end") + # (NVPTX has a feature for every PTX version) + ptx in LLVM.processor_features(sti) || + 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 = ptx_minimum_version(llvmgpu_state(), triple, 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 + # match the layout computed by the NVPTX back-end (computeNVPTXDataLayout); components # that match LLVM's defaults (small integers, floats, common vectors) are left implicit. # note that the external back-end ignores the module datalayout and recomputes it from @@ -378,6 +426,9 @@ end object code (LTO-IR) requires the NVVM back-end (`backend=:nvvm`).""") end + if is_llvmgpu(mod.library) + return String(llvmgpu_emit(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 @@ -402,8 +453,11 @@ end ## NVVM back-end -# the options for a job, and the architecture they target -function nvvm_options(@nospecialize(job::CompilerJob{PTXCompilerTarget})) +# the newest LLVM whose bitcode libNVVM reads (with `-nvvm-latest`) +const nvvm_max_llvm = 22 + +# the options for a job whose bitcode is of LLVM `version`, and the architecture they target +function nvvm_options(@nospecialize(job::CompilerJob{PTXCompilerTarget}), version::Integer) target = job.config.target arch = replace(cpu_name(target), "sm_" => "compute_") @@ -419,7 +473,7 @@ function nvvm_options(@nospecialize(job::CompilerJob{PTXCompilerTarget})) reader = NVVM.llvm_version(arch) if reader === nothing error("libNVVM does not support $arch.") - elseif reader < LLVM.version().major + elseif reader < version push!(options, "-nvvm-latest") end @@ -450,10 +504,19 @@ function nvvm_codegen(@nospecialize(job::CompilerJob{PTXCompilerTarget}), mod::L optimize_nvvm!(mod) end legalize_nvvm!(mod; lto) - options, arch = nvvm_options(job) - lto && push!(options, "-gen-lto") input = bitcode(mod) + version = LLVM.version(mod).major + if version > nvvm_max_llvm + if !isavailable(LLVMDowngrader_jll) + error("The NVVM back-end requires the LLVMDowngrader_jll package to compile bitcode of LLVM $version, which should be installed and loaded first.") + end + target = downgrade_target(nvvm_max_llvm) + input = downgrade(input, target) + version = target.major + end + options, arch = nvvm_options(job, version) + lto && push!(options, "-gen-lto") prog = NVVM.Program() output = try NVVM.add!(prog, input) @@ -1198,6 +1261,13 @@ end # does a function flush f32 denormals, per its denormal mode attributes? function flushes_f32_denormals(f::LLVM.Function) attrs = f.function_attributes + # LLVM 23 replaced the string attributes by `denormal_fpenv`, which packs the output + # and input modes of all types and of f32 in four 2-bit fields + attr = get(attrs, :denormal_fpenv, nothing) + if attr !== nothing + output = (LLVM.value(attr) >> 4) & 0x3 + return output in (1, 2) # preserve-sign, positive-zero + end for kind in ("denormal-fp-math-f32", "denormal-fp-math") attr = get(attrs, kind, nothing) attr === nothing && continue diff --git a/src/reflection.jl b/src/reflection.jl index d86170ad..6d7b18af 100644 --- a/src/reflection.jl +++ b/src/reflection.jl @@ -247,7 +247,8 @@ The following keyword arguments are supported: - `optimize`: determines if the code is optimized, which includes kernel-specific optimizations if `kernel` is true -- `raw`: return the raw IR including all metadata +- `raw`: return the raw IR including all metadata (IR that moved to another LLVM library + than Julia's, see [`llvm_library`](@ref), is always printed with all metadata) - `dump_module`: display the entire module instead of just the function See also: [`@device_code_llvm`](@ref), `InteractiveUtils.code_llvm` @@ -258,6 +259,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_llvmgpu(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 d4fa14c9..1a433a09 100644 --- a/src/spirv.jl +++ b/src/spirv.jl @@ -69,7 +69,10 @@ Base.@kwdef struct SPIRVCompilerTarget <: AbstractCompilerTarget # these are performed on `float` (see `widen_bfloat16!`). supports_bfloat16_arithmetic::Bool = false - backend::Symbol = isavailable(SPIRV_LLVM_Backend_jll) ? :llvm : :khronos + # the code generator: LLVM's SPIR-V back-end (`:llvm`, from SPIRV_LLVM_Backend_jll, or + # with the `llvmgpu` toolchain, libLLVMGPU's) or the Khronos translator (`:khronos`) + backend::Symbol = TOOLCHAIN === :llvmgpu || isavailable(SPIRV_LLVM_Backend_jll) ? + :llvm : :khronos # the driver that will consume the SPIR-V, used to work around its bugs. `:generic` if # unknown, `:intel` for Intel's GPU driver (NEO, with IGC), `:pocl`, `:nvidia`, ... @@ -93,13 +96,31 @@ 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 +# Julia's LLVM does not have the SPIR-V target, so we can't get a target machine, except +# from libLLVMGPU. the Khronos translator takes `spir` modules, for which there's no target +# machine at all. +llvm_library(::SPIRVCompilerTarget) = toolchain_library() + +function llvm_machine(target::SPIRVCompilerTarget) + (is_llvmgpu() && 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 = llvmgpu_state() + @lock state.lock begin + set_spirv_extensions!(state, spirv_extensions(target)) + LLVM.TargetMachine(t, triple) + end +end function backend_llvm_version(target::SPIRVCompilerTarget) target.backend === :khronos && return nothing # (without the back-end, `mcgen` reports a clearer error) - if isavailable(SPIRV_LLVM_Backend_jll) && SPIRV_LLVM_Backend_jll.is_available() + if TOOLCHAIN === :julia && + isavailable(SPIRV_LLVM_Backend_jll) && SPIRV_LLVM_Backend_jll.is_available() return llvm_version(ExternalBackend(SPIRV_LLVM_Backend_jll.libspirv, "SPIRV")) end return @invoke backend_llvm_version(target::AbstractCompilerTarget) @@ -350,7 +371,9 @@ end # translate to SPIR-V input = bitcode(mod) - spirv = if target.backend === :llvm + spirv = if is_llvmgpu(mod.library) && target.backend === :llvm + llvmgpu_emit(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/src/toolchain.jl b/src/toolchain.jl new file mode 100644 index 00000000..69b62a9e --- /dev/null +++ b/src/toolchain.jl @@ -0,0 +1,191 @@ +# the LLVM toolchain that optimizes code and generates machine code +# +# With the default `julia` toolchain, the whole pipeline uses Julia's LLVM, and external +# back-end libraries (e.g. NVPTX_LLVM_Backend_jll) generate code. With the `llvmgpu` +# toolchain, once linked and post-processed, the module of a top-level job moves to a newer, +# standalone LLVM library with GPU back-ends (libLLVMGPU, from LLVMGPU_jll): optimization, +# target finalization (`finish_ir!`), validation and relocation collection happen with that +# library, and so does code generation, except with libNVVM or the Khronos SPIR-V +# translator, which get the optimized bitcode. That is for GPUCompiler's GPU targets; others, +# like the host, stay with Julia's LLVM (see `llvm_library`). Julia's code generator always +# uses Julia's LLVM. +# +# Select it with `Preferences.set_preferences!(GPUCompiler, "toolchain" => "llvmgpu")`. + +import JuliaIR +import LLVMGPU_jll + +const TOOLCHAIN = Symbol(@load_preference("toolchain", "julia")) +TOOLCHAIN in (:julia, :llvmgpu) || + error("Invalid toolchain preference $(repr(String(TOOLCHAIN))); expected \"julia\" or \"llvmgpu\"") + + +## libLLVMGPU + +struct LLVMGPUState + 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 minimum PTX ISA version of each processor (see `ptx_minimum_version`) + ptx_minimum_versions::Dict{String,VersionNumber} +end + +# (process-local: reset by `__init__`) +const llvmgpu_state_ref = Ref{Union{Nothing,LLVMGPUState}}(nothing) +const llvmgpu_init_lock = ReentrantLock() + +# libLLVMGPU, registered with LLVM.jl and initialized on first use +function llvmgpu_state() + @lock llvmgpu_init_lock begin + state = llvmgpu_state_ref[] + if state === nothing + lib = LLVM.register_library!(:gpu, LLVMGPU_jll.libLLVMGPU) + state = llvmgpu_state_ref[] = initialize_llvmgpu(lib) + end + return state + end +end + +function initialize_llvmgpu(lib::LLVM.Library) + # (the command-line options and back-end behavior relied on are those of LLVM 23) + LLVM.version(lib).major == 23 || + error("The llvmgpu toolchain 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", "BPF"), + 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 LLVMGPUState(lib, ReentrantLock(), Dict{String,VersionNumber}()) +end + +# whether `lib` is libLLVMGPU +function is_llvmgpu(lib::LLVM.Library=LLVM.library()) + TOOLCHAIN === :llvmgpu || return false + state = @lock llvmgpu_init_lock llvmgpu_state_ref[] + return state !== nothing && state.library === lib +end + +# whether `job` moves to libLLVMGPU. nested jobs are linked into the module of their parent +# before it does. +uses_llvmgpu(@nospecialize(job::CompilerJob)) = + job.config.toplevel && is_llvmgpu(checked_llvm_library(job.config.target)) + + +## contexts + +# The IR that `compile` returns lives in a context of the enclosing `JuliaContext` block, +# which, with the `llvmgpu` toolchain, also has a context of libLLVMGPU for the modules that +# move there (see `JuliaContext`). Like with Julia's LLVM, that is the context of the +# library that was activated last by the task, so a context created inside the block owns +# the modules compiled while it is active. +function llvmgpu_context(lib::LLVM.Library) + ctx = LLVM.library!(() -> context(; throw_error=false), lib) + ctx === nothing && + error("No active context of libLLVMGPU; compile inside a `JuliaContext() do ... end` block, which owns the resulting IR") + return ctx +end + + +## transfer + +# Move the linked module `ir` to libLLVMGPU, returning the new module (in a context owned by +# the enclosing `JuliaContext` block). The original is disposed of. +function move_to_llvmgpu!(ir::LLVM.Module) + state = llvmgpu_state() + ctx = llvmgpu_context(state.library) + + # bitcode is forward compatible, so the newer library can read it. the module keeps + # its datalayout, like with Julia's LLVM: Julia's non-integral address spaces keep the + # optimizer from turning GC-tracked pointers into integers until `RemoveNIPass`, and + # the layout of types like `Int128` must match the host's. + input = bitcode(ir) + mod = context!(() -> parse(LLVM.Module, input), ctx) + dispose(ir) + return mod +end + +# run `f` in the context of `ir`, which can belong to libLLVMGPU +in_context(f, ir::LLVM.Module) = TOOLCHAIN === :llvmgpu ? context!(f, context(ir)) : f() + + +## code generation + +# generate code for `mod`, a module of libLLVMGPU, with libLLVMGPU's back-end for the target +function llvmgpu_emit(@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 = llvmgpu_state() + @lock state.lock begin + with_llvm_machine(job.config.target) do tm + tm === nothing && error("No target machine for $(job.config.target)") + # code generation mutates the module, which is also returned as `meta.ir` + @dispose mod=copy(mod) begin + set_subtarget_attributes!(mod, tm) + LLVM.emit(tm, mod, format) + end + 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_expect_assume" (where, as with +# SPIRV_LLVM_Backend_jll, an entry without a sign enables the extension). 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 enabled extensions, but the ones it disables (with `-NAME`) stay +# disabled for the rest of the process, so those are rejected. Must be called with +# `state.lock` held, through the creation of the target machine. +function set_spirv_extensions!(state::LLVMGPUState, extensions::AbstractString) + entries = String[] + for entry in split(extensions, ','; keepempty=false) + entry = strip(entry) + isempty(entry) && continue + if startswith(entry, '-') + error("Cannot disable SPIR-V extensions ($entry in $(repr(extensions))) with the llvmgpu toolchain") + end + name = lstrip(entry, '+') + push!(entries, name == "all" ? "all" : "+" * name) + end + LLVM.library!(state.library) do + try + LLVM.clopts("--spirv-ext=" * join(entries, ',')) + catch err + err isa LLVM.LLVMException || rethrow() + error("Invalid SPIR-V extensions $(repr(extensions)): $(err.info)") + end + end + return +end diff --git a/test/gcn.jl b/test/gcn.jl index 44874cac..27f68337 100644 --- a/test/gcn.jl +++ b/test/gcn.jl @@ -1,8 +1,28 @@ -if :AMDGPU in LLVM.backends() +# (with the llvmgpu toolchain, libLLVMGPU generates the code) +if llvmgpu || :AMDGPU in LLVM.backends() + +# the back-ends to test. the llvmgpu toolchain only supports :external, whose code +# libLLVMGPU generates. +const gcn_backends = llvmgpu ? (:external,) : (:inprocess, :external) # XXX: generic `sink` generates an instruction selection error sink_gcn(i) = sink(i, Val(5)) +if llvmgpu +@testset "backend selector" begin + # libLLVMGPU generates the code, as the external back-end + @test GCNCompilerTarget(dev_isa="gfx900").backend === :external + @test_throws "only supports `backend=:external`" GCNCompilerTarget("gfx900"; backend=:inprocess) + @test_throws "only supports `backend=:external`" GCNCompilerTarget("gfx900"; backend=:bogus) + + mod = @eval module $(gensym()) + kernel() = return + end + @test (GCN.code_native(devnull, mod.kernel, Tuple{}); true) + @test GPUCompiler.backend_llvm_version(GCNCompilerTarget("gfx900")) == + LLVM.version(GPUCompiler.llvm_library(GCNCompilerTarget("gfx900"))) +end +else @testset "backend selector" begin # in the test environment AMDGPU_LLVM_Backend_jll is loaded, so the default is :external @test GCNCompilerTarget(dev_isa="gfx900").backend === :external @@ -47,6 +67,7 @@ sink_gcn(i) = sink(i, Val(5)) @test GPUCompiler.backend_llvm_version(GCNCompilerTarget("gfx900"; backend=:inprocess)) == LLVM.version() end +end @testset "IR" begin @@ -88,7 +109,7 @@ end end # LLVM 23+ can runtime-unroll a loop with a side exit if that exit is weighed as unlikely -if LLVM.version() >= v"23" +if llvmgpu || LLVM.version() >= v"23" @testset "bounds-checked loops" begin mod = @eval module $(gensym()) @inline function load(ptr, len, i) @@ -191,7 +212,7 @@ end @testset "atomic validation" begin # validate textual IR, with AMDGPU's synchronization scopes, for a GCN target - function validate_atomics(body; backend=:inprocess) + function validate_atomics(body; backend=first(gcn_backends)) source = methodinstance(typeof(identity), Tuple{Int}, Base.get_world_counter()) target = GCNCompilerTarget(; dev_isa="gfx90a", backend) job = CompilerJob(source, CompilerConfig(target, GCN.CompilerParams(); kernel=true)) @@ -259,8 +280,10 @@ end # the cluster scope (the agent on targets without clusters) is only known from LLVM 22 cluster = "%a = atomicrmw add ptr addrspace(1) %p, i32 1 syncscope(\"cluster\") monotonic, align 4\n" * "fence syncscope(\"cluster-one-as\") acquire" - @test occursin("synchronization scope \"cluster\"", validate_atomics(cluster)) == - (LLVM.version() < v"22") + if !llvmgpu + @test occursin("synchronization scope \"cluster\"", validate_atomics(cluster)) == + (LLVM.version() < v"22") + end @test validate_atomics(cluster; backend=:external) == "" end @@ -357,8 +380,8 @@ end # byref struct params should be ptr addrspace(4) in kernel IR @test @filecheck begin - @check cond=typed_ptrs "define amdgpu_kernel void @_Z6kernel8MyStruct({{.*}} addrspace(4)*" - @check cond=opaque_ptrs "define amdgpu_kernel void @_Z6kernel8MyStruct(ptr addrspace(4)" + @check cond=gpu_typed_ptrs "define amdgpu_kernel void @_Z6kernel8MyStruct({{.*}} addrspace(4)*" + @check cond=gpu_opaque_ptrs "define amdgpu_kernel void @_Z6kernel8MyStruct(ptr addrspace(4)" GCN.code_llvm(mod.kernel, Tuple{mod.MyStruct}; dump_module=true, kernel=true) end @@ -412,8 +435,8 @@ end @test @filecheck begin @check "define amdgpu_kernel void" @check_same "double" - @check_same cond=typed_ptrs "{{.*}} addrspace(4)*" - @check_same cond=opaque_ptrs "ptr addrspace(4)" + @check_same cond=gpu_typed_ptrs "{{.*}} addrspace(4)*" + @check_same cond=gpu_opaque_ptrs "ptr addrspace(4)" @check_same "{{(i64|ptr)}}" GCN.code_llvm(mod.kernel, Tuple{Float64, mod.Params, Ptr{Float64}}; dump_module=true, kernel=true) @@ -438,7 +461,7 @@ end kernel=true) JuliaContext() do ctx ir, meta = GPUCompiler.compile(:llvm, job) - @dispose ir=ir begin + context!(context(ir)) do entry = meta.entry ft = entry.function_type params = ft.parameters @@ -456,6 +479,7 @@ end ir_str = string(ir) @test occursin("byref", ir_str) end + dispose(ir) end end @@ -515,7 +539,7 @@ end Base.invokelatest(getfield, mod, :kernel), Tuple{Core.LLVMPtr{JT,1},JT} end f, tt = add_kernel("i128") - for backend in (:inprocess, :external) + for backend in gcn_backends @test_throws_message(InvalidIRError, Base.invokelatest(GCN.code_execution, f, tt; backend)) do msg occursin("Reason: unsupported 128-bit atomic operation", msg) && @@ -569,6 +593,8 @@ LLVM.version() >= v"20" && @testset "usub_sat atomics" begin asm = sprint(io->GCN.code_native(io, f, tt; dev_isa, kernel)) @test occursin(instruction, asm) + llvmgpu && continue + # Julia's LLVM needs the workaround from version 22 on ir = sprint(io->GCN.code_llvm(io, f, tt; dev_isa, kernel, backend=:inprocess)) @test occursin("atomicrmw usub_sat", ir) == (LLVM.version() < v"22" || !affected) @@ -580,7 +606,7 @@ LLVM.version() >= v"20" && @testset "usub_sat atomics" begin end # the expansion is a workaround, not part of validation - if LLVM.version() >= v"22" + if !llvmgpu && LLVM.version() >= v"22" f, tt = rmw_kernel(3) ir = sprint(io->GCN.code_llvm(io, f, tt; dev_isa="gfx1030", kernel=true, backend=:inprocess, validate=false)) @@ -620,10 +646,13 @@ end dev_isa="gfx1030", kernel=true, backend)) end + for (T, op, as) in (("i8", "add", 1), ("i16", "max", 3), ("i8", "umin", 0)) + @test occursin("atomicrmw $op", rmw_ir(T, op; as, backend=:external)) + end + if !llvmgpu for (T, op, as) in (("i8", "add", 1), ("i16", "max", 3), ("i8", "umin", 0)) @test occursin("atomicrmw $op", rmw_ir(T, op; as, backend=:inprocess)) == (LLVM.version() >= v"21") - @test occursin("atomicrmw $op", rmw_ir(T, op; as, backend=:external)) end # other operations, unused results and wider atomics are unaffected @test occursin("atomicrmw xchg", rmw_ir("i8", "xchg"; backend=:inprocess)) @@ -648,6 +677,7 @@ end """ cmd = `$(Base.julia_cmd()) --project=$(Base.active_project()) -e $script` @test success(pipeline(cmd; stdout, stderr)) + end end @testset "s_load for kernarg struct access" begin @@ -998,7 +1028,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=!llvmgpu "addrspacecast" @check_not "julia.gpu.alloca" GCN.code_llvm(mod.scratch, Tuple{Float32}; optimize=false, dump_module=true) end @@ -1020,4 +1051,4 @@ end end end -end # :AMDGPU in LLVM.backends() +end # llvmgpu || :AMDGPU in LLVM.backends() diff --git a/test/helpers/toolchain.jl b/test/helpers/toolchain.jl new file mode 100644 index 00000000..a40f09a3 --- /dev/null +++ b/test/helpers/toolchain.jl @@ -0,0 +1,12 @@ +# whether GPUCompiler uses the `llvmgpu` toolchain (see src/toolchain.jl), selected by its +# `toolchain` preference: top-level jobs of every target but the host are optimized with +# libLLVMGPU, using JuliaIR.jl's ports of Julia's passes, so their IR differs in places +const llvmgpu = GPUCompiler.TOOLCHAIN === :llvmgpu + +# whether the IR of top-level GPU jobs uses typed pointers, for conditional FileCheck checks: +# with the llvmgpu toolchain, it belongs to libLLVMGPU, which only supports opaque pointers +const gpu_typed_ptrs = typed_ptrs && !llvmgpu +const gpu_opaque_ptrs = !gpu_typed_ptrs + +# the LLVM library of the IR that top-level GPU jobs return, e.g. to parse its text again +gpu_library() = llvmgpu ? GPUCompiler.llvmgpu_state().library : LLVM.Library(:julia) diff --git a/test/metal.jl b/test/metal.jl index 22b42e5c..a26cb49b 100644 --- a/test/metal.jl +++ b/test/metal.jl @@ -8,16 +8,16 @@ @test @filecheck begin @check_label "define void @{{(julia|j)_kernel_[0-9]+}}" - @check_same cond=typed_ptrs "({{(\\{ i64 \\}|\\[1 x i64\\])}}*" - @check_same cond=opaque_ptrs "(ptr" + @check_same cond=gpu_typed_ptrs "({{(\\{ i64 \\}|\\[1 x i64\\])}}*" + @check_same cond=gpu_opaque_ptrs "(ptr" Metal.code_llvm(mod.kernel, Tuple{Tuple{Int}}) end # for kernels, every pointer argument needs to take an address space @test @filecheck begin @check_label "define void @_Z6kernel5TupleI5Int64E" - @check_same cond=typed_ptrs "({{(\\{ i64 \\}|\\[1 x i64\\])}} addrspace(1)*" - @check_same cond=opaque_ptrs "(ptr addrspace(1)" + @check_same cond=gpu_typed_ptrs "({{(\\{ i64 \\}|\\[1 x i64\\])}} addrspace(1)*" + @check_same cond=gpu_opaque_ptrs "(ptr addrspace(1)" Metal.code_llvm(mod.kernel, Tuple{Tuple{Int}}; kernel=true) end end @@ -69,8 +69,8 @@ end # for kernels, every pointer argument needs to take an address space @test @filecheck begin @check_label "define void @_Z6kernel5Int64" - @check_same cond=typed_ptrs "(i64 addrspace(1)*" - @check_same cond=opaque_ptrs "(ptr addrspace(1)" + @check_same cond=gpu_typed_ptrs "(i64 addrspace(1)*" + @check_same cond=gpu_opaque_ptrs "(ptr addrspace(1)" Metal.code_llvm(mod.kernel, Tuple{Int}; kernel=true) end end @@ -92,7 +92,7 @@ end Tuple{Core.LLVMPtr{Int32,1}, Core.LLVMPtr{Int32,1}, Int32, Int32, Int}; dump_module=true, kernel=true) end - @test Context() do ctx + @test Context(; opaque_pointers=gpu_opaque_ptrs, library=gpu_library()) do ctx verify(parse(LLVM.Module, ir)) true end @@ -126,7 +126,7 @@ end # (by position, as older Julia versions do not name the parameters) function kernel_parameter_attributes(ir) - Context() do ctx + Context(; opaque_pointers=gpu_opaque_ptrs, library=gpu_library()) do ctx m = parse(LLVM.Module, ir) f = only(filter(f -> startswith(f.name, "_Z6kernel"), collect(m.functions))) [Dict(LLVM.kind(attr) => LLVM.value(attr) @@ -176,7 +176,7 @@ end tt = Tuple{mod.Vec, Int, Int} ir = sprint(io -> Metal.code_llvm(io, mod.kernel, tt; kernel=true, dump_module=true)) - Context() do ctx + Context(; opaque_pointers=gpu_opaque_ptrs, library=gpu_library()) do ctx m = parse(LLVM.Module, ir) f = only(filter(f -> startswith(f.name, "_Z6kernel"), collect(m.functions))) store = only(inst for bb in f.blocks for inst in bb.instructions @@ -511,16 +511,16 @@ end @test @filecheck begin @check_label "define void @{{(julia|j)_kernel_[0-9]+}}" - @check_same cond=typed_ptrs "({{.+}} addrspace(1)* %{{.+}})" - @check_same cond=opaque_ptrs "(ptr addrspace(1) %{{.+}})" + @check_same cond=gpu_typed_ptrs "({{.+}} addrspace(1)* %{{.+}})" + @check_same cond=gpu_opaque_ptrs "(ptr addrspace(1) %{{.+}})" @check "call i32 @julia.air.thread_position_in_threadgroup.i32" Metal.code_llvm(mod.kernel, Tuple{Core.LLVMPtr{Int,1}}) end @test @filecheck begin @check_label "define void @_Z6kernel7LLVMPtrI5Int64Li1EE" - @check_same cond=typed_ptrs "({{.+}} addrspace(1)* %{{.+}}, i32 %thread_position_in_threadgroup)" - @check_same cond=opaque_ptrs "(ptr addrspace(1) %{{.+}}, i32 %thread_position_in_threadgroup)" + @check_same cond=gpu_typed_ptrs "({{.+}} addrspace(1)* %{{.+}}, i32 %thread_position_in_threadgroup)" + @check_same cond=gpu_opaque_ptrs "(ptr addrspace(1) %{{.+}}, i32 %thread_position_in_threadgroup)" @check_not "call i32 @julia.air.thread_position_in_threadgroup.i32" Metal.code_llvm(mod.kernel, Tuple{Core.LLVMPtr{Int,1}}; kernel=true) end @@ -796,17 +796,17 @@ end # (`nocapture` having been replaced by `captures(none)` in LLVM 21) @test @filecheck begin @check "declare float @air.sincos.f32" - @check_same cond=typed_ptrs "(float, float* nocapture writeonly)" - @check_same cond=(opaque_ptrs && LLVM.version() < v"21") "(float, ptr nocapture writeonly)" - @check_same cond=(LLVM.version() >= v"21") "(float, ptr writeonly captures(none))" + @check_same cond=gpu_typed_ptrs "(float, float* nocapture writeonly)" + @check_same cond=(gpu_opaque_ptrs && LLVM.version(gpu_library()) < v"21") "(float, ptr nocapture writeonly)" + @check_same cond=(LLVM.version(gpu_library()) >= v"21") "(float, ptr writeonly captures(none))" Metal.code_llvm(mod.kernel, Tuple{Float32}; dump_module=true) end @test @filecheck begin @check "declare float @air.fast_sincos.f32" - @check_same cond=typed_ptrs "(float, float* nocapture writeonly)" - @check_same cond=(opaque_ptrs && LLVM.version() < v"21") "(float, ptr nocapture writeonly)" - @check_same cond=(LLVM.version() >= v"21") "(float, ptr writeonly captures(none))" + @check_same cond=gpu_typed_ptrs "(float, float* nocapture writeonly)" + @check_same cond=(gpu_opaque_ptrs && LLVM.version(gpu_library()) < v"21") "(float, ptr nocapture writeonly)" + @check_same cond=(LLVM.version(gpu_library()) >= v"21") "(float, ptr writeonly captures(none))" Metal.code_llvm(mod.kernel_fast, Tuple{Float32}; dump_module=true) end @@ -1552,7 +1552,9 @@ end return end end - if LLVM.version() >= v"17" + # (demotion runs with the library that optimizes the kernel; before 1.11, Julia embeds + # the box's address instead) + if GPUCompiler.supports_relocatable_ir() && LLVM.version(gpu_library()) >= v"17" # the box must be demoted, leaving a stack alloca rather than an addrspace(2) constant air = sprint() do io Metal.code_native(io, mod.kernel, (Core.LLVMPtr{Int64,1}, Bool, Int32); kernel=true) @@ -1598,8 +1600,8 @@ end @check_label "define void @_Z6kernel7LLVMPtrI7Float32Li1EE5Int64" # the load must happen in addrspace(2); Metal miscompiles loads of # the constant if they occur via an addrspacecast to the generic AS - @check cond=opaque_ptrs "load float, ptr addrspace(2)" - @check cond=typed_ptrs "load float, float addrspace(2)*" + @check cond=gpu_opaque_ptrs "load float, ptr addrspace(2)" + @check cond=gpu_typed_ptrs "load float, float addrspace(2)*" Metal.code_llvm(mod.kernel, Tuple{Core.LLVMPtr{Float32,1}, Int}; dump_module=true, kernel=true) end @@ -3690,9 +3692,11 @@ end Base.get_world_counter()) target = MetalCompilerTarget(; macos=v"15", metal=v"3.2", air=v"2.7") job = CompilerJob(source, CompilerConfig(target, Metal.CompilerParams(); kernel=true)) + # (JuliaIR's port of `AllocOpt` removes the object altogether) @test @filecheck begin - @check "alloca" - @check "cmpxchg" + @check cond=!llvmgpu "alloca" + @check cond=!llvmgpu "cmpxchg" + @check_not cond=llvmgpu "cmpxchg" GPUCompiler.code_llvm(job; dump_module=true) end @test @filecheck begin diff --git a/test/ptx.jl b/test/ptx.jl index e7cf84c2..e541c043 100644 --- a/test/ptx.jl +++ b/test/ptx.jl @@ -68,7 +68,7 @@ end types = Tuple{Ptr{Float32},Ptr{Float32},Ptr{Float32},Int,Int,Int,Int} # the check's side exit is weighed as unlikely, which lets LLVM 23+ runtime-unroll the loop - if LLVM.version() >= v"23" + if llvmgpu || LLVM.version() >= v"23" @test @filecheck begin @check_label "define void @{{.*}}dot" @check "epil" @@ -575,15 +575,15 @@ end @test @filecheck begin @check_label "define void @{{(julia|j)_kernel_[0-9]+}}" - @check_same cond=typed_ptrs "({{({ i64 }|\\[1 x i64\\])}}*" - @check_same cond=opaque_ptrs "(ptr" + @check_same cond=gpu_typed_ptrs "({{({ i64 }|\\[1 x i64\\])}}*" + @check_same cond=gpu_opaque_ptrs "(ptr" PTX.code_llvm(mod.kernel, Tuple{mod.Aggregate}; backend) end @test @filecheck begin @check_label "define ptx_kernel void @_Z6kernel9Aggregate" - @check_not cond=typed_ptrs "*" - @check_not cond=opaque_ptrs "ptr" + @check_not cond=gpu_typed_ptrs "*" + @check_not cond=gpu_opaque_ptrs "ptr" PTX.code_llvm(mod.kernel, Tuple{mod.Aggregate}; backend, kernel=true) end end @@ -1164,7 +1164,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\"" + # (libLLVMGPU upgrades the string attribute to `denormal_fpenv`) + @check cond=fastmath&&!llvmgpu "\"denormal-fp-math-f32\"=\"preserve-sign,preserve-sign\"" + @check cond=fastmath&&llvmgpu "denormal_fpenv(float: preservesign)" @check cond=fastmath "\"unsafe-fp-math\"=\"true\"" unsafe_store!(out, sqrt(unsafe_load(x))) return diff --git a/test/runtests.jl b/test/runtests.jl index 763a5f09..d645a315 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -66,7 +66,8 @@ if filter_tests!(testsuite, args) startswith(key, "ptx") && delete!(testsuite, key) end end - if !AMDGPU_LLVM_Backend_jll.is_available() + # (with the llvmgpu toolchain, libLLVMGPU generates the code) + if !AMDGPU_LLVM_Backend_jll.is_available() && GPUCompiler.TOOLCHAIN !== :llvmgpu @warn "AMDGPU back-end not available; skipping GCN tests" delete!(testsuite, "gcn") end diff --git a/test/spirv.jl b/test/spirv.jl index 5624c91f..bafa027f 100644 --- a/test/spirv.jl +++ b/test/spirv.jl @@ -93,13 +93,13 @@ end @test @filecheck begin @check_label "define spir_kernel void @_Z6kernel" @check "gpu_report_exception_name(" - @check_same cond=opaque_ptrs "ptr addrspace(1) @exception" - @check_same cond=typed_ptrs "i8 addrspace(1)* getelementptr inbounds ({{.*}} @exception" + @check_same cond=gpu_opaque_ptrs "ptr addrspace(1) @exception" + @check_same cond=gpu_typed_ptrs "i8 addrspace(1)* getelementptr inbounds ({{.*}} @exception" @check "gpu_report_exception_frame(i32 1," - @check_same cond=opaque_ptrs "ptr addrspace(1) @di_func" - @check_same cond=opaque_ptrs "ptr addrspace(1) @di_file" - @check_same cond=typed_ptrs "i8 addrspace(1)* getelementptr inbounds ({{.*}} @di_func" - @check_same cond=typed_ptrs "i8 addrspace(1)* getelementptr inbounds ({{.*}} @di_file" + @check_same cond=gpu_opaque_ptrs "ptr addrspace(1) @di_func" + @check_same cond=gpu_opaque_ptrs "ptr addrspace(1) @di_file" + @check_same cond=gpu_typed_ptrs "i8 addrspace(1)* getelementptr inbounds ({{.*}} @di_func" + @check_same cond=gpu_typed_ptrs "i8 addrspace(1)* getelementptr inbounds ({{.*}} @di_file" SPIRV.code_llvm(mod.kernel, Tuple{}; backend, kernel=true, debug_level=2, optimize=false) end @@ -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 llvmgpu toolchain, 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/toolchain.jl b/test/toolchain.jl new file mode 100644 index 00000000..8ad5e4b3 --- /dev/null +++ b/test/toolchain.jl @@ -0,0 +1,256 @@ +# the toolchain selected by GPUCompiler's `toolchain` preference (see src/toolchain.jl) + +if haskey(ENV, "GPUCOMPILER_TEST_TOOLCHAIN") + @test GPUCompiler.TOOLCHAIN === Symbol(ENV["GPUCOMPILER_TEST_TOOLCHAIN"]) +end + +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} + +# PTX jobs whose kernels are replaced by copies after linking, and that record the LLVM +# library they are optimized with +struct HookParams <: AbstractCompilerParams end +GPUCompiler.runtime_module(::CompilerJob{PTXCompilerTarget,HookParams}) = PTX.PTXTestRuntime +function GPUCompiler.finish_linked_module!( + @nospecialize(job::CompilerJob{PTXCompilerTarget,HookParams}), mod::LLVM.Module) + for f in GPUCompiler.kernels(mod) + GPUCompiler.replace_function!(f, LLVM.clone(f)) + end +end +const optimized_with = Ref{Symbol}() +GPUCompiler.optimize_module!( + @nospecialize(job::CompilerJob{PTXCompilerTarget,HookParams}), mod::LLVM.Module) = + (optimized_with[] = LLVM.library().name; return) + +# a target defined elsewhere +struct OtherTarget <: AbstractCompilerTarget end + +# the library of the IR that `job` compiles to +function ir_library(job) + JuliaContext() do ctx + ir, meta = GPUCompiler.compile(:llvm, job) + lib = ir.library + dispose(ir) + lib.name + end +end + +@testset "LLVM library" begin + gpu = llvmgpu ? :gpu : :julia + @test ir_library(first(PTX.create_job(kernel, tt; kernel=true))) === gpu + @test ir_library(first(GCN.create_job(kernel, tt; kernel=true))) === gpu + for backend in (:llvm, :khronos) + @test ir_library(first(SPIRV.create_job(kernel, tt; kernel=true, backend))) === gpu + end + @test ir_library(first(BPF.create_job(identity, Tuple{Int}))) === gpu + @test ir_library(first(Metal.create_job(kernel, tt; kernel=true))) === gpu + if PTX.nvvm_available() + @test ir_library(first(PTX.create_job(kernel, tt; kernel=true, backend=:nvvm))) === gpu + end + + # host code stays with Julia's LLVM + @test ir_library(first(Native.create_job(kernel, tt; kernel=true))) === :julia + @test GPUCompiler.llvm_library(NativeCompilerTarget()) === LLVM.Library(:julia) + # as does that of targets defined elsewhere, unless they opt in (e.g. Enzyme's, which + # wraps the native target) + @test GPUCompiler.llvm_library(Enzyme.EnzymeTarget()) === LLVM.Library(:julia) + @test GPUCompiler.llvm_library(OtherTarget()) === LLVM.Library(:julia) + + # nested jobs are linked into their parent before it moves to libLLVMGPU + job, _ = PTX.create_job(kernel, tt; kernel=true) + job = CompilerJob(job; config=CompilerConfig(job.config; toplevel=false)) + @test ir_library(job) === :julia + + # the module moves before optimization, and back-ends can replace the entry point + # before that (OpenCL.jl does, adding input arguments in `finish_linked_module!`) + job, _ = PTX.create_job(kernel, tt; kernel=true) + job = CompilerJob(job; config=CompilerConfig(job.config; params=HookParams())) + JuliaContext() do ctx + ir, meta = GPUCompiler.compile(:llvm, job) + @test optimized_with[] === gpu + context!(context(ir)) do + @test meta.entry in ir.functions + @test meta.entry.callconv == LLVM.CallConv.PTXKernel + + # Julia code can be compiled while inspecting the IR, into the contexts of + # another block + JuliaContext() do ctx2 + ir2, _ = GPUCompiler.compile(:llvm, job) + @test ir2.library.name === gpu + @test context(ir2) != context(ir) + dispose(ir2) + end + end + dispose(ir) + end + + # the do-block form runs its block in the context of the IR, of either library + for (job, lib) in ((first(PTX.create_job(kernel, tt; kernel=true)), gpu), + (first(Native.create_job(kernel, tt; kernel=true)), :julia)) + res = GPUCompiler.compile(:llvm, job) do ir, meta + @test context() == context(ir) + ir.library.name, meta.entry.name + end + @test res[1] === lib && occursin("kernel", res[2]) + # (without the llvmgpu toolchain, PTX code needs NVPTX_LLVM_Backend_jll, which + # isn't available everywhere) + job.config.target isa PTXCompilerTarget && !llvmgpu && + !NVPTX_LLVM_Backend_jll.is_available() && continue + asm, entry = GPUCompiler.compile(:asm, job) do asm, meta + @test meta.entry in meta.ir.functions + asm, meta.entry.name + end + @test asm isa String && entry == res[2] + end + @test_throws "boom" GPUCompiler.compile((_, _) -> error("boom"), :llvm, + first(PTX.create_job(kernel, tt; kernel=true))) + # (which leaves no context of either library behind) + @test context(; throw_error=false) === nothing + if llvmgpu + @test LLVM.library!(() -> context(; throw_error=false), + GPUCompiler.llvmgpu_state().library) === nothing + end + + # the IR keeps GPUCompiler's datalayout (e.g. for the host's layout of `Int128`) + for job in (first(PTX.create_job(kernel, tt; kernel=true)), + first(SPIRV.create_job(kernel, tt; kernel=true, backend=:llvm))) + JuliaContext() do ctx + expected = GPUCompiler.llvm_datalayout(job.config.target) + ir, _ = GPUCompiler.compile(:llvm, job) + @test string(LLVM.datalayout(ir)) == expected + dispose(ir) + end + end +end + +if llvmgpu + +@testset "defaults" begin + # (whether SPIRV_LLVM_Backend_jll is loaded or not) + @test SPIRVCompilerTarget().backend === :llvm + + # the version of the LLVM that generates code, also in Julia's context + lib = GPUCompiler.llvmgpu_state().library + for target in (PTXCompilerTarget(; cap=v"7.0"), GCNCompilerTarget(; dev_isa="gfx900"), + SPIRVCompilerTarget(), BPFCompilerTarget()) + @test GPUCompiler.llvm_library(target) === lib + @test GPUCompiler.backend_llvm_version(target) == LLVM.version(lib) + end +end + +@testset "IR" begin + job, _ = PTX.create_job(kernel, tt; kernel=true) + JuliaContext() do ctx + ir, meta = GPUCompiler.compile(:llvm, job) + @test LLVM.version(ir) >= v"23" + context!(context(ir)) do + @test meta.entry in ir.functions + @test meta.entry.callconv == LLVM.CallConv.PTXKernel + + # Julia code can't be compiled in that context + @test_throws "in a context of Julia's LLVM" GPUCompiler.compile(:llvm, job) + end + + # the block owns one context of the library, for all its compilations + ir2, meta2 = GPUCompiler.compile(:llvm, job) + @test context(ir2) == context(ir) + + # the IR can be compiled after the fact + asm, _ = GPUCompiler.emit_asm(job, ir2, meta2.relocations, + LLVM.CodeGenFileType.Assembly) + @test occursin(".entry", asm) + dispose(ir2) + dispose(ir) + end + + # that context is owned by the `JuliaContext` block, of the task that runs it + ThreadSafeContext() do ts_ctx + context!(context(ts_ctx)) do + @test_throws "No active context of libLLVMGPU" GPUCompiler.compile(:llvm, job) + end + end + JuliaContext() do ctx + msg = fetch(@async ThreadSafeContext() do ts_ctx + context!(context(ts_ctx)) do + try + GPUCompiler.compile(:llvm, job) + "" + catch err + sprint(showerror, err) + end + end + end) + @test occursin("No active context of libLLVMGPU", msg) + end + + # the move keeps Julia's non-integral address spaces, which optimization relies on + JuliaContext() do ctx + config = CompilerConfig(job.config; optimize=false, validate=false) + ir, _ = GPUCompiler.compile(:llvm, CompilerJob(job; config)) + @test ir.library.name === :gpu + @test occursin("ni:10:11:12:13", string(LLVM.datalayout(ir))) + dispose(ir) + end + + # Julia's LLVM can use typed pointers (on 1.10 and 1.11 by default), as host code keeps + # using Julia's passes there, and the module moves to libLLVMGPU as bitcode + if VERSION < v"1.12" + JuliaContext(; opaque_pointers=false) do ctx + ir, meta = GPUCompiler.compile(:llvm, first(Native.create_job(kernel, tt))) + @test supports_typed_pointers(context(ir)) + dispose(ir) + ir, meta = GPUCompiler.compile(:llvm, job) + @test ir.library.name === :gpu + dispose(ir) + end + end + + # reflection prints the IR of the library + ir = sprint(io -> PTX.code_llvm(io, kernel, tt; kernel=true)) + @test occursin("define ptx_kernel void", ir) +end + +@testset "code generation" begin + asm = sprint(io -> PTX.code_native(io, kernel, tt; kernel=true, 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, cap=v"1.2") + @test_throws "needs at least PTX ISA version 7.8" PTX.code_native(devnull, kernel, tt; + kernel=true, cap=v"9.0", ptx=v"7.0") + + asm = sprint(io -> GCN.code_native(io, kernel, tt; kernel=true)) + @test occursin("amdhsa.kernels", asm) + @test_throws "only supports `backend=:external`" GCN.code_native(devnull, kernel, tt; + kernel=true, backend=:inprocess) + @test_throws "Unsupported processor gfx1" GCN.code_native(devnull, kernel, tt; + kernel=true, dev_isa="gfx1") + + asm = sprint(io -> SPIRV.code_native(io, kernel, tt; kernel=true, backend=:llvm)) + @test occursin("OpEntryPoint Kernel", asm) + @test_throws "Invalid SPIR-V extensions \"+SPV_FOO\"" SPIRV.code_native(devnull, kernel, tt; + kernel=true, backend=:llvm, extensions="+SPV_FOO") + # (disabled extensions would stay disabled for every later target machine) + @test_throws "Cannot disable SPIR-V extensions" SPIRV.code_native(devnull, kernel, tt; + kernel=true, backend=:llvm, extensions="all,-SPV_KHR_bit_instructions") + # extensions without a sign are enabled, as with SPIRV_LLVM_Backend_jll + for extensions in ("SPV_KHR_bit_instructions", "") + asm = sprint(io -> SPIRV.code_native(io, kernel, tt; kernel=true, backend=:llvm, + extensions)) + @test occursin("OpEntryPoint Kernel", asm) + end + + # the Khronos translator reads libLLVMGPU's bitcode (the job validates the SPIR-V) + job, _ = SPIRV.create_job(kernel, tt; kernel=true, backend=:khronos) + lib = GPUCompiler.compile(:obj, job) do obj, meta + meta.ir.library.name + end + @test lib === :gpu + + asm = sprint(io -> BPF.code_native(io, identity, Tuple{Int})) + @test occursin("exit", asm) +end + +end diff --git a/test/utils.jl b/test/utils.jl index 3da5e3bf..86a0ca31 100644 --- a/test/utils.jl +++ b/test/utils.jl @@ -391,7 +391,8 @@ GPUCompiler.llvm_triple(::UnknownTarget) = "unknown-unknown-unknown" end @testset "back-end LLVM versions" begin - # the back-end libraries report the version of their LLVM + # the back-end libraries report the version of their LLVM (with the llvmgpu toolchain, + # libLLVMGPU generates the code; see test/toolchain.jl) function library_version(library, prefix) major, minor, patch = Ref{Cuint}(), Ref{Cuint}(), Ref{Cuint}() Libdl = GPUCompiler.Libdl @@ -399,11 +400,11 @@ end ccall(f, Cvoid, (Ref{Cuint}, Ref{Cuint}, Ref{Cuint}), major, minor, patch) VersionNumber(major[], minor[], patch[]) end - if NVPTX_LLVM_Backend_jll.is_available() + if !llvmgpu && NVPTX_LLVM_Backend_jll.is_available() @test GPUCompiler.backend_llvm_version(PTXCompilerTarget(; cap=v"7.0")) == library_version(NVPTX_LLVM_Backend_jll.libnvptx, "NVPTX") end - if SPIRV_LLVM_Backend_jll.is_available() + if !llvmgpu && SPIRV_LLVM_Backend_jll.is_available() @test GPUCompiler.backend_llvm_version(SPIRVCompilerTarget(; backend=:llvm)) == library_version(SPIRV_LLVM_Backend_jll.libspirv, "SPIRV") end From efb5e8176bbe248527d9a688ebd4ab20c4bb678f Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Wed, 25 Nov 2026 15:43:46 +0100 Subject: [PATCH 6/6] Test the llvmgpu toolchain on CI GitHub Actions runs the test suite with the llvmgpu toolchain on x86_64 Linux for every Julia version, on aarch64 Linux for Julia 1.11, and on macOS and Windows for Julia 1.12. Julia 1.12 and 1.13 on aarch64 Linux are left out, as Julia's GC lowering crashes on JuliaIR.jl's code there (JuliaLang/julia#62899). Buildkite tests every downstream package with it as well, in a step of its own. The steps of CUDA.jl, AMDGPU.jl, oneAPI.jl and OpenCL.jl may fail until those packages work with the IR in libLLVMGPU's context, using the do-block form of `compile`. --- .buildkite/downstream.yml | 157 +++++++++++++++++++++++++++++++++++++ .ci/toolchain.jl | 58 ++++++++++++++ .github/workflows/Test.yml | 19 ++++- README.md | 4 + 4 files changed, 236 insertions(+), 2 deletions(-) create mode 100644 .ci/toolchain.jl diff --git a/.buildkite/downstream.yml b/.buildkite/downstream.yml index 084a8ee0..abc1f238 100644 --- a/.buildkite/downstream.yml +++ b/.buildkite/downstream.yml @@ -4,6 +4,13 @@ # `src/` and `ext/`, `Project.toml` and the CI configuration, except the other back-ends' # target files. The `if:` conditions implement the commit message tags documented in the # Development section of the README; keep both in sync when adding a step. +# +# Every package also gets an "(llvmgpu)" step, which runs its tests with the llvmgpu +# toolchain (the `toolchain = "llvmgpu"` preference, set up by `.ci/toolchain.jl` in an +# environment of its own, as the default one persists on some agents). +# `[only llvmgpu]` selects only those steps and `[skip llvmgpu]` skips them; a package's own +# tags (e.g. `[only cuda]`) select both of its steps. Steps are skipped on draft pull +# requests unless a tag selects them. steps: - label: "CUDA.jl" plugins: @@ -34,6 +41,7 @@ steps: - "ext/**" - "Project.toml" - ".buildkite/**" + - ".ci/**" exclude: - "src/{gcn,spirv,metal,bpf,native}.jl" if: | @@ -44,6 +52,38 @@ steps: soft_fail: - exit_status: 3 + - label: "CUDA.jl (llvmgpu)" + plugins: + - JuliaCI/julia#v1: + version: "1.13" + command: | + unset LD_LIBRARY_PATH + echo "--- :julia: Instantiating project" + # an environment and checkouts of its own, so that the preference and the edited test + # environment don't reach the other steps + export JULIA_PROJECT="$$(mktemp -d)" + export JULIA_PKG_DEVDIR="$$JULIA_PROJECT/dev" + julia .ci/toolchain.jl CUDA + + julia -e 'println("+++ :julia: Running tests") + using Pkg + Pkg.test("CUDA")' + agents: + queue: "cuda" + env: + JULIA_CPU_THREADS: "3" + if_changed: + include: *sources + exclude: + - "src/{gcn,spirv,metal,bpf,native}.jl" + if: | + build.message !~ /\[skip [^\]]*(tests|cuda|ptx|llvmgpu)/ && + (build.message =~ /\[only [^\]]*(cuda|ptx|llvmgpu)/ || + build.message !~ /\[only / && !build.pull_request.draft) + timeout_in_minutes: 120 + # until the package works with IR of libLLVMGPU (JuliaGPU/CUDA.jl#3627) + soft_fail: true + - label: "oneAPI.jl" plugins: - JuliaCI/julia#v1: @@ -77,6 +117,38 @@ steps: soft_fail: - exit_status: 3 + - label: "oneAPI.jl (llvmgpu)" + plugins: + - JuliaCI/julia#v1: + version: "1.13" + command: | + echo "--- :julia: Instantiating project" + # an environment and checkouts of its own, so that the preference and the edited test + # environment don't reach the other steps + export JULIA_PROJECT="$$(mktemp -d)" + export JULIA_PKG_DEVDIR="$$JULIA_PROJECT/dev" + julia .ci/toolchain.jl oneAPI + julia -e 'using Pkg; + println("+++ :julia: Building support library") + include(joinpath(Pkg.devdir(), "oneAPI", "deps", "build_ci.jl"))' + + julia -e 'println("+++ :julia: Running tests") + using Pkg + Pkg.test("oneAPI")' + agents: + queue: "oneapi" + if_changed: + include: *sources + exclude: + - "src/{ptx,gcn,metal,bpf,native}.jl" + if: | + build.message !~ /\[skip [^\]]*(tests|oneapi|spirv|llvmgpu)/ && + (build.message =~ /\[only [^\]]*(oneapi|spirv|llvmgpu)/ || + build.message !~ /\[only / && !build.pull_request.draft) + timeout_in_minutes: 60 + # until the package works with IR of libLLVMGPU (JuliaGPU/oneAPI.jl#780) + soft_fail: true + - label: "AMDGPU.jl" plugins: - JuliaCI/julia#v1: @@ -106,6 +178,35 @@ steps: soft_fail: - exit_status: 3 + - label: "AMDGPU.jl (llvmgpu)" + plugins: + - JuliaCI/julia#v1: + version: "1.13" + command: | + echo "--- :julia: Instantiating project" + # an environment and checkouts of its own, so that the preference and the edited test + # environment don't reach the other steps + export JULIA_PROJECT="$$(mktemp -d)" + export JULIA_PKG_DEVDIR="$$JULIA_PROJECT/dev" + julia .ci/toolchain.jl AMDGPU + + julia -e 'println("+++ :julia: Running tests") + using Pkg + Pkg.test("AMDGPU")' + agents: + queue: "rocm" + if_changed: + include: *sources + exclude: + - "src/{ptx,spirv,metal,bpf,native}.jl" + if: | + build.message !~ /\[skip [^\]]*(tests|amdgpu|gcn|llvmgpu)/ && + (build.message =~ /\[only [^\]]*(amdgpu|gcn|llvmgpu)/ || + build.message !~ /\[only / && !build.pull_request.draft) + timeout_in_minutes: 60 + # until the package works with IR of libLLVMGPU (JuliaGPU/AMDGPU.jl#1250) + soft_fail: true + - label: "Metal.jl" plugins: - JuliaCI/julia#v1: @@ -146,6 +247,33 @@ steps: soft_fail: - exit_status: 3 + - label: "Metal.jl (llvmgpu)" + plugins: + - JuliaCI/julia#v1: + version: "1.13" + command: | + echo "--- :julia: Instantiating project" + # an environment and checkouts of its own, so that the preference and the edited test + # environment don't reach the other steps + export JULIA_PROJECT="$$(mktemp -d)" + export JULIA_PKG_DEVDIR="$$JULIA_PROJECT/dev" + JULIA_PKG_PRECOMPILE_AUTO=0 julia .ci/toolchain.jl Metal --workspace + + julia -e 'println("+++ :julia: Running tests") + using Pkg + Pkg.test("Metal")' + agents: + queue: "metal" + if_changed: + include: *sources + exclude: + - "src/{ptx,gcn,spirv,bpf,native}.jl" + if: | + build.message !~ /\[skip [^\]]*(tests|metal|llvmgpu)/ && + (build.message =~ /\[only [^\]]*(metal|llvmgpu)/ || + build.message !~ /\[only / && !build.pull_request.draft) + timeout_in_minutes: 120 + - label: "OpenCL.jl" plugins: - JuliaCI/julia#v1: @@ -176,5 +304,34 @@ steps: soft_fail: - exit_status: 3 + - label: "OpenCL.jl (llvmgpu)" + plugins: + - JuliaCI/julia#v1: + version: "1.13" + command: | + echo "--- :julia: Instantiating project" + # an environment and checkouts of its own, so that the preference and the edited test + # environment don't reach the other steps + export JULIA_PROJECT="$$(mktemp -d)" + export JULIA_PKG_DEVDIR="$$JULIA_PROJECT/dev" + julia .ci/toolchain.jl OpenCL SPIRVIntrinsics + + julia -e 'println("+++ :julia: Running tests") + using Pkg + Pkg.test("OpenCL")' + agents: + queue: "cuda" + if_changed: + include: *sources + exclude: + - "src/{ptx,gcn,metal,bpf,native}.jl" + if: | + build.message !~ /\[skip [^\]]*(tests|opencl|spirv|llvmgpu)/ && + (build.message =~ /\[only [^\]]*(opencl|spirv|llvmgpu)/ || + build.message !~ /\[only / && !build.pull_request.draft) + timeout_in_minutes: 120 + # until the package works with IR of libLLVMGPU (JuliaGPU/OpenCL.jl#631) + soft_fail: true + env: JULIA_PKG_SERVER_REGISTRY_PREFERENCE: "eager" # see freshly-registered versions without cloning the registry diff --git a/.ci/toolchain.jl b/.ci/toolchain.jl new file mode 100644 index 00000000..caa83b19 --- /dev/null +++ b/.ci/toolchain.jl @@ -0,0 +1,58 @@ +# Set up a CI environment to test a downstream package with the llvmgpu toolchain. +# +# julia .ci/toolchain.jl PACKAGE [PACKAGES...] [--workspace] +# +# Develops GPUCompiler and the downstream PACKAGE (and further PACKAGES, e.g. packages of +# PACKAGE's repository) into the active environment, for `Pkg.test(PACKAGE)`. The +# preference goes into the active environment (in CI, a temporary one), which `Pkg.test` +# passes on to the test environment; GPUCompiler is added to PACKAGE's test dependencies so +# that it applies there. `--workspace` also instantiates PACKAGE's workspace against +# GPUCompiler (Metal.jl's tests run examples in its workspace environments). + +using Pkg, TOML + +const ROOT = dirname(@__DIR__) +const GPUCOMPILER_UUID = "61eb1bfa-7361-4325-ad38-22787b887f55" + +function downstream(packages, workspace) + package = first(packages) + env = dirname(Base.active_project()) + + # an environment that doesn't exist yet (Pkg creates it on the first change) + mkpath(env) + file = joinpath(env, "LocalPreferences.toml") + open(io -> TOML.print(io, Dict("GPUCompiler" => Dict("toolchain" => "llvmgpu"))), file, "w") + println("$file:") + print(read(file, String)) + + Pkg.develop(path=ROOT) + Pkg.develop([PackageSpec(name=name) for name in packages]) + + checkout = joinpath(Pkg.devdir(), package) + if workspace + # before editing the test environment, which is part of the workspace and could + # then not be resolved; the examples that need the workspace run in the test + # process, which has loaded GPUCompiler already + Pkg.activate(checkout) + Pkg.develop(path=ROOT) + Pkg.instantiate(workspace=true) + Pkg.activate(env) + end + test_project = joinpath(checkout, "test", "Project.toml") + isfile(test_project) || error("$package has no test/Project.toml") + # by editing the text, as rewriting it with TOML.print reorders the file + deps = get(TOML.parsefile(test_project), "deps", Dict()) + if !haskey(deps, "GPUCompiler") + text = read(test_project, String) + occursin(r"^\[deps\]$"m, text) || (text = "[deps]\n\n" * text) + text = replace(text, r"^\[deps\]$"m => "[deps]\nGPUCompiler = \"$GPUCOMPILER_UUID\""; + count=1) + write(test_project, text) + end + + Pkg.status() +end + +packages = filter(!=("--workspace"), ARGS) +isempty(packages) && error("Usage: julia .ci/toolchain.jl PACKAGE [PACKAGES...] [--workspace]") +downstream(packages, "--workspace" in ARGS) diff --git a/.github/workflows/Test.yml b/.github/workflows/Test.yml index 9681d16d..6abbcd7d 100644 --- a/.github/workflows/Test.yml +++ b/.github/workflows/Test.yml @@ -13,7 +13,7 @@ concurrency: jobs: release_test: - name: Julia ${{ matrix.version }} ${{ matrix.llvm_args }}${{ matrix.coverage == 'false' && ' (no coverage)' || '' }} - ${{ matrix.os }} + name: Julia ${{ matrix.version }} ${{ matrix.llvm_args }}${{ matrix.toolchain == 'llvmgpu' && ' with llvmgpu' || '' }}${{ matrix.coverage == 'false' && ' (no coverage)' || '' }} - ${{ matrix.os }} runs-on: ${{ matrix.os }} timeout-minutes: 20 strategy: @@ -23,7 +23,19 @@ jobs: os: [ubuntu-24.04, ubuntu-24.04-arm, macOS-15, windows-2025] llvm_args: [''] coverage: ['true'] + toolchain: ['julia'] include: + # the llvmgpu toolchain (JuliaIR's passes, libLLVMGPU), on fewer platforms. not on + # aarch64 Linux with Julia 1.12 or 1.13, whose GC lowering crashes on JuliaIR's + # code (JuliaLang/julia#62899). + - {version: '1.10', os: 'ubuntu-24.04', llvm_args: '', coverage: 'true', toolchain: 'llvmgpu'} + - {version: '1.11', os: 'ubuntu-24.04', llvm_args: '', coverage: 'true', toolchain: 'llvmgpu'} + - {version: '1.12', os: 'ubuntu-24.04', llvm_args: '', coverage: 'true', toolchain: 'llvmgpu'} + - {version: '1.13', os: 'ubuntu-24.04', llvm_args: '', coverage: 'true', toolchain: 'llvmgpu'} + - {version: 'nightly', os: 'ubuntu-24.04', llvm_args: '', coverage: 'true', toolchain: 'llvmgpu'} + - {version: '1.12', os: 'macOS-15', llvm_args: '', coverage: 'true', toolchain: 'llvmgpu'} + - {version: '1.12', os: 'windows-2025', llvm_args: '', coverage: 'true', toolchain: 'llvmgpu'} + - {version: '1.11', os: 'ubuntu-24.04-arm', llvm_args: '', coverage: 'true', toolchain: 'llvmgpu'} # code coverage recompiles the package instead of using its precompiled code, # which hides bugs in how that code interacts with methods back-ends define - version: '1.12' @@ -68,11 +80,12 @@ jobs: uses: julia-actions/cache@v3 # without a driver, CUDA_Compiler_jll selects no toolkit; libNVVM works without one - - name: Select a CUDA toolkit + - name: Set preferences shell: bash run: | for dir in . test; do echo -e '[CUDA_Compiler_jll]\nversion = "13.5"' >$dir/LocalPreferences.toml + echo -e '[GPUCompiler]\ntoolchain = "${{ matrix.toolchain || 'julia' }}"' >>$dir/LocalPreferences.toml done - name: Run tests @@ -81,6 +94,8 @@ jobs: coverage: ${{ matrix.coverage != 'false' }} env: JULIA_LLVM_ARGS: ${{ matrix.llvm_args }} + # makes the tests check that the preference applied + GPUCOMPILER_TEST_TOOLCHAIN: ${{ matrix.toolchain || 'julia' }} - name: Process coverage # CoverageTools 1.4.1 uses a PkgLoadSpec field renamed in Julia 1.14. diff --git a/README.md b/README.md index cbb62197..75ddb652 100644 --- a/README.md +++ b/README.md @@ -52,6 +52,10 @@ Back-ends are named `cuda`, `amdgpu`, `metal`, `oneapi` and `opencl` (all lowerc their target: `ptx` for CUDA.jl, `gcn` for AMDGPU.jl, and `spirv` for both oneAPI.jl and OpenCL.jl. +Each back-end is tested twice: with the default toolchain, and with the llvmgpu toolchain +(see below). `llvmgpu` can be used as a back-end name to select or skip only the latter, +e.g., `[only llvmgpu]`. + ## LLVM toolchain