From c034220175d7622e818169a50084cda1fd5565a9 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Fri, 20 Nov 2026 22:29:10 -0800 Subject: [PATCH] Private memory past the 16 KiB floor lives in the runtime's arena, one slot an invocation; a dispatch past its budget splits A kernel whose private arrays (indexed at run time) passed the translator's 16 KiB floor was refused as Unsupported{PrivateMemory}. The app's 780M library holds 7 such kernels (19,792 to 34,736 bytes a thread), and the Iris walk refused one at 28,704. Metal holds that memory itself. The runtime now holds it in device memory it owns. Translator, under the identity domains only (the default domains' binder supplies no such memory, so they refuse as before): - memory::plan::private_memory: a kernel with no call stack whose private bytes pass the floor places every alloca it indexes at run time in its private arena, and marks the arena ArenaLayout::device. The arena then leaves the private bytes. The kernel's own bytes decide; no device fact does. - Such an arena has no Private variable. Its words are PhysicalStorageBuffer words (Aligned 4) at the invocation's slot. The slot is PushField::PrivateArenaAddress (a u64) plus i * slot_bytes, with i = ((wz*ny + wy)*nx + wx)*n + LocalInvocationIndex in 32 bits. It is computed once in the entry block (dispatch::KernelDecl::arena_slot, Invariant::ArenaSlot). RuntimeFact::PrivateArena { slot_bytes } states the slot: the arena's bytes rounded up to 16. - A tile kernel's arena past the floor stays refused (PrivateMemory). A slot past u32 is LimitExceeded(PrivateArenaBytes). Runtime (crate::arena): - The arena is one Private pool block, never zeroed: Metal's private memory is undefined until the thread writes it. The device keeps a Weak to the last block. Each command buffer that dispatches into a block keeps it (keep_block), and a dispatch that needs no more than a block still kept takes it again. - A dispatch's slots take at most 1/16 of the largest DEVICE_LOCAL heap, capped at the longest block, or one threadgroup's slots where those are more. A dispatch past that budget runs in pieces of whole threadgroups through the existing split loop, each piece's DispatchRegion carrying its first threadgroup. There is one split form; vkCmdDispatchBase is not used. - A barrier (the encoder's owed barrier, so it merges with a hazard barrier) comes before each arena piece, except the first piece in a block the dispatch took new. Dispatches of kernels without an arena take no new barrier. - An indirect dispatch of an arena kernel is Gap::IndirectPrivateArena: its counts are the GPU's, so the runtime can neither size the arena nor split it. - Metrics::private_arena_dispatches, private_arena_pieces and private_arena_blocks count the path, and private_arena_allocations counts the block takes. - The budget a device test splits with is Core::arena_budget's test override (cfg(test) with m2v_gpu or m2v_cpu_icd), never a DeviceOptions field. Docs: docs/API.md (the field, the fact, the slot formula), the runtime README (Compute encoders: the arena, its budget, its order, the indirect gap), docs/REFUSALS.md (regenerated), api_signatures.tsv (blessed). SEMANTICS_VERSION 2244 -> 2245, ARTIFACT_FORMAT_VERSION 581 -> 582, RUNTIME_VERSION 2549 -> 2550. Tests: - engine_private_memory's a_kernel_past_the_floor_keeps_its_private_memory_in_the_runtimes_memory_under_identity: 7176, 9216 and 51,200 words on the 780M's, the Iris Xe's and an RTX 50's profiles. Each compiles, passes L3, pushes the address, states the fact, holds 0 private bytes and records no note. The default domains refuse as before. - rt private_arena's every_device_holds_private_memory_past_the_floor_in_its_arena_split_or_whole: 28,704, 36,864 and 204,800 bytes a thread, 8 groups of 64, under the device's budget (1 piece) and a test budget (4 and 8 pieces). Every answer matches a CPU reference. It counts 2 arena dispatches, their pieces, and exactly 2*pieces - (blocks taken) barriers beyond a plain command buffer's. Four plain dispatches take the barriers one does. The kernel interface declares the arena's slot (Interface::private_arena, the slot bytes of RuntimeFact::PrivateArena); the compute test's interface sets it to None. --- crates/metal2vulkan-runtime/README.md | 19 ++ crates/metal2vulkan-runtime/src/arena.rs | 94 ++++++++ crates/metal2vulkan-runtime/src/counters.rs | 36 ++- crates/metal2vulkan-runtime/src/device.rs | 31 ++- crates/metal2vulkan-runtime/src/encoder.rs | 48 +++- crates/metal2vulkan-runtime/src/error.rs | 11 + crates/metal2vulkan-runtime/src/lib.rs | 1 + crates/metal2vulkan-runtime/src/pipeline.rs | 14 ++ .../src/render_encoder.rs | 2 +- .../metal2vulkan-runtime/src/tests/compute.rs | 1 + crates/metal2vulkan-runtime/src/tests/mod.rs | 1 + .../src/tests/private_arena.rs | 224 ++++++++++++++++++ crates/metal2vulkan/src/bind/plan/compute.rs | 8 +- crates/metal2vulkan/src/cache/codec.rs | 2 + crates/metal2vulkan/src/cache/mod.rs | 6 +- .../src/device/function_storage.rs | 11 +- crates/metal2vulkan/src/device/mechanism.rs | 3 + crates/metal2vulkan/src/lower/access/local.rs | 42 +++- crates/metal2vulkan/src/lower/dispatch.rs | 72 +++++- .../metal2vulkan/src/lower/dispatch/tests.rs | 1 + crates/metal2vulkan/src/lower/emit.rs | 30 +++ crates/metal2vulkan/src/lower/mesh/mod.rs | 2 +- crates/metal2vulkan/src/lower/push.rs | 3 +- crates/metal2vulkan/src/lower/select.rs | 9 +- crates/metal2vulkan/src/memory/arena.rs | 73 ++++-- crates/metal2vulkan/src/memory/plan.rs | 61 ++++- crates/metal2vulkan/src/pipeline/facts.rs | 9 + crates/metal2vulkan/src/pipeline/sym.rs | 9 + crates/metal2vulkan/src/spirv/interp/tests.rs | 10 +- .../src/tests/engine_private_memory.rs | 58 ++++- crates/metal2vulkan/tests/api_signatures.tsv | 7 + docs/API.md | 12 +- docs/REFUSALS.md | 16 +- 33 files changed, 849 insertions(+), 77 deletions(-) create mode 100644 crates/metal2vulkan-runtime/src/arena.rs create mode 100644 crates/metal2vulkan-runtime/src/tests/private_arena.rs diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index 347d6dfcb..767c31760 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -2009,6 +2009,25 @@ while the driver's exit handler waited on a lock, with every runtime thread alre encoder that set none is `Gap::NoStageInRegion`: what Metal's kernel reads then is not established. A kernel with a `[[stage_in]]` argument, which fetches by the region, is `Gap::KernelInput` of `KernelInputKind::StageIn` at its state's creation. +- A kernel whose private memory passes the translator's 16 KiB floor (its arrays a thread + indexes at run time: Metal holds such a kernel's thread memory itself) keeps it in the runtime's + device memory, the private arena (`RuntimeFact::PrivateArena`): one slot of the kernel's bytes, + rounded up to 16, for each invocation of the dispatch, at the address the dispatch pushes + (`PushField::PrivateArenaAddress`), its invocation's slot at its index in the Vulkan dispatch. + The arena is one Private block of the pool, never zeroed (Metal's private memory is undefined + until the thread writes it). The device keeps the last block it took while a command buffer + keeps it, and a dispatch that needs no more takes it again; one that needs more takes a block of + its need rounded up to a power of two. A dispatch's slots take at most a sixteenth of the + device's largest device-local heap, within its longest block, or one threadgroup's slots where + those are more: a dispatch past that runs as several, each of as many whole threadgroups as the + budget holds, its region carrying its first threadgroup, as a count past + `maxComputeWorkGroupCount` does. Each piece is ordered after the commands before it by a + barrier, but the first in a block the dispatch took new, which nothing reached before; a + dispatch of a kernel without an arena takes no such barrier. + `Metrics::private_arena_dispatches`, `private_arena_pieces` and `private_arena_blocks` count + them, and `private_arena_allocations` the blocks' takes. An indirect dispatch of such a kernel + is `Gap::IndirectPrivateArena`: the GPU reads its counts, so the runtime can neither size its + arena nor split it. - `use_heap` is `useHeap:`, for the block a heap's memory is: the command buffer keeps the block until it retires, as it keeps a used buffer's block, so a heap given back while the work runs stays valid under it. It declares no access (Metal states no retention for it; keeping is the diff --git a/crates/metal2vulkan-runtime/src/arena.rs b/crates/metal2vulkan-runtime/src/arena.rs new file mode 100644 index 000000000..450deba8c --- /dev/null +++ b/crates/metal2vulkan-runtime/src/arena.rs @@ -0,0 +1,94 @@ +//! The private arena: device memory the runtime owns that holds the private memory of a kernel +//! past the translator's floor (`RuntimeFact::PrivateArena`), one slot of the kernel's slot bytes +//! for each invocation of a dispatch, at the address the dispatch pushes +//! (`PushField::PrivateArenaAddress`). Metal holds such a kernel's private memory itself. +//! +//! - **Budget.** A dispatch's slots take at most one sixteenth of the device's largest +//! device-local heap, and at most its longest block ([`budget`]), or one workgroup's slots where +//! those are more. A dispatch whose invocations' slots pass it runs as several dispatches, each +//! of as many whole workgroups as the budget holds ([`piece`]), each one's region carrying its +//! first threadgroup in Metal's grid (`crate::encoder`). An indirect dispatch, whose counts the +//! runtime never reads, cannot be split or sized: it is refused +//! ([`Gap::IndirectPrivateArena`](crate::Gap::IndirectPrivateArena)). +//! - **Memory.** A Private block of the pool, never zeroed: Metal's private memory is undefined +//! until the thread writes it. The device keeps a weak reference to the last block it took; each +//! command buffer that dispatches into a block keeps it until it retires, so the block goes back +//! to the pool once the last of them does, and a dispatch that needs no more than it holds while +//! one of them lives takes it again ([`take`]). A dispatch that needs more takes a block +//! of its need rounded up to a power of two, within the budget. +//! - **Order.** The pieces of a dispatch share their block's slots, and so may the dispatches +//! before them: each piece is ordered after the commands before it by a barrier, but the first +//! piece in a block the dispatch took new, which no command reached before. +//! +//! Counted in [`Metrics::private_arena_dispatches`](crate::Metrics::private_arena_dispatches), +//! [`Metrics::private_arena_pieces`](crate::Metrics::private_arena_pieces) and +//! [`Metrics::private_arena_blocks`](crate::Metrics::private_arena_blocks). + +use crate::counters::{Metric, Site}; +use crate::device::{lock, Core}; +use crate::error::Error; +use crate::memory::{self, MemoryClass}; +use ash::vk; +use std::sync::{Arc, Weak}; + +/// The share of the largest device-local heap a dispatch's slots take at most: one sixteenth. +const HEAP_SHARE: u64 = 16; + +/// The most bytes a dispatch's slots take on a device of `memory`'s heaps whose longest block is +/// `max_block_len`: a sixteenth of its largest device-local heap, within that block. +pub(crate) fn budget(memory: &vk::PhysicalDeviceMemoryProperties, max_block_len: u64) -> u64 { + let largest = (memory.memory_heaps_as_slice().iter()) + .filter(|heap| heap.flags.contains(vk::MemoryHeapFlags::DEVICE_LOCAL)) + .map(|heap| heap.size) + .max() + .unwrap_or(0); + (largest / HEAP_SHARE).min(max_block_len) +} + +/// The workgroups per axis of each piece of a dispatch of `groups` workgroups of `invocations` +/// invocations each, whose slots are `slot_bytes` each, under `budget` bytes and the device's +/// `max` workgroups per axis: as many whole workgroups as the budget's slots hold, at least one, +/// filling `x`, then `y`, then `z`, so every piece but an edge one has the same shape. A piece's +/// invocations stay under 2^32, so each one's index in it fits a `u32`. +pub(crate) fn piece( + (groups, max): ([u32; 3], [u32; 3]), + invocations: u64, + slot_bytes: u32, + budget: u64, +) -> [u32; 3] { + let slots = (budget / u64::from(slot_bytes)).min(u64::from(u32::MAX)); + let mut room = (slots / invocations.max(1)).max(1); + std::array::from_fn(|axis| { + let along = u64::from(groups[axis].min(max[axis])).min(room).max(1); + room = (room / along).max(1); + along as u32 + }) +} + +/// The block a dispatch on `core` whose slots take `len` bytes reaches its slots in, and whether +/// the dispatch took it new: the device's last, where a command buffer still keeps it and it holds +/// `len`, else a block of `len` rounded up to a power of two, within `budget` where `len` is. +/// +/// Err: what [`Core::take_memory`] returns. +pub(crate) fn take( + core: &Arc, + len: u64, + budget: u64, +) -> Result<(Arc, bool), Error> { + let mut last = lock(&core.arena); + if let Some(block) = last.upgrade().filter(|block| block.memory.len >= len) { + return Ok((block, false)); + } + let len = len + .checked_next_power_of_two() + .unwrap_or(len) + .min(budget.max(len)); + let memory = core.take_memory(MemoryClass::Private, len, Site::PrivateArena)?; + let block = Arc::new(memory::Block::new(memory, Arc::clone(core))); + *last = Arc::downgrade(&block); + core.counters.count(Metric::PrivateArenaBlocks); + Ok((block, true)) +} + +/// What the device keeps of its last arena block ([`take`]). +pub(crate) type Last = std::sync::Mutex>; diff --git a/crates/metal2vulkan-runtime/src/counters.rs b/crates/metal2vulkan-runtime/src/counters.rs index f686e9044..db3cbac01 100644 --- a/crates/metal2vulkan-runtime/src/counters.rs +++ b/crates/metal2vulkan-runtime/src/counters.rs @@ -193,6 +193,12 @@ pub(crate) enum Metric { BlocksMade, /// [`Metrics::dispatches_without_effects`]. DispatchesWithoutEffects, + /// [`Metrics::private_arena_dispatches`]. + PrivateArenaDispatches, + /// [`Metrics::private_arena_pieces`]. + PrivateArenaPieces, + /// [`Metrics::private_arena_blocks`]. + PrivateArenaBlocks, /// [`Metrics::translations`]. Translations, /// [`Metrics::translations_loaded`]. @@ -258,6 +264,9 @@ const METRIC_ORDER: [Metric; METRICS] = [ Metric::PipelinesCreated, Metric::BlocksMade, Metric::DispatchesWithoutEffects, + Metric::PrivateArenaDispatches, + Metric::PrivateArenaPieces, + Metric::PrivateArenaBlocks, Metric::Translations, Metric::TranslationsLoaded, Metric::RenderRecordsRead, @@ -439,6 +448,8 @@ pub(crate) enum Site { SharedTake, /// [`Metrics::private_take_allocations`]. PrivateTake, + /// [`Metrics::private_arena_allocations`]. + PrivateArena, } impl Site { @@ -452,7 +463,7 @@ impl Site { } /// The number of [`Site`]s. -const SITES: usize = Site::PrivateTake as usize + 1; +const SITES: usize = Site::PrivateArena as usize + 1; /// Why a texture over a buffer lives in an image of its own that the device copies its bytes into /// and back (`crate::over`), as the texture's making decides it (`crate::texture::check_over`, @@ -564,6 +575,9 @@ struct Atomics { maker_yields: AtomicU64, maker_yield_nanos: AtomicU64, dispatches_without_effects: AtomicU64, + private_arena_dispatches: AtomicU64, + private_arena_pieces: AtomicU64, + private_arena_blocks: AtomicU64, shared_long_reuses: AtomicU64, private_long_reuses: AtomicU64, allocations_mapped: AtomicU64, @@ -735,6 +749,9 @@ impl Counters { Metric::PipelinesCreated => &a.pipelines_created, Metric::BlocksMade => &a.blocks_made, Metric::DispatchesWithoutEffects => &a.dispatches_without_effects, + Metric::PrivateArenaDispatches => &a.private_arena_dispatches, + Metric::PrivateArenaPieces => &a.private_arena_pieces, + Metric::PrivateArenaBlocks => &a.private_arena_blocks, Metric::Translations => &a.translations, Metric::TranslationsLoaded => &a.translations_loaded, Metric::RenderRecordsRead => &a.render_records_read, @@ -1478,6 +1495,7 @@ impl Counters { zero_source_allocations: site(Site::ZeroSource), shared_take_allocations: site(Site::SharedTake), private_take_allocations: site(Site::PrivateTake), + private_arena_allocations: site(Site::PrivateArena), maker_waits: a.maker_waits.load(Relaxed), maker_wait_max_nanos: a.maker_wait_max_nanos.load(Relaxed), maker_memory_calls: a.maker_memory_calls.load(Relaxed), @@ -1489,6 +1507,9 @@ impl Counters { allocations_mapped_on_takes: a.allocations_mapped_on_takes.load(Relaxed), allocation_map_refusals: a.allocation_map_refusals.load(Relaxed), dispatches_without_effects: a.dispatches_without_effects.load(Relaxed), + private_arena_dispatches: a.private_arena_dispatches.load(Relaxed), + private_arena_pieces: a.private_arena_pieces.load(Relaxed), + private_arena_blocks: a.private_arena_blocks.load(Relaxed), translations: a.translations.load(Relaxed), translations_loaded: a.translations_loaded.load(Relaxed), render_records_read: a.render_records_read.load(Relaxed), @@ -1952,6 +1973,9 @@ pub struct Metrics { /// Private blocks. Texture blocks' are /// [`texture_block_allocations`](Self::texture_block_allocations). pub private_take_allocations: SiteAllocations, + /// As [`private_take_allocations`](Self::private_take_allocations), of the takes of the + /// private arena's blocks (`crate::arena`), on the thread of the dispatch that needed one. + pub private_arena_allocations: SiteAllocations, /// Calls that waited for the block-maker thread's make of one of the runtime's fixed-size /// internals they need, which it makes off every caller's thread: the zero source, a /// parameter ring block or the staging region (the sites above). Such a @@ -1994,6 +2018,16 @@ pub struct Metrics { /// direct and indirect: each was checked as Metal checks it, and nothing was recorded, bound /// or read for it, as it has no effect a program can observe. pub dispatches_without_effects: u64, + /// Direct dispatches of a kernel whose private memory is in the runtime's arena, past the + /// translator's floor (`crate::arena`). No Metal counterpart: Metal holds such a kernel's + /// private memory itself. + pub private_arena_dispatches: u64, + /// The `vkCmdDispatch`es those recorded: one each, and one more for each piece past the first + /// of a dispatch whose slots passed the arena's budget. + pub private_arena_pieces: u64, + /// The arena's blocks taken from the pool: one for the first such dispatch, and one more each + /// time a dispatch needed more than the last block held, or no command buffer kept it. + pub private_arena_blocks: u64, /// Functions the translator lowered, each a module of a pipeline content the device did not /// hold compiled: of a compute content, one for a kernel that does not observe its threadgroup /// partition and two for one that does; of a render content, one for each of its functions diff --git a/crates/metal2vulkan-runtime/src/device.rs b/crates/metal2vulkan-runtime/src/device.rs index 00f540031..f7f5e7242 100644 --- a/crates/metal2vulkan-runtime/src/device.rs +++ b/crates/metal2vulkan-runtime/src/device.rs @@ -290,6 +290,12 @@ pub(crate) struct Core { /// of device memory, before the driver is called. #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] pub(crate) fail_private: std::sync::atomic::AtomicU32, + /// For the device tests: where nonzero, the private arena's budget in place of the device's + /// ([`Core::arena_budget`]), so a small dispatch splits. + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + pub(crate) arena_budget: std::sync::atomic::AtomicU64, + /// The private arena's last block (`crate::arena`). + pub(crate) arena: crate::arena::Last, /// For the device tests: nanoseconds added to the host time of each calibration read, as a /// calibration whose host clock is read that long after its GPU tick. #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] @@ -672,16 +678,17 @@ impl Device { let limits = &properties.properties.limits; // The sampler arrays' two defaults count against the device's samplers too. let sampler_cap = limits.max_sampler_allocation_count.saturating_sub(2); + let max_block_len = vulkan11 + .max_memory_allocation_size + .min(vulkan13.max_buffer_size); let limits = EncoderLimits { max_group_count: limits.max_compute_work_group_count, max_shared_memory: limits.max_compute_shared_memory_size, max_viewport: limits.max_viewport_dimensions, viewport_bounds: limits.viewport_bounds_range, max_framebuffer_layers: limits.max_framebuffer_layers, + arena_budget: crate::arena::budget(&capabilities.memory, max_block_len), }; - let max_block_len = vulkan11 - .max_memory_allocation_size - .min(vulkan13.max_buffer_size); let resolve_modes = ResolveModes { depth: vulkan12.supported_depth_resolve_modes, stencil: vulkan12.supported_stencil_resolve_modes, @@ -731,6 +738,9 @@ impl Device { #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] fail_private: std::sync::atomic::AtomicU32::new(0), #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + arena_budget: std::sync::atomic::AtomicU64::new(0), + arena: Mutex::new(Weak::new()), + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] calibration_lateness: std::sync::atomic::AtomicU64::new(0), #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] tick_spans: Mutex::default(), @@ -1408,9 +1418,24 @@ pub(crate) struct EncoderLimits { pub(crate) viewport_bounds: [f32; 2], /// `maxFramebufferLayers`: the most layers a render pass renders (`renderTargetArrayLength`). pub(crate) max_framebuffer_layers: u32, + /// The most bytes a dispatch's slots of the private arena take (`crate::arena::budget`). + pub(crate) arena_budget: u64, } impl Core { + /// The most bytes a dispatch's slots of the private arena take: the device's + /// ([`EncoderLimits::arena_budget`]), or in a device test the one the test set. + pub(crate) fn arena_budget(&self) -> u64 { + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + { + let set = self.arena_budget.load(Ordering::Relaxed); + if set != 0 { + return set; + } + } + self.limits.arena_budget + } + /// The gauges of the device's stage entries ([`Gauges::stage_entries`] and /// [`Gauges::stage_entry_bytes`]), read after a creation moved them. /// diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index 8b218f13a..280839b6b 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -1,5 +1,6 @@ //! Compute command encoders: their binding state, their dispatches, and where barriers go. +use crate::arena; use crate::buffer::{Buffer, BufferInner, BufferObject}; use crate::command::{Building, CommandBuffer}; use crate::counters::Metric; @@ -1008,6 +1009,11 @@ impl ComputeCommandEncoder { if inner.whole.interface.stage_in_region && self.stage_in_region.is_none() { return Err(Error::Unsupported(Gap::NoStageInRegion)); } + // A private arena is sized and split by the dispatch's counts, which an indirect + // dispatch's GPU reads alone (`crate::arena`). + if inner.whole.interface.private_arena.is_some() && matches!(grid, Grid::Indirect(..)) { + return Err(Error::Unsupported(Gap::IndirectPrivateArena)); + } if let Grid::Indirect(buffer, _) = &grid { recording(&mut self.building).keep(buffer); } @@ -1115,9 +1121,26 @@ impl ComputeCommandEncoder { let ids = &state.numbered.ids; match (direct, grid) { (Some((threads, groups, ragged)), _) => { - // A count past the device's limit on an axis is split: each piece starts at its + // A count past the device's limit on an axis is split, and so is one whose slots + // of the private arena pass its budget (`crate::arena`): each piece starts at its // first threadgroup in Metal's grid, which its region carries. - let limit = limits.max_group_count; + let (limit, arena) = match interface.private_arena { + None => (limits.max_group_count, None), + Some(slot_bytes) => { + let budget = core.arena_budget(); + let invocations = local.iter().map(|&n| u64::from(n)).product::(); + let pair = (groups, limits.max_group_count); + let limit = arena::piece(pair, invocations, slot_bytes, budget); + let piece = limit.iter().map(|&n| u64::from(n)).product::(); + let need = piece * invocations * u64::from(slot_bytes); + let (block, fresh) = arena::take(&self.core, need, budget)?; + let building = recording(&mut self.building); + building.keep_block(&block); + building.count(Metric::PrivateArenaDispatches); + (limit, Some((block.memory.address, fresh))) + } + }; + let mut first = true; for z in (0..groups[2]).step_by(limit[2] as usize) { for y in (0..groups[1]).step_by(limit[1] as usize) { for x in (0..groups[0]).step_by(limit[0] as usize) { @@ -1127,10 +1150,22 @@ impl ComputeCommandEncoder { }); let region = region(base, threads, ragged)?; let bound = (&self.slots[..], &self.textures[..], &self.samplers[..]); - let regions = (®ion, self.stage_in_region.as_ref()); + let address = arena.map_or(0, |(address, _)| address); + let regions = (®ion, self.stage_in_region.as_ref(), address); self.parameters .fill(kernel, (bound, self.facts.nil), ids, regions); - recording(&mut self.building).record_dispatch( + let building = recording(&mut self.building); + // The piece reuses the slots the commands before it may have used: + // all but the first in a block the dispatch took new, which nothing + // reached before. + if let Some((_, fresh)) = arena { + if !(first && fresh) { + building.owe(); + } + building.count(Metric::PrivateArenaPieces); + } + first = false; + building.record_dispatch( core, vk_pipeline, &mut self.parameters, @@ -1144,7 +1179,7 @@ impl ComputeCommandEncoder { (None, Grid::Indirect(buffer, offset)) => { let region = region([0; 3], [0; 3], false)?; let bound = (&self.slots[..], &self.textures[..], &self.samplers[..]); - let regions = (®ion, self.stage_in_region.as_ref()); + let regions = (®ion, self.stage_in_region.as_ref(), 0); self.parameters .fill(kernel, (bound, self.facts.nil), ids, regions); recording(&mut self.building).record_dispatch( @@ -1380,7 +1415,7 @@ impl Parameters { kernel: &Kernel, (bound, (nil, zero)): (Bound<'_>, (u64, u64)), sampler_ids: &[u32], - (region, stage_in): (&[u8; 32], Option<&[u8; 32]>), + (region, stage_in, arena): (&[u8; 32], Option<&[u8; 32]>, u64), ) { let (slots, textures, samplers) = bound; let interface: &Interface = &kernel.interface; @@ -1453,6 +1488,7 @@ impl Parameters { bytes[at..at + 4].copy_from_slice(&index.to_le_bytes()); } FieldValue::DispatchRegion => bytes[at..at + 32].copy_from_slice(region), + FieldValue::PrivateArena => bytes[at..at + 8].copy_from_slice(&arena.to_le_bytes()), FieldValue::StageInRegion => { if let Some(stage_in) = stage_in { bytes[at..at + 32].copy_from_slice(stage_in); diff --git a/crates/metal2vulkan-runtime/src/error.rs b/crates/metal2vulkan-runtime/src/error.rs index a98223858..858e2715f 100644 --- a/crates/metal2vulkan-runtime/src/error.rs +++ b/crates/metal2vulkan-runtime/src/error.rs @@ -1001,6 +1001,14 @@ pub enum Gap { /// /// Basis: ours (no replay stream dispatches such a kernel without setting a region). NoStageInRegion, + /// `dispatchThreadgroupsWithIndirectBuffer:indirectBufferOffset:threadsPerThreadgroup:` of a + /// kernel whose private memory lives in the runtime's arena, past the translator's floor + /// (`crate::arena`): the GPU reads the counts and the runtime never does, so it can neither + /// size the arena for the dispatch nor split it under the arena's budget. Metal runs it. + /// Refused at the dispatch; the state's direct dispatches run. + /// + /// Basis: ours (no replay stream dispatches such a kernel indirectly). + IndirectPrivateArena, /// A texture of `Memoryless` storage, which only render passes use. /// /// Basis: ours (render passes are not built). @@ -2280,6 +2288,9 @@ impl fmt::Display for Gap { Gap::NoStageInRegion => { f.write_str("the kernel reads the stage-in region, which the encoder never set") } + Gap::IndirectPrivateArena => f.write_str( + "an indirect dispatch of a kernel whose private memory is in the runtime's arena", + ), Gap::PartialSimdgroups { threads_per_threadgroup, width, diff --git a/crates/metal2vulkan-runtime/src/lib.rs b/crates/metal2vulkan-runtime/src/lib.rs index 6318c7fc2..f4abfd875 100644 --- a/crates/metal2vulkan-runtime/src/lib.rs +++ b/crates/metal2vulkan-runtime/src/lib.rs @@ -8,6 +8,7 @@ #![warn(missing_docs)] +mod arena; mod arrays; mod blit; mod block; diff --git a/crates/metal2vulkan-runtime/src/pipeline.rs b/crates/metal2vulkan-runtime/src/pipeline.rs index 952012311..5f5956e25 100644 --- a/crates/metal2vulkan-runtime/src/pipeline.rs +++ b/crates/metal2vulkan-runtime/src/pipeline.rs @@ -571,6 +571,10 @@ pub(crate) struct Interface { /// Whether the kernel reads the stage-in region ([`FieldValue::StageInRegion`]), which a /// dispatch needs the encoder to have set. pub(crate) stage_in_region: bool, + /// The bytes of each invocation's slot in the kernel's private arena + /// (`RuntimeFact::PrivateArena`), where its private memory passes the translator's floor: a + /// dispatch of it takes the runtime's arena (`crate::arena`, [`FieldValue::PrivateArena`]). + pub(crate) private_arena: Option, /// The kernel's specialization constants: each one's id and what sets it. pub(crate) constants: Vec<(u32, Constant)>, /// The index of each threadgroup memory argument the kernel takes, in the order of @@ -739,6 +743,10 @@ pub(crate) enum FieldValue { /// past which a vertex function's `[[render_target_array_index]]` stores `Layer` 0 /// (`PushField::RenderTargetArrayLength`). RenderTargetArrayLength, + /// A `u64`: the address of a dispatch's slots in the private arena (`crate::arena`), each + /// invocation's at its index in the dispatch times the slot's bytes + /// (`PushField::PrivateArenaAddress`). + PrivateArena, } /// A `VkPipeline`'s specialization: the threadgroup size, the threadgroup memory lengths in the @@ -1260,6 +1268,7 @@ fn interface( let mut multiples = Vec::new(); let mut aligned = Vec::new(); let mut vote = 0; + let mut private_arena = None; let mut own = OwnMemory::Static(pipeline.metal_info.static_threadgroup_memory_length); for dependency in &pipeline.dependencies { match dependency.fact { @@ -1276,6 +1285,9 @@ fn interface( } if align.is_power_of_two() => aligned.push((index, u64::from(align) - 1)), // The walk's vote word: 4 bytes beside the threadgroup memory. RuntimeFact::PredicationVote => vote = 4, + // Each invocation's slot of the private arena, which the encoder places + // (`FieldValue::PrivateArena`). + RuntimeFact::PrivateArena { slot_bytes } => private_arena = Some(slot_bytes), // The emulated tier's arena and scratch, in place of Metal's static part. RuntimeFact::SimdgroupEmulation { bytes_per_simdgroup, @@ -1421,6 +1433,7 @@ fn interface( _, ) => FieldValue::BufferBounds(index), (PushField::ZeroAddress, _) => FieldValue::ZeroAddress, + (PushField::PrivateArenaAddress, _) => FieldValue::PrivateArena, _ => return Err(KernelInputKind::PushField), }; fields.push(Field { place, value }); @@ -1513,6 +1526,7 @@ fn interface( block_address, stage_in_region: (fields.iter()) .any(|field| matches!(field.value, FieldValue::StageInRegion)), + private_arena, fields, constants, threadgroups, diff --git a/crates/metal2vulkan-runtime/src/render_encoder.rs b/crates/metal2vulkan-runtime/src/render_encoder.rs index 7b5055247..c95f95157 100644 --- a/crates/metal2vulkan-runtime/src/render_encoder.rs +++ b/crates/metal2vulkan-runtime/src/render_encoder.rs @@ -2774,7 +2774,7 @@ fn fill_push( bytes[at..at + 4].copy_from_slice(&pass.layers.to_le_bytes()); } // A render content has no dispatch or stage-in region (`render::draws`). - FieldValue::DispatchRegion | FieldValue::StageInRegion => {} + FieldValue::DispatchRegion | FieldValue::StageInRegion | FieldValue::PrivateArena => {} } } } diff --git a/crates/metal2vulkan-runtime/src/tests/compute.rs b/crates/metal2vulkan-runtime/src/tests/compute.rs index 83a3ce966..8fbda34cd 100644 --- a/crates/metal2vulkan-runtime/src/tests/compute.rs +++ b/crates/metal2vulkan-runtime/src/tests/compute.rs @@ -52,6 +52,7 @@ pub(crate) mod on_device { block_address: 0, fields, stage_in_region: false, + private_arena: None, constants: vec![ (0, Constant::Size(0)), (1, Constant::Size(1)), diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index fe071ffa7..d90b61a45 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -68,6 +68,7 @@ mod pixel_format_info; mod pixel_interlock; mod places; mod present; +mod private_arena; mod push_window; mod quad_control; mod read_write_tier; diff --git a/crates/metal2vulkan-runtime/src/tests/private_arena.rs b/crates/metal2vulkan-runtime/src/tests/private_arena.rs new file mode 100644 index 000000000..5dba15721 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/private_arena.rs @@ -0,0 +1,224 @@ +//! The private arena (`crate::arena`), under a device cfg on every device of the cfg's kind: an +//! owned synthetic kernel, `arena`, keeps a private array of `N` words past the translator's +//! floor, fills it with `31 gid + i` and folds it back read at `(7 j + gid) mod N` as +//! `s = 3 s + a[k]`, so each thread's answer depends on every word of its own slot in an order no +//! other slot's words reproduce. It runs at 7176 words (28,704 bytes a thread), 9216 (36 KiB) and +//! 51,200 (200 KiB), over 8 threadgroups of 64, under the device's own budget (one piece) and +//! under a budget of a test's (`Core::arena_budget`) that splits the dispatch: two threadgroups a +//! piece at 28,704 bytes, four at 36 KiB and one at 200 KiB. Every answer is the CPU's. The counts show the path: one arena +//! dispatch each, its pieces, a barrier before each piece but the first in a block the dispatch +//! took new, and none for a kernel without an arena, whose dispatches beside it add no barrier. +//! +//! `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}; + use std::sync::atomic::Ordering::Relaxed; + + /// Threadgroups of a dispatch, and threads of each. + const GROUPS: u32 = 8; + const THREADS: u32 = 64; + + /// The kernel `arena` of `n` private words and the kernel `plain`, which writes its thread's + /// index and keeps no private memory. + fn module(n: u32) -> String { + format!( + r#"; Owned synthetic kernels: a private array of {n} words, and none. +source_filename = "private_arena.metal" + +define void @arena(ptr addrspace(1) %out, i32 %gid) {{ +entry: + %a = alloca [{n} x i32], align 4 + %m = mul i32 %gid, 31 + br label %fill +fill: + %i = phi i32 [ 0, %entry ], [ %i1, %fill ] + %v = add i32 %m, %i + %p = getelementptr inbounds [{n} x i32], ptr %a, i32 0, i32 %i + store i32 %v, ptr %p, align 4 + %i1 = add i32 %i, 1 + %more = icmp ult i32 %i1, {n} + br i1 %more, label %fill, label %read +read: + %j = phi i32 [ 0, %fill ], [ %j1, %read ] + %s = phi i32 [ 0, %fill ], [ %s1, %read ] + %j7 = mul i32 %j, 7 + %k0 = add i32 %j7, %gid + %k = urem i32 %k0, {n} + %q = getelementptr inbounds [{n} x i32], ptr %a, i32 0, i32 %k + %x = load i32, ptr %q, align 4 + %s3 = mul i32 %s, 3 + %s1 = add i32 %s3, %x + %j1 = add i32 %j, 1 + %again = icmp ult i32 %j1, {n} + br i1 %again, label %read, label %done +done: + %g = zext i32 %gid to i64 + %o = getelementptr inbounds i32, ptr addrspace(1) %out, i64 %g + store i32 %s1, ptr addrspace(1) %o, align 4 + ret void +}} + +define void @plain(ptr addrspace(1) %out, i32 %gid) {{ +entry: + %g = zext i32 %gid to i64 + %o = getelementptr inbounds i32, ptr addrspace(1) %out, i64 %g + store i32 %gid, ptr addrspace(1) %o, align 4 + ret void +}} + +!air.kernel = !{{!0, !3}} +!0 = !{{ptr @arena, !1, !2}} +!3 = !{{ptr @plain, !1, !2}} +!1 = !{{}} +!2 = !{{!10, !12}} +!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"}} +!12 = !{{i32 1, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"gid"}} +"# + ) + } + + /// What thread `gid` of `arena` of `n` words writes. + fn reference(n: u32, gid: u32) -> u32 { + let a: Vec = (0..n) + .map(|i| gid.wrapping_mul(31).wrapping_add(i)) + .collect(); + (0..n).fold(0u32, |s, j| { + let k = (j.wrapping_mul(7).wrapping_add(gid)) % n; + s.wrapping_mul(3).wrapping_add(a[k as usize]) + }) + } + + /// 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() + } + + /// The barriers of one command buffer that dispatches `kernels` in turn, one encoder, each into + /// its own of `outs`. + fn barriers( + name: &str, + device: &Device, + kernels: &[&ComputePipelineState], + outs: &[Buffer], + ) -> (u64, crate::Metrics) { + let counters = device.counters(); + let before = counters.metrics(); + 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"); + for (kernel, out) in kernels.iter().zip(outs) { + encoder.set_compute_pipeline_state(kernel).expect("a state"); + encoder.set_buffer(Some(out), 0, 0).expect("out"); + (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}"); + let after = counters.metrics(); + (after.barriers - before.barriers, after) + } + + #[test] + fn every_device_holds_private_memory_past_the_floor_in_its_arena_split_or_whole() { + let threads = (GROUPS * THREADS) as usize; + for n in [7176u32, 9216, 51_200] { + let bitcode = match llvm_assemble_text(&module(n)) { + Ok(bitcode) => bitcode, + Err(AssembleError::Missing(why)) => { + eprintln!("SKIPPED: {why}"); + return; + } + Err(error) => panic!("private_arena: {error:?}"), + }; + let library = Library::from_air(&bitcode).expect("the library"); + let want: Vec = (0..threads as u32).map(|gid| reference(n, gid)).collect(); + let slot = u64::from(4 * n); + // A budget of two threadgroups' slots at 28,704 bytes, four at 36 KiB, one at 200 KiB. + let per_piece = match n { + 7176 => 2, + 9216 => 4, + _ => 1, + }; + let small = per_piece * u64::from(THREADS) * slot; + each_device("private_arena", |name, _, device| { + let arena = state(name, &device, &library, "arena"); + let plain = state(name, &device, &library, "plain"); + let block = (device.take_block(MemoryClass::Shared, 1 << 20)).expect("a block"); + let outs: Vec = (0..4) + .map(|k| { + (device.new_buffer(block.id, 4096 * k, 4096, Some(0))).expect("a buffer") + }) + .collect(); + // Kernels without an arena: four dispatches into four buffers take the barriers one + // does, no more. + let (one, _) = barriers(name, &device, &[&plain], &outs[..1]); + let (four, _) = barriers(name, &device, &[&plain, &plain, &plain, &plain], &outs); + assert_eq!( + four, one, + "{name}: dispatches without an arena add no barrier" + ); + for budget in [0, small] { + device.core().arena_budget.store(budget, Relaxed); + let pieces = match budget { + 0 => 1, + _ => u64::from(GROUPS) / per_piece, + }; + let counters = device.counters(); + let before = counters.metrics(); + let kernels = [&plain, &arena, &arena, &plain]; + let (barriers, after) = barriers(name, &device, &kernels, &outs); + let what = format!("{name}: {n} words, budget {budget}"); + for k in [1, 2] { + assert_eq!(words(&outs[k], threads), want, "{what}: arena dispatch {k}"); + } + assert_eq!( + after.private_arena_dispatches - before.private_arena_dispatches, + 2, + "{what}" + ); + assert_eq!( + after.private_arena_pieces - before.private_arena_pieces, + 2 * pieces, + "{what}" + ); + // The first dispatch takes a block where none a command buffer keeps holds its + // slots; the second reaches the first's. + let taken = after.private_arena_blocks - before.private_arena_blocks; + assert!(taken <= 1, "{what}: {taken} blocks"); + let ordered = 2 * pieces - taken; + assert_eq!(barriers, one + ordered, "{what}: barriers"); + println!( + "{what}: {pieces} pieces a dispatch, {taken} block taken, {ordered} \ + barriers before arena pieces" + ); + } + device.core().arena_budget.store(0, Relaxed); + drop((arena, plain, outs)); + (device.release_block(block)).unwrap_or_else(|error| panic!("{name}: {error}")); + }); + } + } +} diff --git a/crates/metal2vulkan/src/bind/plan/compute.rs b/crates/metal2vulkan/src/bind/plan/compute.rs index c510a8d9c..d6d0fadc3 100644 --- a/crates/metal2vulkan/src/bind/plan/compute.rs +++ b/crates/metal2vulkan/src/bind/plan/compute.rs @@ -448,9 +448,11 @@ fn plan(p: &ComputePipeline, device: &Device, shape: &BindShape) -> Result {} - // The identity domains' zero range is the runtime's own memory, and their bicubic - // slot's format treatment the runtime's own field. - PushField::ZeroAddress | PushField::BicubicTexels(_) => { + // The identity domains' zero range and private arena are the runtime's own memory, and + // their bicubic slot's format treatment the runtime's own field. + PushField::ZeroAddress + | PushField::BicubicTexels(_) + | PushField::PrivateArenaAddress => { return Err(not_implemented(Feature::IdentityDomains)) } PushField::SlotBindOffset(SlotRef { diff --git a/crates/metal2vulkan/src/cache/codec.rs b/crates/metal2vulkan/src/cache/codec.rs index 752deac31..823b6f8dc 100644 --- a/crates/metal2vulkan/src/cache/codec.rs +++ b/crates/metal2vulkan/src/cache/codec.rs @@ -905,6 +905,7 @@ codec_enum! { ArgumentTableAddress, ConstexprSampler(f0), TessellationFactorAddress, + PrivateArenaAddress, SlotBounds(f0), ZeroAddress, FetchedColor { color, texels }, @@ -1299,6 +1300,7 @@ codec_enum! { TexelBufferParts { slot }, AddressAlignment { slot, align }, GridTiles, + PrivateArena { slot_bytes }, } UniformViewChoice { Viewed, Spare, Kept } Mechanism { diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index a71033cc7..aceb09503 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 = 2244; +pub const SEMANTICS_VERSION: u32 = 2245; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another @@ -71,7 +71,7 @@ pub const SEMANTICS_VERSION: u32 = 2244; /// re-typed in an encoded type, its `codec` body or its `envelope`. A variant removed while its tag /// stays unused needs no bump: an entry holding it fails to decode, which is a miss. The commit that /// bumps it says what changed; this comment keeps no history. -pub const ARTIFACT_FORMAT_VERSION: u32 = 581; +pub const ARTIFACT_FORMAT_VERSION: u32 = 582; /// The version of what this crate's runtime does with a compiled pipeline: instantiating a binding /// plan (`BindingPlan::instantiate_*`: descriptor ranges, push bytes, root, argument, and handle @@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 581; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 2549; +pub const RUNTIME_VERSION: u32 = 2550; /// Writes a digest as lowercase hex. pub(crate) fn write_hex(f: &mut fmt::Formatter<'_>, name: &str, hash: &Hash256) -> fmt::Result { diff --git a/crates/metal2vulkan/src/device/function_storage.rs b/crates/metal2vulkan/src/device/function_storage.rs index 45538934a..3083487b5 100644 --- a/crates/metal2vulkan/src/device/function_storage.rs +++ b/crates/metal2vulkan/src/device/function_storage.rs @@ -13,10 +13,13 @@ //! runs up to [`METAL`], 192 KiB a thread, the most a Metal device was measured to hold, and //! records `PrecisionNote::FunctionStorageAssumed`: past the floor it rests on no measurement, and //! a driver that holds less can answer wrongly or hang the GPU, as the RTX 5080 at 48 KiB and the -//! RTX 3090 at 192 KiB hung when probed. A kernel, an object or a mesh function past the floor is -//! refused, as is a vertex or fragment function past [`METAL`]: typed (`Unsupported{PrivateMemory}`, -//! or `Unsupported{Recursion}` for a stage with a call stack, needing -//! `VkLimit::FunctionStorageBytesPerThread`). +//! RTX 3090 at 192 KiB hung when probed. A kernel without a call stack past the floor keeps the +//! private memory a run-time index reaches in device memory the runtime owns, one slot a thread +//! (`memory::plan::ArenaLayout::device`, `RuntimeFact::PrivateArena`), and what is left is held +//! to the floor. An object or a mesh function past the floor is refused, as are a kernel with a +//! call stack past it, a tile function past it, and a vertex or fragment function past [`METAL`]: +//! typed (`Unsupported{PrivateMemory}`, or `Unsupported{Recursion}` for a stage with a call stack, +//! needing `VkLimit::FunctionStorageBytesPerThread`). //! //! [`ProfileFields::function_storage`]: crate::device::profile::ProfileFields::function_storage diff --git a/crates/metal2vulkan/src/device/mechanism.rs b/crates/metal2vulkan/src/device/mechanism.rs index a4e22f9e5..2e0968aa5 100644 --- a/crates/metal2vulkan/src/device/mechanism.rs +++ b/crates/metal2vulkan/src/device/mechanism.rs @@ -178,6 +178,9 @@ pub fn mechanism(fact: &RuntimeFact, profile: &DeviceProfile) -> Mechanism { RuntimeFact::PartialThreadgroups => Mechanism::Variant, // The binder's regions carry the tile as the nominal size, under `MultiRegion` 1. RuntimeFact::GridTiles => Mechanism::RegionSelected, + // The runtime pushes its arena's address, and sizes and orders the arena's slots by the + // slot's bytes. + RuntimeFact::PrivateArena { .. } => Mechanism::PushConstant, // Keyed by the slots bound to a texture whose planes are read in place, on a profile that // reads them so (`ProfileFields::ycbcr_in_place`). RuntimeFact::YCbCrInPlace { .. } => Mechanism::Variant, diff --git a/crates/metal2vulkan/src/lower/access/local.rs b/crates/metal2vulkan/src/lower/access/local.rs index 8fa38adbd..881aa79ae 100644 --- a/crates/metal2vulkan/src/lower/access/local.rs +++ b/crates/metal2vulkan/src/lower/access/local.rs @@ -452,6 +452,9 @@ pub struct LocalPlan { pub tg: Option, /// The private arena's byte size, when a pointer into it is used. pub private: Option, + /// The private arena lives in device memory, an invocation's slot of the runtime's memory + /// (`memory::plan::ArenaLayout::device`). + pub private_device: bool, /// The payload's byte size (its parameter's `air.arg_type_size`), when a pointer into it is /// used. pub payload: Option, @@ -649,10 +652,33 @@ fn zero_threadgroup(cx: &mut SelectCx<'_>) -> Result<(), Error> { Ok(()) } +/// The private arena of `size` bytes in device memory (`ArenaLayout::device`): a slot of +/// `size` rounded up to 16 bytes for each invocation of a dispatch, at the address the runtime +/// pushes (`PushField::PrivateArenaAddress`), which the pipeline names with the slot's bytes +/// (`RuntimeFact::PrivateArena`). A tile function, whose invocations a render pass's tiles +/// place, keeps the refusal of private memory past the floor. +fn device_arena(cx: &mut SelectCx<'_>, size: u64) -> Result<(), Error> { + let slot = size.next_multiple_of(16); + if super::tile::is_tile(cx) { + let limit = Capability::Limit { + limit: crate::device::VkLimit::FunctionStorageBytesPerThread, + required: slot.saturating_add(cx.memory.private_bytes), + available: crate::device::function_storage::FLOOR, + }; + return Err(Unsupported::needs(Feature::PrivateMemory, limit).into()); + } + let slot_bytes = + u32::try_from(slot).map_err(|_| Error::LimitExceeded(Limit::PrivateArenaBytes))?; + cx.push + .insert(crate::pipeline::sym::PushField::PrivateArenaAddress); + cx.facts.insert(RuntimeFact::PrivateArena { slot_bytes }); + Ok(()) +} + /// Record that the function uses `arena`. The threadgroup arena's shape is fixed and checked /// against `maxComputeSharedMemorySize` once, and every region's length becomes a runtime fact of /// the function. A private arena past `budget::PRIVATE_ARENA_BYTES` is -/// `LimitExceeded(PrivateArenaBytes)`. +/// `LimitExceeded(PrivateArenaBytes)`; one in device memory is the runtime's ([`device_arena`]). pub(super) fn use_arena(cx: &mut SelectCx<'_>, arena: Arena) -> Result<(), Error> { match arena { Arena::Threadgroup => { @@ -726,6 +752,10 @@ pub(super) fn use_arena(cx: &mut SelectCx<'_>, arena: Arena) -> Result<(), Error if size > PRIVATE_ARENA_BYTES { return Err(Error::LimitExceeded(Limit::PrivateArenaBytes)); } + if cx.memory.priv_arena.device { + device_arena(cx, size)?; + cx.families.access.local.private_device = true; + } cx.families.access.local.private = Some(size); } } @@ -1113,7 +1143,7 @@ pub fn declare(mb: &mut ModuleBuilder, plan: &Plan) -> BResult { None => None, }, private: match p.private { - Some(size) => Some(arena::declare_private(mb, size)?), + Some(size) => Some(arena::declare_private(mb, size, p.private_device)?), None => None, }, payload: match p.payload { @@ -1944,6 +1974,9 @@ pub(super) fn decl_of( if let Some(tile) = fragment { decl.tile_base = Some(cx.tile_base(fb, tile)?); } + if arena == Arena::Private && cx.plan.families.access.local.private_device { + decl.slot = Some(cx.arena_slot(fb)?); + } Ok(decl) } @@ -2061,7 +2094,10 @@ fn float_words( } let two = k32(fb, 2)?; let first = fb.binary(BinOp::ShiftRightLogical, off, two)?; - let base = fb.module().global_value(decl.global)?; + let Some(global) = decl.global else { + return Err(cx.fail("an arena of float words without its array")); + }; + let base = fb.module().global_value(global)?; let access = ops.access(fb, MemAccess::default(), stored.is_some())?; let mut loaded = Vec::with_capacity(lanes as usize); for j in 0..lanes { diff --git a/crates/metal2vulkan/src/lower/dispatch.rs b/crates/metal2vulkan/src/lower/dispatch.rs index a3a593540..119167f8c 100644 --- a/crates/metal2vulkan/src/lower/dispatch.rs +++ b/crates/metal2vulkan/src/lower/dispatch.rs @@ -536,6 +536,9 @@ pub struct DispatchPlan { /// A kernel of the [`LocalSizeForm::Spec`] form without compute derivatives (whose quads are two-dimensional): it declares /// `SpecKey::DeepThreadgroup`, under which its threadgroup runs as one row (the module docs). pub deep: bool, + /// A kernel whose private arena lives in device memory (`memory::plan::ArenaLayout::device`): + /// each invocation reaches its slot by its index in its dispatch ([`arena_slot`]). + pub private_arena: bool, } /// The words a flat grid adds: its thread's index, position, and early return, derived once for the @@ -744,6 +747,7 @@ pub fn plan_kernel(cx: &mut SelectCx<'_>, tier: Tier) -> Result, fb: &mut FunctionBuilder<'_>) -> BResult< let Some(plan) = cx.plan.dispatch.as_ref() else { return Ok(()); }; + // The private arena's slot, in the first block, which every access of the arena reads. + if plan.private_arena { + cx.arena_slot(fb)?; + } // A flat grid's invocation past the grid's last thread returns before the body. Its position // is derived here once, with the test, and is the `thread_position_in_grid` every parameter // reads: a second derivation would repeat the divisions in a construct of its own, which the @@ -979,6 +987,8 @@ pub struct KernelDecl { uvec3: TypeId, /// `sx, sy, sz`. size: [ConstId; 3], + /// The `WorkgroupSize` composite. + workgroup: ConstId, /// `SpecKey::DeepThreadgroup`, where the plan declares it ([`DispatchPlan::deep`]). deep: Option, /// How the kernel tells a region, when it reads a grid builtin. @@ -1080,14 +1090,20 @@ impl Needs { .any(has) || (local_pos && (dp.local_size == LocalSizeForm::Flat || dp.tile)) || partial; + // A private arena in device memory counts its slot from the workgroup's position. + let arena = dp.private_arena; Needs { lin, local_pos, workgroup_id: folded || partial + || arena || has(K::ThreadPositionInGrid) || has(K::ThreadgroupPositionInGrid), - num_workgroups: folded || has(K::ThreadsPerGrid) || has(K::ThreadgroupsPerGrid), + num_workgroups: folded + || arena + || has(K::ThreadsPerGrid) + || has(K::ThreadgroupsPerGrid), } } } @@ -1240,7 +1256,7 @@ impl KernelDecl { .map(|(k, d)| mb.spec(k, u32_, ConstBits(u64::from(d)))); let size = [sx?, sy?, sz?]; let mut deep = None; - match dp.local_size { + let workgroup = match dp.local_size { LocalSizeForm::Spec if dp.deep => { let b = mb.ty(Type::Bool)?; let one_row = mb.spec(SpecKey::DeepThreadgroup, b, ConstBits(0))?; @@ -1252,12 +1268,10 @@ impl KernelDecl { })?; let [x, y, z] = [(sn, size[0]), (one, size[1]), (one, size[2])] .map(|(deep, own)| mb.spec_op(SpecOp::Select, u32_, &[one_row, deep, own])); - mb.workgroup_size(x?, y?, z?)?; deep = Some(one_row); + mb.workgroup_size(x?, y?, z?)? } - LocalSizeForm::Spec => { - mb.workgroup_size(size[0], size[1], size[2])?; - } + LocalSizeForm::Spec => mb.workgroup_size(size[0], size[1], size[2])?, LocalSizeForm::Flat => { let n = u64::from(dx) * u64::from(dy) * u64::from(dz); let sn = mb.spec(keys.flat, u32_, ConstBits(n))?; @@ -1265,9 +1279,9 @@ impl KernelDecl { ty: u32_, bits: ConstBits(1), })?; - mb.workgroup_size(sn, one, one)?; + mb.workgroup_size(sn, one, one)? } - } + }; let multi_region = match (dp.multi_region, dp.identity) { (false, _) => None, (true, identity) => { @@ -1291,7 +1305,8 @@ impl KernelDecl { // A grid tile counts by `LocalInvocationIndex` in either form too, and a deep // threadgroup's position is unflattened from it. let index = (needs.lin && (!flat || by_index || dp.grid_edge)) - || (needs.local_pos && deep.is_some()); + || (needs.local_pos && deep.is_some()) + || dp.private_arena; let subgroups = needs.lin && flat && !by_index && !dp.grid_edge; use crate::spv::BuiltIn as B; let mut var = |on: bool, b: crate::spv::BuiltIn, ty: TypeId| -> BResult> { @@ -1315,6 +1330,7 @@ impl KernelDecl { draw_index: var(dp.draw_pieces, B::DrawIndex, u32_)?, uvec3, size, + workgroup, deep, multi_region, local_id: var( @@ -1339,6 +1355,44 @@ impl KernelDecl { }) } + /// The device address (a `u64`) of the invocation's slot of `slot_bytes` in the private + /// arena at `arena` (`PushField::PrivateArenaAddress`): `arena + i · slot_bytes` for its index + /// in its dispatch `i = ((wz · ny + wy) · nx + wx) · n + LocalInvocationIndex`, `n` the + /// workgroup's invocations. The runtime keeps a dispatch's invocations under 2^32, so `i` is + /// counted in 32 bits. + pub(crate) fn arena_slot( + &self, + fb: &mut FunctionBuilder<'_>, + arena: SValue, + slot_bytes: u32, + ) -> BResult { + let wg = self.load(fb, self.workgroup_id)?; + let groups = self.load(fb, self.num_workgroups)?; + let index = self.load(fb, self.local_index)?; + let size = fb.module().const_value(self.workgroup)?; + let n = Self::volume(fb, size)?; + let [wx, wy, wz] = [0, 1, 2].map(|i| fb.composite_extract(wg, &[i])); + let [nx, ny] = [0, 1].map(|i| fb.composite_extract(groups, &[i])); + let group = fb.binary(BinOp::IMul, wz?, ny?)?; + let group = fb.binary(BinOp::IAdd, group, wy?)?; + let group = fb.binary(BinOp::IMul, group, nx?)?; + let group = fb.binary(BinOp::IAdd, group, wx?)?; + let first = fb.binary(BinOp::IMul, group, n)?; + let at = fb.binary(BinOp::IAdd, first, index)?; + let u64_ = fb.module().ty(Type::Int { + width: 64, + signed: false, + })?; + let at = fb.convert(ConvOp::UConvert, at, u64_)?; + let bytes = fb.module().constant(Constant::Scalar { + ty: u64_, + bits: ConstBits(u64::from(slot_bytes)), + })?; + let bytes = fb.module().const_value(bytes)?; + let offset = fb.binary(BinOp::IMul, at, bytes)?; + fb.binary(BinOp::IAdd, arena, offset) + } + fn load(&self, fb: &mut FunctionBuilder<'_>, g: Option) -> BResult { let Some(g) = g else { return Err(dangling_value()); diff --git a/crates/metal2vulkan/src/lower/dispatch/tests.rs b/crates/metal2vulkan/src/lower/dispatch/tests.rs index 115a82d4c..68e1c5b12 100644 --- a/crates/metal2vulkan/src/lower/dispatch/tests.rs +++ b/crates/metal2vulkan/src/lower/dispatch/tests.rs @@ -41,6 +41,7 @@ fn plan(form: LocalSizeForm, multi_region: bool) -> DispatchPlan { identity: false, pinned_subgroup_size: None, deep: false, + private_arena: false, } } diff --git a/crates/metal2vulkan/src/lower/emit.rs b/crates/metal2vulkan/src/lower/emit.rs index c15fa368f..00d35e6c4 100644 --- a/crates/metal2vulkan/src/lower/emit.rs +++ b/crates/metal2vulkan/src/lower/emit.rs @@ -47,6 +47,7 @@ use crate::lower::{ access, arith, dispatch, fragment, mesh, raytracing, sampler, simd, stage_io, sync, tessellation, texture, }; +use crate::pipeline::facts::RuntimeFact; use crate::pipeline::interface::PushLoc; use crate::pipeline::sym::{PushField, SlotRef, Stage}; use crate::spirv::builder::constructs::{ArmEnd, ArmFn}; @@ -236,6 +237,9 @@ enum Invariant { /// A fragment function's tile's first word in the pass's tile memory buffer /// (`access::tile_memory::base`), computed at entry (`access::tile_memory::emit_entry`). TileBase, + /// A kernel's slot of the runtime's private arena ([`EmitCx::arena_slot`]), computed at entry + /// (`dispatch::emit_entry`). + ArenaSlot, /// The table word of the argument buffer's sampler of a handle, tested for a cubic filter /// (`sampler::emit`'s reach test): an operation through the same handle where an earlier test /// dominates it ran that test on the same sampler, so it needs none of its own. @@ -404,6 +408,32 @@ impl<'a> EmitCx<'a> { Ok(v) } + /// The device address of the invocation's slot of the runtime's memory that holds the + /// kernel's private arena (`dispatch::KernelDecl::arena_slot`, of the pushed + /// `PushField::PrivateArenaAddress` and the slot's bytes, `RuntimeFact::PrivateArena`), + /// computed once where it dominates: `dispatch::emit_entry` computes it in the function's + /// first block. + pub(crate) fn arena_slot(&mut self, fb: &mut FunctionBuilder<'_>) -> BResult { + if let Some(v) = self.recall(fb, Invariant::ArenaSlot) { + return Ok(v); + } + let slot_bytes = self.plan.facts.iter().find_map(|f| match *f { + RuntimeFact::PrivateArena { slot_bytes } => Some(slot_bytes), + _ => None, + }); + let Some(slot_bytes) = slot_bytes else { + return Err(self.fail("a private arena in device memory without its slot's bytes")); + }; + let arena = self.push_field(fb, PushField::PrivateArenaAddress)?; + let decl: &Declared = self.decl; + let Some(kernel) = decl.families.dispatch.kernel.as_ref() else { + return Err(self.fail("a private arena in device memory without its kernel")); + }; + let v = kernel.arena_slot(fb, arena, slot_bytes)?; + self.remember(fb, Invariant::ArenaSlot, v); + Ok(v) + } + /// An indexed capture form's raw index, read once where it dominates: /// `stage_io::emit_draw_entry` reads it in the function's first block, which dominates every block of the function, the /// merge of the restart test it then closes included. diff --git a/crates/metal2vulkan/src/lower/mesh/mod.rs b/crates/metal2vulkan/src/lower/mesh/mod.rs index 51668c646..9b4095277 100644 --- a/crates/metal2vulkan/src/lower/mesh/mod.rs +++ b/crates/metal2vulkan/src/lower/mesh/mod.rs @@ -1402,7 +1402,7 @@ pub fn wrap_entry(cx: &mut EmitCx<'_>, mb: &mut ModuleBuilder, body: FuncId) -> let grid = fb.load(p, access)?; let [x, y, z] = [0, 1, 2].map(|i| fb.composite_extract(grid, &[i])); let [x, y, z] = bounded_grid(cx, &mut fb, [x?, y?, z?])?; - let payload = cx.decl.families.access.local.payload.map(|d| d.global); + let payload = cx.decl.families.access.local.payload.and_then(|d| d.global); fb.emit_mesh_tasks(x, y, z, payload)?; return fb.finish(); } diff --git a/crates/metal2vulkan/src/lower/push.rs b/crates/metal2vulkan/src/lower/push.rs index 1fac5c0ac..79150c09d 100644 --- a/crates/metal2vulkan/src/lower/push.rs +++ b/crates/metal2vulkan/src/lower/push.rs @@ -157,7 +157,8 @@ pub const fn shape(f: PushField) -> FieldShape { | PushField::MergedDrawAddress | PushField::CommandRecordsAddress | PushField::ReplayRegionAddress - | PushField::TessellationFactorAddress => FieldShape::U64, + | PushField::TessellationFactorAddress + | PushField::PrivateArenaAddress => FieldShape::U64, // A Metal address, low word first: the same eight bytes as a `u64`, readable without // `shaderInt64`. PushField::SlotGuestBase(_) => FieldShape::UVec2, diff --git a/crates/metal2vulkan/src/lower/select.rs b/crates/metal2vulkan/src/lower/select.rs index 3a28be231..4569fee86 100644 --- a/crates/metal2vulkan/src/lower/select.rs +++ b/crates/metal2vulkan/src/lower/select.rs @@ -1140,7 +1140,9 @@ pub fn selector_form( } /// Whether `p`'s device holds `e`'s private memory: what a driver backs with scratch, the plan's -/// `private_bytes` (the private arena, and each typed `alloca`, call stacks among them, and each +/// `private_bytes` (the private arena where it is not in the runtime's device memory, which a +/// kernel's past the floor is, `memory::plan::ArenaLayout::device`; and each typed `alloca`, call +/// stacks among them, and each /// constant held as a `Private` variable that an access indexes at run time), may take a thread /// up to `device::function_storage::ceiling`: the profile's `function_storage`, or Metal's 192 KiB /// for a vertex or fragment function on a device not measured. Past it the entry is @@ -1923,7 +1925,9 @@ fn identity_unsourced(f: &RuntimeFact) -> bool { /// fragment function reads a colour attachment through (`PushField::FetchedColor`, framebuffer /// fetch on a device with neither ordered form); and the render pass's length, at or past which a /// vertex function that writes `[[render_target_array_index]]` stores `Layer` 0 -/// (`PushField::RenderTargetArrayLength`). Its fields past the push window are a parameter block, whose +/// (`PushField::RenderTargetArrayLength`); and the address of the runtime's memory that holds a +/// kernel's private arena past the floor (`PushField::PrivateArenaAddress`). Its fields past the +/// push window are a parameter block, whose /// address the window holds. Its refusal names the first form the plan holds that they do not /// lower ([`identity_refusal`]). fn identity_admits(plan: &Plan) -> Result<(), Error> { @@ -1966,6 +1970,7 @@ fn identity_refusal(plan: &Plan) -> Option { | PushField::AlphaTestReference | PushField::FetchedColor { .. } | PushField::RenderTargetArrayLength + | PushField::PrivateArenaAddress ), }); if let Some(f) = field { diff --git a/crates/metal2vulkan/src/memory/arena.rs b/crates/metal2vulkan/src/memory/arena.rs index adb60c710..0421a2fe1 100644 --- a/crates/metal2vulkan/src/memory/arena.rs +++ b/crates/metal2vulkan/src/memory/arena.rs @@ -66,11 +66,11 @@ use crate::memory::leaf::{Coherence, WordMem, WordOps}; use crate::memory::plan::ArenaLayout; use crate::pipeline::sym::{ResourceKind, ResourceSlot, SpecKey, Stage, SyntheticBinding}; use crate::spirv::builder::{FunctionBuilder, ModuleBuilder}; -use crate::spirv::error::BResult; +use crate::spirv::error::{BResult, BuildError, Dangling}; use crate::spirv::ids::{ConstId, GlobalId, TypeId, Value}; use crate::spirv::ir::{ - AtomicOp, BinOp, ConstBits, Constant, MemAccess, Scope, Semantics, SpecOp, StorageClass, Type, - UnOp, + AtomicOp, BinOp, ConstBits, Constant, ConvOp, MemAccess, Scope, Semantics, SpecOp, + StorageClass, Type, UnOp, }; /// The smallest arena array in bytes: the widest leaf (4 lanes of 8 bytes). A contained @@ -278,11 +278,12 @@ pub fn workgroup_limit(stage: Stage, limits: &Limits) -> WorkgroupLimit { /// A declared arena: its `u32` array variable and its byte size, the containment domain (a /// plain `u32` constant, or for a threadgroup arena with regions an `OpSpecConstantOp`), or a -/// threadgroup arena's `float` array. +/// threadgroup arena's `float` array. A private arena in device memory has no variable: its words +/// are the invocation's slot of the runtime's memory, at `slot`. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct ArenaDecl { pub arena: Arena, - pub global: GlobalId, + pub global: Option, pub size: ConstId, /// A fragment function's threadgroup arena (the module docs): `global` is the pass's tile /// memory buffer, a storage view, whose word `tile_base` (a `u32` of the function that emits @@ -291,6 +292,10 @@ pub struct ArenaDecl { pub tile_base: Option, /// An arena of `float` words (the module docs): `global` is a `float` array. pub floats: bool, + /// A private arena in device memory (`memory::plan::ArenaLayout::device`): the device address + /// (a `u64` of the function that emits the access, `lower::dispatch::arena_slot`) of the + /// invocation's slot, the arena's word 0. `None` for any other arena, and in the declaration. + pub slot: Option, } /// The declared threadgroup arena and the byte offset of each region: `(parameter, offset)` in @@ -416,10 +421,11 @@ pub fn declare_threadgroup( return Ok(TgDecl { decl: ArenaDecl { arena: Arena::Threadgroup, - global, + global: Some(global), size, tile_base: None, floats, + slot: None, }, regions: Vec::new(), imageblock: None, @@ -488,10 +494,11 @@ pub fn declare_threadgroup( Ok(TgDecl { decl: ArenaDecl { arena: Arena::Threadgroup, - global, + global: Some(global), size, tile_base: None, floats, + slot: None, }, regions, imageblock, @@ -518,10 +525,11 @@ fn declare_fragment(mb: &mut ModuleBuilder, shape: &TgShape, coord: usize) -> BR Ok(TgDecl { decl: ArenaDecl { arena: Arena::Threadgroup, - global: view.global, + global: Some(view.global), size: tile_length(mb)?, tile_base: None, floats: false, + slot: None, }, regions, imageblock: None, @@ -564,24 +572,32 @@ pub fn declare_payload(mb: &mut ModuleBuilder, size: u64) -> BResult let global = array(mb, StorageClass::TaskPayloadWorkgroupEXT, words, false)?; Ok(ArenaDecl { arena: Arena::Payload, - global, + global: Some(global), size: bytes, tile_base: None, floats: false, + slot: None, }) } -/// Declare the private arena of `size` bytes. -pub fn declare_private(mb: &mut ModuleBuilder, size: u64) -> BResult { +/// Declare the private arena of `size` bytes: a `Private` array, or where it is in `device` +/// memory, no variable (its words are the invocation's slot of the runtime's memory). +pub fn declare_private(mb: &mut ModuleBuilder, size: u64, device: bool) -> BResult { let bytes = konst(mb, size)?; - let words = konst(mb, static_words(size))?; - let global = array(mb, StorageClass::Private, words, false)?; + let global = match device { + true => None, + false => { + let words = konst(mb, static_words(size))?; + Some(array(mb, StorageClass::Private, words, false)?) + } + }; Ok(ArenaDecl { arena: Arena::Private, global, size: bytes, tile_base: None, floats: false, + slot: None, }) } @@ -595,10 +611,32 @@ pub fn declare_private(mb: &mut ModuleBuilder, size: u64) -> BResult pub struct ArenaMem(pub ArenaDecl, pub WordOps); impl ArenaMem { - /// A pointer to word `word` (a `u32` index) of the arena: of its array, or for a fragment - /// function's tile memory, word `tile_base + word` of the pass's buffer. + /// A pointer to word `word` (a `u32` index) of the arena: of its array, for a fragment + /// function's tile memory word `tile_base + word` of the pass's buffer, or for a private arena + /// in device memory the `PhysicalStorageBuffer` word `4 · word` bytes past its slot. pub fn ptr(&self, fb: &mut FunctionBuilder<'_>, word: Value) -> BResult { - let base = fb.module().global_value(self.0.global)?; + let global = match (self.0.slot, self.0.global) { + (Some(slot), _) => { + let u64_ = fb.module().ty(Type::Int { + width: 64, + signed: false, + })?; + let u32_ = u32_ty(fb.module())?; + // An arena's bytes fit `u32`, so its byte offset does. + let two = crate::memory::leaf::k32(fb, 2)?; + let at = fb.binary(BinOp::ShiftLeftLogical, word, two)?; + let at = fb.convert(ConvOp::UConvert, at, u64_)?; + let address = fb.binary(BinOp::IAdd, slot, at)?; + return fb.device_place(address, u32_); + } + (None, Some(global)) => global, + // A private arena in device memory reached before its function placed its slot + // (`lower::access::local::decl_of` places it). + (None, None) => { + return Err(BuildError::Dangling(Dangling::Value(Value::new(u32::MAX)))) + } + }; + let base = fb.module().global_value(global)?; match self.0.tile_base { None => fb.access_chain(base, &[word]), Some(first) => { @@ -628,8 +666,11 @@ impl ArenaMem { fn access(&self, fb: &mut FunctionBuilder<'_>, store: bool) -> BResult { match self.0.arena { Arena::Threadgroup => self.1.access(fb, MemAccess::default(), store), + // A word in device memory is aligned to 4, as a `PhysicalStorageBuffer` access + // states. Arena::Private | Arena::Payload => Ok(MemAccess { volatile: self.1.volatile, + aligned: self.0.slot.map(|_| 4), ..MemAccess::default() }), } diff --git a/crates/metal2vulkan/src/memory/plan.rs b/crates/metal2vulkan/src/memory/plan.rs index 13986b228..781686e5c 100644 --- a/crates/metal2vulkan/src/memory/plan.rs +++ b/crates/metal2vulkan/src/memory/plan.rs @@ -160,6 +160,10 @@ pub struct ArenaLayout { /// bytes hold. The private arena keeps it when some pointer into it may be null /// (`lower::access::local`). pub null_word: bool, + /// The private arena lives in device memory the runtime owns, one slot a thread + /// (`RuntimeFact::PrivateArena`), not in the driver's scratch: a kernel's private memory past + /// the floor ([`Planner::private_memory`]). + pub device: bool, } impl ArenaLayout { @@ -356,7 +360,8 @@ pub struct MemoryPlan { pub typed_allocas: Vec, /// The bytes of private memory a thread holds where a driver backs it with scratch memory, /// which selection holds to the device's Function storage: the private arena (its pointers - /// merge, escape, or reinterpret its bytes), and each typed alloca (a recursion's call stacks + /// merge, escape, or reinterpret its bytes) unless it lives in device memory + /// ([`ArenaLayout::device`]), and each typed alloca (a recursion's call stacks /// among them) and each constant held as a `Private` variable that some access indexes at run /// time, each at its allocation size, and under the identity domains the constant blob, the /// module's `Private` words (`memory::blob`), where some access reaches it at an offset only @@ -778,15 +783,11 @@ impl Planner<'_> { let mut room = super::alloca::MAX_UNSHARED; let (const_globals, blob) = self.const_globals(&mut room, m)?; let tg_arena = self.threadgroup_arena(&[], m)?; - let (priv_arena, typed_allocas, fragment_values) = self.allocas(&mut room, m)?; + let consts = (&const_globals[..], blob.as_ref()); + let (priv_arena, typed_allocas, fragment_values, private_bytes) = + self.private_memory(&mut room, consts, m)?; let tg_metal_static = tg_arena.static_size; let (tg_arena, typed_shared) = self.typed_threadgroup(tg_arena, &mut room, m)?; - let private_bytes = self.private_bytes( - &priv_arena, - &typed_allocas, - (&const_globals, blob.as_ref()), - m, - )?; let Reprs { repr, offsets, @@ -826,8 +827,39 @@ impl Planner<'_> { }) } + /// The private arena, the typed allocas, the `<64 x T>` instructions that are fragments + /// ([`Planner::allocas`]) and the private bytes ([`Planner::private_bytes`]). Under the + /// identity domains, whose consumer supplies the memory (`PushField::PrivateArenaAddress`), a + /// kernel without a call stack whose private bytes pass the floor every device holds + /// (`device::function_storage::FLOOR`) keeps its private memory in device memory instead: every + /// alloca an access indexes at run time goes in the arena, which lives in the runtime's memory + /// ([`ArenaLayout::device`]) and leaves the private bytes. The kernel's own bytes decide, never + /// a device fact; the bytes left are held to the floor as before. + fn private_memory( + &self, + room: &mut u64, + consts: (&[ConstGlobalPlan], Option<&ConstantBlob>), + m: &mut Meter, + ) -> Result<(ArenaLayout, Vec, Vec, u64), Error> { + let start = *room; + let (arena, typed, values) = self.allocas(room, false, m)?; + let bytes = self.private_bytes(&arena, &typed, consts, m)?; + let kernel = super::static_root::stage_of(self.e) == crate::pipeline::sym::Stage::Kernel; + let floor = crate::device::function_storage::FLOOR; + let identity = crate::lower::access::identity(self.p); + if !kernel || !identity || self.e.call_stack.is_some() || bytes <= floor { + return Ok((arena, typed, values, bytes)); + } + *room = start; + let (mut arena, typed, values) = self.allocas(room, true, m)?; + arena.device = true; + let bytes = self.private_bytes(&arena, &typed, consts, m)?; + Ok((arena, typed, values, bytes)) + } + /// The bytes of private memory a thread holds where a driver backs it with scratch memory - /// ([`MemoryPlan::private_bytes`]): the private arena's size, and the allocation size of each + /// ([`MemoryPlan::private_bytes`]): the private arena's size where it is not in device memory, + /// and the allocation size of each /// typed alloca and each `Private` constant some access indexes at run time, the blob among /// them under the identity domains, where it is the module's `Private` words /// (`memory::blob`), at their size. An alloca that holds simdgroup matrices as fragments @@ -839,7 +871,7 @@ impl Planner<'_> { (consts, blob): (&[ConstGlobalPlan], Option<&ConstantBlob>), m: &mut Meter, ) -> Result { - let mut bytes = arena.static_size; + let mut bytes = if arena.device { 0 } else { arena.static_size }; for a in typed .iter() .filter(|a| self.uses(Root::Alloca(a.inst)).indexed) @@ -1982,7 +2014,8 @@ impl Planner<'_> { } /// The private arena and the typed allocas, in instruction order. An alloca a typed object - /// cannot hold, or one past `room`, has its place in the arena. + /// cannot hold, or one past `room`, has its place in the arena; so, where `device`, does one an + /// access indexes at run time ([`Planner::private_memory`]). /// /// An alloca that holds simdgroup matrices is typed only when they hold fragments /// (`memory::fragment`): the candidates are found in a first pass over the room, and the held @@ -1992,6 +2025,7 @@ impl Planner<'_> { fn allocas( &self, room: &mut u64, + device: bool, m: &mut Meter, ) -> Result<(ArenaLayout, Vec, Vec), Error> { let body = self @@ -2001,7 +2035,7 @@ impl Planner<'_> { .and_then(|f| f.body.as_ref()) .ok_or_else(|| invariant("the entry function has no body"))?; let mut charged = 0; - let placed = self.place_allocas(body, room, &mut charged, m); + let placed = self.place_allocas(body, (room, device), &mut charged, m); m.release(charged); placed } @@ -2009,7 +2043,7 @@ impl Planner<'_> { fn place_allocas( &self, body: &crate::air::ir::Body, - room: &mut u64, + (room, device): (&mut u64, bool), charged: &mut usize, m: &mut Meter, ) -> Result<(ArenaLayout, Vec, Vec), Error> { @@ -2048,6 +2082,7 @@ impl Planner<'_> { let fragments = held.contains(&id); let typed_here = match shape { Some(_) if fragments => true, + Some(_) if device && self.uses(Root::Alloca(id)).indexed => false, Some((_, size, false)) => match room.checked_sub(size) { Some(left) => { *room = left; diff --git a/crates/metal2vulkan/src/pipeline/facts.rs b/crates/metal2vulkan/src/pipeline/facts.rs index fc0ee7b18..f67edadd3 100644 --- a/crates/metal2vulkan/src/pipeline/facts.rs +++ b/crates/metal2vulkan/src/pipeline/facts.rs @@ -832,6 +832,14 @@ pub enum RuntimeFact { /// body; an unflagged region runs no test of the grid's edge. Its plans run a `dispatchThreads` /// grid in such tiles, flagged where the tile does not divide it. GridTiles, + /// The kernel's private memory past the floor every device holds + /// (`device::function_storage::FLOOR`) lives in memory the runtime owns: a slot of + /// `slot_bytes` (a multiple of 16) for each invocation of a dispatch, at the address it pushes + /// (`PushField::PrivateArenaAddress`, which says which slot an invocation takes). A dispatch + /// whose invocations' slots pass what the runtime keeps runs as several dispatches, each of + /// them in its own slots' memory or ordered after the last one that used it. The kernel's own + /// bytes decide it, never a device fact. + PrivateArena { slot_bytes: u32 }, } impl RuntimeFact { @@ -941,6 +949,7 @@ impl RuntimeFact { RuntimeFact::TexelBufferParts { .. } => "TexelBufferParts", RuntimeFact::AddressAlignment { .. } => "AddressAlignment", RuntimeFact::GridTiles => "GridTiles", + RuntimeFact::PrivateArena { .. } => "PrivateArena", } } } diff --git a/crates/metal2vulkan/src/pipeline/sym.rs b/crates/metal2vulkan/src/pipeline/sym.rs index cee2a9264..3b273beed 100644 --- a/crates/metal2vulkan/src/pipeline/sym.rs +++ b/crates/metal2vulkan/src/pipeline/sym.rs @@ -1142,6 +1142,15 @@ pub enum PushField { /// pipeline's interface states it in a vertex-stage placement of its own, at the /// `TessellationState::push_offset`. TessellationFactorAddress, + /// The device address (`u64`, a multiple of 16) of the runtime's memory that holds a kernel's + /// private arena past the floor (`RuntimeFact::PrivateArena`): one slot of the fact's + /// `slot_bytes` for each invocation of the dispatch, the invocation's slot its index in its + /// dispatch, `((wz · ny + wy) · nx + wx) · n + LocalInvocationIndex` with `(wx, wy, wz)` its + /// `WorkgroupId`, `(nx, ny, nz)` the dispatch's `NumWorkgroups` and `n` its workgroup's + /// invocations. The memory holds a slot for every invocation of the dispatch, and no other + /// dispatch that may run beside it reaches those slots. Nothing is zeroed: the arena's bytes + /// are undefined until the thread writes them, as Metal's private memory is. + PrivateArenaAddress, // The check's fields come last in the order: what every access reads is placed ahead of what // only a checked access reads, so where a function's fields spill into its parameter block // they are the first to go. diff --git a/crates/metal2vulkan/src/spirv/interp/tests.rs b/crates/metal2vulkan/src/spirv/interp/tests.rs index 9ab083f77..b3ec5fd1a 100644 --- a/crates/metal2vulkan/src/spirv/interp/tests.rs +++ b/crates/metal2vulkan/src/spirv/interp/tests.rs @@ -884,7 +884,10 @@ fn a_small_specialized_threadgroup_arena_is_floored_at_eight_words() { fragment: None, words: Default::default(), }; - Ok(declare_threadgroup(mb, &shape, false)?.decl.global) + Ok(declare_threadgroup(mb, &shape, false)? + .decl + .global + .expect("a threadgroup arena's array")) }); let mut res = buffers(&[64]); res.spec.insert(SpecKey::TgLength(0), len); @@ -909,7 +912,10 @@ fn a_small_specialized_threadgroup_arena_is_floored_at_eight_words() { fragment: None, words: Default::default(), }; - Ok(declare_threadgroup(mb, &shape, false)?.decl.global) + Ok(declare_threadgroup(mb, &shape, false)? + .decl + .global + .expect("a threadgroup arena's array")) }); let mut res = buffers(&[64]); res.spec.insert(SpecKey::TgLength(0), 48); diff --git a/crates/metal2vulkan/src/tests/engine_private_memory.rs b/crates/metal2vulkan/src/tests/engine_private_memory.rs index 4ad6037cb..b3c8cfc92 100644 --- a/crates/metal2vulkan/src/tests/engine_private_memory.rs +++ b/crates/metal2vulkan/src/tests/engine_private_memory.rs @@ -23,6 +23,8 @@ //! `llvm-as` assembles the functions; a missing tool skips visibly. use crate::budget::SPIRV_WORDS; +use crate::device::profile::{HandleDomain, PointerDomain}; +use crate::device::DevicePolicy; use crate::device::{DeviceProfile, VkLimit}; use crate::error::{Capability, Error, Feature, Unsupported}; use crate::library::{FunctionConstantValue, FunctionConstantValues}; @@ -30,8 +32,11 @@ use crate::lower::select::LowerInputs; use crate::metal::DataType; use crate::pipeline::artifact::PrecisionNote; use crate::pipeline::compile::{compile_bitcode_linked, EntryRef, LinkedSource}; +use crate::pipeline::facts::RuntimeFact; +use crate::pipeline::sym::PushField; use crate::pipeline::testing::{ - compile, engine_dir, link_and_validate, llvm_assemble, meter, profile, AssembleError, + compile, compile_kept, engine_dir, link_and_validate, llvm_assemble, meter, profile, + AssembleError, }; /// The functions, `words`, `vwords` and `fwords` with a private array of `n` words. @@ -243,6 +248,57 @@ fn render_stages_past_the_floor_of_a_device_not_measured_run_noted_up_to_metal_s assert_eq!(kernel.map(|_| ()), needs(4352 * 4, 16 * 1024)); } +/// Under the identity domains a kernel whose private memory passes the floor keeps it in the +/// runtime's device memory, one slot an invocation (`memory::plan::ArenaLayout::device`): the +/// `words` kernel of 7176 words (28,704 bytes), 9216 (36 KiB) and 51,200 (200 KiB) compiles on the +/// 780M's, the Iris Xe's and an RTX 50's profiles with no note, pushes +/// `PushField::PrivateArenaAddress`, states `RuntimeFact::PrivateArena` of its arena's bytes, a +/// multiple of 16, holds no private bytes, and passes L3. Under the default domains, whose binder supplies no such memory, it is +/// refused as before, needing its bytes of the floor. +#[test] +fn a_kernel_past_the_floor_keeps_its_private_memory_in_the_runtimes_memory_under_identity() { + let identity = DevicePolicy { + pointer_domain: PointerDomain::Identity, + handle_domain: HandleDomain::Identity, + ..DevicePolicy::default() + }; + for stem in ["amd-780m-radv", "intel-irisxe-anv", "nvidia-rtx50-linux"] { + let p = profile(stem, identity).expect("profile"); + for n in [7176u32, 9216, 51_200] { + let Some(bitcode) = module(n) else { + return; + }; + let what = format!("{stem}: words {n}"); + let (a, plan, _) = + compile_kept(&bitcode, "words", &p).unwrap_or_else(|e| panic!("{what}: {e}")); + link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); + assert!(plan.families.access.local.private_device, "{what}"); + assert_eq!(plan.memory.private_bytes, 0, "{what}"); + assert!( + plan.facts + .contains(&RuntimeFact::PrivateArena { slot_bytes: 4 * n }), + "{what}: {:?}", + plan.facts + ); + assert!( + (plan.push.fields.iter()).any(|f| f.field == PushField::PrivateArenaAddress), + "{what}" + ); + assert!( + !a.precision.contains(&PrecisionNote::FunctionStorageAssumed), + "{what}: {:?}", + a.precision + ); + let default = notes(stem, n, "words").expect("assembled"); + assert_eq!( + default.map(|_| ()), + needs(4 * u64::from(n), 16 * 1024), + "{what}" + ); + } + } +} + /// An array reached only at constant indices counts nothing: a driver holds its parts in registers. /// Six times the floor's 16 KiB compiles with no note on the RTX 5080's profile and on RDNA 3's; /// the same array indexed at run time is refused. diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 98ac34c89..31f62927d 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -1672,6 +1672,10 @@ field metal2vulkan-runtime::Metrics.pipeline_cache_lock_waits pub pipeline_cache field metal2vulkan-runtime::Metrics.pipeline_cache_looks_skipped pub pipeline_cache_looks_skipped: u64 field metal2vulkan-runtime::Metrics.pipeline_creation_nanos pub pipeline_creation_nanos: u64 field metal2vulkan-runtime::Metrics.pipelines_created pub pipelines_created: u64 +field metal2vulkan-runtime::Metrics.private_arena_allocations pub private_arena_allocations: SiteAllocations +field metal2vulkan-runtime::Metrics.private_arena_blocks pub private_arena_blocks: u64 +field metal2vulkan-runtime::Metrics.private_arena_dispatches pub private_arena_dispatches: u64 +field metal2vulkan-runtime::Metrics.private_arena_pieces pub private_arena_pieces: u64 field metal2vulkan-runtime::Metrics.private_long_reuses pub private_long_reuses: u64 field metal2vulkan-runtime::Metrics.private_remade_after_frees pub private_remade_after_frees: u64 field metal2vulkan-runtime::Metrics.private_take_allocations pub private_take_allocations: SiteAllocations @@ -9223,6 +9227,7 @@ variant metal2vulkan-runtime::Gap::FloatDepthUpload FloatDepthUpload { pixel_for variant metal2vulkan-runtime::Gap::HeapTexture HeapTexture { pixel_format: PixelFormat } variant metal2vulkan-runtime::Gap::ImageblockLength ImageblockLength variant metal2vulkan-runtime::Gap::IndirectCommandBuffers IndirectCommandBuffers +variant metal2vulkan-runtime::Gap::IndirectPrivateArena IndirectPrivateArena variant metal2vulkan-runtime::Gap::KernelInput KernelInput { kind: KernelInputKind } variant metal2vulkan-runtime::Gap::LinearPlanePass LinearPlanePass { kind: LinearPlanePassKind } variant metal2vulkan-runtime::Gap::LodClamps LodClamps @@ -10954,6 +10959,7 @@ variant metal2vulkan::pipeline::PushField::LineBand LineBand variant metal2vulkan::pipeline::PushField::MergedDrawAddress MergedDrawAddress variant metal2vulkan::pipeline::PushField::PatchIndexBound PatchIndexBound variant metal2vulkan::pipeline::PushField::PatchIndexOffset PatchIndexOffset +variant metal2vulkan::pipeline::PushField::PrivateArenaAddress PrivateArenaAddress variant metal2vulkan::pipeline::PushField::RegionBox RegionBox variant metal2vulkan::pipeline::PushField::RegionProbe RegionProbe variant metal2vulkan::pipeline::PushField::RenderTargetArrayLength RenderTargetArrayLength @@ -11056,6 +11062,7 @@ variant metal2vulkan::pipeline::RuntimeFact::OutOfBoundsAlpha OutOfBoundsAlpha { variant metal2vulkan::pipeline::RuntimeFact::PartialObjectThreadgroups PartialObjectThreadgroups variant metal2vulkan::pipeline::RuntimeFact::PartialThreadgroups PartialThreadgroups variant metal2vulkan::pipeline::RuntimeFact::PredicationVote PredicationVote +variant metal2vulkan::pipeline::RuntimeFact::PrivateArena PrivateArena { slot_bytes: u32 } variant metal2vulkan::pipeline::RuntimeFact::PrivateList PrivateList variant metal2vulkan::pipeline::RuntimeFact::QuadPrimitiveIds QuadPrimitiveIds variant metal2vulkan::pipeline::RuntimeFact::RegionViewports RegionViewports diff --git a/docs/API.md b/docs/API.md index 4607205a1..ad527fed1 100644 --- a/docs/API.md +++ b/docs/API.md @@ -209,7 +209,17 @@ compile does. `DevicePolicy::default()` is `DevicePolicy::UNTRUSTED`: read-only signed-integer attachment joins `signed_color_attachments`. A vertex function that writes `[[render_target_array_index]]` compiles in the variant that writes `Layer`, which stores 0 for an index at or past the render pass's length the consumer pushes - (`PushField::RenderTargetArrayLength`, `renderTargetArrayLength` at least 1). Every precision note is + (`PushField::RenderTargetArrayLength`, `renderTargetArrayLength` at least 1). A kernel without a + call stack whose private bytes pass the 16 KiB floor every device holds keeps its private memory + in the consumer's device memory: every alloca it indexes at run time is in its private arena, + whose words for an invocation are the slot of `RuntimeFact::PrivateArena { slot_bytes }` (the + arena's bytes rounded up to 16) at the address the consumer pushes + (`PushField::PrivateArenaAddress`, a `u64`, a multiple of 16) plus `i * slot_bytes`, `i` the + invocation's index in its Vulkan dispatch, `((wz * ny + wy) * nx + wx) * n` plus its + `LocalInvocationIndex` (`n` the workgroup's invocations), counted in 32 bits. The consumer + supplies `count * slot_bytes` bytes for each dispatch of `count` invocations, and keeps a + dispatch's invocations under `2^32`. The memory needs no zeros: Metal's private memory is + undefined until the thread writes it. 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 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 diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index 91274dbce..b358b395f 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -34,13 +34,13 @@ Columns: | Devices below the runtime's floor | 8 | 8 | 0 | 0 | 0 | 0 | 0 | | The runtime's `Refusal` | 76 | 76 | 0 | 0 | 0 | 0 | 0 | | The runtime's `Limit` | 17 | 17 | 0 | 0 | 0 | 0 | 0 | -| The runtime's `Gap` | 30 | 30 | 0 | 0 | 0 | 0 | 0 | +| The runtime's `Gap` | 31 | 31 | 0 | 0 | 0 | 0 | 0 | ## Totals by basis | Kind | `metal-measured` | `metal-documented` | `metal-takes` | `device` | `ours` | `unknown` | `delegated` | `-` | |---|---|---|---|---|---|---|---|---| -| Translator and front-end refusals | 0 | 0 | 0 | 41 | 57 | 0 | 0 | 37 | +| Translator and front-end refusals | 0 | 0 | 0 | 42 | 57 | 0 | 0 | 36 | | Binder refusals at a device limit | 0 | 0 | 0 | 9 | 0 | 0 | 0 | 0 | | Translation caps | 0 | 0 | 0 | 0 | 14 | 0 | 0 | 0 | | Rate maps the compile layer does not compile | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 5 | @@ -48,7 +48,7 @@ Columns: | Devices below the runtime's floor | 0 | 0 | 0 | 8 | 0 | 0 | 0 | 0 | | The runtime's `Refusal` | 21 | 20 | 0 | 0 | 35 | 0 | 0 | 0 | | The runtime's `Limit` | 0 | 0 | 0 | 13 | 4 | 0 | 0 | 0 | -| The runtime's `Gap` | 0 | 0 | 0 | 2 | 28 | 0 | 0 | 0 | +| The runtime's `Gap` | 0 | 0 | 0 | 2 | 29 | 0 | 0 | 0 | ## 1. Translator and front-end refusals (`Unsupported`: a `Feature` and its `Needs`) @@ -173,7 +173,7 @@ Columns: | `CountingVisibility` | A `Counting` visibility result (`MTLVisibilityResultModeCounting`) on a device without `occlusionQueryPrecise` | - | `-` | 0 | `rare`: counting occlusion queries on a device without precise queries | | `ViewFormatReinterpretation` | A texture view whose format has other components, or components of other widths, than its texture's (`RGBA8Unorm` as `R32Uint`), on a device whose... | - | `-` | 0 | `app`: a view of another component layout on a portability subset (MoltenVK) | | `SeparateMultisampledDepthStencil` | A render pass whose depth and stencil attachments are separate multisampled textures that it loads or may store, on a device without maintenance8 | - | `-` | 0 | `rare`: separate multisampled depth and stencil textures | -| `PrivateMemory` | A stage whose private memory (its `thread` variables and arrays, and the constants it holds per thread) takes more Function storage a thread than... | - | `-` | via a helper: 1: `crates/metal2vulkan/src/lower/select.rs (function_storage)` | `rare`: very large per-thread arrays | +| `PrivateMemory` | A stage whose private memory (its `thread` variables and arrays, and the constants it holds per thread) takes more Function storage a thread than... | devices without a capability the site computes (`limit`) | `device` | 1: `crates/metal2vulkan/src/lower/access/local.rs (device_arena)` | `rare`: very large per-thread arrays | | `SparseTextures` | A sparse heap (`MTLHeapTypeSparse`), or a texture made from one, on a device without what a sparse resident image of it needs, which `missing` names | - | `-` | 0 | `rare`: sparse heaps on a device without sparse images | | `TimelineSemaphores` | Command buffers and events, which the runtime completes and signals through timeline semaphores (core in Vulkan 1.2), on a device whose... | - | `-` | 0 | `none`: a device below the runtime's floor | | `Reflection` | Reflection of an argument whose answer Metal's has not been measured for (`reflection`) | every device (not implemented) | `ours` | 8: `crates/metal2vulkan/src/reflection/derive.rs (gap_at)`, `crates/metal2vulkan/src/reflection/derive.rs (read_attributes)` (+6) | `rare`: reflection of argument kinds Metal's answer is unmeasured for | @@ -220,7 +220,7 @@ Columns: | `InstructionCount` | Instructions of the decoded module | every device (a deterministic cap) | `ours` | 8: `crates/metal2vulkan-air/src/bitcode/function.rs (call)`, `crates/metal2vulkan-air/src/bitcode/function.rs (constants)` (+4) | `rare`: very large modules | | `LayoutNesting` | Nesting depth of `air.struct_type_info` layouts and the argument-buffer members inside them | every device (a deterministic cap) | `ours` | 3: `crates/metal2vulkan-air/src/abi/structs.rs (finish)`, `crates/metal2vulkan-air/src/abi/structs.rs (open)` (+1) | `none`: argument-buffer layouts nested past the cap | | `ConstructNesting` | Nesting depth of structured constructs the structurizer emits (P8 recurses once per level) | every device (a deterministic cap) | `ours` | 2: `crates/metal2vulkan/src/structurize/emit.rs (check_tree)`, `crates/metal2vulkan/src/structurize/emit/predicate.rs (facts_of)` | `none`: control flow nested past the cap | -| `PrivateArenaBytes` | Bytes of a function's private arena, whose pointers are `u32` byte offsets | every device (a deterministic cap) | `ours` | 3: `crates/metal2vulkan/src/lower/access/local.rs (use_arena)`, `crates/metal2vulkan/src/memory/plan.rs (place_allocas, 2 sites)` | `none`: a private arena past 4 GiB | +| `PrivateArenaBytes` | Bytes of a function's private arena, whose pointers are `u32` byte offsets | every device (a deterministic cap) | `ours` | 4: `crates/metal2vulkan/src/lower/access/local.rs (device_arena)`, `crates/metal2vulkan/src/lower/access/local.rs (use_arena)` (+1) | `none`: a private arena past 4 GiB | | `CallStackBytes` | Bytes of a kernel's call stack | every device (a deterministic cap) | `ours` | 1: `crates/metal2vulkan-air/src/canon/recursion.rs (metal_stack)` | `rare`: deep visible-function call stacks | ## 4. Rate maps the compile layer does not compile (`UnpinnedCompile`) @@ -365,6 +365,7 @@ Columns: | `PartialSimdgroups` | A dispatch whose threadgroup is not whole SIMD groups of a kernel whose tier runs each SIMD group as one subgroup of `width` threads (a pinned... | every device (a public call's own check of its arguments) | `ours`: no emulated-SIMD-group module | 1: `crates/metal2vulkan-runtime/src/encoder.rs (decide)` | `-` | | `PartialThreadgroups` | `dispatchThreads` with a grid that is not a whole number of threadgroups on some axis, of a kernel that observes its threadgroup partition and... | every device (a public call's own check of its arguments) | `ours`: the translator's partial-threadgroups variant does not take the emulated SIMD-group tier, nor a vote word past the workgroup memory | 1: `crates/metal2vulkan-runtime/src/encoder.rs (decide)` | `-` | | `NoStageInRegion` | A dispatch of a kernel that reads the stage-in region (`[[grid_origin]]`, `[[grid_size]]`) on an encoder that never set one... | every device (a public call's own check of its arguments) | `ours`: no replay stream dispatches such a kernel without setting a region | 1: `crates/metal2vulkan-runtime/src/encoder.rs (dispatch)` | `-` | +| `IndirectPrivateArena` | `dispatchThreadgroupsWithIndirectBuffer:indirectBufferOffset:threadsPerThreadgroup:` of a kernel whose private memory lives in the runtime's... | every device (a public call's own check of its arguments) | `ours`: no replay stream dispatches such a kernel indirectly | 1: `crates/metal2vulkan-runtime/src/encoder.rs (dispatch)` | `-` | | `MemorylessTexture` | A texture of `Memoryless` storage, which only render passes use | every device (a public call's own check of its arguments) | `ours`: render passes are not built | 1: `crates/metal2vulkan-runtime/src/texture.rs (checked)` | `-` | | `TextureBuffer` | A texture buffer (`MTLTextureTypeTextureBuffer`) | every device (a public call's own check of its arguments) | `ours`: no texel-buffer array; no replay stream or live session has used one; harvested guest render functions declare one in an argument buffer, validation's texture_buffer_member | 2: `crates/metal2vulkan-runtime/src/texture.rs (shape, 2 sites)` | `-` | | `CubeArrayTexture` | A cube array texture (`MTLTextureTypeCubeArray`), and so a view of one | every device (a public call's own check of its arguments) | `ours`: no replay stream makes a cube array texture or view; built when one does | 2: `crates/metal2vulkan-runtime/src/texture.rs (checked)`, `crates/metal2vulkan-runtime/src/texture.rs (view)` | `-` | @@ -503,7 +504,7 @@ Each refusal's sites, with the function that builds it. - `feature::ConstantAlphaBlendFactor`: `crates/metal2vulkan/src/metal/state.rs (check_constant_alpha)` - `feature::SparseTexture`: `crates/metal2vulkan/src/bind/plan/slots.rs (check_sparse_textures, 2 sites)` - `feature::TextureSwizzle`: `crates/metal2vulkan/src/bind/heap.rs (member_texel_view)`; `crates/metal2vulkan/src/bind/plan/resources.rs (plain_texture)`; `crates/metal2vulkan/src/lower/sampler/select.rs (select_one)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select_read_as)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select_write)`; `crates/metal2vulkan/src/lower/texture/slice.rs (select)` -- `feature::PrivateMemory`: `crates/metal2vulkan/src/lower/select.rs (function_storage)` +- `feature::PrivateMemory`: `crates/metal2vulkan/src/lower/access/local.rs (device_arena)` - `feature::Reflection`: `crates/metal2vulkan/src/reflection/derive.rs (gap_at)`; `crates/metal2vulkan/src/reflection/derive.rs (read_attributes)`; `crates/metal2vulkan/src/reflection/derive.rs (specialized_reads)`; `crates/metal2vulkan/src/reflection/function.rs (attribute)`; `crates/metal2vulkan/src/reflection/function.rs (module_constants)`; `crates/metal2vulkan/src/reflection/function.rs (unmeasured)`; `crates/metal2vulkan/src/reflection/linked.rs (function)`; `crates/metal2vulkan/src/reflection/mod.rs (kernel_stage)` - `feature::IndirectRenderState`: `crates/metal2vulkan/src/lower/access/encode.rs (select_command)` - `feature::GlobalBuiltinInFragment`: `crates/metal2vulkan/src/lower/select.rs (route_air)` @@ -535,7 +536,7 @@ Each refusal's sites, with the function that builds it. - `limit::InstructionCount`: `crates/metal2vulkan-air/src/bitcode/function.rs (call)`; `crates/metal2vulkan-air/src/bitcode/function.rs (constants)`; `crates/metal2vulkan-air/src/bitcode/function.rs (count_record, 2 sites)`; `crates/metal2vulkan-air/src/bitcode/function.rs (decode)`; `crates/metal2vulkan-air/src/bitcode/function.rs (forward)`; `crates/metal2vulkan-air/src/bitcode/function.rs (push, 2 sites)` - `limit::LayoutNesting`: `crates/metal2vulkan-air/src/abi/structs.rs (finish)`; `crates/metal2vulkan-air/src/abi/structs.rs (open)`; `crates/metal2vulkan/src/bind/argument_buffer.rs (layout)` - `limit::ConstructNesting`: `crates/metal2vulkan/src/structurize/emit.rs (check_tree)`; `crates/metal2vulkan/src/structurize/emit/predicate.rs (facts_of)` -- `limit::PrivateArenaBytes`: `crates/metal2vulkan/src/lower/access/local.rs (use_arena)`; `crates/metal2vulkan/src/memory/plan.rs (place_allocas, 2 sites)` +- `limit::PrivateArenaBytes`: `crates/metal2vulkan/src/lower/access/local.rs (device_arena)`; `crates/metal2vulkan/src/lower/access/local.rs (use_arena)`; `crates/metal2vulkan/src/memory/plan.rs (place_allocas, 2 sites)` - `limit::CallStackBytes`: `crates/metal2vulkan-air/src/canon/recursion.rs (metal_stack)` - `ratemap::ScreenExtent`: `crates/metal2vulkan/src/bind/rate_map.rs (new)` - `ratemap::LayerCount`: `crates/metal2vulkan/src/bind/rate_map.rs (new)` @@ -650,6 +651,7 @@ Each refusal's sites, with the function that builds it. - `rt:Gap::PartialSimdgroups`: `crates/metal2vulkan-runtime/src/encoder.rs (decide)` - `rt:Gap::PartialThreadgroups`: `crates/metal2vulkan-runtime/src/encoder.rs (decide)` - `rt:Gap::NoStageInRegion`: `crates/metal2vulkan-runtime/src/encoder.rs (dispatch)` +- `rt:Gap::IndirectPrivateArena`: `crates/metal2vulkan-runtime/src/encoder.rs (dispatch)` - `rt:Gap::MemorylessTexture`: `crates/metal2vulkan-runtime/src/texture.rs (checked)` - `rt:Gap::TextureBuffer`: `crates/metal2vulkan-runtime/src/texture.rs (shape, 2 sites)` - `rt:Gap::CubeArrayTexture`: `crates/metal2vulkan-runtime/src/texture.rs (checked)`; `crates/metal2vulkan-runtime/src/texture.rs (view)`