From 4232d4ed9b6017d138ade1a048bd2a82d1a87277 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Tue, 17 Nov 2026 16:17:01 -0800 Subject: [PATCH] translator: every slot held to 4 is reached from its address as it is Under the identity domains a device-address slot whose argument's alignment is at least 4 now takes the direct form whatever its window: each access is the slot's address plus its 32-bit byte offset from the bind address, sign-extended. The runtime makes no buffer longer than 2 GiB (MAX_BUFFER_LENGTH), so every byte of a buffer lies within 2^31 bytes of each bind address in it and the sign extension is exact. The window no longer picks the form, and the offset is taken from the bind address rather than the window's start, so the start's 64-bit add and 32-bit subtract go and the start need not be a multiple of 16 (the alignment proofs are from the bind address). DIRECT_WINDOW and direct_window are deleted, and so is the test of accesses past 2 GiB, which the 2 GiB cap puts outside every buffer; the interpreter test of accesses up to 2 GiB stays. Slots held to less than 4 keep the word form. The word-phase alignment test now expects one uvec4 in every slot held to 16, its Whole window included. SEMANTICS_VERSION 2166: identity-domain modules change. --- crates/metal2vulkan/src/lower/access/emit.rs | 2 +- crates/metal2vulkan/src/lower/access/mod.rs | 36 ++-- crates/metal2vulkan/src/lower/access/psb.rs | 47 ++--- .../src/tests/engine_offsets_past_2gib.rs | 174 ------------------ .../src/tests/engine_word_phases.rs | 21 +-- crates/metal2vulkan/src/tests/mod.rs | 1 - docs/API.md | 12 +- 7 files changed, 41 insertions(+), 252 deletions(-) delete mode 100644 crates/metal2vulkan/src/tests/engine_offsets_past_2gib.rs diff --git a/crates/metal2vulkan/src/lower/access/emit.rs b/crates/metal2vulkan/src/lower/access/emit.rs index 943851d1f..e93810ce6 100644 --- a/crates/metal2vulkan/src/lower/access/emit.rs +++ b/crates/metal2vulkan/src/lower/access/emit.rs @@ -282,7 +282,7 @@ pub(super) fn prepare( let address = cx.push_field(fb, PushField::SlotGuestBase(choice.slot))?; let address = super::pointer::slot_guest_base_u64(fb, address)?; match aligned { - true => psb::prepare_direct(fb, address, m, start)?, + true => psb::prepare_direct(address, m), false => psb::prepare_at(fb, address, m, start)?, } } else { diff --git a/crates/metal2vulkan/src/lower/access/mod.rs b/crates/metal2vulkan/src/lower/access/mod.rs index 13c022791..60998a33d 100644 --- a/crates/metal2vulkan/src/lower/access/mod.rs +++ b/crates/metal2vulkan/src/lower/access/mod.rs @@ -762,11 +762,11 @@ pub struct AccessPlan { /// uniform read is a scalar load). pub unwritten: BTreeSet, /// Memory-plan slots reached under the identity domains from their address as it is, which - /// the binder holds to a multiple of their argument's alignment ([`address_alignment`], - /// `RuntimeFact::AddressAlignment`), and whose window the analysis bounds to at most 2 GiB - /// (`DIRECT_WINDOW`): no access rounds the address (`psb::prepare_direct`), and `uvec2` and - /// `uvec4` units are taken at offsets proven multiples of their size. Every other - /// device-address slot is reached from the word below each access (`psb::prepare_at`). + /// the binder holds to a multiple of their argument's alignment, at least 4 + /// ([`address_alignment`], `RuntimeFact::AddressAlignment`): no access rounds the address + /// (`psb::prepare_direct`), and `uvec2` and `uvec4` units are taken at offsets proven + /// multiples of their size. Every other device-address slot is reached from the word below + /// each access (`psb::prepare_at`). pub aligned: BTreeSet, /// The units ([`Units`]) the static-root accesses of each slot read or write whole, by /// memory-plan slot index: narrow units whose storage access the profile has, and `uvec2` @@ -1622,15 +1622,15 @@ fn place_slots(cx: &mut SelectCx<'_>, m: &mut Meter) -> Result BufferForm::Descriptor(descriptor_view(*kind)), - SlotLowering::Psb { start } => { + SlotLowering::Psb { .. } => { addressed_slot(cx, plan.slot); if let Some(align) = address_alignment(cx, plan) { cx.facts.insert(RuntimeFact::AddressAlignment { slot: plan.slot, align, }); - // A word memory's base is a multiple of 4, and of 16 for its vector units. - if align >= 4 && start % 16 == 0 && direct_window(*window) { + // A word memory's base is a multiple of 4. + if align >= 4 { cx.families.access.aligned.insert(i); } } @@ -1696,28 +1696,14 @@ fn place_slots(cx: &mut SelectCx<'_>, m: &mut Meter) -> Result bool { - matches!(window, Window::Bounded { len, .. } if len <= DIRECT_WINDOW) -} - /// The alignment (2, 4, 8 or 16) the binder holds a device-address slot's address to under the /// identity domains: its argument's `air.arg_type_align_size`, at most 16. Metal's API validation /// refuses a buffer bound at an offset that is not a multiple of its argument type's alignment /// ("must be a multiple of 4 but was set to 2" for a `uint *` argument, "of 16 ... 8" for a /// `float4 *`, "of 2 ... 1" for a `ushort *`; `probes/vector_access_placement.m` in the conformance -/// crate). A slot whose alignment is at least 4 and whose window starts at a multiple of 16 and -/// is at most [`DIRECT_WINDOW`] long is then reached from its address as it is -/// ([`AccessPlan::aligned`]). `None` for a buffer-table -/// element, an argument buffer, and an argument with no alignment or one of 1. +/// crate). A slot whose alignment is at least 4 is then reached from its address as it is +/// ([`AccessPlan::aligned`]). `None` for a buffer-table element, an argument buffer, and an +/// argument with no alignment or one of 1. fn address_alignment(cx: &SelectCx<'_>, plan: &SlotPlan) -> Option { if !identity(cx.profile) || plan.element.is_some() || plan.argument_buffer { return None; diff --git a/crates/metal2vulkan/src/lower/access/psb.rs b/crates/metal2vulkan/src/lower/access/psb.rs index 070513ba3..e89bddc6d 100644 --- a/crates/metal2vulkan/src/lower/access/psb.rs +++ b/crates/metal2vulkan/src/lower/access/psb.rs @@ -173,8 +173,9 @@ enum Reach { /// From a slot's own device address under the identity domains ([`prepare_direct`]): each /// unit at that address plus its 32-bit byte offset sign-extended, in 64-bit integers, then /// one `OpConvertUToPtr` to the unit's block (`NonWritable` for a load of an unwritten slot). - /// The offset is below 2^31, the window being at most `DIRECT_WINDOW`, so the sign extension - /// is exact. It is the integer form of an access chain's signed index, which a device adds as + /// Every byte of a buffer lies within 2^31 bytes of each bind address in it, the runtime + /// making no buffer longer than 2 GiB (`metal2vulkan_rt::MAX_BUFFER_LENGTH`), so the sign + /// extension is exact. It is the integer form of an access chain's signed index, which a device adds as /// it would that index: no shift of the offset in 64 bits, no zero-extended offset to split /// into a scalar base and a vector one, and no pointer bitcast. Direct, @@ -208,39 +209,23 @@ pub fn prepare_at( }) } -/// Prepare an access of a static slot whose window starts at `start` at the `u32` displacement -/// `m` from its bind offset, under the identity domains, from `address` (a `u64`), the slot's own -/// device address, which the binder holds to a multiple of 16 or of the argument's alignment -/// (`RuntimeFact::AddressAlignment`), and `start` a multiple of 16: the access is the byte offset -/// `m − start` (in 32 bits, below 2^31 as the window is at most 2 GiB long, `DIRECT_WINDOW`) -/// from `address + start`, as a descriptor view's is `m` from its base. -/// Nothing is rounded, so a constant offset is one immediate. Uncontained, as Metal contains no -/// device-address access. -pub fn prepare_direct( - fb: &mut FunctionBuilder<'_>, - address: Value, - m: Value, - start: i64, -) -> BResult { - let (base, off) = match start { - 0 => (address, m), - // `m − start` modulo 2^32 from `address + start` (its two's-complement bits are its value - // modulo 2^64). - _ => { - let k = k64(fb, start as u64)?; - let base = fb.binary(BinOp::IAdd, address, k)?; - let k = crate::memory::leaf::k32(fb, start as u32)?; - (base, crate::memory::leaf::u32_op(fb, BinOp::ISub, m, k)?) - } - }; - Ok(PsbAccess { +/// Prepare an access of a static slot at the `u32` displacement `m` from its bind offset, under +/// the identity domains, from `address` (a `u64`), the slot's own device address, which the +/// binder holds to a multiple of the argument's alignment (`RuntimeFact::AddressAlignment`): the +/// access is the byte offset `m`, read as signed, from `address`, as a descriptor view's is `m` +/// from its base. Every byte of a buffer lies within 2^31 bytes of each bind address in it, the +/// runtime making no buffer longer than 2 GiB (`metal2vulkan_rt::MAX_BUFFER_LENGTH`), so the +/// offset is exact whatever the slot's window. Nothing is rounded, so a constant offset is one +/// immediate. Uncontained, as Metal contains no device-address access. +pub fn prepare_direct(address: Value, m: Value) -> PsbAccess { + PsbAccess { mem: PsbMem { reach: Reach::Direct, - ..PsbMem::at(base) + ..PsbMem::at(address) }, - off, + off: m, inb: None, - }) + } } /// The narrow units a device-address memory loads and stores directly on profile `p`: the 1- and diff --git a/crates/metal2vulkan/src/tests/engine_offsets_past_2gib.rs b/crates/metal2vulkan/src/tests/engine_offsets_past_2gib.rs deleted file mode 100644 index 0e12f1340..000000000 --- a/crates/metal2vulkan/src/tests/engine_offsets_past_2gib.rs +++ /dev/null @@ -1,174 +0,0 @@ -//! A buffer argument's offsets are Metal's unsigned 32-bit ones under the identity domains, which -//! reach every buffer through its device address (`lower::access::psb`): an access 2 GiB and more -//! past the bind offset lands there, not 4 GiB below, where a signed 32-bit access-chain index -//! would place it. The CPU interpreter takes an access chain's index as signed, as SPIR-V does, -//! and traps on an address that lies in no buffer. On it, `ob1_storage_buffer` loads and stores at -//! word indices on both sides of 2^29 through slots whose bytes are two buffers, one at the bind -//! address and one around 2 GiB past it. The direct form, whose sign-extended offsets are exact -//! below 2 GiB only, takes a window of at most 2 GiB. -//! -//! `llvm-as` assembles the fixture; without it the test skips visibly. - -use std::collections::BTreeMap; - -use super::engine_word_phases::identity_profiles; -use crate::lower::dispatch::region_bytes; -use crate::pipeline::interface::PushLoc; -use crate::pipeline::sym::{Axis, PushField, SpecKey}; -use crate::pipeline::testing::{compile_kept, engine_dir, llvm_assemble, AssembleError}; -use crate::spirv::interp::{run, Buffer, Config, Resources}; - -const FIXTURE: &str = "ob1_storage_buffer"; -const THREADS: u32 = 8; -/// The word at byte 2 GiB of the slot. -const AT_2_GIB: u32 = 1 << 29; -/// The device address of the index buffer, and the one `src` and `out` are both bound at. -const IDX: u64 = 0x1_0000_0000; -const SLOT: u64 = 0x2_0000_0000; -/// The slot's words in the interpreter's buffers: the first 1024 at `SLOT`, and those from -/// `HIGH` on, 16 below 2 GiB to 64 KiB past it, at `SLOT + 4 * HIGH`. -const LOW_WORDS: u32 = 1024; -const HIGH: u32 = AT_2_GIB - 16; -const HIGH_WORDS: u32 = 16 + (64 << 10) / 4; - -/// Thread `t` loads `src[LOADS[t]]` into `out[t]` and stores `0xA0000000 | t` to -/// `out[STORES[t]]`: one load and one store below 2 GiB, the rest from the word below it to the -/// last word of the high range. -const LOADS: [u32; 8] = [ - 64, - AT_2_GIB - 1, - AT_2_GIB, - AT_2_GIB + 1, - AT_2_GIB + 2, - AT_2_GIB + 3, - AT_2_GIB + 4096, - HIGH + HIGH_WORDS - 1, -]; -const STORES: [u32; 8] = [ - 128, - AT_2_GIB - 2, - AT_2_GIB + 8, - AT_2_GIB + 9, - AT_2_GIB + 10, - AT_2_GIB + 11, - AT_2_GIB + 8000, - HIGH + HIGH_WORDS - 2, -]; - -/// The interpreter buffer (1 low, 2 high) and byte offset in it of slot word `word`. -fn at(word: u32) -> (usize, usize) { - match word { - w if w < LOW_WORDS => (1, 4 * w as usize), - w => (2, 4 * (w - HIGH) as usize), - } -} - -#[test] -fn accesses_past_2_gib_land_at_their_own_words() { - let bc = match llvm_assemble(&engine_dir().join(format!("{FIXTURE}.ll"))) { - Ok(b) => b, - Err(AssembleError::Missing(why)) => { - eprintln!("SKIPPED: {why}"); - return; - } - Err(e) => panic!("{FIXTURE}: {e:?}"), - }; - for (stem, p) in identity_profiles() - .iter() - .filter(|(s, _)| s == "lavapipe" || s == "moltenvk-m3") - { - let (_, plan, module) = - compile_kept(&bc, FIXTURE, p).unwrap_or_else(|e| panic!("{stem}: {e}")); - let mut push = vec![0u8; plan.push.push_range.map_or(0, |(_, end)| end as usize)]; - let region = region_bytes([0; 3], [THREADS, 1, 1], [THREADS, 1, 1]).expect("packs"); - for f in &plan.push.fields { - let PushLoc::Push { offset } = f.loc else { - panic!("{stem}: {f:?} spilled"); - }; - let o = offset as usize; - match f.field { - PushField::SlotGuestBase(s) => { - let address = if s.index == 0 { IDX } else { SLOT }; - push[o..o + 8].copy_from_slice(&address.to_le_bytes()); - } - PushField::DispatchRegion => push[o..o + 32].copy_from_slice(®ion), - _ => panic!("{stem}: unexpected push field {f:?}"), - } - } - let mut bytes = [ - LOADS - .iter() - .chain(&STORES) - .flat_map(|w| w.to_le_bytes()) - .collect(), - vec![0u8; 4 * LOW_WORDS as usize], - vec![0u8; 4 * HIGH_WORDS as usize], - ]; - for (t, &word) in LOADS.iter().enumerate() { - let (b, o) = at(word); - bytes[b][o..o + 4].copy_from_slice(&(0x5000_0000 | t as u32).to_le_bytes()); - } - let spec = BTreeMap::from([ - (SpecKey::LocalSize(Axis::X), u64::from(THREADS)), - (SpecKey::LocalSize(Axis::Y), 1), - (SpecKey::LocalSize(Axis::Z), 1), - (SpecKey::FlatLocalSize, u64::from(THREADS)), - ]); - let res = Resources { - buffers: [IDX, SLOT, SLOT + 4 * u64::from(HIGH)] - .into_iter() - .zip(bytes) - .map(|(address, bytes)| Buffer { - slot: None, - address: Some(address), - bytes, - }) - .collect(), - push, - spec, - }; - let got = run(&module, &Config::default(), res).unwrap_or_else(|e| { - panic!("{stem}: loads at {LOADS:#x?}, stores at {STORES:#x?}: {e}") - }); - let word = |w: u32| { - let (b, o) = at(w); - u32::from_le_bytes(got.buffers[b][o..o + 4].try_into().expect("a word")) - }; - let loaded: Vec = (0..THREADS).map(word).collect(); - let want: Vec = (0..THREADS).map(|t| 0x5000_0000 | t).collect(); - assert_eq!(loaded, want, "{stem}: the loads at {LOADS:#x?}"); - for (t, &w) in STORES.iter().enumerate() { - assert_eq!( - word(w), - 0xA000_0000 | t as u32, - "{stem}: the store to word {w:#x}" - ); - } - } -} - -/// The direct form's choice (`lower::access::direct_window`): a `Bounded` window of exactly -/// 2 GiB takes it, every byte offset in it below 2^31 so that its sign extension is exact; one a -/// byte longer does not, nor does a `Whole` one. -#[test] -fn the_direct_form_takes_windows_of_at_most_2_gib() { - use crate::lower::access::direct_window; - use crate::pipeline::interface::Window; - for start in [0, -16, 64] { - assert!( - direct_window(Window::Bounded { - start, - len: 1 << 31 - }), - "start {start}" - ); - assert!( - !direct_window(Window::Bounded { - start, - len: (1 << 31) + 1 - }), - "start {start}" - ); - } - assert!(!direct_window(Window::Whole)); -} diff --git a/crates/metal2vulkan/src/tests/engine_word_phases.rs b/crates/metal2vulkan/src/tests/engine_word_phases.rs index 8d359bf66..69c6f4b90 100644 --- a/crates/metal2vulkan/src/tests/engine_word_phases.rs +++ b/crates/metal2vulkan/src/tests/engine_word_phases.rs @@ -21,7 +21,7 @@ use crate::device::{Device, DevicePolicy}; use crate::library::FunctionConstantValues; use crate::lower::dispatch::region_bytes; use crate::pipeline::facts::RuntimeFact; -use crate::pipeline::interface::{PushLoc, SlotInterface}; +use crate::pipeline::interface::PushLoc; use crate::pipeline::sym::{Axis, PushField, SpecKey}; use crate::pipeline::testing::{ compile, compile_kept, description, engine_dir, link_and_validate, llvm_assemble, meter, @@ -134,10 +134,9 @@ fn device_alignments(words: &[u32]) -> Vec { /// Every device-address load and store of the two kernels claims at most the alignment the /// translator proves for its address: 4 where the buffer is a `uint` one Metal binds at any /// multiple of 4, whatever the `align 16` of the AIR's `uint4` and `float4` accesses through it, -/// and 16 where it is a `float4` one. The access is one `uvec4` there only where the slot is -/// reached from its address as it is (`lower::access::direct_window`: a window bounded to at most -/// 2 GiB); a `Whole` window, which an access may reach past 2 GiB, keeps the word form. Each -/// argument states its alignment (`RuntimeFact::AddressAlignment`). Each module passes L3. +/// and 16 where it is a `float4` one, where the access is one `uvec4`: a slot held to at least 4 +/// is reached from its address as it is, whatever its window. Each argument states its alignment +/// (`RuntimeFact::AddressAlignment`). Each module passes L3. #[test] fn device_accesses_claim_at_most_the_proven_alignment() { let Some(bc) = bitcode() else { @@ -171,17 +170,11 @@ fn device_accesses_claim_at_most_the_proven_alignment() { claimed.iter().all(|&c| (4..=align).contains(&u64::from(c))), "{what}: claimed {claimed:?}, proven {align}" ); - // A `float4` access at an offset proven a multiple of 16 is one `uvec4` access where - // its slot's window takes the direct form, and words where it does not. - let direct = (a.interface.slots.values()).all(|s| match s { - SlotInterface::Buffer(b) => crate::lower::access::direct_window(b.window), - _ => true, - }); - let unit = if direct { align } else { 4 }; + // A `float4` access at an offset proven a multiple of 16 is one `uvec4` access. assert_eq!( claimed.iter().max().copied().map(u64::from), - Some(unit), - "{what}: claimed {claimed:?}, proven {align}, direct {direct}" + Some(align), + "{what}: claimed {claimed:?}, proven {align}" ); // Both arguments state their alignment, which the binder holds their addresses to. let stated: Vec = (a.facts.iter()) diff --git a/crates/metal2vulkan/src/tests/mod.rs b/crates/metal2vulkan/src/tests/mod.rs index 22c6e2dfc..23b70b488 100644 --- a/crates/metal2vulkan/src/tests/mod.rs +++ b/crates/metal2vulkan/src/tests/mod.rs @@ -120,7 +120,6 @@ mod engine_not_mipmapped_anisotropic; mod engine_nullable_private; mod engine_nuw; mod engine_offset_arms; -mod engine_offsets_past_2gib; mod engine_offsets_to_2gib; mod engine_opencl_mode; mod engine_padded_blends; diff --git a/docs/API.md b/docs/API.md index 4b3afc39a..692e08e86 100644 --- a/docs/API.md +++ b/docs/API.md @@ -113,14 +113,14 @@ compile does. `DevicePolicy::default()` is `DevicePolicy::UNTRUSTED`: them a buffer slot is reached at its own device address (`gpuAddress` plus the bind offset), pushed as `PushField::SlotGuestBase`, with no root table, no descriptor and no containment, as Metal contains no device-address access. A slot whose argument states an alignment of at least - 4 (`air.arg_type_align_size`) and whose window the translator bounds to at most 2 GiB is reached - from that address as it is: each access is at the address plus its 32-bit byte offset, - sign-extended (exact below 2 GiB), and an access of 8 or 16 bytes at an offset proven a - multiple of its size is one `uvec2` or `uvec4`. The function states + 4 (`air.arg_type_align_size`) is reached from that address as it is: each access is at the + address plus its 32-bit byte offset, sign-extended, which is exact as the new runtime makes no + buffer longer than 2 GiB (`MAX_BUFFER_LENGTH`), and an access of 8 or 16 bytes at an offset + proven a multiple of its size is one `uvec2` or `uvec4`. The function states `RuntimeFact::AddressAlignment` with that alignment (at most 16), and a binder refuses a binding whose address is not a multiple of it, as Metal's API validation refuses the bind offset. Any - other slot (an argument with no alignment or one below 4, or a window no access bounds) is - reached from the word below each access, its offset zero-extended (exact to 4 GiB). Fields past a kernel's push window (128 bytes; 256 on + other slot (an argument with no alignment or one below 4) is reached from the word below each + access, its offset zero-extended. Fields past a kernel's push window (128 bytes; 256 on a device made by `Device::from_queries`, whose runtime's floor requires that much `maxPushConstantsSize`: a dispatch region and 28 buffer addresses) go to a parameter block in memory, read at the device address `PushField::ArgumentTableAddress`, which