From cd0dce11b5aceaa7dc3453153210e5c2533f401d Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sat, 21 Nov 2026 20:01:42 -0800 Subject: [PATCH] A contained store into a thread's private memory rewrites what it does not address, with no branch A contained store whose bytes are not all in bounds used to sit in a builder-closed if_, two blocks a store. A store into a thread's own private memory now always runs: - private arena (a Private array or a slot in device memory): each word it writes is written at select(inb, word, 0) as select(inb, value, old), old read from that word first, and a partial word's mask is select(inb, mask, 0). Out of bounds it rewrites word 0 with word 0's own bits. - typed alloca: a checked store takes each dynamic index past its level as 0 (as a checked load already did) and writes select(ok, v, old), old the element at those indices, read first. The private arena and a typed alloca are the thread's own, so no other invocation writes the element between the read and the write. Threadgroup and payload arena stores keep their if_: an invocation rewriting a shared word's old value would undo another's write (the module docs). Nothing is added to the thread's memory and the plan's private bytes do not change. A store with no old-value read (the clamped index written unconditionally) is not used: it would overwrite a live element. This replaces the sink form (steelbrain/storesink: cd68dd4c8e, 0e178ee64a, 9aeed12ecf, ad85331cb2, dead, not landed), which wrote past the object and so added bytes to the plan. SEMANTICS_VERSION 2266 (modules change). Tests: a run-time store into the private arena and into a typed alloca adds no block and changes no word (CPU interpreter, engine_arena); each device-arena access shape adds no block (engine_device_arena); on each device (runtime private_sinks), stores inside two private arrays of 4 and 2100 words answer what the M3 Max answered for the same steps (probe private_sinks.m, job m3-max-65609), stores past them answer what the same kernel without them answers, and element 0 keeps the bits of a NaN with payload bits (quiet, signalling and negative) with a store past its array. Standing condition: at the pin carrying this form, the consumer's cold launch lines on the RTX 3090, the RX 7900 XTX and the 780M give render seconds (first sample to quit, same scene, 64 samples) against the same span at 28e1026b3d. Within 3% on each, it stays. 3% or more slower on any, the form is removed by a new commit, not tuned. This does not gate landing or pin naming. --- .../probes/private_sinks.m | 117 +++++ crates/metal2vulkan-runtime/src/tests/mod.rs | 1 + .../src/tests/private_sinks.rs | 402 ++++++++++++++++++ crates/metal2vulkan/src/cache/mod.rs | 2 +- .../metal2vulkan/src/lower/access/atomic.rs | 6 +- crates/metal2vulkan/src/lower/access/local.rs | 101 +++-- crates/metal2vulkan/src/memory/alloca.rs | 7 +- crates/metal2vulkan/src/tests/engine_arena.rs | 97 ++++- .../src/tests/engine_device_arena.rs | 35 +- .../src/tests/engine_typed_clamp.rs | 14 +- 10 files changed, 723 insertions(+), 59 deletions(-) create mode 100644 crates/metal2vulkan-conformance/probes/private_sinks.m create mode 100644 crates/metal2vulkan-runtime/src/tests/private_sinks.rs diff --git a/crates/metal2vulkan-conformance/probes/private_sinks.m b/crates/metal2vulkan-conformance/probes/private_sinks.m new file mode 100644 index 000000000..559effc50 --- /dev/null +++ b/crates/metal2vulkan-conformance/probes/private_sinks.m @@ -0,0 +1,117 @@ +// What Metal answers for a kernel that stores into its private arrays at an index only the run +// knows: the computation of `metal2vulkan-runtime`'s `private_sinks` test (whose kernels are +// owned LLVM IR of the same steps). Each thread `t` of 64 (two threadgroups of 32) fills two +// arrays of `N` words, `a[i] = 31 t + i` and `b[i] = 17 t + 3 i`, stores `t + 100000` into `a`'s +// word at byte offset `4 k` and `t + 200000` into `b[k]`, `k = in[t]`, then folds +// `s = 3 (3 s + a[j]) + b[j]` over `j` and reads byte `(5 t) mod 4N` of `a`. +// +// Build (no cargo target needed): +// clang -fobjc-arc -O1 -fmodules -o private_sinks private_sinks.m \ +// -framework Foundation -framework Metal +// Run: ./private_sinks 4 (or 2100), one size a process, MTL_DEBUG_LAYER unset. +// +// `in[t]` is `(5 t + 1) mod N`, inside both arrays; an index past them is undefined in Metal and +// is not asked. Each thread's two output words, `s` and the byte, are printed in thread order, and +// compared with the same steps on the CPU (`reference`, the test's own). +// +// WHAT IT MEASURED (Apple M3 Max, macOS 27.0.1, job m3-max-65609): both sizes completed (status +// 4, no error), and all 64 threads equal the reference at N 4 and at N 2100 (thread 0: s +// 40500126, byte 0 at N 4; s 3075928718, byte 0 at N 2100). +#import +#import +#include +#include +#include + +static const char *SOURCE = + "#include \nusing namespace metal;\n" + "kernel void private_sinks(device uint *out [[buffer(0)]],\n" + " device const uint *in [[buffer(1)]],\n" + " uint t [[thread_position_in_grid]]) {\n" + " uint a[N];\n" + " uint b[N];\n" + " for (uint i = 0; i < N; i++) {\n" + " a[i] = 31 * t + i;\n" + " b[i] = 17 * t + 3 * i;\n" + " }\n" + " uint k = in[t];\n" + " *(thread uint *)((thread uchar *)a + 4 * k) = t + 100000;\n" + " b[k] = t + 200000;\n" + " uint s = 0;\n" + " for (uint j = 0; j < N; j++) s = 3 * (3 * s + a[j]) + b[j];\n" + " uint byte = ((thread uchar *)a)[(5 * t) % (4 * N)];\n" + " out[2 * t] = s;\n" + " out[2 * t + 1] = byte;\n" + "}\n"; + +enum { GROUPS = 2, THREADS = 32 }; + +// Thread `t`'s two words with `n` words an array, its stores at `k` (which is inside both). +static void reference(uint32_t n, uint32_t t, uint32_t k, uint32_t *s, uint32_t *byte) { + uint32_t *a = calloc(n, 4), *b = calloc(n, 4); + for (uint32_t i = 0; i < n; i++) { + a[i] = 31 * t + i; + b[i] = 17 * t + 3 * i; + } + a[k] = t + 100000; + b[k] = t + 200000; + uint32_t f = 0; + for (uint32_t j = 0; j < n; j++) f = 3 * (3 * f + a[j]) + b[j]; + uint32_t at = (5 * t) % (4 * n); + *s = f; + *byte = (a[at / 4] >> (8 * (at % 4))) & 0xff; + free(a); + free(b); +} + +int main(int argc, char **argv) { + if (argc < 2) return 2; + int n = atoi(argv[1]); + if (n <= 0) return 2; + @autoreleasepool { + printf("RESULT n=%d debug_layer=%s\n", n, + getenv("MTL_DEBUG_LAYER") ? getenv("MTL_DEBUG_LAYER") : "unset"); + id D = MTLCreateSystemDefaultDevice(); + printf("RESULT device=%s os=%s\n", D.name.UTF8String, + NSProcessInfo.processInfo.operatingSystemVersionString.UTF8String); + id Q = [D newCommandQueue]; + MTLCompileOptions *o = [MTLCompileOptions new]; + o.preprocessorMacros = @{@"N" : @(n)}; + NSError *e = nil; + id lib = [D newLibraryWithSource:[NSString stringWithUTF8String:SOURCE] + options:o + error:&e]; + if (!lib) { printf("RESULT library error %s\n", e.localizedDescription.UTF8String); return 1; } + id f = [lib newFunctionWithName:@"private_sinks"]; + id ps = [D newComputePipelineStateWithFunction:f error:&e]; + if (!ps) { printf("RESULT pipeline error %s\n", e.localizedDescription.UTF8String); return 1; } + int threads = GROUPS * THREADS; + id in = [D newBufferWithLength:threads * 4 options:MTLResourceStorageModeShared]; + uint32_t *ins = (uint32_t *)in.contents; + for (int t = 0; t < threads; t++) ins[t] = (uint32_t)((5 * t + 1) % n); + id out = [D newBufferWithLength:threads * 8 options:MTLResourceStorageModeShared]; + memset(out.contents, 0xee, threads * 8); + id cb = [Q commandBuffer]; + id ce = [cb computeCommandEncoder]; + [ce setComputePipelineState:ps]; + [ce setBuffer:out offset:0 atIndex:0]; + [ce setBuffer:in offset:0 atIndex:1]; + [ce dispatchThreadgroups:MTLSizeMake(GROUPS, 1, 1) + threadsPerThreadgroup:MTLSizeMake(THREADS, 1, 1)]; + [ce endEncoding]; + [cb commit]; + [cb waitUntilCompleted]; + printf("RESULT status=%ld error=%s\n", (long)cb.status, + cb.error ? cb.error.localizedDescription.UTF8String : "none"); + const uint32_t *w = (const uint32_t *)out.contents; + int same = 0; + for (int t = 0; t < threads; t++) { + uint32_t s, byte; + reference((uint32_t)n, (uint32_t)t, ins[t], &s, &byte); + same += w[2 * t] == s && w[2 * t + 1] == byte; + printf("RESULT t=%d s=%u byte=%u reference s=%u byte=%u\n", t, w[2 * t], w[2 * t + 1], s, byte); + } + printf("RESULT n=%d threads equal to the reference: %d of %d\n", n, same, threads); + } + return 0; +} diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index 85f7ae24c..0bf7a5edc 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -76,6 +76,7 @@ mod pixel_interlock; mod places; mod present; mod private_arena; +mod private_sinks; mod push_window; mod quad_control; mod raster; diff --git a/crates/metal2vulkan-runtime/src/tests/private_sinks.rs b/crates/metal2vulkan-runtime/src/tests/private_sinks.rs new file mode 100644 index 000000000..08ae45e7a --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/private_sinks.rs @@ -0,0 +1,402 @@ +//! Stores into a thread's private arrays at an index only the run knows, under a device cfg on +//! every device of the cfg's kind: the owned synthetic kernel `sinks` fills two arrays of `N` +//! words, `a[i] = 31 t + i` and `b[i] = 17 t + 3 i`, at its loop's index, stores `t + 100000` at +//! byte offset `4 k` of `a` and `t + 200000` at `b[k]`, `k = in[t]`, then folds +//! `s = 3 (3 s + a[j]) + b[j]` over `j` and reads byte `(5 t) mod 4N` of `a`. The byte read at a +//! run-time offset places `a` in the private arena; `b` is a typed array. `kept` is the same kernel +//! without the two stores at `k`. +//! +//! At `N` 4 the arena is a `Private` array; at `N` 2100 the two arrays pass the translator's floor +//! and the arena is the runtime's device memory (`crate::arena`), which the counters show. Each +//! contained store always runs, at its index where it is in bounds; otherwise it rewrites the +//! arena's word 0, or the array's element 0, with the bits it holds (the translator's +//! `lower::access::local` and `memory::alloca`). +//! +//! - In bounds, `k = (5 t + 1) mod N`, every thread's two words are Metal's: the same steps in MSL +//! (`metal2vulkan-conformance/probes/private_sinks.m`) answered `reference`'s on an Apple M3 Max +//! for both sizes. +//! - Out of bounds, `k` past both arrays (2N, 2N + 1, 3N + 7 and 100N by turns), Metal's answer is +//! not a defined one and none is claimed: on our side the stores change no word a thread +//! reads, so `sinks` answers what `kept` answers, `reference` without the stores. (An index past +//! `a` but within the arena reaches `b`, as Metal's own memory may: not asked.) +//! - Element 0 keeps a NaN's bits: the owned synthetic kernel `nan` stores a NaN with payload bits +//! from `in` into element 0 of the punned `a: [4 x float]` (in the private arena) and of the +//! typed `b: [4 x float]`, `1.0` into the rest, and `2.5` at byte offset `4 k` of `a` and at +//! `b[k]`, `k` past both, then writes `a[0]`'s and `b[0]`'s bits and byte `(5 t) mod 16` of `a`. +//! `nan_kept` is the same kernel without the two stores at `k`. Both answer the NaN's bits as +//! `in` held them: the typed array's store selects between a float and its old value, and a +//! device whose select or float move changed a NaN's payload would show it here. +//! +//! `llvm-as` assembles the kernels; without it the tests skip visibly. + +#[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod on_device { + 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}; + + /// Threadgroups of a dispatch, and threads of each. + const GROUPS: u32 = 2; + const THREADS: u32 = 32; + + /// One kernel of [`module`]: `@name`, with the two stores at `k` where `stores`. + fn kernel(name: &str, n: u32, stores: bool) -> String { + let poke = if stores { + " %pk = getelementptr inbounds i32, ptr addrspace(1) %in, i32 %t + %k = load i32, ptr addrspace(1) %pk, align 4 + %w = shl i32 %k, 2 + %pa2 = getelementptr inbounds i8, ptr %a, i32 %w + %v1 = add i32 %t, 100000 + store i32 %v1, ptr %pa2, align 4 + %pb2 = getelementptr inbounds [N x i32], ptr %b, i32 0, i32 %k + %v2 = add i32 %t, 200000 + store i32 %v2, ptr %pb2, align 4 +" + } else { + "" + }; + let threads = THREADS; + let body = format!( + r#"define void @{name}(ptr addrspace(1) %out, ptr addrspace(1) %in, i32 %tg, i32 %tid) {{ +entry: + %a = alloca [N x i32], align 4 + %b = alloca [N x i32], align 4 + %first = mul i32 %tg, {threads} + %t = add i32 %first, %tid + %ta = mul i32 %t, 31 + %tb = mul i32 %t, 17 + br label %fill +fill: + %i = phi i32 [ 0, %entry ], [ %i1, %fill ] + %va = add i32 %ta, %i + %pa = getelementptr inbounds [N x i32], ptr %a, i32 0, i32 %i + store i32 %va, ptr %pa, align 4 + %i3 = mul i32 %i, 3 + %vb = add i32 %tb, %i3 + %pb = getelementptr inbounds [N x i32], ptr %b, i32 0, i32 %i + store i32 %vb, ptr %pb, align 4 + %i1 = add i32 %i, 1 + %more = icmp ult i32 %i1, N + br i1 %more, label %fill, label %poke +poke: +{poke} br label %fold +fold: + %j = phi i32 [ 0, %poke ], [ %j1, %fold ] + %s = phi i32 [ 0, %poke ], [ %s2, %fold ] + %qa = getelementptr inbounds [N x i32], ptr %a, i32 0, i32 %j + %xa = load i32, ptr %qa, align 4 + %qb = getelementptr inbounds [N x i32], ptr %b, i32 0, i32 %j + %xb = load i32, ptr %qb, align 4 + %s3 = mul i32 %s, 3 + %s1 = add i32 %s3, %xa + %s4 = mul i32 %s1, 3 + %s2 = add i32 %s4, %xb + %j1 = add i32 %j, 1 + %again = icmp ult i32 %j1, N + br i1 %again, label %fold, label %done +done: + %t5 = mul i32 %t, 5 + %at = urem i32 %t5, {bytes} + %py = getelementptr inbounds i8, ptr %a, i32 %at + %y = load i8, ptr %py, align 1 + %yw = zext i8 %y to i32 + %o0 = shl i32 %t, 1 + %q0 = getelementptr inbounds i32, ptr addrspace(1) %out, i32 %o0 + store i32 %s2, ptr addrspace(1) %q0, align 4 + %o1 = or i32 %o0, 1 + %q1 = getelementptr inbounds i32, ptr addrspace(1) %out, i32 %o1 + store i32 %yw, ptr addrspace(1) %q1, align 4 + ret void +}} +"#, + bytes = 4 * n + ); + body.replace("N x i32", &format!("{n} x i32")) + .replace("i32 %i1, N", &format!("i32 %i1, {n}")) + .replace("i32 %j1, N", &format!("i32 %j1, {n}")) + } + + /// The kernels `sinks` and `kept` of `n` words an array. + fn module(n: u32) -> String { + format!( + r#"; Owned synthetic kernels: two private arrays of {n} words, stored at an index the run knows. +source_filename = "private_sinks.metal" + +{} +{} +!air.kernel = !{{!0, !1}} +!0 = !{{ptr @sinks, !2, !3}} +!1 = !{{ptr @kept, !2, !3}} +!2 = !{{}} +!3 = !{{!10, !11, !12, !13}} +!10 = !{{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", !"uint", !"air.arg_name", !"out"}} +!11 = !{{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"in"}} +!12 = !{{i32 2, !"air.threadgroup_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"tg"}} +!13 = !{{i32 3, !"air.thread_position_in_threadgroup", !"air.arg_type_name", !"uint", !"air.arg_name", !"tid"}} +"#, + kernel("sinks", n, true), + kernel("kept", n, false) + ) + } + + /// Thread `t`'s two words with `n` words an array, its stores at `k` where `k` is inside both + /// (none past them). + fn reference(n: u32, t: u32, k: u32) -> [u32; 2] { + let mut a: Vec = (0..n).map(|i| t.wrapping_mul(31).wrapping_add(i)).collect(); + let mut b: Vec = (0..n) + .map(|i| t.wrapping_mul(17).wrapping_add(3 * i)) + .collect(); + if k < n { + a[k as usize] = t + 100_000; + b[k as usize] = t + 200_000; + } + let s = (0..n as usize).fold(0u32, |s, j| { + let s = s.wrapping_mul(3).wrapping_add(a[j]); + s.wrapping_mul(3).wrapping_add(b[j]) + }); + let at = (5 * t) % (4 * n); + [s, (a[(at / 4) as usize] >> (8 * (at % 4))) & 0xff] + } + + /// The state of kernel `entry` of `library` on `device`. + fn state(name: &str, device: &Device, library: &Library, entry: &str) -> ComputePipelineState { + let function = library.function(entry).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}: {entry}: {error}")) + } + + /// The words of `buffer`, read once its writer completed. + fn words(buffer: &Buffer, count: usize) -> Vec { + let contents = buffer.contents().expect("a Shared buffer"); + // SAFETY: the work that wrote the buffer completed, and its writes reach the host; the + // buffer holds at least `count` words. + unsafe { std::slice::from_raw_parts(contents.as_ptr().cast::(), count) }.to_vec() + } + + /// Write `values` to `buffer`'s first words. + fn fill(buffer: &Buffer, values: &[u32]) { + let contents = buffer.contents().expect("a Shared buffer"); + // SAFETY: no work reaches the buffer yet; it holds at least `values.len()` words. + let at = unsafe { + std::slice::from_raw_parts_mut(contents.as_ptr().cast::(), values.len()) + }; + at.copy_from_slice(values); + } + + /// The first `count` words `kernel` writes, one dispatch of [`GROUPS`] threadgroups of + /// [`THREADS`] over the input words `ins`. + fn run( + name: &str, + device: &Device, + kernel: &ComputePipelineState, + (input, out): (&Buffer, &Buffer), + ins: &[u32], + count: usize, + ) -> Vec { + fill(input, ins); + fill(out, &vec![0xeeee_eeee; count]); + 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(kernel).expect("a state"); + encoder.set_buffer(Some(out), 0, 0).expect("out"); + encoder.set_buffer(Some(input), 0, 1).expect("in"); + (encoder.dispatch_threadgroups([GROUPS, 1, 1], [THREADS, 1, 1])) + .unwrap_or_else(|error| panic!("{name}: {error}")); + encoder.end_encoding(); + command_buffer.commit().expect("a commit"); + finished(name, &command_buffer); + assert_eq!(command_buffer.error(), None, "{name}"); + words(out, count) + } + + #[test] + fn every_device_keeps_a_store_past_a_private_array_off_its_words() { + let threads = GROUPS * THREADS; + for n in [4u32, 2100] { + let bitcode = match llvm_assemble_text(&module(n)) { + Ok(bitcode) => bitcode, + Err(AssembleError::Missing(why)) => { + eprintln!("SKIPPED: {why}"); + return; + } + Err(error) => panic!("private_sinks: {error:?}"), + }; + let library = Library::from_air(&bitcode).expect("the library"); + let inside: Vec = (0..threads).map(|t| (5 * t + 1) % n).collect(); + let past: Vec = (0..threads) + .map(|t| [2 * n, 2 * n + 1, 3 * n + 7, 100 * n][(t % 4) as usize]) + .collect(); + let metal: Vec = (0..threads) + .flat_map(|t| reference(n, t, inside[t as usize])) + .collect(); + let untouched: Vec = (0..threads).flat_map(|t| reference(n, t, n)).collect(); + each_device("private_sinks", |name, _, device| { + let sinks = state(name, &device, &library, "sinks"); + let kept = state(name, &device, &library, "kept"); + let slot = sinks.inner.compiled.whole.interface.private_arena; + assert_eq!( + slot.is_some(), + n > 4, + "{name}: {n} words, arena slot {slot:?}" + ); + let block = (device.take_block(MemoryClass::Shared, 1 << 16)).expect("a block"); + let input = (device.new_buffer(block.id, 0, 4096, Some(0))).expect("a buffer"); + let out = (device.new_buffer(block.id, 4096, 4096, Some(0))).expect("a buffer"); + let counters = device.counters(); + let before = counters.metrics().private_arena_dispatches; + let what = format!("{name}: {n} words"); + let count = 2 * threads as usize; + let read = run(name, &device, &sinks, (&input, &out), &inside, count); + assert_eq!(read, metal, "{what}: stores inside the arrays"); + let read = run(name, &device, &sinks, (&input, &out), &past, count); + let without = run(name, &device, &kept, (&input, &out), &past, count); + assert_eq!(read, without, "{what}: stores past the arrays against none"); + assert_eq!(without, untouched, "{what}: no store"); + let arena = counters.metrics().private_arena_dispatches - before; + assert_eq!(arena, if n > 4 { 3 } else { 0 }, "{what}: arena dispatches"); + println!( + "{what}: stores inside the arrays answer Metal's, past them change no word \ + ({arena} dispatches in the runtime's arena, slot {slot:?})" + ); + drop((sinks, kept, input, out)); + (device.release_block(block)).unwrap_or_else(|error| panic!("{name}: {error}")); + }); + } + } + + /// One kernel of [`nan_module`]: `@name`, with the two stores at `k` where `stores`. + fn nan_kernel(name: &str, stores: bool) -> String { + let poke = if stores { + " %i1 = or i32 %i0, 1 + %pk = getelementptr inbounds i32, ptr addrspace(1) %in, i32 %i1 + %k = load i32, ptr addrspace(1) %pk, align 4 + %w = shl i32 %k, 2 + %pa2 = getelementptr inbounds i8, ptr %a, i32 %w + store float 2.500000e+00, ptr %pa2, align 4 + %pb2 = getelementptr inbounds [4 x float], ptr %b, i32 0, i32 %k + store float 2.500000e+00, ptr %pb2, align 4 +" + } else { + "" + }; + let mut fill = String::new(); + for x in ["a", "b"] { + fill += &format!( + " %p{x}0 = getelementptr inbounds [4 x float], ptr %{x}, i32 0, i32 0\n store float %nan, ptr %p{x}0, align 4\n" + ); + for i in 1..4 { + fill += &format!( + " %p{x}{i} = getelementptr inbounds [4 x float], ptr %{x}, i32 0, i32 {i}\n store float 1.000000e+00, ptr %p{x}{i}, align 4\n" + ); + } + } + format!( + r#"define void @{name}(ptr addrspace(1) %out, ptr addrspace(1) %in, i32 %tg, i32 %tid) {{ +entry: + %a = alloca [4 x float], align 4 + %b = alloca [4 x float], align 4 + %first = mul i32 %tg, {THREADS} + %t = add i32 %first, %tid + %i0 = shl i32 %t, 1 + %pn = getelementptr inbounds float, ptr addrspace(1) %in, i32 %i0 + %nan = load float, ptr addrspace(1) %pn, align 4 +{fill}{poke} %ra = load float, ptr %pa0, align 4 + %rb = load float, ptr %pb0, align 4 + %t5 = mul i32 %t, 5 + %at = urem i32 %t5, 16 + %py = getelementptr inbounds i8, ptr %a, i32 %at + %y = load i8, ptr %py, align 1 + %yw = zext i8 %y to i32 + %o0 = mul i32 %t, 3 + %q0 = getelementptr inbounds float, ptr addrspace(1) %out, i32 %o0 + store float %ra, ptr addrspace(1) %q0, align 4 + %o1 = add i32 %o0, 1 + %q1 = getelementptr inbounds float, ptr addrspace(1) %out, i32 %o1 + store float %rb, ptr addrspace(1) %q1, align 4 + %o2 = add i32 %o0, 2 + %q2 = getelementptr inbounds i32, ptr addrspace(1) %out, i32 %o2 + store i32 %yw, ptr addrspace(1) %q2, align 4 + ret void +}} +"# + ) + } + + /// The kernels `nan` and `nan_kept`. + fn nan_module() -> String { + format!( + r#"; Owned synthetic kernels: a NaN in element 0 of two private arrays, stored past them. +source_filename = "private_sinks_nan.metal" + +{} +{} +!air.kernel = !{{!0, !1}} +!0 = !{{ptr @nan, !2, !3}} +!1 = !{{ptr @nan_kept, !2, !3}} +!2 = !{{}} +!3 = !{{!10, !11, !12, !13}} +!10 = !{{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", !"uint", !"air.arg_name", !"out"}} +!11 = !{{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"in"}} +!12 = !{{i32 2, !"air.threadgroup_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"tg"}} +!13 = !{{i32 3, !"air.thread_position_in_threadgroup", !"air.arg_type_name", !"uint", !"air.arg_name", !"tid"}} +"#, + nan_kernel("nan", true), + nan_kernel("nan_kept", false) + ) + } + + #[test] + fn a_store_past_a_private_array_keeps_the_bits_of_a_nan_at_element_0() { + let threads = GROUPS * THREADS; + let bitcode = match llvm_assemble_text(&nan_module()) { + Ok(bitcode) => bitcode, + Err(AssembleError::Missing(why)) => { + eprintln!("SKIPPED: {why}"); + return; + } + Err(error) => panic!("private_sinks nan: {error:?}"), + }; + let library = Library::from_air(&bitcode).expect("the library"); + // A quiet NaN with payload bits, a signalling one, and a negative quiet one. + let nans = [0x7fc0_1234u32, 0x7f80_1234, 0xffc5_a5a5]; + let ins: Vec = (0..threads) + .flat_map(|t| [nans[(t % 3) as usize], [8, 9, 19, 400][(t % 4) as usize]]) + .collect(); + let want: Vec = (0..threads) + .flat_map(|t| { + let x = nans[(t % 3) as usize]; + let at = (5 * t) % 16; + let word = if at < 4 { x } else { 0x3f80_0000 }; + [x, x, (word >> (8 * (at % 4))) & 0xff] + }) + .collect(); + each_device("private_sinks nan", |name, _, device| { + let nan = state(name, &device, &library, "nan"); + let kept = state(name, &device, &library, "nan_kept"); + let block = (device.take_block(MemoryClass::Shared, 1 << 16)).expect("a block"); + let input = (device.new_buffer(block.id, 0, 4096, Some(0))).expect("a buffer"); + let out = (device.new_buffer(block.id, 4096, 4096, Some(0))).expect("a buffer"); + let count = 3 * threads as usize; + let without = run(name, &device, &kept, (&input, &out), &ins, count); + let hex = |w: &[u32]| w.iter().map(|w| format!("{w:08x}")).collect::>(); + assert_eq!( + hex(&without), + hex(&want), + "{name}: a NaN with no store past it" + ); + let read = run(name, &device, &nan, (&input, &out), &ins, count); + assert_eq!(hex(&read), hex(&want), "{name}: a NaN with a store past it"); + println!("{name}: element 0 keeps each NaN's bits with a store past its array"); + drop((nan, kept, input, out)); + (device.release_block(block)).unwrap_or_else(|error| panic!("{name}: {error}")); + }); + } +} diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index e8bfc020d..ac3421f43 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -61,7 +61,7 @@ mod tests; /// unchanged version, and its bless records the version. Independent of the crate's version and of /// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no /// history. -pub const SEMANTICS_VERSION: u32 = 2265; +pub const SEMANTICS_VERSION: u32 = 2266; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another diff --git a/crates/metal2vulkan/src/lower/access/atomic.rs b/crates/metal2vulkan/src/lower/access/atomic.rs index 0db8b64c6..00311d57b 100644 --- a/crates/metal2vulkan/src/lower/access/atomic.rs +++ b/crates/metal2vulkan/src/lower/access/atomic.rs @@ -78,8 +78,10 @@ //! check; an in-shader check //! guards a view's atomic with `if_(inb)` (its result is 0 out of bounds, where Metal's is //! unmeasured); a device-address atomic out of bounds (a static slot's or a wide pointer's, checked -//! against the root entry's size) operates on the write-only sink and yields 0; an arena atomic -//! sits in `if_(inb)` against the arena's exact size. A wide pointer's atomic through root 0 (null +//! against the root entry's size) operates on the write-only sink and yields 0; a threadgroup +//! arena atomic, where the arena is contained, sits in `if_(inb)` against the arena's exact size; +//! a thread atomic is a load and a store of the private arena, contained as they are (out of +//! bounds it yields 0 and rewrites word 0 as it was). A wide pointer's atomic through root 0 (null //! or a resident-set miss) is counted under isolation, as a wide leaf access is. A wide atomic's //! address is naturally aligned (`(bind_offset + offset) & ~(n - 1)`), as Metal atomic objects are. //! diff --git a/crates/metal2vulkan/src/lower/access/local.rs b/crates/metal2vulkan/src/lower/access/local.rs index 881aa79ae..1c78d7797 100644 --- a/crates/metal2vulkan/src/lower/access/local.rs +++ b/crates/metal2vulkan/src/lower/access/local.rs @@ -46,13 +46,22 @@ //! intrinsics', pointer cells' and imageblock's alike, nor a typed threadgroup object's index, and //! one past the memory is undefined, as in Metal (no robustness feature covers arenas). Contained, //! with `inb` the normative check against the arena's exact byte -//! size, a load reads at `select(inb, off, 0)` and yields `select(inb, v, 0)`, and a store sits in -//! a builder-closed `if_(inb)`. A dereference of a null private pointer (undefined in Metal) reads +//! size, a load reads at `select(inb, off, 0)` and yields `select(inb, v, 0)`. A store into the +//! private arena, wherever it lives (a `Private` array or a slot in device memory), always runs +//! ([`Guarded`]): each word it writes is written at `select(inb, word, 0)` as `select(inb, value, +//! old)`, `old` the word it replaces, read first, and a partial word's mask is `select(inb, mask, +//! 0)`, so an out-of-bounds store rewrites word 0 with its own bits and adds no block. The private +//! arena is the thread's own, so no other invocation writes word 0 between the read and the write. +//! A store into the threadgroup or payload arena, which invocations share, sits in a +//! builder-closed `if_(inb)`: rewriting a word's old value there would undo another invocation's +//! write. A dereference of a null private pointer (undefined in Metal) reads //! or writes the kept first word, or an object's bytes at a field's offset: inside the arena. A //! typed access's dynamic indices are **bounded** (`memory::alloca`), so the access never leaves //! its object: a thread's own -//! object's (an alloca's) are checked against their levels' lengths, a load past a level reading -//! zero and a store past one sitting in a builder-closed `if_` that drops it; a threadgroup +//! object's (an alloca's) are checked against their levels' lengths, each index past its level +//! taken as 0, a load past a level reading zero and a store past one writing `select(ok, v, old)`, +//! `old` the element at the taken indices, read first: the element's own value, so it adds no +//! block and changes nothing. A threadgroup //! object's, where threadgroup memory is contained ([`contained`]), and a constant object's are //! each clamped to the level's last element. A constant index is in range by //! construction. Each dynamic index is the defining `getelementptr`'s own operand where the GEP's @@ -109,7 +118,7 @@ use crate::memory::alloca::{self, Init, Shape, Step, Strides, TypedPath, TypedTy use crate::memory::arena::{self, Arena, ArenaDecl, ArenaMem, TgDecl, TgShape, TgWords}; use crate::memory::contain; use crate::memory::fragment; -use crate::memory::leaf::{self, k32, Leaf, WordOps}; +use crate::memory::leaf::{self, k32, Leaf, WordMem, WordOps}; use crate::memory::plan::ArenaObject; use crate::memory::provenance::{map_entry_bytes, ConstForm, OffsetRange, PrivForm, Repr, Root}; use crate::pipeline::facts::RuntimeFact; @@ -196,8 +205,9 @@ pub struct TypedAccess { impl TypedAccess { /// A contained access of a thread's own typed object (an alloca) is checked: a load past a - /// level reads zero and a store past one is dropped, so a store never changes an element it - /// does not address, as Metal's store past the array changes none of the array's. A threadgroup + /// level reads zero and a store past one writes back the element it reaches with each index + /// past its level taken as 0, as that element was, so a store never changes an element it does + /// not address, as Metal's store past the array changes none of the array's. A threadgroup /// or constant object's contained access clamps each index to its level's last element /// (`memory::alloca`). pub fn checked(&self) -> bool { @@ -208,7 +218,8 @@ impl TypedAccess { let chain = 8u32.saturating_add(self.path.steps.len() as u32); let levels = self.path.dynamic().count() as u32; let dynamic = 24 * levels; - // A checked access's value select or store guard, beside its per-level checks. + // A checked access's value select (a store's also its old element's load), beside its + // per-level checks. let clamp = match (self.clamped, self.checked()) { (false, _) => 0, (true, false) => 32 * levels, @@ -2062,6 +2073,12 @@ pub(super) fn emit_access_at( let z = leaf::zero(fb, &leaf)?; fb.select(inb, v, z).map(Some) } + Some(v) if a.arena == Arena::Private => { + let mut guarded = Guarded { mem: &mut mem, inb }; + leaf::store(fb, &mut guarded, &leaf, off, v)?; + Ok(None) + } + // A store into memory invocations share keeps its branch (the module docs). Some(v) => { let then: ArmFn<'_, ()> = Box::new(move |fb, _| { let mut mem = KeptMem { @@ -2077,6 +2094,44 @@ pub(super) fn emit_access_at( } } +/// The words of a contained store into the private arena (the module docs): each word written at +/// `select(inb, word, 0)` as `select(inb, value, old)`, `old` read from that word first, and each +/// partial word's mask taken as `select(inb, mask, 0)`, so a store whose bytes are out of bounds +/// rewrites word 0 with its own bits. It offers no narrow or whole-word units, so every store is +/// of words. +struct Guarded<'m> { + mem: &'m mut KeptMem, + inb: SValue, +} + +impl WordMem for Guarded<'_> { + fn read(&mut self, fb: &mut FunctionBuilder<'_>, word: SValue) -> BResult { + self.mem.read(fb, word) + } + + fn write(&mut self, fb: &mut FunctionBuilder<'_>, word: SValue, value: SValue) -> BResult<()> { + let zero = k32(fb, 0)?; + let at = fb.select(self.inb, word, zero)?; + let old = self.mem.read(fb, at)?; + let x = fb.select(self.inb, value, old)?; + self.mem.write(fb, at, x) + } + + fn write_bits( + &mut self, + fb: &mut FunctionBuilder<'_>, + word: SValue, + mask: SValue, + bits: SValue, + ) -> BResult<()> { + let zero = k32(fb, 0)?; + let at = fb.select(self.inb, word, zero)?; + let mask = fb.select(self.inb, mask, zero)?; + let bits = fb.select(self.inb, bits, zero)?; + self.mem.write_bits(fb, at, mask, bits) + } +} + /// Load or store (`stored`) `a`'s leaf, whole `float` words, at byte offset `off` of an arena of /// `float` words (`ArenaDecl::floats`, the module docs): lane `j` of `lanes` at word /// `off / 4 + j`, one typed access each, uncontained. @@ -2132,15 +2187,13 @@ fn float_words( /// ([`TypedAccess::checked`]). Each dynamic index is the defining GEP's operand where they line up /// (`TypedAccess::indices`), or is recovered from the pointer's offset level by level (`(rem - /// start) / stride`, the next level's `rem` being `(rem - start) % stride`, `memory::alloca`). -/// When `a.clamped`, a checked access's condition is every level's `idx < len`, a load reading -/// each level at `select(idx < len, idx, 0)` (a store's chain is built under the condition); any -/// other access clamps each index to its level's last element, `min(idx, len - 1)`. Either way the -/// chain never leaves the object. +/// When `a.clamped`, a checked access's condition is every level's `idx < len`, a load or store +/// reaching each level at `select(idx < len, idx, 0)`; any other access clamps each index to its +/// level's last element, `min(idx, len - 1)`. Either way the chain never leaves the object. fn chain_indices( cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, a: &TypedAccess, - load: bool, ) -> BResult<(Vec, Option)> { let levels = a.path.dynamic().count(); let mut rem = match (levels, &a.indices) { @@ -2218,19 +2271,15 @@ fn chain_indices( None => in_range, Some(all) => fb.binary(BinOp::LogicalAnd, all, in_range)?, }); - out.push(if load { - let zero = k32(fb, 0)?; - fb.select(in_range, idx, zero)? - } else { - idx - }); + let zero = k32(fb, 0)?; + out.push(fb.select(in_range, idx, zero)?); } Ok((out, ok)) } /// Load or store (`stored`) typed access `a` through an access chain of its path, contained when /// `a.clamped` ([`chain_indices`]): a checked load past a level yields zero and a checked store -/// past one is dropped. +/// past one writes back the element its indices taken as 0 reach, as it was (the module docs). fn emit_typed( cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, @@ -2249,7 +2298,7 @@ fn emit_typed( let Some(g) = found else { return Err(cx.fail(format!("typed object {:?} is not declared", a.home))); }; - let (mut idx, ok) = chain_indices(cx, fb, a, stored.is_none())?; + let (mut idx, ok) = chain_indices(cx, fb, a)?; // One held element of a matrix's fragment is that lane of it. if let Some(alloca::FragmentPart::Lane(i)) = a.part { idx.push(k32(fb, i)?); @@ -2306,12 +2355,10 @@ fn emit_typed( Ok(None) } (Some(v), Some(ok)) => { - let then: ArmFn<'_, ()> = Box::new(move |fb, _| { - let p = fb.access_chain(base, &idx)?; - fb.store(p, v, store_access)?; - Ok(ArmEnd::FallThrough(Vec::new())) - }); - fb.if_(&mut (), ok, then, None)?; + let p = fb.access_chain(base, &idx)?; + let old = fb.load(p, load_access)?; + let v = fb.select(ok, v, old)?; + fb.store(p, v, store_access)?; Ok(None) } } diff --git a/crates/metal2vulkan/src/memory/alloca.rs b/crates/metal2vulkan/src/memory/alloca.rs index 0828b9fbb..47348fea3 100644 --- a/crates/metal2vulkan/src/memory/alloca.rs +++ b/crates/metal2vulkan/src/memory/alloca.rs @@ -29,9 +29,10 @@ //! undefined in Metal, whose own answer is whatever its memory holds at the address: //! //! - in a thread's own object (an alloca) the access is checked, every dynamic level's `idx < len`: -//! a load past a level reads zero, and a store past one is dropped, so it changes no element of -//! the object, as Metal's store past an array changes none of the array's elements (it lands -//! past them); +//! a load past a level reads zero, and a store past one writes back, as it was, the element its +//! indices reach with each one past its level taken as 0 (`select(ok, v, old)`, `old` read +//! first), so it adds no block and changes no element of the object, as Metal's store past an +//! array changes none of the array's elements (it lands past them); //! - in a threadgroup or constant object each dynamic level's index is `min(idx, len - 1)`: an //! index past it reaches the level's last element, a load reading that element and a store //! writing it. diff --git a/crates/metal2vulkan/src/tests/engine_arena.rs b/crates/metal2vulkan/src/tests/engine_arena.rs index d9e6f0015..ac7abded8 100644 --- a/crates/metal2vulkan/src/tests/engine_arena.rs +++ b/crates/metal2vulkan/src/tests/engine_arena.rs @@ -9,11 +9,11 @@ //! - Byte stores into threadgroup memory by neighbouring invocations of different subgroups //! preserve each other (two word atomics). //! - An alloca whose accesses are punned lives in the private arena, word-composed and -//! byte-exact. +//! byte-exact; a store out of its bounds rewrites word 0 as it was, with no block. //! - Typed allocas and closed constant globals are `Private` arrays indexed by access chains; their -//! dynamic indices are bounded (a typed alloca's out-of-range load -//! is 0 and its out-of-range store is dropped; a constant global's out-of-range load reads the -//! level's last element) and unclamped without it. +//! dynamic indices are bounded (a typed alloca's out-of-range load is 0 and its out-of-range +//! store rewrites the element at index 0 as it was, with no block; a constant global's +//! out-of-range load reads the level's last element) and unclamped without it. //! //! `llvm-as` assembles the kernels; without it the tests skip visibly. @@ -563,7 +563,7 @@ fn typed_alloca_body() -> String { } /// A typed alloca is a `Private` array indexed by access chains; its dynamic indices are checked -/// under isolation (an out-of-range load is 0, an out-of-range store is dropped) and exact in +/// under isolation (an out-of-range load is 0, an out-of-range store changes nothing) and exact in /// range, including a 12-byte (non-power-of-two) stride. Without isolation no check is emitted. #[test] fn typed_alloca_indices_are_clamped_under_isolation() { @@ -602,6 +602,93 @@ fn typed_alloca_indices_are_clamped_under_isolation() { } } +/// A kernel `@name(out, t)` over the punned `a: [4 x i32]` (a byte load at a run-time offset +/// places it in the private arena) and the typed `b: [4 x i32]`, each initialized to `10 + i`; +/// where `stores`, `t` is stored at word `t` of each (out of bounds from `t = 4`), at a run-time +/// byte offset into `a` and a run-time index into `b`. Thread `t` writes `a`'s and `b`'s words and +/// the loaded byte to `out[9t..9t + 9]`. +fn sink_kernel(name: &str, stores: bool) -> String { + let mut s = + String::from(" %a = alloca [4 x i32], align 4\n %b = alloca [4 x i32], align 4\n"); + for (x, i) in [ + ("a", 0), + ("a", 1), + ("a", 2), + ("a", 3), + ("b", 0), + ("b", 1), + ("b", 2), + ("b", 3), + ] { + s += &format!( + " %i{x}{i} = getelementptr inbounds [4 x i32], ptr %{x}, i32 0, i32 {i}\n store i32 {}, ptr %i{x}{i}, align 4\n", + 10 + i + ); + } + s += " %k = and i32 %t, 15\n %pk = getelementptr inbounds i8, ptr %a, i32 %k\n %byte = load i8, ptr %pk, align 1\n"; + if stores { + s += " %w = shl i32 %t, 2\n %pa = getelementptr inbounds i8, ptr %a, i32 %w\n store i32 %t, ptr %pa, align 4\n %pb = getelementptr inbounds [4 x i32], ptr %b, i32 0, i32 %t\n store i32 %t, ptr %pb, align 4\n"; + } + s += " %base = mul i32 %t, 9\n"; + for (j, (x, i)) in [ + ("a", 0), + ("a", 1), + ("a", 2), + ("a", 3), + ("b", 0), + ("b", 1), + ("b", 2), + ("b", 3), + ] + .into_iter() + .enumerate() + { + s += &format!( + " %r{x}{i} = load i32, ptr %i{x}{i}, align 4\n %o{j} = add i32 %base, {j}\n %q{j} = getelementptr inbounds i32, ptr addrspace(1) %out, i32 %o{j}\n store i32 %r{x}{i}, ptr addrspace(1) %q{j}, align 4\n" + ); + } + s += " %bw = zext i8 %byte to i32\n %o8 = add i32 %base, 8\n %q8 = getelementptr inbounds i32, ptr addrspace(1) %out, i32 %o8\n store i32 %bw, ptr addrspace(1) %q8, align 4\n"; + format!( + "define void @{name}(ptr addrspace(1) %out, i32 %t) {{\n{s} ret void\n}}\n\n{}", + KERNEL_MD.replace("NAME", name) + ) +} + +/// A contained store at a run-time offset always runs and adds no block: where its bytes are out +/// of bounds, into the private arena it rewrites word 0 with word 0's own bits, and into a typed +/// alloca it rewrites the element at index 0 as it was, so neither changes a byte. `sunk`, with +/// the stores, has as many blocks as `kept`, without them, and thread `t` reads `t` at word `t` +/// of each object below 4 and `10 + i` at every other word `i`. +#[test] +fn a_run_time_store_rewrites_what_it_does_not_address_and_adds_no_block() { + let Some(sunk) = assemble("sunk", &sink_kernel("sunk", true)) else { + return; + }; + let Some(kept) = assemble("kept", &sink_kernel("kept", false)) else { + return; + }; + for stem in PROFILES { + let prof = p(stem); + l3(&sunk, "sunk", &prof, stem); + let (plan, m) = typed_module(&sunk, "sunk", &prof).expect("module"); + let (_, without) = typed_module(&kept, "kept", &prof).expect("module"); + let local = &plan.families.access.local; + assert_eq!(local.private, Some(16), "{stem}: a in the private arena"); + assert_eq!(local.typed.len(), 1, "{stem}: b typed"); + assert_eq!(m.blocks().len(), without.blocks().len(), "{stem}"); + let res = resources(&plan, 0, 9 * 32, 32, &[]); + let want: Vec = (0..32u32) + .flat_map(|t| { + let word = move |i: u32| if i == t { t } else { 10 + i }; + let k = t & 15; + let byte = if k % 4 == 0 { 10 + k / 4 } else { 0 }; + (0..4).map(word).chain((0..4).map(word)).chain([byte]) + }) + .collect(); + assert_eq!(run_both(&m, &res).expect("run"), want, "{stem}"); + } +} + /// The body of the nested-levels kernel: `c: [3 x [5 x i32]]` (strides 20 and 4) initialized to /// `100 + 5i + j`, a store of `900 + t` at `c[t % 3][7t % 5]`, a store of 777 at `c[t][0]` (out /// of range from `t = 3`), `x = c[(t + 1) % 3][3t % 5]` and `z = c[t][t]` (out of range from `t diff --git a/crates/metal2vulkan/src/tests/engine_device_arena.rs b/crates/metal2vulkan/src/tests/engine_device_arena.rs index a10214291..bff66f2d0 100644 --- a/crates/metal2vulkan/src/tests/engine_device_arena.rs +++ b/crates/metal2vulkan/src/tests/engine_device_arena.rs @@ -21,7 +21,8 @@ //! store at a run-time index, a `float4` load (four words) at a run-time index, and a word load //! at a constant index. Each word is an access chain from the slot's words, placed once //! (`EmitCx::arena_slot`), and a load or store, so each shape stays within its bound on every -//! identity profile. The table of the first profile is printed. +//! identity profile and adds no block: a store whose bytes are out of bounds rewrites word 0 as +//! it was. The table of the first profile is printed. //! //! `llvm-as` assembles the kernels; without it the tests skip visibly. @@ -294,17 +295,17 @@ fn shapes_module() -> (String, Vec<(String, String)>) { (text, names) } -/// Each shape's instructions for one access on profile `p`, or `None` where the profile keeps the -/// arena out of device memory. +/// Each shape's instructions and blocks for one access on profile `p`, or `None` where the profile +/// keeps the arena out of device memory. fn measure( bc: &[u8], names: &[(String, String)], stem: &str, p: &crate::device::DeviceProfile, -) -> Option> { +) -> Option> { let mut costs = Vec::new(); for (one, two) in names { - let mut weights = [0u64; 2]; + let mut weights = [(0u64, 0usize); 2]; for (w, n) in weights.iter_mut().zip([one, two]) { let (a, plan, module) = compile_kept(bc, n, p).unwrap_or_else(|e| panic!("{stem} {n}: {e}")); @@ -312,15 +313,20 @@ fn measure( if !plan.families.access.local.private_device { return None; } - *w = entry_weight(&module, &mut meter()).expect("a weight"); + let weight = entry_weight(&module, &mut meter()).expect("a weight"); + *w = (weight, module.blocks().len()); } - costs.push(weights[1].saturating_sub(weights[0])); + costs.push(( + weights[1].0.saturating_sub(weights[0].0), + weights[1].1.saturating_sub(weights[0].1), + )); } Some(costs) } -/// Each access of the arena's words costs at most its shape's bound, on every identity profile -/// that keeps the arena in device memory. +/// Each access of the arena's words costs at most its shape's bound and adds no block, a store at +/// a run-time index included (out of bounds it rewrites word 0 as it was), on every identity +/// profile that keeps the arena in device memory. #[test] fn an_arena_word_is_one_access_chain_and_one_load_or_store() { let (text, names) = shapes_module(); @@ -334,18 +340,19 @@ fn an_arena_word_is_one_access_chain_and_one_load_or_store() { }; if !printed { printed = true; - eprintln!("one arena access on {stem}: instructions"); - for (shape, cost) in SHAPES.iter().zip(&costs) { - eprintln!(" {:<40} {cost:>4}", shape.name); + eprintln!("one arena access on {stem}: instructions, blocks"); + for (shape, (cost, blocks)) in SHAPES.iter().zip(&costs) { + eprintln!(" {:<40} {cost:>4} {blocks:>2}", shape.name); } } - for (shape, cost) in SHAPES.iter().zip(&costs) { + for (shape, &(cost, blocks)) in SHAPES.iter().zip(&costs) { assert!( - *cost <= shape.bound, + cost <= shape.bound, "{stem}: {} costs {cost} instructions, over {}", shape.name, shape.bound ); + assert_eq!(blocks, 0, "{stem}: {} adds blocks", shape.name); } } assert!( diff --git a/crates/metal2vulkan/src/tests/engine_typed_clamp.rs b/crates/metal2vulkan/src/tests/engine_typed_clamp.rs index 8d1429eb0..16c340334 100644 --- a/crates/metal2vulkan/src/tests/engine_typed_clamp.rs +++ b/crates/metal2vulkan/src/tests/engine_typed_clamp.rs @@ -9,9 +9,9 @@ //! offset, and every enclosing array level is recovered with them. //! - An out-of-range dynamic index, from a buffer (past the end, and -1), on a load of a constant //! object reaches its level's last element. On a typed alloca the access is checked: the load -//! reads zero and the store is dropped. The neighbouring object is untouched, and an in-range -//! index on each kind reads every element as stored. A threadgroup object's accesses are not -//! contained: one past the object is undefined, as in Metal. +//! reads zero and the store rewrites element 0 as it was. The neighbouring object is untouched, +//! and an in-range index on each kind reads every element as stored. A threadgroup object's +//! accesses are not contained: one past the object is undefined, as in Metal. //! - The tiled matrix product of a kernel's two `float[16][16]` threadgroup tiles, every access //! lined up, answers the CPU's fused multiply-adds in the kernel's order bit for bit. //! @@ -339,9 +339,9 @@ const SECOND: u32 = 0x4200_0000; const STORED: u32 = 0x4300_0000; /// An out-of-range dynamic index never leaves its object. A constant object's load reaches the -/// level's last element; a typed alloca's are checked, the load reading zero and the store dropped, -/// so the alloca's last element keeps its value. The neighbouring object keeps its elements, and -/// every in-range element reads back as stored. +/// level's last element; a typed alloca's are checked, the load reading zero and the store +/// rewriting element 0 as it was, so every element of the alloca keeps its value. The neighbouring +/// object keeps its elements, and every in-range element reads back as stored. #[test] fn an_out_of_range_index_stays_inside_its_object() { // Two typed allocas of the thread's own, filled by constant-index stores. @@ -408,7 +408,7 @@ entry: if got.is_empty() { return; } - // A checked store was dropped and a checked load read zero; a clamped out-of-range + // A checked store changed nothing and a checked load read zero; a clamped out-of-range // load reads the first object's last element. The second object is untouched. let last = FIRST + 7; let loaded = if checked { 0 } else { last };