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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Project.toml
Original file line number Diff line number Diff line change
Expand Up @@ -56,4 +56,4 @@ SPIRV_LLVM_Backend_jll = "23"
SPIRV_Tools_jll = "2025.1"
UnsafeAtomics = "0.4"
julia = "1.10"
spirv2clc_jll = "0.2.5"
spirv2clc_jll = "0.2.6"
80 changes: 53 additions & 27 deletions src/compiler/compilation.jl
Original file line number Diff line number Diff line change
Expand Up @@ -241,18 +241,6 @@ function compile_to_obj(@nospecialize(job::CompilerJob))
end
end

function run_and_collect(cmd)
stdout = Pipe()
proc = run(pipeline(ignorestatus(cmd); stdout, stderr=stdout), wait=false)
close(stdout.in)

reader = Threads.@spawn String(read(stdout))
Base.wait(proc)
log = strip(fetch(reader))

return proc, log
end

"""
OpenCL.llvm_to_spirv_backend :: Symbol

Expand Down Expand Up @@ -361,6 +349,58 @@ function dump_artifacts(artifacts::Pair{String}...)
return paths
end

# Matches SPIRV2CLCTranslateOptions in libspirv2clc.h.
struct SPIRV2CLCTranslateOptions
spirv_major::Cuint
spirv_minor::Cuint
opencl_version::Cuint
end

function spirv2clc_diagnostic(severity::Cint, message::Cstring, context::Ptr{Cvoid})
diagnostics = unsafe_pointer_to_objref(context)::Vector{Tuple{Cint,String}}
push!(diagnostics, (severity, unsafe_string(message)))
return nothing
end

function translate_spirv(spirv::Vector{UInt8}, spirv_version::VersionNumber,
clc_version::VersionNumber)
options = SPIRV2CLCTranslateOptions(spirv_version.major, spirv_version.minor,
100 * clc_version.major + 10 * clc_version.minor)
source = Ref{Cstring}(C_NULL)
message = Ref{Cstring}(C_NULL)
diagnostics = Tuple{Cint,String}[]
handler = @cfunction(spirv2clc_diagnostic, Cvoid, (Cint, Cstring, Ptr{Cvoid}))
try
status = GC.@preserve diagnostics ccall(
(:SPIRV2CLCTranslate, spirv2clc_jll.libspirv2clc), Cint,
(Ptr{UInt8}, Csize_t, Ref{SPIRV2CLCTranslateOptions}, Ptr{Cvoid}, Ptr{Cvoid},
Ref{Cstring}, Ref{Cstring}),
spirv, length(spirv), options, handler, pointer_from_objref(diagnostics),
source, message)
# Errors are included in the returned failure message. Log other diagnostics only
# after returning from C, so a Julia logger cannot throw across the C++ frames.
for (severity, text) in diagnostics
if severity == 1
@warn text
elseif severity == 2
@info text
end
end
if status != 0
log = message[] == C_NULL ? "Unknown translation error" : unsafe_string(message[])
spv_file, = dump_artifacts(".spv" => spirv)
error("Failed to translate SPIR-V to OpenCL C source code:\n$(log)\n" *
"If you think this is a bug, please file an issue and attach $spv_file")
end
return unsafe_string(source[])
finally
ccall((:SPIRV2CLCDisposeMessage, spirv2clc_jll.libspirv2clc), Cvoid,
(Cstring,), source[])
ccall((:SPIRV2CLCDisposeMessage, spirv2clc_jll.libspirv2clc), Cvoid,
(Cstring,), message[])
end
end

# link the SPIR-V bytes into a session-local `cl.Kernel` on the active context.
function link_kernel(@nospecialize(job::CompilerJob), obj::Vector{UInt8}, entry::String)
spirv_bitcode = obj
Expand All @@ -376,21 +416,7 @@ function link_kernel(@nospecialize(job::CompilerJob), obj::Vector{UInt8}, entry:
clc_version = source_opencl_c_version(dev)
cl_std = "CL$(clc_version.major).$(clc_version.minor)"

# Be consistent with the SPIR-V version we generated code for
spv = job.config.target.version
spirv_version = "$(spv.major).$(spv.minor)"

spirv_path = tempname(cleanup=false) * ".spv"
write(spirv_path, spirv_bitcode)
proc, log = run_and_collect(`$(spirv2clc_jll.spirv2clc()) --spirv-version=$spirv_version --cl-std=$cl_std $spirv_path`)
rm(spirv_path)
if !success(proc)
spv_file, = dump_artifacts(".spv" => spirv_bitcode)
error("Failed to translate SPIR-V to OpenCL C source code:\n$(log)\n" *
"If you think this is a bug, please file an issue and attach $spv_file")
end

clc_source = strip(log)
clc_source = translate_spirv(spirv_bitcode, job.config.target.version, clc_version)
build_options = "-cl-std=$cl_std"
cl.Program(; source=clc_source)
end
Expand Down
58 changes: 58 additions & 0 deletions test/translation.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
@testset "SPIR-V to OpenCL C" begin
mktempdir() do dir
# Ordered atomics require OpenCL C 2.0, exercising both the source and error paths.
assembly = """
OpCapability Addresses
OpCapability Kernel
OpMemoryModel Physical64 OpenCL
OpEntryPoint Kernel %k "clear"
%void = OpTypeVoid
%uint = OpTypeInt 32 0
%pg = OpTypePointer CrossWorkgroup %uint
%device = OpConstant %uint 1
%release = OpConstant %uint 4
%fnty = OpTypeFunction %void %pg
%k = OpFunction %void None %fnty
%flag = OpFunctionParameter %pg
%entry = OpLabel
OpAtomicFlagClear %flag %device %release
OpReturn
OpFunctionEnd
"""
input = joinpath(dir, "input.spvasm")
binary = joinpath(dir, "input.spv")
write(input, assembly)
run(`$(OpenCL.SPIRV_Tools_jll.spirv_as()) --target-env spv1.4 $input -o $binary`)
spirv = read(binary)
for version in (v"2.0", v"3.0")
source = OpenCL.translate_spirv(spirv, v"1.4", version)
@test occursin("atomic_flag_clear_explicit", source)
cl_std = "CL$(version.major).$(version.minor)"
# The tool prints the source plus a newline, in text mode (CRLF on Windows).
expected = readlines(`$(OpenCL.spirv2clc_jll.spirv2clc()) --spirv-version=1.4 --cl-std=$cl_std $binary`)
@test readlines(IOBuffer(source * "\n")) == expected
end
# Also exercise successful translation with the OpenCL C 1.2 target.
write(input, replace(assembly, "OpAtomicFlagClear %flag %device %release" =>
"OpStore %flag %device"))
run(`$(OpenCL.SPIRV_Tools_jll.spirv_as()) --target-env spv1.4 $input -o $binary`)
source = OpenCL.translate_spirv(read(binary), v"1.4", v"1.2")
expected = readlines(`$(OpenCL.spirv2clc_jll.spirv2clc()) --spirv-version=1.4 --cl-std=CL1.2 $binary`)
@test readlines(IOBuffer(source * "\n")) == expected

# Returned Julia strings must survive subsequent translations and garbage collection.
sources = [OpenCL.translate_spirv(spirv, v"1.4", v"2.0") for _ in 1:10]
GC.gc()
@test all(==(first(sources)), sources)

dumps = joinpath(dir, "dumps")
withenv("JULIA_OPENCL_DUMP_DIR" => dumps) do
@test_throws "ordered atomics require OpenCL C 2.0" OpenCL.translate_spirv(spirv, v"1.4", v"1.2")
@test read(only(readdir(dumps; join=true))) == spirv
@test_throws "not a multiple of 4 bytes" OpenCL.translate_spirv(UInt8[1, 2, 3], v"1.4", v"1.2")
@test_throws "Invalid SPIR-V magic number" OpenCL.translate_spirv(zeros(UInt8, 24), v"1.4", v"1.2")
@test_throws "unsupported SPIR-V version" OpenCL.translate_spirv(spirv, v"2.0", v"2.0")
@test_throws "unsupported OpenCL C version" OpenCL.translate_spirv(spirv, v"1.4", v"2.1")
end
end
end
Loading