diff --git a/crates/metal2vulkan-validation/fixtures/public/engine/README.md b/crates/metal2vulkan-validation/fixtures/public/engine/README.md index a1b7b58b7..0437c9b09 100644 --- a/crates/metal2vulkan-validation/fixtures/public/engine/README.md +++ b/crates/metal2vulkan-validation/fixtures/public/engine/README.md @@ -69,7 +69,7 @@ threadgroup's threads); an authored case that executes a loop declares it | `kernel_spin_on_an_unraised_word` | `spin_on_an_unraised_word` | the queue storm's busy work: one thread loads buffer 0's word with relaxed atomic loads until it reads nonzero or has made `cap` (buffer 2) of them, then stores how many it made to buffer 1; it calls nothing a translation drops, so Metal's compilation and the translation's spin the same loads | with buffer 0 zero, buffer 1 holds `cap` | | `kernel_vector_function_constant` | `kernel_vector_function_constant` | compiled replacement for the hand-written top-level fixture of that name (no `!air.function_constants`); Metal's `uint4` function constant: an `air.fc_initializer` global named at index 0 and an `air.static_init` constructor copying it into the program-scope constant | `out[0]` = sum of the four lanes (case `vector-function-constant-sum`: 10); `NeedsInput{FunctionConstant}` without a value | | `kernel_nested_loop_constant_weight_walk` | `nested_loop_constant_weight_walk` | compiled replacement for the hand-written top-level fixture of that name (misnumbered SSA, `llvm-as` rejects it); a `constant float4` pointer walked by a nested loop whose outer backedge advances it by one `gep %outer, 3` | `out[t] = t + Σ weights[k].x` over the first twelve `float4`s (case `sum-a-constant-weight-run-walked-by-a-nested-loop`: `t + 78`) | -| `descriptor_limit_uniform_views` | `descriptor_limit_uniform_views`, `descriptor_limit_atomic_load` | six buffer slots, five read only (two `device` arrays and a `device` array with `Whole` windows, a `constant` array with a `Whole` window, an 8-byte `device` struct), over `vk12-floor`'s four storage buffers per stage; Profile F's fallback views the struct and the `constant` array as uniform buffers. The second entry's five slots include a `device` atomic that is only loaded, which stays a storage view | `out[i] = a[i] + b[i] * p.scale + c[i] + (d[i] ^ p.bias)`; `out[i] = i < n ? a[i] + b[i] : d[i]` for the atomic's value `n` (CPU interpreter through the binder, the fallback's variant, and its refusals, `crates/metal2vulkan/tests/engine_binder.rs`) | +| `descriptor_limit_uniform_views` | `descriptor_limit_uniform_views`, `descriptor_limit_atomic_load` | six buffer slots, five read only (two `device` arrays and a `device` array with `Whole` windows, a `constant` array with a `Whole` window, an 8-byte `device` struct), over `vk12-floor`'s four storage buffers per stage; Profile F, without device addresses, refuses it (`DescriptorCount`). The second entry's five slots include a `device` atomic that is only loaded | `out[i] = a[i] + b[i] * p.scale + c[i] + (d[i] ^ p.bias)`; `out[i] = i < n ? a[i] + b[i] : d[i]` for the atomic's value `n` (CPU interpreter through the binder, and Profile F's refusal, `crates/metal2vulkan/src/tests/engine_binder.rs`) | | `a1_bool_from_float` | `a1_bool_from_float` | `air.convert` from a float to `i1` (`bool(x)`; L1d), scalar and vector, `float` and `half`, default fast math | Metal's reading is the question (case `float-to-bool-at-every-special-value`); `Unsupported{Lowering(Arith)}` in the engine | | `a1_bool_from_float_precise` | `a1_bool_from_float_precise` | the same program compiled `-fno-fast-math` | as `a1_bool_from_float` (case `float-to-bool-at-every-special-value-without-fast-math`) | | `a1_pow_special_values` | `a1_pow_special_values` | `air.pow`, `air.fast_pow`, `air.pow.f16` at every C99 Annex F special operand, `-fno-fast-math` | the C99 answer on each of 432 lanes, if Metal follows C99 (case `pow-at-every-c99-special-operand`) | diff --git a/crates/metal2vulkan-validation/fixtures/public/engine/descriptor_limit_uniform_views.metal b/crates/metal2vulkan-validation/fixtures/public/engine/descriptor_limit_uniform_views.metal index 6527a9074..19be5cf06 100644 --- a/crates/metal2vulkan-validation/fixtures/public/engine/descriptor_limit_uniform_views.metal +++ b/crates/metal2vulkan-validation/fixtures/public/engine/descriptor_limit_uniform_views.metal @@ -2,14 +2,12 @@ // storage-buffer limit (vk12-floor allows four). Five slots are read only: two // `device` arrays and a `device` array indexed by the thread (`Whole` windows), a `constant` array // indexed by the thread (`Whole`), and a `device` struct reference (`Bounded`, 8 bytes); one slot -// is written. On Profile F the per-stage fallback views read-only slots as uniform buffers until -// four storage buffers remain: the struct first (its window bounds its range), then the `constant` -// array. Bind every buffer with at least as many words as threads: -// out[i] = a[i] + b[i] * p.scale + c[i] + (d[i] ^ p.bias). Loop-free. +// is written. A profile with device addresses reaches the slots past the limit by their +// addresses; Profile F, which has none, refuses the kernel. Bind every buffer with at least as +// many words as threads: out[i] = a[i] + b[i] * p.scale + c[i] + (d[i] ^ p.bias). Loop-free. // // `descriptor_limit_atomic_load` has five storage slots too, one of them a `device` atomic that -// is only loaded (a 4-byte `Bounded` window, read only): an atomic needs a storage view, so the -// fallback views the highest-index `device` array instead. out[i] = i < n ? a[i] + b[i] : d[i], +// is only loaded (a 4-byte `Bounded` window, read only). out[i] = i < n ? a[i] + b[i] : d[i], // where n is the atomic's value. Loop-free. #include using namespace metal; diff --git a/crates/metal2vulkan-validation/src/candidate/engine.rs b/crates/metal2vulkan-validation/src/candidate/engine.rs index bdd7641b6..d499848a0 100644 --- a/crates/metal2vulkan-validation/src/candidate/engine.rs +++ b/crates/metal2vulkan-validation/src/candidate/engine.rs @@ -478,24 +478,12 @@ pub fn function_constants( Ok(constants) } -/// The view base alignment the executor's bind states state (`BindState::view_base_alignment`): -/// 256, the largest `minUniformBufferOffsetAlignment` Vulkan allows, a multiple of every device's -/// view base alignment, which every bind offset the -/// executor binds, 0, is a multiple of in turn. Each of its states tells it apart at every buffer -/// slot ([`views_told_apart`]), so a uniform view's range starts at its bind offset in its plan -/// (`SpecKey::RangeAtBindOffset`) on every device, as in the runtime's plan of the same binds: the -/// runtime states its device's own alignment at the slots its pipeline reads through a uniform -/// view, and the plans of the two are the same. -pub const VIEW_BASE_ALIGNMENT: u32 = 256; - -/// `state` telling [`VIEW_BASE_ALIGNMENT`] apart at every buffer slot of each of its stages. Each -/// stage table classes its buffers' lengths under `ranges` (`StageTable::buffer_ranges`), the -/// device's range limits (`BufferRanges::of`), as the runtime's tables class them, so a buffer's -/// shape states the length class the runtime's shape of the same bind states. -pub fn views_told_apart(mut state: BindState, ranges: BufferRanges) -> BindState { - state.view_base_alignment = VIEW_BASE_ALIGNMENT; +/// `state` with each stage table classing its buffers' lengths under `ranges` +/// (`StageTable::buffer_ranges`), the device's range limit (`BufferRanges::of`), as the runtime's +/// tables class them, so a buffer's shape states the length class the runtime's shape of the same +/// bind states. +pub fn lengths_classed(mut state: BindState, ranges: BufferRanges) -> BindState { for table in state.stages.values_mut() { - table.at_bind_views = u64::MAX; table.buffer_ranges = ranges; } state @@ -510,8 +498,8 @@ pub fn views_told_apart(mut state: BindState, ranges: BufferRanges) -> BindState /// with its resource id (its token follows the buffers', [`argument_buffers::texture_tokens`]), /// each made resident for reading and writing, as the Metal oracle's `useResource` does, and each /// argument-buffer sampler as an argument sampler with its id -/// ([`argument_buffers::argument_samplers`]); telling the executor's view base alignment apart and -/// classing lengths under the device's range limits `ranges` ([`views_told_apart`]). +/// ([`argument_buffers::argument_samplers`]); classing lengths under the device's range limit +/// `ranges` ([`lengths_classed`]). pub fn bind_state( case: &ComputeCase, addresses: &BTreeMap, @@ -562,7 +550,7 @@ pub fn bind_state( } state.argument_samplers = argument_buffers::argument_samplers(case.argument_buffer_samplers.iter())?; - Ok(views_told_apart(state, ranges)) + Ok(lengths_classed(state, ranges)) } /// The consumer token of each argument-buffer texture of `case`, by its key diff --git a/crates/metal2vulkan-validation/src/candidate/engine/graphics.rs b/crates/metal2vulkan-validation/src/candidate/engine/graphics.rs index 447003cbb..c106a34bf 100644 --- a/crates/metal2vulkan-validation/src/candidate/engine/graphics.rs +++ b/crates/metal2vulkan-validation/src/candidate/engine/graphics.rs @@ -34,7 +34,7 @@ use super::argument_buffers::{self, FieldKey}; use super::{ - function_constants, require_case_families, resources, select_range, views_told_apart, + function_constants, lengths_classed, require_case_families, resources, select_range, BufferAddress, }; use crate::case::out_of_bounds::OutOfBoundsTarget; @@ -1027,8 +1027,8 @@ pub fn synthetic_address(stage: ShaderStage, index: u32) -> BufferAddress { /// and a patch draw's factor buffer, its whole length at the shared offset and instance stride, /// with Metal's default scale (`executor_contract::tessellation`); and the draw's depth/stencil /// descriptor, the one the Metal oracle sets (`RenderCase::depth_stencil_state`), which a -/// pipeline's shader-side stencil reads as push data; telling the executor's view base alignment -/// apart and classing lengths under the device's range limits `ranges` ([`views_told_apart`]). +/// pipeline's shader-side stencil reads as push data; classing lengths under the device's range +/// limit `ranges` ([`lengths_classed`]). pub fn bind_state( case: &RenderCase, addresses: &BTreeMap<(ShaderStage, u32), BufferAddress>, @@ -1094,7 +1094,7 @@ pub fn bind_state( } state.argument_samplers = argument_buffers::argument_samplers(case.argument_buffer_samplers())?; state.depth_stencil = case.depth_stencil_state.descriptor; - Ok(views_told_apart(state, ranges)) + Ok(lengths_classed(state, ranges)) } /// The bind table of `function`'s own resources: its buffers, each bound as `bound` binds a buffer diff --git a/crates/metal2vulkan-validation/src/candidate/engine/mesh.rs b/crates/metal2vulkan-validation/src/candidate/engine/mesh.rs index ef53f9dac..dae96d2fc 100644 --- a/crates/metal2vulkan-validation/src/candidate/engine/mesh.rs +++ b/crates/metal2vulkan-validation/src/candidate/engine/mesh.rs @@ -17,9 +17,7 @@ //! ([`mesh_shape`]). use super::graphics::{self, ColorTarget, RenderFunction, RenderOutput, StageResources}; -use super::{ - function_constants, require_case_families, resources, views_told_apart, BufferAddress, -}; +use super::{function_constants, lengths_classed, require_case_families, resources, BufferAddress}; use crate::acceptance::{MeshFunction, PipelineRequest, RequestFunction}; use crate::case::{AuthoredCase, MeshGrid, OutputSelection, Stage}; use crate::check::admission::{ExecutorError, NotSupported}; @@ -243,8 +241,8 @@ impl MeshTemplate { /// The `BindShape` the runtime binds `mesh`'s draw with on a device that has device addresses /// exactly when `addressed` and the range limits `ranges`: its own stage's buffers at their /// synthetic guest addresses (and, when `addressed`, a host address), textures and samplers -/// ([`graphics::stage_table`]); a partner binds none; telling the executor's view base alignment -/// apart and classing lengths under `ranges` ([`views_told_apart`]), so its plan is the runtime's +/// ([`graphics::stage_table`]); a partner binds none; classing lengths under `ranges` +/// ([`lengths_classed`]), so its plan is the runtime's /// of the same binds. What the compile worker compiles the draw for /// (`variants::compile_mesh_for_shape`). /// A case whose own function takes an argument buffer is not built here (`NotImplemented`). @@ -280,7 +278,7 @@ pub fn mesh_shape( let table = graphics::stage_table(function, bound).map_err(ExecutorError::Failed)?; state.stages.insert(stage, table); } - Ok(views_told_apart(state, ranges).shape()) + Ok(lengths_classed(state, ranges).shape()) } /// The compile request for `mesh`'s pipeline for the bind shape `shape`, and its libraries in diff --git a/crates/metal2vulkan-validation/src/executor_contract/out_of_bounds.rs b/crates/metal2vulkan-validation/src/executor_contract/out_of_bounds.rs index b73d6d7ba..10056aa32 100644 --- a/crates/metal2vulkan-validation/src/executor_contract/out_of_bounds.rs +++ b/crates/metal2vulkan-validation/src/executor_contract/out_of_bounds.rs @@ -6,8 +6,8 @@ //! rows: //! //! - **The form and mechanism** of each target are what its compiled module does with it, never -//! only what the case says ([`containment`]): a buffer is a storage or uniform buffer as its -//! descriptor view is, or a device address; a buffer slot the product reaches through a descriptor view is +//! only what the case says ([`containment`]): a buffer is a storage buffer through its +//! descriptor, or a device address; a buffer slot the product reaches through a descriptor view is //! checked in the shader or left to the device's buffer robustness (the two encodings); a slot //! reached by its device address and the threadgroup arena are checked in the shader in every //! leg; a texel buffer and an image follow the product's texel containment @@ -55,7 +55,7 @@ use metal2vulkan::device::{DevicePolicy, DeviceProfile, HandleDomain, PointerDom use metal2vulkan::library::CompiledFunction; use metal2vulkan::pipeline::VertexInputState; use metal2vulkan::pipeline::{AttributeFetch, StrategyCensus}; -use metal2vulkan::pipeline::{BufferForm, DescriptorView, SlotInterface}; +use metal2vulkan::pipeline::{BufferForm, SlotInterface}; use metal2vulkan::pipeline::{SlotClass, SlotRef, Stage as SymStage}; use serde::{Deserialize, Serialize}; use std::collections::{BTreeMap, BTreeSet}; @@ -64,7 +64,7 @@ use std::collections::{BTreeMap, BTreeSet}; #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum Medium { - /// A storage or uniform buffer descriptor view (`BufferForm::Descriptor`). + /// A storage buffer descriptor view (`BufferForm::Descriptor`). DescriptorView, /// The buffer's device address (`BufferForm::Psb`). DeviceAddress, @@ -475,19 +475,18 @@ pub fn containment( Check::Shader, written, ), - BufferForm::Descriptor(view) => { - let (form, check) = match view { - DescriptorView::Storage if atomic => { - (ContainmentForm::BufferAtomic, robust) - } - DescriptorView::Storage => (ContainmentForm::StorageBuffer, robust), - DescriptorView::UniformWords | DescriptorView::UniformVec4 => { - (ContainmentForm::UniformBuffer, robust) - } - _ => return unknown(), - }; - made(form, Medium::DescriptorView, check, written) - } + BufferForm::Descriptor if atomic => made( + ContainmentForm::BufferAtomic, + Medium::DescriptorView, + robust, + written, + ), + BufferForm::Descriptor => made( + ContainmentForm::StorageBuffer, + Medium::DescriptorView, + robust, + written, + ), _ => unknown(), } } @@ -586,11 +585,9 @@ pub fn containment( BufferForm::Psb => { made(target.form, Medium::DeviceAddress, Check::Shader, false) } - BufferForm::Descriptor( - DescriptorView::Storage - | DescriptorView::UniformWords - | DescriptorView::UniformVec4, - ) => made(target.form, Medium::DescriptorView, robust, false), + BufferForm::Descriptor => { + made(target.form, Medium::DescriptorView, robust, false) + } _ => unknown(), }, _ => Err(format!( diff --git a/crates/metal2vulkan/src/bind/dispatch/tests.rs b/crates/metal2vulkan/src/bind/dispatch/tests.rs index 50965f074..4f5463b33 100644 --- a/crates/metal2vulkan/src/bind/dispatch/tests.rs +++ b/crates/metal2vulkan/src/bind/dispatch/tests.rs @@ -6,7 +6,7 @@ use super::*; use crate::bind::plan::{BoundKind, PlannedBuffer}; use crate::bind::state::{BoundBuffer, ResourceClass, StageTable, UsedResource}; use crate::pipeline::artifact::SpecConstant; -use crate::pipeline::interface::{AccessSet, BufferForm, DescriptorView, PlacedField, Window}; +use crate::pipeline::interface::{AccessSet, BufferForm, PlacedField, Window}; use crate::pipeline::sym::{SlotClass, SlotRef, Stage}; /// `BindingPlan::instantiate_dispatch` of a compute plan of template `t` with no variant. @@ -76,7 +76,7 @@ fn template() -> ComputeTemplate { buffers: vec![PlannedBuffer { slot: kslot(0), window: Window::Bounded { start: 0, len: 64 }, - form: BufferForm::Descriptor(DescriptorView::Storage), + form: BufferForm::Descriptor, access: AccessSet::READ_WRITE, binding: Some((0, 0)), alignment: 64, @@ -85,7 +85,6 @@ fn template() -> ComputeTemplate { device_address: false, length_class: crate::bind::state::length_class(4096), }, - disjoint: false, }], spec: vec![ spec(0, SpecKey::LocalSize(Axis::X)), diff --git a/crates/metal2vulkan/src/bind/graphics.rs b/crates/metal2vulkan/src/bind/graphics.rs index db01d25f7..12f590cef 100644 --- a/crates/metal2vulkan/src/bind/graphics.rs +++ b/crates/metal2vulkan/src/bind/graphics.rs @@ -220,10 +220,9 @@ use crate::bind::plan::compute::{internal, not_implemented, spec_key, tile_memor use crate::bind::plan::resources::{separate_samplers, ResourcePlanner}; use crate::bind::plan::slots::{ address_map_variant, anisotropic_variant, bindings, bound_value, buffer_use, check_slots, - check_sparse_textures, cross_variant, cubic_variant, heap_raw, large_view_candidates, - mark_disjoint, plan_buffer, psb_variant, range_variant, record_noted, srgb_variant, - storage_view_variant, texel_buffer_parts_variant, used_uses, ycbcr_in_place_variant, - ycbcr_planes_sampled_variant, + check_sparse_textures, cross_variant, cubic_variant, heap_raw, plan_buffer, psb_variant, + range_variant, record_noted, srgb_variant, texel_buffer_parts_variant, used_uses, + ycbcr_in_place_variant, ycbcr_planes_sampled_variant, }; use crate::bind::plan::{ AccessClass, BindingPlan, BoundKind, ByteRange, DescriptorWrite, FactorTemplate, FieldLocation, @@ -903,7 +902,6 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result Result Result bool { - let a = alignment.max(4); - bind_offset.is_multiple_of(a) - && match window { - Window::Whole => true, - Window::Bounded { start, .. } => u64::try_from(start).is_ok_and(|s| s < a), - } -} - /// The descriptor range and the `SlotBindOffset` residual of a descriptor-form slot, in checked /// `i128` arithmetic, for an allocation of `length` bytes (padded to 16) bound at `bind_offset`, /// with the slot's proven `window`, the descriptor base `alignment` `A` (at least 4 is used; a -/// Metal buffer slot's plan gives `max(min*BufferOffsetAlignment, 16)`, so a descriptor byte is +/// Metal buffer slot's plan gives `max(minStorageBufferOffsetAlignment, 16)`, so a descriptor byte is /// congruent to its Metal address modulo 16), and the view's maximum range `max_range`. /// /// - `Bounded{start, len}`: from `align_down(max(0, bind_offset + start), A)` to @@ -511,43 +494,30 @@ pub(crate) fn shared_range( } /// The descriptor range and the `SlotBindOffset` residual of planned buffer slot `pb` bound at -/// `bind_offset` of an allocation of `length` bytes, where `views_at_residual` says the consumer -/// reads every uniform view at its residual (`BindState::uniform_views_at_residual`). Its function -/// reads byte `residual + m` of the range for the Metal offset `m`, the byte it read of the range -/// from the bind offset, so a slot read at its residual binds a range its bind offsets share: +/// `bind_offset` of an allocation of `length` bytes. Its function reads byte `residual + m` of the +/// range for the Metal offset `m`, the byte it read of the range from the bind offset, so a slot +/// binds a range its bind offsets share: /// -/// - a storage view of a `Whole` window takes its range from the start of the bound buffer's -/// space (offset 0) to the padded end, its residual the bind offset, so every bind offset of one -/// buffer binds one descriptor and a draw or dispatch that moves only the offset keeps its set 0 -/// (a dynamic one's offset moves with the space alone); the bytes before the bind offset, which -/// the window does not state, are reachable as Metal's own memory is. Where that range would -/// exceed the view's `max_range` or reach past `2^32` (a `u32` residual and offset), or the bind -/// offset lies at or past the padded end, it takes [`descriptor_range`]'s range; -/// - a storage view of a `Bounded` window, which a function reads at its residual but at bind -/// offset 0 (`SpecKey::RangeAtBindOffset`, where its profile declares the key, set only where -/// [`starts_at_bind`] holds there, which leaves that range's residual 0), and a uniform view of -/// one where `views_at_residual` (no function reads it at its bind offset alone), take -/// [`shared_range`]'s, where it holds the window; +/// - a `Whole` window takes its range from the start of the bound buffer's space (offset 0) to the +/// padded end, its residual the bind offset, so every bind offset of one buffer binds one +/// descriptor and a draw or dispatch that moves only the offset keeps its set 0 (a dynamic one's +/// offset moves with the space alone); the bytes before the bind offset, which the window does +/// not state, are reachable as Metal's own memory is. Where that range would exceed the view's +/// `max_range` or reach past `2^32` (a `u32` residual and offset), or the bind offset lies at or +/// past the padded end, it takes [`descriptor_range`]'s range; +/// - a `Bounded` window takes [`shared_range`]'s, where it holds the window; /// - every other slot takes [`descriptor_range`]'s, which starts at the bind offset aligned down -/// to the descriptor base alignment: a uniform view's key may read it at its bind offset alone, -/// where its residual is 0. +/// to the descriptor base alignment. pub(crate) fn planned_range( pb: &PlannedBuffer, bind_offset: u64, length: u64, - views_at_residual: bool, ) -> Result<(BufferRange, u32), RangeError> { let end = padded(length); - let storage = pb.form == BufferForm::Descriptor(DescriptorView::Storage); - let from_start = pb.window == Window::Whole - && storage - && bind_offset < end - && end <= pb.max_range - && end <= 1 << 32; + let from_start = + pb.window == Window::Whole && bind_offset < end && end <= pb.max_range && end <= 1 << 32; if !from_start { - let shared = (storage || (views_at_residual && pb.form.uniform_view())) - .then(|| shared_range(bind_offset, length, pb.window, pb.alignment, pb.max_range)) - .flatten(); + let shared = shared_range(bind_offset, length, pb.window, pb.alignment, pb.max_range); return match shared { Some(shared) => Ok(shared), None => descriptor_range(bind_offset, length, pb.window, pb.alignment, pb.max_range), @@ -573,7 +543,7 @@ pub(crate) fn bound_buffer( // table's buffer ranges class it in the shape. let ranges = table.map(|t| t.buffer_ranges).unwrap_or_default(); let kind = BoundKind::of_bound(b, ranges); - debug_assert_eq!(kind, BoundKind::of(b.map(|b| b.shape(0, ranges)).as_ref())); + debug_assert_eq!(kind, BoundKind::of(b.map(|b| b.shape(ranges)).as_ref())); if kind != expected { return Err(internal(format!( "the bind state's shape differs from the plan's at {slot:?}" @@ -621,72 +591,16 @@ impl Residuals { } } -/// The Metal addresses `[lo, hi)` a buffer bound at `gpu_address + offset` (an allocation of -/// `length` bytes) can reach through `window`: a `Bounded` window from the bind offset, a `Whole` -/// one from the bind offset to the end, clamped to the padded allocation, since an access outside -/// it is not Metal-defined (containment keeps it in the bound range). -fn metal_extent(window: Window, gpu_address: u64, offset: u64, length: u64) -> (i128, i128) { - let base = i128::from(gpu_address); - let end = base + i128::from(padded(length)); - let bind = base + i128::from(offset); - let (lo, hi) = match window { - Window::Bounded { start, len } => { - let lo = bind + i128::from(start); - (lo, lo + i128::from(len)) - } - _ => (bind, end), - }; - (lo.max(base), hi.min(end)) -} - -/// Refuse a binding where a slot read through a `device` uniform view (`PlannedBuffer::disjoint`) -/// can reach Metal addresses a written slot of the pipeline can reach: a uniform view need not -/// observe the dispatch's or draw's own writes. Inline bytes are copies and alias nothing. -fn check_uniform_aliasing(buffers: &[PlannedBuffer], state: &BindState) -> Result<(), BindError> { - let extent = |pb: &PlannedBuffer| -> Result, BindError> { - Ok(match bound_buffer(state, pb.slot, pb.bound)? { - Some(&BoundBuffer::Buffer { - length, - offset, - gpu_address, - .. - }) => Some(metal_extent(pb.window, gpu_address, offset, length)), - _ => None, - }) - }; - for pb in buffers.iter().filter(|b| b.disjoint) { - let Some((lo, hi)) = extent(pb)? else { - continue; - }; - for w in buffers - .iter() - .filter(|b| b.access.write && b.slot != pb.slot) - { - if let Some((wlo, whi)) = extent(w)? { - if lo < whi && wlo < hi { - return Err(BindError::UniformViewAliased { - slot: pb.slot, - written: w.slot, - }); - } - } - } - } - Ok(()) -} - /// Instantiate `buffers` for `state`: each descriptor-form slot's range, pushed onto /// `descriptor_ranges`, and residual (checked `i128`, `DescriptorRangeExceeded` above the view's /// limit, an empty allocation `Unsupported{BufferRange}`), each bound device-address slot's root -/// entry, and each bound buffer's extent, pushed onto `extents`. A `device` slot's uniform view -/// must not alias a written slot (`UniformViewAliased`). +/// entry, and each bound buffer's extent, pushed onto `extents`. pub(crate) fn bind_buffers( buffers: &[PlannedBuffer], state: &BindState, descriptor_ranges: &mut Vec, extents: &mut Vec, ) -> Result { - check_uniform_aliasing(buffers, state)?; let mut out = BoundBuffers { residuals: Residuals::default(), statics: Vec::new(), @@ -706,10 +620,9 @@ pub(crate) fn bind_buffers( None => continue, }; match (pb.form, pb.binding) { - (BufferForm::Descriptor(_), Some((set, binding))) => { - let views = state.uniform_views_at_residual; + (BufferForm::Descriptor, Some((set, binding))) => { let (range, residual) = - planned_range(pb, bind_offset, length, views).map_err(|e| match e { + planned_range(pb, bind_offset, length).map_err(|e| match e { RangeError::TooLarge { needed } => BindError::DescriptorRangeExceeded { slot: pb.slot, needed, diff --git a/crates/metal2vulkan/src/bind/instantiate/tests.rs b/crates/metal2vulkan/src/bind/instantiate/tests.rs index c2183c5d8..30211fbbc 100644 --- a/crates/metal2vulkan/src/bind/instantiate/tests.rs +++ b/crates/metal2vulkan/src/bind/instantiate/tests.rs @@ -187,9 +187,9 @@ fn ranges_above_the_descriptor_limit_are_refused() { ); } -/// A planned buffer slot of `window`, read through `view`, under a view base alignment of -/// `alignment` and a range limit of `max_range`. -fn planned(window: Window, view: DescriptorView, alignment: u64, max_range: u64) -> PlannedBuffer { +/// A planned buffer slot of `window`, under a view base alignment of `alignment` and a range limit +/// of `max_range`. +fn planned(window: Window, alignment: u64, max_range: u64) -> PlannedBuffer { use crate::pipeline::sym::{SlotClass, Stage}; PlannedBuffer { slot: SlotRef { @@ -198,7 +198,7 @@ fn planned(window: Window, view: DescriptorView, alignment: u64, max_range: u64) index: 0, }, window, - form: BufferForm::Descriptor(view), + form: BufferForm::Descriptor, access: crate::pipeline::interface::AccessSet::READ_WRITE, binding: Some((0, 0)), alignment, @@ -207,7 +207,6 @@ fn planned(window: Window, view: DescriptorView, alignment: u64, max_range: u64) device_address: false, length_class: crate::bind::state::length_class(1 << 12), }, - disjoint: false, } } @@ -219,11 +218,11 @@ fn planned(window: Window, view: DescriptorView, alignment: u64, max_range: u64) fn a_storage_view_of_a_whole_buffer_binds_its_space_from_its_start() { const LENGTH: u64 = 4096; for alignment in [16, 64, 256] { - let pb = planned(Window::Whole, DescriptorView::Storage, alignment, MAX); + let pb = planned(Window::Whole, alignment, MAX); for bind_offset in (0..LENGTH).step_by(4).chain([1, 15, LENGTH - 1]) { let what = format!("{alignment} {bind_offset}"); - let (range, residual) = planned_range(&pb, bind_offset, LENGTH, false) - .unwrap_or_else(|e| panic!("{what}: {e:?}")); + let (range, residual) = + planned_range(&pb, bind_offset, LENGTH).unwrap_or_else(|e| panic!("{what}: {e:?}")); let whole = BufferRange { offset: 0, range: LENGTH, @@ -244,9 +243,9 @@ fn a_storage_view_of_a_whole_buffer_binds_its_space_from_its_start() { } } // A buffer of 2^32 bytes, bound at its last word: the residual still fits. - let pb = planned(Window::Whole, DescriptorView::Storage, 16, MAX); + let pb = planned(Window::Whole, 16, MAX); let last = (1 << 32) - 4; - let (range, residual) = planned_range(&pb, last, 1 << 32, false).unwrap(); + let (range, residual) = planned_range(&pb, last, 1 << 32).unwrap(); assert_eq!( (range.offset, range.range, residual), (0, 1 << 32, u32::MAX - 3) @@ -254,37 +253,36 @@ fn a_storage_view_of_a_whole_buffer_binds_its_space_from_its_start() { } /// Every other slot takes `descriptor_range`'s range: a storage view's range from 0 past the -/// view's limit or past `2^32`, a bind offset at or past the padded end, a uniform view where the -/// consumer may read it at its bind offset alone (`views_at_residual` false), a bounded window no +/// view's limit or past `2^32`, a bind offset at or past the padded end, a bounded window no /// shared range holds. A limit the range from the bind offset meets binds; one it does not is /// refused as before. #[test] fn other_slots_bind_the_range_from_their_bind_offset() { let same = |pb: &PlannedBuffer, bind_offset: u64, length: u64| { assert_eq!( - planned_range(pb, bind_offset, length, false), + planned_range(pb, bind_offset, length), descriptor_range(bind_offset, length, pb.window, pb.alignment, pb.max_range), "{:?} {:?} {bind_offset} {length}", pb.window, pb.form ); }; - let storage = |max_range| planned(Window::Whole, DescriptorView::Storage, 64, max_range); + let storage = |max_range| planned(Window::Whole, 64, max_range); // Past the view's limit: the tail from the bind offset fits; the whole buffer from 0 is // refused as before, at the range from the bind offset. let limited = storage(1 << 16); let length = 1 << 20; same(&limited, length - 4096, length); - assert!(planned_range(&limited, length - 4096, length, false).is_ok()); + assert!(planned_range(&limited, length - 4096, length).is_ok()); same(&limited, 64, length); assert_eq!( - planned_range(&limited, 64, length, false), + planned_range(&limited, 64, length), Err(RangeError::TooLarge { needed: length - 64 }) ); // At the limit exactly, from 0. - let (range, _) = planned_range(&storage(length), 64, length, false).unwrap(); + let (range, _) = planned_range(&storage(length), 64, length).unwrap(); assert_eq!(range.offset, 0); // Past 2^32 bytes: a residual and an offset of 32 bits could not state the bind offset. for length in [(1 << 32) + 16, 1 << 33] { @@ -298,20 +296,7 @@ fn other_slots_bind_the_range_from_their_bind_offset() { same(&storage(MAX), bind_offset, 4096); same(&storage(MAX), bind_offset, 4090); let bounded = Window::Bounded { start: 0, len: 16 }; - same( - &planned(bounded, DescriptorView::Storage, 64, MAX), - bind_offset, - 4096, - ); - } - // A uniform view a key may read at its bind offset alone (`RangeAtBindOffset`), of a whole - // window or a bounded one. - for bind_offset in (0..4096).step_by(4) { - for view in [DescriptorView::UniformWords, DescriptorView::UniformVec4] { - same(&planned(Window::Whole, view, 256, MAX), bind_offset, 4096); - let bounded = Window::Bounded { start: 0, len: 64 }; - same(&planned(bounded, view, 256, 1 << 16), bind_offset, 4096); - } + same(&planned(bounded, 64, MAX), bind_offset, 4096); } } @@ -410,16 +395,15 @@ fn shared_ranges_hold_every_window_byte_at_the_residual() { } } -/// A slot read at its residual binds one range at every bind offset of a buffer that fits the -/// view's limit, from 0, its residual the bind offset: a storage view of a bounded window always, -/// a uniform view where the consumer reads every view at its residual. Past the limit, the bind -/// offsets of one block of half the limit share one; the next block binds the next. +/// A slot of a bounded window binds one range at every bind offset of a buffer that fits the +/// view's limit, from 0, its residual the bind offset. Past the limit, the bind offsets of one +/// block of half the limit share one; the next block binds the next. #[test] fn bounded_slots_read_at_their_residual_share_one_range_along_a_buffer() { const CHUNK: u64 = 64 * 1024; let bounded = Window::Bounded { start: 0, len: 16 }; - let uniform = planned(bounded, DescriptorView::UniformVec4, 64, CHUNK); - let storage = planned(bounded, DescriptorView::Storage, 64, 1 << 27); + let limited = planned(bounded, 64, CHUNK); + let storage = planned(bounded, 64, 1 << 27); let whole = BufferRange { offset: 0, range: CHUNK, @@ -427,25 +411,22 @@ fn bounded_slots_read_at_their_residual_share_one_range_along_a_buffer() { for bind_offset in (0..CHUNK).step_by(256) { let shared = (whole, bind_offset as u32); assert_eq!( - planned_range(&uniform, bind_offset, CHUNK, true), + planned_range(&limited, bind_offset, CHUNK), Ok(shared), - "uniform {bind_offset}" + "limited {bind_offset}" ); assert_eq!( - planned_range(&storage, bind_offset, CHUNK, false), + planned_range(&storage, bind_offset, CHUNK), Ok(shared), "storage {bind_offset}" ); - // A uniform view a key may read at its bind offset alone: the range starts there. - let (range, residual) = planned_range(&uniform, bind_offset, CHUNK, false).unwrap(); - assert_eq!((range.offset, residual), (bind_offset, 0), "{bind_offset}"); } - // A buffer of 1 MiB, past the uniform view's limit: blocks of 32 KiB. + // A buffer of 1 MiB, past the view's limit: blocks of 32 KiB. let length = 1 << 20; let block = CHUNK / 2; for bind_offset in (0..length).step_by(256) { let base = bind_offset - bind_offset % block; - let (range, residual) = planned_range(&uniform, bind_offset, length, true).unwrap(); + let (range, residual) = planned_range(&limited, bind_offset, length).unwrap(); assert_eq!( (range.offset, range.range, u64::from(residual)), (base, CHUNK.min(length - base), bind_offset - base), @@ -475,9 +456,9 @@ fn bounded_slots_read_at_their_residual_share_one_range_along_a_buffer() { None, "{start}" ); - let pb = planned(longer, DescriptorView::UniformVec4, 64, CHUNK); + let pb = planned(longer, 64, CHUNK); assert_eq!( - planned_range(&pb, start, length, true), + planned_range(&pb, start, length), descriptor_range(start, length, longer, 64, CHUNK), "{start}" ); diff --git a/crates/metal2vulkan/src/bind/plan.rs b/crates/metal2vulkan/src/bind/plan.rs index 58c47a2c9..27db53208 100644 --- a/crates/metal2vulkan/src/bind/plan.rs +++ b/crates/metal2vulkan/src/bind/plan.rs @@ -28,10 +28,8 @@ use crate::vk; #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct BindingPlan { /// The variant the shape requires: the storage-image choices, `BufferRangeLimit` device-address - /// slots, vertex buffers fixed-function input cannot fetch as bound, a vertex function's - /// dropped `Layer` output in a pass of one layer, and the read-only slots Profile F's per-stage - /// storage-buffer fallback must keep as storage views where the shape binds more than a uniform - /// view may reach. Empty on the common path; otherwise the consumer compiles the pipeline with + /// slots, vertex buffers fixed-function input cannot fetch as bound, and a vertex function's + /// dropped `Layer` output in a pass of one layer. Empty on the common path; otherwise the consumer compiles the pipeline with /// this variant (`Device::compile_render_variant` for a render pipeline) and plans that /// pipeline, whose plan for the same shape states the same key. The descriptors are those of /// the pipeline planned; a draw of a plan whose variant pulls a vertex buffer the pipeline @@ -457,17 +455,13 @@ pub(crate) struct PlannedBuffer { pub access: AccessSet, /// `(set, binding)` of a descriptor-form slot. pub binding: Option<(u32, u32)>, - /// The descriptor base alignment: the view's `min*BufferOffsetAlignment`, at least 16 + /// The descriptor base alignment: `minStorageBufferOffsetAlignment`, at least 16 /// (`views::base_alignment`). pub alignment: u64, - /// The view's `max*BufferRange`. + /// `maxStorageBufferRange`. pub max_range: u64, /// What the shape binds at the slot. pub bound: BoundKind, - /// A `device` slot read through a uniform view: no written slot may be bound overlapping - /// its window (`RuntimeFact::UniformViewAliasing`). - #[cfg_attr(feature = "serde", serde(default))] - pub disjoint: bool, } /// What a shape binds at a buffer slot. @@ -950,7 +944,6 @@ pub enum UseTarget { #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub enum AccessClass { Storage, - Uniform, Sampled, StorageImage, VertexInput, diff --git a/crates/metal2vulkan/src/bind/plan/compute.rs b/crates/metal2vulkan/src/bind/plan/compute.rs index 809ae8fc7..267b6aabc 100644 --- a/crates/metal2vulkan/src/bind/plan/compute.rs +++ b/crates/metal2vulkan/src/bind/plan/compute.rs @@ -62,10 +62,9 @@ use super::resources::{separate_samplers, ResourcePlanner}; use super::slots::{ address_map_variant, anisotropic_variant, bindings, bound_value, buffer_use, check_slots, - check_sparse_textures, cross_variant, cubic_variant, heap_raw, mark_disjoint, - open_cl_line_variant, plan_buffer, psb_variant, record_noted, srgb_variant, - storage_view_variant, texel_buffer_parts_variant, used_uses, ycbcr_in_place_variant, - ycbcr_planes_sampled_variant, + check_sparse_textures, cross_variant, cubic_variant, heap_raw, open_cl_line_variant, + plan_buffer, psb_variant, record_noted, srgb_variant, texel_buffer_parts_variant, used_uses, + ycbcr_in_place_variant, ycbcr_planes_sampled_variant, }; use super::{ BindingPlan, BoundKind, ComputeTemplate, DescriptorWrite, FieldLocation, LocalRules, @@ -420,7 +419,6 @@ fn plan(p: &ComputePipeline, device: &Device, shape: &BindShape) -> Result Result), @@ -122,10 +122,11 @@ pub(crate) fn plan_buffer( bindings: &BTreeMap, ) -> Result { let bound = BoundKind::of(shape); - let (min_offset, max_range) = b.form.view_limits(limits); - let alignment = crate::memory::views::base_alignment(min_offset); + let alignment = + crate::memory::views::base_alignment(limits.min_storage_buffer_offset_alignment); + let max_range = u64::from(limits.max_storage_buffer_range); let binding = match b.form { - BufferForm::Descriptor(_) => Some( + BufferForm::Descriptor => Some( bindings .get(&BindingSource::Buffer(slot)) .copied() @@ -152,43 +153,9 @@ pub(crate) fn plan_buffer( alignment, max_range, bound, - disjoint: false, }) } -/// The `SpecKey::RangeAtBindOffset` of buffer slot `b`, bound as `shape` states: whether the -/// descriptor range starts at its bind offset (`instantiate::starts_at_bind`, under the view's -/// descriptor base alignment, as [`plan_buffer`] takes it): inline bytes, at offset 0 of the -/// consumer's aligned upload; a buffer read through a uniform view, at an offset whose alignment -/// class (`BufferShape::Buffer::offset_alignment`: `BindState::view_base_alignment` where the -/// runtime tells it apart at the slot and it divides the offset, else a power of two up to 4) the -/// base alignment divides. A slot bound to nothing has the residual 0 -/// (`instantiate::slot_field`), so either form reads the Metal offset alone of the same -/// descriptor: it takes false, the form that reads at the residual, which keeps the key of a draw -/// that leaves the slot unbound the key that reads every such slot at its residual. Only a uniform -/// view declares the key (`lower::access`); a storage view's range starts at the buffer's start or -/// its window's aligned first byte (`instantiate::planned_range`), read at its residual, so it -/// takes false too. -pub(crate) fn range_at_bind_offset( - b: &BufferSlot, - shape: Option<&BufferShape>, - limits: &Limits, -) -> bool { - if !b.form.uniform_view() { - return false; - } - let (min, _) = b.form.view_limits(limits); - let offset = match shape { - Some(&BufferShape::Buffer { - offset_alignment, .. - }) => u64::from(offset_alignment), - Some(BufferShape::Bytes { .. }) => 0, - None => return false, - }; - let alignment = crate::memory::views::base_alignment(min); - crate::bind::instantiate::starts_at_bind(offset, b.window, alignment) -} - /// The value of `key` for a draw or dispatch of `shape`, whose resources `resources` plans, where /// the bound resources decide it: a slot's presence, a bound sampler's words, a bound texture's /// class, swizzle, sparseness and view axes. It is what a specialization constant of `key` is set @@ -222,14 +189,6 @@ pub(crate) fn bound_value( SpecKey::SparseTexture(slot) => sparse_texture(shape, slot), SpecKey::ConstantLanes(slot) => constant_lanes(shape, slot), SpecKey::OffsetBaseAxes(slot) => offset_base_axes(shape, slot), - SpecKey::RangeAtBindOffset(slot) => match resources.slots.get(&slot) { - Some(SlotInterface::Buffer(b)) => u64::from(range_at_bind_offset( - b, - bound_buffer(shape, slot), - &resources.profile.fields().limits, - )), - _ => 0, - }, _ => return Ok(None), })) } @@ -700,14 +659,6 @@ pub(crate) fn anisotropic_variant( } /// The texture `shape` binds at `slot`. -/// What `shape` binds at buffer `slot`. -fn bound_buffer(shape: &BindShape, slot: SlotRef) -> Option<&BufferShape> { - shape - .stages - .get(&slot.stage) - .and_then(|s| s.buffers.get(&slot.index)) -} - fn bound_texture(shape: &BindShape, slot: SlotRef) -> Option<&TextureShape> { shape .stages @@ -779,78 +730,6 @@ pub(crate) fn check_sparse_textures( Ok(()) } -/// Mark each planned buffer whose uniform view no written slot may alias -/// (`RuntimeFact::UniformViewAliasing`): instantiation compares their Metal windows. -pub(crate) fn mark_disjoint(buffers: &mut [PlannedBuffer], dependencies: &[RuntimeDependency]) { - for b in buffers { - b.disjoint = dependencies - .iter() - .any(|d| d.fact == RuntimeFact::UniformViewAliasing { slot: b.slot }); - } -} - -/// The read-only slots Profile F's per-stage storage-buffer fallback must keep as storage views -/// for this shape (`VariantKey::storage_view_slots`): the slots the pipeline was compiled keeping -/// (`Kept`), and, when a slot the pipeline views as a uniform buffer is large, every large -/// candidate ([`large_view_candidates`]), so the fallback views none of them. The variant's -/// compile keeps and restates every slot of the key, and views only candidates the shape proves -/// small, so its plan for the same shape states the same key (a fixed point, in one compile). -/// Otherwise the key is the pipeline's own. -pub(crate) fn storage_view_variant( - dependencies: &[RuntimeDependency], - buffers: &[PlannedBuffer], - profile: &DeviceProfile, -) -> std::collections::BTreeSet { - let mut kept = std::collections::BTreeSet::new(); - let large = large_view_candidates(dependencies, buffers, profile, None); - let mut viewed_large = false; - for d in dependencies { - let RuntimeFact::UniformViewRange { slot, choice } = d.fact else { - continue; - }; - match choice { - UniformViewChoice::Kept => { - kept.insert(slot); - } - UniformViewChoice::Viewed => viewed_large |= large.contains(&slot), - _ => {} - } - } - if viewed_large { - kept.extend(large); - } - kept -} - -/// The candidates of Profile F's per-stage storage-buffer fallback (`UniformViewRange` facts of -/// any choice, of `stage` when given) at which the shape binds a buffer whose length class does -/// not prove that a uniform view's range fits `maxUniformBufferRange`. A plan whose variant adds a -/// storage buffer to a stage (a newly pulled vertex layout) names them all, since that variant's -/// fallback may view any of them. -pub(crate) fn large_view_candidates( - dependencies: &[RuntimeDependency], - buffers: &[PlannedBuffer], - profile: &DeviceProfile, - stage: Option, -) -> std::collections::BTreeSet { - let max = u64::from(profile.fields().limits.max_uniform_buffer_range); - dependencies - .iter() - .filter_map(|d| match d.fact { - RuntimeFact::UniformViewRange { slot, .. } => Some(slot), - _ => None, - }) - .filter(|slot| stage.is_none_or(|s| slot.stage == s)) - .filter(|&slot| { - buffers.iter().any(|b| { - b.slot == slot - && matches!(b.bound, BoundKind::Buffer { length_class, .. } - if !class_fits(length_class, max)) - }) - }) - .collect() -} - /// Whether every range of an allocation of length class `class` fits `max_range`: its padded /// length is below `2^class` (`BindShape` length class). pub(crate) fn class_fits(class: u8, max_range: u64) -> bool { @@ -892,17 +771,13 @@ pub(crate) fn range_variant(slot: SlotRef, bound: BoundKind, profile: &DevicePro && matches!(bound, BoundKind::Buffer { length_class, .. } if !class_fits(length_class, storage)) } -/// The `uses` entry of a bound buffer slot: its proven access, `Uniform` for a uniform view and -/// `Storage` otherwise, `stages`, and the window as a range when it starts at or after the bind -/// offset. +/// The `uses` entry of a bound buffer slot: its proven access, `Storage`, `stages`, and the window +/// as a range when it starts at or after the bind offset. pub(crate) fn buffer_use(b: &PlannedBuffer, stages: vk::PipelineStageFlags2) -> ResourceUse { ResourceUse { resource: UseTarget::Slot(b.slot), access: b.access, - class: match b.form { - form if form.uniform_view() => AccessClass::Uniform, - _ => AccessClass::Storage, - }, + class: AccessClass::Storage, stages, range: match b.window { Window::Bounded { start, len } if start >= 0 => Some(ByteRange { diff --git a/crates/metal2vulkan/src/bind/plan/slots/tests.rs b/crates/metal2vulkan/src/bind/plan/slots/tests.rs index 78a2f17e6..642f486c0 100644 --- a/crates/metal2vulkan/src/bind/plan/slots/tests.rs +++ b/crates/metal2vulkan/src/bind/plan/slots/tests.rs @@ -6,8 +6,8 @@ use crate::bind::state::{ UsedResource, }; use crate::device::profile::BufferAccess; -use crate::pipeline::facts::{Mechanism, UniformViewChoice}; -use crate::pipeline::interface::{BufferKind, DescriptorView}; +use crate::pipeline::facts::Mechanism; +use crate::pipeline::interface::BufferKind; use crate::pipeline::sym::Stage; use crate::spirv::testing::committed_profiles; @@ -65,7 +65,6 @@ fn planned(index: u32, bound: BoundKind, form: BufferForm) -> PlannedBuffer { alignment: 16, max_range: 0, bound, - disjoint: false, } } @@ -79,7 +78,7 @@ fn a_large_buffer_needs_the_device_address_variant_on_profile_a_only() { fact: RuntimeFact::BufferRangeLimit { slot: slot(n) }, mechanism: Mechanism::Variant, }); - let storage = BufferForm::Descriptor(DescriptorView::Storage); + let storage = BufferForm::Descriptor; let mut seen = [false; 2]; let mut profiles = committed_profiles().expect("profiles"); let f = crate::pipeline::testing::device_f(crate::device::DevicePolicy::RESIDENT_TABLES) @@ -142,73 +141,6 @@ fn a_large_buffer_needs_the_device_address_variant_on_profile_a_only() { assert_eq!(seen, [true, true], "both profile kinds are checked"); } -/// A shape asks for the storage-view variant exactly when it binds, at a slot the pipeline views as -/// a uniform buffer, a buffer whose length class does not prove the range fits -/// `maxUniformBufferRange`; the key then names every such candidate (viewed, spare, or kept) -/// and the slots the pipeline was compiled keeping, so the variant's plan restates it. -#[test] -fn a_large_viewed_slot_asks_for_every_large_candidate_to_stay_storage() { - let p = crate::pipeline::testing::profile( - "runtime-floor", - crate::device::DevicePolicy::RESIDENT_TABLES, - ) - .expect("profile"); - let max = u64::from(p.fields().limits.max_uniform_buffer_range); - let big = BoundKind::Buffer { - device_address: false, - length_class: length_class(max.saturating_add(1)), - }; - let fits = BoundKind::Buffer { - device_address: false, - length_class: length_class(max - 16), - }; - let dep = |n, choice| RuntimeDependency { - fact: RuntimeFact::UniformViewRange { - slot: slot(n), - choice, - }, - mechanism: Mechanism::Variant, - }; - let uniform = BufferForm::Descriptor(DescriptorView::UniformWords); - let storage = BufferForm::Descriptor(DescriptorView::Storage); - use UniformViewChoice::{Kept, Spare, Viewed}; - // Slot 0 viewed, slot 1 spare, slot 2 viewed, slot 3 spare. - let base = [dep(0, Viewed), dep(1, Spare), dep(2, Viewed), dep(3, Spare)]; - let bound = |b: [BoundKind; 4]| { - [ - planned(0, b[0], uniform), - planned(1, b[1], storage), - planned(2, b[2], uniform), - planned(3, b[3], storage), - ] - }; - // Small everywhere, or large only at spare slots, or at an unbound or inline slot: no variant. - let none = [BoundKind::Unbound, big, BoundKind::Bytes, big]; - assert!(storage_view_variant(&base, &bound([fits, big, fits, big]), &p).is_empty()); - assert!(storage_view_variant(&base, &bound(none), &p).is_empty()); - // A large viewed slot: every large candidate. - let key = storage_view_variant(&base, &bound([big, big, fits, fits]), &p); - assert_eq!(key, [slot(0), slot(1)].into()); - // The variant's own facts for the same shape: slots 0 and 1 kept, 2 still viewed, 3 now - // viewed; the plan restates the key. - let variant = [dep(0, Kept), dep(1, Kept), dep(2, Viewed), dep(3, Viewed)]; - let buffers = [ - planned(0, big, storage), - planned(1, big, storage), - planned(2, fits, uniform), - planned(3, fits, uniform), - ]; - assert_eq!(storage_view_variant(&variant, &buffers, &p), key); - // A kept slot the shape binds small is still restated. - let buffers = [ - planned(0, fits, storage), - planned(1, fits, storage), - planned(2, fits, uniform), - planned(3, fits, uniform), - ]; - assert_eq!(storage_view_variant(&variant, &buffers, &p), key); -} - /// Used resources reach a plan's `uses` exactly when a function can reach them, with the guest's /// declared usage, and the shape unions a token listed twice. #[test] @@ -350,15 +282,14 @@ fn used_resources_are_written_only_by_stages_that_write_memory() { ); } -/// Buffer range limits tell a buffer's length class apart as far as a plan reads it -/// (`BufferRanges::length_class`), under 4 GiB limits (an RX 7900 XTX's), limits of 64 KiB and -/// 128 MiB either way round, one limit of 16 KiB, and none (the default, every class its own): -/// the class a buffer's shape states of each length answers `class_fits` against each limit as -/// the exact class does (all a plan reads of it: `large_view_candidates`, `range_variant`), still -/// bounds the padded length from above, and is the exact one under none; and instantiation's kind -/// check (`instantiate::bound_buffer`) takes a binding of each length for the kind a plan of -/// another length stored exactly where the two classes are one, which is only where their exact -/// classes answer both limits alike. +/// A buffer range limit tells a buffer's length class apart as far as a plan reads it +/// (`BufferRanges::length_class`), under a 4 GiB limit (an RX 7900 XTX's), limits of 128 MiB, +/// 64 KiB and 16 KiB, and none (the default, every class its own): the class a buffer's shape +/// states of each length answers `class_fits` against the limit as the exact class does (all a +/// plan reads of it: `range_variant`), still bounds the padded length from above, and is the exact +/// one under none; and instantiation's kind check (`instantiate::bound_buffer`) takes a binding of +/// each length for the kind a plan of another length stored exactly where the two classes are +/// one, which is only where their exact classes answer the limit alike. #[test] fn length_classes_are_told_apart_as_far_as_a_plan_reads_them() { let mut lengths = vec![0u64, 1, 15, 16, 17, u64::MAX]; @@ -367,27 +298,13 @@ fn length_classes_are_told_apart_as_far_as_a_plan_reads_them() { } let limits = [ BufferRanges::default(), - BufferRanges { - uniform: u32::MAX, - storage: u32::MAX, - }, - BufferRanges { - uniform: 1 << 16, - storage: 1 << 27, - }, - BufferRanges { - uniform: 1 << 27, - storage: 1 << 16, - }, - BufferRanges { - uniform: 1 << 14, - storage: 1 << 14, - }, + BufferRanges { storage: u32::MAX }, + BufferRanges { storage: 1 << 27 }, + BufferRanges { storage: 1 << 16 }, + BufferRanges { storage: 1 << 14 }, ]; for ranges in limits { - let fits = |class| { - [ranges.uniform, ranges.storage].map(|limit| class_fits(class, u64::from(limit))) - }; + let fits = |class| class_fits(class, u64::from(ranges.storage)); let states: Vec = (lengths.iter()) .map(|&length| { let mut table = StageTable { @@ -439,7 +356,7 @@ fn length_classes_are_told_apart_as_far_as_a_plan_reads_them() { } } } - // Under 4 GiB limits every length up to 4 GiB is one class, past them each its own. + // Under a 4 GiB limit every length up to 4 GiB is one class, past it each its own. let ranges = limits[1]; assert_eq!(ranges.length_class(1), ranges.length_class((1 << 32) - 16)); assert_ne!(ranges.length_class(1), ranges.length_class(1 << 32)); @@ -457,7 +374,7 @@ fn the_bound_kind_carries_the_length_class() { attribute_stride: None, }; assert_eq!( - BoundKind::of(Some(&b.shape(0, BufferRanges::default()))), + BoundKind::of(Some(&b.shape(BufferRanges::default()))), BoundKind::Buffer { device_address: true, length_class: 7 @@ -501,14 +418,13 @@ fn slots_beyond_the_metal_tables_are_refused() { assert!(check_slots(&shape).is_err()); } -/// On every committed profile a storage or uniform view's descriptor base is aligned to -/// `max(min*BufferOffsetAlignment, 16)`, so whatever the bind offset and window, every byte of the -/// range sits at a descriptor offset congruent to its allocation offset modulo 16: a 16-byte leaf -/// whose Metal address is a multiple of 16 is one `uvec4` element of the view. +/// On every committed profile a storage view's descriptor base is aligned to +/// `max(minStorageBufferOffsetAlignment, 16)`, so whatever the bind offset and window, every byte +/// of the range sits at a descriptor offset congruent to its allocation offset modulo 16: a 16-byte +/// leaf whose Metal address is a multiple of 16 is one `uvec4` element of the view. #[test] fn descriptor_bases_are_sixteen_aligned_on_every_profile() { - let buffer = |index| BindingSource::Buffer(slot(index)); - let bindings: BTreeMap<_, _> = [(buffer(0), (0, 0)), (buffer(1), (0, 1))].into(); + let bindings: BTreeMap<_, _> = [(BindingSource::Buffer(slot(0)), (0, 0))].into(); let shape = BufferShape::Buffer { device_address: false, length_class: length_class(4096), @@ -517,134 +433,40 @@ fn descriptor_bases_are_sixteen_aligned_on_every_profile() { }; for (stem, p) in committed_profiles().expect("profiles") { let limits = &p.fields().limits; - for (index, view, min) in [ - ( - 0, - DescriptorView::Storage, - limits.min_storage_buffer_offset_alignment, - ), - ( - 1, - DescriptorView::UniformWords, - limits.min_uniform_buffer_offset_alignment, - ), - ] { - let b = BufferSlot { - access: AccessSet::READ, - window: Window::Whole, - form: BufferForm::Descriptor(view), - kind: BufferKind::Buffer, - }; - let pb = plan_buffer((slot(index), &b, Some(&shape)), false, limits, &bindings) - .unwrap_or_else(|e| panic!("{stem} {view:?}: {e:?}")); - assert_eq!(pb.alignment, min.max(16), "{stem} {view:?}"); - for bind_offset in (0..64).step_by(4) { - for window in [ - Window::Whole, - Window::Bounded { start: 0, len: 64 }, - Window::Bounded { start: 4, len: 28 }, - Window::Bounded { start: 52, len: 16 }, - Window::Bounded { start: -8, len: 40 }, - ] { - let (range, residual) = crate::bind::instantiate::descriptor_range( - bind_offset, - 4096, - window, - pb.alignment, - u64::MAX, - ) - .unwrap_or_else(|e| panic!("{stem} {view:?}: {e:?}")); - assert_eq!(range.offset % 16, 0, "{stem} {view:?} {bind_offset}"); - // Byte `m` from the bind offset is byte `residual + m` of the range. - assert_eq!( - u64::from(residual) % 16, - bind_offset % 16, - "{stem} {view:?} {bind_offset} {window:?}" - ); - } - } - } - } -} - -/// A uniform view's `RangeAtBindOffset` holds exactly where instantiation starts its range at the -/// bind offset, its residual 0, on every committed profile, for a buffer bound anywhere before the -/// end of its allocation under a window starting at or after the bind offset and inside the -/// allocation (elsewhere it never holds where the residual is not 0; false reads correctly at any -/// residual); and for inline bytes, at offset 0 of their upload. An unbound slot, whose residual -/// is 0, takes false: the key's residual form, which a draw's key matches where it leaves the slot -/// unbound. -#[test] -fn a_uniform_range_starts_at_the_bind_offset_where_the_specialization_says() { - const LENGTH: u64 = 4096; - for (stem, p) in committed_profiles().expect("profiles") { - let limits = &p.fields().limits; - let alignment = - crate::memory::views::base_alignment(limits.min_uniform_buffer_offset_alignment); - for window in [ - Window::Whole, - Window::Bounded { start: 0, len: 64 }, - Window::Bounded { start: 4, len: 28 }, - Window::Bounded { start: 52, len: 16 }, - Window::Bounded { - start: 192, - len: 16, - }, - Window::Bounded { start: 255, len: 1 }, - Window::Bounded { start: -8, len: 40 }, - ] { - let b = BufferSlot { - access: AccessSet::READ, - window, - form: BufferForm::Descriptor(DescriptorView::UniformWords), - kind: BufferKind::Buffer, - }; - let zero = |bind_offset: u64| { - let (_, residual) = crate::bind::instantiate::descriptor_range( + let min = limits.min_storage_buffer_offset_alignment; + let b = BufferSlot { + access: AccessSet::READ, + window: Window::Whole, + form: BufferForm::Descriptor, + kind: BufferKind::Buffer, + }; + let pb = plan_buffer((slot(0), &b, Some(&shape)), false, limits, &bindings) + .unwrap_or_else(|e| panic!("{stem}: {e:?}")); + assert_eq!(pb.alignment, min.max(16), "{stem}"); + for bind_offset in (0..64).step_by(4) { + for window in [ + Window::Whole, + Window::Bounded { start: 0, len: 64 }, + Window::Bounded { start: 4, len: 28 }, + Window::Bounded { start: 52, len: 16 }, + Window::Bounded { start: -8, len: 40 }, + ] { + let (range, residual) = crate::bind::instantiate::descriptor_range( bind_offset, - LENGTH, + 4096, window, - alignment, + pb.alignment, u64::MAX, ) - .unwrap_or_else(|e| panic!("{stem} {window:?} {bind_offset}: {e:?}")); - residual == 0 - }; - for bind_offset in (0..LENGTH).step_by(4) { - let shape = BoundBuffer::Buffer { - gpu_address: 0x1_0000, - length: LENGTH, - offset: bind_offset, - device_address: None, - attribute_stride: None, - } - .shape(alignment as u32, BufferRanges::default()); - let at = range_at_bind_offset(&b, Some(&shape), limits); - let what = format!("{stem} {window:?} {bind_offset}"); - // A window starting below the bind offset, or past the allocation's end (whose - // range is widened down into it), may still start at the bind offset. - match window { - Window::Bounded { start, .. } - if start < 0 || bind_offset as i64 + start >= LENGTH as i64 => - { - assert!(!at || zero(bind_offset), "{what}") - } - _ => assert_eq!(at, zero(bind_offset), "{what}"), - } + .unwrap_or_else(|e| panic!("{stem}: {e:?}")); + assert_eq!(range.offset % 16, 0, "{stem} {bind_offset}"); + // Byte `m` from the bind offset is byte `residual + m` of the range. + assert_eq!( + u64::from(residual) % 16, + bind_offset % 16, + "{stem} {bind_offset} {window:?}" + ); } - let bytes = BufferShape::Bytes { - attribute_stride: None, - }; - let at = range_at_bind_offset(&b, Some(&bytes), limits); - assert_eq!( - at, - zero(0) && !matches!(window, Window::Bounded { start, .. } if start < 0), - "{stem} {window:?} bytes" - ); - assert!( - !range_at_bind_offset(&b, None, limits), - "{stem} {window:?} unbound" - ); } } } diff --git a/crates/metal2vulkan/src/bind/state.rs b/crates/metal2vulkan/src/bind/state.rs index 480c7dca3..cf0b8dc12 100644 --- a/crates/metal2vulkan/src/bind/state.rs +++ b/crates/metal2vulkan/src/bind/state.rs @@ -153,28 +153,6 @@ pub struct BindState { /// [`BindingPlan::heap_elements`]: crate::bind::BindingPlan::heap_elements #[cfg_attr(feature = "serde", serde(default))] pub heap_placement: HeapPlacement, - /// The descriptor base alignment of the device's uniform views, which the runtime sets: the one - /// alignment above the vertex fetch's that the bind offset class of a buffer at a slot of - /// [`StageTable::at_bind_views`] tells apart, as a uniform view's range starts at its bind - /// offset only at a multiple of it (`SpecKey::RangeAtBindOffset`). 0, the - /// default, tells none apart: every view is then read at its residual, exact on every device, - /// as it is under any other value the plan does not find its own. - #[cfg_attr(feature = "serde", serde(default))] - pub view_base_alignment: u32, - /// Whether the consumer reads every uniform view at its residual: it draws and dispatches - /// with each plan's key at every uniform view's `SpecKey::RangeAtBindOffset` 0, as the runtime - /// does on a device whose driver loads no uniform read at a constant offset ahead of the - /// shader. A uniform view's descriptor range then need not start at its bind offset, and - /// instantiation binds one that a run of bind offsets of the bound buffer shares (the buffer - /// from its start where it fits the view's maximum range), its `SlotBindOffset` residual the - /// rest: a command that moves only such a slot's offset binds the same descriptor, keeps its - /// set 0 and pushes only its residual. False, the default, starts each uniform view's range at - /// its bind offset aligned down to the view base alignment, which a key reading it at its bind - /// offset alone (`RangeAtBindOffset` 1) needs. Either reads the same bytes. Only the descriptor - /// ranges and residuals a command's instantiation writes depend on it, so it is not part of - /// the shape. - #[cfg_attr(feature = "serde", serde(default))] - pub uniform_views_at_residual: bool, /// The render encoder's viewport count (`setViewports:count:`): a vertex function's /// `[[viewport_array_index]]` at or past it draws through viewport 0, as Metal's does /// (`PushField::ViewportCount`). Metal's default is one viewport; 0, the default here, and 1 @@ -428,9 +406,8 @@ impl BindState { /// The projection of this state that can change a plan: per stage, which slots are bound and /// with what kind of resource, whether a buffer has a device address, its per-bind stride, its /// length class as the table's [`StageTable::buffer_ranges`] tell it apart and bind-offset - /// alignment class (the largest power of two up to 4 that divides the offset, or - /// [`view_base_alignment`](Self::view_base_alignment) where that divides it at a slot of - /// [`StageTable::at_bind_views`]), texture types and formats, sampler modes, threadgroup + /// alignment class (the largest power of two up to 4 that divides the offset), texture types + /// and formats, sampler modes, threadgroup /// lengths, the vertex amplification, the render target array length, whether a /// tessellation factor buffer is set, a tile dispatch's render area, the argument samplers' /// capacity class and shapes ([`ArgumentSamplersShape::of`]), and the tile threadgroup memory @@ -441,7 +418,7 @@ impl BindState { let stages = self .stages .iter() - .map(|(stage, t)| (*stage, t.shape(self.view_base_alignment))) + .map(|(stage, t)| (*stage, t.shape())) .filter(|(_, s)| *s != StageShape::default()) .collect(); BindShape { @@ -551,9 +528,9 @@ impl BindState { } = shape; let tables = self.stages.iter().filter(|(_, t)| !t.has_empty_shape()); tables.clone().count() == stages.len() - && tables.zip(stages).all(|((stage, t), (of, s))| { - stage == of && t.has_shape(s, self.view_base_alignment) - }) + && tables + .zip(stages) + .all(|((stage, t), (of, s))| stage == of && t.has_shape(s)) && self.vertex_amplification == *vertex_amplification && self.imageblock_size == *imageblock_size && self.render_target_array_length == *render_target_array_length @@ -766,18 +743,11 @@ impl ViewMapping { } impl StageTable { - /// The shape of this stage's tables ([`BindState::shape`]), the bind offsets of its buffers at - /// [`at_bind_views`](Self::at_bind_views) classed under the uniform views' base alignment - /// `view_base_alignment` ([`BindState::view_base_alignment`]) and their lengths under its - /// [`buffer_ranges`](Self::buffer_ranges). - pub fn shape(&self, view_base_alignment: u32) -> StageShape { + /// The shape of this stage's tables ([`BindState::shape`]), the lengths of its buffers classed + /// under its [`buffer_ranges`](Self::buffer_ranges). + pub fn shape(&self) -> StageShape { let ranges = self.buffer_ranges; - let buffer = |(i, b): (&u32, &BoundBuffer)| { - ( - *i, - b.shape(self.class_alignment(*i, view_base_alignment), ranges), - ) - }; + let buffer = |(i, b): (&u32, &BoundBuffer)| (*i, b.shape(ranges)); StageShape { buffers: self.buffers.iter().map(buffer).collect(), textures: self.textures.iter().map(|(i, t)| (*i, t.shape())).collect(), @@ -794,9 +764,8 @@ impl StageTable { && self.threadgroup_lengths.is_empty() } - /// Whether `shape` is its shape ([`BindState::has_shape`]), under the uniform views' base - /// alignment `view_base_alignment`. - fn has_shape(&self, shape: &StageShape, view_base_alignment: u32) -> bool { + /// Whether `shape` is its shape ([`BindState::has_shape`]). + fn has_shape(&self, shape: &StageShape) -> bool { let StageShape { buffers, textures, @@ -804,12 +773,7 @@ impl StageTable { threadgroup_lengths, } = shape; let ranges = self.buffer_ranges; - let buffer_shapes = (self.buffers.iter()).map(|(i, b)| { - ( - *i, - b.shape(self.class_alignment(*i, view_base_alignment), ranges), - ) - }); + let buffer_shapes = (self.buffers.iter()).map(|(i, b)| (*i, b.shape(ranges))); let texture_shapes = self.textures.iter().map(|(i, t)| (*i, t.shape())); let sampler_shapes = self.samplers.iter().map(|(i, s)| (*i, s.shape())); buffer_shapes.eq(buffers.iter().map(|(i, b)| (*i, *b))) @@ -817,24 +781,13 @@ impl StageTable { && sampler_shapes.eq(samplers.iter().map(|(i, s)| (*i, *s))) && self.threadgroup_lengths == *threadgroup_lengths } - - /// The alignment above the vertex fetch's that the bind offset class of a buffer at index - /// `index` tells apart ([`BoundBuffer::shape`]): `view_base_alignment` at a slot of - /// [`at_bind_views`](Self::at_bind_views), else 0 (none). - pub fn class_alignment(&self, index: u32, view_base_alignment: u32) -> u32 { - if index < u64::BITS && (self.at_bind_views >> index) & 1 == 1 { - view_base_alignment - } else { - 0 - } - } } impl BoundBuffer { - /// The shape of this binding, its bind offset classed under the uniform views' base alignment - /// `view_base_alignment` (`BufferShape::Buffer`'s `offset_alignment`) and its length under the - /// buffer range limits `ranges` (its `length_class`, [`BufferRanges::length_class`]). - pub fn shape(&self, view_base_alignment: u32, ranges: BufferRanges) -> BufferShape { + /// The shape of this binding, its bind offset classed (`BufferShape::Buffer`'s + /// `offset_alignment`) and its length under the buffer range limits `ranges` (its + /// `length_class`, [`BufferRanges::length_class`]). + pub fn shape(&self, ranges: BufferRanges) -> BufferShape { match *self { BoundBuffer::Buffer { length, @@ -846,7 +799,7 @@ impl BoundBuffer { attribute_stride, device_address: device_address.is_some(), length_class: ranges.length_class(length), - offset_alignment: offset_alignment(offset, view_base_alignment), + offset_alignment: offset_alignment(offset), }, BoundBuffer::Bytes { attribute_stride, .. @@ -854,15 +807,9 @@ impl BoundBuffer { } } - /// Whether this binding and `other` have one shape under `view_base_alignment` and `ranges`, - /// as their [`shape`](Self::shape)s compare: a length or bind offset the two share is not - /// classed. - pub fn same_shape( - &self, - other: &BoundBuffer, - view_base_alignment: u32, - ranges: BufferRanges, - ) -> bool { + /// Whether this binding and `other` have one shape under `ranges`, as their + /// [`shape`](Self::shape)s compare: a length or bind offset the two share is not classed. + pub fn same_shape(&self, other: &BoundBuffer, ranges: BufferRanges) -> bool { match (*self, *other) { ( BoundBuffer::Buffer { @@ -885,8 +832,7 @@ impl BoundBuffer { && (length == other_length || ranges.length_class(length) == ranges.length_class(other_length)) && (offset == other_offset - || offset_alignment(offset, view_base_alignment) - == offset_alignment(other_offset, view_base_alignment)) + || offset_alignment(offset) == offset_alignment(other_offset)) } ( BoundBuffer::Bytes { @@ -904,20 +850,12 @@ impl BoundBuffer { } /// The alignment class of bind offset `offset` (a buffer's, -/// [`BufferShape::Buffer::offset_alignment`]): `view_base_alignment` where that divides it (the -/// uniform views' descriptor base alignment, [`BindState::view_base_alignment`]: a view's range -/// then starts at the offset, `SpecKey::RangeAtBindOffset`), else the largest power of two up to +/// [`BufferShape::Buffer::offset_alignment`]): the largest power of two up to /// [`MAX_VERTEX_ALIGNMENT`](metal::vertex::MAX_VERTEX_ALIGNMENT) that divides it (whether -/// fixed-function vertex input can fetch every attribute format at a buffer bound there). These -/// are the only predicates a plan reads of a bind offset, so offsets moving between multiples of -/// 4 that the base alignment does not divide, or between those it divides, keep one shape; a -/// `view_base_alignment` of 4 or less (0, the default) tells only the vertex fetch's apart. -pub fn offset_alignment(offset: u64, view_base_alignment: u32) -> u32 { - if view_base_alignment > metal::vertex::MAX_VERTEX_ALIGNMENT - && offset.is_multiple_of(u64::from(view_base_alignment)) - { - return view_base_alignment; - } +/// fixed-function vertex input can fetch every attribute format at a buffer bound there). It is +/// the only predicate a plan reads of a bind offset, so offsets moving between multiples of 4 +/// keep one shape. +pub fn offset_alignment(offset: u64) -> u32 { let mut a = metal::vertex::MAX_VERTEX_ALIGNMENT; while a > 1 && !offset.is_multiple_of(u64::from(a)) { a /= 2; @@ -1043,18 +981,9 @@ pub struct StageTable { /// shape. #[cfg_attr(feature = "serde", serde(default))] pub acceleration_structures: BTreeMap, - /// The buffer slots (bit `i` for index `i`) whose bind offset class tells - /// [`BindState::view_base_alignment`] apart, which the runtime sets: the - /// slots its function reads through a uniform view, whose range a plan starts at the bind - /// offset where that alignment divides it (`SpecKey::RangeAtBindOffset`). No plan reads that - /// predicate of another slot, so its offsets moving among multiples of 4 keep one shape. A slot - /// left out (none, the default) reads its view at its residual, exact at every offset: a - /// runtime leaves out a slot it finds bound at moving offsets, so that its draws keep one shape. - #[cfg_attr(feature = "serde", serde(default))] - pub at_bind_views: u64, - /// The device's buffer range limits, which the runtime sets: its buffers' length classes are - /// told apart only as far as those limits tell them apart ([`BufferRanges::length_class`]), - /// all a plan reads of a buffer's length, so its buffers of lengths they do not tell apart + /// The device's buffer range limit, which the runtime sets: its buffers' length classes are + /// told apart only as far as that limit tells them apart ([`BufferRanges::length_class`]), + /// all a plan reads of a buffer's length, so its buffers of lengths it does not tell apart /// keep one shape. None (the default) tells every class apart. #[cfg_attr(feature = "serde", serde(default))] pub buffer_ranges: BufferRanges, @@ -1409,47 +1338,41 @@ pub fn length_class(length: u64) -> u8 { (u128::BITS - padded.leading_zeros()) as u8 } -/// The range limits of a device's buffer views (`maxUniformBufferRange` and -/// `maxStorageBufferRange`, [`BufferRanges::of`]), the only values a plan compares a bound -/// buffer's length class with (whether every range of the buffer fits each), which the runtime -/// sets on each stage table ([`StageTable::buffer_ranges`]). A buffer's shape tells apart only the -/// classes those comparisons tell apart ([`BufferRanges::length_class`]), so buffers of lengths -/// the device's limits do not tell apart bind one shape and take one plan, as a stream of -/// dispatches over buffers of many sizes binds them. The default, both 0, tells every class apart. +/// The range limit of a device's buffer views (`maxStorageBufferRange`, [`BufferRanges::of`]), the +/// only value a plan compares a bound buffer's length class with (whether every range of the +/// buffer fits it), which the runtime sets on each stage table ([`StageTable::buffer_ranges`]). A +/// buffer's shape tells apart only the classes that comparison tells apart +/// ([`BufferRanges::length_class`]), so buffers of lengths the device's limit does not tell apart +/// bind one shape and take one plan, as a stream of dispatches over buffers of many sizes binds +/// them. The default, 0, tells every class apart. #[non_exhaustive] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct BufferRanges { - /// `maxUniformBufferRange`. - pub uniform: u32, /// `maxStorageBufferRange`. pub storage: u32, } impl BufferRanges { - /// The range limits of a device of `limits`. + /// The range limit of a device of `limits`. pub fn of(limits: &Limits) -> BufferRanges { BufferRanges { - uniform: limits.max_uniform_buffer_range, storage: limits.max_storage_buffer_range, } } /// The length class a buffer's shape states of an allocation of `length` bytes /// ([`BufferShape::Buffer`]'s `length_class`): its exact class rounded up to the greatest - /// class whose every range fits the least of the two limits it fits, so a plan's comparison of - /// the class with either limit answers as the exact class's does; a class past both limits is - /// its own. Rounded up, the class still bounds the padded length (`padded(length) < - /// 2^class`), so under limits other than its device's no plan reads a range past a limit - /// either: it may take only the form a longer buffer takes. + /// class whose every range fits the limit, where it fits, so a plan's comparison of the class + /// with the limit answers as the exact class's does; a class past the limit is its own. + /// Rounded up, the class still bounds the padded length (`padded(length) < 2^class`), so under + /// a limit other than its device's no plan reads a range past it either: it may take only the + /// form a longer buffer takes. pub fn length_class(&self, length: u64) -> u8 { let class = length_class(length); - let (uniform, storage) = (widest_class(self.uniform), widest_class(self.storage)); - let (least, most) = (uniform.min(storage), uniform.max(storage)); - if class <= least { - least - } else if class <= most { - most + let widest = widest_class(self.storage); + if class <= widest { + widest } else { class } @@ -1773,8 +1696,6 @@ pub enum BufferShape { /// ([`BufferRanges::length_class`]), as [`BindState::shape`] computes it. length_class: u8, /// The alignment class of the bind offset, as [`BindState::shape`] computes it: the - /// uniform views' base alignment ([`BindState::view_base_alignment`]) where the slot - /// tells it apart ([`StageTable::at_bind_views`]) and it divides the offset, else the /// largest power of two up to 4 that divides it. offset_alignment: u32, }, diff --git a/crates/metal2vulkan/src/cache/codec.rs b/crates/metal2vulkan/src/cache/codec.rs index 58cb43680..0fa6e97b3 100644 --- a/crates/metal2vulkan/src/cache/codec.rs +++ b/crates/metal2vulkan/src/cache/codec.rs @@ -38,16 +38,16 @@ use crate::pipeline::artifact::{ SpecializedNote, StageModule, StrategyCensus, StrategyUse, }; use crate::pipeline::descriptor::TessellationDescriptor; -use crate::pipeline::facts::{Mechanism, RuntimeFact, UniformViewChoice}; +use crate::pipeline::facts::{Mechanism, RuntimeFact}; use crate::pipeline::graphics::{ BandPrimitive, BlendState, ColorAttachmentState, GraphicsState, InputAttachmentUse, LineBandState, TessellationState, }; use crate::pipeline::interface::{ - AccessSet, BufferForm, BufferKind, BufferSlot, CommandWrites, DescriptorView, LevelReads, - NumberedSampler, PatchDomain, PipelineInterface, PlacedField, PushLoc, PushPlacement, - SampledLevels, SamplerArray, SamplerSlot, SlotInterface, StageDescriptor, StageInterface, - StageSpec, TessellationStage, TextureAccess, TextureSlot, ThreadgroupArgument, Window, + AccessSet, BufferForm, BufferKind, BufferSlot, CommandWrites, LevelReads, NumberedSampler, + PatchDomain, PipelineInterface, PlacedField, PushLoc, PushPlacement, SampledLevels, + SamplerArray, SamplerSlot, SlotInterface, StageDescriptor, StageInterface, StageSpec, + TessellationStage, TextureAccess, TextureSlot, ThreadgroupArgument, Window, }; use crate::pipeline::layout::{ BindingSource, DescriptorBinding, DescriptorSetLayout, PipelineLayout, PushConstantRange, @@ -865,7 +865,7 @@ codec_enum! { TgOffset(f0), TileThreadgroupLength, TileGridWidth, TextureSwizzle(f0), ObjectLocalSize(f0), ObjectFlatLocalSize, ObjectMultiRegion, SamplerMinLevel(f0), ConstantLanes(f0), BoundTexelFormat(f0), OffsetBaseAxes(f0), SamplerAnisotropy(f0), - RangeAtBindOffset(f0), NearestPixelSampler(f0), BoundSamplerWord(f0), StageInReach, + NearestPixelSampler(f0), BoundSamplerWord(f0), StageInReach, HeapRawTextures(f0), BorderTexels(f0), HeapNanFamilies(f0), DeepThreadgroup, } PushField { @@ -1157,9 +1157,8 @@ codec_enum! { NumberedSampler { Constexpr(f0), Read, Write } PatchDomain { Triangle, Quad } Window { Bounded { start, len }, Whole } - BufferForm { Descriptor(f0), Psb } + BufferForm { Descriptor, Psb } BufferKind { Buffer, VisibleFunctionTable, IntersectionFunctionTable } - DescriptorView { Storage, UniformWords, UniformVec4 } PushLoc { Push { offset }, ArgumentTable { offset } } IoRole { Attribute { index }, Varying { user, interpolation }, @@ -1212,7 +1211,6 @@ codec_enum! { ImageblockSize { cell_bytes }, RenderTargetArrayLength { layer_dropped }, StageInRegion, StageInStride { layout }, - UniformViewRange { slot, choice }, UniformViewAliasing { slot }, TileFunction, TileAttachmentFormat { color, format }, StorageTextureNumericType { slot }, OutOfBoundsAlpha { slot }, @@ -1273,7 +1271,6 @@ codec_enum! { GridTiles, PrivateArena { slot_bytes }, } - UniformViewChoice { Viewed, Spare, Kept } Mechanism { Specialization, Variant, PushConstant, DynamicState, DynamicStateOrPushConstant, Builtin, PlanTimeCheck, BinderView, KeyProjection, RegionSelected, diff --git a/crates/metal2vulkan/src/cache/codec/tests.rs b/crates/metal2vulkan/src/cache/codec/tests.rs index 9e5fc5d3d..89980975b 100644 --- a/crates/metal2vulkan/src/cache/codec/tests.rs +++ b/crates/metal2vulkan/src/cache/codec/tests.rs @@ -211,10 +211,7 @@ fn variants_are_named_not_numbered() { } } // The same field bytes under another variant name. - assert_ne!( - BufferForm::Descriptor(DescriptorView::Storage).digest(), - BufferForm::Psb.digest() - ); + assert_ne!(BufferForm::Descriptor.digest(), BufferForm::Psb.digest()); assert_ne!(Stage::Vertex.digest(), Stage::Fragment.digest()); } diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 9183154c5..7c51b16aa 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -178,13 +178,6 @@ pub struct VariantKey { /// without it. #[cfg_attr(feature = "serde", serde(default))] pub unit_axes: u8, - /// Read-only slots that Profile F's per-stage storage-buffer fallback keeps as storage views: - /// the shape binds a buffer whose length class does not prove that a uniform view's range fits - /// `maxUniformBufferRange` at a slot the fallback views as a uniform buffer, so every such - /// candidate stays a storage view and the fallback views others (or the compile refuses the - /// per-stage limit). The plan of a pipeline compiled under it states it. - #[cfg_attr(feature = "serde", serde(default))] - pub storage_view_slots: BTreeSet, /// Texture slots bound to an 8-bit sRGB texture the device cannot sample, which the runtime /// holds as the format's UNORM twin (`metal::format::srgb_raw_twin`), whose views read the /// codes (`c / 255`): every slot of a `RuntimeFact::SrgbTexture` the shape binds in such a @@ -502,7 +495,6 @@ impl VariantKey { && !self.emulated_simdgroups && !self.one_row && self.unit_axes == 0 - && self.storage_view_slots.is_empty() && self.srgb_textures.is_empty() && self.ycbcr_in_place.is_empty() && self.ycbcr_planes_sampled.is_empty() @@ -597,12 +589,6 @@ impl VariantKey { .filter(|_| stage != crate::pipeline::sym::Stage::Kernel); out.region_viewports = self.region_viewports && stage == crate::pipeline::sym::Stage::Vertex; - out.storage_view_slots = self - .storage_view_slots - .iter() - .filter(|s| s.stage == stage) - .copied() - .collect(); out.srgb_textures = self .srgb_textures .iter() diff --git a/crates/metal2vulkan/src/cache/tests.rs b/crates/metal2vulkan/src/cache/tests.rs index 7232c7eb6..255c34722 100644 --- a/crates/metal2vulkan/src/cache/tests.rs +++ b/crates/metal2vulkan/src/cache/tests.rs @@ -1245,76 +1245,6 @@ fn combined_and_separate_texture_symbols_round_trip() { } } -#[test] -fn the_storage_view_variant_round_trips() { - use crate::bind::{BindState, BoundBuffer, StageTable}; - use crate::cache::VariantKey; - use crate::pipeline::facts::{RuntimeFact, UniformViewChoice}; - // Profile F's descriptor buffers: four storage buffers a stage, below the runtime's floor. - let dev = crate::pipeline::testing::device_f(DevicePolicy::RESIDENT_TABLES).expect("device"); - let Some(bc) = fixture("descriptor_limit_uniform_views") else { - return; - }; - let f = Library::from_air(&bc) - .and_then(|lib| lib.function("descriptor_limit_uniform_views")) - .expect("kernel"); - let slot = |index| SlotRef { - stage: Stage::Kernel, - class: SlotClass::Buffer, - index, - }; - let mut key = VariantKey::new(); - key.storage_view_slots.insert(slot(2)); - let compiled = dev - .compile_function( - &FunctionDescriptor::new(f), - &key.lowering_inputs(Stage::Kernel), - &Budget::standard(), - ) - .expect("function"); - let pipeline = dev - .compile_compute_pipeline( - &ComputePipelineDescriptor::new(StageSource::Compiled(compiled)), - &Budget::standard(), - ) - .expect("pipeline"); - let decoded = ComputePipeline::from_bytes(&pipeline.to_bytes(), &dev).expect("decoded"); - assert_eq!(decoded, pipeline); - let has = |fact| decoded.dependencies.iter().any(|d| d.fact == fact); - let range = |index, choice| RuntimeFact::UniformViewRange { - slot: slot(index), - choice, - }; - assert!(has(range(2, UniformViewChoice::Kept))); - assert!(has(range(4, UniformViewChoice::Viewed))); - assert!(has(range(0, UniformViewChoice::Spare))); - assert!(has(RuntimeFact::UniformViewAliasing { slot: slot(3) })); - let mut t = StageTable::default(); - for (index, length) in [ - (0, 256), - (1, 256), - (2, 1 << 16), - (3, 16), - (4, 256), - (5, 256), - ] { - t.buffers.insert( - index, - BoundBuffer::Buffer { - length, - offset: 0, - gpu_address: u64::from(index + 1) << 32, - device_address: None, - attribute_stride: None, - }, - ); - } - let mut state = BindState::default(); - state.stages.insert(Stage::Kernel, t); - let plan = decoded.plan(&dev, &state.shape()).expect("plan"); - assert_eq!(plan.variant, key); -} - /// A body that passes the checksum is still decoded strictly (every byte used) and scanned: a /// relocation off its decoration literal, a nonzero relocation slot, a broken header, a zero-word /// instruction, or a mismatched key are `Corrupt` (the linear sanity scan). diff --git a/crates/metal2vulkan/src/device/mechanism.rs b/crates/metal2vulkan/src/device/mechanism.rs index 264f3afa9..763f80a8a 100644 --- a/crates/metal2vulkan/src/device/mechanism.rs +++ b/crates/metal2vulkan/src/device/mechanism.rs @@ -79,11 +79,6 @@ pub fn mechanism(fact: &RuntimeFact, profile: &DeviceProfile) -> Mechanism { RuntimeFact::StageInRegion => Mechanism::PushConstant, // The binder writes the bound stride per dispatch. RuntimeFact::StageInStride { .. } => Mechanism::PushConstant, - // A shape that does not prove a uniform view's range fits asks for the variant that keeps - // the slot a storage view. - RuntimeFact::UniformViewRange { .. } => Mechanism::Variant, - // Instantiation compares the bound Metal addresses. - RuntimeFact::UniformViewAliasing { .. } => Mechanism::PlanTimeCheck, // The render area is specialized; the planner refuses a layered pass. RuntimeFact::TileFunction => Mechanism::Specialization, // Compiled in under the function's key; the tile pipeline checks its descriptor. diff --git a/crates/metal2vulkan/src/device/tests/mechanism.rs b/crates/metal2vulkan/src/device/tests/mechanism.rs index 73fb3fa99..0017eb054 100644 --- a/crates/metal2vulkan/src/device/tests/mechanism.rs +++ b/crates/metal2vulkan/src/device/tests/mechanism.rs @@ -2,7 +2,7 @@ use super::profile::device; use crate::device::mechanism::mechanism; -use crate::pipeline::facts::{Mechanism, RuntimeFact, UniformViewChoice}; +use crate::pipeline::facts::{Mechanism, RuntimeFact}; use crate::pipeline::sym::{ ImageAccess, ImageDim, ImageHandleClass, SampledType, SlotClass, SlotRef, Stage, StorageFormatClass, @@ -62,19 +62,6 @@ fn every_fact() -> Vec { }, RuntimeFact::StageInRegion, RuntimeFact::StageInStride { layout: 2 }, - RuntimeFact::UniformViewRange { - slot, - choice: UniformViewChoice::Viewed, - }, - RuntimeFact::UniformViewRange { - slot, - choice: UniformViewChoice::Spare, - }, - RuntimeFact::UniformViewRange { - slot, - choice: UniformViewChoice::Kept, - }, - RuntimeFact::UniformViewAliasing { slot }, RuntimeFact::TileFunction, RuntimeFact::TileAttachmentFormat { color: 1, @@ -254,8 +241,8 @@ fn variant(f: &RuntimeFact) -> usize { RuntimeFact::RenderTargetArrayLength { .. } => 25, RuntimeFact::StageInRegion => 26, RuntimeFact::StageInStride { .. } => 27, - RuntimeFact::UniformViewRange { .. } => 28, - RuntimeFact::UniformViewAliasing { .. } => 29, + RuntimeFact::OneRow => 28, + RuntimeFact::RegionViewports => 29, RuntimeFact::TileFunction => 30, RuntimeFact::TileAttachmentFormat { .. } => 31, RuntimeFact::StorageTextureNumericType { .. } => 32, @@ -306,8 +293,6 @@ fn variant(f: &RuntimeFact) -> usize { RuntimeFact::RowLockstep => 86, RuntimeFact::BorderTexels { .. } => 87, RuntimeFact::HeapResidency { .. } => 88, - RuntimeFact::OneRow => 89, - RuntimeFact::RegionViewports => 90, RuntimeFact::CallThreadgroups => 84, RuntimeFact::PartialThreadgroups => 81, RuntimeFact::TexelRows { .. } => 78, @@ -324,7 +309,7 @@ fn variant(f: &RuntimeFact) -> usize { fn mechanism_is_total_over_every_fact_and_profile() { let facts = every_fact(); let covered: std::collections::BTreeSet = facts.iter().map(variant).collect(); - assert_eq!(covered, (0..91).collect(), "every_fact misses a variant"); + assert_eq!(covered, (0..89).collect(), "every_fact misses a variant"); for (stem, _) in super::committed_profiles() { let dev = device(&stem); let p = dev.profile(); @@ -360,7 +345,6 @@ fn mechanism_is_total_over_every_fact_and_profile() { | RuntimeFact::TexelBufferRange { .. } | RuntimeFact::SimdgroupEmulation { .. } | RuntimeFact::PredicationVote - | RuntimeFact::UniformViewAliasing { .. } | RuntimeFact::SparseTexture { sparse_arm: false, tile_map: false, @@ -386,7 +370,6 @@ fn mechanism_is_total_over_every_fact_and_profile() { | RuntimeFact::StorageTextureNumericType { .. } | RuntimeFact::EmulatedSimdgroups | RuntimeFact::RenderTargetArrayLength { .. } - | RuntimeFact::UniformViewRange { .. } | RuntimeFact::SrgbTexture { .. } | RuntimeFact::CrossClassReads { .. } | RuntimeFact::FlatGrid diff --git a/crates/metal2vulkan/src/error/mod.rs b/crates/metal2vulkan/src/error/mod.rs index 89ff6f7db..bfad467ce 100644 --- a/crates/metal2vulkan/src/error/mod.rs +++ b/crates/metal2vulkan/src/error/mod.rs @@ -1350,7 +1350,7 @@ pub enum DynamicLibraryProblem { /// A binder planning or instantiation error. A pipeline's `plan` sees only the pipeline, the /// device, and the `BindShape`, so a planning error is permanent for its `(PipelineKey, /// BindShape)` pair. An instantiation error can also depend on the dispatch or draw and on the -/// bind state's per-draw values (`MissingStageInRegion`, `UniformViewAliased`, the patch-draw +/// bind state's per-draw values (`MissingStageInRegion`, the patch-draw /// errors, a descriptor range or texel buffer beyond its limit, ...), so it is not permanent for /// the pair. `NeedsVariant` names the pipeline a dispatch or draw runs on instead. #[non_exhaustive] @@ -1425,12 +1425,6 @@ pub enum BindError { /// stepping by thread position, or `[[grid_origin]]` or `[[grid_size]]`) and the encoder /// never set one (`setStageInRegion:`): what Metal reads then is not established. MissingStageInRegion, - /// A `device` buffer slot the pipeline reads through a uniform view (Profile F's per-stage - /// storage-buffer fallback, `RuntimeFact::UniformViewAliasing`) is bound where a buffer slot - /// the pipeline writes (`written`) may write: their Metal windows overlap. A uniform view need - /// not observe the dispatch's or draw's own writes, so nothing is bound. Depends on the - /// per-draw Metal addresses, not on the shape. - UniformViewAliased { slot: SlotRef, written: SlotRef }, /// A draw Metal does not make with this pipeline: patches (`patches`) with a pipeline whose /// vertex function is not post-tessellation, or primitives with one whose vertex function is. InvalidDrawKind { patches: bool }, diff --git a/crates/metal2vulkan/src/lower/access/absent.rs b/crates/metal2vulkan/src/lower/access/absent.rs index 891c19b75..e9c1883b6 100644 --- a/crates/metal2vulkan/src/lower/access/absent.rs +++ b/crates/metal2vulkan/src/lower/access/absent.rs @@ -33,7 +33,7 @@ use crate::lower::emit::EmitCx; use crate::lower::select::SelectCx; use crate::memory::leaf::k32; use crate::memory::roots::k64; -use crate::memory::views::{self, View, ViewKind}; +use crate::memory::views::{self, View}; use crate::pipeline::facts::RuntimeFact; use crate::pipeline::sym::{PushField, ResourceKind, ResourceSlot, Stage, SyntheticBinding}; use crate::spirv::builder::{FunctionBuilder, ModuleBuilder}; @@ -177,11 +177,7 @@ pub fn declare( plan: &super::AccessPlan, ) -> BResult> { match plan.status_binding { - Some(_) => Ok(Some(views::declare_at( - mb, - symbol(stage), - ViewKind::Storage, - )?)), + Some(_) => Ok(Some(views::declare_at(mb, symbol(stage))?)), None => Ok(None), } } @@ -239,10 +235,7 @@ pub fn status_word( ) -> BResult { if let Some(view) = cx.decl.families.access.status { let word = k32(fb, w.byte_offset() / 4)?; - return match views::word_ptr(fb, view, word)? { - Some(ptr) => Ok(ptr), - None => Err(cx.fail("an ExecutionStatus view that is not a storage view")), - }; + return views::word_ptr(fb, view, word); } let status = cx.push_field(fb, PushField::ExecutionStatusAddress)?; let address = match w.byte_offset() { diff --git a/crates/metal2vulkan/src/lower/access/atomic.rs b/crates/metal2vulkan/src/lower/access/atomic.rs index deea44e3c..48790812a 100644 --- a/crates/metal2vulkan/src/lower/access/atomic.rs +++ b/crates/metal2vulkan/src/lower/access/atomic.rs @@ -107,7 +107,7 @@ use crate::memory::arena::{Arena, ArenaMem}; use crate::memory::contain::{self, Check}; use crate::memory::leaf::{k32, WordOps}; use crate::memory::provenance::{PrivForm, Repr}; -use crate::memory::views::{self, ViewKind}; +use crate::memory::views; use crate::pipeline::sym::{PushField, Stage}; use crate::spirv::builder::constructs::{ArmEnd, ArmFn, LoopFn, LoopSpec}; use crate::spirv::builder::FunctionBuilder; @@ -120,7 +120,7 @@ use crate::spirv::ir::{ use super::emit::{prepare, Mem, Prepared, ViewMem}; use super::local::{self, LocalAccess, LocalPtr}; -use super::{not_lowered, refuse, static_roots, view_kind, AccessPlan, BufferReach, Target}; +use super::{not_lowered, refuse, static_roots, AccessPlan, BufferReach, Target}; use crate::error::LowerFamily; mod narrow; @@ -683,9 +683,6 @@ pub fn select( .slots .get(t.slot) .ok_or_else(|| cx.invariant("an atomic target names a missing slot"))?; - if view_kind(cx.profile, plan) != ViewKind::Storage { - return Err(cx.invariant("an atomic through a uniform view")); - } let slot = plan.slot; cx.push.insert(PushField::SlotBindOffset(slot)); super::note_variable(cx, slot, fixed, false); @@ -1081,9 +1078,7 @@ fn on_target(fb: &mut FunctionBuilder<'_>, p: Prepared, o: Op) -> BResult