Runtime tests: port the old runtime's OpenCL-mode device tests

The old runtime's OpenCL-mode device tests went with it (5d725aeec7) and none was carried
to the runtime, so an OpenCL-mode regression had no device test to fail. This brings every
test of the old opencl_mode, opencl_images, opencl_swizzles, opencl_data and opencl_kernels
files into crates/metal2vulkan-runtime/src/tests, under the device cfgs, on every device of
the cfg's kind (each_device), with the module text and the oracle answers as they stood:

- the kernels are built with ComputePipelineDescriptor::open_cl_mode_enabled and bound as
  the replay player's OpenCL-mode play binds them: the first hidden buffer's four words by
  setBytes at index 0, the second and third as buffers at 1 and 2 (the third the image
  order and data type table), the kernel's own from 3;
- buffers are Shared buffers in blocks of their own, textures and sampler states are made
  at indices of the device's grants;
- vsh_round's NativeHalfConversion and NativeNanEncoding are read from the state's own
  precision notes (ComputePipelineState::precision_notes) where the old runtime heard its
  announcements; the NaN test's exemption for a device measured to move a NaN as Metal's
  (DriverDeviation::MetalNanMoves) has no counterpart in the translator now, which records
  the note for every module that encodes a half, so the test asserts the note.

Left out: the old opencl_mode test's lsum (a threadgroup sum through __local memory),
ported on its own branch, and the old runtime's pipeline creation log test and its child
(METAL2VULKAN_LOG_PIPELINES and METAL2VULKAN_DUMP_PIPELINES), which the runtime does not
have.

Verified: not yet run; the lavapipe run follows.
This commit is contained in:
Anees Iqbal committed 2026-11-27 03:35:19 -08:00
1 parent 9a6404e17a
commit 1c959e079c
6 files changed
+2468

No files matched your search

