diff --git a/crates/metal2vulkan-rt/README.md b/crates/metal2vulkan-rt/README.md index b33a8a5eb..396775387 100644 --- a/crates/metal2vulkan-rt/README.md +++ b/crates/metal2vulkan-rt/README.md @@ -98,8 +98,11 @@ them over this crate's items: - `Device::argument_buffers_support` is `MTLArgumentBuffersTier2` on every device above the floor, which holds buffer device addresses and the set-1 arrays' runtime descriptor arrays, partial binding and update-after-bind of sampled and storage images. The device tests - `argument_tier` read and write the writable textures an argument buffer holds, and read - through an argument buffer a kernel wrote and a Private one. Some forms both tiers promise are + `argument_tier` read and write the writable textures an argument buffer holds, read through + an argument buffer a kernel wrote and a Private one, read the texture of an argument buffer a + pointer member reaches, read buffers through an argument buffer's pointer members and through a + `gpuAddress` the CPU wrote into a buffer, and answer a buffer argument's pointer converted to + an integer as its `gpuAddress` plus the offsets. Some forms both tiers promise are refused at the making of a state (the known gaps of pipeline states). ### Teardown @@ -857,8 +860,11 @@ the Direct3D 11 texture's payload until it is freed. without device addresses): 0.27 to 0.51 ms a MB across the runs. A buffer in the exported allocation takes the same GPU time at its first fill as at its second, 14.15 and 14.09 ms at P010's size. The ready wait is 1.12 and 0.61 ms. -- A shader uses a buffer's `gpuAddress` directly, unchecked: a stale one, of a released buffer, can - still fault the device. +- A shader uses a buffer's `gpuAddress` directly, unchecked, wherever the program holds one: a + pointer member of an argument buffer, an address it wrote into a buffer, a pointer it made from + an integer. The stored word must be a buffer's `gpu_address` plus an offset inside that buffer, + and a buffer the consumer did not place at the address its guest asked for has a `gpu_address` + other than that one. A stale address, of a released buffer, can still fault the device. - An app buffer too large for the consumer's map budget is copied, on drivers whose dma-buf query offers a non-host-visible type first. - A block freed before a submission used it waits on the block-maker thread for its bind, and a @@ -2387,18 +2393,6 @@ or does not check is rebuilt from the generations' names, with young counted ful domains, which every state is translated under: a state over a function that holds one is `Error::Translation` of `Unsupported{IdentityDomains}`, not implemented, whose symbol names the first form it holds. By form: - - tier 2's pointer indexing to a texture: a texture behind a pointer member of an argument - buffer, read in the argument buffer that pointer reaches, whose plan reads the root table - ("an encoder value the function reads as RootTableAddress"). The translator test - `a_texture_of_an_argument_buffer_a_pointer_member_reaches_is_refused_under_the_identity_domains` - and the device test `argument_tier` assert it; - - a buffer reached through a pointer member of an argument buffer, or through a `gpuAddress` - the program stored in a buffer, and a pointer the function makes from an integer, whose - plan reads the root table as the pointer indexing above does (the same symbol): a plain - kernel that reads a buffer through an argument buffer's pointer member is refused so. No - test yet; - - a kernel that turns a buffer argument's pointer into an integer, which the translator takes - as a wide pointer read through the root table (the same symbol): no test yet; - a sample, gather or comparison of an argument buffer's texture, and a depth texture of one both compared and sampled without comparison: no test yet; - an argument buffer's sampler, and an array of samplers: no test yet; diff --git a/crates/metal2vulkan-rt/src/tests/argument_tier.rs b/crates/metal2vulkan-rt/src/tests/argument_tier.rs index ef8875a87..e519e808c 100644 --- a/crates/metal2vulkan-rt/src/tests/argument_tier.rs +++ b/crates/metal2vulkan-rt/src/tests/argument_tier.rs @@ -9,13 +9,15 @@ //! - an argument buffer the CPU cannot reach: a Private buffer a blit filled, which `ab_read` //! reads through; //! - pointer indexing, and an argument buffer that points at others: `ab_indexed`'s thread `g` -//! reads the texture of element `g` of an array of argument buffers a pointer member reaches. -//! The translator's identity domains, which every state the runtime makes is translated under, -//! do not lower that read yet (its plan reads the root table): the state is a typed refusal -//! naming the form, a known gap of the runtime's README, and the test asserts it. +//! reads the texture of element `g` of an array of argument buffers a pointer member reaches; +//! - buffers behind device addresses (`ab_pointers`): `ab_sum` adds two buffers an argument +//! buffer's two pointer members reach, `ab_address` reads a buffer through a `gpuAddress` the +//! CPU wrote into a constant buffer, and `ab_slot_address` stores a slot pointer converted to an +//! integer, which is the slot's `gpuAddress` plus its offsets. //! -//! The program writes each texture member itself, as the texture's `gpuResourceID`, as tier 2's -//! layout lets it. The floor holds every feature tier 2 rests on (buffer device addresses, and the +//! The program writes each texture member itself, as the texture's `gpuResourceID`, and each +//! pointer member as the buffer's `gpu_address` plus the offset an encoder's `setBuffer:offset:` +//! names, as tier 2's layout lets it. The floor holds every feature tier 2 rests on (buffer device addresses, and the //! set-1 arrays' runtime descriptor arrays, partial binding and update-after-bind of sampled and //! storage images), so the tier is a floor fact. //! @@ -26,11 +28,10 @@ mod on_device { use crate::tests::command::on_device::{each_device, finished}; use crate::{ ArgumentBuffersTier, Block, Buffer, ComputePipelineDescriptor, ComputePipelineState, - Device, DispatchType, Error, FunctionDescriptor, IndexClass, Library, MemoryClass, - PixelFormat, Region, Resource, ResourceUsage, StageSource, Texture, TextureDescriptor, - TextureType, TextureUsage, + Device, DispatchType, FunctionDescriptor, IndexClass, Library, MemoryClass, PixelFormat, + Region, Resource, ResourceUsage, StageSource, Texture, TextureDescriptor, TextureType, + TextureUsage, }; - use metal2vulkan::error::{Feature, Needs}; use metal2vulkan_devtools::{engine_dir, llvm_assemble, AssembleError}; /// The fixture `name`'s library, or None where `llvm-as` is missing. @@ -318,44 +319,203 @@ mod on_device { }); } - /// The form the identity domains' refusal of `ab_indexed` names: its plan reads the texture - /// handle through the root table, whose address they do not push. - const POINTER_INDEXED_FORM: &str = "an encoder value the function reads as RootTableAddress"; - - /// The bound argument buffer holds the address of an array of argument buffers, each holding a - /// texture, and thread `g` reads the texture of element `g` (`ab_indexed`): the state is the - /// translator's typed refusal, `Unsupported{IdentityDomains}`, not implemented, naming the - /// form ([`POINTER_INDEXED_FORM`]). + /// The bound argument buffer holds the address of an array of four argument buffers, each + /// holding a texture, and thread `g` reads texel (0, 0) of the texture of element `g` + /// (`ab_indexed`). #[test] - fn every_device_refuses_the_texture_an_argument_buffer_a_pointer_member_reaches_holds() { + fn every_device_reads_the_texture_an_argument_buffer_a_pointer_member_reaches_holds() { let Some(library) = library("ab_tier2") else { return; }; each_device("argument_tier_indexed", |name, _, device| { - let function = library.function("ab_indexed").expect("the kernel"); - let descriptor = ComputePipelineDescriptor::new(StageSource::Function( - FunctionDescriptor::new(function), - )); - let made = device - .new_compute_pipeline_state(&descriptor, |samplers| Ok(vec![0; samplers.len()])); - match made { - Err(Error::Translation(metal2vulkan::error::Error::Unsupported(refusal))) => { - assert_eq!( - (refusal.feature, refusal.needs), - (Feature::IdentityDomains, Needs::NotImplemented), - "{name}" - ); - assert_eq!( - refusal.symbol.map(|form| form.to_string()).as_deref(), - Some(POINTER_INDEXED_FORM), - "{name}" - ); - } - other => panic!("{name}: {:?}", other.map(|_| "a state")), + let read = state(name, &device, &library, "ab_indexed"); + let grant = (device.grant_indices(IndexClass::Texture, 1, 4)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let textures: Vec = (TEXELS.iter().zip(1..)) + .map(|(texel, index)| texture(name, &device, 1, index, std::slice::from_ref(texel))) + .collect(); + let mut shared = Shared::new(&device); + let ids: Vec = (textures.iter()) + .flat_map(|t| t.gpu_resource_id().to_bits().to_le_bytes()) + .collect(); + let held = shared.of(&device, &ids); + let table = shared.of(&device, &held.gpu_address().to_le_bytes()); + let out = shared.of(&device, &[0; 64]); + 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(&read).expect("a state"); + encoder.set_buffer(Some(&table), 0, 0).expect("table"); + encoder.set_buffer(Some(&out), 0, 1).expect("out"); + (encoder.use_resource(Resource::Buffer(&held), ResourceUsage::READ)) + .expect("the held argument buffers"); + for texture in &textures { + (encoder.use_resource(Resource::Texture(texture), ResourceUsage::READ)) + .expect("a texture"); } - println!( - "{name}: ab_indexed refused under the identity domains: {POINTER_INDEXED_FORM}" + (encoder.dispatch_threadgroups([1, 1, 1], [4, 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}"); + assert_eq!(float4s(&out, 4), TEXELS, "{name}"); + drop((textures, command_buffer)); + (device.release_indices(grant)).unwrap_or_else(|error| panic!("{name}: {error}")); + println!("{name}: the textures argument buffers a pointer member reaches hold, read"); + }); + } + + /// Threads of `ab_pointers`' kernels, in two threadgroups. + const THREADS: u32 = 64; + + /// The `count` words at the start 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 of `T`, at its start, which is 256-byte aligned. + unsafe { std::slice::from_raw_parts(contents.as_ptr().cast::(), count) }.to_vec() + } + + /// The bytes of `values`. + fn u32_bytes(values: impl IntoIterator) -> Vec { + values.into_iter().flat_map(u32::to_le_bytes).collect() + } + + /// One dispatch of `state` over [`THREADS`] threads, with `bound` at buffer indices 0 and 1 + /// and `used` made resident (`useResource`, read). + fn dispatch( + name: &str, + device: &Device, + state: &ComputePipelineState, + bound: [&Buffer; 2], + used: &[&Buffer], + ) { + 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("a state"); + for (index, buffer) in (0..).zip(bound) { + encoder + .set_buffer(Some(buffer), 0, index) + .expect("a buffer"); + } + for buffer in used { + (encoder.use_resource(Resource::Buffer(buffer), ResourceUsage::READ)) + .expect("a buffer"); + } + (encoder.dispatch_threadgroups([2, 1, 1], [THREADS / 2, 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}"); + } + + /// An argument buffer whose two pointer members, as an argument encoder writes them at index + /// 0, hold the addresses of two buffers, the second 16 bytes past its buffer's start: thread + /// `i` stores `a[i] + b[i]` (`ab_sum`). + #[test] + fn every_device_sums_the_buffers_an_argument_buffers_pointer_members_reach() { + let Some(library) = library("ab_pointers") else { + return; + }; + each_device("argument_tier_pointer_members", |name, _, device| { + let sum = state(name, &device, &library, "ab_sum"); + let mut shared = Shared::new(&device); + let a = shared.of(&device, &u32_bytes((0..THREADS).map(|k| 0x1000 + k))); + let b = shared.of( + &device, + &u32_bytes((0..THREADS + 4).map(|k| 0x7000_0000 + 3 * k)), ); + let members: Vec = [a.gpu_address(), b.gpu_address() + 16] + .iter() + .flat_map(|address| address.to_le_bytes()) + .collect(); + let args = shared.of(&device, &members); + let out = shared.of(&device, &u32_bytes((0..THREADS).map(|_| 0))); + dispatch(name, &device, &sum, [&args, &out], &[&a, &b]); + let want: Vec = (0..THREADS) + .map(|i| (0x1000 + i) + (0x7000_0000 + 3 * (4 + i))) + .collect(); + assert_eq!(words::(&out, THREADS as usize), want, "{name}"); + println!("{name}: two buffers summed through an argument buffer's pointer members"); + }); + } + + /// A constant buffer whose bytes hold a buffer's `gpuAddress` plus 8, as the CPU wrote it: + /// thread `i` stores the word `i` past that address (`ab_address`). + #[test] + fn every_device_reads_a_buffer_through_a_gpu_address_the_cpu_wrote() { + let Some(library) = library("ab_pointers") else { + return; + }; + each_device("argument_tier_stored_address", |name, _, device| { + let read = state(name, &device, &library, "ab_address"); + let mut shared = Shared::new(&device); + let read_from = shared.of( + &device, + &u32_bytes((0..THREADS + 2).map(|k| 0xA000_0000 | k)), + ); + let held = shared.of(&device, &(read_from.gpu_address() + 8).to_le_bytes()); + let out = shared.of(&device, &u32_bytes((0..THREADS).map(|_| 0))); + dispatch(name, &device, &read, [&held, &out], &[&read_from]); + let want: Vec = (0..THREADS).map(|i| 0xA000_0000 | (2 + i)).collect(); + assert_eq!(words::(&out, THREADS as usize), want, "{name}"); + println!("{name}: a buffer read through a gpuAddress the CPU wrote"); + }); + } + + /// A slot pointer converted to an integer: thread `i` stores the address of element `i` of + /// buffer 0, bound 16 bytes past its buffer's start, and increments the element through the + /// same pointer (`ab_slot_address`). The address is the buffer's `gpuAddress` plus 16 plus + /// `4 i`. + #[test] + fn every_device_answers_a_slot_pointer_converted_to_an_integer_as_its_gpu_address() { + let Some(library) = library("ab_pointers") else { + return; + }; + each_device("argument_tier_slot_address", |name, _, device| { + let convert = state(name, &device, &library, "ab_slot_address"); + let mut shared = Shared::new(&device); + let elements: Vec = (0..THREADS + 4).map(|k| 0x500 + 7 * k).collect(); + let buf = shared.of(&device, &u32_bytes(elements.iter().copied())); + let out = shared.of(&device, &vec![0; 8 * THREADS as usize]); + 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(&convert) + .expect("a state"); + encoder.set_buffer(Some(&buf), 16, 0).expect("buf"); + encoder.set_buffer(Some(&out), 0, 1).expect("out"); + (encoder.dispatch_threadgroups([2, 1, 1], [THREADS / 2, 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}"); + let want: Vec = (0..u64::from(THREADS)) + .map(|i| buf.gpu_address() + 16 + 4 * i) + .collect(); + assert_eq!( + words::(&out, THREADS as usize), + want, + "{name}: the addresses" + ); + let mut incremented = elements.clone(); + for e in &mut incremented[4..] { + *e += 1; + } + assert_eq!( + words::(&buf, elements.len()), + incremented, + "{name}: the elements" + ); + println!("{name}: a slot pointer converted to an integer is its gpuAddress"); }); } } diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 765d4bc2c..0d1bf0670 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -62,7 +62,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 = 2201; +pub const SEMANTICS_VERSION: u32 = 2202; /// 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/device/profile.rs b/crates/metal2vulkan/src/device/profile.rs index dbb49a184..b0c141352 100644 --- a/crates/metal2vulkan/src/device/profile.rs +++ b/crates/metal2vulkan/src/device/profile.rs @@ -1100,10 +1100,11 @@ pub enum PointerDomain { ResidentTable, /// Pointers are device addresses used directly: a `device` or `constant` pointer is the /// 64-bit Vulkan device address of the byte it names, as Metal's `gpuAddress` is, and a - /// buffer slot is reached at its own address, pushed, uncontained. Needs + /// buffer slot is reached at its own address, pushed, uncontained, and a pointer loaded from + /// memory or made from an integer is the address it holds, used directly. Needs /// `bufferDeviceAddress` and `shaderInt64`. So far it lowers a kernel that reaches memory - /// only through its buffer slots, and, on `Device::from_queries`' profile, a vertex or - /// fragment function that does; any other function is refused as + /// only through its buffer slots and such addresses, and, on `Device::from_queries`' profile, + /// a vertex or fragment function that does; any other function is refused as /// [`Feature::IdentityDomains`](crate::error::Feature::IdentityDomains). Identity, } diff --git a/crates/metal2vulkan/src/lower/access/dynamic.rs b/crates/metal2vulkan/src/lower/access/dynamic.rs index b2a5851b0..c6c223c93 100644 --- a/crates/metal2vulkan/src/lower/access/dynamic.rs +++ b/crates/metal2vulkan/src/lower/access/dynamic.rs @@ -47,6 +47,15 @@ //! device-address slots carries the status by address). Every static slot a wide access may reach //! becomes `BufferForm::Psb` (`access::finish_slots`), so the binder writes its root entry. //! +//! **Under the identity domains** there is no root table: a pointer is the device address of the +//! byte it names, so a loaded word or an `inttoptr` operand is the pointer itself, with no search. +//! A wide pointer there is `(0, a, 0, 0)` for address `a`: the form of a miss, whose Metal address +//! is `at` and whose accesses are at `host + at`. A wide buffer parameter is its slot's address +//! (`SlotGuestBase`, the bias added back) in `at`. No access through a wide pointer is contained +//! or counted: a stored address is used as it is, unchecked, and no resident set exists to miss. +//! No root table is read and no `RootTableAddress` pushed. An escaping slot root stays static +//! there (`memory::plan`), so a converted or stored slot pointer is `access::pointer`'s. +//! //! **Compares.** `icmp` of wide pointers, or of a wide pointer and the null constant, compares //! their Metal addresses: `guest + at` of each pointer's root entry, the null root's fields being //! 0 (so a miss `(0, i, 0, 0)` is address `i`, and null is 0). A compare of a wide @@ -100,7 +109,7 @@ use crate::memory::leaf::{self, k32, Coherence, Leaf, Path, Units, WordOps}; use crate::memory::provenance::{Repr, RootSetId}; use crate::memory::roots::{self, k64}; use crate::pipeline::facts::RuntimeFact; -use crate::pipeline::sym::{PushField, Stage}; +use crate::pipeline::sym::{PushField, SlotClass, SlotRef, Stage}; use crate::spirv::builder::constructs::{ArmEnd, ArmFn}; use crate::spirv::builder::FunctionBuilder; use crate::spirv::error::BResult; @@ -368,17 +377,33 @@ fn wide_operand(cx: &SelectCx<'_>, v: Value) -> Result { operand(cx, v) } -/// The function reads the root table for a wide pointer. +/// The function reads the root table for a wide pointer; under the identity domains, which have +/// none, nothing is read. fn use_table(cx: &mut SelectCx<'_>) { + if super::identity(cx.profile) { + return; + } cx.families.access.dynamic.used = true; cx.push.insert(PushField::RootTableAddress); } +/// Plan one resident-set search of a guest address (a loaded pointer, an `inttoptr` operand, an +/// encoder's record address): the function reads the root table and searches it once more. Under +/// the identity domains the address is the pointer, with no search. +fn plan_resolve(cx: &mut SelectCx<'_>) { + if super::identity(cx.profile) { + return; + } + use_table(cx); + cx.families.access.dynamic.resolves += 1; +} + /// Plan a read of wide pointer `v`'s root entry: its static slots go through the root table, so /// the binder writes their entries. The slots are its root set's (`root_sets::SetFacts`), each /// with a window; a root that is neither null, dynamic, nor an accessed buffer slot (the constant /// blob, an arena, a slot the function never accesses and therefore has no root entry for) is -/// refused. A set's slots join the plan's once, at its first such read. +/// refused. A set's slots join the plan's once, at its first such read. Under the identity domains +/// the pointer carries its address, and no entry is read ([`use_table`]). pub(super) fn plan_entry(cx: &mut SelectCx<'_>, v: Value) -> Result { require_addresses(cx)?; let roots = wide(cx, v).ok_or_else(refuse)?; @@ -407,9 +432,10 @@ pub(super) fn plan_deref(cx: &mut SelectCx<'_>, v: Value) -> Result) -> Result<(), Error> { - if cx.profile.fields().isolation == GuestIsolation::On { + if cx.profile.fields().isolation == GuestIsolation::On && !super::identity(cx.profile) { let enabled = &cx.profile.fields().enabled.features; if let Some(f) = stage_stores(cx.stage).find(|f| !enabled.contains(f)) { return Err(Unsupported::needs( @@ -466,16 +492,38 @@ pub fn is_wide_param(cx: &SelectCx<'_>, b: &ParamBinding) -> bool { wide(cx, Value::Arg(crate::air::ir::ArgIdx::new(b.param))).is_some() } -/// Plan a buffer parameter whose value is a wide pointer. +/// Plan a buffer parameter whose value is a wide pointer: under the identity domains its slot's +/// address is read from its `SlotGuestBase`. pub fn select_param(cx: &mut SelectCx<'_>, b: &ParamBinding) -> Result<(), Error> { require_addresses(cx)?; + if super::identity(cx.profile) { + let slot = param_slot(cx.entry, b).ok_or_else(refuse)?; + cx.push.insert(PushField::SlotGuestBase(slot)); + } cx.families.access.dynamic.params.insert(b.param); Ok(()) } +/// The slot of buffer parameter `b`, `[[buffer(n)]]` of its function's stage, or `None` when it +/// is not one. +fn param_slot(entry: &crate::air::Entry, b: &ParamBinding) -> Option { + match &b.role { + ParamRole::Buffer(arg) | ParamRole::ArgumentBuffer(arg) => match arg.location.index { + AbiInt::Const(index) => Some(SlotRef { + stage: crate::memory::static_root::stage_of(entry), + class: SlotClass::Buffer, + index, + }), + _ => None, + }, + _ => None, + } +} + /// The value of a wide buffer parameter, `[2 + n, bind_offset, host, size]` of its root entry /// (read where the value is first needed: [`emit_entry`] holds it from the function's first -/// block), or `None` when `b` is not one. +/// block), or `None` when `b` is not one. Under the identity domains it is `[0, a, 0, 0]` for its +/// slot's address `a`, read where it is needed. pub fn param_value( cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, @@ -484,14 +532,14 @@ pub fn param_value( if !cx.plan.families.access.dynamic.params.contains(&b.param) { return Ok(None); } - let index = match &b.role { - ParamRole::Buffer(arg) | ParamRole::ArgumentBuffer(arg) => match arg.location.index { - AbiInt::Const(i) => i, - _ => return Err(cx.fail(format!("parameter {} is no buffer slot", b.param))), - }, - _ => return Err(cx.fail(format!("parameter {} is no buffer", b.param))), + let Some(slot) = param_slot(cx.entry, b) else { + return Err(cx.fail(format!("parameter {} is no buffer slot", b.param))); }; - let root = k64(fb, u64::from(slot_root(index)))?; + if cx.plan.families.access.identity { + let address = super::pointer::slot_address(cx, fb, slot)?; + return Ok(Some(at_address(fb, address)?)); + } + let root = k64(fb, u64::from(slot_root(slot.index)))?; let table = cx.push_field(fb, PushField::RootTableAddress)?; let at = roots::entry_field(fb, table, root, roots::BIND_OFFSET)?; let host = roots::entry_field(fb, table, root, roots::HOST)?; @@ -688,8 +736,7 @@ pub fn select( ) { return Err(refuse()); } - use_table(cx); - cx.families.access.dynamic.resolves += 1; + plan_resolve(cx); DynStrategy::FromInt { of: operand(cx, *v)?, } @@ -703,8 +750,7 @@ pub fn select( } if result_wide => { require_addresses(cx)?; let leaf = pointer_leaf(cx, inst.ty, *align)?; - use_table(cx); - cx.families.access.dynamic.resolves += 1; + plan_resolve(cx); let source = match cx.memory.repr(*ptr) { Some(Repr::BufPtr { wide: false, .. }) => { Source::Static(static_access(cx, *ptr, leaf, false, m)?) @@ -1006,6 +1052,12 @@ fn fat(fb: &mut FunctionBuilder<'_>, parts: [SValue; 4]) -> BResult { fb.composite_construct(ty, &parts) } +/// The identity domains' wide pointer of device address `a` (a `u64`): `[0, a, 0, 0]`. +fn at_address(fb: &mut FunctionBuilder<'_>, a: SValue) -> BResult { + let zero = k64(fb, 0)?; + fat(fb, [zero, a, zero, zero]) +} + /// The fields of wide pointer value `p`: `[root, at, host, size]`. fn fields(fb: &mut FunctionBuilder<'_>, p: SValue) -> BResult<[SValue; 4]> { Ok([ @@ -1297,12 +1349,16 @@ fn metal_address(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, side: Side) } /// The Metal (guest) address of wide pointer value `p` (a `u64vec4`): `guest + at` of its root -/// entry (the null root's fields are 0, so a miss `[0, i, 0, 0]` is `i`). +/// entry (the null root's fields are 0, so a miss `[0, i, 0, 0]` is `i`). Under the identity +/// domains, which have no root table, it is `at`. pub(super) fn guest_address( cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, p: SValue, ) -> BResult { + if cx.plan.families.access.identity { + return fb.composite_extract(p, &[1]); + } let root = fb.composite_extract(p, &[0])?; let at = fb.composite_extract(p, &[1])?; let table = cx.push_field(fb, PushField::RootTableAddress)?; @@ -1371,7 +1427,11 @@ pub(super) fn plan_static_guest( /// The wide pointer of guest address `guest` (a `u64`): a call of the module's resident-set /// search ([`roots::define_resolve`]), or the search in place when it is the module's only one. +/// Under the identity domains the address is the pointer: `[0, guest, 0, 0]`, with no search. fn resolve(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, guest: SValue) -> BResult { + if cx.plan.families.access.identity { + return at_address(fb, guest); + } let table = cx.push_field(fb, PushField::RootTableAddress)?; match cx.decl.families.access.resolve { Some(search) => fb @@ -1543,8 +1603,7 @@ pub(super) fn plan_word( /// root 0. The caller checked the profile's device addresses and the stage's store feature. pub(super) fn plan_search(cx: &mut SelectCx<'_>) -> Result<(), Error> { require_addresses(cx)?; - use_table(cx); - cx.families.access.dynamic.resolves += 1; + plan_resolve(cx); plan_misses(cx) } diff --git a/crates/metal2vulkan/src/lower/access/pointer.rs b/crates/metal2vulkan/src/lower/access/pointer.rs index 3ddef8b2b..a4d8464b9 100644 --- a/crates/metal2vulkan/src/lower/access/pointer.rs +++ b/crates/metal2vulkan/src/lower/access/pointer.rs @@ -39,12 +39,12 @@ //! word first, and `SlotGuestBase` is placed as a `uvec2` on every profile (the same eight //! bytes). //! -//! **Stored and converted pointers on Profile F** ([`PointerValue::ToInt`], -//! [`PointerValue::StorePointer`]). Without device addresses an escaping slot root stays static -//! (`memory::plan`), so `ptrtoint` of a static fat pointer (or of the null constant) is its -//! Metal address as above, truncated to the integer's width (a `bool` its low bit), and a stored -//! one is that address as an 8-byte leaf through a static-root destination (stored pointers are -//! guest addresses). On Profile A such a pointer is wide. +//! **Stored and converted pointers on Profile F and under the identity domains** +//! ([`PointerValue::ToInt`], [`PointerValue::StorePointer`]). Without root entries an escaping +//! slot root stays static (`memory::plan`), so `ptrtoint` of a static fat pointer (or of the null +//! constant) is its Metal address as above, truncated to the integer's width (a `bool` its low +//! bit), and a stored one is that address as an 8-byte leaf through a static-root destination +//! (stored pointers are guest addresses). On Profile A's resident table such a pointer is wide. //! //! **Handles of the other families.** A command buffer, pipeline state, acceleration structure, or //! function table loaded from an argument buffer, or any access-family instruction on one, is @@ -432,7 +432,8 @@ fn compare( } /// Whether stored or converted pointer `v` takes the static form here: a static fat pointer -/// (which on Profile A never escapes), or the null constant on a profile without device addresses. +/// (which escapes only without root entries: on Profile F and under the identity domains), or the +/// null constant on a profile without device addresses. /// Every other pointer is `dynamic`'s (or refused there). fn static_escape(cx: &SelectCx<'_>, v: Value) -> Result, Error> { if !buffer_space(cx, v) { @@ -473,7 +474,7 @@ fn address_leaf(cx: &SelectCx<'_>, ty: TypeId, align: Option) -> Result, val: Value, diff --git a/crates/metal2vulkan/src/lower/select.rs b/crates/metal2vulkan/src/lower/select.rs index f841dfe90..6a1a7d363 100644 --- a/crates/metal2vulkan/src/lower/select.rs +++ b/crates/metal2vulkan/src/lower/select.rs @@ -1926,7 +1926,8 @@ fn identity_unsourced(f: &RuntimeFact) -> bool { /// Under the identity domains on profile `p`, the plans lowered so far: a kernel, or on the floor's /// push window (`PushWindow::Floor`, `Device::from_queries`' profile) a vertex or fragment -/// function, that reaches memory only through its buffer slots' device addresses, its textures' +/// function, that reaches memory only through its buffer slots' device addresses, the device +/// addresses it loads or makes from integers (`access::dynamic`, no root table), its textures' /// and runtime samplers' resource IDs and its constexpr samplers' pushed indices, with no /// descriptor and no state of a bound texture or sampler but its resource ID's /// (`SlotPlan::identity_lowered`, [`identity_unsourced`]). The values it reads of the encoder are diff --git a/crates/metal2vulkan/src/memory/plan.rs b/crates/metal2vulkan/src/memory/plan.rs index 874df6381..ef2468461 100644 --- a/crates/metal2vulkan/src/memory/plan.rs +++ b/crates/metal2vulkan/src/memory/plan.rs @@ -8,9 +8,9 @@ //! (`super::roots::wide_roots`), so a pointer and its operands share one width. On a profile with //! device addresses (Profile A), a buffer slot root whose pointer escapes (stored as a value, or //! `ptrtoint`) joins that component: its address may come back as a loaded pointer, and a wide -//! pointer's guest address is exact. On Profile F it stays static, and its stored or converted -//! address is `SlotGuestBase` plus its displacement. Such a slot's window is `Whole` when its own -//! accesses give none. +//! pointer's guest address is exact. On Profile F, and under the identity domains, it stays +//! static, and its stored or converted address is `SlotGuestBase` plus its displacement. Such a +//! slot's window is `Whole` when its own accesses give none. //! - **Slots**: every buffer or argument-buffer parameter an instruction reaches, and every //! accessed element of a buffer table (an `array_ref` of buffers), with its access set, its //! proven [`Window`], and whether it needs its guest base (`PushField::SlotGuestBase`: @@ -944,13 +944,14 @@ impl Planner<'_> { /// Every buffer slot root (a parameter or a buffer-table element) whose pointer escapes, /// paired with the dynamic root: the sets that join it to the dynamic component, on a profile - /// with device addresses only (Profile F has no root entries; its escaping roots stay static). - /// A constant global's address has no guest address to escape as (the blob is no resident - /// allocation), so it stays out and its stored pointer is refused. A working table charged to - /// the ledger. + /// with root entries only. Profile F has none, and the identity domains no root table, where a + /// loaded pointer is the device address it holds: there an escaping root stays static, and its + /// stored or converted address is `SlotGuestBase` plus its displacement. A constant global's + /// address has no guest address to escape as (the blob is no resident allocation), so it stays + /// out and its stored pointer is refused. A working table charged to the ledger. fn escaping_roots(&self, m: &mut Meter) -> Result, Error> { let mut out = Vec::new(); - if !self.addressed { + if !self.addressed || crate::lower::access::identity(self.p) { return Ok(out); } for (r, u) in &self.prov.uses { diff --git a/crates/metal2vulkan/src/tests/engine_identity.rs b/crates/metal2vulkan/src/tests/engine_identity.rs index b89c9b31f..da75ff4ce 100644 --- a/crates/metal2vulkan/src/tests/engine_identity.rs +++ b/crates/metal2vulkan/src/tests/engine_identity.rs @@ -397,37 +397,6 @@ fn a_slot_pointer_used_as_a_value_is_its_metal_address() { } } -/// A slot pointer converted to an integer (`ptrtoint`) is a wide pointer, which reads the root -/// table: the identity domains refuse the kernel as `Unsupported{IdentityDomains}`, not -/// implemented, where the default domains compile it. -#[test] -fn a_slot_pointer_converted_to_an_integer_is_refused_under_the_identity_domains() { - use super::engine_pointer_memory::{assemble, kernel}; - let body = " %p = getelementptr inbounds i8, ptr addrspace(1) %b0, i64 20 - %a = ptrtoint ptr addrspace(1) %p to i64 - store i64 %a, ptr addrspace(1) %b1, align 8 -"; - let name = "slot_to_int"; - let Some(bc) = assemble(name, &kernel(name, 2, body, "")) else { - return; - }; - for stem in PROFILES { - let default = profile(stem, DevicePolicy::default()).unwrap_or_else(|e| panic!("{e}")); - compile(&bc, name, &default).unwrap_or_else(|e| panic!("{stem}: default domains: {e}")); - let p = profile(stem, identity()).unwrap_or_else(|e| panic!("{e}")); - match compile(&bc, name, &p) { - Err(Error::Unsupported(u)) => { - assert_eq!( - (u.feature, u.needs), - (Feature::IdentityDomains, Needs::NotImplemented), - "{stem}" - ); - } - other => panic!("{stem}: {other:?}"), - } - } -} - /// The harness's sampling kernels (`fixtures/public/harness/workloads.ll`, our own), assembled. fn workloads() -> Option> { let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) @@ -844,46 +813,6 @@ fn a_bicubic_kernel_reads_each_slots_format_treatment_from_its_pushed_field() { } } -const POINTER_INDEXED_FORM: &str = "an encoder value the function reads as RootTableAddress"; - -/// Argument buffers tier 2's forms under the identity domains (`engine/ab_tier2`): a kernel that -/// copies a texture member from one argument buffer to another (`ab_copy`) and one that reads a -/// texel through an argument buffer's texture (`ab_read`) are lowered, and one that reads the -/// texture of an argument buffer a pointer member of the bound one reaches (`ab_indexed`) is -/// refused as `Unsupported{IdentityDomains}`, not implemented, naming the form the gate refuses -/// ([`POINTER_INDEXED_FORM`]), where the default domains compile it. -#[test] -fn a_texture_of_an_argument_buffer_a_pointer_member_reaches_is_refused_under_the_identity_domains() -{ - let Some(bc) = assemble("ab_tier2") else { - return; - }; - for stem in PROFILES { - let default = profile(stem, DevicePolicy::default()).unwrap_or_else(|e| panic!("{e}")); - compile(&bc, "ab_indexed", &default) - .unwrap_or_else(|e| panic!("{stem}: ab_indexed: default domains: {e}")); - let p = profile(stem, identity()).unwrap_or_else(|e| panic!("{e}")); - for entry in ["ab_copy", "ab_read"] { - compile(&bc, entry, &p).unwrap_or_else(|e| panic!("{stem}: {entry}: {e}")); - } - match compile(&bc, "ab_indexed", &p) { - Err(Error::Unsupported(u)) => { - assert_eq!( - (u.feature, u.needs), - (Feature::IdentityDomains, Needs::NotImplemented), - "{stem}" - ); - assert_eq!( - u.symbol.map(|form| form.to_string()).as_deref(), - Some(POINTER_INDEXED_FORM), - "{stem}" - ); - } - other => panic!("{stem}: {other:?}"), - } - } -} - /// Under the identity domains a kernel that encodes indirect commands is refused for that feature, /// `Unsupported{GpuEncodedIndirectCommands}`, not implemented, on every profile. #[test] diff --git a/crates/metal2vulkan/src/tests/engine_identity_pointers.rs b/crates/metal2vulkan/src/tests/engine_identity_pointers.rs new file mode 100644 index 000000000..1c0429967 --- /dev/null +++ b/crates/metal2vulkan/src/tests/engine_identity_pointers.rs @@ -0,0 +1,272 @@ +//! Buffers a kernel reaches through a device address held in memory or made from a slot pointer, +//! under the identity domains (`PointerDomain::Identity` with `HandleDomain::Identity`), on every +//! committed profile `Device::from_queries` derives there (our own MSL: `engine/ab_pointers` and +//! `engine/ab_tier2`'s `ab_indexed`). +//! +//! - `ab_sum` reads two buffers through the two pointer members of an argument buffer, +//! `ab_address` one through a `gpuAddress` written into a constant buffer's bytes, and +//! `ab_indexed` the texture of an argument buffer a pointer member of the bound one reaches: +//! each loaded word is the device address of the bytes it names, used as it is. No plan pushes +//! `RootTableAddress` (there is no root table) or `ExecutionStatusAddress` (no access through a +//! loaded address is counted), and no module declares a descriptor. Each passes L3. +//! - `ab_slot_address` converts a slot pointer to an integer and increments the element through +//! it: the slot stays a static root, reached at its pushed address and checked against its +//! pushed bounds (`SlotBounds`), and no parameter is a wide pointer. +//! - On the CPU interpreter, with every buffer above 4 GiB and the loaded addresses and the slot +//! bound at offsets past their buffers' starts, `ab_sum` and `ab_address` store the words the +//! addresses name, and `ab_slot_address` stores each element's Metal address (the slot's +//! address, `gpuAddress` plus its bind offset, plus the element's offset) and increments it. +//! Nothing else is written. +//! +//! `llvm-as` assembles the fixtures; without it the tests skip visibly. + +use std::collections::BTreeMap; + +use super::engine_word_phases::{bounds_word, identity_profiles, slot_word, ZERO_UNMAPPED}; +use crate::device::profile::DeviceProfile; +use crate::lower::dispatch::region_bytes; +use crate::lower::select::Plan; +use crate::pipeline::interface::PushLoc; +use crate::pipeline::sym::{Axis, PushField, SlotClass, SlotRef, SpecKey, Stage}; +use crate::pipeline::testing::{ + compile_kept, engine_dir, link_and_validate, llvm_assemble, AssembleError, +}; +use crate::spirv::interp::{run, Buffer, Config, Resources}; +use crate::spirv::ir::TypedModule; + +/// Threads a threadgroup, and threadgroups. +const GROUP: u32 = 8; +const GROUPS: u32 = 2; +const THREADS: usize = (GROUP * GROUPS) as usize; + +/// Where the interpreter holds the buffers: the two slots, and the two buffers only a loaded +/// address names. Each lies above 4 GiB, so a dropped high word shows. +const SLOT0: u64 = 0x1_0000_0000; +const SLOT1: u64 = 0x4_0000_0000; +const FIRST: u64 = 0x2_0000_0000; +const SECOND: u64 = 0x3_0000_1000; + +fn assemble(name: &str) -> Option> { + match llvm_assemble(&engine_dir().join(format!("{name}.ll"))) { + Ok(b) => Some(b), + Err(AssembleError::Missing(why)) => { + eprintln!("SKIPPED: {why}"); + None + } + Err(e) => panic!("{name}: {e:?}"), + } +} + +fn slot(index: u32) -> SlotRef { + SlotRef { + stage: Stage::Kernel, + class: SlotClass::Buffer, + index, + } +} + +fn words(values: impl IntoIterator) -> Vec { + values.into_iter().flat_map(u32::to_le_bytes).collect() +} + +fn addresses(values: &[u64]) -> Vec { + values.iter().flat_map(|a| a.to_le_bytes()).collect() +} + +/// `entry` of `bc` compiled on `stem`'s profile `p`, in the identity form: no descriptor, no +/// `RootTableAddress` and no `ExecutionStatusAddress` among its push fields, and an artifact that +/// passes L3. +fn compiled(bc: &[u8], entry: &str, stem: &str, p: &DeviceProfile) -> (Plan, TypedModule) { + let (a, plan, module) = + compile_kept(bc, entry, p).unwrap_or_else(|e| panic!("{stem}: {entry}: {e}")); + assert!(a.interface.descriptors.is_empty(), "{stem}: {entry}"); + let fields: Vec = plan.push.fields.iter().map(|f| f.field).collect(); + for absent in [ + PushField::RootTableAddress, + PushField::ExecutionStatusAddress, + ] { + assert!(!fields.contains(&absent), "{stem}: {entry}: {fields:?}"); + } + link_and_validate(&a, p).unwrap_or_else(|e| panic!("{stem}: {entry}: L3: {e}")); + (plan, module) +} + +/// The push bytes of `plan`, slot `i` bound at `slots[i]`: its buffer's address, its bind offset +/// and its buffer's length. +fn push(plan: &Plan, what: &str, slots: &[(u64, u64, usize)]) -> Vec { + let mut push = vec![0u8; plan.push.push_range.map_or(0, |(_, end)| end as usize)]; + let region = region_bytes([0; 3], [GROUP * GROUPS, 1, 1], [GROUP, 1, 1]).expect("packs"); + for f in &plan.push.fields { + let PushLoc::Push { offset } = f.loc else { + panic!("{what}: {f:?} spilled"); + }; + let o = offset as usize; + match f.field { + PushField::SlotGuestBase(s) => { + let (base, bind, _) = slots[s.index as usize]; + push[o..o + 8].copy_from_slice(&slot_word(base + bind).to_le_bytes()); + } + PushField::SlotBounds(s) => { + let (_, bind, bytes) = slots[s.index as usize]; + push[o..o + 8].copy_from_slice(&bounds_word(bytes, bind)); + } + PushField::ZeroAddress => push[o..o + 8].copy_from_slice(&ZERO_UNMAPPED.to_le_bytes()), + PushField::DispatchRegion => push[o..o + 32].copy_from_slice(®ion), + _ => panic!("{what}: unexpected push field {f:?}"), + } + } + push +} + +/// The buffers at `at`, each with its bytes. +fn buffers(at: &[(u64, &[u8])]) -> Vec { + (at.iter()) + .map(|(address, bytes)| Buffer { + slot: None, + address: Some(*address), + bytes: bytes.to_vec(), + }) + .collect() +} + +fn spec() -> BTreeMap { + BTreeMap::from([ + (SpecKey::LocalSize(Axis::X), u64::from(GROUP)), + (SpecKey::LocalSize(Axis::Y), 1), + (SpecKey::LocalSize(Axis::Z), 1), + (SpecKey::FlatLocalSize, u64::from(GROUP)), + ]) +} + +fn config() -> Config { + Config { + workgroups: [GROUPS, 1, 1], + ..Config::default() + } +} + +/// An argument buffer's two pointer members, each the address of a buffer, the second 16 bytes +/// past its buffer's start as an encoder's `setBuffer:offset:` writes it: thread `i` stores +/// `a[i] + b[i]` through them, and the plan reads no root table. +#[test] +fn an_argument_buffers_pointer_members_are_the_device_addresses_they_hold() { + let Some(bc) = assemble("ab_pointers") else { + return; + }; + let n = THREADS as u32 + 4; + let a = words((0..n).map(|k| 0x1000 + k)); + let b = words((0..n).map(|k| 0x7000_0000 + 3 * k)); + let args = addresses(&[FIRST, SECOND + 16]); + // One spare word past the output's end, which the kernel must not write. + let out = vec![0u8; 4 * THREADS + 4]; + let mut want = words((0..THREADS as u32).map(|i| (0x1000 + i) + (0x7000_0000 + 3 * (4 + i)))); + want.extend_from_slice(&[0; 4]); + for (stem, p) in identity_profiles() { + let (plan, module) = compiled(&bc, "ab_sum", &stem, &p); + let res = Resources { + push: push( + &plan, + &stem, + &[(SLOT0, 0, args.len()), (SLOT1, 0, out.len())], + ), + buffers: buffers(&[(SLOT0, &args), (SLOT1, &out), (FIRST, &a), (SECOND, &b)]), + spec: spec(), + }; + let got = run(&module, &config(), res).unwrap_or_else(|e| panic!("{stem}: {e}")); + assert_eq!(got.buffers[1], want, "{stem}: out"); + assert_eq!( + (&got.buffers[2], &got.buffers[3]), + (&a, &b), + "{stem}: read only" + ); + } +} + +/// A `gpuAddress` the program wrote into a constant buffer's bytes, 8 bytes past its buffer's +/// start: thread `i` stores the word `i` past it. +#[test] +fn a_stored_gpu_address_is_the_device_address_it_holds() { + let Some(bc) = assemble("ab_pointers") else { + return; + }; + let n = THREADS as u32 + 2; + let words_at = words((0..n).map(|k| 0xA000_0000 | k)); + let held = addresses(&[FIRST + 8]); + let out = vec![0u8; 4 * THREADS + 4]; + let mut want = words((0..THREADS as u32).map(|i| 0xA000_0000 | (2 + i))); + want.extend_from_slice(&[0; 4]); + for (stem, p) in identity_profiles() { + let (plan, module) = compiled(&bc, "ab_address", &stem, &p); + let res = Resources { + push: push( + &plan, + &stem, + &[(SLOT0, 0, held.len()), (SLOT1, 0, out.len())], + ), + buffers: buffers(&[(SLOT0, &held), (SLOT1, &out), (FIRST, &words_at)]), + spec: spec(), + }; + let got = run(&module, &config(), res).unwrap_or_else(|e| panic!("{stem}: {e}")); + assert_eq!(got.buffers[1], want, "{stem}: out"); + } +} + +/// A slot pointer converted to an integer is its Metal address: the slot's address (bound 16 +/// bytes past its buffer's start) plus the element's offset. The slot stays a static root, its +/// run-time accesses checked against its pushed bounds, and the increment through the same +/// pointer lands in the element. +#[test] +fn a_slot_pointer_converted_to_an_integer_is_its_metal_address() { + let Some(bc) = assemble("ab_pointers") else { + return; + }; + const BIND: u64 = 16; + let elements: Vec = (0..THREADS as u32 + 1).map(|k| 0x500 + 7 * k).collect(); + let mut buf = vec![0xEE; BIND as usize]; + buf.extend_from_slice(&words(elements.iter().copied())); + let out = vec![0u8; 8 * THREADS]; + let want_out = addresses( + &(0..THREADS as u64) + .map(|i| SLOT0 + BIND + 4 * i) + .collect::>(), + ); + let mut want_buf = vec![0xEE; BIND as usize]; + want_buf.extend_from_slice(&words(elements[..THREADS].iter().map(|v| v + 1))); + want_buf.extend_from_slice(&elements[THREADS].to_le_bytes()); + for (stem, p) in identity_profiles() { + let (plan, module) = compiled(&bc, "ab_slot_address", &stem, &p); + assert!( + plan.families.access.dynamic.params.is_empty(), + "{stem}: a wide parameter" + ); + assert!( + (plan.push.fields.iter()).any(|f| f.field == PushField::SlotBounds(slot(0))), + "{stem}: the slot is not checked: {:?}", + plan.push.fields + ); + let res = Resources { + push: push( + &plan, + &stem, + &[(SLOT0, BIND, buf.len()), (SLOT1, 0, out.len())], + ), + buffers: buffers(&[(SLOT0, &buf), (SLOT1, &out)]), + spec: spec(), + }; + let got = run(&module, &config(), res).unwrap_or_else(|e| panic!("{stem}: {e}")); + assert_eq!(got.buffers[1], want_out, "{stem}: out"); + assert_eq!(got.buffers[0], want_buf, "{stem}: buf"); + } +} + +/// The texture of an argument buffer a pointer member of the bound one reaches (`ab_indexed`) +/// compiles with no root table: its handle is read at the loaded address. +#[test] +fn a_texture_behind_an_argument_buffers_pointer_member_is_read_at_the_loaded_address() { + let Some(bc) = assemble("ab_tier2") else { + return; + }; + for (stem, p) in identity_profiles() { + compiled(&bc, "ab_indexed", &stem, &p); + } +} diff --git a/crates/metal2vulkan/src/tests/mod.rs b/crates/metal2vulkan/src/tests/mod.rs index 4fec5aafe..49b0147e7 100644 --- a/crates/metal2vulkan/src/tests/mod.rs +++ b/crates/metal2vulkan/src/tests/mod.rs @@ -86,6 +86,7 @@ mod engine_helper_threads; mod engine_identity; mod engine_identity_contain; mod engine_identity_domain; +mod engine_identity_pointers; mod engine_identity_render; mod engine_identity_spill; mod engine_image_shapes; diff --git a/docs/API.md b/docs/API.md index 182c92f27..0ba9200f8 100644 --- a/docs/API.md +++ b/docs/API.md @@ -211,17 +211,18 @@ compile does. `DevicePolicy::default()` is `DevicePolicy::UNTRUSTED`: (`PushField::FetchedColor { color, texels }`, `texels` the read's numeric class), and a read-only signed-integer attachment joins `signed_color_attachments`. Every precision note is static there: no constant or binder decides one. So far they lower a kernel that reaches memory - through its buffer slots and reads, writes, sizes or tests for nil its texture slots and its - argument buffers' textures, and samples its texture slots through its runtime sampler slots - and its constexpr samplers. Any other function is refused as `Unsupported{IdentityDomains}`, + through its buffer slots and the device addresses it loads (an argument buffer's pointer + member, a stored `gpuAddress`) or makes from integers, and reads, writes, sizes or tests for nil + its texture slots and its argument buffers' textures, those of an argument buffer a pointer + member reaches included, and samples its texture slots through its runtime sampler slots and + its constexpr samplers. Any other function is refused as `Unsupported{IdentityDomains}`, whose symbol names the first such form the function holds: one that samples through an argument buffer's sampler or an array of samplers or samples an argument buffer's texture, emulates a sampler's anisotropy, samples a 1D texture or at pixel coordinates through a bicubic filter, uses a texture buffer, a slot's levels or swizzle, a two-plane, extended-range or sRGB-twin form, reads an argument buffer's texture - through another numeric type or as raw texels, reads the texture of an argument buffer that a - pointer another argument buffer holds reaches (it reads the root table, `RootTableAddress`), or - uses any other state of a texture or sampler beyond its ID. + through another numeric type or as raw texels, or uses any other state of a texture or sampler + beyond its ID. An argument buffer's texture reads the element at its ID's index masked to its low 16 bits, so a bad ID reads an element of the arrays ([RESOURCE-ID.md](RESOURCE-ID.md)); the change that first lowers an argument buffer's sampler masks its index the same way. @@ -1611,11 +1612,13 @@ for dependency in &pipeline.dependencies { `setBytes` copy, or of the consumer's nil buffer where nothing is bound), less 2^31, modulo 2^64. An access through the slot adds its 32-bit byte offset plus 2^31, modulo 2^32, zero-extended, to that word; a pointer compare, a pulled vertex fetch and an access from the - word below it add the 2^31 back to read the address itself. A slot pointer converted to an - integer is a wide pointer, which reads the root table: the identity domains refuse it. The - binder (`BindingPlan::instantiate_*`) of a device that compiles under the identity domains - writes the word so. A pointer loaded from an argument buffer is the address the buffer holds, - unbiased. A texture's or sampler's `SlotGuestBase` is its `gpuResourceID`, unbiased. + word below it add the 2^31 back to read the address itself, and so does a slot pointer + converted to an integer or stored, which is the slot's address plus its offset. The binder + (`BindingPlan::instantiate_*`) of a device that compiles under the identity domains writes the + word so. A pointer loaded from memory (an argument buffer's pointer member, a `gpuAddress` the + program stored) and a pointer made from an integer are the device address the word holds, + unbiased and used directly, unchecked: there is no root table, no `PushField::RootTableAddress` + and no search. A texture's or sampler's `SlotGuestBase` is its `gpuResourceID`, unbiased. - Under the identity domains with containment on, a buffer slot that an access may reach at a byte offset that is not a translation-time constant (an index the memory plan does not prove one value, a looping `memcpy` or `memset`, a pulled fetch) also reads