@@ -83,7 +83,17 @@ mod nil_slots;
mod no_attachment;
mod null_descriptor;
mod one_path;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod opencl_data;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod opencl_images;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod opencl_kernels;
mod opencl_local;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod opencl_mode;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod opencl_swizzles;
mod over;
mod over_aliases;
mod over_causes;
@@ -0,0 +1,474 @@
//! OpenCL C's vector data functions and `native_powr` in compute pipelines of OpenCL mode
//! (`ComputePipelineDescriptor::open_cl_mode_enabled`), each kernel in the shape Apple's OpenCL
//! compiler writes (`__entry_<name>` calling the kernel; `vl3_odd` calls the intrinsics through
//! the internal wrappers the compiler writes, the others call them directly), run with the hidden
//! buffers bound as Metal's OpenCL dispatcher binds them, and compared with what an M3 Max (macOS
//! 27.0.1), a Radeon Pro 5300M and a UHD Graphics 630 (macOS 26.7.1) compute for kernels of the
//! same shapes over the same data:
//!
//! - **vl3_odd**: `vstore3(vload3(i, g + 1), i, o)` over 10 threads, `g[j] = 100 + j`: `o[j]` is
//! `101 + j`, three `uint`s a thread from one past the buffer's start (no 16-byte alignment).
//! - **vlodd**: `vstore3(vload3(i, g + 1), i, o + 1)` of `uchar`s and `vstore2(vload2(i, s + 1), i,
//! t + 1)` of `short`s over 4 threads, `g[j] = 100 + j`, `s[j] = 1000 + j`: bytes 1 to 12 of `o`
//! are 101 to 112 and shorts 1 to 8 of `t` are 1001 to 1008, the rest untouched.
//! - **vha3**: `vload_half3(i, g)` and `vloada_half3(i, g)` of halves `g[j] = 0x5000 + j` over 4
//! threads read halves `3i` to `3i + 2` and `4i` to `4i + 2`; `vstore_half3(_, i, h)` writes
//! halves 0 to 11 and `vstorea_half3_rte(_, i, h + 32)` three of each four from half 32, on the
//! M3 Max and the UHD Graphics 630. The Radeon Pro 5300M's `vstorea_half3` also writes the
//! fourth half of each four (the half after the three `vloada_half3` read); what no Mac
//! guarantees is no part of the store, and the crate leaves it.
//! - **vsh_round**: `vstore_half` and its `_rte`, `_rtz`, `_rtp` and `_rtn` forms of 32 floats:
//! the Radeon Pro 5300M and the UHD Graphics 630 store every form as `vstore_half_rte`, word for
//! word, and the M3 Max rounds as each names; the crate stores every form as the device converts
//! (to nearest even, checked on the values whose `half` is normal; toward zero too where the
//! module records `NativeHalfConversion`, as on NVIDIA's RTX 2080).
//! - **vsh_round** of NaNs: each form stores a `half` NaN, its bits the device's conversion's,
//! and the pipeline records `NativeNanEncoding`, as the translator records it for every module
//! that encodes a `half` to its bits, on every device.
//! - **npowr**: `native_powr` of `float4`s: each device answers within a few ulps of the others
//! (`powr(100, 0.5)` is `0x1.400002p+3` on the M3 Max, `0x1.4p+3` on the Radeon Pro 5300M); the
//! crate's answers are within `2^-12` of the M3 Max's, relatively (the device's own `powr`).
//!
//! Under a device cfg, on every device of the cfg's kind. The modules are LLVM text written here;
//! `llvm-as` assembles them, and without it the tests skip visibly.
use crate::tests::command::on_device::each_device;
use crate::tests::opencl_mode::{
bytes, bytes_buffer, floats, floats_buffer, kernel_list, library, line, run, state, whole,
words, words_buffer,
};
use crate::{Buffer, Device, PrecisionNote};
/// The node of argument `n`, a buffer at `index` of `size`-byte elements of `ty`, `access` one of
/// `read`, `read_write`.
fn data(n: u32, index: u32, access: &str, (ty, size): (&str, u32), name: &str) -> String {
format!(
"!{{i32 {n}, !\"air.buffer\", !\"air.location_index\", i32 {index}, i32 1, !\"air.{access}\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 {size}, !\"air.arg_type_align_size\", i32 {size}, !\"air.arg_type_name\", !\"{ty}\", !\"air.arg_name\", !\"{name}\"}}"
)
}
/// `__kernel void vl3_odd(__global const uint *g, __global uint *o)`.
fn vl3_odd() -> String {
let body = "define void @__entry_vl3_odd(ptr addrspace(1) %0, ptr addrspace(1) %1) #0 {\n\
entry:\n\
tail call fastcc void @vl3_odd(ptr addrspace(1) %0, ptr addrspace(1) %1)\n\
ret void\n}\n\
define internal fastcc void @vl3_odd(ptr addrspace(1) %g, ptr addrspace(1) %o) #1 {\n\
entry:\n\
%i = tail call fastcc i64 @_Z13get_global_idj(i32 0)\n\
%g1 = getelementptr inbounds i32, ptr addrspace(1) %g, i64 1\n\
%v = tail call fastcc <3 x i32> @_Z6vload3mPU8CLglobalKj(i64 %i, ptr addrspace(1) %g1)\n\
tail call fastcc void @_Z7vstore3Dv3_jmPU8CLglobalj(<3 x i32> %v, i64 %i, ptr addrspace(1) %o)\n\
ret void\n}\n\
define internal fastcc void @_Z7vstore3Dv3_jmPU8CLglobalj(<3 x i32> %0, i64 %1, ptr addrspace(1) %2) #2 {\n\
tail call void @air.vstore.global.v3i32(<3 x i32> %0, i64 %1, ptr addrspace(1) %2) #6\n\
ret void\n}\n\
define internal fastcc <3 x i32> @_Z6vload3mPU8CLglobalKj(i64 %0, ptr addrspace(1) %1) #2 {\n\
%3 = tail call <3 x i32> @air.vload.global.v3i32(i64 %0, ptr addrspace(1) %1) #7\n\
ret <3 x i32> %3\n}\n\
declare void @air.vstore.global.v3i32(<3 x i32>, i64, ptr addrspace(1)) #6\n\
declare <3 x i32> @air.vload.global.v3i32(i64, ptr addrspace(1)) #7\n\
attributes #6 = { nounwind willreturn memory(argmem: write) }\n\
attributes #7 = { nounwind willreturn memory(argmem: read) }\n";
let args = [
data(0, 0, "read", ("uint", 4), "g"),
data(1, 1, "read_write", ("uint", 4), "o"),
];
format!("{body}{}", kernel_list("__entry_vl3_odd", &args))
}
/// `__kernel void vlodd(__global const uchar *g, __global const short *s, __global uchar *o,
/// __global short *t)`.
fn vlodd() -> String {
let body = "define void @__entry_vlodd(ptr addrspace(1) %0, ptr addrspace(1) %1, ptr addrspace(1) %2, ptr addrspace(1) %3) #0 {\n\
entry:\n\
tail call fastcc void @vlodd(ptr addrspace(1) %0, ptr addrspace(1) %1, ptr addrspace(1) %2, ptr addrspace(1) %3)\n\
ret void\n}\n\
define internal fastcc void @vlodd(ptr addrspace(1) %g, ptr addrspace(1) %s, ptr addrspace(1) %o, ptr addrspace(1) %t) #1 {\n\
entry:\n\
%i = tail call fastcc i64 @_Z13get_global_idj(i32 0)\n\
%g1 = getelementptr inbounds i8, ptr addrspace(1) %g, i64 1\n\
%o1 = getelementptr inbounds i8, ptr addrspace(1) %o, i64 1\n\
%b = tail call <3 x i8> @air.vload.global.v3i8(i64 %i, ptr addrspace(1) %g1) #7\n\
tail call void @air.vstore.global.v3i8(<3 x i8> %b, i64 %i, ptr addrspace(1) %o1) #6\n\
%s1 = getelementptr inbounds i16, ptr addrspace(1) %s, i64 1\n\
%t1 = getelementptr inbounds i16, ptr addrspace(1) %t, i64 1\n\
%h = tail call <2 x i16> @air.vload.global.v2i16(i64 %i, ptr addrspace(1) %s1) #7\n\
tail call void @air.vstore.global.v2i16(<2 x i16> %h, i64 %i, ptr addrspace(1) %t1) #6\n\
ret void\n}\n\
declare <3 x i8> @air.vload.global.v3i8(i64, ptr addrspace(1)) #7\n\
declare void @air.vstore.global.v3i8(<3 x i8>, i64, ptr addrspace(1)) #6\n\
declare <2 x i16> @air.vload.global.v2i16(i64, ptr addrspace(1)) #7\n\
declare void @air.vstore.global.v2i16(<2 x i16>, i64, ptr addrspace(1)) #6\n\
attributes #6 = { nounwind willreturn memory(argmem: write) }\n\
attributes #7 = { nounwind willreturn memory(argmem: read) }\n";
let args = [
data(0, 0, "read", ("uchar", 1), "g"),
data(1, 1, "read", ("short", 2), "s"),
data(2, 2, "read_write", ("uchar", 1), "o"),
data(3, 3, "read_write", ("short", 2), "t"),
];
format!("{body}{}", kernel_list("__entry_vlodd", &args))
}
/// `__kernel void vha3(__global const half *g, __global float *o, __global half *h)`: `o[6i..]`
/// take `vload_half3(i, g)` and `vloada_half3(i, g)`, stored to `h` by `vstore_half3` and to
/// `h + 32` by `vstorea_half3_rte`.
fn vha3() -> String {
let mut body = String::from(
"define void @__entry_vha3(ptr addrspace(1) %0, ptr addrspace(1) %1, ptr addrspace(1) %2) #0 {\n\
entry:\n\
tail call fastcc void @vha3(ptr addrspace(1) %0, ptr addrspace(1) %1, ptr addrspace(1) %2)\n\
ret void\n}\n\
define internal fastcc void @vha3(ptr addrspace(1) %g, ptr addrspace(1) %o, ptr addrspace(1) %h) #1 {\n\
entry:\n\
%i = tail call fastcc i64 @_Z13get_global_idj(i32 0)\n\
%a = tail call <3 x float> @air.vload_half.global.v3f32(i64 %i, ptr addrspace(1) %g) #7\n\
%b = tail call <3 x float> @air.vloada_half.global.v3f32(i64 %i, ptr addrspace(1) %g) #7\n\
%i6 = mul i64 %i, 6\n",
);
for (k, (v, lane)) in [("a", 0), ("a", 1), ("a", 2), ("b", 0), ("b", 1), ("b", 2)]
.into_iter()
.enumerate()
{
body.push_str(&format!(
" %x{k} = extractelement <3 x float> %{v}, i32 {lane}\n\
%j{k} = add i64 %i6, {k}\n\
%p{k} = getelementptr inbounds float, ptr addrspace(1) %o, i64 %j{k}\n\
store float %x{k}, ptr addrspace(1) %p{k}, align 4\n"
));
}
body.push_str(
" tail call void @air.vstore_half.global.rte.v3f32(<3 x float> %a, i64 %i, ptr addrspace(1) %h) #6\n\
%h32 = getelementptr inbounds half, ptr addrspace(1) %h, i64 32\n\
tail call void @air.vstorea_half.global.rte.v3f32(<3 x float> %b, i64 %i, ptr addrspace(1) %h32) #6\n\
ret void\n}\n\
declare <3 x float> @air.vload_half.global.v3f32(i64, ptr addrspace(1)) #7\n\
declare <3 x float> @air.vloada_half.global.v3f32(i64, ptr addrspace(1)) #7\n\
declare void @air.vstore_half.global.rte.v3f32(<3 x float>, i64, ptr addrspace(1)) #6\n\
declare void @air.vstorea_half.global.rte.v3f32(<3 x float>, i64, ptr addrspace(1)) #6\n\
attributes #6 = { nounwind willreturn memory(argmem: write) }\n\
attributes #7 = { nounwind willreturn memory(argmem: read) }\n",
);
let args = [
data(0, 0, "read", ("half", 2), "g"),
data(1, 1, "read_write", ("float", 4), "o"),
data(2, 2, "read_write", ("half", 2), "h"),
];
format!("{body}{}", kernel_list("__entry_vha3", &args))
}
/// `__kernel void vsh_round(__global const float *f, __global half *h)`: `f[i]` stored at half
/// `i` by `vstore_half`, and at `32 + i`, `64 + i`, `96 + i` and `128 + i` by its `_rte`,
/// `_rtz`, `_rtp` and `_rtn` forms.
fn vsh_round() -> String {
let mut body = String::from(
"define void @__entry_vsh_round(ptr addrspace(1) %0, ptr addrspace(1) %1) #0 {\n\
entry:\n\
tail call fastcc void @vsh_round(ptr addrspace(1) %0, ptr addrspace(1) %1)\n\
ret void\n}\n\
define internal fastcc void @vsh_round(ptr addrspace(1) %f, ptr addrspace(1) %h) #1 {\n\
entry:\n\
%i = tail call fastcc i64 @_Z13get_global_idj(i32 0)\n\
%pf = getelementptr inbounds float, ptr addrspace(1) %f, i64 %i\n\
%x = load float, ptr addrspace(1) %pf, align 4\n",
);
let mut decls = String::new();
for (k, rounding) in ["rte", "rte", "rtz", "rtp", "rtn"].into_iter().enumerate() {
let name = format!("@air.vstore_half.global.{rounding}.f32");
body.push_str(&format!(
" %h{k} = getelementptr inbounds half, ptr addrspace(1) %h, i64 {}\n\
tail call void {name}(float %x, i64 %i, ptr addrspace(1) %h{k}) #6\n",
32 * k
));
let decl = format!("declare void {name}(float, i64, ptr addrspace(1)) #6\n");
if !decls.contains(&decl) {
decls.push_str(&decl);
}
}
body.push_str(" ret void\n}\n");
body.push_str(&decls);
body.push_str("attributes #6 = { nounwind willreturn memory(argmem: write) }\n");
let args = [
data(0, 0, "read", ("float", 4), "f"),
data(1, 1, "read_write", ("half", 2), "h"),
];
format!("{body}{}", kernel_list("__entry_vsh_round", &args))
}
/// `__kernel void npowr(__global const float4 *a, __global const float4 *b, __global float4 *o)`:
/// `o[i] = native_powr(a[i], b[i])`.
fn npowr() -> String {
let body = "define void @__entry_npowr(ptr addrspace(1) %0, ptr addrspace(1) %1, ptr addrspace(1) %2) #0 {\n\
entry:\n\
tail call fastcc void @npowr(ptr addrspace(1) %0, ptr addrspace(1) %1, ptr addrspace(1) %2)\n\
ret void\n}\n\
define internal fastcc void @npowr(ptr addrspace(1) %a, ptr addrspace(1) %b, ptr addrspace(1) %o) #1 {\n\
entry:\n\
%i = tail call fastcc i64 @_Z13get_global_idj(i32 0)\n\
%pa = getelementptr inbounds <4 x float>, ptr addrspace(1) %a, i64 %i\n\
%va = load <4 x float>, ptr addrspace(1) %pa, align 16\n\
%pb = getelementptr inbounds <4 x float>, ptr addrspace(1) %b, i64 %i\n\
%vb = load <4 x float>, ptr addrspace(1) %pb, align 16\n\
%r = tail call fastcc <4 x float> @_Z11native_powrDv4_fS_(<4 x float> %va, <4 x float> %vb)\n\
%po = getelementptr inbounds <4 x float>, ptr addrspace(1) %o, i64 %i\n\
store <4 x float> %r, ptr addrspace(1) %po, align 16\n\
ret void\n}\n\
define internal fastcc <4 x float> @_Z11native_powrDv4_fS_(<4 x float> %0, <4 x float> %1) #2 {\n\
%3 = tail call <4 x float> @air.native_powr.v4f32(<4 x float> %0, <4 x float> %1) #3\n\
ret <4 x float> %3\n}\n\
declare <4 x float> @air.native_powr.v4f32(<4 x float>, <4 x float>) #3\n";
let args = [
data(0, 0, "read", ("float4", 16), "a"),
data(1, 1, "read", ("float4", 16), "b"),
data(2, 2, "read_write", ("float4", 16), "o"),
];
format!("{body}{}", kernel_list("__entry_npowr", &args))
}
/// A Shared buffer of the 16-bit words `halves`.
fn halves_buffer(device: &Device, halves: &[u16]) -> Buffer {
let bytes: Vec<u8> = halves.iter().flat_map(|h| h.to_le_bytes()).collect();
bytes_buffer(device, &bytes)
}
/// The 16-bit words of `buffer`, which no command uses now.
fn halves(buffer: &Buffer) -> Vec<u16> {
bytes(buffer)
.as_chunks::<2>()
.0
.iter()
.map(|h| u16::from_le_bytes(*h))
.collect()
}
/// No dispatch offset, one dimension.
const ONE: ([u32; 3], u32) = ([0; 3], 1);
#[test]
fn opencl_mode_vload3_reads_three_elements_past_an_unaligned_pointer() {
let Some(vl3_odd) = library(&vl3_odd()) else {
return;
};
each_device("opencl-data-vload3", |name, _, device| {
let s = state(&device, &vl3_odd, "__entry_vl3_odd");
let g = words_buffer(&device, &(0..64).map(|j| 100 + j).collect::<Vec<_>>());
let o = words_buffer(&device, &[0xeeee_eeee; 30]);
let args = [whole(&g), whole(&o)];
run(name, &device, &s, line(10, 1), ONE, &args);
assert_eq!(words(&o), (101..131).collect::<Vec<u32>>(), "{name}");
println!("{name}: vload3 and vstore3 past an unaligned pointer");
});
}
#[test]
fn opencl_mode_vector_data_moves_bytes_and_shorts_at_odd_elements() {
let Some(vlodd) = library(&vlodd()) else {
return;
};
each_device("opencl-data-narrow", |name, _, device| {
let s = state(&device, &vlodd, "__entry_vlodd");
let g = bytes_buffer(&device, &(100..164).collect::<Vec<u8>>());
let sh = halves_buffer(&device, &(1000..1064).collect::<Vec<u16>>());
let o = bytes_buffer(&device, &[0xee; 16]);
let t = halves_buffer(&device, &[0xeeee; 16]);
let args = [whole(&g), whole(&sh), whole(&o), whole(&t)];
run(name, &device, &s, line(4, 1), ONE, &args);
let mut want = vec![0xee; 16];
want[1..13].copy_from_slice(&(101..113).collect::<Vec<u8>>());
assert_eq!(bytes(&o), want, "{name}");
let mut want = vec![0xeeee; 16];
want[1..9].copy_from_slice(&(1001..1009).collect::<Vec<u16>>());
assert_eq!(halves(&t), want, "{name}");
println!("{name}: bytes and shorts at odd elements");
});
}
#[test]
fn opencl_mode_half_vector_data_steps_three_or_four_halves() {
let Some(vha3) = library(&vha3()) else {
return;
};
each_device("opencl-data-half3", |name, _, device| {
let s = state(&device, &vha3, "__entry_vha3");
let g = halves_buffer(&device, &(0..64).map(|j| 0x5000 + j).collect::<Vec<u16>>());
let o = floats_buffer(&device, &[0.0; 24]);
let h = halves_buffer(&device, &[0xeeee; 64]);
let args = [whole(&g), whole(&o), whole(&h)];
run(name, &device, &s, line(4, 1), ONE, &args);
// Each half `0x5000 + j` is `32 + j / 32`.
let read: Vec<f32> = floats(&o).iter().map(|x| (x - 32.0) * 32.0).collect();
#[rustfmt::skip]
let want: [f32; 24] = [
0.0, 1.0, 2.0, 0.0, 1.0, 2.0,
3.0, 4.0, 5.0, 4.0, 5.0, 6.0,
6.0, 7.0, 8.0, 8.0, 9.0, 10.0,
9.0, 10.0, 11.0, 12.0, 13.0, 14.0,
];
assert_eq!(read, want, "{name}");
let mut want = vec![0xeeee; 64];
for (j, w) in (0..).zip(want.iter_mut().take(12)) {
*w = 0x5000 + j;
}
for i in 0..4u16 {
for lane in 0..3 {
want[usize::from(32 + 4 * i + lane)] = 0x5000 + 4 * i + lane;
}
}
assert_eq!(halves(&h), want, "{name}");
println!("{name}: half vectors of three step three halves, aligned ones four");
});
}
/// The 32 floats of `vsh_round`, with the half `vstore_half_rte` stores for each on the three
/// Macs where that half is a normal number or an infinity (`None` for the rest: a NaN, a zero, a
/// subnormal, whose encoding the device's conversion decides).
#[rustfmt::skip]
const ROUNDED: [(f32, Option<u16>); 32] = [
// 1 + 2^-11 (a tie), 1 + 3 * 2^-12, and its negation.
(1.0 + 1.0 / 2048.0, Some(0x3c00)), (1.0 + 3.0 / 4096.0, Some(0x3c01)),
(-(1.0 + 3.0 / 4096.0), Some(0xbc01)),
// Past the largest half: 65520 is the tie with the next power of two.
(65520.0, Some(0x7c00)), (70000.0, Some(0x7c00)), (-70000.0, Some(0xfc00)),
(1e-8, None), (-1e-8, None), (3e-5, None), (-3e-5, None), (f32::NAN, None),
(f32::INFINITY, Some(0x7c00)), (f32::NEG_INFINITY, Some(0xfc00)), (-0.0, None),
(0.1, Some(0x2e66)), (1.0 / 3.0, Some(0x3555)), (2049.0, Some(0x6800)), (2051.0, Some(0x6802)),
(-2049.0, Some(0xe800)), (65504.0, Some(0x7bff)), (65519.0, Some(0x7bff)),
// 2^-24, 1.5 * 2^-25, 2^-25, -1.5 * 2^-25, 6.1e-5: zeros and subnormals.
(1.0 / 16_777_216.0, None), (1.5 / 33_554_432.0, None), (1.0 / 33_554_432.0, None),
(-1.5 / 33_554_432.0, None), (6.1e-5, None),
// 2^-14 - 2^-25 (the tie between the largest subnormal and the least normal) and
// 2^-14 - 2^-26.
(1.0 / 16_384.0 - 1.0 / 33_554_432.0, Some(0x0400)),
(1.0 / 16_384.0 - 1.0 / 67_108_864.0, Some(0x0400)),
(1e10, Some(0x7c00)), (-1e10, Some(0xfc00)), (0.5, Some(0x3800)),
(std::f32::consts::PI, Some(0x4248)),
];
/// `x`'s `half` rounded toward zero (finite `x`): 65504 from there up, a subnormal truncated.
fn half_toward_zero(x: f32) -> u16 {
let sign = if x.is_sign_negative() { 0x8000 } else { 0 };
let a = x.abs();
let magnitude = if a.is_infinite() {
0x7c00
} else if a >= 65504.0 {
0x7bff
} else if a >= 1.0 / 16_384.0 {
let b = a.to_bits();
u16::try_from((((b >> 23) - 112) << 10) | ((b >> 13) & 0x3ff)).unwrap()
} else {
// A power-of-two scaling, exact; the cast truncates.
(a * 16_777_216.0) as u16
};
sign | magnitude
}
#[test]
fn opencl_mode_vstore_half_stores_every_rounding_as_the_device_converts() {
let Some(vsh_round) = library(&vsh_round()) else {
return;
};
each_device("opencl-data-vstore-half", |name, _, device| {
let s = state(&device, &vsh_round, "__entry_vsh_round");
let f = floats_buffer(&device, &ROUNDED.map(|(x, _)| x));
let h = halves_buffer(&device, &[0xeeee; 160]);
run(name, &device, &s, line(32, 1), ONE, &[whole(&f), whole(&h)]);
let h = halves(&h);
let (plain, forms) = h.split_at(32);
// Every rounding the names spell stores what `vstore_half` stores, as the x86 Macs do.
for (k, form) in forms.chunks(32).enumerate() {
assert_eq!(form, plain, "{name}: form {k} of rte, rtz, rtp, rtn");
}
// That is the device's conversion: to nearest, ties to even, where the half is normal.
// Where the module records `NativeHalfConversion`, Vulkan leaves the conversion's rounding
// to the device (no `RoundingModeRTE`), and the note's bound lets it round toward zero
// (NVIDIA's RTX 3090 and RTX 2080) and flush a 16-bit denormal to the zero of its sign.
let notes = s.precision_notes();
let devices_rounding = notes.contains(&PrecisionNote::NativeHalfConversion);
for (i, (&(x, rte), &got)) in ROUNDED.iter().zip(plain).enumerate() {
if let Some(rte) = rte {
let rtz = half_toward_zero(x);
let flushed = (rtz & 0x7fff) < 0x0400 && got == (rtz & 0x8000);
assert!(
got == rte || (devices_rounding && (got == rtz || flushed)),
"{name}: {i}: {x:e}: {got:#06x}, to nearest {rte:#06x}, toward zero {rtz:#06x}, notes {notes:?}"
);
}
}
println!("{name}: every rounding stores the device's conversion, notes {notes:?}");
});
}
/// A NaN `vstore_half` narrows (each rounding's form) is the device's conversion's NaN, whose bits
/// are its own (NVIDIA's `0x7fff` where Metal stores `0x7e00`): the compute pipeline of OpenCL
/// mode records `NativeNanEncoding` for it.
#[test]
fn opencl_mode_vstore_half_of_a_nan_announces_the_devices_nan_encoding() {
let Some(vsh_round) = library(&vsh_round()) else {
return;
};
each_device("opencl-data-vstore-half-nan", |name, _, device| {
let s = state(&device, &vsh_round, "__entry_vsh_round");
let nans = [0x7fc0_0000u32, 0x7fff_ffff, 0xffc0_0000, 0x7f80_0001];
let inputs: Vec<f32> = (0..32)
.map(|i| nans.get(i).map_or(1.0, |&b| f32::from_bits(b)))
.collect();
let f = floats_buffer(&device, &inputs);
let h = halves_buffer(&device, &[0xeeee; 160]);
run(name, &device, &s, line(32, 1), ONE, &[whole(&f), whole(&h)]);
for (k, form) in halves(&h).chunks(32).enumerate() {
let (nan, one) = form.split_at(nans.len());
for (i, &got) in nan.iter().enumerate() {
assert!(
got & 0x7c00 == 0x7c00 && got & 0x3ff != 0,
"{name}: form {k}, NaN {i}: {got:#06x}"
);
}
assert!(
one.iter().all(|&g| g == 0x3c00),
"{name}: form {k}: {one:x?}"
);
}
let notes = s.precision_notes();
assert!(
notes.contains(&PrecisionNote::NativeNanEncoding),
"{name}: {notes:?}"
);
println!("{name}: each form stores a half NaN, notes {notes:?}");
});
}
#[test]
fn opencl_mode_native_powr_answers_the_devices_powr() {
let Some(npowr) = library(&npowr()) else {
return;
};
each_device("opencl-data-native-powr", |name, _, device| {
let s = state(&device, &npowr, "__entry_npowr");
#[rustfmt::skip]
let (a, b, m3) = (
[2.0, 0.5, 10.0, 3.0, 1.5, 100.0, 0.25, 7.0, 1e-3, 1e3, 4.0, 9.0],
[3.0, 2.0, -1.0, 0.5, 7.25, 0.5, -2.0, 1.5, 2.0, -1.0, 0.5, 0.5],
[
8.0, 0.25, f32::from_bits(0x3dcc_cccd), f32::from_bits(0x3fdd_b3d7),
f32::from_bits(0x4197_4504), f32::from_bits(0x4120_0001), 16.0,
f32::from_bits(0x4194_297e), f32::from_bits(0x3586_37be), f32::from_bits(0x3a83_126f),
2.0, 3.0,
],
);
let (ab, bb) = (floats_buffer(&device, &a), floats_buffer(&device, &b));
let o = floats_buffer(&device, &[0.0; 12]);
let args = [whole(&ab), whole(&bb), whole(&o)];
run(name, &device, &s, line(3, 1), ONE, &args);
for (i, (got, want)) in floats(&o).into_iter().zip(m3).enumerate() {
let error = ((got - want) / want).abs();
assert!(
error <= 2f32.powi(-12),
"{name}: powr({}, {}): {got:e}, the M3 Max {want:e}",
a[i],
b[i]
);
}
println!("{name}: native_powr within 2^-12 of the M3 Max's");
});
}
@@ -0,0 +1,505 @@
//! Images in compute pipelines of OpenCL mode (`ComputePipelineDescriptor::open_cl_mode_enabled`),
//! each kernel in the shape Apple's OpenCL compiler writes OpenCL C's image functions, run with the
//! textures, samplers and hidden buffers bound as Apple's OpenCL binds them, and compared with what
//! an M3 Max (macOS 27.0.1) and a Radeon Pro 5300M (macOS 26.7.1) compute for kernels of the same
//! shapes over the same data:
//!
//! - **formats**: `get_image_channel_order` and `get_image_channel_data_type` answer the words of
//! the third hidden buffer (`__image_order_data_type_table`) of the image's texture index `t`:
//! `2t + 1` for the order, `2t` for the data type. With the buffer's word `i` holding
//! `i * 0x10000 + 0x1234`: the order of the 1D image at texture 1 is `0x31234`, the data type of
//! the 2D array image at 2 `0x41234`, and the 2D image at 0 answers `0x11234` and `0x1234`.
//! - **lines**: a 1D image bound as a 2D texture of height 1 and a 1D array image as a 2D array
//! texture of height 1, as Apple's OpenCL binds them, read with and without a sampler and
//! queried: each read answers the 1D image's texel (row 0, of the layer an array read names;
//! a linear filter at a border-clamped edge blends in no row of the border), and the width and
//! layer count are the image's.
//! - **wlines**: writes to the same two bindings land in row 0, of the layer named.
//! - **real lines**: the same reads over a real 1D texture and a real 1D array texture, which
//! Apple's OpenCL never binds, answer the 1D images' values, layer 1 of the array: the Radeon
//! Pro 5300M's answer (an Intel UHD 630 reads layer 0 of the array, an M3 Max texel 0 at every
//! coordinate).
//!
//! Under a device cfg, on every device of the cfg's kind. The modules are LLVM text written here;
//! `llvm-as` assembles them, and without it the tests skip visibly.
use crate::tests::command::on_device::{each_device, finished};
use crate::tests::opencl_mode::{
buffer, floats, floats_buffer, kernel_list, library, state, words, words_buffer,
};
use crate::{
Buffer, ComputePipelineState, Device, DispatchType, IndexClass, PixelFormat, Region,
SamplerAddressMode, SamplerDescriptor, SamplerMinMagFilter, SamplerState, StorageMode, Texture,
TextureDescriptor, TextureType, TextureUsage,
};
/// The 1D images' width, in texels, and the threads that read or write them.
const WIDTH: u32 = 16;
/// The node of argument `n`, a texture at `index` of the MSL type `ty` (`texture1d<unknown,
/// read>`), its access `access` (`sample` or `write`).
pub(super) fn image(n: u32, index: u32, access: &str, ty: &str, name: &str) -> String {
format!(
"!{{i32 {n}, !\"air.texture\", !\"air.location_index\", i32 {index}, i32 1, !\"air.{access}\", !\"air.arg_type_name\", !\"{ty}\", !\"air.arg_name\", !\"{name}\"}}"
)
}
/// The node of argument `n`, a sampler at `index`.
pub(super) fn sampler_node(n: u32, index: u32, name: &str) -> String {
format!(
"!{{i32 {n}, !\"air.sampler\", !\"air.location_index\", i32 {index}, i32 1, !\"air.arg_type_name\", !\"sampler\", !\"air.arg_name\", !\"{name}\"}}"
)
}
/// The node of argument `n`, a read-write `float4` buffer at `index`.
pub(super) fn float4s(n: u32, index: u32, name: &str) -> String {
format!(
"!{{i32 {n}, !\"air.buffer\", !\"air.location_index\", i32 {index}, i32 1, !\"air.read_write\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 16, !\"air.arg_type_align_size\", i32 16, !\"air.arg_type_name\", !\"float4\", !\"air.arg_name\", !\"{name}\"}}"
)
}
/// `__kernel void formats(__read_only image2d_t a, __read_only image1d_t b, __read_only
/// image2d_array_t c, __global int *o)`: `o[0..4]` take the order of `b`, the data type of `c`, and
/// the order and the data type of `a`.
fn formats() -> String {
let body = "define void @__entry_formats(ptr addrspace(1) %0, ptr addrspace(1) %1, ptr addrspace(1) %2, ptr addrspace(1) %3) #0 {\n\
entry:\n\
tail call fastcc void @formats(ptr addrspace(1) %0, ptr addrspace(1) %1, ptr addrspace(1) %2, ptr addrspace(1) %3)\n\
ret void\n}\n\
define internal fastcc void @formats(ptr addrspace(1) %a, ptr addrspace(1) %b, ptr addrspace(1) %c, ptr addrspace(1) %o) #1 {\n\
entry:\n\
%ob = tail call fastcc i32 @_Z23get_image_channel_order14ocl_image1d_ro(ptr addrspace(1) %b)\n\
store i32 %ob, ptr addrspace(1) %o, align 4\n\
%dc = tail call fastcc i32 @_Z27get_image_channel_data_type20ocl_image2d_array_ro(ptr addrspace(1) %c)\n\
%o1 = getelementptr inbounds i32, ptr addrspace(1) %o, i64 1\n\
store i32 %dc, ptr addrspace(1) %o1, align 4\n\
%oa = tail call fastcc i32 @_Z23get_image_channel_order14ocl_image2d_ro(ptr addrspace(1) %a)\n\
%o2 = getelementptr inbounds i32, ptr addrspace(1) %o, i64 2\n\
store i32 %oa, ptr addrspace(1) %o2, align 4\n\
%da = tail call fastcc i32 @_Z27get_image_channel_data_type14ocl_image2d_ro(ptr addrspace(1) %a)\n\
%o3 = getelementptr inbounds i32, ptr addrspace(1) %o, i64 3\n\
store i32 %da, ptr addrspace(1) %o3, align 4\n\
ret void\n}\n\
define internal fastcc i32 @_Z23get_image_channel_order14ocl_image1d_ro(ptr addrspace(1) %0) #2 {\n\
%2 = tail call i32 @air.get_channel_order_texture_1d(ptr addrspace(1) %0) #0\n\
ret i32 %2\n}\n\
define internal fastcc i32 @_Z27get_image_channel_data_type20ocl_image2d_array_ro(ptr addrspace(1) %0) #2 {\n\
%2 = tail call i32 @air.get_channel_data_type_texture_2d_array(ptr addrspace(1) %0) #0\n\
ret i32 %2\n}\n\
define internal fastcc i32 @_Z23get_image_channel_order14ocl_image2d_ro(ptr addrspace(1) %0) #2 {\n\
%2 = tail call i32 @air.get_channel_order_texture_2d(ptr addrspace(1) %0) #0\n\
ret i32 %2\n}\n\
define internal fastcc i32 @_Z27get_image_channel_data_type14ocl_image2d_ro(ptr addrspace(1) %0) #2 {\n\
%2 = tail call i32 @air.get_channel_data_type_texture_2d(ptr addrspace(1) %0) #0\n\
ret i32 %2\n}\n\
declare i32 @air.get_channel_order_texture_1d(ptr addrspace(1)) #0\n\
declare i32 @air.get_channel_data_type_texture_2d_array(ptr addrspace(1)) #0\n\
declare i32 @air.get_channel_order_texture_2d(ptr addrspace(1)) #0\n\
declare i32 @air.get_channel_data_type_texture_2d(ptr addrspace(1)) #0\n";
let args = [
image(0, 0, "sample", "texture2d<unknown, read>", "a"),
image(1, 1, "sample", "texture1d<unknown, read>", "b"),
image(2, 2, "sample", "texture2d_array<unknown, read>", "c"),
buffer(3, 0, "read_write", 1, "int", "o"),
];
format!("{body}{}", kernel_list("__entry_formats", &args))
}
/// `__kernel void lines(__read_only image1d_t a, __read_only image1d_array_t b, sampler_t s,
/// sampler_t l, __global float4 *o)`: at `x = get_global_id(0)`, `o[6x..6x + 6]` take `a` read at
/// `x`, sampled through `s` at `x` and through `l` at `(x + 0.5) / 16`, layer 1 of `b` read at `x`
/// and sampled through `l` at `(x + 0.5) / 16`, and `(width(a), width(b), array_size(b), 0)`.
fn lines() -> String {
let body = "define void @__entry_lines(ptr addrspace(1) %0, ptr addrspace(1) %1, ptr addrspace(2) %2, ptr addrspace(2) %3, ptr addrspace(1) %4) #0 {\n\
entry:\n\
tail call fastcc void @lines(ptr addrspace(1) %0, ptr addrspace(1) %1, ptr addrspace(2) %2, ptr addrspace(2) %3, ptr addrspace(1) %4)\n\
ret void\n}\n\
define internal fastcc void @lines(ptr addrspace(1) %a, ptr addrspace(1) %b, ptr addrspace(2) %s, ptr addrspace(2) %l, ptr addrspace(1) %o) #1 {\n\
entry:\n\
%g = tail call fastcc i64 @_Z13get_global_idj(i32 0)\n\
%x = trunc i64 %g to i32\n\
%base = mul i64 %g, 6\n\
%fx = sitofp i32 %x to float\n\
%h = fadd float %fx, 5.000000e-01\n\
%nx = fmul float %h, 6.250000e-02\n\
%rs = tail call ptr addrspace(2) @air.get_read_sampler()\n\
%r0 = tail call { <4 x float>, i8 } @air.read_texture_1d.v4f32(ptr addrspace(1) %a, ptr addrspace(2) %rs, i32 %x, i32 0, i32 1)\n\
%t0 = extractvalue { <4 x float>, i8 } %r0, 0\n\
%p0 = getelementptr inbounds <4 x float>, ptr addrspace(1) %o, i64 %base\n\
store <4 x float> %t0, ptr addrspace(1) %p0, align 16\n\
%r1 = tail call { <4 x float>, i8 } @air.sample_texture_1d.v4f32(ptr addrspace(1) %a, ptr addrspace(2) %s, float %fx, i1 false, i32 0, i1 false, float 0.000000e+00, float 0.000000e+00, i32 0)\n\
%t1 = extractvalue { <4 x float>, i8 } %r1, 0\n\
%i1 = add i64 %base, 1\n\
%p1 = getelementptr inbounds <4 x float>, ptr addrspace(1) %o, i64 %i1\n\
store <4 x float> %t1, ptr addrspace(1) %p1, align 16\n\
%r2 = tail call { <4 x float>, i8 } @air.sample_texture_1d.v4f32(ptr addrspace(1) %a, ptr addrspace(2) %l, float %nx, i1 false, i32 0, i1 false, float 0.000000e+00, float 0.000000e+00, i32 0)\n\
%t2 = extractvalue { <4 x float>, i8 } %r2, 0\n\
%i2 = add i64 %base, 2\n\
%p2 = getelementptr inbounds <4 x float>, ptr addrspace(1) %o, i64 %i2\n\
store <4 x float> %t2, ptr addrspace(1) %p2, align 16\n\
%r3 = tail call { <4 x float>, i8 } @air.read_texture_1d_array.v4f32(ptr addrspace(1) %b, ptr addrspace(2) %rs, i32 %x, i32 1, i32 0, i32 1)\n\
%t3 = extractvalue { <4 x float>, i8 } %r3, 0\n\
%i3 = add i64 %base, 3\n\
%p3 = getelementptr inbounds <4 x float>, ptr addrspace(1) %o, i64 %i3\n\
store <4 x float> %t3, ptr addrspace(1) %p3, align 16\n\
%r4 = tail call { <4 x float>, i8 } @air.sample_texture_1d_array.v4f32(ptr addrspace(1) %b, ptr addrspace(2) %l, float %nx, i32 1, i1 false, i32 0, i1 false, float 0.000000e+00, float 0.000000e+00, i32 0)\n\
%t4 = extractvalue { <4 x float>, i8 } %r4, 0\n\
%i4 = add i64 %base, 4\n\
%p4 = getelementptr inbounds <4 x float>, ptr addrspace(1) %o, i64 %i4\n\
store <4 x float> %t4, ptr addrspace(1) %p4, align 16\n\
%wa = tail call i32 @air.get_width_texture_1d(ptr addrspace(1) %a, i32 0)\n\
%wb = tail call i32 @air.get_width_texture_1d_array(ptr addrspace(1) %b, i32 0)\n\
%nb = tail call i32 @air.get_array_size_texture_1d_array(ptr addrspace(1) %b)\n\
%fwa = sitofp i32 %wa to float\n\
%fwb = sitofp i32 %wb to float\n\
%fnb = uitofp i32 %nb to float\n\
%v0 = insertelement <4 x float> <float poison, float poison, float poison, float 0.000000e+00>, float %fwa, i64 0\n\
%v1 = insertelement <4 x float> %v0, float %fwb, i64 1\n\
%v2 = insertelement <4 x float> %v1, float %fnb, i64 2\n\
%i5 = add i64 %base, 5\n\
%p5 = getelementptr inbounds <4 x float>, ptr addrspace(1) %o, i64 %i5\n\
store <4 x float> %v2, ptr addrspace(1) %p5, align 16\n\
ret void\n}\n\
declare ptr addrspace(2) @air.get_read_sampler() #0\n\
declare { <4 x float>, i8 } @air.read_texture_1d.v4f32(ptr addrspace(1), ptr addrspace(2), i32, i32, i32) #0\n\
declare { <4 x float>, i8 } @air.read_texture_1d_array.v4f32(ptr addrspace(1), ptr addrspace(2), i32, i32, i32, i32) #0\n\
declare { <4 x float>, i8 } @air.sample_texture_1d.v4f32(ptr addrspace(1), ptr addrspace(2), float, i1, i32, i1, float, float, i32) #0\n\
declare { <4 x float>, i8 } @air.sample_texture_1d_array.v4f32(ptr addrspace(1), ptr addrspace(2), float, i32, i1, i32, i1, float, float, i32) #0\n\
declare i32 @air.get_width_texture_1d(ptr addrspace(1), i32) #0\n\
declare i32 @air.get_width_texture_1d_array(ptr addrspace(1), i32) #0\n\
declare i32 @air.get_array_size_texture_1d_array(ptr addrspace(1)) #0\n";
let args = [
image(0, 0, "sample", "texture1d<unknown, read>", "a"),
image(1, 1, "sample", "texture1d_array<unknown, read>", "b"),
sampler_node(2, 0, "s"),
sampler_node(3, 1, "l"),
float4s(4, 0, "o"),
];
format!("{body}{}", kernel_list("__entry_lines", &args))
}
/// `__kernel void wlines(__write_only image1d_t a, __write_only image1d_array_t b)`: at
/// `x = get_global_id(0)`, `a` takes `(x, 1, 2, 3)` at `x` and layer 1 of `b` `(x, 4, 5, 6)`.
fn wlines() -> String {
let body = "define void @__entry_wlines(ptr addrspace(1) %0, ptr addrspace(1) %1) #0 {\n\
entry:\n\
tail call fastcc void @wlines(ptr addrspace(1) %0, ptr addrspace(1) %1)\n\
ret void\n}\n\
define internal fastcc void @wlines(ptr addrspace(1) %a, ptr addrspace(1) %b) #1 {\n\
entry:\n\
%g = tail call fastcc i64 @_Z13get_global_idj(i32 0)\n\
%x = trunc i64 %g to i32\n\
%fx = sitofp i32 %x to float\n\
%ta = insertelement <4 x float> <float poison, float 1.000000e+00, float 2.000000e+00, float 3.000000e+00>, float %fx, i64 0\n\
tail call void @air.write_texture_1d.v4f32(ptr addrspace(1) %a, i32 %x, <4 x float> %ta, i32 0, i32 2)\n\
%tb = insertelement <4 x float> <float poison, float 4.000000e+00, float 5.000000e+00, float 6.000000e+00>, float %fx, i64 0\n\
tail call void @air.write_texture_1d_array.v4f32(ptr addrspace(1) %b, i32 %x, i32 1, <4 x float> %tb, i32 0, i32 2)\n\
ret void\n}\n\
declare void @air.write_texture_1d.v4f32(ptr addrspace(1), i32, <4 x float>, i32, i32) #0\n\
declare void @air.write_texture_1d_array.v4f32(ptr addrspace(1), i32, i32, <4 x float>, i32, i32) #0\n";
let args = [
image(0, 0, "write", "texture1d<unknown, write>", "a"),
image(1, 1, "write", "texture1d_array<unknown, write>", "b"),
];
format!("{body}{}", kernel_list("__entry_wlines", &args))
}
/// A Shared `RGBA32Float` texture of `texture_type` at texture index `index`, `width` by
/// `height`, of `layers` layers, each of `texels` where given.
fn texture(
device: &Device,
texture_type: TextureType,
(width, height, layers): (u32, u32, u32),
texels: Option<&[f32]>,
index: u32,
) -> Texture {
let mut descriptor =
TextureDescriptor::new(texture_type, PixelFormat::RGBA32Float, width, height);
descriptor.array_length = layers;
descriptor.usage = TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE;
descriptor.storage_mode = StorageMode::Shared;
let texture = (device.new_texture(&descriptor, Some(index)))
.unwrap_or_else(|error| panic!("{descriptor:?}: {error}"));
let image = (width * height * 4) as usize;
if let Some(texels) = texels {
for (layer, texels) in (0u32..).zip(texels.chunks(image)) {
let bytes: Vec<u8> = texels.iter().flat_map(|f| f.to_le_bytes()).collect();
let row = u64::from(16 * width);
let region = Region {
origin: [0; 3],
size: [width, height, 1],
};
let bytes = crate::HostBytes::from(&bytes[..]);
(texture.replace_region(region, 0, layer, bytes, row, row * u64::from(height)))
.unwrap_or_else(|error| panic!("layer {layer}: {error}"));
}
}
texture
}
/// Row 0 of layer `layer` of `texture`, `WIDTH` texels wide, as floats.
fn row(texture: &Texture, layer: u32) -> Vec<f32> {
let mut bytes = vec![0u8; (16 * WIDTH) as usize];
let region = Region {
origin: [0; 3],
size: [WIDTH, 1, 1],
};
let row = u64::from(16 * WIDTH);
(texture.get_bytes(&mut bytes, row, row, region, 0, layer)).expect("the row");
bytes
.as_chunks::<4>()
.0
.iter()
.map(|w| f32::from_le_bytes(*w))
.collect()
}
/// A sampler state at sampler index `index` of `filter`, `address` and `normalized` coordinates.
pub(super) fn sampler(
device: &Device,
filter: SamplerMinMagFilter,
address: SamplerAddressMode,
normalized: bool,
index: u32,
) -> SamplerState {
let mut descriptor = SamplerDescriptor::new();
descriptor.min_filter = filter;
descriptor.mag_filter = filter;
descriptor.s_address_mode = address;
descriptor.t_address_mode = address;
descriptor.r_address_mode = address;
descriptor.normalized_coordinates = normalized;
(device.new_sampler_state(&descriptor, index)).expect("a sampler state")
}
/// What `state` binds besides its hidden buffers.
pub(super) struct Bound<'a> {
pub(super) textures: &'a [&'a Texture],
pub(super) samplers: &'a [&'a SamplerState],
/// The kernel's own buffer at 3 (its index 0), if any.
pub(super) out: Option<&'a Buffer>,
}
/// `state` dispatched on `device` (named `name`) over `threads` threads, one dimension, its hidden
/// buffers bound as Apple's OpenCL binds them (the first's bytes at index 0 no offset and one
/// dimension, the third holding word `i` as `i * 0x10000 + 0x1234`), and `bound`'s textures,
/// samplers and buffer at their indices; committed and finished without an error.
pub(super) fn run(
name: &str,
device: &Device,
state: &ComputePipelineState,
threads: u32,
bound: &Bound<'_>,
) {
let table: Vec<u32> = (0..64).map(|i| i * 0x10000 + 0x1234).collect();
let first: Vec<u8> = [0u32, 0, 0, 1]
.iter()
.flat_map(|w| w.to_le_bytes())
.collect();
let hidden = [words_buffer(device, &[0; 16]), words_buffer(device, &table)];
let queue = device.new_command_queue(1).expect("a queue");
let command_buffer = queue.command_buffer().expect("a command buffer");
let mut encoder =
(command_buffer.compute_command_encoder(DispatchType::Serial)).expect("an encoder");
encoder
.set_compute_pipeline_state(state)
.expect("the state");
encoder
.set_bytes(&first, 0)
.expect("the first hidden buffer");
for (index, b) in (1u32..).zip(&hidden) {
(encoder.set_buffer(Some(b), 0, index)).expect("a hidden buffer");
}
if let Some(out) = bound.out {
encoder
.set_buffer(Some(out), 0, 3)
.expect("the kernel's buffer");
}
for (index, t) in (0u32..).zip(bound.textures) {
(encoder.set_texture(Some(t), index))
.unwrap_or_else(|error| panic!("{name}: texture {index}: {error}"));
}
for (index, s) in (0u32..).zip(bound.samplers) {
(encoder.set_sampler_state(Some(s), index))
.unwrap_or_else(|error| panic!("{name}: sampler {index}: {error}"));
}
(encoder.dispatch_threads([threads, 1, 1], [threads, 1, 1]))
.unwrap_or_else(|error| panic!("{name}: the dispatch: {error}"));
encoder.end_encoding();
command_buffer.commit().expect("a commit");
finished(name, &command_buffer);
assert_eq!(command_buffer.error(), None, "{name}");
}
/// The 1D image's texels: lane `i` of the row is `10 + i`.
fn line() -> Vec<f32> {
(0..WIDTH * 4).map(|i| 10.0 + i as f32).collect()
}
/// The 1D array image's texels: lane `i` of its two layers is `1000 + i`.
fn layers() -> Vec<f32> {
(0..2 * WIDTH * 4).map(|i| 1000.0 + i as f32).collect()
}
#[test]
fn opencl_mode_image_formats_read_the_third_hidden_buffer() {
let Some(formats) = library(&formats()) else {
return;
};
each_device("opencl-images-formats", |name, _, device| {
let _grant = (device.grant_indices(IndexClass::Texture, 1, 3))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let formats = state(&device, &formats, "__entry_formats");
let a = texture(&device, TextureType::Type2D, (8, 4, 1), None, 1);
let b = texture(&device, TextureType::Type2D, (WIDTH, 1, 1), None, 2);
let c = texture(&device, TextureType::Type2DArray, (8, 4, 3), None, 3);
let o = words_buffer(&device, &[0xeeee_eeee; 4]);
let bound = Bound {
textures: &[&a, &b, &c],
samplers: &[],
out: Some(&o),
};
run(name, &device, &formats, 1, &bound);
assert_eq!(words(&o), [0x31234, 0x41234, 0x11234, 0x1234], "{name}");
println!("{name}: each image's order and data type are the third hidden buffer's words");
});
}
/// [`lines`] run on `device` (named `name`) over `a`, its 1D image, and `b`, its 1D array image
/// (each holding [`line`] and [`layers`]), with a nearest sampler of unnormalized coordinates and a
/// linear one of normalized coordinates clamped to zero: every read, sample and size query answers
/// the 1D images' values.
fn lines_read(name: &str, device: &Device, lines: &ComputePipelineState, a: &Texture, b: &Texture) {
let (line, layers) = (line(), layers());
let _grant = (device.grant_indices(IndexClass::Sampler, 1, 2))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let s = sampler(
device,
SamplerMinMagFilter::Nearest,
SamplerAddressMode::ClampToEdge,
false,
1,
);
let l = sampler(
device,
SamplerMinMagFilter::Linear,
SamplerAddressMode::ClampToZero,
true,
2,
);
let o = floats_buffer(device, &vec![-1.0; (WIDTH * 6 * 4) as usize]);
let bound = Bound {
textures: &[a, b],
samplers: &[&s, &l],
out: Some(&o),
};
run(name, device, lines, WIDTH, &bound);
let got = floats(&o);
for x in 0..WIDTH as usize {
let at = |column: usize| &got[(6 * x + column) * 4..(6 * x + column + 1) * 4];
let texel = &line[4 * x..4 * x + 4];
let layer1 = &layers[(WIDTH as usize + x) * 4..(WIDTH as usize + x + 1) * 4];
assert_eq!(at(0), texel, "{name}: read of a at {x}");
assert_eq!(at(1), texel, "{name}: sample of a through s at {x}");
assert_eq!(at(2), texel, "{name}: sample of a through l at {x}");
assert_eq!(at(3), layer1, "{name}: read of b's layer 1 at {x}");
assert_eq!(
at(4),
layer1,
"{name}: sample of b's layer 1 through l at {x}"
);
assert_eq!(at(5), [16.0, 16.0, 2.0, 0.0], "{name}: sizes at {x}");
}
}
#[test]
fn opencl_mode_1d_images_read_their_2d_bindings_row_0() {
let Some(lines) = library(&lines()) else {
return;
};
each_device("opencl-images-lines", |name, _, device| {
let _grant = (device.grant_indices(IndexClass::Texture, 1, 2))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let lines = state(&device, &lines, "__entry_lines");
let (line, layers) = (line(), layers());
let a = texture(&device, TextureType::Type2D, (WIDTH, 1, 1), Some(&line), 1);
let b = texture(
&device,
TextureType::Type2DArray,
(WIDTH, 1, 2),
Some(&layers),
2,
);
lines_read(name, &device, &lines, &a, &b);
println!("{name}: 1D images read row 0 of their 2D bindings");
});
}
/// A 1D image bound as a real 1D texture and a 1D array image as a real 1D array texture, which
/// Apple's OpenCL never binds, read as the 1D images they are: the Radeon Pro 5300M's answer
/// (macOS 26.7.1), every read, sample and size query the 1D image's value, layer 1 of the array.
#[test]
fn opencl_mode_1d_images_read_real_1d_textures() {
let Some(lines) = library(&lines()) else {
return;
};
each_device("opencl-images-real-lines", |name, _, device| {
let _grant = (device.grant_indices(IndexClass::Texture, 1, 2))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let lines = state(&device, &lines, "__entry_lines");
let (line, layers) = (line(), layers());
let a = texture(&device, TextureType::Type1D, (WIDTH, 1, 1), Some(&line), 1);
let b = texture(
&device,
TextureType::Type1DArray,
(WIDTH, 1, 2),
Some(&layers),
2,
);
lines_read(name, &device, &lines, &a, &b);
println!("{name}: 1D images read real 1D textures");
});
}
#[test]
fn opencl_mode_1d_images_write_their_2d_bindings_row_0() {
let Some(wlines) = library(&wlines()) else {
return;
};
each_device("opencl-images-wlines", |name, _, device| {
let _grant = (device.grant_indices(IndexClass::Texture, 1, 2))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let wlines = state(&device, &wlines, "__entry_wlines");
let zeros = vec![0.0; (2 * WIDTH * 4) as usize];
let one_layer = &zeros[..(WIDTH * 4) as usize];
let a = texture(
&device,
TextureType::Type2D,
(WIDTH, 1, 1),
Some(one_layer),
1,
);
let b = texture(
&device,
TextureType::Type2DArray,
(WIDTH, 1, 2),
Some(&zeros),
2,
);
let bound = Bound {
textures: &[&a, &b],
samplers: &[],
out: None,
};
run(name, &device, &wlines, WIDTH, &bound);
let texels = |lanes: [f32; 3]| -> Vec<f32> {
(0..WIDTH)
.flat_map(|x| [x as f32, lanes[0], lanes[1], lanes[2]])
.collect()
};
assert_eq!(row(&a, 0), texels([1.0, 2.0, 3.0]), "{name}");
assert_eq!(row(&b, 0), vec![0.0; (WIDTH * 4) as usize], "{name}");
assert_eq!(row(&b, 1), texels([4.0, 5.0, 6.0]), "{name}");
println!("{name}: 1D images write row 0 of their 2D bindings");
});
}
@@ -0,0 +1,161 @@
//! Kernels in the shapes Metal's compiler writes for OpenCL C (`newLibraryWithSource` with
//! `sourceLanguage` 1, as the GL renderer's compute path builds an OpenCL program), each run and
//! compared with what Metal computes.
//!
//! - **A barrier out of line**: OpenCL C's `barrier(flags)` stays an internal function passing its
//! flags on to `air.wg.barrier`, and `mem_fence(flags)` computes `air.atomic.fence`'s flags from
//! them through `llvm.bitreverse.i2`. Both made and run on an M3 Max (macOS 27.0.1) and an Intel
//! UHD 630 (26.7.1): `x[i] = 1`, the barrier, `x[i] += x[i ^ 1]` stores 2 in every word.
//!
//! Under a device cfg, on every device of the cfg's kind. The modules are LLVM text written here;
//! `llvm-as` assembles them, and without it the test skips visibly.
use crate::tests::command::on_device::{each_device, finished};
use crate::tests::opencl_mode::{bytes_buffer, words};
use crate::{
ComputePipelineDescriptor, ComputePipelineState, Device, DispatchType, FunctionDescriptor,
Library, StageSource,
};
use metal2vulkan_devtools::{llvm_assemble_text, AssembleError};
/// The target, the work-item function, and the module's versions.
const HEAD: &str = "target datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32\"\n\
target triple = \"air64_v28-apple-macosx26.0.0\"\n\
declare i32 @air.get_global_id.i32(i32) #9\n\
attributes #9 = { nounwind readnone willreturn }\n\
!air.version = !{!90}\n\
!air.language_version = !{!91}\n\
!90 = !{i32 2, i32 8, i32 0}\n\
!91 = !{!\"Metal\", i32 3, i32 2, i32 0}\n";
/// The node of kernel argument 0, `x`, a read-write `int` buffer at index 0.
const X: &str = "!{i32 0, !\"air.buffer\", !\"air.location_index\", i32 0, i32 1, !\"air.read_write\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"int\", !\"air.arg_name\", !\"x\"}";
/// The words a dispatch runs over.
const WORDS: u32 = 64;
/// The library of the module `text` (after [`HEAD`]), or None where `llvm-as` is missing.
fn library(text: &str) -> Option<Library> {
match llvm_assemble_text(&format!("{HEAD}{text}")) {
Ok(air) => Some(Library::from_air(&air).expect("the library")),
Err(AssembleError::Missing(why)) => {
eprintln!("SKIPPED: {why}");
None
}
Err(error) => panic!("the module: {error:?}"),
}
}
/// The state of kernel `name` of `library`, a plain pipeline's.
fn state(device: &Device, library: &Library, name: &str) -> ComputePipelineState {
let function = library.function(name).expect("the kernel");
let descriptor =
ComputePipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new(function)));
(device.new_compute_pipeline_state(&descriptor, crate::tests::no_constexpr_samplers))
.unwrap_or_else(|error| panic!("{name}: {error}"))
}
/// `state` run on `device` (named `name`) over [`WORDS`] threads in threadgroups of `group`, `x`
/// holding `init`; `x`'s words after.
fn run(
name: &str,
device: &Device,
state: &ComputePipelineState,
init: &[u32],
group: u32,
) -> Vec<u32> {
let bytes: Vec<u8> = init.iter().flat_map(|w| w.to_le_bytes()).collect();
let x = bytes_buffer(device, &bytes);
let queue = device.new_command_queue(1).expect("a queue");
let command_buffer = queue.command_buffer().expect("a command buffer");
let mut encoder =
(command_buffer.compute_command_encoder(DispatchType::Serial)).expect("an encoder");
encoder
.set_compute_pipeline_state(state)
.expect("the state");
encoder.set_buffer(Some(&x), 0, 0).expect("x");
(encoder.dispatch_threads([WORDS, 1, 1], [group, 1, 1]))
.unwrap_or_else(|error| panic!("{name}: the dispatch: {error}"));
encoder.end_encoding();
command_buffer.commit().expect("a commit");
finished(name, &command_buffer);
assert_eq!(command_buffer.error(), None, "{name}");
words(&x)
}
/// `x[i] = 1`, `@wait(3)`, `x[i] += x[i ^ 1]`, the barrier's flags (`mem_device |
/// mem_threadgroup`, which order the device words the threads exchange) `@wait`'s parameter.
const BARRIER: &str = "define void @fence(ptr addrspace(1) nocapture %x) #3 {\n\
%id = tail call i32 @air.get_global_id.i32(i32 0)\n\
%i = zext i32 %id to i64\n\
%p = getelementptr inbounds i32, ptr addrspace(1) %x, i64 %i\n\
store i32 1, ptr addrspace(1) %p, align 4\n\
tail call fastcc void @wait(i32 3)\n\
%j = xor i64 %i, 1\n\
%q = getelementptr inbounds i32, ptr addrspace(1) %x, i64 %j\n\
%a = load i32, ptr addrspace(1) %q, align 4\n\
%b = load i32, ptr addrspace(1) %p, align 4\n\
%s = add i32 %a, %b\n\
store i32 %s, ptr addrspace(1) %p, align 4\n\
ret void\n}\n\
define internal fastcc void @wait(i32 %flags) #2 {\n\
tail call void @air.wg.barrier(i32 %flags, i32 1) #1\n\
ret void\n}\n\
declare void @air.wg.barrier(i32, i32) #1\n\
attributes #1 = { convergent nounwind willreturn }\n\
attributes #2 = { convergent noinline nounwind }\n\
attributes #3 = { convergent nounwind }\n\
!air.kernel = !{!0}\n\
!0 = !{ptr @fence, !1, !2}\n\
!1 = !{}\n\
!2 = !{!3}\n";
/// `x[i] = 1`, `@fence(2)` (its flags `bitreverse.i2` of the parameter's low bits, as OpenCL C's
/// `mem_fence(CLK_GLOBAL_MEM_FENCE)` becomes `mem_device`), `x[i] = 2`.
const FENCE: &str = "define void @store2(ptr addrspace(1) nocapture %x) #3 {\n\
%id = tail call i32 @air.get_global_id.i32(i32 0)\n\
%i = zext i32 %id to i64\n\
%p = getelementptr inbounds i32, ptr addrspace(1) %x, i64 %i\n\
store i32 1, ptr addrspace(1) %p, align 4\n\
tail call fastcc void @fence(i32 2)\n\
store i32 2, ptr addrspace(1) %p, align 4\n\
ret void\n}\n\
define internal fastcc void @fence(i32 %flags) #2 {\n\
%t = trunc i32 %flags to i2\n\
%r = tail call i2 @llvm.bitreverse.i2(i2 %t)\n\
%m = zext i2 %r to i32\n\
tail call void @air.atomic.fence(i32 %m, i32 3, i32 1) #1\n\
ret void\n}\n\
declare void @air.atomic.fence(i32, i32, i32) #1\n\
declare i2 @llvm.bitreverse.i2(i2) #9\n\
attributes #1 = { nounwind willreturn }\n\
attributes #2 = { noinline nounwind }\n\
attributes #3 = { nounwind }\n\
!air.kernel = !{!0}\n\
!0 = !{ptr @store2, !1, !2}\n\
!1 = !{}\n\
!2 = !{!3}\n";
#[test]
fn a_barrier_and_a_fence_out_of_line_compute_what_metal_computes() {
let kernels = [(BARRIER, "fence"), (FENCE, "store2")];
let Some(libraries) = kernels
.iter()
.map(|(text, _)| library(&format!("{text}!3 = {X}\n")))
.collect::<Option<Vec<Library>>>()
else {
return;
};
each_device("opencl-barrier", |name, _, device| {
let start = vec![0u32; WORDS as usize];
for ((_, kernel), library) in kernels.iter().zip(&libraries) {
let state = state(&device, library, kernel);
assert_eq!(
run(name, &device, &state, &start, 32),
vec![2; WORDS as usize],
"{name}: {kernel}"
);
}
println!("{name}: the barrier and the fence out of line store 2 in every word");
});
}
@@ -0,0 +1,868 @@
//! Compute pipelines of OpenCL mode (`ComputePipelineDescriptor::open_cl_mode_enabled`), under a
//! device cfg on every device of the cfg's kind, each kernel in the shape Apple's OpenCL compiler
//! writes for OpenCL C (`__entry_<name>` calling the kernel, an internal function, which calls the
//! work-item functions through internal wrappers of `air.get_*`), run with the three hidden
//! buffers bound as Metal's OpenCL dispatcher binds them (the first, the dispatch's global offset
//! in each dimension and its dimension count, by `setBytes` at index 0, as the replay player binds
//! it; the second and third as buffers at 1 and 2; the kernel's own buffers from 3), and compared
//! with what the M3 Max (macOS 27.0.1) computes for the same kernels:
//!
//! - **add**: `c[i] = a[i] + b[i]` over 1024 threads, `a[i] = i`, `b[i] = 2i + 1`: `3i + 1`.
//! - **scale**: `b[i] *= k` for `i < n`, `k` and `n` passed by value, over 128 threads, `b[i] = i`:
//! `k = 2.5, n = 100` set as bytes, then `k = 3, n = 50` in a buffer at offsets 16 and 32.
//! - **st**: `o[i] = s.a + s.b` for a struct passed by value, `s = {2.5, 4}`: 6.5.
//! - **wg**: `o[i] = get_local_size(0)` of `reqd_work_group_size(64, 1, 1)`: a pipeline of at most
//! 64 threads a threadgroup, which answers 64 in threadgroups of 64 and 32 in threadgroups of
//! 32.
//! - **cmul**: `o[i] *= c[i & 3]` through a `__constant` pointer, `o[i] = i + 1`, `c = 1, 2, 3, 4`:
//! 1, 4, 9, 16, 5, 12, ...
//! - **items**: every work-item function, of the dimensions it names and of one passed by value,
//! over a grid of 8 by 4 threads in threadgroups of 4 by 2 at offset (3, 5), of
//! two dimensions. The M3 Max answers each word as OpenCL defines it, but for the store of
//! `get_global_id(3) + get_local_size(4) + get_global_size(5)`, which it leaves unwritten; the
//! crate stores OpenCL's 2.
//!
//! - **conversions**: `air.convert` with each rounding and `.sat` Apple's OpenCL compiler spells
//! on `convert_<type>[_sat][_<mode>]`, one conversion a work-item, against the words a Radeon
//! Pro 5300M and a UHD Graphics 630 (macOS 26.7.1) answered alike in OpenCL mode (probe jobs
//! m3-max-15651 and m3-max-15652, OpenCL C of our own): integers of 32 and 64 bits to `float`
//! toward zero, up and down; `float` to integers of 8 to 64 bits to nearest even, up and down;
//! and `.sat` between integers.
//!
//! The modules are LLVM text written here; `llvm-as` assembles them, and without it the tests skip
//! visibly.
use crate::tests::command::on_device::{each_device, finished};
use crate::{
Buffer, ComputePipelineDescriptor, ComputePipelineState, Device, DispatchType,
FunctionDescriptor, Library, MemoryClass, StageSource,
};
use metal2vulkan_devtools::{llvm_assemble_text, AssembleError};
/// The target, the work-item functions' wrappers as the OpenCL compiler writes them, and the
/// module's versions.
const HEAD: &str = "target datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32\"\n\
target triple = \"air64_v29-apple-macosx27.0.0\"\n\
define internal fastcc i64 @_Z13get_global_idj(i32 %0) #2 {\n\
%2 = tail call i32 @air.get_global_id.i32(i32 %0) #3\n\
%3 = zext i32 %2 to i64\n\
ret i64 %3\n}\n\
define internal fastcc i64 @_Z12get_local_idj(i32 %0) #2 {\n\
%2 = tail call i32 @air.get_local_id.i32(i32 %0) #3\n\
%3 = zext i32 %2 to i64\n\
ret i64 %3\n}\n\
define internal fastcc i64 @_Z12get_group_idj(i32 %0) #2 {\n\
%2 = tail call i32 @air.get_group_id.i32(i32 %0) #3\n\
%3 = zext i32 %2 to i64\n\
ret i64 %3\n}\n\
define internal fastcc i64 @_Z14get_local_sizej(i32 %0) #2 {\n\
%2 = tail call i32 @air.get_local_size.i32(i32 %0) #3\n\
%3 = zext i32 %2 to i64\n\
ret i64 %3\n}\n\
define internal fastcc i64 @_Z15get_global_sizej(i32 %0) #2 {\n\
%2 = tail call i32 @air.get_global_size.i32(i32 %0) #3\n\
%3 = zext i32 %2 to i64\n\
ret i64 %3\n}\n\
define internal fastcc i64 @_Z14get_num_groupsj(i32 %0) #2 {\n\
%2 = tail call i32 @air.get_num_groups.i32(i32 %0) #3\n\
%3 = zext i32 %2 to i64\n\
ret i64 %3\n}\n\
define internal fastcc i64 @_Z17get_global_offsetj(i32 %0) #2 {\n\
%2 = tail call i32 @air.get_global_offset.i32(i32 %0) #3\n\
%3 = zext i32 %2 to i64\n\
ret i64 %3\n}\n\
define internal fastcc i32 @_Z12get_work_dimv() #2 {\n\
%1 = tail call i32 @air.get_work_dim.i32() #3\n\
ret i32 %1\n}\n\
define internal fastcc void @_Z7barrierj(i32 %0) #4 {\n\
call void @air.wg.barrier(i32 %0, i32 5, i32 1) #5\n\
ret void\n}\n\
declare i32 @air.get_global_id.i32(i32) #3\n\
declare i32 @air.get_local_id.i32(i32) #3\n\
declare i32 @air.get_group_id.i32(i32) #3\n\
declare i32 @air.get_local_size.i32(i32) #3\n\
declare i32 @air.get_global_size.i32(i32) #3\n\
declare i32 @air.get_num_groups.i32(i32) #3\n\
declare i32 @air.get_global_offset.i32(i32) #3\n\
declare i32 @air.get_work_dim.i32() #3\n\
declare void @air.wg.barrier(i32, i32, i32) #5\n\
attributes #0 = { nounwind }\n\
attributes #1 = { convergent nounwind }\n\
attributes #2 = { nounwind optsize }\n\
attributes #3 = { nounwind readnone willreturn }\n\
attributes #4 = { convergent nounwind }\n\
attributes #5 = { convergent nounwind willreturn }\n\
!air.version = !{!90}\n\
!air.language_version = !{!91}\n\
!90 = !{i32 2, i32 9, i32 0}\n\
!91 = !{!\"Metal\", i32 1, i32 1, i32 0}\n";
/// The node of argument `n`, a buffer at `index` of address space `space` holding `ty`, `access`
/// one of `read`, `read_write`.
pub(super) fn buffer(n: u32, index: u32, access: &str, space: u32, ty: &str, name: &str) -> String {
format!(
"!{{i32 {n}, !\"air.buffer\", !\"air.location_index\", i32 {index}, i32 1, !\"air.{access}\", !\"air.address_space\", i32 {space}, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"{ty}\", !\"air.arg_name\", !\"{name}\"}}"
)
}
/// The node of argument `n`, passed by value at `index`: `size` bytes of `ty`, its layout the node
/// `layout` names where `Some`.
fn constant(n: u32, index: u32, size: u32, ty: &str, name: &str, layout: Option<&str>) -> String {
let layout = layout
.map(|l| format!(" !\"air.struct_type_info\", {l},"))
.unwrap_or_default();
format!(
"!{{i32 {n}, !\"air.constant\", !\"air.location_index\", i32 {index}, i32 1,{layout} !\"air.arg_type_size\", i32 {size}, !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"{ty}\", !\"air.arg_name\", !\"{name}\"}}"
)
}
/// The kernel list of `entry` with argument nodes `args`.
pub(super) fn kernel_list(entry: &str, args: &[String]) -> String {
kernel_list_with(entry, args, "")
}
/// The kernel list of `entry` with argument nodes `args` and the trailing entry attributes
/// `attributes` (each `, !n`).
fn kernel_list_with(entry: &str, args: &[String], attributes: &str) -> String {
let refs: Vec<String> = (0..args.len()).map(|i| format!("!{}", 3 + i)).collect();
let mut out = format!(
"!air.kernel = !{{!0}}\n!0 = !{{ptr @{entry}, !1, !2{attributes}}}\n!1 = !{{}}\n!2 = !{{{}}}\n",
refs.join(", ")
);
for (i, a) in args.iter().enumerate() {
out.push_str(&format!("!{} = {a}\n", 3 + i));
}
out
}
/// `__kernel void add(__global const float *a, __global const float *b, __global float *c)`.
fn add() -> String {
let body = "define void @__entry_add(ptr addrspace(1) %0, ptr addrspace(1) %1, ptr addrspace(1) %2) #0 {\n\
entry:\n\
tail call fastcc void @add(ptr addrspace(1) %0, ptr addrspace(1) %1, ptr addrspace(1) %2)\n\
ret void\n}\n\
define internal fastcc void @add(ptr addrspace(1) %a, ptr addrspace(1) %b, ptr addrspace(1) %c) #1 {\n\
entry:\n\
%i = tail call fastcc i64 @_Z13get_global_idj(i32 0)\n\
%pa = getelementptr inbounds float, ptr addrspace(1) %a, i64 %i\n\
%va = load float, ptr addrspace(1) %pa, align 4\n\
%pb = getelementptr inbounds float, ptr addrspace(1) %b, i64 %i\n\
%vb = load float, ptr addrspace(1) %pb, align 4\n\
%s = fadd float %va, %vb\n\
%pc = getelementptr inbounds float, ptr addrspace(1) %c, i64 %i\n\
store float %s, ptr addrspace(1) %pc, align 4\n\
ret void\n}\n";
let args = [
buffer(0, 0, "read", 1, "float", "a"),
buffer(1, 1, "read", 1, "float", "b"),
buffer(2, 2, "read_write", 1, "float", "c"),
];
format!("{body}{}", kernel_list("__entry_add", &args))
}
/// `__kernel void scale(__global float *b, float k, uint n)`: `if (i < n) b[i] *= k`.
fn scale() -> String {
let body = "define void @__entry_scale(ptr addrspace(1) %0, ptr addrspace(2) %1, ptr addrspace(2) %2) #0 {\n\
entry:\n\
%3 = load float, ptr addrspace(2) %1, align 4\n\
%4 = load i32, ptr addrspace(2) %2, align 4\n\
tail call fastcc void @scale(ptr addrspace(1) %0, float %3, i32 %4)\n\
ret void\n}\n\
define internal fastcc void @scale(ptr addrspace(1) %b, float %k, i32 %n) #1 {\n\
entry:\n\
%i = tail call fastcc i64 @_Z13get_global_idj(i32 0)\n\
%wide = zext i32 %n to i64\n\
%in = icmp ult i64 %i, %wide\n\
br i1 %in, label %then, label %end\n\
then:\n\
%p = getelementptr inbounds float, ptr addrspace(1) %b, i64 %i\n\
%v = load float, ptr addrspace(1) %p, align 4\n\
%m = fmul float %v, %k\n\
store float %m, ptr addrspace(1) %p, align 4\n\
br label %end\n\
end:\n\
ret void\n}\n";
let args = [
buffer(0, 0, "read_write", 1, "float", "b"),
constant(1, 1, 4, "float", "k", None),
constant(2, 2, 4, "uint", "n", None),
];
format!("{body}{}", kernel_list("__entry_scale", &args))
}
/// `__kernel void st(__global float *o, struct S s)`, `struct S { float a; int b; }`: `o[i] = s.a +
/// s.b`, the entry copying the struct to the private `byval` copy the kernel reads.
fn st() -> String {
let body = "%struct.S = type { float, i32 }\n\
define void @__entry_st(ptr addrspace(1) %0, ptr addrspace(2) %1) #0 {\n\
entry:\n\
%2 = alloca i64, align 8\n\
%3 = load i64, ptr addrspace(2) %1, align 4\n\
store i64 %3, ptr %2, align 8\n\
tail call fastcc void @st(ptr addrspace(1) %0, ptr nonnull byval(%struct.S) %2)\n\
ret void\n}\n\
define internal fastcc void @st(ptr addrspace(1) %o, ptr byval(%struct.S) align 4 %s) #1 {\n\
entry:\n\
%i = tail call fastcc i64 @_Z13get_global_idj(i32 0)\n\
%pa = getelementptr inbounds %struct.S, ptr %s, i64 0, i32 0\n\
%a = load float, ptr %pa, align 4\n\
%pb = getelementptr inbounds %struct.S, ptr %s, i64 0, i32 1\n\
%b = load i32, ptr %pb, align 4\n\
%fb = tail call float @air.convert.f.f32.s.i32(i32 %b) #3\n\
%r = fadd float %a, %fb\n\
%po = getelementptr inbounds float, ptr addrspace(1) %o, i64 %i\n\
store float %r, ptr addrspace(1) %po, align 4\n\
ret void\n}\n\
declare float @air.convert.f.f32.s.i32(i32) #3\n\
!50 = !{i32 0, i32 4, i32 0, !\"float\", !\"a\", i32 4, i32 4, i32 0, !\"int\", !\"b\"}\n";
let args = [
buffer(0, 0, "read_write", 1, "float", "o"),
constant(1, 1, 8, "S", "s", Some("!50")),
];
format!("{body}{}", kernel_list("__entry_st", &args))
}
/// `__kernel __attribute__((reqd_work_group_size(64, 1, 1))) void wg(__global float *o)`:
/// `o[get_global_id(0)] = get_local_size(0)`.
fn wg() -> String {
let body = "define void @__entry_wg(ptr addrspace(1) %0) #0 {\n\
entry:\n\
tail call fastcc void @wg(ptr addrspace(1) %0)\n\
ret void\n}\n\
define internal fastcc void @wg(ptr addrspace(1) %o) #1 {\n\
entry:\n\
%i = tail call fastcc i64 @_Z13get_global_idj(i32 0)\n\
%n = tail call fastcc i64 @_Z14get_local_sizej(i32 0)\n\
%f = uitofp i64 %n to float\n\
%po = getelementptr inbounds float, ptr addrspace(1) %o, i64 %i\n\
store float %f, ptr addrspace(1) %po, align 4\n\
ret void\n}\n\
!51 = !{!\"air.work_group_size\", i32 64, i32 1, i32 1}\n";
let args = [buffer(0, 0, "read_write", 1, "float", "o")];
format!("{body}{}", kernel_list_with("__entry_wg", &args, ", !51"))
}
/// `__kernel void cmul(__global float *o, __constant float *c)`: `o[i] *= c[i & 3]`.
fn cmul() -> String {
let body = "define void @__entry_cmul(ptr addrspace(1) %0, ptr addrspace(2) %1) #0 {\n\
entry:\n\
tail call fastcc void @cmul(ptr addrspace(1) %0, ptr addrspace(2) %1)\n\
ret void\n}\n\
define internal fastcc void @cmul(ptr addrspace(1) %o, ptr addrspace(2) %c) #1 {\n\
entry:\n\
%i = tail call fastcc i64 @_Z13get_global_idj(i32 0)\n\
%po = getelementptr inbounds float, ptr addrspace(1) %o, i64 %i\n\
%vo = load float, ptr addrspace(1) %po, align 4\n\
%k = and i64 %i, 3\n\
%pc = getelementptr inbounds float, ptr addrspace(2) %c, i64 %k\n\
%vc = load float, ptr addrspace(2) %pc, align 4\n\
%m = fmul float %vo, %vc\n\
store float %m, ptr addrspace(1) %po, align 4\n\
ret void\n}\n";
let args = [
buffer(0, 0, "read_write", 1, "float", "o"),
buffer(1, 1, "read", 2, "float", "c"),
];
format!("{body}{}", kernel_list("__entry_cmul", &args))
}
/// `__kernel void items(__global uint *o, uint d)`: thread `i` (its linear index in the grid) stores eight words at `o[8i]`: `get_global_id(0)`,
/// `get_global_id(1)`, the local ids and group ids of dimensions 0 and 1 a byte each, the group
/// counts and local sizes so, the global sizes and `get_work_dim()` so, the sum of
/// `get_global_id`, `get_local_size`, `get_num_groups` and `get_global_offset` of `d`,
/// `get_global_id(3) + get_local_size(4) + get_global_size(5)`, and 7.
fn items() -> String {
let body = "define void @__entry_items(ptr addrspace(1) %0, ptr addrspace(2) %1) #0 {\n\
entry:\n\
%2 = load i32, ptr addrspace(2) %1, align 4\n\
tail call fastcc void @items(ptr addrspace(1) %0, i32 %2)\n\
ret void\n}\n\
define internal fastcc void @items(ptr addrspace(1) %o, i32 %d) #1 {\n\
entry:\n\
%g1 = tail call fastcc i64 @_Z13get_global_idj(i32 1)\n\
%f1 = tail call fastcc i64 @_Z17get_global_offsetj(i32 1)\n\
%y = sub i64 %g1, %f1\n\
%gs0 = tail call fastcc i64 @_Z15get_global_sizej(i32 0)\n\
%row = mul i64 %y, %gs0\n\
%g0 = tail call fastcc i64 @_Z13get_global_idj(i32 0)\n\
%f0 = tail call fastcc i64 @_Z17get_global_offsetj(i32 0)\n\
%x = sub i64 %g0, %f0\n\
%i = add i64 %row, %x\n\
%base = shl i64 %i, 3\n\
%w0 = trunc i64 %g0 to i32\n\
%p0 = getelementptr inbounds i32, ptr addrspace(1) %o, i64 %base\n\
store i32 %w0, ptr addrspace(1) %p0, align 4\n\
%w1 = trunc i64 %g1 to i32\n\
%a1 = or i64 %base, 1\n\
%p1 = getelementptr inbounds i32, ptr addrspace(1) %o, i64 %a1\n\
store i32 %w1, ptr addrspace(1) %p1, align 4\n\
%l0 = tail call fastcc i64 @_Z12get_local_idj(i32 0)\n\
%l1 = tail call fastcc i64 @_Z12get_local_idj(i32 1)\n\
%l1s = shl i64 %l1, 8\n\
%q0 = or i64 %l1s, %l0\n\
%r0 = tail call fastcc i64 @_Z12get_group_idj(i32 0)\n\
%r0s = shl i64 %r0, 16\n\
%q1 = or i64 %q0, %r0s\n\
%r1 = tail call fastcc i64 @_Z12get_group_idj(i32 1)\n\
%r1s = shl i64 %r1, 24\n\
%q2 = or i64 %q1, %r1s\n\
%w2 = trunc i64 %q2 to i32\n\
%a2 = or i64 %base, 2\n\
%p2 = getelementptr inbounds i32, ptr addrspace(1) %o, i64 %a2\n\
store i32 %w2, ptr addrspace(1) %p2, align 4\n\
%n0 = tail call fastcc i64 @_Z14get_num_groupsj(i32 0)\n\
%n1 = tail call fastcc i64 @_Z14get_num_groupsj(i32 1)\n\
%n1s = shl i64 %n1, 8\n\
%u0 = or i64 %n1s, %n0\n\
%z0 = tail call fastcc i64 @_Z14get_local_sizej(i32 0)\n\
%z0s = shl i64 %z0, 16\n\
%u1 = or i64 %u0, %z0s\n\
%z1 = tail call fastcc i64 @_Z14get_local_sizej(i32 1)\n\
%z1s = shl i64 %z1, 24\n\
%u2 = or i64 %u1, %z1s\n\
%w3 = trunc i64 %u2 to i32\n\
%a3 = or i64 %base, 3\n\
%p3 = getelementptr inbounds i32, ptr addrspace(1) %o, i64 %a3\n\
store i32 %w3, ptr addrspace(1) %p3, align 4\n\
%gs1 = tail call fastcc i64 @_Z15get_global_sizej(i32 1)\n\
%gs1s = shl i64 %gs1, 8\n\
%v0 = or i64 %gs1s, %gs0\n\
%wd = tail call fastcc i32 @_Z12get_work_dimv()\n\
%wds = shl i32 %wd, 16\n\
%v0t = trunc i64 %v0 to i32\n\
%w4 = or i32 %wds, %v0t\n\
%a4 = or i64 %base, 4\n\
%p4 = getelementptr inbounds i32, ptr addrspace(1) %o, i64 %a4\n\
store i32 %w4, ptr addrspace(1) %p4, align 4\n\
%dg = tail call fastcc i64 @_Z13get_global_idj(i32 %d)\n\
%dl = tail call fastcc i64 @_Z14get_local_sizej(i32 %d)\n\
%s0 = add i64 %dl, %dg\n\
%dn = tail call fastcc i64 @_Z14get_num_groupsj(i32 %d)\n\
%s1 = add i64 %s0, %dn\n\
%df = tail call fastcc i64 @_Z17get_global_offsetj(i32 %d)\n\
%s2 = add i64 %s1, %df\n\
%w5 = trunc i64 %s2 to i32\n\
%a5 = or i64 %base, 5\n\
%p5 = getelementptr inbounds i32, ptr addrspace(1) %o, i64 %a5\n\
store i32 %w5, ptr addrspace(1) %p5, align 4\n\
%e0 = tail call fastcc i64 @_Z13get_global_idj(i32 3)\n\
%e1 = tail call fastcc i64 @_Z14get_local_sizej(i32 4)\n\
%t0 = add i64 %e1, %e0\n\
%e2 = tail call fastcc i64 @_Z15get_global_sizej(i32 5)\n\
%t1 = add i64 %t0, %e2\n\
%w6 = trunc i64 %t1 to i32\n\
%a6 = or i64 %base, 6\n\
%p6 = getelementptr inbounds i32, ptr addrspace(1) %o, i64 %a6\n\
store i32 %w6, ptr addrspace(1) %p6, align 4\n\
tail call fastcc void @_Z7barrierj(i32 2)\n\
%a7 = or i64 %base, 7\n\
%p7 = getelementptr inbounds i32, ptr addrspace(1) %o, i64 %a7\n\
store i32 7, ptr addrspace(1) %p7, align 4\n\
ret void\n}\n";
let args = [
buffer(0, 0, "read_write", 1, "uint", "o"),
constant(1, 1, 4, "uint", "d", None),
];
format!("{body}{}", kernel_list("__entry_items", &args))
}
/// The library of the module `text` (after [`HEAD`]), or None where `llvm-as` is missing.
pub(super) fn library(text: &str) -> Option<Library> {
match llvm_assemble_text(&format!("{HEAD}{text}")) {
Ok(air) => Some(Library::from_air(&air).expect("the library")),
Err(AssembleError::Missing(why)) => {
eprintln!("SKIPPED: {why}");
None
}
Err(error) => panic!("the module: {error:?}"),
}
}
/// The state of `entry` of `library`, of OpenCL mode, each sampler it numbers (a read's or a
/// write's) taking nothing at its index.
pub(super) fn state(device: &Device, library: &Library, entry: &str) -> ComputePipelineState {
let function = library.function(entry).expect("the kernel");
let mut descriptor =
ComputePipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new(function)));
descriptor.open_cl_mode_enabled = true;
(device.new_compute_pipeline_state(&descriptor, crate::tests::no_constexpr_samplers))
.unwrap_or_else(|error| panic!("{entry}: {error}"))
}
/// A Shared buffer of `bytes`.
pub(super) fn bytes_buffer(device: &Device, bytes: &[u8]) -> Buffer {
let len = bytes.len() as u64;
let block = (device.take_block(MemoryClass::Shared, len)).expect("a Shared block");
let buffer = (device.new_buffer(block.id, 0, len, None)).expect("a buffer");
let contents = buffer.contents().expect("a Shared buffer");
// SAFETY: the buffer holds `len` bytes, and no command uses it yet.
unsafe {
bytes
.as_ptr()
.copy_to_nonoverlapping(contents.as_ptr(), bytes.len())
};
buffer
}
/// A Shared buffer of `words`.
pub(super) fn words_buffer(device: &Device, words: &[u32]) -> Buffer {
let bytes: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
bytes_buffer(device, &bytes)
}
/// A Shared buffer of `floats`.
pub(super) fn floats_buffer(device: &Device, floats: &[f32]) -> Buffer {
words_buffer(
device,
&floats.iter().map(|f| f.to_bits()).collect::<Vec<_>>(),
)
}
/// The bytes of `buffer`, which no command uses now.
pub(super) fn bytes(buffer: &Buffer) -> Vec<u8> {
let contents = buffer.contents().expect("a Shared buffer");
// SAFETY: the buffer's bytes, which no command uses now.
unsafe { std::slice::from_raw_parts(contents.as_ptr(), buffer.length() as usize) }.to_vec()
}
/// The words of `buffer`, which no command uses now.
pub(super) fn words(buffer: &Buffer) -> Vec<u32> {
bytes(buffer)
.as_chunks::<4>()
.0
.iter()
.map(|w| u32::from_le_bytes(*w))
.collect()
}
/// The floats of `buffer`, which no command uses now.
pub(super) fn floats(buffer: &Buffer) -> Vec<f32> {
words(buffer).into_iter().map(f32::from_bits).collect()
}
/// One of a kernel's own arguments, as bound.
#[derive(Clone, Copy)]
pub(super) enum Arg<'a> {
/// A buffer from a byte offset (`setBuffer:offset:atIndex:`).
Buffer(&'a Buffer, u64),
/// Bytes (`setBytes:length:atIndex:`).
Bytes(&'a [u8]),
}
/// `buffer` from its start.
pub(super) fn whole(buffer: &Buffer) -> Arg<'_> {
Arg::Buffer(buffer, 0)
}
/// `state` dispatched on `device` (named `name`) over `grid` threads in threadgroups of `group`,
/// the first hidden buffer's bytes at index 0 the global offset `offset` and the dimension count
/// `dims`, buffers 1 and 2 bound as the dispatcher binds them, `args` at 3 and up; committed and
/// finished without an error.
pub(super) fn run(
name: &str,
device: &Device,
state: &ComputePipelineState,
(grid, group): ([u32; 3], [u32; 3]),
(offset, dims): ([u32; 3], u32),
args: &[Arg<'_>],
) {
let first: Vec<u8> = [offset[0], offset[1], offset[2], dims]
.iter()
.flat_map(|w| w.to_le_bytes())
.collect();
let hidden = [
words_buffer(device, &[0; 16]),
words_buffer(device, &[0; 16]),
];
let queue = device.new_command_queue(1).expect("a queue");
let command_buffer = queue.command_buffer().expect("a command buffer");
let mut encoder =
(command_buffer.compute_command_encoder(DispatchType::Serial)).expect("an encoder");
encoder
.set_compute_pipeline_state(state)
.expect("the state");
encoder
.set_bytes(&first, 0)
.expect("the first hidden buffer");
for (index, b) in (1u32..).zip(&hidden) {
(encoder.set_buffer(Some(b), 0, index)).expect("a hidden buffer");
}
for (index, arg) in (3u32..).zip(args) {
match *arg {
Arg::Buffer(b, offset) => encoder.set_buffer(Some(b), offset, index),
Arg::Bytes(bytes) => encoder.set_bytes(bytes, index),
}
.unwrap_or_else(|error| panic!("{name}: argument {index}: {error}"));
}
(encoder.dispatch_threads(grid, group))
.unwrap_or_else(|error| panic!("{name}: the dispatch: {error}"));
encoder.end_encoding();
command_buffer.commit().expect("a commit");
finished(name, &command_buffer);
assert_eq!(command_buffer.error(), None, "{name}");
}
/// One dimension's grid.
pub(super) fn line(threads: u32, group: u32) -> ([u32; 3], [u32; 3]) {
([threads, 1, 1], [group, 1, 1])
}
#[test]
fn opencl_mode_kernels_compute_what_metal_computes() {
let (Some(add), Some(cmul), Some(scale), Some(st), Some(wg)) = (
library(&add()),
library(&cmul()),
library(&scale()),
library(&st()),
library(&wg()),
) else {
return;
};
each_device("opencl-mode", |name, _, device| {
let one = ([0; 3], 1);
const N: usize = 1024;
let a = floats_buffer(&device, &(0..N).map(|i| i as f32).collect::<Vec<_>>());
let b = floats_buffer(
&device,
&(0..N).map(|i| (2 * i + 1) as f32).collect::<Vec<_>>(),
);
let c = floats_buffer(&device, &[0.0; N]);
let add_state = state(&device, &add, "__entry_add");
run(
name,
&device,
&add_state,
line(N as u32, 64),
one,
&[whole(&a), whole(&b), whole(&c)],
);
let sums: Vec<f32> = (0..N).map(|i| (3 * i + 1) as f32).collect();
assert_eq!(floats(&c), sums, "{name}: add");
let o = floats_buffer(
&device,
&(0..64).map(|i| (i + 1) as f32).collect::<Vec<_>>(),
);
let k = floats_buffer(&device, &[1.0, 2.0, 3.0, 4.0]);
let cmul_state = state(&device, &cmul, "__entry_cmul");
run(
name,
&device,
&cmul_state,
line(64, 32),
one,
&[whole(&o), whole(&k)],
);
let products: Vec<f32> = (0..64).map(|i| ((i + 1) * (i % 4 + 1)) as f32).collect();
assert_eq!(floats(&o), products, "{name}: cmul");
assert_eq!(floats(&o)[..6], [1.0, 4.0, 9.0, 16.0, 5.0, 12.0], "{name}");
let ramp: Vec<f32> = (0..128).map(|i| i as f32).collect();
let scaled = |k: f32, n: usize| -> Vec<f32> {
(0..128)
.map(|i| if i < n { i as f32 * k } else { i as f32 })
.collect()
};
let scale_state = state(&device, &scale, "__entry_scale");
let b = floats_buffer(&device, &ramp);
run(
name,
&device,
&scale_state,
line(128, 32),
one,
&[
whole(&b),
Arg::Bytes(&2.5f32.to_le_bytes()),
Arg::Bytes(&100u32.to_le_bytes()),
],
);
let got = floats(&b);
assert_eq!(got, scaled(2.5, 100), "{name}: scale, by bytes");
assert_eq!(
[got[1], got[99], got[100], got[127]],
[2.5, 247.5, 100.0, 127.0],
"{name}"
);
let b = floats_buffer(&device, &ramp);
let mut values = [0u32; 16];
values[4] = 3.0f32.to_bits();
values[8] = 50;
let values = words_buffer(&device, &values);
run(
name,
&device,
&scale_state,
line(128, 32),
one,
&[
whole(&b),
Arg::Buffer(&values, 16),
Arg::Buffer(&values, 32),
],
);
let got = floats(&b);
assert_eq!(got, scaled(3.0, 50), "{name}: scale, by buffers at offsets");
assert_eq!([got[1], got[49], got[50]], [3.0, 147.0, 50.0], "{name}");
let st_state = state(&device, &st, "__entry_st");
let o = floats_buffer(&device, &[0.0; 16]);
let s: Vec<u8> = [2.5f32.to_bits(), 4]
.iter()
.flat_map(|w| w.to_le_bytes())
.collect();
run(
name,
&device,
&st_state,
line(16, 16),
one,
&[whole(&o), Arg::Bytes(&s)],
);
assert_eq!(floats(&o), [6.5; 16], "{name}: st");
let wg_state = state(&device, &wg, "__entry_wg");
assert_eq!(wg_state.max_total_threads_per_threadgroup(), 64, "{name}");
for group in [64u32, 32] {
let o = floats_buffer(&device, &[0.0; 128]);
run(
name,
&device,
&wg_state,
line(128, group),
one,
&[whole(&o)],
);
assert_eq!(
floats(&o),
[group as f32; 128],
"{name}: wg in groups of {group}"
);
}
println!("{name}: add, cmul, scale, st and wg answer the M3 Max's values");
});
}
/// The eight words thread `(x, y)` of [`items`] stores over the 8-by-4 grid in groups of 4 by 2 at
/// offset (3, 5), of two dimensions, reading dimension `d` (`dims`, `local`, `groups` and
/// `offset` OpenCL's 1, 1, 1 and 0 past dimension 1).
fn items_words(x: u32, y: u32, d: u32) -> [u32; 8] {
let (offset, global, local) = ([3, 5], [8, 4], [4, 2]);
let id = [x + offset[0], y + offset[1]];
let lid = [x % local[0], y % local[1]];
let group = [x / local[0], y / local[1]];
let groups = [global[0] / local[0], global[1] / local[1]];
let of = |v: [u32; 2], past: u32| v.get(d as usize).copied().unwrap_or(past);
[
id[0],
id[1],
lid[0] | lid[1] << 8 | group[0] << 16 | group[1] << 24,
groups[0] | groups[1] << 8 | local[0] << 16 | local[1] << 24,
global[0] | global[1] << 8 | 2 << 16,
of(id, 0) + of(local, 1) + of(groups, 1) + of(offset, 0),
2,
7,
]
}
#[test]
fn opencl_mode_work_item_functions_read_the_dispatch() {
let Some(items) = library(&items()) else {
return;
};
each_device("opencl-mode-items", |name, _, device| {
let items_state = state(&device, &items, "__entry_items");
// Dimension 1, as the M3 Max ran it, and dimension 5, past the grid's.
for d in [1u32, 5] {
let o = words_buffer(&device, &[0xEEEE_EEEE; 32 * 8]);
run(
name,
&device,
&items_state,
([8, 4, 1], [4, 2, 1]),
([3, 5, 0], 2),
&[whole(&o), Arg::Bytes(&d.to_le_bytes())],
);
let got = words(&o);
let want: Vec<u32> = (0..4)
.flat_map(|y| (0..8).flat_map(move |x| items_words(x, y, d)))
.collect();
assert_eq!(got, want, "{name}: dimension {d}");
if d == 1 {
// The M3 Max's first thread, word 6 OpenCL's 2 where it leaves the word unwritten.
assert_eq!(
got[..8],
[3, 5, 0, 0x0204_0202, 0x0002_0408, 0xe, 2, 7],
"{name}: the first thread"
);
}
}
println!("{name}: every work-item function answers the M3 Max's words");
});
}
/// One conversion in OpenCL mode: its name after `air.convert.`, its destination's and source's
/// LLVM types, and operands each with the word both oracles answered (every operand of the probe
/// they answered alike and OpenCL defines, at most ten, those where the suffix changes the answer
/// first).
type Conversion = (
&'static str,
&'static str,
&'static str,
&'static [(u64, u64)],
);
#[rustfmt::skip]
const CONVERSIONS: [Conversion; 57] = [
("f.f32.s.i32.rtz", "float", "i32", &[(0x0, 0x0), (0x1000003, 0x4b800001), (0x1ffffff, 0x4bffffff), (0x2000003, 0x4c000000), (0xfefffffd, 0xcb800001), (0xfe000001, 0xcbffffff), (0x7fffffff, 0x4effffff), (0x80000001, 0xceffffff), (0x7fffffc0, 0x4effffff), (0x75bcd15, 0x4ceb79a2)]),
("f.f32.s.i64.rtz", "float", "i64", &[(0x0, 0x0), (0x7fffffffffffffff, 0x5effffff), (0x8000000000000001, 0xdeffffff), (0x7fffffc000000000, 0x5effffff), (0x10000010001, 0x53800000), (0x20000020000001, 0x5a000000), (0xffdfffffdfffffff, 0xda000000), (0xffffffff, 0x4f7fffff), (0x80000000ffffffff, 0xdeffffff), (0xffffffffffffff, 0x5b7fffff)]),
("f.f32.s.i32.rtp", "float", "i32", &[(0x0, 0x0), (0x1, 0x3f800000), (0xffffffff, 0xbf800000), (0x1000000, 0x4b800000), (0x1000001, 0x4b800001), (0x2000001, 0x4c000001), (0xfefffffd, 0xcb800001), (0xfe000001, 0xcbffffff), (0x80000001, 0xceffffff), (0x7fffffbf, 0x4f000000)]),
("f.f32.s.i64.rtp", "float", "i64", &[(0x0, 0x0), (0x1, 0x3f800000), (0xffffffffffffffff, 0xbf800000), (0x1000001, 0x4b800001), (0x20000000000001, 0x5a000001), (0x8000000000000001, 0xdeffffff), (0x4000000000000001, 0x5e800001), (0xffdfffffdfffffff, 0xda000000), (0x100000001, 0x4f800001), (0x80000000ffffffff, 0xdeffffff)]),
("f.f32.s.i32.rtn", "float", "i32", &[(0x0, 0x0), (0x1, 0x3f800000), (0xffffffff, 0xbf800000), (0x1000003, 0x4b800001), (0x1ffffff, 0x4bffffff), (0x2000003, 0x4c000000), (0xfeffffff, 0xcb800001), (0x7fffffff, 0x4effffff), (0x7fffffc0, 0x4effffff), (0x75bcd15, 0x4ceb79a2)]),
("f.f32.s.i64.rtn", "float", "i64", &[(0x0, 0x0), (0x1, 0x3f800000), (0x7fffffffffffffff, 0x5effffff), (0x7fffffc000000000, 0x5effffff), (0x10000010001, 0x53800000), (0x20000020000001, 0x5a000000), (0xffffffff, 0x4f7fffff), (0xfffffffeffffffff, 0xcf800001), (0xffffffff7fffffff, 0xcf000001), (0xffffffffffffff, 0x5b7fffff)]),
("f.f32.u.i32.rtz", "float", "i32", &[(0xffffffff, 0x4f7fffff), (0x1000003, 0x4b800001), (0x1ffffff, 0x4bffffff), (0x2000003, 0x4c000000), (0xfeffffff, 0x4f7effff), (0xfefffffd, 0x4f7effff), (0x7fffffff, 0x4effffff), (0x7fffffc0, 0x4effffff), (0xffffff80, 0x4f7fffff), (0xffffffc0, 0x4f7fffff)]),
("f.f32.u.i64.rtz", "float", "i64", &[(0xffffffffffffffff, 0x5f7fffff), (0x7fffffffffffffff, 0x5effffff), (0x7fffffc000000000, 0x5effffff), (0xffffff8000000000, 0x5f7fffff), (0xffffffffffffff00, 0x5f7fffff), (0x10000010001, 0x53800000), (0x20000020000001, 0x5a000000), (0xffdfffffdfffffff, 0x5f7fdfff), (0xffffffff, 0x4f7fffff), (0xfffffffeffffffff, 0x5f7fffff)]),
("f.f32.u.i32.rtp", "float", "i32", &[(0x0, 0x0), (0x1, 0x3f800000), (0xffffffff, 0x4f800000), (0x1000001, 0x4b800001), (0x2000001, 0x4c000001), (0xfe000001, 0x4f7e0001), (0x80000001, 0x4f000001), (0x7fffffbf, 0x4f000000), (0xffffff7f, 0x4f800000), (0xffffff7f, 0x4f800000)]),
("f.f32.u.i64.rtp", "float", "i64", &[(0x0, 0x0), (0x1, 0x3f800000), (0xffffffffffffffff, 0x5f800000), (0x1000001, 0x4b800001), (0x20000000000001, 0x5a000001), (0x7fffffffffffffff, 0x5f000000), (0x8000000000000001, 0x5f000001), (0x4000000000000001, 0x5e800001), (0x100000001, 0x4f800001), (0x80000000ffffffff, 0x5f000001)]),
("f.f32.u.i32.rtn", "float", "i32", &[(0xffffffff, 0x4f7fffff), (0x1000003, 0x4b800001), (0x1ffffff, 0x4bffffff), (0x2000003, 0x4c000000), (0xfeffffff, 0x4f7effff), (0xfefffffd, 0x4f7effff), (0x7fffffff, 0x4effffff), (0x7fffffc0, 0x4effffff), (0xffffff80, 0x4f7fffff), (0xffffffc0, 0x4f7fffff)]),
("f.f32.u.i64.rtn", "float", "i64", &[(0xffffffffffffffff, 0x5f7fffff), (0x7fffffffffffffff, 0x5effffff), (0x7fffffc000000000, 0x5effffff), (0xffffff8000000000, 0x5f7fffff), (0xffffffffffffff00, 0x5f7fffff), (0x10000010001, 0x53800000), (0x20000020000001, 0x5a000000), (0xffdfffffdfffffff, 0x5f7fdfff), (0xffffffff, 0x4f7fffff), (0xfffffffeffffffff, 0x5f7fffff)]),
("s.i32.f.f32.rte", "i32", "float", &[(0x3fc00000, 0x2), (0xbfc00000, 0xfffffffe), (0x46ffff33, 0x8000), (0xc7000099, 0xffff7fff), (0x437f8000, 0x100), (0x42ff0000, 0x80), (0xbf400000, 0xffffffff), (0x477fff80, 0x10000), (0x406ccccd, 0x4), (0x3f400000, 0x1)]),
("s.i32.f.f32.rte.sat", "i32", "float", &[(0x3fc00000, 0x2), (0xbfc00000, 0xfffffffe), (0x46ffff33, 0x8000), (0xc7000099, 0xffff7fff), (0x437f8000, 0x100), (0x42ff0000, 0x80), (0xbf400000, 0xffffffff), (0x477fff80, 0x10000), (0x406ccccd, 0x4), (0x3f400000, 0x1)]),
("u.i32.f.f32.rte.sat", "i32", "float", &[(0x3f000000, 0x0), (0x3fc00000, 0x2), (0x40200000, 0x2), (0xbf000000, 0x0), (0x46ffff33, 0x8000), (0x437f8000, 0x100), (0x42ff0000, 0x80), (0x477fff80, 0x10000), (0x406ccccd, 0x4), (0x3f400000, 0x1)]),
("s.i8.f.f32.rte.sat", "i8", "float", &[(0x3f000000, 0x0), (0x3fc00000, 0x2), (0x40200000, 0x2), (0xbf000000, 0x0), (0xbfc00000, 0xfe), (0xc0200000, 0xfe), (0xbf400000, 0xff), (0x406ccccd, 0x4), (0x3f400000, 0x1), (0xc0600000, 0xfc)]),
("u.i8.f.f32.rte.sat", "i8", "float", &[(0x3f000000, 0x0), (0x3fc00000, 0x2), (0x40200000, 0x2), (0xbf000000, 0x0), (0xbfc00000, 0x0), (0xc0200000, 0x0), (0x3effffff, 0x0), (0xbeffffff, 0x0), (0x406ccccd, 0x4), (0x3f400000, 0x1)]),
("s.i16.f.f32.rte.sat", "i16", "float", &[(0x3f000000, 0x0), (0x3fc00000, 0x2), (0x40200000, 0x2), (0xbfc00000, 0xfffe), (0x437f8000, 0x100), (0x42ff0000, 0x80), (0xbf400000, 0xffff), (0x406ccccd, 0x4), (0x3f400000, 0x1), (0xc0600000, 0xfffc)]),
("u.i16.f.f32.rte.sat", "i16", "float", &[(0x3f000000, 0x0), (0x3fc00000, 0x2), (0x40200000, 0x2), (0xbf000000, 0x0), (0xbfc00000, 0x0), (0x46ffff33, 0x8000), (0x437f8000, 0x100), (0x42ff0000, 0x80), (0x406ccccd, 0x4), (0x3f400000, 0x1)]),
("s.i64.f.f32.rte.sat", "i64", "float", &[(0x3fc00000, 0x2), (0xbfc00000, 0xfffffffffffffffe), (0x46ffff33, 0x8000), (0xc7000099, 0xffffffffffff7fff), (0x437f8000, 0x100), (0x42ff0000, 0x80), (0xbf400000, 0xffffffffffffffff), (0x477fff80, 0x10000), (0x406ccccd, 0x4), (0x3f400000, 0x1)]),
("u.i64.f.f32.rte.sat", "i64", "float", &[(0x3f000000, 0x0), (0x3fc00000, 0x2), (0x40200000, 0x2), (0xbf000000, 0x0), (0x46ffff33, 0x8000), (0x437f8000, 0x100), (0x42ff0000, 0x80), (0x477fff80, 0x10000), (0x406ccccd, 0x4), (0x3f400000, 0x1)]),
("s.i32.f.f32.rtp", "i32", "float", &[(0x3f000000, 0x1), (0x3fc00000, 0x2), (0x40200000, 0x3), (0x3effffff, 0x1), (0x46ffff33, 0x8000), (0x46fffecd, 0x8000), (0x437f8000, 0x100), (0x437e8000, 0xff), (0x42ff0000, 0x80), (0x477fff80, 0x10000)]),
("s.i32.f.f32.rtp.sat", "i32", "float", &[(0x3f000000, 0x1), (0x3fc00000, 0x2), (0x40200000, 0x3), (0x3effffff, 0x1), (0x46ffff33, 0x8000), (0x46fffecd, 0x8000), (0x437f8000, 0x100), (0x437e8000, 0xff), (0x42ff0000, 0x80), (0x477fff80, 0x10000)]),
("u.i32.f.f32.rtp.sat", "i32", "float", &[(0x3f000000, 0x1), (0x3fc00000, 0x2), (0x40200000, 0x3), (0x3effffff, 0x1), (0x46ffff33, 0x8000), (0x46fffecd, 0x8000), (0x437f8000, 0x100), (0x437e8000, 0xff), (0x42ff0000, 0x80), (0x477fff80, 0x10000)]),
("s.i8.f.f32.rtp.sat", "i8", "float", &[(0x3f000000, 0x1), (0x3fc00000, 0x2), (0x40200000, 0x3), (0xbf000000, 0x0), (0xbfc00000, 0xff), (0xc0200000, 0xfe), (0x3effffff, 0x1), (0xbeffffff, 0x0), (0x406ccccd, 0x4), (0x3f400000, 0x1)]),
("u.i8.f.f32.rtp.sat", "i8", "float", &[(0x3f000000, 0x1), (0x3fc00000, 0x2), (0x40200000, 0x3), (0xbf000000, 0x0), (0xbfc00000, 0x0), (0xc0200000, 0x0), (0x3effffff, 0x1), (0xbeffffff, 0x0), (0x406ccccd, 0x4), (0x3f400000, 0x1)]),
("s.i16.f.f32.rtp.sat", "i16", "float", &[(0x3f000000, 0x1), (0x3fc00000, 0x2), (0x40200000, 0x3), (0xbf000000, 0x0), (0x3effffff, 0x1), (0x437f8000, 0x100), (0x437e8000, 0xff), (0x42ff0000, 0x80), (0x406ccccd, 0x4), (0x3f400000, 0x1)]),
("u.i16.f.f32.rtp.sat", "i16", "float", &[(0x3f000000, 0x1), (0x3fc00000, 0x2), (0x40200000, 0x3), (0x3effffff, 0x1), (0x46ffff33, 0x8000), (0x46fffecd, 0x8000), (0x437f8000, 0x100), (0x437e8000, 0xff), (0x42ff0000, 0x80), (0x406ccccd, 0x4)]),
("s.i64.f.f32.rtp.sat", "i64", "float", &[(0x3f000000, 0x1), (0x3fc00000, 0x2), (0x40200000, 0x3), (0x3effffff, 0x1), (0x46ffff33, 0x8000), (0x46fffecd, 0x8000), (0x437f8000, 0x100), (0x437e8000, 0xff), (0x42ff0000, 0x80), (0x477fff80, 0x10000)]),
("u.i64.f.f32.rtp.sat", "i64", "float", &[(0x3f000000, 0x1), (0x3fc00000, 0x2), (0x40200000, 0x3), (0x3effffff, 0x1), (0x46ffff33, 0x8000), (0x46fffecd, 0x8000), (0x437f8000, 0x100), (0x437e8000, 0xff), (0x42ff0000, 0x80), (0x477fff80, 0x10000)]),
("s.i32.f.f32.rtn", "i32", "float", &[(0x3f000000, 0x0), (0x3fc00000, 0x1), (0xbf000000, 0xffffffff), (0xbfc00000, 0xfffffffe), (0xc0200000, 0xfffffffd), (0xbeffffff, 0xffffffff), (0xc7000099, 0xffff7fff), (0xc3008000, 0xffffff7f), (0xbf400000, 0xffffffff), (0xc0600000, 0xfffffffc)]),
("s.i32.f.f32.rtn.sat", "i32", "float", &[(0x3f000000, 0x0), (0x3fc00000, 0x1), (0xbf000000, 0xffffffff), (0xbfc00000, 0xfffffffe), (0xc0200000, 0xfffffffd), (0xbeffffff, 0xffffffff), (0xc7000099, 0xffff7fff), (0xc3008000, 0xffffff7f), (0xbf400000, 0xffffffff), (0xc0600000, 0xfffffffc)]),
("u.i32.f.f32.rtn.sat", "i32", "float", &[(0x3f000000, 0x0), (0x3fc00000, 0x1), (0x40200000, 0x2), (0xbf000000, 0x0), (0xbfc00000, 0x0), (0xc0200000, 0x0), (0x3effffff, 0x0), (0xbeffffff, 0x0), (0x3f800000, 0x1), (0xbf800000, 0x0)]),
("s.i8.f.f32.rtn.sat", "i8", "float", &[(0x3f000000, 0x0), (0x3fc00000, 0x1), (0x40200000, 0x2), (0xbf000000, 0xff), (0xbfc00000, 0xfe), (0xc0200000, 0xfd), (0x3effffff, 0x0), (0xbeffffff, 0xff), (0xbf400000, 0xff), (0xc0600000, 0xfc)]),
("u.i8.f.f32.rtn.sat", "i8", "float", &[(0x3f000000, 0x0), (0x3fc00000, 0x1), (0x40200000, 0x2), (0xbf000000, 0x0), (0xbfc00000, 0x0), (0xc0200000, 0x0), (0x3effffff, 0x0), (0xbeffffff, 0x0), (0x3f800000, 0x1), (0xbf800000, 0x0)]),
("s.i16.f.f32.rtn.sat", "i16", "float", &[(0x3f000000, 0x0), (0x3fc00000, 0x1), (0x40200000, 0x2), (0xbf000000, 0xffff), (0xbfc00000, 0xfffe), (0xc0200000, 0xfffd), (0xbeffffff, 0xffff), (0xc3008000, 0xff7f), (0xbf400000, 0xffff), (0xc0600000, 0xfffc)]),
("u.i16.f.f32.rtn.sat", "i16", "float", &[(0x3f000000, 0x0), (0x3fc00000, 0x1), (0x40200000, 0x2), (0xbf000000, 0x0), (0xbfc00000, 0x0), (0xc0200000, 0x0), (0x3effffff, 0x0), (0xbeffffff, 0x0), (0x3f800000, 0x1), (0xbf800000, 0x0)]),
("s.i64.f.f32.rtn.sat", "i64", "float", &[(0x3f000000, 0x0), (0x3fc00000, 0x1), (0xbf000000, 0xffffffffffffffff), (0xbfc00000, 0xfffffffffffffffe), (0xc0200000, 0xfffffffffffffffd), (0xbeffffff, 0xffffffffffffffff), (0xc7000099, 0xffffffffffff7fff), (0xc3008000, 0xffffffffffffff7f), (0xbf400000, 0xffffffffffffffff), (0xc0600000, 0xfffffffffffffffc)]),
("u.i64.f.f32.rtn.sat", "i64", "float", &[(0x3f000000, 0x0), (0x3fc00000, 0x1), (0x40200000, 0x2), (0xbf000000, 0x0), (0xbfc00000, 0x0), (0xc0200000, 0x0), (0x3effffff, 0x0), (0xbeffffff, 0x0), (0x3f800000, 0x1), (0xbf800000, 0x0)]),
("u.i8.s.i32.rtz.sat", "i8", "i32", &[(0xffffffff, 0x0), (0x1000000, 0xff), (0x1000001, 0xff), (0x1000002, 0xff), (0x1000003, 0xff), (0x2000001, 0xff), (0x2000003, 0xff), (0xfeffffff, 0x0), (0xfefffffd, 0x0), (0xfe000001, 0x0)]),
("s.i8.s.i32.rtz.sat", "i8", "i32", &[(0x1000000, 0x7f), (0x1000001, 0x7f), (0x1000002, 0x7f), (0x1000003, 0x7f), (0x1ffffff, 0x7f), (0x2000001, 0x7f), (0x2000003, 0x7f), (0xfeffffff, 0x80), (0xfefffffd, 0x80), (0xfe000001, 0x80)]),
("u.i8.u.i32.rtz.sat", "i8", "i32", &[(0x1000000, 0xff), (0x1000001, 0xff), (0x1000002, 0xff), (0x1000003, 0xff), (0x2000001, 0xff), (0x2000003, 0xff), (0xfefffffd, 0xff), (0xfe000001, 0xff), (0x80000000, 0xff), (0x80000001, 0xff)]),
("s.i8.u.i32.rtz.sat", "i8", "i32", &[(0xffffffff, 0x7f), (0x1000000, 0x7f), (0x1000001, 0x7f), (0x1000002, 0x7f), (0x1000003, 0x7f), (0x1ffffff, 0x7f), (0x2000001, 0x7f), (0x2000003, 0x7f), (0xfeffffff, 0x7f), (0xfefffffd, 0x7f)]),
("u.i16.s.i32.rtz.sat", "i16", "i32", &[(0xffffffff, 0x0), (0x1000000, 0xffff), (0x1000001, 0xffff), (0x1000002, 0xffff), (0x1000003, 0xffff), (0x2000001, 0xffff), (0x2000003, 0xffff), (0xfeffffff, 0x0), (0xfefffffd, 0x0), (0xfe000001, 0x0)]),
("s.i16.s.i32.rtz.sat", "i16", "i32", &[(0x1000000, 0x7fff), (0x1000001, 0x7fff), (0x1000002, 0x7fff), (0x1000003, 0x7fff), (0x1ffffff, 0x7fff), (0x2000001, 0x7fff), (0x2000003, 0x7fff), (0xfeffffff, 0x8000), (0xfefffffd, 0x8000), (0xfe000001, 0x8000)]),
("u.i16.u.i32.rtz.sat", "i16", "i32", &[(0x1000000, 0xffff), (0x1000001, 0xffff), (0x1000002, 0xffff), (0x1000003, 0xffff), (0x2000001, 0xffff), (0x2000003, 0xffff), (0xfefffffd, 0xffff), (0xfe000001, 0xffff), (0x80000000, 0xffff), (0x80000001, 0xffff)]),
("s.i16.u.i32.rtz.sat", "i16", "i32", &[(0xffffffff, 0x7fff), (0x1000000, 0x7fff), (0x1000001, 0x7fff), (0x1000002, 0x7fff), (0x1000003, 0x7fff), (0x1ffffff, 0x7fff), (0x2000001, 0x7fff), (0x2000003, 0x7fff), (0xfeffffff, 0x7fff), (0xfefffffd, 0x7fff)]),
("u.i32.s.i32.rtz.sat", "i32", "i32", &[(0xffffffff, 0x0), (0xfeffffff, 0x0), (0xfefffffd, 0x0), (0xfe000001, 0x0), (0x80000000, 0x0), (0x80000001, 0x0), (0xffffff7f, 0x0), (0xffffff80, 0x0), (0xffffffc0, 0x0), (0xfffffffe, 0x0)]),
("s.i32.u.i32.rtz.sat", "i32", "i32", &[(0xffffffff, 0x7fffffff), (0xfeffffff, 0x7fffffff), (0xfefffffd, 0x7fffffff), (0xfe000001, 0x7fffffff), (0x80000000, 0x7fffffff), (0x80000001, 0x7fffffff), (0xffffff7f, 0x7fffffff), (0xffffff80, 0x7fffffff), (0xffffffc0, 0x7fffffff), (0xfffffffe, 0x7fffffff)]),
("u.i8.s.i32.rte.sat", "i8", "i32", &[(0xffffffff, 0x0), (0x1000000, 0xff), (0x1000001, 0xff), (0x1000002, 0xff), (0x1000003, 0xff), (0x2000001, 0xff), (0x2000003, 0xff), (0xfeffffff, 0x0), (0xfefffffd, 0x0), (0xfe000001, 0x0)]),
("u.i64.s.i32.rtz.sat", "i64", "i32", &[(0xffffffff, 0x0), (0xfeffffff, 0x0), (0xfefffffd, 0x0), (0xfe000001, 0x0), (0x80000000, 0x0), (0x80000001, 0x0), (0xffffff7f, 0x0), (0xffffff80, 0x0), (0xffffffc0, 0x0), (0xfffffffe, 0x0)]),
("s.i32.s.i64.rtz.sat", "i32", "i64", &[(0x20000000000001, 0x7fffffff), (0x7fffffffffffffff, 0x7fffffff), (0x8000000000000000, 0x80000000), (0x8000000000000001, 0x80000000), (0x4000000000000001, 0x7fffffff), (0x7fffff8000000000, 0x7fffffff), (0x7fffffc000000000, 0x7fffffff), (0xffffff8000000000, 0x80000000), (0x10000010001, 0x7fffffff), (0x20000020000001, 0x7fffffff)]),
("u.i32.s.i64.rtz.sat", "i32", "i64", &[(0xffffffffffffffff, 0x0), (0x20000000000001, 0xffffffff), (0x8000000000000001, 0x0), (0x4000000000000001, 0xffffffff), (0x7fffff8000000000, 0xffffffff), (0x7fffffc000000000, 0xffffffff), (0xffffffffffffff00, 0x0), (0x10000010001, 0xffffffff), (0x20000020000001, 0xffffffff), (0xffdfffffdfffffff, 0x0)]),
("s.i32.u.i64.rtz.sat", "i32", "i64", &[(0xffffffffffffffff, 0x7fffffff), (0x20000000000001, 0x7fffffff), (0x7fffffffffffffff, 0x7fffffff), (0x8000000000000000, 0x7fffffff), (0x8000000000000001, 0x7fffffff), (0x4000000000000001, 0x7fffffff), (0x7fffff8000000000, 0x7fffffff), (0x7fffffc000000000, 0x7fffffff), (0xffffff8000000000, 0x7fffffff), (0xffffffffffffff00, 0x7fffffff)]),
("u.i32.u.i64.rtz.sat", "i32", "i64", &[(0x20000000000001, 0xffffffff), (0x8000000000000000, 0xffffffff), (0x8000000000000001, 0xffffffff), (0x4000000000000001, 0xffffffff), (0x7fffff8000000000, 0xffffffff), (0x7fffffc000000000, 0xffffffff), (0xffffff8000000000, 0xffffffff), (0xffffffffffffff00, 0xffffffff), (0x10000010001, 0xffffffff), (0x20000020000001, 0xffffffff)]),
("s.i64.u.i64.rtz.sat", "i64", "i64", &[(0x0, 0x0), (0xffffffffffffffff, 0x7fffffffffffffff), (0x8000000000000000, 0x7fffffffffffffff), (0x8000000000000001, 0x7fffffffffffffff), (0xffffff8000000000, 0x7fffffffffffffff), (0xffffffffffffff00, 0x7fffffffffffffff), (0xffdfffffdfffffff, 0x7fffffffffffffff), (0xfffffffeffffffff, 0x7fffffffffffffff), (0xffffffff7fffffff, 0x7fffffffffffffff), (0x80000000ffffffff, 0x7fffffffffffffff)]),
("u.i64.s.i64.rtz.sat", "i64", "i64", &[(0x0, 0x0), (0xffffffffffffffff, 0x0), (0x8000000000000000, 0x0), (0x8000000000000001, 0x0), (0xffffff8000000000, 0x0), (0xffffffffffffff00, 0x0), (0xffdfffffdfffffff, 0x0), (0xfffffffeffffffff, 0x0), (0xffffffff7fffffff, 0x0), (0x80000000ffffffff, 0x0)]),
];
/// The bytes of a value of LLVM type `ty`.
fn size_of(ty: &str) -> usize {
match ty {
"i8" => 1,
"i16" => 2,
"i64" => 8,
_ => 4,
}
}
/// `__kernel void cv(__global DST *o, __global const SRC *in)`: `o[i] = convert(in[i])` through
/// `name`.
fn conversion(dst: &str, src: &str, name: &str) -> String {
let (da, sa) = (size_of(dst), size_of(src));
let body = format!(
"define void @__entry_cv(ptr addrspace(1) %0, ptr addrspace(1) %1) #0 {{\n\
entry:\n\
tail call fastcc void @cv(ptr addrspace(1) %0, ptr addrspace(1) %1)\n\
ret void\n}}\n\
define internal fastcc void @cv(ptr addrspace(1) %o, ptr addrspace(1) %in) #1 {{\n\
entry:\n\
%i = tail call fastcc i64 @_Z13get_global_idj(i32 0)\n\
%p = getelementptr inbounds {src}, ptr addrspace(1) %in, i64 %i\n\
%x = load {src}, ptr addrspace(1) %p, align {sa}\n\
%r = tail call {dst} @{name}({src} %x) #3\n\
%q = getelementptr inbounds {dst}, ptr addrspace(1) %o, i64 %i\n\
store {dst} %r, ptr addrspace(1) %q, align {da}\n\
ret void\n}}\n\
declare {dst} @{name}({src}) #3\n"
);
let args = [
buffer(0, 0, "read_write", 1, "uint", "o"),
buffer(1, 1, "read", 1, "uint", "in"),
];
format!("{body}{}", kernel_list("__entry_cv", &args))
}
/// The values of `size` bytes `buffer` holds, which no command uses now.
fn elements(buffer: &Buffer, size: usize) -> Vec<u64> {
bytes(buffer)
.chunks_exact(size)
.map(|c| {
let mut b = [0u8; 8];
b[..size].copy_from_slice(c);
u64::from_le_bytes(b)
})
.collect()
}
#[test]
fn opencl_mode_conversions_answer_what_metal_answers() {
let Some(libraries) = CONVERSIONS
.iter()
.map(|(form, dst, src, _)| library(&conversion(dst, src, &format!("air.convert.{form}"))))
.collect::<Option<Vec<Library>>>()
else {
return;
};
each_device("opencl-mode-conversions", |name, _, device| {
let mut operands = 0;
for ((form, dst, src, measured), cv) in CONVERSIONS.iter().zip(&libraries) {
let (da, sa) = (size_of(dst), size_of(src));
let input: Vec<u8> = measured
.iter()
.flat_map(|(x, _)| x.to_le_bytes()[..sa].to_vec())
.collect();
let input = bytes_buffer(&device, &input);
let out = bytes_buffer(&device, &vec![0xEE; da * measured.len()]);
let cv = state(&device, cv, "__entry_cv");
run(
name,
&device,
&cv,
line(measured.len() as u32, 1),
([0; 3], 1),
&[whole(&out), whole(&input)],
);
let want: Vec<u64> = measured.iter().map(|(_, w)| *w).collect();
let x: Vec<u64> = measured.iter().map(|(x, _)| *x).collect();
assert_eq!(
elements(&out, da),
want,
"{name}: air.convert.{form} of {x:x?}"
);
operands += measured.len();
}
println!(
"{name}: {} conversions in OpenCL mode answered the oracles' words over {operands} operands",
CONVERSIONS.len()
);
});
}
@@ -0,0 +1,450 @@
//! Images of OpenCL mode (`ComputePipelineDescriptor::open_cl_mode_enabled`) over swizzled texture
//! views, as Apple's OpenCL binds an image of most channel orders, compared with what an M3 Max
//! (macOS 27.0.1) answers for kernels of the same shapes over the same views (our probe
//! `crates/metal2vulkan-conformance/probes/opencl_swizzled_images.m`, job m3-max-16336).
//!
//! Each view is 4 by 2, of an `RGBA8Unorm` or `R8Unorm` texture, made with the swizzle of one of
//! OpenCL's channel orders (`BGRA`, `ARGB`, `A`, `INTENSITY`, `LUMINANCE`; the identity as a
//! control). Texel `i` (`x + 4y`) of a filled texture holds bytes `(0x10 + i, 0x50 + i, 0x90 + i,
//! 0xd0 + i)` (`R8Unorm`: `0x10 + i`); a write stores `(0x11 + i, 0x51 + i, 0x91 + i, 0xd1 + i) /
//! 255` into a texture filled with `0xee`. The M3 Max answers, on every view, for plain Metal and
//! for OpenCL mode alike:
//!
//! - **query**: a write-only image the kernel only queries answers the view's width and height
//! and, for its channel order and data type, the third hidden buffer's words, which no swizzle
//! reaches (`4, 2, 0x11234, 0x1234`);
//! - **write**: a write-only image's write stores channel `c` from the first lane whose source is
//! `c`, and lane `c` where no lane names it: the swizzle undone;
//! - **read**: a read-only image's read, without a sampler and through one (nearest, at the
//! texel's centre), answers the texel swizzled: lane `l` the channel the swizzle's `l` names (a
//! format's missing green and blue 0, its missing alpha 1), `Zero` 0 and `One` 1;
//! - **read-write**: Apple's OpenCL compiler takes no `__read_write` image (OpenCL C 2.0's), so
//! the shape is plain Metal's `read_write` texture, read then written, in OpenCL mode: the read
//! and the write rules above, as the M3 Max answers a `read_write` texture of a swizzled view.
//!
//! Under a device cfg, on every device of the cfg's kind. The modules are LLVM text written here;
//! `llvm-as` assembles them, and without it the tests skip visibly.
use crate::tests::command::on_device::each_device;
use crate::tests::opencl_images::{float4s, image, run, sampler, sampler_node, Bound};
use crate::tests::opencl_mode::{
buffer, floats, floats_buffer, kernel_list, library, state, words, words_buffer,
};
use crate::{
Device, IndexClass, PixelFormat, Region, SamplerAddressMode, SamplerMinMagFilter, StorageMode,
Texture, TextureDescriptor, TextureSwizzle, TextureSwizzleChannels, TextureType, TextureUsage,
};
/// The views' size, and the threads that use them: thread `i` takes texel `(i & 3, i >> 2)`.
const W: u32 = 4;
const H: u32 = 2;
const N: u32 = W * H;
/// The thread's texel: `%g` its global id, `%i` that as `i32`, `%p` the texel's `<2 x i32>`.
const TEXEL: &str = " %g = tail call fastcc i64 @_Z13get_global_idj(i32 0)\n\
%i = trunc i64 %g to i32\n\
%x = and i32 %i, 3\n\
%y = lshr i32 %i, 2\n\
%p0 = insertelement <2 x i32> poison, i32 %x, i64 0\n\
%p = insertelement <2 x i32> %p0, i32 %y, i64 1\n";
/// The value thread `i` writes, `%v`: `(0x11 + i, 0x51 + i, 0x91 + i, 0xd1 + i) / 255`.
const VALUE: &str = " %fi = uitofp i32 %i to float\n\
%v0 = insertelement <4 x float> poison, float %fi, i64 0\n\
%vs = shufflevector <4 x float> %v0, <4 x float> poison, <4 x i32> zeroinitializer\n\
%va = fadd <4 x float> %vs, <float 1.700000e+01, float 8.100000e+01, float 1.450000e+02, float 2.090000e+02>\n\
%v = fdiv <4 x float> %va, <float 2.550000e+02, float 2.550000e+02, float 2.550000e+02, float 2.550000e+02>\n";
/// `__kernel void sw_query(__write_only image2d_t img, __global int *o)`: `o[0..4]` take the
/// image's width, height, channel order and channel data type.
fn query() -> String {
let body = "define void @__entry_sw_query(ptr addrspace(1) %0, ptr addrspace(1) %1) #0 {\n\
entry:\n\
tail call fastcc void @sw_query(ptr addrspace(1) %0, ptr addrspace(1) %1)\n\
ret void\n}\n\
define internal fastcc void @sw_query(ptr addrspace(1) %img, ptr addrspace(1) %o) #1 {\n\
entry:\n\
%w = tail call i32 @air.get_width_texture_2d(ptr addrspace(1) %img, i32 0)\n\
store i32 %w, ptr addrspace(1) %o, align 4\n\
%h = tail call i32 @air.get_height_texture_2d(ptr addrspace(1) %img, i32 0)\n\
%o1 = getelementptr inbounds i32, ptr addrspace(1) %o, i64 1\n\
store i32 %h, ptr addrspace(1) %o1, align 4\n\
%c = tail call fastcc i32 @_Z23get_image_channel_order14ocl_image2d_wo(ptr addrspace(1) %img)\n\
%o2 = getelementptr inbounds i32, ptr addrspace(1) %o, i64 2\n\
store i32 %c, ptr addrspace(1) %o2, align 4\n\
%d = tail call fastcc i32 @_Z27get_image_channel_data_type14ocl_image2d_wo(ptr addrspace(1) %img)\n\
%o3 = getelementptr inbounds i32, ptr addrspace(1) %o, i64 3\n\
store i32 %d, ptr addrspace(1) %o3, align 4\n\
ret void\n}\n\
define internal fastcc i32 @_Z23get_image_channel_order14ocl_image2d_wo(ptr addrspace(1) %0) #2 {\n\
%2 = tail call i32 @air.get_channel_order_texture_2d(ptr addrspace(1) %0) #0\n\
ret i32 %2\n}\n\
define internal fastcc i32 @_Z27get_image_channel_data_type14ocl_image2d_wo(ptr addrspace(1) %0) #2 {\n\
%2 = tail call i32 @air.get_channel_data_type_texture_2d(ptr addrspace(1) %0) #0\n\
ret i32 %2\n}\n\
declare i32 @air.get_width_texture_2d(ptr addrspace(1), i32) #0\n\
declare i32 @air.get_height_texture_2d(ptr addrspace(1), i32) #0\n\
declare i32 @air.get_channel_order_texture_2d(ptr addrspace(1)) #0\n\
declare i32 @air.get_channel_data_type_texture_2d(ptr addrspace(1)) #0\n";
let args = [
image(0, 0, "write", "texture2d<unknown, write>", "img"),
buffer(1, 0, "read_write", 1, "int", "o"),
];
format!("{body}{}", kernel_list("__entry_sw_query", &args))
}
/// `__kernel void sw_write(__write_only image2d_t img)`: thread `i` writes its value to its texel.
fn write() -> String {
let body = format!(
"define void @__entry_sw_write(ptr addrspace(1) %0) #0 {{\n\
entry:\n\
tail call fastcc void @sw_write(ptr addrspace(1) %0)\n\
ret void\n}}\n\
define internal fastcc void @sw_write(ptr addrspace(1) %img) #1 {{\n\
entry:\n\
{TEXEL}{VALUE}\
tail call void @air.write_texture_2d.v4f32(ptr addrspace(1) %img, <2 x i32> %p, <4 x float> %v, i32 0, i32 2)\n\
ret void\n}}\n\
declare void @air.write_texture_2d.v4f32(ptr addrspace(1), <2 x i32>, <4 x float>, i32, i32) #0\n"
);
let args = [image(0, 0, "write", "texture2d<unknown, write>", "img")];
format!("{body}{}", kernel_list("__entry_sw_write", &args))
}
/// `__kernel void sw_read(__read_only image2d_t img, sampler_t s, __global float4 *o)`: thread `i`
/// stores its texel read without a sampler to `o[2i]`, and sampled through `s` at its centre to
/// `o[2i + 1]`.
fn read() -> String {
let body = format!(
"define void @__entry_sw_read(ptr addrspace(1) %0, ptr addrspace(2) %1, ptr addrspace(1) %2) #0 {{\n\
entry:\n\
tail call fastcc void @sw_read(ptr addrspace(1) %0, ptr addrspace(2) %1, ptr addrspace(1) %2)\n\
ret void\n}}\n\
define internal fastcc void @sw_read(ptr addrspace(1) %img, ptr addrspace(2) %s, ptr addrspace(1) %o) #1 {{\n\
entry:\n\
{TEXEL}\
%rs = tail call ptr addrspace(2) @air.get_read_sampler()\n\
%r0 = tail call {{ <4 x float>, i8 }} @air.read_texture_2d.v4f32(ptr addrspace(1) %img, ptr addrspace(2) %rs, <2 x i32> %p, <2 x i32> zeroinitializer, i32 0, i32 1)\n\
%t0 = extractvalue {{ <4 x float>, i8 }} %r0, 0\n\
%b0 = mul i64 %g, 2\n\
%q0 = getelementptr inbounds <4 x float>, ptr addrspace(1) %o, i64 %b0\n\
store <4 x float> %t0, ptr addrspace(1) %q0, align 16\n\
%fp = uitofp <2 x i32> %p to <2 x float>\n\
%c = fadd <2 x float> %fp, <float 5.000000e-01, float 5.000000e-01>\n\
%r1 = tail call {{ <4 x float>, i8 }} @air.sample_texture_2d.v4f32(ptr addrspace(1) %img, ptr addrspace(2) %s, <2 x float> %c, i1 true, <2 x i32> zeroinitializer, i1 false, float 0.000000e+00, float 0.000000e+00, i32 0)\n\
%t1 = extractvalue {{ <4 x float>, i8 }} %r1, 0\n\
%b1 = add i64 %b0, 1\n\
%q1 = getelementptr inbounds <4 x float>, ptr addrspace(1) %o, i64 %b1\n\
store <4 x float> %t1, ptr addrspace(1) %q1, align 16\n\
ret void\n}}\n\
declare ptr addrspace(2) @air.get_read_sampler() #0\n\
declare {{ <4 x float>, i8 }} @air.read_texture_2d.v4f32(ptr addrspace(1), ptr addrspace(2), <2 x i32>, <2 x i32>, i32, i32) #0\n\
declare {{ <4 x float>, i8 }} @air.sample_texture_2d.v4f32(ptr addrspace(1), ptr addrspace(2), <2 x float>, i1, <2 x i32>, i1, float, float, i32) #0\n"
);
let args = [
image(0, 0, "sample", "texture2d<unknown, read>", "img"),
sampler_node(1, 0, "s"),
float4s(2, 0, "o"),
];
format!("{body}{}", kernel_list("__entry_sw_read", &args))
}
/// A `read_write` image (Metal's; OpenCL C 1.2 has none) in OpenCL mode: thread `i` stores its
/// texel to `o[i]`, then writes its value there.
fn read_write() -> String {
let body = format!(
"define void @__entry_sw_rw(ptr addrspace(1) %0, ptr addrspace(1) %1) #0 {{\n\
entry:\n\
tail call fastcc void @sw_rw(ptr addrspace(1) %0, ptr addrspace(1) %1)\n\
ret void\n}}\n\
define internal fastcc void @sw_rw(ptr addrspace(1) %img, ptr addrspace(1) %o) #1 {{\n\
entry:\n\
{TEXEL}\
%rs = tail call ptr addrspace(2) @air.get_read_sampler()\n\
%r0 = tail call {{ <4 x float>, i8 }} @air.read_texture_2d.v4f32(ptr addrspace(1) %img, ptr addrspace(2) %rs, <2 x i32> %p, <2 x i32> zeroinitializer, i32 0, i32 3)\n\
%t0 = extractvalue {{ <4 x float>, i8 }} %r0, 0\n\
%q0 = getelementptr inbounds <4 x float>, ptr addrspace(1) %o, i64 %g\n\
store <4 x float> %t0, ptr addrspace(1) %q0, align 16\n\
{VALUE}\
tail call void @air.write_texture_2d.v4f32(ptr addrspace(1) %img, <2 x i32> %p, <4 x float> %v, i32 0, i32 3)\n\
ret void\n}}\n\
declare ptr addrspace(2) @air.get_read_sampler() #0\n\
declare {{ <4 x float>, i8 }} @air.read_texture_2d.v4f32(ptr addrspace(1), ptr addrspace(2), <2 x i32>, <2 x i32>, i32, i32) #0\n\
declare void @air.write_texture_2d.v4f32(ptr addrspace(1), <2 x i32>, <4 x float>, i32, i32) #0\n"
);
let args = [
image(0, 0, "read_write", "texture2d<unknown, read_write>", "img"),
float4s(1, 0, "o"),
];
format!("{body}{}", kernel_list("__entry_sw_rw", &args))
}
/// A view the probe measured: its name, its texture's format and channel count, and its swizzle.
struct View {
name: &'static str,
format: PixelFormat,
channels: usize,
swizzle: [TextureSwizzle; 4],
}
/// The probe's views: each OpenCL channel order's swizzle over `RGBA8Unorm`, the one-channel
/// orders' over `R8Unorm` too, and the identity.
fn views() -> Vec<View> {
use TextureSwizzle::{Alpha as A, Blue as B, Green as G, One as I, Red as R, Zero as O};
let rgba = |name, swizzle| View {
name,
format: PixelFormat::RGBA8Unorm,
channels: 4,
swizzle,
};
let r8 = |name, swizzle| View {
name,
format: PixelFormat::R8Unorm,
channels: 1,
swizzle,
};
vec![
rgba("rgba8/identity", [R, G, B, A]),
rgba("rgba8/BGRA", [B, G, R, A]),
rgba("rgba8/ARGB", [G, B, A, R]),
rgba("rgba8/A", [O, O, O, R]),
rgba("rgba8/INTENSITY", [R, R, R, R]),
rgba("rgba8/LUMINANCE", [R, R, R, I]),
r8("r8/A", [O, O, O, R]),
r8("r8/INTENSITY", [R, R, R, R]),
r8("r8/LUMINANCE", [R, R, R, I]),
]
}
/// Byte `c` of texel `i` of a filled texture.
fn filled(i: usize, c: usize) -> u8 {
(0x10 + 0x40 * c + i) as u8
}
/// Lane `l` of the value thread `i` writes, as a byte.
fn written(i: usize, l: usize) -> u8 {
(0x11 + 0x40 * l + i) as u8
}
/// The channel a swizzle source names, if any.
fn channel(s: TextureSwizzle) -> Option<usize> {
match s {
TextureSwizzle::Red => Some(0),
TextureSwizzle::Green => Some(1),
TextureSwizzle::Blue => Some(2),
TextureSwizzle::Alpha => Some(3),
_ => None,
}
}
/// The bytes a read of texel `i` of a filled texture through `v` answers: the read rule.
fn read_rule(v: &View, i: usize) -> [u8; 4] {
std::array::from_fn(|l| match (v.swizzle[l], channel(v.swizzle[l])) {
(TextureSwizzle::One, _) => 0xff,
(_, Some(c)) if c < v.channels => filled(i, c),
(_, Some(3)) => 0xff,
_ => 0,
})
}
/// The bytes texel `i` holds after its write through `v`: the write rule.
fn write_rule(v: &View, i: usize) -> Vec<u8> {
(0..v.channels)
.map(|c| {
let lane = (0..4)
.find(|&l| channel(v.swizzle[l]) == Some(c))
.unwrap_or(c);
written(i, lane)
})
.collect()
}
/// A Shared texture of `v`'s format, 4 by 2, at texture index 1, every byte `fill` or the filled
/// texels, and its view through `v`'s swizzle at texture index 2.
fn swizzled(device: &Device, v: &View, fill: Option<u8>) -> (Texture, Texture) {
let mut descriptor = TextureDescriptor::new(TextureType::Type2D, v.format, W, H);
descriptor.usage =
TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE | TextureUsage::PIXEL_FORMAT_VIEW;
descriptor.storage_mode = StorageMode::Shared;
let texture = (device.new_texture(&descriptor, Some(1)))
.unwrap_or_else(|error| panic!("{}: {error}", v.name));
let bytes: Vec<u8> = (0..N as usize)
.flat_map(|i| (0..v.channels).map(move |c| fill.unwrap_or(filled(i, c))))
.collect();
let row = u64::from(W) * v.channels as u64;
(texture.replace_region(
whole(),
0,
0,
crate::HostBytes::from(&bytes[..]),
row,
row * u64::from(H),
))
.unwrap_or_else(|error| panic!("{}: {error}", v.name));
let [red, green, blue, alpha] = v.swizzle;
let swizzle = TextureSwizzleChannels {
red,
green,
blue,
alpha,
};
let view = (texture.new_texture_view_with_swizzle(
v.format,
TextureType::Type2D,
0..1,
0..1,
swizzle,
Some(2),
))
.unwrap_or_else(|error| panic!("{}: the view: {error}", v.name));
(texture, view)
}
/// The views' whole region.
fn whole() -> Region {
Region {
origin: [0; 3],
size: [W, H, 1],
}
}
/// The bytes of `texture`, of `v`'s format.
fn bytes(texture: &Texture, v: &View) -> Vec<u8> {
let row = u64::from(W) * v.channels as u64;
let mut out = vec![0u8; (row * u64::from(H)) as usize];
(texture.get_bytes(&mut out, row, row * u64::from(H), whole(), 0, 0))
.unwrap_or_else(|error| panic!("{}: {error}", v.name));
out
}
/// The bytes of the `float4` at `at` of `got`: each lane times 255, rounded.
fn lanes(got: &[f32], at: usize) -> [u8; 4] {
std::array::from_fn(|l| (got[4 * at + l] * 255.0).round() as u8)
}
#[test]
fn opencl_mode_queries_of_a_swizzled_write_only_image_answer_the_view() {
let Some(query) = library(&query()) else {
return;
};
each_device("opencl-swizzles-query", |name, _, device| {
let _grant = (device.grant_indices(IndexClass::Texture, 1, 2))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let query = state(&device, &query, "__entry_sw_query");
for v in views() {
let (_texture, view) = swizzled(&device, &v, None);
let o = words_buffer(&device, &[0xcdcd_cdcd; 4]);
let bound = Bound {
textures: &[&view],
samplers: &[],
out: Some(&o),
};
run(name, &device, &query, 1, &bound);
assert_eq!(words(&o), [4, 2, 0x11234, 0x1234], "{name}: {}", v.name);
}
println!("{name}: queries of each swizzled view answer the view");
});
}
#[test]
fn opencl_mode_writes_through_a_swizzled_image_undo_the_swizzle() {
let Some(write) = library(&write()) else {
return;
};
each_device("opencl-swizzles-write", |name, _, device| {
let _grant = (device.grant_indices(IndexClass::Texture, 1, 2))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let write = state(&device, &write, "__entry_sw_write");
for v in views() {
let (texture, view) = swizzled(&device, &v, Some(0xee));
let bound = Bound {
textures: &[&view],
samplers: &[],
out: None,
};
run(name, &device, &write, N, &bound);
let want: Vec<u8> = (0..N as usize).flat_map(|i| write_rule(&v, i)).collect();
assert_eq!(bytes(&texture, &v), want, "{name}: {}", v.name);
}
println!("{name}: writes through each swizzled view undo the swizzle");
});
}
#[test]
fn opencl_mode_reads_of_a_swizzled_image_answer_the_swizzled_texel() {
let Some(read) = library(&read()) else {
return;
};
each_device("opencl-swizzles-read", |name, _, device| {
let _textures = (device.grant_indices(IndexClass::Texture, 1, 2))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let _samplers = (device.grant_indices(IndexClass::Sampler, 1, 1))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let read = state(&device, &read, "__entry_sw_read");
let s = sampler(
&device,
SamplerMinMagFilter::Nearest,
SamplerAddressMode::ClampToEdge,
false,
1,
);
for v in views() {
let (_texture, view) = swizzled(&device, &v, None);
let o = floats_buffer(&device, &vec![-1.0; (2 * N * 4) as usize]);
let bound = Bound {
textures: &[&view],
samplers: &[&s],
out: Some(&o),
};
run(name, &device, &read, N, &bound);
let got = floats(&o);
for i in 0..N as usize {
let want = read_rule(&v, i);
let at = |k| lanes(&got, k);
assert_eq!(at(2 * i), want, "{name}: {} read of texel {i}", v.name);
assert_eq!(
at(2 * i + 1),
want,
"{name}: {} sample of texel {i}",
v.name
);
}
}
println!("{name}: reads of each swizzled view answer the swizzled texel");
});
}
#[test]
fn opencl_mode_read_write_images_of_a_swizzled_view_read_and_write_as_metal() {
let Some(rw) = library(&read_write()) else {
return;
};
each_device("opencl-swizzles-rw", |name, _, device| {
let _grant = (device.grant_indices(IndexClass::Texture, 1, 2))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let rw = state(&device, &rw, "__entry_sw_rw");
for v in views() {
let (texture, view) = swizzled(&device, &v, None);
let o = floats_buffer(&device, &vec![-1.0; (N * 4) as usize]);
let bound = Bound {
textures: &[&view],
samplers: &[],
out: Some(&o),
};
run(name, &device, &rw, N, &bound);
let got = floats(&o);
for i in 0..N as usize {
let read = lanes(&got, i);
assert_eq!(
read,
read_rule(&v, i),
"{name}: {} read of texel {i}",
v.name
);
}
let want: Vec<u8> = (0..N as usize).flat_map(|i| write_rule(&v, i)).collect();
assert_eq!(bytes(&texture, &v), want, "{name}: {} write", v.name);
}
println!("{name}: read_write images of each swizzled view read and write as Metal's");
});
}