Translator: a buffer slot takes the storage view on every profile; the uniform view goes

A buffer slot took a uniform view only where containment was the device's
(contain::encoding gave Check::None, under robustBufferAccess or robustBufferAccess2): the
uniform arm of the slot's view choice and Profile F's per-stage storage-buffer fallback. The
runtime enables neither feature, so no runtime module took one. The next commit deletes the
robustness choice; memory, lower and spirv are crate-private, so its dead_code would fail that
commit on its own. The uniform view goes first, with everything that only it reached:

- the uniform forms of a view (UniformWords and UniformVec4) and their reads, and Profile F's
  fallback (fallback_view, fallback_rank). Profile F (runtime-floor without device addresses,
  below the runtime's floor) now refuses a stage past maxPerStageDescriptorStorageBuffers as
  DescriptorCount, where before it read its read-only slots through uniform views, under robust
  descriptors only;
- SlotPlan::lane_read and its planner pass, and Uniformity::among_active_lanes, which only that
  pass ran;
- the storage-view variant: LoweringInputs and VariantKey storage_view_slots, the binder's
  storage_view_variant and large_view_candidates;
- RuntimeFact::UniformViewAliasing and UniformViewRange with UniformViewChoice, and the binder's
  aliasing check with its refusal BindError::UniformViewAliased (docs/REFUSALS.md regenerated:
  binder refusals 9 to 8);
- SpecKey::RangeAtBindOffset (only uniform views declared it), BindState::view_base_alignment and
  uniform_views_at_residual, StageTable.at_bind_views and StageTable::class_alignment;
  BoundBuffer::shape, BoundBuffer::same_shape and StageTable::shape lose their
  view_base_alignment parameter;
- BufferRanges.uniform: BufferRanges::length_class and the binder's offset alignment now read
  maxStorageBufferRange and minStorageBufferOffsetAlignment alone. Nothing in the runtime crate
  reads BufferRanges, BindState, BoundBuffer, StageTable or BindShape (git grep: 0 hits); it
  reaches validation's candidate engine only;
- AccessClass::Uniform, DescriptorView (Storage, UniformWords, UniformVec4) and
  BufferForm::uniform_view; BufferForm::Descriptor loses its DescriptorView field.

The loop hoist stays: the argument table's Uniform block (lower::access::table, the spilled
push fields) still feeds it. Its docs no longer name a buffer slot's uniform view.

Removed or changed public items and the types that own them, each with 0 hits in the
consumer's checkout at bd9d6ae85a and at ad28ebd881 (git grep -w -F over *.rs, *.toml, *.md):
DescriptorView, UniformWords, UniformVec4,
UniformViewChoice, UniformViewRange, UniformViewAliasing, UniformViewAliased, RangeAtBindOffset,
storage_view_slots, view_base_alignment, uniform_views_at_residual, at_bind_views,
class_alignment, uniform_view, same_shape, AccessClass, BufferRanges, buffer_ranges, BufferForm,
StageTable, BoundBuffer, BindState, VariantKey, LoweringInputs, RuntimeFact, SpecKey, BindError.
crates/metal2vulkan/tests/api_signatures.tsv and api_surface.rs are blessed in this commit, and
docs/API.md (the uniform-view form, the bind-offset key, BufferRanges) changes with it.

Stored: VariantKey's storage_view_slots, and the codec tags of BufferForm::Descriptor (no
field), SpecKey (RangeAtBindOffset gone), RuntimeFact (two variants gone) and DescriptorView
(gone). The batch's ARTIFACT_FORMAT_VERSION bump (590 to 591), applied last once for the
batch, covers them; no version moves here.

Tests deleted whole, neither a containment proof: engine_storage_view_variant.rs (the
variant's fixed point) and engine_lane_reads.rs (the uniform view's lane choice). Deleted with
the forms they tested: the uniform-view cases of engine_access.rs and engine_binder.rs, the
slots tests of the large-view candidates and the bind-offset range, the variant's cache round
trip, and the active-lanes tests of lower/simd/uniform. The kept containment proof, a constant
buffer shorter than its window, runs on the storage form
(a_constant_buffer_shorter_than_its_window_is_contained_in_shader). Profile F's new refusal has
its test (a_stage_past_the_storage_buffer_limit_without_device_addresses_is_refused).

Golden: at the batch's top only the stated set's 24 texel-buffer rows moved, the 312 cells
commit 2 alone moved before the rebase; no other row moved on either set. The .air.ll half (567 typed-pointer fixtures,
which need metal-as) is unchecked per commit; the batch's golden bless on the M3 covers it.

Verified:
- On unshipped's tip before this rebase (96d953bb0b), the same change: compile job
  m3-max-66120 green (fmt, signatures, refusals, clippy plain, m2v_gpu and m2v_cpu_icd,
  workspace Rustdoc, api-docs). Before that rebase, this commit alone (hash probe job
  m3-max-65979) read 252 rows equal to its base's arm.
- At the batch's top on 96d953bb0b (all four commits, probe job m3-max-66130): the hash probe's
  252 rows equal unshipped's arm at 4861c9863d (m3-max-65976); the golden probe's set without
  buffer robustness (the runtime's state) equals the base arm 96d953bb0b (m3-max-66128), 1855 of
  1855 rows.
- The states-only play at the batch's top (render and compute states made and refused,
  pipelines_created, made_ahead_variants) is the coordinator's, run on the branch; it is not
  evidence here.
- Here: cargo fmt; signatures check; refusal surface regenerated. The compile job follows on the
  branch tip.
This commit is contained in:
Anees Iqbal committed 2026-11-22 00:17:41 -08:00
1 parent 0fe6627d58
commit 5e3477e60a
76 files changed
+664 -3591

No files matched your search

@@ -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`) |
@@ -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 <metal_stdlib>
using namespace metal;
@@ -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<u32, BufferAddress>,
@@ -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
@@ -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
@@ -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
@@ -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!(
@@ -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)),
+4 -21
View File
@@ -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<Bindin
let bound = stage_shape(slot.stage).and_then(|s| s.buffers.get(&slot.index));
buffers.push(plan_buffer((*slot, b, bound), replayed, limits, &bindings)?);
}
mark_disjoint(&mut buffers, &p.dependencies);
let planned = |slot: SlotRef| buffers.iter().find(|b| b.slot == slot);
// The layout stride of each pulled layout (one per Metal buffer index).
let pulled_stride = |layout: u32| {
@@ -1617,7 +1615,6 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<Bindin
}
let mut variant = resources.variant;
variant.psb_slots = psb_variant(&p.dependencies, &buffers, profile);
variant.storage_view_slots = storage_view_variant(&p.dependencies, &buffers, profile);
variant.cross_class = cross_variant(&p.dependencies, &p.interface.slots, shape);
variant.srgb_textures = srgb_variant(profile, &p.dependencies, shape, &variant.cross_class);
variant.ycbcr_in_place = ycbcr_in_place_variant(&p.dependencies, shape);
@@ -1637,20 +1634,6 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<Bindin
variant.psb_slots.insert(slot);
}
}
// A layout the variant newly pulls adds a storage buffer to the vertex stage, whose fallback
// may then view any of its candidates as a uniform buffer: the key keeps every large one a
// storage view now, so the variant's plan states the same key.
if pulled_vertex_buffers
.iter()
.any(|l| !p.vertex_input.variant_pulled.contains(l))
{
variant.storage_view_slots.extend(large_view_candidates(
&p.dependencies,
&buffers,
profile,
Some(Stage::Vertex),
));
}
variant.pulled_vertex_buffers = pulled_vertex_buffers;
variant.amplification_draws = amplification_draws;
// A pipeline compiled for a draw replay's bindings states its variant.
@@ -3154,7 +3137,7 @@ fn instantiate(
};
// The plan put a layout fixed function cannot fetch as bound into its variant,
// whose pipeline pulls it; this plan's pipeline is not that one.
if !fetchable(vb, &t.vertex_strides, offset_alignment(offset, 0), per_bind) {
if !fetchable(vb, &t.vertex_strides, offset_alignment(offset), per_bind) {
return Err(internal(format!(
"a draw of {:?} as the plan's pulled-vertex-buffer variant binds it; \
compile and plan the variant",
@@ -4,7 +4,6 @@
use super::*;
use crate::bind::plan::{PlannedBuffer, ResourceTemplate};
use crate::bind::state::{length_class, StageTable};
use crate::pipeline::interface::DescriptorView;
use std::cell::RefCell;
thread_local! {
@@ -360,16 +359,12 @@ fn fixed_function_fetches_only_what_vulkan_can_bind() {
let first = vertex_buffers()[0];
assert!(fetchable(&first, &rules(None, true), 4, None));
assert!(!fetchable(&first, &rules(None, true), 2, None));
// Classed up to 4, and the view base alignment where one is told apart and divides it.
// Classed up to 4.
let offsets = [0, 1, 2, 3, 4, 6, 8, 12, 64, 192, 1 << 40, (1 << 40) + 2];
assert_eq!(
offsets.map(|o| offset_alignment(o, 0)),
offsets.map(offset_alignment),
[4, 1, 2, 1, 4, 2, 4, 4, 4, 4, 4, 2]
);
assert_eq!(
offsets.map(|o| offset_alignment(o, 64)),
[64, 1, 2, 1, 4, 2, 4, 4, 64, 64, 64, 2]
);
}
/// An attribute's alignment is its component size (the whole word of a packed format) and the
@@ -757,7 +752,7 @@ fn draws_bind_vertex_buffers_at_aligned_offsets_with_their_windows() {
buffers: vec![PlannedBuffer {
slot: vslot(1),
window: Window::Bounded { start: 0, len: 16 },
form: BufferForm::Descriptor(DescriptorView::Storage),
form: BufferForm::Descriptor,
access: AccessSet::READ,
binding: Some((0, 0)),
alignment: 16,
@@ -766,7 +761,6 @@ fn draws_bind_vertex_buffers_at_aligned_offsets_with_their_windows() {
device_address: false,
length_class: length_class(4096),
},
disjoint: false,
}],
stages: Vec::new(),
vertex_buffers: vertex_buffers(),
+21 -108
View File
@@ -12,7 +12,7 @@ use crate::error::{BindError, Feature, Unsupported};
use crate::memory::roots::{
BIND_OFFSET, ENTRY_BYTES, GUEST, HOST, RESIDENT_COUNT, RESIDENT_FIRST, SINK_ROOT, SIZE,
};
use crate::pipeline::interface::{BufferForm, DescriptorView, PushLoc, Window};
use crate::pipeline::interface::{BufferForm, PushLoc, Window};
use crate::pipeline::sym::{PushField, SlotRef};
use crate::vk;
@@ -377,27 +377,10 @@ pub(crate) enum RangeError {
TooLarge { needed: u64 },
}
/// Whether [`descriptor_range`] starts the range of a slot with `window` at `bind_offset` for the
/// descriptor base alignment `alignment` (`A`, at least 4 used), so its residual is 0, wherever
/// the bind offset lies before the padded end of the allocation: the bind offset is a multiple of
/// `A`, and the window is `Whole` or starts in `[0, A)` (`align_down(bind_offset + start, A)` is
/// then the bind offset, and a range from an aligned bind offset inside the allocation is at least
/// 16 bytes, so it is never widened down). At or past the end, where every byte the slot reaches
/// lies outside the bound buffer, the range is widened down into the allocation and the residual
/// is not 0. The plan specializes `SpecKey::RangeAtBindOffset` on it.
pub(crate) fn starts_at_bind(bind_offset: u64, window: Window, alignment: u64) -> 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<Option<(i128, i128)>, 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<DescriptorRange>,
extents: &mut Vec<BufferExtent>,
) -> Result<BoundBuffers, BindError> {
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,
@@ -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}"
);
+4 -11
View File
@@ -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,
+3 -6
View File
@@ -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<Bindi
&bindings,
)?);
}
mark_disjoint(&mut buffers, &p.dependencies);
let planned = |slot: SlotRef| buffers.iter().find(|b| b.slot == slot);
// Push placement.
@@ -874,7 +872,6 @@ fn plan(p: &ComputePipeline, device: &Device, shape: &BindShape) -> Result<Bindi
}
let mut variant = resources.variant;
variant.psb_slots = psb_variant(&p.dependencies, &buffers, device.profile());
variant.storage_view_slots = storage_view_variant(&p.dependencies, &buffers, device.profile());
variant.cross_class = cross_variant(&p.dependencies, &p.interface.slots, shape);
variant.srgb_textures = srgb_variant(
device.profile(),
+10 -135
View File
@@ -14,7 +14,7 @@ use crate::device::{mechanism, DeviceProfile};
use crate::error::{BindError, Capability, Feature, Unsupported};
use crate::metal;
use crate::pipeline::artifact::RuntimeDependency;
use crate::pipeline::facts::{Mechanism, RuntimeFact, UniformViewChoice};
use crate::pipeline::facts::{Mechanism, RuntimeFact};
use crate::pipeline::interface::SlotInterface;
use crate::pipeline::interface::{AccessSet, BufferForm, BufferSlot, Window};
use crate::pipeline::layout::{BindingSource, PipelineLayout};
@@ -107,13 +107,13 @@ impl BoundKind {
}
/// The plan of buffer slot `slot` with interface `b` and what the shape binds there: its descriptor
/// binding (descriptor forms), the view's descriptor base alignment and range limit, and a
/// binding (the descriptor form), the storage view's descriptor base alignment and range limit, and a
/// `MissingDeviceAddress` refusal for a device-address slot bound without an address: a buffer
/// without one, or inline bytes, but in a pipeline compiled for a replay's bindings (`replayed`,
/// `RuntimeFact::ReplayBindings`), which reads every buffer through the slot table the replay's
/// preprocess writes, inline bytes the encoder bound at the consumer's upload of them
/// (`DrawReplayPreprocess::inherited_bytes`). The base alignment is
/// `max(min*BufferOffsetAlignment, 16)` (`views::base_alignment`): a descriptor byte is then
/// `max(minStorageBufferOffsetAlignment, 16)` (`views::base_alignment`): a descriptor byte is then
/// congruent to its Metal address modulo 16, which a `uvec4` view of the slot relies on.
pub(crate) fn plan_buffer(
(slot, b, shape): (SlotRef, &BufferSlot, Option<&BufferShape>),
@@ -122,10 +122,11 @@ pub(crate) fn plan_buffer(
bindings: &BTreeMap<BindingSource, (u32, u32)>,
) -> Result<PlannedBuffer, BindError> {
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<SlotRef> {
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<Stage>,
) -> std::collections::BTreeSet<SlotRef> {
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 {
+52 -230
View File
@@ -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<BindState> = (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"
);
}
}
}
+46 -125
View File
@@ -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<u32, BoundAccelerationStructure>,
/// 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,
},
+7 -10
View File
@@ -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,
+1 -4
View File
@@ -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());
}
-14
View File
@@ -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<SlotRef>,
/// 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()
-70
View File
@@ -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).
@@ -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.
@@ -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> {
},
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<usize> = 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
+1 -7
View File
@@ -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 },
+3 -10
View File
@@ -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<Option<View>> {
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<crate::spirv::ids::Value> {
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() {
@@ -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<Option
let two = k32(fb, 2)?;
let word = fb.binary(BinOp::ShiftRightLogical, p.off, two)?;
let ptr = match (p.mem, o.typed) {
(Mem::View(ViewMem(view, ..)), None) => {
views::word_ptr(fb, view, word)?.ok_or_else(dangling)?
}
(Mem::View(ViewMem(view, ..)), None) => views::word_ptr(fb, view, word)?,
(Mem::Psb(m), typed) => {
let pointee = match typed {
Some(t) => t,
+1 -5
View File
@@ -339,11 +339,7 @@ pub fn load_decl(
if !checked {
return leaf::load(fb, &mut mem, leaf, off);
}
let Some(size) = views::storage_bytes(fb, view)? else {
return Err(crate::spirv::error::BuildError::Dangling(
crate::spirv::error::Dangling::Global(view.global),
));
};
let size = views::storage_bytes(fb, view)?;
contained(fb, &mut mem, leaf, off, size)
}
BlobDecl::Module(mut words) => {
@@ -632,9 +632,6 @@ fn static_access(
.slots
.get(t.slot)
.ok_or_else(|| cx.invariant("a target names a missing slot"))?;
if write && super::view_kind(cx.profile, plan) != super::ViewKind::Storage {
return Err(cx.invariant("a pointer store through a uniform view"));
}
let slot = plan.slot;
cx.push.insert(PushField::SlotBindOffset(slot));
super::note_variable(cx, slot, fixed, !write);
+13 -49
View File
@@ -6,7 +6,7 @@ use crate::air::ir::InstId;
use crate::lower::emit::EmitCx;
use crate::memory::contain::{self, Check};
use crate::memory::leaf::{self, k32, u32_op, Leaf, Units, WordMem, WordOps};
use crate::memory::views::{self, UnitViews, View, ViewKind};
use crate::memory::views::{self, UnitViews, View};
use crate::pipeline::sym::PushField;
use crate::spirv::builder::constructs::{ArmEnd, ArmFn};
use crate::spirv::builder::FunctionBuilder;
@@ -22,8 +22,7 @@ use super::{
};
/// The word memory of one descriptor view, loaded and stored with memory operands (a coherence,
/// and `Volatile`; a uniform view's read-only words stay plain: no agent writes them while the
/// dispatch runs). Sub-word stores are two relaxed device-scope word atomics, except where the
/// and `Volatile`). Sub-word stores are two relaxed device-scope word atomics, except where the
/// slot's narrow views hold the leaf's units; a 16-byte (8-byte) leaf at an offset proven a
/// multiple of its size is one `uvec4` (`uvec2`) where the slot has that view.
#[derive(Clone, Copy, Debug)]
@@ -55,11 +54,7 @@ impl WordMem for ViewMem {
index: SValue,
) -> BResult<SValue> {
let view = self.vec(lanes)?;
// A uniform view's read-only vectors are read plainly, as its words are.
let access = match view.class {
crate::spirv::ir::StorageClass::Uniform => MemAccess::default(),
_ => self.1.access(fb, MemAccess::default(), false)?,
};
let access = self.1.access(fb, MemAccess::default(), false)?;
views::read_vec(fb, view, index, access)
}
@@ -103,16 +98,16 @@ impl WordMem for ViewMem {
}
fn read(&mut self, fb: &mut FunctionBuilder<'_>, word: SValue) -> BResult<SValue> {
if self.1 == WordOps::default() || self.0.kind != ViewKind::Storage {
if self.1 == WordOps::default() {
return views::read_word(fb, self.0, word);
}
let p = storage_ptr(fb, self.0, word)?;
let p = views::word_ptr(fb, self.0, word)?;
let access = self.1.access(fb, MemAccess::default(), false)?;
fb.load(p, access)
}
fn write(&mut self, fb: &mut FunctionBuilder<'_>, word: SValue, value: SValue) -> BResult<()> {
let p = storage_ptr(fb, self.0, word)?;
let p = views::word_ptr(fb, self.0, word)?;
let access = self.1.access(fb, MemAccess::default(), true)?;
fb.store(p, value, access)
}
@@ -124,7 +119,7 @@ impl WordMem for ViewMem {
mask: SValue,
bits: SValue,
) -> BResult<()> {
let p = storage_ptr(fb, self.0, word)?;
let p = views::word_ptr(fb, self.0, word)?;
let keep = fb.unary(UnOp::Not, mask)?;
let clear = fb.binary(BinOp::BitwiseOr, keep, bits)?;
fb.atomic(AtomicOp::And, p, Scope::Device, Semantics::RELAXED, clear)?;
@@ -133,17 +128,6 @@ impl WordMem for ViewMem {
}
}
/// A word pointer of a storage view. Stores through a uniform view are refused by selection, so a
/// missing pointer is an internal invariant failure.
fn storage_ptr(fb: &mut FunctionBuilder<'_>, view: View, word: SValue) -> BResult<SValue> {
match views::word_ptr(fb, view, word)? {
Some(p) => Ok(p),
None => Err(crate::spirv::error::BuildError::Dangling(
crate::spirv::error::Dangling::Global(view.global),
)),
}
}
/// The word memory of one target: a descriptor view or a device address.
#[derive(Clone, Copy, Debug)]
pub(super) enum Mem {
@@ -377,32 +361,12 @@ pub(super) fn prepare(
return Err(cx.fail("an access names an undeclared slot view"));
};
let residual = cx.push_field(fb, PushField::SlotBindOffset(choice.slot))?;
let shifted = u32_op(fb, BinOp::IAdd, residual, m)?;
// Where the binder starts a view's range at the bind offset (`RangeAtBindOffset`: a uniform
// view's, or a storage view's where the plan declares it), the residual is 0: the offset alone,
// a constant for a constant member, which a driver can push, and no push word read.
let off = match cx
.decl
.families
.access
.at_bind
.get(t.slot)
.copied()
.flatten()
{
Some(at_bind) => fb.select(at_bind, m, shifted)?,
None => shifted,
};
let inb = match (t.check, view.kind) {
(Check::None, _) => None,
(Check::InShader, ViewKind::Storage) => match views::storage_bytes(fb, view)? {
Some(size) => Some(contain::in_bounds(fb, off, size, u64::from(n))?),
None => return Err(cx.fail("a storage view without a size")),
},
(Check::InShader, ViewKind::UniformWords { .. } | ViewKind::UniformVec4 { .. }) => {
// Selection gives a uniform view only to an encoding without checks: the range bound
// behind it may be shorter than its declared size.
return Err(cx.fail("an in-shader check of a uniform view"));
let off = u32_op(fb, BinOp::IAdd, residual, m)?;
let inb = match t.check {
Check::None => None,
Check::InShader => {
let size = views::storage_bytes(fb, view)?;
Some(contain::in_bounds(fb, off, size, u64::from(n))?)
}
};
let (off, guard_store) = match inb {
@@ -249,7 +249,7 @@ pub fn declare(mb: &mut ModuleBuilder, plan: &Plan) -> BResult<Option<FunctionTa
words: DeclaredWords::Addressed(directory),
}));
}
let view = views::declare_at(mb, snapshot_symbol(plan.stage), views::ViewKind::Storage)?;
let view = views::declare_at(mb, snapshot_symbol(plan.stage))?;
Ok(Some(FunctionTables {
lookup,
words: DeclaredWords::Snapshot(view),
+46 -336
View File
@@ -17,19 +17,10 @@
//! profile's encoding (`memory::contain`): none with robust descriptors, else the normative check
//! against the storage view's bound size (`OpArrayLength`, the padded range).
//!
//! **Slots** ([`finish_slots`]). An accessed slot is a descriptor view: with robust descriptors (or
//! containment off), a uniform view for a read-only `constant` slot whose `Bounded` window's
//! descriptor range fits `maxUniformBufferRange` (`u32[]` with `uniformBufferStandardLayout`, else
//! `uvec4[]`); a storage view otherwise. The in-shader encoding never uses a uniform view: its
//! declared size is the window's range, while the binder may bind a shorter range (the binder
//! clamps it to the allocation), and a shader cannot query a uniform range. A storage slot whose
//! range is not provably within `maxStorageBufferRange` declares `RuntimeFact::BufferRangeLimit`.
//! On Profile F an exceeded per-stage storage-buffer limit views read-only slots as uniform buffers
//! instead: sized to the window where it bounds the range, else to `maxUniformBufferRange`, with
//! the range (`UniformViewRange`) and, for a `device` slot, the absence of aliasing writes
//! (`UniformViewAliasing`) left to the binder. On Profile A a `BufferRangeLimit` variant
//! (`LowerInputs.psb_slots`) and the per-stage descriptor-limit fallback move storage slots to
//! their device addresses (`BufferForm::Psb`, the PSB leaf of `psb`, reached through the root
//! **Slots** ([`finish_slots`]). An accessed slot is a storage view. A storage slot whose range is
//! not provably within `maxStorageBufferRange` declares `RuntimeFact::BufferRangeLimit`. On
//! Profile A a `BufferRangeLimit` variant (`LowerInputs.psb_slots`) and the per-stage
//! descriptor-limit fallback move storage slots to their device addresses (`BufferForm::Psb`, the PSB leaf of `psb`, reached through the root
//! table), which declare `RuntimeFact::DeviceAddresses`. The pulled vertex fetch's source buffers
//! are slots under the same rules ([`pulled`]): one sharing a read-only buffer argument's Metal
//! index is that argument's slot, widened to a `Whole` storage slot; any other is a read-only
@@ -85,8 +76,8 @@
//! **Volatile accesses**. A volatile load or store is selected as the same instruction without
//! `volatile` and then takes its volatile form (`volatile_form`): every word load and store it
//! composes carries SPIR-V's `Volatile` (performed, once, never combined), in the function's memory
//! model, whose coherence it keeps. Loads of read-only memories (uniform views, the constant blob,
//! typed constant objects) stay plain, and a handle-array or buffer-table element load, which reads
//! model, whose coherence it keeps. Loads of read-only memories (the constant blob, typed constant
//! objects) stay plain, and a handle-array or buffer-table element load, which reads
//! no memory at the access, is refused volatile.
//!
//! Not lowered yet (`Unsupported{Lowering(Access), NotImplemented}`): coherent accesses of
@@ -136,11 +127,9 @@ use crate::memory::contain::{self, Check};
use crate::memory::leaf::{self, Coherence, Leaf, Units};
use crate::memory::plan::SlotPlan;
use crate::memory::provenance::{Repr, Root};
use crate::memory::views::{self, View, ViewKind};
use crate::pipeline::facts::{RuntimeFact, UniformViewChoice};
use crate::pipeline::interface::{
AccessSet, BufferForm, DescriptorView, PushLoc, PushPlacement, Window,
};
use crate::memory::views::{self, View};
use crate::pipeline::facts::RuntimeFact;
use crate::pipeline::interface::{AccessSet, BufferForm, PushLoc, PushPlacement, Window};
use crate::pipeline::sym::{PushField, SlotRef};
use crate::spirv::builder::{FunctionBuilder, ModuleBuilder};
use crate::spirv::error::BResult;
@@ -515,7 +504,7 @@ impl AccessPlan {
pub fn source_reach(&self, slot: SlotRef) -> BufferReach {
match self.source_lowering(slot) {
Some(SlotLowering::Psb { .. }) => BufferReach::ADDRESSES,
Some(SlotLowering::View(_)) => BufferReach::VIEWS,
Some(SlotLowering::View) => BufferReach::VIEWS,
None => BufferReach::NONE,
}
}
@@ -689,8 +678,8 @@ pub fn spirv_type(mb: &mut ModuleBuilder, ty: &DemoteTy) -> BResult<Option<TypeI
/// How an accessed slot is reached.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SlotLowering {
/// Through its descriptor view.
View(ViewKind),
/// Through its storage view.
View,
/// Through its device address (`BufferForm::Psb`). `start` is the start of the slot's window
/// relative to the bind offset (0 for `Window::Whole`): the `u32` pointer offset is recovered
/// as the unique 64-bit displacement in `[start, start + 2³²)` congruent to it (`psb`).
@@ -764,8 +753,7 @@ pub struct AccessPlan {
/// and writes the field.
pub observed: BTreeSet<usize>,
/// Memory-plan slots a volatile, coherent, or atomic access reaches: what they read may change
/// while the dispatch or draw runs, and an atomic needs a storage view's word pointer, so the
/// per-stage storage-buffer fallback never views them as uniform buffers.
/// while the dispatch or draw runs.
pub ordered: BTreeSet<usize>,
/// Memory-plan slots whose memory nothing in the module writes ([`unwritten_slots`]), read
/// through a storage view or, under the identity domains, their device address: their views
@@ -905,24 +893,6 @@ pub struct Declared {
/// The stage's view of the command buffer's `ExecutionStatus` buffer, where it binds the
/// buffer ([`absent::declare`]).
pub status: Option<View>,
/// The `RangeAtBindOffset` specialization of each slot read through a uniform view, by
/// memory-plan slot index: where it holds, an access reads the view at the Metal offset alone
/// ([`range_at_bind_offset`]).
pub at_bind: Vec<Option<SValue>>,
}
/// Slot `slot`'s `RangeAtBindOffset` specialization: a `bool`, false by default, fixed at pipeline
/// creation, true where the binder starts the slot's descriptor range at its bind offset, so its
/// `SlotBindOffset` residual is 0 and an access reads the Metal offset alone: a constant for a
/// constant member, which a driver can push ahead of the shader.
fn range_at_bind_offset(mb: &mut ModuleBuilder, slot: SlotRef) -> BResult<SValue> {
let b = mb.ty(SType::Bool)?;
let c = mb.spec(
crate::pipeline::sym::SpecKey::RangeAtBindOffset(slot),
b,
ConstBits(0),
)?;
mb.const_value(c)
}
/// The module's routines the access family's strategies call, each charged once to the census: the
@@ -1014,100 +984,6 @@ pub fn param_value(
fb.module().const_value(c)
}
/// The view kind of a slot on profile `p`: a uniform view for a read-only `constant` slot with a
/// `Bounded` window whose descriptor range fits `maxUniformBufferRange`, when the profile's
/// containment encoding emits no check and the slot has no lane read; a storage view otherwise.
///
/// Under the in-shader encoding a uniform view could not be contained: the bound range may be
/// shorter than the view's declared size (the binder clamps it to the padded allocation), a uniform
/// block has no `OpArrayLength`, and the proven window bounds Metal-defined accesses only. A
/// storage view's check reads the size actually bound.
///
/// A lane read ([`SlotPlan::lane_read`]) is a read whose address may differ between the lanes
/// that run it together. A uniform buffer may serve one address at a time, so on every device the
/// slot keeps its storage view, which reads the same bytes. Measured with a bare Vulkan program
/// (256 workgroups of 64 invocations, each adding 64 or 1024 `uvec4` reads of a window of 1 to
/// 32 KiB, each invocation reading its own word or walking the window): the storage buffer took
/// 0.011 to 0.18 of the uniform buffer's time on NVIDIA's driver (RTX 3090, RTX 2080, RTX 5080
/// Laptop GPU) and 0.96 to 1.00 of it on RADV (Radeon 780M, RX 7900 XTX). The choice is the
/// slot's, so its reads at a uniform address take the storage view too: measured at 0.96 to 1.68
/// times the uniform buffer's time (every lane reading one word of a 1 to 32 KiB window), and a
/// storage view's loads are not moved out of their loops as a uniform view's are
/// (`spirv::hoist`). Every stage takes the rule; compute was measured, the graphics stages are
/// expected to read alike, not measured.
pub fn view_kind(p: &DeviceProfile, s: &SlotPlan) -> ViewKind {
let limits = &p.fields().limits;
let uniform = match s.window {
Some(window)
if s.space == AddrSpace::Constant
&& !s.access.write
&& !s.atomic
&& !s.lane_read
&& contain::encoding(p) == Check::None =>
{
uniform_bytes(window, limits)
}
_ => None,
};
match uniform {
Some(bytes) => uniform_view(p, bytes),
None => ViewKind::Storage,
}
}
/// The uniform view of `bytes` bytes (a multiple of 16) on `p`: `u32[]` with
/// `uniformBufferStandardLayout`, `uvec4[]` without.
fn uniform_view(p: &DeviceProfile, bytes: u32) -> ViewKind {
if p.fields().descriptors.uniform_buffer_standard_layout {
ViewKind::UniformWords { words: bytes / 4 }
} else {
ViewKind::UniformVec4 { vecs: bytes / 16 }
}
}
/// Whether a uniform view's descriptor range is provably within `maxUniformBufferRange`: a
/// `Bounded` window's range is at most `uniform_range(len, A)`, with `A` the descriptor base
/// alignment `max(minUniformBufferOffsetAlignment, 16)`.
fn uniform_range_fits(window: Window, limits: &Limits) -> bool {
uniform_bytes(window, limits).is_some()
}
/// The uniform range of a `Bounded` window that provably fits `maxUniformBufferRange`.
fn uniform_bytes(window: Window, limits: &Limits) -> Option<u32> {
match window {
Window::Bounded { len, .. } => {
let align = views::base_alignment(limits.min_uniform_buffer_offset_alignment);
views::uniform_range(len, align)
.filter(|r| *r <= u64::from(limits.max_uniform_buffer_range))
.and_then(|r| u32::try_from(r).ok())
}
_ => None,
}
}
/// The uniform view the per-stage storage-buffer fallback gives a read-only slot with `window`:
/// sized to the window's range where that provably fits `maxUniformBufferRange`, else the largest
/// whole number of 16-byte vectors within it, which covers every range instantiation accepts
/// (`BindError::DescriptorRangeExceeded` above the limit).
fn fallback_view(p: &DeviceProfile, window: Window) -> ViewKind {
let limits = &p.fields().limits;
let bytes = uniform_bytes(window, limits).unwrap_or(limits.max_uniform_buffer_range & !15);
uniform_view(p, bytes)
}
/// The fallback's order among read-only storage slots, lowest first: a window whose uniform range
/// provably fits, then a `constant` slot, then a `device` slot, which also needs instantiation's
/// alias check. Within a rank the highest Metal index moves first, as the Profile A fallback does.
fn fallback_rank(plan: &SlotPlan, window: Window, limits: &Limits) -> u8 {
if uniform_range_fits(window, limits) {
0
} else if plan.space == AddrSpace::Constant {
1
} else {
2
}
}
/// Whether a storage slot's descriptor range is provably within `maxStorageBufferRange`: a
/// `Bounded` window's range is at most `round_up(len + align - 1, 16)`, with `align` the descriptor
/// base alignment `max(minStorageBufferOffsetAlignment, 16)`.
@@ -1115,48 +991,33 @@ fn storage_range_fits(window: Window, limits: &Limits) -> bool {
match window {
Window::Bounded { len, .. } => {
let align = views::base_alignment(limits.min_storage_buffer_offset_alignment);
views::uniform_range(len, align)
views::descriptor_range(len, align)
.is_some_and(|r| r <= u64::from(limits.max_storage_buffer_range))
}
_ => false,
}
}
fn descriptor_view(kind: ViewKind) -> DescriptorView {
match kind {
ViewKind::Storage => DescriptorView::Storage,
ViewKind::UniformWords { .. } => DescriptorView::UniformWords,
ViewKind::UniformVec4 { .. } => DescriptorView::UniformVec4,
}
}
/// Choose the form of every accessed slot and of every pulled vertex source buffer, and add their
/// descriptors to `cx.descriptors`. Returns the form of each accessed slot, by memory-plan slot
/// index (`None` for slots the function does not access).
///
/// A slot is a descriptor view unless a `BufferRangeLimit` variant (`LowerInputs.psb_slots`)
/// A slot is a storage view unless a `BufferRangeLimit` variant (`LowerInputs.psb_slots`)
/// moves it to its device address, or, on Profile A, the per-stage descriptor limits are exceeded:
/// then the highest-index storage slots move to device addresses, one at a time, until the
/// storage-buffer and resource counts fit (a deterministic per-function choice). Every
/// device-address slot declares `DeviceAddresses` and reads the root table
/// (`PushField::RootTableAddress`) instead of its bind residual.
///
/// On Profile F with robust descriptors (or containment off), an exceeded per-stage
/// storage-buffer limit moves read-only storage slots to uniform views instead, one at a time in
/// `fallback_rank` order, while a uniform buffer is left. Every candidate whose window does not
/// bound its range declares `UniformViewRange` whether or not the fallback ran (so a plan can ask
/// for the variant that keeps them all storage views), each slot the compile keeps a storage view
/// declares it `Kept`, and a viewed `device` slot declares `UniformViewAliasing`.
///
/// A pulled source buffer ([`pulled`]) shares the accessed slot of its Metal index, widened to a
/// `Whole` storage slot that the fetch reads too (a window outside the first 2³² bytes above the
/// bind offset is refused), or is a read-only `Whole` storage slot of its own; either takes part
/// in the rules above like any storage slot.
///
/// Each step of either fallback moves one storage view, so the descriptors and push fields of the
/// Each step of the fallback moves one storage view, so the descriptors and push fields of the
/// slots' forms are kept in a census the step updates, and the order of the slots it moves is
/// sorted once: the fallbacks take one pass over the slots, metered, where they recounted every
/// slot per slot moved before. The working tables are charged while they run.
/// sorted once: the fallback takes one pass over the slots, metered, where it recounted every slot
/// per slot moved before. The working tables are charged while they run.
pub fn finish_slots(
cx: &mut SelectCx<'_>,
m: &mut Meter,
@@ -1168,20 +1029,17 @@ pub fn finish_slots(
result
}
/// The ledger bytes `place_slots` works in per memory-plan slot: its form and window, whether
/// the fallback viewed it, and its places in the two fallbacks' orders.
/// The ledger bytes `place_slots` works in per memory-plan slot: its form and window, and its
/// place in the fallback's order.
const SLOT_WORK_BYTES: usize = std::mem::size_of::<Option<SlotLowering>>()
+ std::mem::size_of::<Option<Window>>()
+ 1
+ std::mem::size_of::<(usize, u8, u32)>()
+ std::mem::size_of::<(u32, Moved)>();
/// The descriptors and push fields of the slots' forms while [`finish_slots`] moves them: the
/// storage and uniform buffer views, and the push fields with each
/// device-address slot's `SlotBindOffset` replaced by the root table. A move updates it in place.
/// storage views, and the push fields with each device-address slot's `SlotBindOffset` replaced by
/// the root table. A move updates it in place.
struct Census {
storage: u32,
uniform: u32,
fields: BTreeSet<PushField>,
/// Under the identity domains a device-address slot reads its own address
/// ([`address_field`]), not the root table.
@@ -1201,7 +1059,6 @@ impl Census {
) -> Result<Census, Error> {
let mut c = Census {
storage: 0,
uniform: 0,
fields: push.clone(),
identity,
push_base,
@@ -1210,8 +1067,7 @@ impl Census {
for (slot, l) in forms {
m.tick(1)?;
match l {
SlotLowering::View(ViewKind::Storage) => c.storage = c.storage.saturating_add(1),
SlotLowering::View(_) => c.uniform = c.uniform.saturating_add(1),
SlotLowering::View => c.storage = c.storage.saturating_add(1),
SlotLowering::Psb { .. } => {
c.fields.remove(&PushField::SlotBindOffset(slot));
match identity {
@@ -1237,24 +1093,12 @@ impl Census {
// address, no descriptor.
uniform_buffers: u32::from(
!self.identity && table::spills(stage, self.push_base, &self.fields),
)
.saturating_add(self.uniform),
),
storage_buffers: self.storage,
..DescriptorCounts::default()
}
}
/// A storage view became a view of `kind`.
fn viewed(&mut self, kind: ViewKind) {
self.storage = self.storage.saturating_sub(1);
match kind {
ViewKind::Storage => self.storage = self.storage.saturating_add(1),
ViewKind::UniformWords { .. } | ViewKind::UniformVec4 { .. } => {
self.uniform = self.uniform.saturating_add(1)
}
}
}
/// A storage view of `slot` became its device address.
fn addressed(&mut self, slot: SlotRef) {
self.storage = self.storage.saturating_sub(1);
@@ -1379,24 +1223,16 @@ fn place_slots(cx: &mut SelectCx<'_>, m: &mut Meter) -> Result<Vec<Option<SlotCh
lowering.push(Some(psb_lowering(window)?));
continue;
}
// The fetch's unbounded read needs a storage view.
let kind = if shared {
ViewKind::Storage
} else {
view_kind(p, plan)
};
let mut l = SlotLowering::View(kind);
if kind == ViewKind::Storage {
if !storage_range_fits(window, limits) {
cx.facts
.insert(RuntimeFact::BufferRangeLimit { slot: plan.slot });
}
if cx.inputs.psb_slots.contains(&plan.slot) {
if !addressed {
return Err(range_variant());
}
l = psb_lowering(window)?;
let mut l = SlotLowering::View;
if !storage_range_fits(window, limits) {
cx.facts
.insert(RuntimeFact::BufferRangeLimit { slot: plan.slot });
}
if cx.inputs.psb_slots.contains(&plan.slot) {
if !addressed {
return Err(range_variant());
}
l = psb_lowering(window)?;
}
lowering.push(Some(l));
}
@@ -1420,7 +1256,7 @@ fn place_slots(cx: &mut SelectCx<'_>, m: &mut Meter) -> Result<Vec<Option<SlotCh
}
psb_lowering(Window::Whole)?
} else {
SlotLowering::View(ViewKind::Storage)
SlotLowering::View
};
own.push((s, l));
}
@@ -1443,115 +1279,12 @@ fn place_slots(cx: &mut SelectCx<'_>, m: &mut Meter) -> Result<Vec<Option<SlotCh
forms,
m,
)?;
// Profile F's per-stage storage-buffer fallback: with robust descriptors (or containment off),
// while the storage-buffer count exceeds its limit and a uniform buffer is left, the first
// read-only storage slot in `fallback_rank` order becomes a uniform view. Slots the variant
// keeps (`LowerInputs::storage_view_slots`), a pulled fetch's source, and slots a volatile,
// coherent, or atomic access reaches stay storage views.
let inputs = cx.inputs;
let fallback = !addressed && contain::encoding(p) == Check::None;
let candidates: Vec<(usize, u8)> = if fallback {
memory
.slots
.iter()
.enumerate()
.filter_map(|(i, plan)| {
let window = windows.get(i).copied().flatten()?;
let storage = lowering.get(i).copied().flatten()
== Some(SlotLowering::View(ViewKind::Storage));
let read_only = !plan.access.write && !plan.atomic;
let eligible = storage
&& read_only
&& !sources.contains(&plan.slot)
&& !cx.families.access.ordered.contains(&i);
eligible.then(|| (i, fallback_rank(plan, window, limits)))
})
.collect()
} else {
Vec::new()
};
// The order the fallback views the candidates in: by rank, the highest Metal index first. The
// sort is stable, so equal keys keep memory-plan order, the first of which the fallback
// takes, as the search for the least key per step once did.
let mut order: Vec<(usize, u8, u32)> = Vec::new();
for &(i, rank) in &candidates {
m.tick(1)?;
if let Some(plan) = memory.slots.get(i) {
if !inputs.storage_view_slots.contains(&plan.slot) {
order.push((i, rank, plan.slot.index));
}
}
}
order.sort_by_key(|&(_, rank, index)| (rank, std::cmp::Reverse(index)));
let mut viewed = vec![false; memory.slots.len()];
for (i, _, _) in order {
m.tick(1)?;
let total = cx.descriptors.plus(&census.counts(stage));
if total.storage_buffers <= limits.max_per_stage_descriptor_storage_buffers
|| total.uniform_buffers >= limits.max_per_stage_descriptor_uniform_buffers
{
break;
}
let Some(window) = windows.get(i).copied().flatten() else {
break;
};
let kind = fallback_view(p, window);
if let Some(l) = lowering.get_mut(i) {
*l = Some(SlotLowering::View(kind));
census.viewed(kind);
}
if let Some(v) = viewed.get_mut(i) {
*v = true;
}
}
// The fallback's facts, on every compile where it can run: each candidate whose window does
// not bound its uniform range states what this compile made of it (`Viewed`, or `Spare`
// whether or not the fallback ran), so a plan can name every slot a variant must keep a
// storage view, a variant that pulls a vertex layout included (it adds a storage buffer); a
// viewed `device` slot needs the alias check. Every slot the compile keeps states `Kept`,
// candidate or not, so the plan of the variant restates its key.
for &(i, _) in &candidates {
let (Some(plan), Some(window)) = (memory.slots.get(i), windows.get(i).copied().flatten())
else {
continue;
};
let slot = plan.slot;
if inputs.storage_view_slots.contains(&slot) {
continue;
}
let is_viewed = viewed.get(i).copied().unwrap_or(false);
if is_viewed {
// The slot is no storage view any more. A slot nothing reads (only compared) cannot
// observe a write, so it needs no alias check.
cx.facts.remove(&RuntimeFact::BufferRangeLimit { slot });
if plan.space != AddrSpace::Constant && plan.access.read {
cx.facts.insert(RuntimeFact::UniformViewAliasing { slot });
}
}
if !uniform_range_fits(window, limits) {
let choice = if is_viewed {
UniformViewChoice::Viewed
} else {
UniformViewChoice::Spare
};
cx.facts
.insert(RuntimeFact::UniformViewRange { slot, choice });
}
}
for plan in &memory.slots {
if inputs.storage_view_slots.contains(&plan.slot) {
cx.facts.insert(RuntimeFact::UniformViewRange {
slot: plan.slot,
choice: UniformViewChoice::Kept,
});
}
}
if addressed {
// The storage views the step may move, the highest Metal index first: the accessed slots
// (by their chosen windows) in memory-plan order, then the source buffers of their own.
// A stable sort read from its end takes the last of equal indices, as the search for the
// greatest index per step once did.
let storage = SlotLowering::View(ViewKind::Storage);
let storage = SlotLowering::View;
let mut order: Vec<(u32, Moved)> = Vec::new();
for (i, (plan, (l, w))) in memory
.slots
@@ -1626,7 +1359,7 @@ fn place_slots(cx: &mut SelectCx<'_>, m: &mut Meter) -> Result<Vec<Option<SlotCh
continue;
};
let form = match l {
SlotLowering::View(kind) => BufferForm::Descriptor(descriptor_view(*kind)),
SlotLowering::View => BufferForm::Descriptor,
SlotLowering::Psb { .. } => {
addressed_slot(cx, plan.slot);
if let Some(align) = address_alignment(cx, plan) {
@@ -1765,7 +1498,7 @@ fn unwritten_slots(
.filter(|&(i, (plan, l))| {
let unwritten = !plan.access.write && !plan.wide.write && unaliased(plan.param);
let read_only = match l {
Some(SlotLowering::View(ViewKind::Storage)) => unwritten,
Some(SlotLowering::View) => unwritten,
Some(SlotLowering::Psb { .. }) if identity => {
unwritten || plan.space == AddrSpace::Constant
}
@@ -2043,19 +1776,13 @@ pub fn declare(
for (i, s) in plan.slots.iter().enumerate() {
let lowering = plan.families.access.slots.get(i).copied().flatten();
let view = match (s, lowering) {
(Some(c), Some(SlotLowering::View(kind))) => Some(views::declare(mb, c.slot, kind)?),
(Some(c), Some(SlotLowering::View)) => Some(views::declare(mb, c.slot)?),
_ => None,
};
if let (Some(c), Some(_), true) = (s, view, plan.families.access.unwritten.contains(&i)) {
mb.unwritten_buffer(views::binding_symbol(c.slot));
}
d.views.push(view);
d.at_bind.push(match (s, view.map(|v| v.kind)) {
(Some(c), Some(ViewKind::UniformWords { .. } | ViewKind::UniformVec4 { .. })) => {
Some(range_at_bind_offset(mb, c.slot)?)
}
_ => None,
});
let units = plan
.families
.access
@@ -2064,7 +1791,7 @@ pub fn declare(
.copied()
.unwrap_or(Units::NONE);
d.units.push(match (s, view) {
(Some(c), Some(view)) => views::UnitViews::declare(mb, c.slot, view, units)?,
(Some(c), Some(_)) => views::UnitViews::declare(mb, c.slot, units)?,
_ => views::UnitViews::NONE,
});
}
@@ -2287,8 +2014,8 @@ fn blob_roots(
Ok((targets, null, blob_check))
}
/// Give each of `targets` the profile's containment check and read its slot's `SlotBindOffset`;
/// a written target is a storage view. Every static-root access places its targets here
/// Give each of `targets` the profile's containment check and read its slot's `SlotBindOffset`.
/// Every static-root access places its targets here
/// ([`access_with_leaf`], `copy::endpoint`), each at a byte offset that is a translation-time
/// constant only where `fixed` ([`note_variable`]).
fn place_targets(
@@ -2305,9 +2032,6 @@ fn place_targets(
.slots
.get(t.slot)
.ok_or_else(|| cx.invariant("a target names a missing slot"))?;
if write && view_kind(cx.profile, plan) != ViewKind::Storage {
return Err(cx.invariant("a write through a uniform view"));
}
let slot = plan.slot;
cx.push.insert(PushField::SlotBindOffset(slot));
note_variable(cx, slot, fixed, !write);
@@ -2333,8 +2057,8 @@ fn leaf_reach(p: &DeviceProfile, leaf: &Leaf) -> u32 {
}
/// Give each slot of `targets` the unit views that read or write `leaf` (a store when `write`)
/// in whole units ([`leaf::leaf_units`]): a storage slot the narrow views the profile can access
/// and a `uvec2` view, and any slot a `uvec4` view.
/// in whole units ([`leaf::leaf_units`]): the narrow views the profile can access, and the `uvec2`
/// and `uvec4` views.
fn note_units(
cx: &mut SelectCx<'_>,
targets: &[Target],
@@ -2346,21 +2070,8 @@ fn note_units(
return Ok(());
}
for t in targets {
let plan = cx
.memory
.slots
.get(t.slot)
.ok_or_else(|| cx.invariant("a target names a missing slot"))?;
let units = match view_kind(cx.profile, plan) {
ViewKind::Storage => units,
// A uniform view has no narrow or `uvec2` view.
ViewKind::UniformWords { .. } | ViewKind::UniformVec4 { .. } => Units {
vec4: units.vec4,
..Units::NONE
},
};
if units.is_empty() {
continue;
if cx.memory.slots.get(t.slot).is_none() {
return Err(cx.invariant("a target names a missing slot"));
}
let entry = cx
.families
@@ -2616,8 +2327,7 @@ pub fn select(
}
/// Record the static slots a volatile, coherent, or atomic access `s` reaches
/// (`AccessPlan::ordered`). An atomic's words are reached through a storage-view pointer, which a
/// uniform view has none of, and an atomic load reads words other invocations may write.
/// (`AccessPlan::ordered`): an atomic load reads words other invocations may write.
fn note_ordered(cx: &mut SelectCx<'_>, s: &AccessStrategy) {
if let AccessStrategy::Atomic(atomic::AtomicAccess {
mem: atomic::AtomicMem::Buffer { targets, .. },
@@ -491,16 +491,6 @@ fn store_pointer(
if in_blob {
return Err(refuse());
}
for t in &targets {
let plan = cx
.memory
.slots
.get(t.slot)
.ok_or_else(|| cx.invariant("a target names a missing slot"))?;
if super::view_kind(cx.profile, plan) != super::ViewKind::Storage {
return Err(cx.invariant("a pointer store through a uniform view"));
}
}
let to = super::access_with_leaf(cx, ptr, None, leaf, targets, null, None)?;
let words = !cx.profile.fields().leaf.int64;
Ok(PointerValue::StorePointer {
+17 -34
View File
@@ -12,14 +12,13 @@
//!
//! - **Shared.** When an accessed buffer slot of the function (a buffer argument or a
//! buffer-table element) has the source buffer's Metal index, the fetch reads through that
//! slot. Its window widens to `Whole`, and it is a storage slot (a uniform view's declared size
//! is a bounded range and has no `OpArrayLength` for the in-shader check) whose access is the
//! function's plus the fetch's read. The function may write it or reach it by atomics: the fetch
//! runs once, before any instruction of the body, so it reads what Metal's attribute holds, an
//! input the body's writes do not change. One shape has no sharing and is
//! `Unsupported{Lowering(StageIo), NotImplemented}` (`share`): a window that is not within the
//! first 2³² bytes at or above the bind offset, the reach of a `Whole` window (a `u32` Metal
//! displacement from the bind offset, through a view or a device address).
//! slot. Its window widens to `Whole`, and its access is the function's plus the fetch's read.
//! The function may write it or reach it by atomics: the fetch runs once, before any
//! instruction of the body, so it reads what Metal's attribute holds, an input the body's writes
//! do not change. One shape has no sharing and is `Unsupported{Lowering(StageIo),
//! NotImplemented}` (`share`): a window that is not within the first 2³² bytes at or above the
//! bind offset, the reach of a `Whole` window (a `u32` Metal displacement from the bind offset,
//! through a view or a device address).
//! - **Own.** Otherwise the source buffer is a read-only `Whole` slot of its own.
//!
//! Either way it is a storage slot like any other: a `Whole` range is never provably within
@@ -40,7 +39,7 @@ use crate::lower::emit::EmitCx;
use crate::lower::stage_io::fetch;
use crate::memory::contain::{self, Check};
use crate::memory::leaf::{self, k32, Leaf, WordMem};
use crate::memory::views::{self, View, ViewKind};
use crate::memory::views::{self, View};
use crate::pipeline::interface::{
AccessSet, BufferForm, BufferKind, BufferSlot, SlotInterface, Window,
};
@@ -51,7 +50,7 @@ use crate::spirv::ids::Value as SValue;
use crate::spirv::ir::BinOp;
use super::psb::{self, PsbMem};
use super::{descriptor_view, slot_root, AccessPlan, SlotLowering};
use super::{slot_root, AccessPlan, SlotLowering};
/// How the fetch reaches a pulled source buffer.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
@@ -111,7 +110,7 @@ pub fn slot_interfaces(plan: &AccessPlan) -> impl Iterator<Item = (SlotRef, Slot
access: AccessSet::READ,
window: Window::Whole,
form: match l {
SlotLowering::View(kind) => BufferForm::Descriptor(descriptor_view(kind)),
SlotLowering::View => BufferForm::Descriptor,
SlotLowering::Psb { .. } => BufferForm::Psb,
},
kind: BufferKind::Buffer,
@@ -125,8 +124,8 @@ pub fn slot_interfaces(plan: &AccessPlan) -> impl Iterator<Item = (SlotRef, Slot
pub(super) fn declare(mb: &mut ModuleBuilder, plan: &AccessPlan) -> BResult<Vec<(u32, View)>> {
let mut out = Vec::new();
for p in &plan.pulled {
if let Reach::Own(SlotLowering::View(kind)) = p.reach {
out.push((p.slot.index, views::declare(mb, p.slot, kind)?));
if let Reach::Own(SlotLowering::View) = p.reach {
out.push((p.slot.index, views::declare(mb, p.slot)?));
}
}
Ok(out)
@@ -236,10 +235,10 @@ fn view_read_at(
) -> BResult<SourceRead> {
let inb = match check {
Check::None => None,
Check::InShader => match views::storage_bytes(fb, view)? {
Some(size) => Some(contain::in_bounds(fb, off, size, u64::from(n))?),
None => return Err(BuildError::Dangling(Dangling::Global(view.global))),
},
Check::InShader => {
let size = views::storage_bytes(fb, view)?;
Some(contain::in_bounds(fb, off, size, u64::from(n))?)
}
};
let off = match inb {
Some(inb) => {
@@ -424,24 +423,8 @@ fn source(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, buffer: u32) -> BRe
None => return Err(cx.fail(format!("source buffer {slot:?} has no planned slot"))),
};
match (lowering, view) {
(Some(SlotLowering::View(ViewKind::Storage)), Some(view)) => {
(Some(SlotLowering::View), Some(view)) => {
let residual = cx.push_field(fb, PushField::SlotBindOffset(slot))?;
// A shared slot whose view the binder starts at the bind offset
// (`RangeAtBindOffset`, where the plan declares it) has residual 0: the fetch reads
// no push word there, as the function's own accesses do (`emit::prepare`).
let at_bind = match reach {
Some(Reach::Shared { slot }) => {
cx.decl.families.access.at_bind.get(slot).copied().flatten()
}
_ => None,
};
let residual = match at_bind {
Some(at_bind) => {
let zero = k32(fb, 0)?;
fb.select(at_bind, zero, residual)?
}
None => residual,
};
Ok(Source::View { view, residual })
}
(Some(SlotLowering::Psb { .. }), _) if identity => {
+2 -5
View File
@@ -1042,8 +1042,7 @@ pub fn declare(mb: &mut ModuleBuilder, access: &super::AccessPlan) -> BResult<Ti
kind: ResourceKind::Synthetic(SyntheticBinding::TileMemory),
index: 0,
};
let view =
crate::memory::views::declare_at(mb, slot, crate::memory::views::ViewKind::Storage)?;
let view = crate::memory::views::declare_at(mb, slot)?;
let u32_ = mb.ty(SType::Int {
width: 32,
signed: false,
@@ -1506,9 +1505,7 @@ fn memory_pass<'c>(cx: &mut EmitCx<'c>, fb: &mut FunctionBuilder<'_>, pass: Pass
let next = fb.binary(BinOp::IAdd, k, n)?;
fb.store(counter, next, MemAccess::default())?;
let at = fb.binary(BinOp::IAdd, base, k)?;
let Some(stored) = crate::memory::views::word_ptr(fb, view, at)? else {
return Err(cx.fail("a tile memory buffer that is not a storage view"));
};
let stored = crate::memory::views::word_ptr(fb, view, at)?;
let mut mem = ArenaMem(arena, WordOps::of(coherence));
match pass {
Pass::Load => {
@@ -7,7 +7,7 @@
//! has no acceleration structures and reports every ray query instruction unmodelled.
use super::*;
use crate::memory::views::{self, View, ViewKind};
use crate::memory::views::{self, View};
use crate::pipeline::sym::{ResourceKind, ResourceSlot, Stage};
use crate::spirv::builder::ModuleBuilder;
use crate::spirv::interp::{self, Buffer, Config, Resources};
@@ -30,9 +30,7 @@ fn word(fb: &mut FunctionBuilder<'_>, view: View, i: u32) -> SValue {
/// Store `x` (a `u32`) to word `i` of `view`.
fn put(fb: &mut FunctionBuilder<'_>, view: View, i: u32, x: SValue) {
let w = u32c(fb, i).expect("index");
let p = views::word_ptr(fb, view, w)
.expect("pointer")
.expect("storage");
let p = views::word_ptr(fb, view, w).expect("pointer");
fb.store(p, x, MemAccess::default()).expect("store");
}
@@ -44,8 +42,8 @@ fn bit(fb: &mut FunctionBuilder<'_>, c: SValue) -> SValue {
/// A one-invocation compute module around `body`, reading buffer 0 and writing buffer 1.
fn harness(body: impl FnOnce(&mut FunctionBuilder<'_>, View, View)) -> TypedModule {
let mut mb = ModuleBuilder::new();
let input = views::declare_at(&mut mb, kslot(0), ViewKind::Storage).expect("input");
let out = views::declare_at(&mut mb, kslot(1), ViewKind::Storage).expect("out");
let input = views::declare_at(&mut mb, kslot(0)).expect("input");
let out = views::declare_at(&mut mb, kslot(1)).expect("out");
let void = mb.ty(SType::Void).expect("void");
let mut f = mb.function(void).expect("function");
body(&mut f, input, out);
@@ -104,11 +104,11 @@ use crate::lower::select::{decl_name, param_binding, FamilyPlans, Plan, SelectCx
use crate::lower::strategy::FamilyStrategy;
use crate::memory::provenance::primitive_data_root;
use crate::memory::provenance::{OffsetRange, Root};
use crate::memory::views::{self, View, ViewKind};
use crate::memory::views::{self, View};
use crate::pipeline::artifact::PrecisionNote;
use crate::pipeline::facts::RuntimeFact;
use crate::pipeline::interface::{
AccessSet, BufferForm, BufferKind, BufferSlot, DescriptorView, SlotInterface, Window,
AccessSet, BufferForm, BufferKind, BufferSlot, SlotInterface, Window,
};
use crate::pipeline::sym::{
AccelerationStructureLevel, PushField, ResourceKind, ResourceSlot, SlotClass, SlotRef, Stage,
@@ -299,7 +299,7 @@ pub fn slot_interfaces(plan: &Plan) -> impl Iterator<Item = (SlotRef, SlotInterf
SlotInterface::Buffer(BufferSlot {
access: AccessSet::READ,
window: Window::Whole,
form: BufferForm::Descriptor(DescriptorView::Storage),
form: BufferForm::Descriptor,
kind: BufferKind::IntersectionFunctionTable,
}),
)
@@ -314,7 +314,7 @@ pub fn declare(
) -> BResult<Declared> {
let mut d = Declared::default();
for &slot in &plan.families.raytracing.tables {
let view = views::declare(mb, table_slot(plan.stage, slot), ViewKind::Storage)?;
let view = views::declare(mb, table_slot(plan.stage, slot))?;
d.tables.insert(slot, view);
}
for (slot, level) in &plan.families.raytracing.structures {
@@ -12,7 +12,7 @@ use crate::spv::ImageFormat;
use super::{counted, Footprint, Kind, Site};
use crate::bind::{SparseTileMap, TileMapping};
use crate::memory::views::{View, ViewKind};
use crate::memory::views::View;
use crate::metal::TextureType;
use crate::pipeline::sym::{CombinedSampler, ResourceKind, ResourceSlot, SamplerRef, Stage};
use crate::spirv::builder::{FunctionBuilder, ModuleBuilder};
@@ -108,7 +108,6 @@ fn kernel(fp: Footprint, dim: Dim, arrayed: bool) -> BResult<TypedModule> {
let map = storage_buffer(&mut b, 2, u32_, 4)?;
let map = View {
global: map,
kind: ViewKind::Storage,
u32_ty: u32_,
};
let id = b.builtin(crate::spv::BuiltIn::GlobalInvocationId, IoDir::Input, uvec3)?;
+28 -82
View File
@@ -77,17 +77,6 @@
//! divergent. A simdgroup's collective operations are divergent there, as for a workgroup: the
//! vertices of one primitive may run in different simdgroups.
//!
//! **Active lanes** ([`Uniformity::among_active_lanes`]). A value that may differ between the
//! active lanes of one execution of its instruction in a simdgroup, which is what the memory a
//! read reaches is chosen by (`memory::plan`'s lane reads): the analysis among a simdgroup
//! with no control divergence. No block turns divergent, so a phi is divergent only through its
//! incoming values: the lanes that run a loop's header together hold its counter alike, whatever
//! branch some lanes left by before the loop. A load is divergent only through its pointer (or as
//! a volatile or atomic one), in any address space: the lanes that run it together read the same
//! bytes at a uniform address; a thread's own memory is reached only through an alloca, which is
//! divergent. What this misses errs toward uniform: a phi joining uniform values after a divergent
//! branch, and a value a loop left on a per-lane condition computes, read after it.
//!
//! The analysis is one worklist over instructions and blocks, each of which turns divergent at
//! most once; its memory is charged to the meter.
@@ -325,9 +314,6 @@ struct State<'a> {
e: &'a Entry,
body: &'a Body,
among: Among,
/// Among the active lanes (the module docs, "Active lanes"): no control divergence, and a
/// load divergent only through its pointer.
active: bool,
/// By parameter and by instruction: the divergent lanes (the module docs, "Lanes").
args: Vec<u8>,
insts: Vec<u8>,
@@ -522,7 +508,7 @@ impl State<'_> {
} => {
*volatile
|| atomic.is_some()
|| (!self.active && self.ptr_space(*ptr) != Some(AddrSpace::Constant))
|| self.ptr_space(*ptr) != Some(AddrSpace::Constant)
|| self.value_divergent(*ptr)
}
InstKind::Alloca { .. } | InstKind::AtomicRmw { .. } | InstKind::CmpXchg { .. } => true,
@@ -588,14 +574,7 @@ impl Uniformity {
/// The uniformity of the blocks of `e`'s entry body. The returned structure stays charged to
/// `m` ([`Uniformity::ledger_bytes`]); the analysis' own tables are released.
pub fn of(e: &Entry, body: &Body, m: &mut Meter) -> Result<Uniformity, Error> {
Uniformity::analyze(e, body, Among::Workgroup, Flow::Control(None), &[], 0, m)
}
/// The values of `e`'s entry body that may differ between the active lanes of one execution
/// of their instruction in a simdgroup (the module docs, "Active lanes"). Its blocks are all
/// uniform: control divergence is not followed. The returned structure stays charged to `m`.
pub fn among_active_lanes(e: &Entry, body: &Body, m: &mut Meter) -> Result<Uniformity, Error> {
Uniformity::analyze(e, body, Among::Simdgroup, Flow::Data, &[], 0, m)
Uniformity::analyze(e, body, Among::Workgroup, None, &[], 0, m)
}
/// [`of`](Self::of) for a dispatch whose threadgroups have one thread along the axes `unit`
@@ -606,7 +585,7 @@ impl Uniformity {
unit: UnitAxes,
m: &mut Meter,
) -> Result<Uniformity, Error> {
Uniformity::analyze(e, body, Among::Workgroup, Flow::Control(None), &[], unit, m)
Uniformity::analyze(e, body, Among::Workgroup, None, &[], unit, m)
}
/// The uniformity of the blocks and values of vertex function `e`'s entry body among the
@@ -619,15 +598,7 @@ impl Uniformity {
uniform: &[u32],
m: &mut Meter,
) -> Result<Uniformity, Error> {
Uniformity::analyze(
e,
body,
Among::Primitive,
Flow::Control(None),
uniform,
0,
m,
)
Uniformity::analyze(e, body, Among::Primitive, None, uniform, 0, m)
}
/// The uniformity of the blocks of `e`'s entry body among the invocations `among` relates,
@@ -642,14 +613,16 @@ impl Uniformity {
loops: &LoopForest<BlockId>,
m: &mut Meter,
) -> Result<Uniformity, Error> {
Uniformity::analyze(e, body, among, Flow::Control(Some(loops)), &[], 0, m)
Uniformity::analyze(e, body, among, Some(loops), &[], 0, m)
}
/// The analysis among `among`, with the barrier contract where `contract` gives the loop
/// forest.
fn analyze(
e: &Entry,
body: &Body,
among: Among,
flow: Flow<'_>,
contract: Option<&LoopForest<BlockId>>,
uniform: &[u32],
unit: UnitAxes,
m: &mut Meter,
@@ -683,23 +656,18 @@ impl Uniformity {
// What the result keeps: the block, instruction, and argument flags.
let kept = nb.saturating_add(n).saturating_add(e.ep.params.len());
m.charge(scratch.saturating_add(kept))?;
let result = match flow {
Flow::Data => {
State::new(e, body, among, true, uniform, unit, m).and_then(|st| st.run(None, m))
}
Flow::Control(contract) => PostDomTree::compute(&e.cfg, m)
.map_err(Error::from)
.and_then(|pdom| {
let r = State::new(e, body, among, false, uniform, unit, m)
.and_then(|st| match contract {
Some(loops) => st.pin(&pdom, loops, m),
None => Ok(st),
})
.and_then(|st| st.run(Some(&pdom), m));
m.release(pdom.ledger_bytes());
r
}),
};
let result = PostDomTree::compute(&e.cfg, m)
.map_err(Error::from)
.and_then(|pdom| {
let r = State::new(e, body, among, uniform, unit, m)
.and_then(|st| match contract {
Some(loops) => st.pin(&pdom, loops, m),
None => Ok(st),
})
.and_then(|st| st.run(&pdom, m));
m.release(pdom.ledger_bytes());
r
});
m.release(scratch);
match result {
Ok(u) => {
@@ -716,22 +684,11 @@ impl Uniformity {
}
}
/// What divergence an analysis follows.
#[derive(Clone, Copy)]
enum Flow<'l> {
/// Values and control: a block control dependent on a divergent branch is divergent, and so
/// is a phi entered from one; with the barrier contract when the loop forest is given.
Control(Option<&'l LoopForest<BlockId>>),
/// Values alone, among the active lanes (the module docs, "Active lanes").
Data,
}
impl<'a> State<'a> {
fn new(
e: &'a Entry,
body: &'a Body,
among: Among,
active: bool,
uniform: &[u32],
unit: UnitAxes,
m: &mut Meter,
@@ -812,7 +769,6 @@ impl<'a> State<'a> {
e,
body,
among,
active,
args,
insts: vec![0; n],
blocks: vec![false; nb],
@@ -885,20 +841,13 @@ impl<'a> State<'a> {
Ok(self)
}
/// Run the worklist; without `pdom` no control divergence is followed (no block turns
/// divergent).
fn run(
mut self,
pdom: Option<&PostDomTree<BlockId>>,
m: &mut Meter,
) -> Result<Uniformity, Error> {
/// Run the worklist.
fn run(mut self, pdom: &PostDomTree<BlockId>, m: &mut Meter) -> Result<Uniformity, Error> {
let body = self.body;
// A reachable block that reaches no exit has no post-dominator information.
if let Some(pdom) = pdom {
for (b, _) in body.blocks.iter() {
if self.e.cfg.is_reachable(b) && !pdom.is_reachable(b) {
self.set_block(b);
}
for (b, _) in body.blocks.iter() {
if self.e.cfg.is_reachable(b) && !pdom.is_reachable(b) {
self.set_block(b);
}
}
for (id, _) in body.insts.iter().rev() {
@@ -926,7 +875,7 @@ impl<'a> State<'a> {
if let Some(d) = self.insts.get_mut(i.index()) {
*d = new;
}
if let (true, 0, Some(pdom)) = (branch, old, pdom) {
if branch && old == 0 {
let a = BlockId::new(self.home.get(i.index()).copied().unwrap_or(0));
self.mark_region(a, pdom, m)?;
}
@@ -935,11 +884,8 @@ impl<'a> State<'a> {
}
Item::Block(b) => {
// Its branch is divergent wherever it leads, and its successors' phis are
// entered from a divergent block. (A block turns divergent only where
// control divergence is followed.)
if let Some(pdom) = pdom {
self.mark_region(b, pdom, m)?;
}
// entered from a divergent block.
self.mark_region(b, pdom, m)?;
// Its simdgroup collectives' threads may hold different executions' results.
if self.among == Among::Simdgroup {
if let Some(block) = body.blocks.get(b) {
@@ -403,101 +403,3 @@ fn a_collective_in_a_loop_left_apart_is_divergent() {
assert_eq!(u, [together], "a loop left per thread: {per_thread}");
}
}
/// Whether each value `body` returns is uniform under [`Uniformity::of`] and among the active
/// lanes ([`Uniformity::among_active_lanes`]), in that order.
fn of_and_active(
body: impl FnOnce(&mut FunctionBuilder<'_>, &Types) -> Vec<Value>,
) -> Vec<(bool, bool)> {
let (e, values) = kernel(body);
let body = e
.module
.func(e.func)
.and_then(|f| f.body.as_ref())
.expect("body");
let mut m = meter();
let of = Uniformity::of(&e, body, &mut m).expect("uniformity");
let active = Uniformity::among_active_lanes(&e, body, &mut m).expect("active lanes");
assert!(
body.blocks.iter().all(|(b, _)| active.is_uniform(b)),
"no block is divergent among the active lanes"
);
values
.into_iter()
.map(|v| (of.is_uniform_value(&e, v), active.is_uniform_value(&e, v)))
.collect()
}
/// After an early return of some invocations, the counter of a loop over a `constant` bound is
/// divergent for the workgroup (its preheader is control dependent on the return), and uniform
/// among the active lanes, which run the header together: an index of it reads one address.
#[test]
fn a_counter_after_an_early_return_is_uniform_among_the_active_lanes() {
let u = of_and_active(|fb, t| {
let (early, rest, header, latch, exit) =
(fb.block(), fb.block(), fb.block(), fb.block(), fb.block());
let n = load(fb, t.i32, fb.arg(CONSTANT));
let out = icmp(fb, t, IntPredicate::Uge, fb.arg(TID), n);
fb.cond_br(out, early, rest);
fb.switch_to(early);
fb.ret(None);
fb.switch_to(rest);
fb.br(header);
fb.switch_to(header);
let zero = fb.module().const_int(t.i32, 0);
let one = fb.module().const_int(t.i32, 1);
// Provisional ids are handed out in push order: the entry's load, compare and branch,
// the early return and the preheader's branch come first.
let next_ref = Value::Inst(InstId::new(6));
let i = fb.push(
t.i32,
InstKind::Phi {
incoming: Box::new([(zero, rest), (next_ref, latch)]),
fmf: crate::air::ir::FastMath::NONE,
},
);
assert_eq!(i, Value::Inst(InstId::new(5)));
let next = fb.bin(crate::air::ir::BinOp::Add, i, one);
assert_eq!(next, next_ref);
let more = icmp(fb, t, IntPredicate::Ult, next, n);
fb.cond_br(more, latch, exit);
fb.switch_to(latch);
fb.br(header);
fb.switch_to(exit);
fb.ret(None);
vec![n, i, next]
});
assert_eq!(u, [(true, true), (false, true), (false, true)]);
}
/// Among the active lanes a value is divergent through per-lane data alone: an index computed
/// from the thread's position is divergent, a load of device memory through a uniform pointer
/// is uniform (one address for every lane), and a phi joining uniform values after a branch on
/// the thread's position is uniform there, the documented miss, which errs toward uniform.
#[test]
fn active_lanes_follow_per_lane_data_alone() {
let u = of_and_active(|fb, t| {
let entry = BlockId::new(0);
let (then, join) = (fb.block(), fb.block());
let one = fb.module().const_int(t.i32, 1);
let two = fb.module().const_int(t.i32, 2);
let lane = fb.bin(crate::air::ir::BinOp::Add, fb.arg(TID), one);
let word = load(fb, t.i32, fb.arg(DEVICE));
let zero = fb.module().const_int(t.i32, 0);
let first = icmp(fb, t, IntPredicate::Eq, fb.arg(TID), zero);
fb.cond_br(first, then, join);
fb.switch_to(then);
fb.br(join);
fb.switch_to(join);
let joined = fb.push(
t.i32,
InstKind::Phi {
incoming: Box::new([(one, then), (two, entry)]),
fmf: crate::air::ir::FastMath::NONE,
},
);
fb.ret(None);
vec![lane, word, joined]
});
assert_eq!(u, [(false, false), (false, true), (false, true)]);
}
@@ -9,7 +9,7 @@
use super::*;
use crate::lower::arith::legal::{f16_to_f64, f64_to_f16};
use crate::memory::views::{self, ViewKind};
use crate::memory::views;
use crate::pipeline::sym::{ResourceKind, ResourceSlot};
use crate::spirv::builder::ModuleBuilder;
use crate::spirv::interp::{self, Buffer, Config, Resources};
@@ -65,9 +65,9 @@ fn module_from(
offset: u32,
) -> TypedModule {
let mut mb = ModuleBuilder::new();
let data = views::declare_at(&mut mb, kslot(0), ViewKind::Storage).expect("data");
let params = views::declare_at(&mut mb, kslot(1), ViewKind::Storage).expect("params");
let out = views::declare_at(&mut mb, kslot(2), ViewKind::Storage).expect("out");
let data = views::declare_at(&mut mb, kslot(0)).expect("data");
let params = views::declare_at(&mut mb, kslot(1)).expect("params");
let out = views::declare_at(&mut mb, kslot(2)).expect("out");
let void = mb.ty(Type::Void).expect("void");
let mut f = mb.function(void).expect("function");
let fb = &mut f;
@@ -122,7 +122,7 @@ fn module_from(
x
};
let w = k32(fb, i).expect("k");
let ptr = views::word_ptr(fb, out, w).expect("ptr").expect("storage");
let ptr = views::word_ptr(fb, out, w).expect("ptr");
fb.store(ptr, x, MemAccess::default()).expect("store");
}
f.ret(None).expect("ret");
+1 -2
View File
@@ -1306,8 +1306,7 @@ pub fn declare(
kind: crate::pipeline::sym::ResourceKind::TileMap,
index: s.slot.index,
};
let view =
crate::memory::views::declare_at(mb, sym, crate::memory::views::ViewKind::Storage)?;
let view = crate::memory::views::declare_at(mb, sym)?;
d.tile_maps.insert(*index, view);
}
if s.swizzle {
+1 -1
View File
@@ -519,7 +519,7 @@ fn declare_fragment(mb: &mut ModuleBuilder, shape: &TgShape, coord: usize) -> BR
kind: ResourceKind::Synthetic(SyntheticBinding::TileMemory),
index: 0,
};
let view = crate::memory::views::declare_at(mb, slot, crate::memory::views::ViewKind::Storage)?;
let view = crate::memory::views::declare_at(mb, slot)?;
let mut regions = Vec::with_capacity(shape.regions.len());
for &(param, index) in &shape.regions {
regions.push((param, tile_offset(mb, index)?));
+2 -4
View File
@@ -25,7 +25,7 @@
use std::sync::Arc;
use crate::memory::leaf::WordMem;
use crate::memory::views::{self, View, ViewKind};
use crate::memory::views::{self, View};
use crate::pipeline::sym::{ResourceKind, ResourceSlot, Stage, SyntheticBinding};
use crate::spirv::builder::{FunctionBuilder, ModuleBuilder};
use crate::spirv::error::{BResult, BuildError, Dangling};
@@ -89,9 +89,7 @@ pub struct ModuleWords {
/// Declare `stage`'s blob `blob` where it lives.
pub fn declare(mb: &mut ModuleBuilder, stage: Stage, blob: &BlobUse) -> BResult<BlobDecl> {
match blob.home {
BlobHome::Bound => {
views::declare_at(mb, symbol(stage), ViewKind::Storage).map(BlobDecl::Bound)
}
BlobHome::Bound => views::declare_at(mb, symbol(stage)).map(BlobDecl::Bound),
BlobHome::Module => declare_module(mb, &blob.bytes).map(BlobDecl::Module),
}
}
+3 -5
View File
@@ -1288,7 +1288,7 @@ pub struct Table {
/// has `shaderInt64`), else a word storage view.
pub fn declare_table(mb: &mut ModuleBuilder, sym: ResourceSlot, int64: bool) -> BResult<Table> {
if !int64 {
let v = views::declare_at(mb, sym, views::ViewKind::Storage)?;
let v = views::declare_at(mb, sym)?;
return Ok(Table {
global: v.global,
u32_ty: v.u32_ty,
@@ -1540,7 +1540,6 @@ pub fn entry_field(
None => {
let words = View {
global: t.global,
kind: views::ViewKind::Storage,
u32_ty: t.u32_ty,
};
entry_word(fb, words, k, word)
@@ -1586,7 +1585,6 @@ pub fn lookup(
let zero = k32(fb, 0)?;
let words = View {
global: t.global,
kind: views::ViewKind::Storage,
u32_ty: t.u32_ty,
};
// The key, and the id of an entry, in the table's form.
@@ -1918,7 +1916,7 @@ mod tests {
};
let mut b = ModuleBuilder::new();
let t = declare_table(&mut b, sym(0), int64)?;
let io = views::declare_at(&mut b, sym(1), views::ViewKind::Storage)?;
let io = views::declare_at(&mut b, sym(1))?;
let search = define_lookup(&mut b, t, form)?;
let void = b.ty(Type::Void)?;
let mut f = b.function(void)?;
@@ -1933,7 +1931,7 @@ mod tests {
.expect("the search returns the element");
for word in per_key(&mut f, t, e)? {
let to = k32(&mut f, at)?;
let p = views::word_ptr(&mut f, io, to)?.expect("a storage view is writable");
let p = views::word_ptr(&mut f, io, to)?;
f.store(p, word, MemAccess::default())?;
at += 1;
}
+1 -1
View File
@@ -83,7 +83,7 @@
//!
//! **Vector units**. A word memory may also load and store 16-byte units through a typed `uvec4`
//! view and 8-byte units through a typed `uvec2` view ([`WordMem::read_vec`]; a descriptor slot's
//! `{ uvec4[] }` and `{ uvec2[] }` views, or its uniform view's own vectors, `memory::views`).
//! `{ uvec4[] }` and `{ uvec2[] }` views, `memory::views`).
//! There a [`Path::Vec4`] leaf is one unit at index `off / 16` and a [`Path::Vec2`] leaf one at
//! `off / 8`, its register value one bitcast of the vector (32-bit lanes, or 64-bit ones) or the
//! composition of its words: one load or store where the aligned path moves four or two words. A
+1 -56
View File
@@ -100,11 +100,6 @@ pub struct SlotPlan {
pub window: Option<Window>,
/// The slot's guest base address is observed.
pub guest_base: bool,
/// Some read reaches the slot at an address that may differ between the lanes that run it
/// together (`Uniformity::among_active_lanes`), for a slot a uniform view could read
/// (`constant`, read-only, no atomic, a `Bounded` window): such a slot keeps its storage view
/// on every device (`lower::access::view_kind`). False on every other slot.
pub lane_read: bool,
}
/// An object in an arena.
@@ -778,7 +773,7 @@ impl Planner<'_> {
fn plan(self, m: &mut Meter) -> Result<MemoryPlan, Error> {
self.check_tables()?;
let dynamic = self.any_dynamic_buffer_root();
let slots = self.lane_reads(self.slots(dynamic, m)?, m)?;
let slots = self.slots(dynamic, m)?;
// The unshared type size the function's typed objects may still declare.
let mut room = super::alloca::MAX_UNSHARED;
let (const_globals, blob) = self.const_globals(&mut room, m)?;
@@ -1057,7 +1052,6 @@ impl Planner<'_> {
atomic: eu.atomic,
window: escaped_window(window::window(eu.extent, None, dynamic), eu),
guest_base: eu.escapes || eu.cross_compare,
lane_read: false,
});
}
continue;
@@ -1084,60 +1078,11 @@ impl Planner<'_> {
atomic: u.atomic,
window: escaped_window(window::window(u.extent, arg.buffer_size, dynamic), &u),
guest_base: u.escapes || u.cross_compare,
lane_read: false,
});
}
Ok(slots)
}
/// `slots` with [`SlotPlan::lane_read`] marked: a slot a uniform view could read with an
/// indexed read ([`Provenance::indexed_constant_reads`]) whose pointer is not uniform among the
/// active lanes is a lane read's. The analysis runs once, only where such a slot has an indexed
/// read (a slot read at constant offsets alone, a struct's fields, has none), and its bytes are
/// released before return.
fn lane_reads(&self, mut slots: Vec<SlotPlan>, m: &mut Meter) -> Result<Vec<SlotPlan>, Error> {
let candidate = |s: &SlotPlan, r: Root| {
s.space == AddrSpace::Constant
&& !s.access.write
&& !s.atomic
&& matches!(s.window, Some(Window::Bounded { .. }))
&& r == match s.element {
Some(element) => Root::BufferElement {
param: s.param,
element,
},
None => Root::Param(s.param),
}
};
let reads = &self.prov.indexed_constant_reads;
let mut any = false;
for &(r, _) in reads {
m.tick(1)?;
any |= slots.iter().any(|s| candidate(s, r));
}
if !any {
return Ok(slots);
}
let body = self
.e
.module
.func(self.e.func)
.and_then(|f| f.body.as_ref())
.ok_or_else(|| invariant("the entry function has no body"))?;
let u = crate::lower::simd::uniform::Uniformity::among_active_lanes(self.e, body, m)?;
for &(r, ptr) in reads {
m.tick(1)?;
if u.is_uniform_value(self.e, ptr) {
continue;
}
if let Some(s) = slots.iter_mut().find(|s| candidate(s, r)) {
s.lane_read = true;
}
}
m.release(u.ledger_bytes());
Ok(slots)
}
/// A buffer table is a pointer to the argument table's own entries: it is only read, through
/// loads of whole entries (provenance refuses every other access). A table pointer that
/// escapes, merges with another root, or is compared across roots has no model (the entries are
+1 -17
View File
@@ -589,11 +589,6 @@ pub struct Provenance {
/// The first dereference of a pointer whose root set contains `Dynamic`, in the device or
/// constant space: the instruction and its block.
pub dynamic_deref: Option<(BlockId, InstId)>,
/// The pointer of every read through a `constant` pointer that reaches a buffer root (a
/// parameter or a buffer table's element) at an offset that is not one constant
/// ([`RootUse::indexed`]), with the root, in walk order: the reads whose address may differ
/// between lanes (`memory::plan`'s lane reads).
pub indexed_constant_reads: Vec<(Root, Value)>,
/// Which allocas forward the pointers stored into them.
pub cells: CellFacts,
/// The entry's bindings and layouts, indexed once.
@@ -2266,7 +2261,6 @@ fn classify(
let (values, n) = (cx.values, cx.ptr_values.len());
let mut uses: BTreeMap<Root, RootUse> = BTreeMap::new();
let mut dynamic_deref = None;
let mut indexed_constant_reads = Vec::new();
// ABI seeds on parameters, and on the removed textures and samplers the body still reads.
for b in e.ep.params.iter().chain(&e.absent_handles) {
@@ -2312,7 +2306,6 @@ fn classify(
classes,
uses: &mut uses,
dynamic_deref: &mut dynamic_deref,
indexed_constant_reads: &mut indexed_constant_reads,
static_sampler: &static_sampler,
slots: Vec::new(),
objects,
@@ -2407,7 +2400,6 @@ fn classify(
classes: resolved,
uses,
dynamic_deref,
indexed_constant_reads,
cells: cx.cells.facts,
abi: cx.abi,
})
@@ -2581,8 +2573,6 @@ struct Walk<'c, 'a> {
classes: &'c mut Classes,
uses: &'c mut BTreeMap<Root, RootUse>,
dynamic_deref: &'c mut Option<(BlockId, InstId)>,
/// [`Provenance::indexed_constant_reads`], charged as it grows.
indexed_constant_reads: &'c mut Vec<(Root, Value)>,
static_sampler: &'c dyn Fn(GlobalId) -> bool,
/// The pointers stored into and loaded from each forwarding cell slot: `(cell, slot, pointer,
/// the store or load that moves it)`.
@@ -2761,13 +2751,7 @@ impl Walk<'_, '_> {
}
u.extent = u.extent.join(extent);
u.typed &= typed;
let indexed = !matches!(fact.shape, Shape::Exact(_));
u.indexed |= indexed;
let buffer = matches!(r, Root::Param(_) | Root::BufferElement { .. });
if indexed && buffer && touch == Touch::Read && space == Some(AddrSpace::Constant) {
grow(self.indexed_constant_reads, 1, m)?;
self.indexed_constant_reads.push((r, ptr));
}
u.indexed |= !matches!(fact.shape, Shape::Exact(_));
}
Ok(())
}
+82 -230
View File
@@ -1,27 +1,13 @@
//! Descriptor views of a static-root buffer slot.
//!
//! A descriptor-form slot has exactly one view, a word array over the slot's descriptor range:
//! A descriptor-form slot has exactly one view, a word array over the slot's descriptor range: a
//! `StorageBuffer` block `{ u32 words[]; }` (std430, `ArrayStride` 4). It is valid on every
//! profile, reads and writes every leaf through word composition (`memory::leaf`), and its
//! `OpArrayLength` is the bound range in words, so the padded byte size is available to the
//! in-shader containment check. The serializer decorates it `Aliased`: two Metal buffer slots may
//! be bound to the same memory.
//!
//! - [`ViewKind::Storage`]: a `StorageBuffer` block `{ u32 words[]; }` (std430, `ArrayStride`
//! 4). It is valid on every profile, reads and writes every leaf through word composition
//! (`memory::leaf`), and its `OpArrayLength` is the bound range in words, so the padded byte
//! size is available to the in-shader containment check. The serializer decorates it `Aliased`:
//! two Metal buffer slots may be bound to the same memory.
//! - [`ViewKind::UniformWords`]: a `Uniform` block `{ u32 words[N]; }` (std430 in `Uniform`, which
//! needs `uniformBufferStandardLayout`).
//! - [`ViewKind::UniformVec4`]: a `Uniform` block `{ uvec4 vecs[N]; }` (std140, valid everywhere);
//! a word is one lane of a 4-vector.
//!
//! Uniform views exist only for read-only slots with a `Bounded` window whose descriptor range
//! fits `maxUniformBufferRange` ([`uniform_range`]), and only on profiles whose containment
//! encoding emits no check: their size is that range, a translation-time constant, because a
//! `Uniform` block cannot end in a runtime array, while the range actually bound may be shorter
//! (the binder clamps it to the allocation) and no in-shader check can read it. On every device a
//! slot with a read whose address may differ between the lanes that run it together
//! (`SlotPlan::lane_read`) keeps its storage view, and its reads at uniform addresses with it
//! (`lower::access::view_kind` gives their measured cost).
//!
//! A storage slot may also have **narrow views** ([`NarrowView`]): `StorageBuffer { u16[] }` and `{
//! A slot may also have **narrow views** ([`NarrowView`]): `StorageBuffer { u16[] }` and `{
//! u8[] }` blocks at the slot's binding (`ModuleBuilder::resource_view`), declared only where the
//! profile has the width's storage access and arithmetic type (`storageBuffer16BitAccess` and
//! `shaderInt16`, `storageBuffer8BitAccess` and `shaderInt8`) and an access of the slot reads or
@@ -31,56 +17,40 @@
//! alignment of 1 or 2 to the unit index, and the word view's `OpArrayLength` still contains every
//! access.
//!
//! A storage or uniform slot may also have a **`uvec4` view** ([`VecView`]): `StorageBuffer {
//! uvec4[] }` or `Uniform { uvec4[N] }` at the slot's binding, declared where an access of the slot
//! moves a 16-byte leaf whose AIR alignment is at least 16 at an offset `residual + m` proven a
//! multiple of 16 (`memory::leaf`'s placement: the residual's alignment is the bind offset's, and
//! `m`'s is its structure's; a `UniformVec4` word view is its own). A storage slot may likewise
//! have a **`uvec2` view**, `StorageBuffer { uvec2[] }`, where an access moves an 8-byte leaf whose
//! AIR alignment is at least 8 at an offset proven a multiple of 8 (a uniform slot has none: a
//! std140 array's stride is 16). The binder's 16-byte-aligned descriptor bases carry that alignment
//! to the unit index `(residual + m) / 16` or `/ 8`, and such a leaf lies wholly inside or wholly
//! outside a bound range (every range is a whole number of 16-byte units), so the word view's
//! containment check of the leaf's bytes is the unit's. `u64[]` views are not declared.
//! A slot may also have a **`uvec4` view** or a **`uvec2` view** ([`VecView`]): `StorageBuffer {
//! uvec4[] }` or `StorageBuffer { uvec2[] }` at the slot's binding, declared where an access of
//! the slot moves a 16-byte (8-byte) leaf whose AIR alignment is at least 16 (8) at an offset
//! `residual + m` proven a multiple of 16 (8) (`memory::leaf`'s placement: the residual's alignment
//! is the bind offset's, and `m`'s is its structure's). The binder's 16-byte-aligned descriptor
//! bases carry that alignment to the unit index `(residual + m) / 16` or `/ 8`, and such a leaf
//! lies wholly inside or wholly outside a bound range (every range is a whole number of 16-byte
//! units), so the word view's containment check of the leaf's bytes is the unit's. `u64[]` views
//! are not declared.
use crate::pipeline::sym::{ResourceKind, ResourceSlot, SlotRef};
use crate::spirv::builder::{FunctionBuilder, ModuleBuilder};
use crate::spirv::error::BResult;
use crate::spirv::ids::{GlobalId, TypeId, Value};
use crate::spirv::ir::{
natural_layout, BinOp, ConstBits, Constant, ConvOp, LayoutRule, MemAccess, StorageClass, Type,
};
/// The view kind of a descriptor-form slot (the plan's `DescriptorView` with its size).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ViewKind {
/// `StorageBuffer { u32[] }`.
Storage,
/// `Uniform { u32[words] }` (std430; `uniformBufferStandardLayout`).
UniformWords { words: u32 },
/// `Uniform { uvec4[vecs] }` (std140).
UniformVec4 { vecs: u32 },
}
use crate::spirv::ir::{natural_layout, BinOp, ConvOp, LayoutRule, MemAccess, StorageClass, Type};
/// A declared view.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct View {
pub global: GlobalId,
pub kind: ViewKind,
/// The `u32` type.
pub u32_ty: TypeId,
}
/// The least alignment of a Metal buffer slot's descriptor base: the binder starts every storage
/// and uniform view's range at a multiple of `max(min*BufferOffsetAlignment, 16)` bytes from the
/// allocation's start ([`base_alignment`]), so with the allocation's first byte at a
/// 16-byte-aligned Metal address, a descriptor byte is congruent to its Metal address modulo 16
/// and a 16-byte leaf whose Metal address is a multiple of 16 is one `uvec4` element.
/// The least alignment of a Metal buffer slot's descriptor base: the binder starts every view's
/// range at a multiple of `max(minStorageBufferOffsetAlignment, 16)` bytes from the allocation's
/// start ([`base_alignment`]), so with the allocation's first byte at a 16-byte-aligned Metal
/// address, a descriptor byte is congruent to its Metal address modulo 16 and a 16-byte leaf whose
/// Metal address is a multiple of 16 is one `uvec4` element.
pub const BASE_ALIGNMENT: u64 = 16;
/// The alignment of a Metal buffer slot's descriptor base for a view whose minimum offset
/// alignment is `min_offset` (`minStorageBufferOffsetAlignment` or
/// `minUniformBufferOffsetAlignment`): the larger of it and [`BASE_ALIGNMENT`].
/// alignment is `min_offset` (`minStorageBufferOffsetAlignment`): the larger of it and
/// [`BASE_ALIGNMENT`].
pub fn base_alignment(min_offset: u64) -> u64 {
min_offset.max(BASE_ALIGNMENT)
}
@@ -95,7 +65,7 @@ pub fn base_alignment(min_offset: u64) -> u64 {
/// The binder states the bound as `round_up(len + align - 4, 16)`, which assumes `bind_offset +
/// start` is a multiple of 4; a window may start at any byte (a `char` at offset 5), so the bound
/// here uses `align - 1`.
pub fn uniform_range(len: u64, align: u64) -> Option<u64> {
pub fn descriptor_range(len: u64, align: u64) -> Option<u64> {
len.checked_add(align.max(4))?
.checked_sub(1)?
.checked_next_multiple_of(16)
@@ -118,69 +88,25 @@ pub fn binding_symbol(slot: SlotRef) -> ResourceSlot {
}
/// Declare the view of `slot` (its `Buffer` descriptor binding symbol).
pub fn declare(mb: &mut ModuleBuilder, slot: SlotRef, kind: ViewKind) -> BResult<View> {
declare_at(mb, binding_symbol(slot), kind)
pub fn declare(mb: &mut ModuleBuilder, slot: SlotRef) -> BResult<View> {
declare_at(mb, binding_symbol(slot))
}
/// Declare a word view of kind `kind` at binding symbol `sym` (a Metal buffer slot, or a
/// synthetic binding such as the constant blob, `memory::blob`).
pub fn declare_at(mb: &mut ModuleBuilder, sym: ResourceSlot, kind: ViewKind) -> BResult<View> {
/// Declare a word view at binding symbol `sym` (a Metal buffer slot, or a synthetic binding such
/// as the constant blob, `memory::blob`).
pub fn declare_at(mb: &mut ModuleBuilder, sym: ResourceSlot) -> BResult<View> {
let u32_ty = u32_type(mb)?;
let (class, rule, member) = match kind {
ViewKind::Storage => (
StorageClass::StorageBuffer,
LayoutRule::Std430,
mb.ty(Type::RuntimeArray {
elem: u32_ty,
stride: Some(4),
})?,
),
ViewKind::UniformWords { words } => {
let len = mb.constant(Constant::Scalar {
ty: u32_ty,
bits: ConstBits(u64::from(words)),
})?;
(
StorageClass::Uniform,
LayoutRule::Std430,
mb.ty(Type::Array {
elem: u32_ty,
len,
stride: Some(4),
})?,
)
}
ViewKind::UniformVec4 { vecs } => {
let v4 = mb.ty(Type::Vector {
elem: u32_ty,
len: 4,
})?;
let len = mb.constant(Constant::Scalar {
ty: u32_ty,
bits: ConstBits(u64::from(vecs)),
})?;
(
StorageClass::Uniform,
LayoutRule::Std140,
mb.ty(Type::Array {
elem: v4,
len,
stride: Some(16),
})?,
)
}
};
let layout = natural_layout(mb.types(), rule, true, &[member])?;
let member = mb.ty(Type::RuntimeArray {
elem: u32_ty,
stride: Some(4),
})?;
let layout = natural_layout(mb.types(), LayoutRule::Std430, true, &[member])?;
let block = mb.ty(Type::Struct {
members: [member].into(),
layout: Some(layout),
})?;
let global = mb.resource(sym, class, block)?;
Ok(View {
global,
kind,
u32_ty,
})
let global = mb.resource(sym, StorageClass::StorageBuffer, block)?;
Ok(View { global, u32_ty })
}
fn k(fb: &mut FunctionBuilder<'_>, v: u32) -> BResult<Value> {
@@ -188,37 +114,19 @@ fn k(fb: &mut FunctionBuilder<'_>, v: u32) -> BResult<Value> {
fb.module().const_value(c)
}
/// A pointer to word `word` (a `u32` index) of a storage view, or `None` for a uniform view.
pub fn word_ptr(fb: &mut FunctionBuilder<'_>, view: View, word: Value) -> BResult<Option<Value>> {
match view.kind {
ViewKind::Storage => {
let base = fb.module().global_value(view.global)?;
let zero = k(fb, 0)?;
Ok(Some(fb.access_chain(base, &[zero, word])?))
}
ViewKind::UniformWords { .. } | ViewKind::UniformVec4 { .. } => Ok(None),
}
/// A pointer to word `word` (a `u32` index) of `view`.
pub fn word_ptr(fb: &mut FunctionBuilder<'_>, view: View, word: Value) -> BResult<Value> {
let base = fb.module().global_value(view.global)?;
let zero = k(fb, 0)?;
fb.access_chain(base, &[zero, word])
}
/// Load word `word` (a `u32` index) of `view`.
pub fn read_word(fb: &mut FunctionBuilder<'_>, view: View, word: Value) -> BResult<Value> {
let base = fb.module().global_value(view.global)?;
let zero = k(fb, 0)?;
match view.kind {
ViewKind::Storage | ViewKind::UniformWords { .. } => {
let p = fb.access_chain(base, &[zero, word])?;
fb.load(p, MemAccess::default())
}
ViewKind::UniformVec4 { .. } => {
let two = k(fb, 2)?;
let three = k(fb, 3)?;
let vi = fb.binary(BinOp::ShiftRightLogical, word, two)?;
let lane = fb.binary(BinOp::BitwiseAnd, word, three)?;
let p = fb.access_chain(base, &[zero, vi])?;
let v = fb.load(p, MemAccess::default())?;
fb.vector_extract_dynamic(v, lane)
}
}
let p = fb.access_chain(base, &[zero, word])?;
fb.load(p, MemAccess::default())
}
/// A typed narrow view of a storage slot: `StorageBuffer { u<8·bytes>[] }` at the slot's binding,
@@ -234,18 +142,16 @@ pub struct NarrowView {
pub u32_ty: TypeId,
}
/// A `uvec4` or `uvec2` view of a descriptor slot: `StorageBuffer { uvec4[] }`, `StorageBuffer {
/// uvec2[] }` or `Uniform { uvec4[N] }` at the slot's binding beside its word view, or a
/// `UniformVec4` word view itself. A unit is vector element `index` of member 0.
/// A `uvec4` or `uvec2` view of a descriptor slot: `StorageBuffer { uvec4[] }` or `StorageBuffer {
/// uvec2[] }` at the slot's binding beside its word view. A unit is vector element `index` of
/// member 0.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct VecView {
pub global: GlobalId,
/// The view's storage class: a uniform view's vectors are read-only, read plainly.
pub class: StorageClass,
}
/// The unit views of a descriptor slot beside its word view: a storage slot's narrow and `uvec2`
/// views and a storage or uniform slot's `uvec4` view.
/// The unit views of a descriptor slot beside its word view: its narrow, `uvec2` and `uvec4`
/// views.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct UnitViews {
pub u16: Option<NarrowView>,
@@ -291,57 +197,41 @@ impl UnitViews {
}
}
/// Declare the unit views of `units` for `slot`, whose word view [`declare`] declared as
/// `view`: a storage view's narrow, `uvec2` and `uvec4` views, a `UniformWords` view's `uvec4`
/// view; a `UniformVec4` view is its own `uvec4` view, declared or not. A
/// uniform slot has no narrow or `uvec2` view.
/// Declare the unit views of `units` for `slot`, whose word view [`declare`] declared.
pub fn declare(
mb: &mut ModuleBuilder,
slot: SlotRef,
view: View,
units: crate::memory::leaf::Units,
) -> BResult<UnitViews> {
let storage = view.kind == ViewKind::Storage;
Ok(UnitViews {
u16: if storage && units.u16 {
u16: if units.u16 {
Some(declare_narrow(mb, slot, 2)?)
} else {
None
},
u8: if storage && units.u8 {
u8: if units.u8 {
Some(declare_narrow(mb, slot, 1)?)
} else {
None
},
vec2: if storage && units.vec2 {
Some(declare_vec(mb, slot, view, 2)?)
vec2: if units.vec2 {
Some(declare_vec(mb, slot, 2)?)
} else {
None
},
vec4: match view.kind {
ViewKind::UniformVec4 { .. } => Some(VecView {
global: view.global,
class: StorageClass::Uniform,
}),
_ if units.vec4 => Some(declare_vec(mb, slot, view, 4)?),
_ => None,
vec4: if units.vec4 {
Some(declare_vec(mb, slot, 4)?)
} else {
None
},
})
}
}
/// Declare the `uvecN` view (`N = lanes`, 2 or 4) of `slot`, whose word view [`declare`] declared
/// as `view`: `StorageBuffer { uvecN[] }` (std430, `ArrayStride` `4N`) beside a storage view, or
/// `Uniform { uvec4[words / 4] }` (std140, valid without `uniformBufferStandardLayout`) beside a
/// `UniformWords` view, whose size is a multiple of 16 bytes ([`uniform_range`]). The serializer
/// decorates a storage one `Aliased` as every storage view of a Metal buffer. A uniform view has no
/// `uvec2` view: a std140 array's stride is 16.
pub fn declare_vec(
mb: &mut ModuleBuilder,
slot: SlotRef,
view: View,
lanes: u32,
) -> BResult<VecView> {
/// Declare the `uvecN` view (`N = lanes`, 2 or 4) of `slot`, whose word view [`declare`]
/// declared: `StorageBuffer { uvecN[] }` (std430, `ArrayStride` `4N`). The serializer decorates it
/// `Aliased` as every storage view of a Metal buffer.
pub fn declare_vec(mb: &mut ModuleBuilder, slot: SlotRef, lanes: u32) -> BResult<VecView> {
let sym = binding_symbol(slot);
let u32_ty = u32_type(mb)?;
let len = u8::try_from(lanes)
@@ -351,50 +241,17 @@ pub fn declare_vec(
crate::spirv::error::GlobalRule::ResourceType,
))?;
let vec = mb.ty(Type::Vector { elem: u32_ty, len })?;
let (class, rule, member) = match view.kind {
ViewKind::Storage => (
StorageClass::StorageBuffer,
LayoutRule::Std430,
mb.ty(Type::RuntimeArray {
elem: vec,
stride: Some(4 * lanes),
})?,
),
ViewKind::UniformWords { words } if lanes == 4 => {
let len = mb.constant(Constant::Scalar {
ty: u32_ty,
bits: ConstBits(u64::from(words / 4)),
})?;
(
StorageClass::Uniform,
LayoutRule::Std140,
mb.ty(Type::Array {
elem: vec,
len,
stride: Some(16),
})?,
)
}
// The word view is already one.
ViewKind::UniformVec4 { .. } if lanes == 4 => {
return Ok(VecView {
global: view.global,
class: StorageClass::Uniform,
})
}
ViewKind::UniformWords { .. } | ViewKind::UniformVec4 { .. } => {
return Err(crate::spirv::error::BuildError::Global(
crate::spirv::error::GlobalRule::ResourceType,
))
}
};
let layout = natural_layout(mb.types(), rule, true, &[member])?;
let member = mb.ty(Type::RuntimeArray {
elem: vec,
stride: Some(4 * lanes),
})?;
let layout = natural_layout(mb.types(), LayoutRule::Std430, true, &[member])?;
let block = mb.ty(Type::Struct {
members: [member].into(),
layout: Some(layout),
})?;
let global = mb.resource_view(sym, class, block)?;
Ok(VecView { global, class })
let global = mb.resource_view(sym, StorageClass::StorageBuffer, block)?;
Ok(VecView { global })
}
/// Load vector unit `index` of `view` with memory operands `ops`.
@@ -498,19 +355,14 @@ pub fn write_unit(
fb.store(p, x, ops)
}
/// The byte size of a storage view's bound range, as a `u32` (`OpArrayLength · 4`): the padded
/// size. A range of `2^30` words or more wraps to a smaller size, which only makes a containment
/// check stricter. `None` for a uniform view, which has no in-shader check.
pub fn storage_bytes(fb: &mut FunctionBuilder<'_>, view: View) -> BResult<Option<Value>> {
match view.kind {
ViewKind::Storage => {
let base = fb.module().global_value(view.global)?;
let len = fb.array_length(base, 0)?;
let four = k(fb, 4)?;
Ok(Some(fb.binary(BinOp::IMul, len, four)?))
}
ViewKind::UniformWords { .. } | ViewKind::UniformVec4 { .. } => Ok(None),
}
/// The byte size of a view's bound range, as a `u32` (`OpArrayLength · 4`): the padded size. A
/// range of `2^30` words or more wraps to a smaller size, which only makes a containment check
/// stricter.
pub fn storage_bytes(fb: &mut FunctionBuilder<'_>, view: View) -> BResult<Value> {
let base = fb.module().global_value(view.global)?;
let len = fb.array_length(base, 0)?;
let four = k(fb, 4)?;
fb.binary(BinOp::IMul, len, four)
}
#[cfg(test)]
@@ -518,14 +370,14 @@ mod tests {
use super::*;
#[test]
fn the_uniform_range_covers_any_start_residue() {
fn the_descriptor_range_covers_any_start_residue() {
// A 1-byte window at an odd start with 16-byte alignment: the residue can be 15, and the
// word read ends at 16.
assert_eq!(uniform_range(1, 16), Some(16));
assert_eq!(descriptor_range(1, 16), Some(16));
// The `- 4` form would give 16 here, but a window of 4 bytes starting at residue 15 reads
// up to byte 19 (word 4): the range must be 32.
assert_eq!(uniform_range(4, 16), Some(32));
assert_eq!(uniform_range(6, 256), Some(272));
assert_eq!(uniform_range(u64::MAX, 16), None);
assert_eq!(descriptor_range(4, 16), Some(32));
assert_eq!(descriptor_range(6, 256), Some(272));
assert_eq!(descriptor_range(u64::MAX, 16), None);
}
}
@@ -215,7 +215,6 @@ mod serde_round_trips {
emulated_simdgroups: true,
one_row: true,
unit_axes: 6,
storage_view_slots: BTreeSet::from([buffer(3)]),
srgb_textures: BTreeSet::from([slot(Stage::Kernel, SlotClass::Texture, 4)]),
ycbcr_in_place: BTreeSet::from([slot(Stage::Kernel, SlotClass::Texture, 7)]),
ycbcr_planes_sampled: BTreeMap::from([(
@@ -306,7 +305,6 @@ mod serde_round_trips {
d.index_buffer_index = 6;
d
}),
storage_view_slots: BTreeSet::from([buffer(4)]),
signed_color_attachments: BTreeSet::from([0, 6]),
tile_attachments: Some(BTreeMap::from([
(0, metal::PixelFormat::RGBA16Float),
@@ -569,7 +567,7 @@ mod serde_round_trips {
SlotInterface::Buffer(BufferSlot {
access: AccessSet::READ_WRITE,
window: Window::Bounded { start: -8, len: 24 },
form: BufferForm::Descriptor(DescriptorView::UniformVec4),
form: BufferForm::Descriptor,
kind: BufferKind::VisibleFunctionTable,
}),
);
@@ -847,13 +845,10 @@ mod bind_serde_round_trips {
},
);
table.threadgroup_lengths.insert(0, 1024);
table.at_bind_views = 0b101;
let mut stages = BTreeMap::new();
stages.insert(Stage::Kernel, table);
round_trip(&BindState {
stages,
view_base_alignment: 64,
uniform_views_at_residual: true,
used_resources: vec![UsedResource {
class: ResourceClass::Heap,
gpu_address: Some(0x2_0000_0000),
+19 -24
View File
@@ -10,7 +10,7 @@
//! links functions, each linked function's list, name, specialized name, specialization, AIR
//! hash, and constant values. A stage without linked functions keeps the key it had before
//! linking existed, and one
//! compiled without `emulated_simdgroups`, `one_row`, `storage_view_slots`,
//! compiled without `emulated_simdgroups`, `one_row`,
//! `signed_color_attachments`, `multisampled` or `replay_bindings` the key it had before those
//! inputs existed. A stage that links dynamic libraries records each library
//! its imports are searched in, in order (install name and content hash), and the install name
@@ -202,11 +202,6 @@ pub fn function_key(
h.bytes(b"stage-input").bytes(format!("{d:?}").as_bytes());
}
// Appended only when set, as above.
if !inputs.storage_view_slots.is_empty() {
h.bytes(b"storage-view-slots")
.bytes(format!("{:?}", inputs.storage_view_slots).as_bytes());
}
// Appended only when set, as above.
if !inputs.signed_color_attachments.is_empty() {
h.bytes(b"signed-color-attachments")
.bytes(format!("{:?}", inputs.signed_color_attachments).as_bytes());
@@ -228,67 +223,67 @@ pub fn function_key(
if inputs.merged_draws {
h.bytes(b"merged-draws");
}
// Appended only when set, as `storage_view_slots`.
// Appended only when set, as `signed_color_attachments`.
if !inputs.srgb_textures.is_empty() {
h.bytes(b"srgb-textures")
.bytes(format!("{:?}", inputs.srgb_textures).as_bytes());
}
// Appended only when set, as `storage_view_slots`.
// Appended only when set, as `signed_color_attachments`.
if !inputs.ycbcr_in_place.is_empty() {
h.bytes(b"ycbcr-in-place")
.bytes(format!("{:?}", inputs.ycbcr_in_place).as_bytes());
}
// Appended only when set, as `storage_view_slots`.
// Appended only when set, as `signed_color_attachments`.
if !inputs.ycbcr_planes_sampled.is_empty() {
h.bytes(b"ycbcr-planes-sampled")
.bytes(format!("{:?}", inputs.ycbcr_planes_sampled).as_bytes());
}
// Appended only when set, as `storage_view_slots`.
// Appended only when set, as `signed_color_attachments`.
if !inputs.texel_rows.is_empty() {
h.bytes(b"texel-rows")
.bytes(format!("{:?}", inputs.texel_rows).as_bytes());
}
// Appended only when set, as `storage_view_slots`.
// Appended only when set, as `signed_color_attachments`.
if !inputs.texel_buffer_parts.is_empty() {
h.bytes(b"texel-buffer-parts")
.bytes(format!("{:?}", inputs.texel_buffer_parts).as_bytes());
}
// Appended only when set, as `storage_view_slots`.
// Appended only when set, as `signed_color_attachments`.
if !inputs.extended_range.is_empty() {
h.bytes(b"extended-range")
.bytes(format!("{:?}", inputs.extended_range).as_bytes());
}
// Appended only when set, as `storage_view_slots`.
// Appended only when set, as `signed_color_attachments`.
if !inputs.extended_range_colors.is_empty() {
h.bytes(b"extended-range-colors")
.bytes(format!("{:?}", inputs.extended_range_colors).as_bytes());
}
// Appended only when set, as `storage_view_slots`.
// Appended only when set, as `signed_color_attachments`.
if !inputs.word_colors.is_empty() {
h.bytes(b"word-colors")
.bytes(format!("{:?}", inputs.word_colors).as_bytes());
}
// Appended only when set, as `storage_view_slots`.
// Appended only when set, as `signed_color_attachments`.
if !inputs.rotated_colors.is_empty() {
h.bytes(b"rotated-colors")
.bytes(format!("{:?}", inputs.rotated_colors).as_bytes());
}
// Appended only when set, as `storage_view_slots`.
// Appended only when set, as `signed_color_attachments`.
if !inputs.alpha_in_red_colors.is_empty() {
h.bytes(b"alpha-in-red-colors")
.bytes(format!("{:?}", inputs.alpha_in_red_colors).as_bytes());
}
// Appended only when set, as `storage_view_slots`.
// Appended only when set, as `signed_color_attachments`.
if !inputs.rotated_factors.is_empty() {
h.bytes(b"rotated-factors")
.bytes(format!("{:?}", inputs.rotated_factors).as_bytes());
}
// Appended only when set, as `storage_view_slots`.
// Appended only when set, as `signed_color_attachments`.
if !inputs.rotated_blends.is_empty() {
h.bytes(b"rotated-blends")
.bytes(format!("{:?}", inputs.rotated_blends).as_bytes());
}
// Appended only when set, as `storage_view_slots`.
// Appended only when set, as `signed_color_attachments`.
if !inputs.swizzled_storage.is_empty() {
h.bytes(b"swizzled-storage")
.bytes(format!("{:?}", inputs.swizzled_storage).as_bytes());
@@ -427,13 +422,13 @@ pub fn function_key(
if inputs.threadgroup_size_matches_tile_size {
h.bytes(b"threadgroup-size-matches-tile-size");
}
// Appended only when set, as `storage_view_slots`: a texture whose map is the identity keeps
// Appended only when set, as `signed_color_attachments`: a texture whose map is the identity keeps
// every key.
if !inputs.address_maps.is_empty() {
h.bytes(b"address-maps")
.bytes(format!("{:?}", inputs.address_maps).as_bytes());
}
// Appended only when set, as `storage_view_slots`.
// Appended only when set, as `signed_color_attachments`.
if !inputs.cubic_samplers.is_empty() {
h.bytes(b"cubic-samplers")
.bytes(format!("{:?}", inputs.cubic_samplers).as_bytes());
@@ -442,18 +437,18 @@ pub fn function_key(
if inputs.texture_write_rounding != crate::metal::TextureWriteRoundingMode::TowardZero {
h.bytes(b"texture-write-rounding-nearest-even");
}
// Appended only when set, as `storage_view_slots`.
// Appended only when set, as `signed_color_attachments`.
if !inputs.cross_class.is_empty() {
h.bytes(b"cross-class")
.bytes(format!("{:?}", inputs.cross_class).as_bytes());
}
// Appended only when set, as `storage_view_slots`: a function bound to no anisotropic
// Appended only when set, as `signed_color_attachments`: a function bound to no anisotropic
// sampler keeps every key.
if !inputs.anisotropic_samplers.is_empty() {
h.bytes(b"anisotropic-samplers")
.bytes(format!("{:?}", inputs.anisotropic_samplers).as_bytes());
}
// Appended only when set, as `storage_view_slots`: a kernel whose 1D images are bound as Apple's
// Appended only when set, as `signed_color_attachments`: a kernel whose 1D images are bound as Apple's
// OpenCL binds them keeps its key.
if !inputs.open_cl_lines.is_empty() {
h.bytes(b"open-cl-lines")
@@ -643,7 +643,6 @@ fn the_inputs_encoding_is_the_earlier_derived_debug() {
.replace(", emulated_simdgroups: false", "")
.replace(", one_row: false", "")
.replace(", stage_input: None", "")
.replace(", storage_view_slots: {}", "")
.replace(", signed_color_attachments: {}", "")
.replace(", tile_attachments: None", "")
.replace(", multisampled: false", "")
+1 -32
View File
@@ -1,4 +1,4 @@
//! `RuntimeFact`, `Mechanism`, and `UniformViewChoice`.
//! `RuntimeFact` and `Mechanism`.
//!
//! `RuntimeFact` is the single dependency vocabulary: `select` emits facts, the planner supplies
//! their values, and `device::mechanism(fact, profile)` is a total function with one [`Mechanism`]
@@ -106,22 +106,6 @@ pub enum RuntimeFact {
/// without one, as Metal reads it (`MTLAttributeStrideStatic` is its low 32 bits). A layout of a fixed stride reads its own, compiled in,
/// whatever the bind's, and records nothing.
StageInStride { layout: u32 },
/// A read-only slot that Profile F's per-stage storage-buffer fallback may read through a
/// uniform view, whose window does not bound its descriptor range within
/// `maxUniformBufferRange` (a `Whole` window, or a longer `Bounded` one): the view is exact
/// only where the range the shape binds fits. `choice` states what this compile made of it.
/// A plan whose shape does not prove the fit for a `Viewed` slot asks for the variant that
/// keeps every such slot a storage view (`VariantKey::storage_view_slots`); instantiation
/// refuses a range above the limit (`BindError::DescriptorRangeExceeded`).
UniformViewRange {
slot: SlotRef,
choice: UniformViewChoice,
},
/// A `device` slot read through a uniform view (Profile F's per-stage storage-buffer
/// fallback). A uniform view need not observe what the dispatch or draw itself writes, so no
/// buffer slot the pipeline writes may be bound overlapping its window: instantiation checks
/// the Metal addresses (`BindError::UniformViewAliased`).
UniformViewAliasing { slot: SlotRef },
/// The kernel is a tile function (`Device::compile_tile_pipeline`): a dispatch covers the
/// render pass's render area (`BindState::render_area`, `SpecKey::RenderAreaWidth` and
/// `SpecKey::RenderAreaHeight`) in tiles of the imageblock size (`BindState::imageblock_size`),
@@ -701,8 +685,6 @@ impl RuntimeFact {
RuntimeFact::RenderTargetArrayLength { .. } => "RenderTargetArrayLength",
RuntimeFact::StageInRegion => "StageInRegion",
RuntimeFact::StageInStride { .. } => "StageInStride",
RuntimeFact::UniformViewRange { .. } => "UniformViewRange",
RuntimeFact::UniformViewAliasing { .. } => "UniformViewAliasing",
RuntimeFact::TileFunction => "TileFunction",
RuntimeFact::TileAttachmentFormat { .. } => "TileAttachmentFormat",
RuntimeFact::StorageTextureNumericType { .. } => "StorageTextureNumericType",
@@ -770,19 +752,6 @@ impl RuntimeFact {
}
}
/// What one compile made of a slot of a `RuntimeFact::UniformViewRange`.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum UniformViewChoice {
/// A uniform view.
Viewed,
/// A storage view the fallback did not need to move.
Spare,
/// A storage view the compile's `LoweringInputs::storage_view_slots` keeps one.
Kept,
}
/// How a profile honors one runtime fact.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+2 -43
View File
@@ -264,54 +264,13 @@ pub enum Window {
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum BufferForm {
/// Through a descriptor of this view kind.
Descriptor(DescriptorView),
/// Through its storage buffer descriptor.
Descriptor,
/// Through a buffer device address (dynamic roots, per-stage limit fallback, or a
/// `BufferRangeLimit` variant); the bound buffer needs a device address.
Psb,
}
impl BufferForm {
/// Whether the form reads through a uniform view, a uniform buffer: the views whose range a
/// plan starts at the bind offset where the device's view base alignment divides it
/// (`SpecKey::RangeAtBindOffset`, `BindState::view_base_alignment`).
pub fn uniform_view(self) -> bool {
matches!(
self,
BufferForm::Descriptor(DescriptorView::UniformWords | DescriptorView::UniformVec4)
)
}
/// The minimum offset alignment and the maximum range, in bytes, of the form's view on a
/// device of `limits`: the uniform-buffer limits for a uniform view, the storage-buffer limits
/// otherwise.
pub(crate) fn view_limits(self, limits: &crate::device::Limits) -> (u64, u64) {
match self {
form if form.uniform_view() => (
limits.min_uniform_buffer_offset_alignment,
u64::from(limits.max_uniform_buffer_range),
),
_ => (
limits.min_storage_buffer_offset_alignment,
u64::from(limits.max_storage_buffer_range),
),
}
}
}
/// The descriptor view kind of a descriptor-form slot.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum DescriptorView {
/// A storage buffer.
Storage,
/// A uniform buffer viewed as `u32[]` (needs `uniformBufferStandardLayout`).
UniformWords,
/// A uniform buffer viewed as a `uvec4` array (std140-valid everywhere).
UniformVec4,
}
/// How a compiled function fetches one attribute it reads
/// ([`CompiledFunction::attribute_fetches`](crate::library::CompiledFunction::attribute_fetches)).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
@@ -56,13 +56,6 @@ pub struct LoweringInputs {
/// compiles as without it.
#[cfg_attr(feature = "serde", serde(default))]
pub stage_input: Option<StageInputDescriptor>,
/// Read-only slots that Profile F's per-stage storage-buffer fallback keeps as storage views
/// (`VariantKey::storage_view_slots`): the shape binds them where a uniform view's range may
/// exceed `maxUniformBufferRange`. The fallback views other read-only slots as uniform buffers
/// instead, and the function depends on `RuntimeFact::UniformViewRange` with
/// `UniformViewChoice::Kept` for each of them; a slot the fallback cannot consider is ignored.
#[cfg_attr(feature = "serde", serde(default))]
pub storage_view_slots: BTreeSet<SlotRef>,
/// The color attachments a fragment function writes that its render pipeline gives a
/// signed-integer pixel format (`MTLRenderPipelineColorAttachmentDescriptor.pixelFormat`). A
/// 32-bit integer color output to one is declared `int`, because Vulkan writes a signed-integer
+5 -5
View File
@@ -123,10 +123,10 @@ pub use graphics::{
};
pub use indirect_draws::IndirectDrawLayout;
pub use interface::{
AccessSet, AttributeFetch, BufferForm, BufferKind, BufferSlot, CommandWrites, DescriptorView,
LevelReads, NumberedSampler, PatchDomain, PipelineInterface, PlacedField, PushLoc,
PushPlacement, SampledLevels, SamplerArray, SamplerLevels, SamplerSlot, SlotInterface,
TextureAccess, TextureSlot, ThreadgroupArgument, Window,
AccessSet, AttributeFetch, BufferForm, BufferKind, BufferSlot, CommandWrites, LevelReads,
NumberedSampler, PatchDomain, PipelineInterface, PlacedField, PushLoc, PushPlacement,
SampledLevels, SamplerArray, SamplerLevels, SamplerSlot, SlotInterface, TextureAccess,
TextureSlot, ThreadgroupArgument, Window,
};
pub use layout::{
BindingSource, DescriptorBinding, DescriptorSetLayout, PipelineLayout, PushConstantRange,
@@ -146,7 +146,7 @@ pub use compile::{
EntryDescriptor, EntryPlan, EntryRef, LinkedSource, StageEntries, StandaloneModule,
COMPILED_STAGE_WEIGHT,
};
pub use facts::{Mechanism, RuntimeFact, UniformViewChoice};
pub use facts::{Mechanism, RuntimeFact};
// The `DispatchRegion` push field's bytes, which a consumer of the identity domains pushes with
// each dispatch, the tile a kernel's grid tiles cover a grid with (`RuntimeFact::GridTiles`), and
// the depth past which a threadgroup runs as one row (`SpecKey::DeepThreadgroup`).
-11
View File
@@ -663,17 +663,6 @@ pub enum SpecKey {
/// device's sampler reads exactly the texel Metal's reads. A slot bound to a normalized sampler,
/// or to none, takes false, so a normalized sampler's filter makes no pipeline of its own.
NearestPixelSampler(SlotRef),
/// Boolean: the descriptor range bound at the buffer slot, which the function reads through a
/// uniform view, starts at the bind offset, so its `SlotBindOffset` residual is 0 (default
/// false): the slot holds inline bytes, which the consumer places at an aligned offset, or a
/// buffer at an offset that is a multiple of the view's descriptor base alignment
/// (`max(minUniformBufferOffsetAlignment, 16)`), under a window that starts in the range's
/// first aligned block. A slot bound to nothing takes true: its residual is 0. Where it holds,
/// the function reads the slot at the Metal offset alone, a constant for a constant member,
/// which a driver can load into registers ahead of the shader (Mesa's ANV does so only for a
/// uniform load at a constant offset); elsewhere at the residual plus the offset. Only a slot
/// read through a uniform view declares it.
RangeAtBindOffset(SlotRef),
/// The word of the runtime sampler bound to the slot (`u32`: its whole
/// [`SamplerWord`](crate::metal::sampler::SamplerWord), its address modes as the bound
/// texture's map sends them), read by a specialized note's test alone
+4 -4
View File
@@ -1,8 +1,8 @@
//! Loads of uniform views that every trip of a loop reads alike, moved out of the loop.
//!
//! A kernel that reads its parameters from a `constant` buffer inside a loop often reads them again
//! on every trip, inside the branches of the loop body, because nothing told its compiler the
//! address cannot be read out of bounds. A driver's compiler keeps such a load where it stands
//! A kernel that reads its parameters inside a loop often reads them again on every trip, inside
//! the branches of the loop body, because nothing told its compiler the address cannot be read out
//! of bounds. A driver's compiler keeps such a load where it stands
//! too: it does not move a load out of a branch. On a 1x1 convolution kernel whose outer loop
//! read 13 such words on each of its trips, the same module with those loads in the loop's
//! preheader ran 13% faster at 120 trips and 3.8% at 24 on an RX 7900 XTX (RADV), and 3.6% faster
@@ -15,7 +15,7 @@
//!
//! - **A uniform view.** The load reads, through a chain of access indices, a module-scope
//! `Uniform` variable that is a descriptor resource whose type is a `Block` structure:
//! `memory::views` declares one only for a read-only buffer slot, and no shader writes a
//! `lower::access::table` declares one for the spilled push fields, and no shader writes a
//! `Uniform` block. The load is neither volatile nor `MakePointerVisible`.
//! - **The same address on every trip.** Every operand of its address is defined outside the loop,
//! or by an instruction inside it that computes its value from its operands alone (arithmetic,
+30 -14
View File
@@ -4,7 +4,7 @@
use super::*;
use crate::budget::Budget;
use crate::device::profile::DeviceProfile;
use crate::memory::views::{declare_at, read_word, View, ViewKind};
use crate::memory::views::{declare_at, read_word, View};
use crate::pipeline::sym::{ResourceKind, ResourceSlot, Stage};
use crate::spirv::builder::constructs::{ArmEnd, LoopSpec};
use crate::spirv::builder::{FunctionBuilder, ModuleBuilder};
@@ -76,22 +76,38 @@ enum Shape {
FromStorage,
}
/// A uniform view at `sym`: a `Uniform` block `{ u32 words[8]; }` (std430 in `Uniform`, under
/// `uniformBufferStandardLayout`), read through `memory::views` as a storage view's words are.
fn uniform_words(mb: &mut ModuleBuilder, sym: ResourceSlot) -> BResult<View> {
let u32_ty = mb.ty(Type::Int {
width: 32,
signed: false,
})?;
let len = mb.constant(Constant::Scalar {
ty: u32_ty,
bits: ConstBits(8),
})?;
let member = mb.ty(Type::Array {
elem: u32_ty,
len,
stride: Some(4),
})?;
let layout = natural_layout(mb.types(), LayoutRule::Std430, true, &[member])?;
let block = mb.ty(Type::Struct {
members: [member].into(),
layout: Some(layout),
})?;
let global = mb.resource(sym, StorageClass::Uniform, block)?;
Ok(View { global, u32_ty })
}
/// `p` the uniform view (slot 1) of 8 words, `in` and `out` storage buffers (slots 0 and 2):
/// `n = in[0]`, `k = in[1]`, then `acc` summed over `n` trips as `shape` says, and `out[0] = acc`.
fn kernel(shape: Shape) -> TypedModule {
kernel_of(shape, ViewKind::UniformWords { words: 8 })
}
/// [`kernel`], its uniform view `p` of the view kind `kind`, read through `memory::views`.
fn kernel_of(shape: Shape, kind: ViewKind) -> TypedModule {
let mut b = ModuleBuilder::new();
let input = declare_at(&mut b, slot(0), ViewKind::Storage)
.expect("in")
.global;
let p: View = declare_at(&mut b, slot(1), kind).expect("p");
let out = declare_at(&mut b, slot(2), ViewKind::Storage)
.expect("out")
.global;
let input = declare_at(&mut b, slot(0)).expect("in").global;
let p = uniform_words(&mut b, slot(1)).expect("p");
let out = declare_at(&mut b, slot(2)).expect("out").global;
let void = b.ty(Type::Void).expect("void");
let mut f = b.function(void).expect("function");
let body = |f: &mut FunctionBuilder<'_>| -> BResult<()> {
@@ -327,7 +343,7 @@ fn loads_a_trip_or_a_buffer_write_may_change_stay() {
/// No module holds a `Uniform` resource that is not a `Block` (what `BufferBlock` decorates in
/// old SPIR-V: a writable buffer; the crate's grammar names no `BufferBlock`): the builder refuses
/// one. The crate's own uniform view is a view.
/// one. A `Uniform` block is a view.
#[test]
fn only_a_block_is_a_uniform_view() {
let mut b = ModuleBuilder::new();
+37 -64
View File
@@ -25,9 +25,9 @@ fn buffer(length: u64, offset: u64) -> BoundBuffer {
}
}
/// Buffer range limits of `uniform` and `storage` bytes.
fn ranges(uniform: u32, storage: u32) -> BufferRanges {
BufferRanges { uniform, storage }
/// A buffer range limit of `storage` bytes.
fn ranges(storage: u32) -> BufferRanges {
BufferRanges { storage }
}
/// A 2D texture of `format`.
@@ -119,28 +119,14 @@ fn states() -> Vec<BindState> {
with(|s| {
vertex(s).buffers.insert(0, buffer(256, 2));
}),
// Buffer range limits that tell the buffer's class apart, of the base's shape; limits of
// 4 GiB, which tell apart no class of either length, of one other shape twice.
with(|s| vertex(s).buffer_ranges = ranges(255, 255)),
with(|s| vertex(s).buffer_ranges = ranges(u32::MAX, u32::MAX)),
// A buffer range limit that tells the buffer's class apart, of the base's shape; a limit
// of 4 GiB, which tells apart no class of either length, of one other shape twice.
with(|s| vertex(s).buffer_ranges = ranges(255)),
with(|s| vertex(s).buffer_ranges = ranges(u32::MAX)),
with(|s| {
vertex(s).buffer_ranges = ranges(u32::MAX, u32::MAX);
vertex(s).buffer_ranges = ranges(u32::MAX);
vertex(s).buffers.insert(0, buffer(1 << 20, 0));
}),
// A view base alignment no slot tells apart, or a slot that tells apart none, or one
// that tells it apart at an offset it does not divide, all of the base's shape; one that
// tells it apart where it divides the offset, of another.
with(|s| s.view_base_alignment = 64),
with(|s| vertex(s).at_bind_views = 1),
with(|s| {
s.view_base_alignment = 64;
vertex(s).at_bind_views = 1;
vertex(s).buffers.insert(0, buffer(256, 16));
}),
with(|s| {
s.view_base_alignment = 64;
vertex(s).at_bind_views = 1;
}),
with(|s| {
vertex(s).buffers.insert(
0,
@@ -269,48 +255,40 @@ fn a_state_has_exactly_the_shape_it_makes() {
);
}
}
// The states of the base's shape (the base, the four its comment names, the one of buffer
// range limits that tell its class apart, the three of a view base alignment told apart
// nowhere it divides an offset, and the base with another argument sampler of the same
// shape), the two of 4 GiB limits and the used resources' two of one shape: each against the
// others of its shape.
assert_eq!(same, 10 * 9 + 2 + 2, "pairs of one shape");
// The states of the base's shape (the base, the four its comment names, the one of a buffer
// range limit that tells its class apart, and the base with another argument sampler of the
// same shape), the two of a 4 GiB limit and the used resources' two of one shape: each
// against the others of its shape.
assert_eq!(same, 7 * 6 + 2 + 2, "pairs of one shape");
}
/// A buffer's bind offset cycling through the multiples of 16 up to 256 at a view base alignment
/// of 64 keeps one shape where its slot tells no alignment past 4 apart (vertex data, or a view
/// a runtime left out), and takes two where the slot tells it apart (a uniform view: 64 divides
/// the offset or not): none past those two, and none new on a second cycle.
/// A buffer's bind offset cycling through the multiples of 16 up to 256 keeps one shape: no
/// alignment past 4 is told apart, and no shape is new on a second cycle.
#[test]
fn a_slot_s_offsets_moving_among_multiples_of_16_keep_their_shapes() {
for (views, shapes) in [(0, 1), (1, 2)] {
let mut seen = Vec::new();
for cycle in 0..2 {
for offset in (16..=256).step_by(16) {
let state = with(|s| {
s.view_base_alignment = 64;
vertex(s).at_bind_views = views;
vertex(s).buffers.insert(0, buffer(4096, offset));
});
let shape = state.shape();
if !seen.contains(&shape) {
assert_eq!(
cycle, 0,
"a new shape at offset {offset} on the second cycle"
);
seen.push(shape);
}
let mut seen = Vec::new();
for cycle in 0..2 {
for offset in (16..=256).step_by(16) {
let state = with(|s| {
vertex(s).buffers.insert(0, buffer(4096, offset));
});
let shape = state.shape();
if !seen.contains(&shape) {
assert_eq!(
cycle, 0,
"a new shape at offset {offset} on the second cycle"
);
seen.push(shape);
}
}
assert_eq!(seen.len(), shapes, "slots telling apart {views:#b}");
}
assert_eq!(seen.len(), 1);
}
/// `BoundBuffer::same_shape` answers `a.shape(x, r) == b.shape(x, r)` for every pair of bindings
/// over lengths of one length class and of others, bind offsets of one alignment class and of
/// others, with and without a device address and a stride, and inline bytes, at view base
/// alignments that tell no offset class past the vertex fetch's apart and one that does, under
/// buffer range limits that tell every length class apart, some, and few.
/// `BoundBuffer::same_shape` answers `a.shape(r) == b.shape(r)` for every pair of bindings over
/// lengths of one length class and of others, bind offsets of one alignment class and of others,
/// with and without a device address and a stride, and inline bytes, under buffer range limits
/// that tell every length class apart, some, and few.
#[test]
fn a_buffer_binding_has_the_shape_of_another_exactly_where_their_shapes_compare_equal() {
let mut bindings = Vec::new();
@@ -341,19 +319,14 @@ fn a_buffer_binding_has_the_shape_of_another_exactly_where_their_shapes_compare_
}
}
let (mut alike, mut apart) = (0, 0);
let limits = [
ranges(0, 0),
ranges(1 << 16, 1 << 27),
ranges(u32::MAX, u32::MAX),
];
for (alignment, r) in [0, 4, 64].into_iter().flat_map(|a| limits.map(|r| (a, r))) {
for r in [ranges(0), ranges(1 << 16), ranges(u32::MAX)] {
for (at, binding) in bindings.iter().enumerate() {
for (of, other) in bindings.iter().enumerate() {
let equal = binding.shape(alignment, r) == other.shape(alignment, r);
let equal = binding.shape(r) == other.shape(r);
assert_eq!(
binding.same_shape(other, alignment, r),
binding.same_shape(other, r),
equal,
"binding {at} against binding {of} at alignment {alignment} under {r:?}"
"binding {at} against binding {of} under {r:?}"
);
alike += usize::from(equal && at != of);
apart += usize::from(!equal);
+64 -679
View File
@@ -9,9 +9,8 @@
//! encoding no access traps, an in-bounds access is exact (a `half` NaN loaded a NaN where the
//! module reads a `half` by the device's widening, `PrecisionNote::NativeNanEncoding`), and an
//! out-of-bounds load is 0 and an out-of-bounds store changes nothing.
//! - Slot forms: the `constant` fixture gets a uniform view (`u32[]` with standard layout,
//! `uvec4[]` without) with robust descriptors and a storage view in shader, where an allocation
//! shorter than the window is contained; several slots are storage views decorated `Aliased`, a
//! - Slot forms: the `constant` fixture gets a storage view, where an allocation shorter than the
//! window is contained in shader; several slots are storage views decorated `Aliased`, a
//! pointer selected between two slots is dispatched by root, and a `Whole` window declares
//! `BufferRangeLimit`.
//! - Device addresses (Profile A): a `BufferRangeLimit` variant and the per-stage
@@ -27,7 +26,7 @@
//!
//! `llvm-as` assembles the fixtures; without it the tests skip visibly.
use std::collections::{BTreeMap, BTreeSet};
use std::collections::BTreeMap;
use std::path::Path;
use std::sync::atomic::{AtomicU64, Ordering};
@@ -43,8 +42,8 @@ use crate::lower::select::{select, LowerInputs, Plan};
use crate::lower::simd::WidestPin;
use crate::memory::static_root::analyze_memory;
use crate::pipeline::compile::{compile_bitcode, plan_bitcode, EntryRef};
use crate::pipeline::facts::{RuntimeFact, UniformViewChoice};
use crate::pipeline::interface::{BufferForm, DescriptorView, PushLoc, SlotInterface, Window};
use crate::pipeline::facts::RuntimeFact;
use crate::pipeline::interface::{BufferForm, PushLoc, SlotInterface, Window};
use crate::pipeline::sym::{
Axis, PushField, ResourceKind, ResourceSlot, SlotClass, SlotRef, SpecKey, Stage, Symbol,
};
@@ -53,9 +52,7 @@ use crate::pipeline::testing::{
AssembleError,
};
use crate::spirv::interp::{run, Buffer, Config, InterpError, Resources};
use crate::spirv::ir::{
ConstBits, ConstKind, GlobalKind, Inst, StorageClass, Type, TypedModule, ValueOrigin,
};
use crate::spirv::ir::{GlobalKind, TypedModule};
use crate::spirv::verify::verify;
/// Profiles with and without 64-bit integers and 8/16-bit storage.
@@ -65,9 +62,8 @@ fn policy() -> DevicePolicy {
DevicePolicy::RESIDENT_TABLES
}
/// Committed profile `stem`, optionally with buffer robustness disabled (the in-shader encoding)
/// and optionally without `uniformBufferStandardLayout`.
fn profile_with(stem: &str, robust: bool, standard_layout: bool) -> DeviceProfile {
/// Committed profile `stem`, optionally with buffer robustness disabled (the in-shader encoding).
fn profile_with(stem: &str, robust: bool) -> DeviceProfile {
let path = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../metal2vulkan-validation/profiles")
.join(format!("{stem}.json"));
@@ -77,10 +73,6 @@ fn profile_with(stem: &str, robust: bool, standard_layout: bool) -> DeviceProfil
desc.features.remove(&VkFeature::RobustBufferAccess);
desc.features.remove(&VkFeature::RobustBufferAccess2);
}
if !standard_layout {
desc.features
.remove(&VkFeature::UniformBufferStandardLayout);
}
Device::from_queries(desc, policy())
.expect("device")
.profile()
@@ -179,7 +171,7 @@ fn encodings() -> Vec<(String, DeviceProfile)> {
for robust in [true, false] {
out.push((
format!("{stem} robust={robust}"),
profile_with(stem, robust, true),
profile_with(stem, robust),
));
}
}
@@ -256,352 +248,11 @@ fn a_byte_store_at_the_end_preserves_its_neighbours() {
}
}
/// The `constant` fixture's slot is a uniform view (`u32[]` with `uniformBufferStandardLayout`,
/// `uvec4[]` without) and reads the last byte exactly.
#[test]
fn a_bounded_constant_buffer_is_a_uniform_view() {
let Some(bc) = assemble_file("buffer_end_byte_load_constant") else {
return;
};
let data = [9u8, 8, 7, 6, 5, 0xC3];
for stem in PROFILES {
for standard in [true, false] {
// Robust descriptors only: the in-shader encoding uses a storage view.
let what = format!("{stem} standard={standard}");
let p = profile_with(stem, true, standard);
let a = compile(&bc, "buffer_end_byte_load_constant", &p)
.unwrap_or_else(|e| panic!("{what}: {e}"));
let form = match a.interface.slots.get(&sref(0)) {
Some(SlotInterface::Buffer(b)) => b.form,
other => panic!("{what}: {other:?}"),
};
let want = if standard {
DescriptorView::UniformWords
} else {
DescriptorView::UniformVec4
};
assert_eq!(form, BufferForm::Descriptor(want), "{what}");
link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}"));
let (plan, m) = typed_module(&bc, "buffer_end_byte_load_constant", &p).expect("module");
for r in [0u32, 4] {
// The uniform view spans `uniform_range(1, align)` bytes. The interpreter models
// no robustness, so this in-bounds run binds that much.
let mut ubo = bound(0, r, &data, 0x44);
ubo.bytes.resize(ubo.bytes.len().max(512), 0x44);
let res = Resources {
buffers: vec![ubo, bound(1, 0, &[0; 4], 0)],
push: push_bytes(&plan, &[(0, r)]),
spec: Default::default(),
};
let out = run(&m, &Config::default(), res).expect("run");
assert_eq!(out.buffers[1][..4], [0xC3, 0, 0, 0], "{what} r={r}");
}
}
}
}
/// A uniform view's slot declares its `RangeAtBindOffset` specialization: where the binder states
/// the range starts at the bind offset, the read takes the Metal offset alone, whatever the
/// residual pushed (an alignment-checked binder pushes 0 there); elsewhere the residual plus the
/// offset, as before. With `uniformBufferStandardLayout` (`u32[]`) and without (`uvec4[]`).
#[test]
fn a_uniform_view_read_at_its_bind_offset_drops_the_residual() {
let Some(bc) = assemble_file("buffer_end_byte_load_constant") else {
return;
};
let data = [9u8, 8, 7, 6, 5, 0xC3];
let key = SpecKey::RangeAtBindOffset(sref(0));
for stem in PROFILES {
for standard in [true, false] {
let what = format!("{stem} standard={standard}");
let p = profile_with(stem, true, standard);
let a = compile(&bc, "buffer_end_byte_load_constant", &p)
.unwrap_or_else(|e| panic!("{what}: {e}"));
assert!(a.interface.read_keys().contains(&key), "{what}");
let (plan, m) = typed_module(&bc, "buffer_end_byte_load_constant", &p).expect("module");
// The data at byte 0, a residual of 8 pushed: byte 5 when the range starts at the bind
// offset, byte 13 (the padding) when it does not.
for (at_bind, want) in [(1u64, 0xC3u8), (0, 0x44)] {
let mut ubo = bound(0, 0, &data, 0x44);
ubo.bytes.resize(512, 0x44);
let res = Resources {
buffers: vec![ubo, bound(1, 0, &[0; 4], 0)],
push: push_bytes(&plan, &[(0, 8)]),
spec: [(key, at_bind)].into(),
};
let out = run(&m, &Config::default(), res).expect("run");
assert_eq!(
out.buffers[1][..4],
[want, 0, 0, 0],
"{what} at_bind={at_bind}"
);
}
}
}
}
/// The Iris Xe RPL-P under ANV, a profile with `uniformBufferStandardLayout`.
const AT_BIND_PROFILE: &str = "intel-irisxe-rplp-anv";
/// Whether a function of `m` reads push member `field` with the specialization constant of `key`
/// at `value`: whether a value the member's word reaches is read by an instruction other than one
/// that computes its own result from its operands alone (`spirv::dead::removable`, a result the
/// word reaches in turn), or a terminator. An `OpSelect` on the key's constant reaches only the
/// arm the value takes, as a driver folds it once the constant is specialized; then every value
/// the word reaches is dead, and the driver's dead-code removal drops the push read itself.
fn reads_push_word(m: &TypedModule, field: PushField, (key, value): (SpecKey, bool)) -> bool {
let Some(member) = m.push_members().iter().find(|p| p.field == field) else {
return false;
};
let member = ConstBits(u64::from(member.index));
let push = m.globals().iter().find(|g| g.kind == GlobalKind::PushBlock);
let push = push.map(|g| g.value);
let cond = m.consts().iter().find_map(|(c, d)| match &d.kind {
ConstKind::Spec { key: k, .. } if *k == key => m.const_value(c).ok(),
_ => None,
});
let is_member = |v| match m.value(v).map(|d| d.origin) {
Ok(ValueOrigin::Const(c)) => m.consts().scalar_bits(c) == Some(member),
_ => false,
};
// The arm `inst` reads its reached operands through: a select on the key's constant reads
// only the arm it takes.
let reads = |inst: &Inst, reached: &BTreeSet<crate::spirv::ids::Value>| match inst {
Inst::Select { cond: c, t, f } if Some(*c) == cond => {
reached.contains(if value { t } else { f })
}
_ => {
let mut any = false;
inst.for_each_value(|v| any |= reached.contains(&v));
any
}
};
let mut reached = BTreeSet::new();
loop {
let before = reached.len();
for blk in m.blocks() {
for phi in &blk.phis {
if phi.incoming.iter().any(|(v, _)| reached.contains(v)) {
reached.insert(phi.result);
}
}
for node in &blk.insts {
let Some(r) = node.result else { continue };
let reaches = match &node.inst {
Inst::AccessChain { base, indices, .. } if Some(*base) == push => {
indices.first().is_some_and(|&i| is_member(i))
}
inst => reads(inst, &reached),
};
if reaches {
reached.insert(r);
}
}
}
if reached.len() == before {
break;
}
}
m.blocks().iter().any(|blk| {
let mut term = false;
blk.term.for_each_value(|v| term |= reached.contains(&v));
term || blk.insts.iter().any(|node| {
let pure = node.result.is_some_and(|r| reached.contains(&r))
&& crate::spirv::dead::removable(&node.inst);
reads(&node.inst, &reached) && !pure
})
})
}
/// On every tested profile, Intel's ANV on two GPUs among them, no storage view declares
/// `RangeAtBindOffset`: the key a binder sets stays absent, and every access reads the slot's
/// `SlotBindOffset` residual.
#[test]
fn a_storage_view_reads_its_residual() {
let Some(bc) = assemble_file("buffer_end_byte_load") else {
return;
};
let key = SpecKey::RangeAtBindOffset(sref(0));
let field = PushField::SlotBindOffset(sref(0));
for stem in PROFILES
.into_iter()
.chain([AT_BIND_PROFILE, "intel-irisxe-anv"])
{
for robust in [true, false] {
let what = format!("{stem} robust={robust}");
let p = profile_with(stem, robust, true);
let a =
compile(&bc, "buffer_end_byte_load", &p).unwrap_or_else(|e| panic!("{what}: {e}"));
assert!(!a.interface.read_keys().contains(&key), "{what}");
let (_, m) = typed_module(&bc, "buffer_end_byte_load", &p).expect("module");
assert!(reads_push_word(&m, field, (key, true)), "{what}");
}
}
}
/// A kernel's `constant` slot reads through a uniform view, and its layout binds nothing for it
/// but that view: on Intel's Iris Xe RPL-P under ANV, with `uniformBufferStandardLayout`
/// (`u32[]`) and without (`uvec4[]`), the slot's form is the
/// plain uniform view, its `RangeAtBindOffset` key is read, and set 0 holds the slot's uniform
/// binding and the written slot's storage binding alone, numbered densely; a plan of nothing
/// bound writes those two, a uniform buffer and a storage buffer, and nothing else in set 0. On
/// every other tested profile the plan writes the two slots alone as well.
#[test]
fn a_kernel_constant_slot_binds_its_uniform_view_alone() {
use crate::bind::{BindState, DescriptorWrite};
use crate::pipeline::layout::BindingSource;
use crate::pipeline::{ComputePipelineDescriptor, FunctionDescriptor, StageSource};
let entry = "buffer_end_byte_load_constant";
let Some(bc) = assemble_file(entry) else {
return;
};
for (standard, view) in [
(true, DescriptorView::UniformWords),
(false, DescriptorView::UniformVec4),
] {
let what = format!("standard={standard}");
let p = profile_with(AT_BIND_PROFILE, true, standard);
let a = compile(&bc, entry, &p).unwrap_or_else(|e| panic!("{what}: {e}"));
let form = |index: u32| match a.interface.slots.get(&sref(index)) {
Some(SlotInterface::Buffer(b)) => b.form,
other => panic!("{what}: slot {index}: {other:?}"),
};
assert_eq!(form(0), BufferForm::Descriptor(view), "{what}");
assert_eq!(
form(1),
BufferForm::Descriptor(DescriptorView::Storage),
"{what}"
);
let key = SpecKey::RangeAtBindOffset(sref(0));
assert!(a.interface.read_keys().contains(&key), "{what}");
let (table, _) = link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}"));
let set0: BTreeMap<ResourceSlot, (u32, u32)> = (table.bindings.iter())
.filter(|(_, at)| at.0 == 0)
.map(|(s, at)| (*s, *at))
.collect();
assert_eq!(
set0,
BTreeMap::from([(kslot(0), (0, 0)), (kslot(1), (0, 1))]),
"{what}"
);
}
let library = crate::library::Library::from_air(&bc).expect("library");
for stem in [AT_BIND_PROFILE].into_iter().chain(PROFILES) {
let device = super::engine_argument_tables::device(stem);
let descriptor = ComputePipelineDescriptor::new(StageSource::Function(
FunctionDescriptor::new(library.function(entry).expect("entry")),
));
let pipeline = device
.compile_compute_pipeline(&descriptor, &crate::budget::Budget::standard())
.unwrap_or_else(|e| panic!("{stem}: {e}"));
let plan = pipeline
.plan(&device, &BindState::default().shape())
.unwrap_or_else(|e| panic!("{stem}: {e}"));
let source = |write: &DescriptorWrite| {
(pipeline.layout.sets.iter())
.filter(|set| set.set == write.set)
.flat_map(|set| &set.bindings)
.find(|b| b.binding == write.binding)
.map(|b| b.source)
};
let set0: BTreeMap<_, _> = (plan.descriptors.iter())
.filter(|write| write.set == 0)
.map(|write| (source(write), write.ty))
.collect();
let slots = BTreeSet::from([
Some(BindingSource::Buffer(sref(0))),
Some(BindingSource::Buffer(sref(1))),
]);
assert_eq!(
set0.keys().cloned().collect::<BTreeSet<_>>(),
slots,
"{stem}"
);
if stem == AT_BIND_PROFILE {
assert_eq!(
set0.values().copied().collect::<Vec<_>>(),
[
crate::vk::DescriptorType::UNIFORM_BUFFER,
crate::vk::DescriptorType::STORAGE_BUFFER
],
"{stem}"
);
}
}
}
/// A `constant` struct of 6 bytes whose first and last bytes are read: its window starts at 0.
const CONSTANT_ENDS: &str = r#"define void @constant_ends(ptr addrspace(2) noundef "air-buffer-no-alias" %0, ptr addrspace(1) noundef "air-buffer-no-alias" %1) {
entry:
%a = load i8, ptr addrspace(2) %0, align 1
%p = getelementptr inbounds i8, ptr addrspace(2) %0, i64 5
%b = load i8, ptr addrspace(2) %p, align 1
%x = zext i8 %a to i32
%y = zext i8 %b to i32
%s = shl i32 %y, 8
%v = or i32 %x, %s
store i32 %v, ptr addrspace(1) %1, align 4
ret void
}
!air.kernel = !{!9}
!air.version = !{!17}
!air.language_version = !{!18}
!9 = !{ptr @constant_ends, !10, !11}
!10 = !{}
!11 = !{!12, !13}
!12 = !{i32 0, !"air.buffer", !"air.buffer_size", i32 6, !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.arg_type_size", i32 6, !"air.arg_type_align_size", i32 1, !"air.arg_type_name", !"Six", !"air.arg_name", !"in"}
!13 = !{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"out"}
!17 = !{i32 2, i32 8, i32 0}
!18 = !{!"Metal", i32 4, i32 0, i32 0}
"#;
/// A uniform view is sized for a descriptor base aligned to `max(minUniformBufferOffsetAlignment,
/// 16)`. A window starting at byte 0 is bound from the multiple of that alignment at or below the
/// bind offset, so its residual is any value below it: on `amd-780m-radv` (an alignment of 4)
/// residuals 12 and 15 put the struct's last byte in words 4 and 5, past the 16 bytes an alignment
/// of 4 alone would declare. The view covers them and reads both ends exactly, with
/// `uniformBufferStandardLayout` (`u32[]`) and without (`uvec4[]`).
#[test]
fn a_uniform_view_covers_every_residual_of_a_sixteen_aligned_base() {
let Some(bc) = assemble_text("constant_ends", CONSTANT_ENDS) else {
return;
};
let data = [0x5Au8, 8, 7, 6, 5, 0xC3];
for stem in ["amd-780m-radv", "moltenvk-m3"] {
for standard in [true, false] {
let what = format!("{stem} standard={standard}");
let p = profile_with(stem, true, standard);
let a = compile(&bc, "constant_ends", &p).unwrap_or_else(|e| panic!("{what}: {e}"));
let form = match a.interface.slots.get(&sref(0)) {
Some(SlotInterface::Buffer(b)) => b.form,
other => panic!("{what}: {other:?}"),
};
let want = if standard {
DescriptorView::UniformWords
} else {
DescriptorView::UniformVec4
};
assert_eq!(form, BufferForm::Descriptor(want), "{what}");
link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}"));
let (plan, m) = typed_module(&bc, "constant_ends", &p).expect("module");
for r in [0u32, 4, 12, 15] {
let res = Resources {
buffers: vec![bound(0, r, &data, 0x44), bound(1, 0, &[0; 4], 0)],
push: push_bytes(&plan, &[(0, r)]),
spec: Default::default(),
};
let out = run(&m, &Config::default(), res).expect("run");
assert_eq!(out.buffers[1][..4], [0x5A, 0xC3, 0, 0], "{what} r={r}");
}
}
}
}
/// Without robust descriptors a `constant` slot is a storage view, contained against the range
/// actually bound. The binder clamps that range to the padded allocation, so it can be shorter than
/// the proven window: here a 16-byte allocation bound at offset 12 leaves 4 of the struct's 6
/// bytes, and the constant-offset read of byte 5 lands past the bound range. It must not trap and
/// must read 0; the same short allocation at offsets 0 and 4 reads byte 5 exactly.
/// A `constant` slot is a storage view, and under the in-shader encoding it is contained against
/// the range actually bound. The binder clamps that range to the padded allocation, so it can be
/// shorter than the proven window: here a 16-byte allocation bound at offset 12 leaves 4 of the
/// struct's 6 bytes, and the constant-offset read of byte 5 lands past the bound range. It must
/// not trap and must read 0; the same short allocation at offsets 0 and 4 reads byte 5 exactly.
#[test]
fn a_constant_buffer_shorter_than_its_window_is_contained_in_shader() {
let Some(bc) = assemble_file("buffer_end_byte_load_constant") else {
@@ -609,37 +260,31 @@ fn a_constant_buffer_shorter_than_its_window_is_contained_in_shader() {
};
let alloc: [u8; 16] = std::array::from_fn(|i| 0x10 + i as u8);
for stem in PROFILES {
for standard in [true, false] {
let what = format!("{stem} standard={standard}");
let p = profile_with(stem, false, standard);
let a = compile(&bc, "buffer_end_byte_load_constant", &p)
.unwrap_or_else(|e| panic!("{what}: {e}"));
let form = match a.interface.slots.get(&sref(0)) {
Some(SlotInterface::Buffer(b)) => b.form,
other => panic!("{what}: {other:?}"),
let what = stem;
let p = profile_with(stem, false);
let a = compile(&bc, "buffer_end_byte_load_constant", &p)
.unwrap_or_else(|e| panic!("{what}: {e}"));
let form = match a.interface.slots.get(&sref(0)) {
Some(SlotInterface::Buffer(b)) => b.form,
other => panic!("{what}: {other:?}"),
};
assert_eq!(form, BufferForm::Descriptor, "{what}");
link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}"));
let (plan, m) = typed_module(&bc, "buffer_end_byte_load_constant", &p).expect("module");
for (r, want) in [(0u32, alloc[5]), (4, alloc[9]), (12, 0)] {
let short = Buffer {
slot: Some(kslot(0)),
address: None,
bytes: alloc.to_vec(),
};
assert_eq!(
form,
BufferForm::Descriptor(DescriptorView::Storage),
"{what}"
);
link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}"));
let (plan, m) = typed_module(&bc, "buffer_end_byte_load_constant", &p).expect("module");
for (r, want) in [(0u32, alloc[5]), (4, alloc[9]), (12, 0)] {
let short = Buffer {
slot: Some(kslot(0)),
address: None,
bytes: alloc.to_vec(),
};
let res = Resources {
buffers: vec![short, bound(1, 0, &[0xAA; 4], 0)],
push: push_bytes(&plan, &[(0, r)]),
spec: Default::default(),
};
let out = run(&m, &Config::default(), res)
.unwrap_or_else(|e| panic!("{what} r={r}: {e:?}"));
assert_eq!(out.buffers[1][..4], [want, 0, 0, 0], "{what} r={r}");
}
let res = Resources {
buffers: vec![short, bound(1, 0, &[0xAA; 4], 0)],
push: push_bytes(&plan, &[(0, r)]),
spec: Default::default(),
};
let out =
run(&m, &Config::default(), res).unwrap_or_else(|e| panic!("{what} r={r}: {e:?}"));
assert_eq!(out.buffers[1][..4], [want, 0, 0, 0], "{what} r={r}");
}
}
}
@@ -970,7 +615,7 @@ fn offsets(size: u64) -> Vec<u64> {
fn every_leaf_path_is_exact_in_bounds_and_contained_out_of_bounds() {
let size = 32u64;
for stem in ["moltenvk-m3", "runtime-floor"] {
let p = profile_with(stem, false, true);
let p = profile_with(stem, false);
for k in leaf_kernels() {
let what = format!("{stem} {}", k.name);
let Some(bc) = assemble_text(k.name, &leaf_kernel(&k)) else {
@@ -1155,7 +800,7 @@ fn an_unbounded_storage_slot_declares_its_range_limit() {
return;
};
for stem in PROFILES {
let p = profile_with(stem, true, true);
let p = profile_with(stem, true);
let a = compile(&bc, k.name, &p).unwrap_or_else(|e| panic!("{stem}: {e}"));
assert!(
a.facts
@@ -1165,7 +810,7 @@ fn an_unbounded_storage_slot_declares_its_range_limit() {
match a.interface.slots.get(&sref(0)) {
Some(SlotInterface::Buffer(b)) => {
assert_eq!(b.window, Window::Whole, "{stem}");
assert_eq!(b.form, BufferForm::Descriptor(DescriptorView::Storage));
assert_eq!(b.form, BufferForm::Descriptor);
}
other => panic!("{stem}: {other:?}"),
}
@@ -1278,7 +923,7 @@ fn push_with_table(plan: &Plan) -> Vec<u8> {
#[test]
fn a_device_address_slot_is_exact_and_contained() {
let size = 32u64;
let p = profile_with("moltenvk-m3", true, true);
let p = profile_with("moltenvk-m3", true);
assert_eq!(p.fields().buffer_access, BufferAccess::Addressed);
let mut inputs = LowerInputs::new();
inputs.psb_slots.insert(sref(0));
@@ -1421,7 +1066,7 @@ fn a_device_address_slot_below_its_bind_offset_is_exact_and_contained() {
let mut inputs = LowerInputs::new();
inputs.psb_slots.insert(sref(0));
for robust in [true, false] {
let p = profile_with("moltenvk-m3", robust, true);
let p = profile_with("moltenvk-m3", robust);
let what = format!("robust={robust}");
assert_eq!(p.fields().buffer_access, BufferAccess::Addressed);
let a = compile_bitcode(
@@ -1528,7 +1173,7 @@ entry:\n\
let Some(bc) = assemble_text("wide_window", &text) else {
return;
};
let p = profile_with("moltenvk-m3", true, true);
let p = profile_with("moltenvk-m3", true);
let mut inputs = LowerInputs::new();
inputs.psb_slots.insert(sref(0));
let r = plan_bitcode(
@@ -1589,11 +1234,8 @@ entry:\n\
/// On Profile A, when the per-stage storage-buffer limit is exceeded, the highest-index storage
/// slot moves to its device address (a deterministic per-function choice), declares
/// `DeviceAddresses`, and the function still validates. Profile F views a read-only slot as a
/// uniform buffer instead: the `device` params word (its window bounds its range) before the
/// `Whole` data slot, which stays a spare candidate; the view depends on the alias check. Without
/// robust descriptors (the in-shader encoding), or when only written slots are left to move,
/// Profile F refuses naming the limit.
/// `DeviceAddresses`, and the function still validates. Profile F, which has no device addresses,
/// refuses naming the limit.
#[test]
fn the_highest_storage_slots_fall_back_to_device_addresses() {
let k = LeafKernel {
@@ -1625,70 +1267,27 @@ fn the_highest_storage_slots_fall_back_to_device_addresses() {
other => panic!("{stem}: {other:?}"),
};
assert_eq!(form(2), BufferForm::Psb, "{stem}");
assert_eq!(form(1), BufferForm::Descriptor(DescriptorView::Storage));
assert_eq!(form(0), BufferForm::Descriptor(DescriptorView::Storage));
assert_eq!(form(1), BufferForm::Descriptor);
assert_eq!(form(0), BufferForm::Descriptor);
assert!(a
.facts
.contains(&RuntimeFact::DeviceAddresses { slot: sref(2) }));
link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem}: L3: {e}"));
} else {
let a = r.unwrap_or_else(|e| panic!("{stem}: {e}"));
let form = |i| match a.interface.slots.get(&sref(i)) {
Some(SlotInterface::Buffer(b)) => b.form,
other => panic!("{stem}: {other:?}"),
};
assert_eq!(
form(2),
BufferForm::Descriptor(DescriptorView::UniformWords),
"{stem}"
);
assert_eq!(form(1), BufferForm::Descriptor(DescriptorView::Storage));
assert_eq!(form(0), BufferForm::Descriptor(DescriptorView::Storage));
assert!(a
.facts
.contains(&RuntimeFact::UniformViewAliasing { slot: sref(2) }));
assert!(a.facts.contains(&RuntimeFact::UniformViewRange {
slot: sref(0),
choice: UniformViewChoice::Spare,
}));
link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem}: L3: {e}"));
// No robust descriptors, or no read-only slot left to move: the limit is refused.
let mut strict = profile_desc(stem);
strict.limits.max_per_stage_descriptor_storage_buffers = 2;
strict.features.remove(&VkFeature::RobustBufferAccess);
strict.features.remove(&VkFeature::RobustBufferAccess2);
let mut written = profile_desc(stem);
written.limits.max_per_stage_descriptor_storage_buffers = 0;
for desc in [strict, written] {
let p = Device::from_queries(desc, policy())
.expect("device")
.profile()
.clone();
match compile(&bc, k.name, &p) {
Err(Error::Unsupported(u)) => {
assert_eq!(u.feature, Feature::DescriptorCount, "{stem}")
}
other => panic!("{stem}: expected a refusal, got {other:?}"),
match r {
Err(Error::Unsupported(u)) => {
assert_eq!(u.feature, Feature::DescriptorCount, "{stem}")
}
other => panic!("{stem}: expected a refusal, got {other:?}"),
}
}
}
}
/// The description of committed profile `stem`.
fn profile_desc(stem: &str) -> DeviceDescription {
let path = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../metal2vulkan-validation/profiles")
.join(format!("{stem}.json"));
let text = std::fs::read_to_string(path).expect("profile");
DeviceDescription::from_khronos_json(&text, None).expect("description")
}
/// A kernel with a loop reserves no status binding (its modules carry no execution bound), so the
/// descriptor fallback counts the Metal slots alone. With three storage slots and a per-stage limit
/// of two, moving one slot brings the storage count to two: the highest slot to a device address
/// where the profile has them, else (Profile F) the uniform-view fallback moves only the bounded
/// params word, and the `Whole` data slot stays a storage descriptor.
/// where the profile has them; Profile F, which has none, refuses naming the limit.
#[test]
fn a_looping_kernel_reserves_no_status_binding_in_the_fallback() {
let name = "fallback_loop";
@@ -1717,23 +1316,17 @@ fn a_looping_kernel_reserves_no_status_binding_in_the_fallback() {
.profile()
.clone();
let r = compile(&bc, name, &p);
let a = r.unwrap_or_else(|e| panic!("{stem}: {e}"));
assert!(!a.facts.contains(&RuntimeFact::ExecutionStatus), "{stem}");
if p.fields().buffer_access != BufferAccess::Addressed {
let form = |i| match a.interface.slots.get(&sref(i)) {
Some(SlotInterface::Buffer(b)) => b.form,
other => panic!("{stem}: {other:?}"),
};
let storage = BufferForm::Descriptor(DescriptorView::Storage);
assert_eq!(
form(2),
BufferForm::Descriptor(DescriptorView::UniformWords),
"{stem}"
);
assert_eq!((form(0), form(1)), (storage, storage), "{stem}: one move");
link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem}: L3: {e}"));
match r {
Err(Error::Unsupported(u)) => {
assert_eq!(u.feature, Feature::DescriptorCount, "{stem}")
}
other => panic!("{stem}: expected a refusal, got {other:?}"),
}
continue;
}
let a = r.unwrap_or_else(|e| panic!("{stem}: {e}"));
assert!(!a.facts.contains(&RuntimeFact::ExecutionStatus), "{stem}");
let form = |i| match a.interface.slots.get(&sref(i)) {
Some(SlotInterface::Buffer(b)) => b.form,
other => panic!("{stem}: {other:?}"),
@@ -1741,10 +1334,10 @@ fn a_looping_kernel_reserves_no_status_binding_in_the_fallback() {
assert_eq!(form(2), BufferForm::Psb, "{stem}");
assert_eq!(
form(1),
BufferForm::Descriptor(DescriptorView::Storage),
BufferForm::Descriptor,
"{stem}: one move is enough"
);
assert_eq!(form(0), BufferForm::Descriptor(DescriptorView::Storage));
assert_eq!(form(0), BufferForm::Descriptor);
link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem}: L3: {e}"));
}
}
@@ -1895,7 +1488,7 @@ fn the_word_cap_holds_on_the_emitted_words() {
let Some(bc) = assemble_file("storage_texture_write") else {
return;
};
let p = profile_with("moltenvk-m3", true, true);
let p = profile_with("moltenvk-m3", true);
let entry = EntryRef::Name("storage_texture_write");
let consts = FunctionConstantValues::defaults();
let inputs = LowerInputs::new();
@@ -2714,211 +2307,3 @@ fn a_float4_aligned_only_to_its_lanes_is_placed_at_its_address() {
}
}
}
/// A kernel reading the `float4` at byte 32 of a `constant` buffer (a `Bounded` window, so a
/// uniform view under robust descriptors) into `out`.
const CONSTANT_VEC4: &str = r#"define void @constant_vec4(ptr addrspace(2) noundef "air-buffer-no-alias" %0, ptr addrspace(1) noundef "air-buffer-no-alias" %1) {
entry:
%p = getelementptr inbounds i8, ptr addrspace(2) %0, i64 32
%v = load <4 x float>, ptr addrspace(2) %p, align 16
store <4 x float> %v, ptr addrspace(1) %1, align 16
ret void
}
!air.kernel = !{!9}
!air.version = !{!17}
!air.language_version = !{!18}
!9 = !{ptr @constant_vec4, !10, !11}
!10 = !{}
!11 = !{!12, !13}
!12 = !{i32 0, !"air.buffer", !"air.buffer_size", i32 48, !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.arg_type_size", i32 48, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"Three", !"air.arg_name", !"in"}
!13 = !{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"out"}
!17 = !{i32 2, i32 8, i32 0}
!18 = !{!"Metal", i32 4, i32 0, i32 0}
"#;
/// Under robust descriptors a `constant` slot's 16-aligned `float4` is one `uvec4` of its uniform
/// view: a `Uniform { uvec4[N] }` view beside the `u32[]` words with `uniformBufferStandardLayout`,
/// the std140 `uvec4[]` word view itself without. It reads the vector's 16 bytes exactly at every
/// residual the binder can give the window `[32, 48)` with a 16-aligned bind offset: the window's
/// first byte at descriptor byte `0, 16, ..., A - 16` for the base alignment `A` (the residual
/// wraps below the window).
#[test]
fn a_constant_vector_is_one_uvec4_of_its_uniform_view() {
let text = format!("{HEADER}{CONSTANT_VEC4}");
let Some(bc) = assemble_text("constant_vec4", &text) else {
return;
};
for stem in PROFILES {
for standard in [true, false] {
let what = format!("{stem} standard={standard}");
let p = profile_with(stem, true, standard);
let a = compile(&bc, "constant_vec4", &p).unwrap_or_else(|e| panic!("{what}: {e}"));
let form = match a.interface.slots.get(&sref(0)) {
Some(SlotInterface::Buffer(b)) => b.form,
other => panic!("{what}: {other:?}"),
};
let want = if standard {
DescriptorView::UniformWords
} else {
DescriptorView::UniformVec4
};
assert_eq!(form, BufferForm::Descriptor(want), "{what}");
link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}"));
let (plan, m) = typed_module(&bc, "constant_vec4", &p).expect("module");
assert_eq!(
views_of(&m, 0),
if standard { 2 } else { 1 },
"{what}: views of in"
);
let data = pattern(512);
let base = p
.fields()
.limits
.min_uniform_buffer_offset_alignment
.max(16) as u32;
// Metal byte 32 is descriptor byte `r + 32`.
for at in (0..base).step_by(16) {
let r = at.wrapping_sub(32);
let at = at as usize;
let res = Resources {
buffers: vec![
Buffer {
slot: Some(kslot(0)),
address: None,
bytes: data.clone(),
},
bound(1, 0, &[0; 16], 0),
],
push: push_bytes(&plan, &[(0, r)]),
spec: Default::default(),
};
let out = run(&m, &Config::default(), res)
.unwrap_or_else(|e| panic!("{what} r={r:#x}: {e:?}"));
assert_eq!(out.buffers[1][..16], data[at..at + 16], "{what} r={r:#x}");
}
}
}
}
/// A kernel that sums, over `n` trips (the struct's first word), the struct's word 3 on an even
/// trip and its word 5 on an odd one, each read under the trip's own branch, into `out`. Both
/// words are at fixed offsets of a `constant` struct (a `Bounded` window, so a uniform view under
/// robust descriptors) that nothing writes.
const CONSTANT_LOOP: &str = r#"%struct.Params = type { i32, i32, i32, i32, i32, i32, i32, i32 }
define void @constant_loop(ptr addrspace(2) noundef "air-buffer-no-alias" %0, ptr addrspace(1) noundef "air-buffer-no-alias" %1) {
entry:
%n = load i32, ptr addrspace(2) %0, align 4
br label %head
head:
%t = phi i32 [ 0, %entry ], [ %t1, %latch ]
%acc = phi i32 [ 0, %entry ], [ %acc1, %latch ]
%done = icmp uge i32 %t, %n
br i1 %done, label %exit, label %body
body:
%bit = and i32 %t, 1
%odd = icmp ne i32 %bit, 0
br i1 %odd, label %odd_trip, label %even_trip
odd_trip:
%p5 = getelementptr inbounds %struct.Params, ptr addrspace(2) %0, i64 0, i32 5
%v5 = load i32, ptr addrspace(2) %p5, align 4
br label %latch
even_trip:
%p3 = getelementptr inbounds %struct.Params, ptr addrspace(2) %0, i64 0, i32 3
%v3 = load i32, ptr addrspace(2) %p3, align 4
br label %latch
latch:
%v = phi i32 [ %v5, %odd_trip ], [ %v3, %even_trip ]
%acc1 = add i32 %acc, %v
%t1 = add i32 %t, 1
br label %head
exit:
store i32 %acc, ptr addrspace(1) %1, align 4
ret void
}
!air.kernel = !{!9}
!air.version = !{!17}
!air.language_version = !{!18}
!9 = !{ptr @constant_loop, !10, !11}
!10 = !{}
!11 = !{!12, !13}
!12 = !{i32 0, !"air.buffer", !"air.buffer_size", i32 32, !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.arg_type_size", i32 32, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"Params", !"air.arg_name", !"in"}
!13 = !{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"out"}
!17 = !{i32 2, i32 8, i32 0}
!18 = !{!"Metal", i32 4, i32 0, i32 0}
"#;
/// The loads through a `Uniform`-class pointer in the blocks of `m`'s loops: each loop's header
/// and every block it reaches before its merge.
fn uniform_loads_in_loops(m: &TypedModule) -> usize {
let mut body = std::collections::BTreeSet::new();
for l in m.loops() {
let mut stack = vec![l.header];
while let Some(b) = stack.pop() {
if b == l.merge || !body.insert(b) {
continue;
}
let mut term = m.blocks()[b.index()].term.clone();
term.for_each_target_mut(|t| stack.push(*t));
}
}
let uniform = |v: crate::spirv::ids::Value| {
let ty = m.values()[v.index()].ty;
matches!(
m.types().get(ty),
Ok(Type::Pointer {
class: StorageClass::Uniform,
..
})
)
};
body.iter()
.flat_map(|b| &m.blocks()[b.index()].insts)
.filter(|n| matches!(n.inst, Inst::Load { ptr, .. } if uniform(ptr)))
.count()
}
/// Under robust descriptors the words of a `constant` struct that a loop reads at fixed offsets,
/// each under a per-trip branch, are loaded once before the loop: the emitted loop holds no load
/// of the struct's uniform view, and the sum is the loop's at every trip count.
#[test]
fn a_constant_struct_read_in_a_loop_is_loaded_before_it() {
let text = format!("{HEADER}{CONSTANT_LOOP}");
let Some(bc) = assemble_text("constant_loop", &text) else {
return;
};
for stem in PROFILES {
let p = profile_with(stem, true, true);
let a = compile(&bc, "constant_loop", &p).unwrap_or_else(|e| panic!("{stem}: {e}"));
let form = match a.interface.slots.get(&sref(0)) {
Some(SlotInterface::Buffer(b)) => b.form,
other => panic!("{stem}: {other:?}"),
};
assert_eq!(
form,
BufferForm::Descriptor(DescriptorView::UniformWords),
"{stem}"
);
link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem}: L3: {e}"));
let (plan, m) = typed_module(&bc, "constant_loop", &p).expect("module");
assert!(!m.loops().is_empty(), "{stem}: the loop");
assert_eq!(
uniform_loads_in_loops(&m),
0,
"{stem}: loads of in in the loop"
);
let (even, odd) = (7u32, 1000u32);
for n in [0u32, 1, 2, 5, 8] {
let words = [n, 0xAA, 0xBB, even, 0xCC, odd, 0xDD, 0xEE];
let bytes: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
let res = Resources {
buffers: vec![bound(0, 0, &bytes, 0), bound(1, 0, &[0; 4], 0)],
push: push_bytes(&plan, &[(0, 0), (1, 0)]),
spec: Default::default(),
};
let out =
run(&m, &Config::default(), res).unwrap_or_else(|e| panic!("{stem} n={n}: {e:?}"));
let want = n.div_ceil(2) * even + n / 2 * odd;
assert_eq!(out.buffers[1][..4], want.to_le_bytes(), "{stem} n={n}");
}
}
}
+21 -282
View File
@@ -36,17 +36,14 @@ use crate::device::requirements::VkFeature;
use crate::device::{Device, DeviceDescription, DevicePolicy};
use crate::error::{BindError, Feature};
use crate::library::Library;
use crate::pipeline::interface::{BufferForm, DescriptorView, SlotInterface};
use crate::pipeline::interface::{BufferForm, SlotInterface};
use crate::pipeline::layout::BindingSource;
use crate::pipeline::sym::{
PushField, ResourceKind, ResourceSlot, SlotClass, SlotRef, SpecKey, Stage,
};
use crate::pipeline::testing::{
engine_dir, llvm_assemble, typed_module, typed_module_with, AssembleError,
};
use crate::pipeline::testing::{engine_dir, llvm_assemble, typed_module, AssembleError};
use crate::pipeline::{
ComputePipeline, ComputePipelineDescriptor, FunctionDescriptor, LoweringInputs, RuntimeFact,
StageSource, UniformViewChoice,
ComputePipeline, ComputePipelineDescriptor, FunctionDescriptor, LoweringInputs, StageSource,
};
use crate::spirv::interp::{run, Buffer, Config, Order, Resources};
use crate::spirv::ir::TypedModule;
@@ -1178,9 +1175,8 @@ fn compared_slots_get_their_guest_bases_and_inline_bytes_are_refused() {
const LIMIT_ENTRY: &str = "descriptor_limit_uniform_views";
/// A world for the fixture: `n` threads, and each read-only array holding `len[k]` words (at
/// least `n`), bound at an offset (`c`'s, 532, is not a multiple of 16, so on the profiles these
/// tests use its uniform view reads through the bind residual); `p = {scale 3, bias 0x5A5A}`.
/// Returns it with the expected `out`.
/// least `n`), bound at an offset (`c`'s, 532, is not a multiple of 16); `p = {scale 3, bias
/// 0x5A5A}`. Returns it with the expected `out`.
fn limit_world(n: usize, len: [usize; 4]) -> (World, Vec<u32>) {
let arr = |seed: u32, words: usize, offset: u64| {
let mut a = Alloc::new(offset as usize + words * 4, offset);
@@ -1234,10 +1230,6 @@ fn form(pipe: &ComputePipeline, index: u32) -> BufferForm {
}
}
fn has_fact(pipe: &ComputePipeline, fact: RuntimeFact) -> bool {
pipe.dependencies.iter().any(|d| d.fact == fact)
}
/// The fixture compiled for `dev` under `inputs` (a `VariantKey`'s kernel inputs).
fn limit_pipeline(
dev: &Device,
@@ -1254,288 +1246,35 @@ fn limit_pipeline(
)
}
/// On Profile F ([`no_addresses`]: four storage buffers per stage) the fixture's six
/// buffer slots fit because the per-stage fallback views two read-only slots as uniform buffers:
/// the `device` struct first (its window bounds its range), then the `constant` array (its `Whole`
/// window leaves the range to the binder). The `device` view depends on the alias check, the
/// `constant` array on its range, and every other read-only `Whole` slot is a spare candidate.
/// Through the binder, on the interpreter, every profile computes Metal's `out`, the same bytes as
/// a profile whose limits need no fallback.
/// On Profile F ([`no_addresses`]: four storage buffers per stage, no device addresses) the
/// fixture's six buffer slots exceed the stage's storage-buffer limit, and no slot can move to a
/// device address: the compile refuses the kernel (`DescriptorCount`). On a profile whose limit
/// holds them every slot is a storage view, and through the binder, on the interpreter, `out` is
/// Metal's.
#[test]
fn profile_f_views_read_only_slots_as_uniform_buffers_over_the_storage_limit() {
fn a_stage_past_the_storage_buffer_limit_without_device_addresses_is_refused() {
let Some(bc) = fixture(LIMIT_ENTRY) else {
return;
};
let n = 64;
let uniform = BufferForm::Descriptor(DescriptorView::UniformWords);
let storage = BufferForm::Descriptor(DescriptorView::Storage);
for (stem, dev) in [
("Profile F", device("runtime-floor", no_addresses)),
("moltenvk-m3", device("moltenvk-m3", |_| {})),
] {
let pipe = pipeline(&dev, &bc, LIMIT_ENTRY).unwrap_or_else(|e| panic!("{stem}: {e}"));
let small = dev
.profile()
.fields()
.limits
.max_per_stage_descriptor_storage_buffers
< 6;
if small {
for (index, want) in [
(0, storage),
(1, storage),
(2, uniform),
(3, uniform),
(4, storage),
(5, storage),
] {
assert_eq!(form(&pipe, index), want, "{stem}: slot {index}");
}
assert!(has_fact(
&pipe,
RuntimeFact::UniformViewAliasing { slot: kslot(3) }
));
assert!(!has_fact(
&pipe,
RuntimeFact::UniformViewAliasing { slot: kslot(2) }
));
assert!(has_fact(
&pipe,
RuntimeFact::UniformViewRange {
slot: kslot(2),
choice: UniformViewChoice::Viewed,
}
));
assert!(!has_fact(
&pipe,
RuntimeFact::BufferRangeLimit { slot: kslot(2) }
));
for spare in [0, 1, 4] {
assert!(
has_fact(
&pipe,
RuntimeFact::UniformViewRange {
slot: kslot(spare),
choice: UniformViewChoice::Spare,
}
),
"{stem}: slot {spare}"
);
}
} else {
assert!(
(0..6).all(|i| form(&pipe, i) == storage),
"{stem}: no fallback"
);
}
let (_, m) = typed_module(&bc, LIMIT_ENTRY, dev.profile()).expect("module");
let (mut w, want) = limit_world(n, [n; 4]);
let state = w.state();
let plan = pipe.plan(&dev, &state.shape()).expect("plan");
assert!(
plan.variant.is_empty(),
"{stem}: small buffers need no variant"
);
execute(&dev, &pipe, &m, &mut w, &limit_dispatch(n))
.unwrap_or_else(|e| panic!("{stem}: {e}"));
assert_eq!(words(&w.buffers[&5].bytes), want, "{stem}");
}
}
/// A shape that binds a buffer larger than `maxUniformBufferRange` (16 KiB on Profile F) at the
/// `constant` array, which the base pipeline views as a uniform buffer, asks for the variant that
/// keeps it a storage view (`VariantKey::storage_view_slots`, from the length class); instantiating
/// the base pipeline anyway is `DescriptorRangeExceeded`. The variant views the highest-index
/// `device` array instead, states the same key for the same shape (a fixed point), and computes
/// Metal's `out`. With every read-only array large, the variant keeps all four storage views, and
/// its compile refuses the per-stage limit.
#[test]
fn a_large_buffer_at_a_uniform_view_asks_for_the_variant_that_keeps_it_storage() {
let Some(bc) = fixture(LIMIT_ENTRY) else {
return;
};
let n = 64;
let dev = device("runtime-floor", no_addresses);
let base = limit_pipeline(&dev, &bc, &LoweringInputs::new()).expect("base");
// `c` holds 8192 words (32 KiB): its length class cannot prove a uniform range.
let (mut w, want) = limit_world(n, [n, n, 8192, n]);
let state = w.state();
let plan = base.plan(&dev, &state.shape()).expect("plan");
assert_eq!(
plan.variant.storage_view_slots,
std::collections::BTreeSet::from([kslot(2)])
);
match plan.instantiate_dispatch(&state, &limit_dispatch(n)) {
Err(BindError::DescriptorRangeExceeded { slot, limit, .. }) => {
assert_eq!((slot, limit), (kslot(2), 16384));
}
other => panic!("expected DescriptorRangeExceeded, got {other:?}"),
}
let inputs = plan.variant.lowering_inputs(Stage::Kernel);
let variant = limit_pipeline(&dev, &bc, &inputs).expect("variant");
let uniform = BufferForm::Descriptor(DescriptorView::UniformWords);
let storage = BufferForm::Descriptor(DescriptorView::Storage);
for (index, want) in [
(0, storage),
(1, storage),
(2, storage),
(3, uniform),
(4, uniform),
(5, storage),
] {
assert_eq!(form(&variant, index), want, "variant slot {index}");
}
assert!(has_fact(
&variant,
RuntimeFact::UniformViewRange {
slot: kslot(2),
choice: UniformViewChoice::Kept,
}
));
assert!(has_fact(
&variant,
RuntimeFact::UniformViewAliasing { slot: kslot(4) }
));
let again = variant.plan(&dev, &state.shape()).expect("variant plan");
assert_eq!(again.variant, plan.variant, "a fixed point");
let (_, m) = typed_module_with(&bc, LIMIT_ENTRY, dev.profile(), &inputs).expect("module");
execute(&dev, &variant, &m, &mut w, &limit_dispatch(n)).expect("variant dispatch");
assert_eq!(words(&w.buffers[&5].bytes), want);
let (w, _) = limit_world(n, [8192; 4]);
let plan = base.plan(&dev, &w.state().shape()).expect("plan");
assert_eq!(
plan.variant.storage_view_slots,
std::collections::BTreeSet::from([kslot(0), kslot(1), kslot(2), kslot(4)])
);
match limit_pipeline(&dev, &bc, &plan.variant.lowering_inputs(Stage::Kernel)) {
match limit_pipeline(&dev, &bc, &LoweringInputs::new()) {
Err(crate::error::Error::Unsupported(u)) => {
assert_eq!(u.feature, Feature::DescriptorCount)
}
other => panic!("expected a DescriptorCount refusal, got {:?}", other.err()),
}
}
/// A `device` slot read through a uniform view must not share Metal addresses with a slot the
/// pipeline writes (a uniform view need not observe the dispatch's own writes): the struct `p`
/// bound where `out` writes is `UniformViewAliased` at instantiation, while the `constant` array's
/// view, which Metal's `constant` address space makes read-only, is not checked, and disjoint
/// windows of one allocation are accepted.
#[test]
fn a_device_uniform_view_bound_where_the_pipeline_writes_is_refused() {
let Some(bc) = fixture(LIMIT_ENTRY) else {
return;
};
let n = 64;
let dev = device("runtime-floor", no_addresses);
let pipe = pipeline(&dev, &bc, LIMIT_ENTRY).expect("Profile F");
let one = limit_dispatch(n);
// The world with `out` bound at bind offset `offset` of a 1 KiB allocation at Metal address
// `guest`: its `Whole` window reaches from the offset to the allocation's end.
let out_at = |guest: u64, offset: u64| {
let (mut w, _) = limit_world(n, [n; 4]);
let out = w.buffers.get_mut(&5).expect("out");
out.guest = guest;
out.offset = offset;
out.bytes = vec![0; 1024];
w
};
let (pg, cg) = {
let (w, _) = limit_world(n, [n; 4]);
(w.buffers[&3].guest, w.buffers[&2].guest)
};
// `out` in `p`'s allocation, over `p`'s window [256, 264).
let w = out_at(pg, 0);
let state = w.state();
let plan = pipe.plan(&dev, &state.shape()).expect("plan");
assert_eq!(
plan.instantiate_dispatch(&state, &one).err(),
Some(BindError::UniformViewAliased {
slot: kslot(3),
written: kslot(5),
})
let dev = device("moltenvk-m3", |_| {});
let pipe = pipeline(&dev, &bc, LIMIT_ENTRY).expect("moltenvk-m3");
assert!(
(0..6).all(|i| form(&pipe, i) == BufferForm::Descriptor),
"every slot a storage view"
);
// `out` after `p`'s window in the same allocation: disjoint, accepted.
let mut w = out_at(pg, 264);
let (_, m) = typed_module(&bc, LIMIT_ENTRY, dev.profile()).expect("module");
execute(&dev, &pipe, &m, &mut w, &one).expect("disjoint windows");
// `out` over the `constant` array: not checked.
let w = out_at(cg, 512);
let (mut w, want) = limit_world(n, [n; 4]);
let state = w.state();
let plan = pipe.plan(&dev, &state.shape()).expect("plan");
assert!(plan.instantiate_dispatch(&state, &one).is_ok());
}
/// An atomic needs a storage view (its words are reached through a storage-view pointer), so the
/// fallback never views a slot an atomic reaches, even one only loaded atomically, whose 4-byte
/// window a uniform view would otherwise take first: the highest-index `device` array is viewed
/// instead. Through the binder, on the interpreter, `out` is Metal's.
#[test]
fn an_atomically_loaded_slot_stays_a_storage_view_under_the_fallback() {
const ENTRY: &str = "descriptor_limit_atomic_load";
let Some(bc) = fixture(LIMIT_ENTRY) else {
return;
};
let n = 64;
let limit = 40u32;
let uniform = BufferForm::Descriptor(DescriptorView::UniformWords);
let storage = BufferForm::Descriptor(DescriptorView::Storage);
for stem in ["Profile F"] {
let dev = device("runtime-floor", no_addresses);
let pipe = pipeline(&dev, &bc, ENTRY).unwrap_or_else(|e| panic!("{stem}: {e}"));
let small = dev
.profile()
.fields()
.limits
.max_per_stage_descriptor_storage_buffers
< 5;
for index in 0..5 {
let want = if small && index == 3 {
uniform
} else {
storage
};
assert_eq!(form(&pipe, index), want, "{stem}: slot {index}");
}
assert_eq!(
has_fact(&pipe, RuntimeFact::UniformViewAliasing { slot: kslot(3) }),
small,
"{stem}"
);
let arr = |seed: u32| {
let mut a = Alloc::new(n * 4, 0);
for i in 0..n {
let v = (i as u32).wrapping_mul(2654435761).wrapping_add(seed);
a.bytes[4 * i..][..4].copy_from_slice(&v.to_le_bytes());
}
a
};
let (a, b, d) = (arr(1), arr(2), arr(4));
let at = |x: &Alloc, i: usize| words(&x.bytes)[i];
let want: Vec<u32> = (0..n)
.map(|i| {
if (i as u32) < limit {
at(&a, i).wrapping_add(at(&b, i))
} else {
at(&d, i)
}
})
.collect();
let mut count = Alloc::new(4, 0);
count.bytes.copy_from_slice(&limit.to_le_bytes());
let mut w = World::new([
(0, a),
(1, b),
(2, count),
(3, d),
(4, Alloc::new(n * 4, 0)),
]);
for (k, a) in w.buffers.iter_mut() {
a.guest = 0x10_0000_0000 + u64::from(*k) * 0x1_0000_0000;
}
let (_, m) = typed_module(&bc, ENTRY, dev.profile()).expect("module");
execute(&dev, &pipe, &m, &mut w, &limit_dispatch(n))
.unwrap_or_else(|e| panic!("{stem}: {e}"));
assert_eq!(words(&w.buffers[&4].bytes), want, "{stem}");
}
assert!(plan.variant.is_empty(), "small buffers need no variant");
execute(&dev, &pipe, &m, &mut w, &limit_dispatch(n)).expect("dispatch");
assert_eq!(words(&w.buffers[&5].bytes), want);
}
@@ -340,7 +340,7 @@ fn a_loaded_pointer_is_exact_in_bounds_and_contained_elsewhere() {
index: s,
}) {
Some(SlotInterface::Buffer(b)) => {
assert!(matches!(b.form, BufferForm::Descriptor(_)), "{what} {s}")
assert!(matches!(b.form, BufferForm::Descriptor), "{what} {s}")
}
None if s == 1 && leaf.store.is_some() => {}
other => panic!("{what} slot {s}: {other:?}"),
@@ -46,7 +46,7 @@ use crate::pipeline::descriptor::{
ColorAttachmentDescriptor, VertexAttributeDescriptor, VertexBufferLayoutDescriptor,
VertexDescriptor,
};
use crate::pipeline::interface::{AccessSet, BufferForm, DescriptorView, SlotInterface, Window};
use crate::pipeline::interface::{AccessSet, BufferForm, SlotInterface, Window};
use crate::pipeline::layout::BindingSource;
use crate::pipeline::sym::{PushField, SlotClass, SlotRef, SpecKey, Stage};
use crate::pipeline::testing::{engine_dir, llvm_assemble, AssembleError};
@@ -1123,7 +1123,7 @@ fn pulled_layouts_take_their_stride_and_share_argument_slots() {
p.interface.slots.get(&scale),
Some(SlotInterface::Buffer(b)) if b.access == AccessSet::READ
&& b.window == Window::Whole
&& b.form == BufferForm::Descriptor(DescriptorView::Storage)
&& b.form == BufferForm::Descriptor
),
"{:?}",
p.interface.slots.get(&scale)
@@ -297,7 +297,7 @@ fn lookup_module(int64: bool, form: Lookup) -> crate::spirv::ir::TypedModule {
};
let mut b = ModuleBuilder::new();
let t = declare_table(&mut b, sym(0), int64).expect("table");
let io = views::declare_at(&mut b, sym(1), views::ViewKind::Storage).expect("io");
let io = views::declare_at(&mut b, sym(1)).expect("io");
let search = define_lookup(&mut b, t, form).expect("search");
let void = b.ty(Type::Void).expect("void");
let mut f = b.function(void).expect("function");
@@ -311,9 +311,7 @@ fn lookup_module(int64: bool, form: Lookup) -> crate::spirv::ir::TypedModule {
.expect("call")
.expect("the search returns the element");
let at = k32(&mut f, 2 * KEYS + i).expect("k");
let p = views::word_ptr(&mut f, io, at)
.expect("ptr")
.expect("a storage view is writable");
let p = views::word_ptr(&mut f, io, at).expect("ptr");
f.store(p, e, MemAccess::default()).expect("store");
}
f.ret(None).expect("ret");
@@ -1,151 +0,0 @@
//! Lane reads end to end: every profile gives a `constant` slot a uniform view could read its
//! storage view where some read reaches it at an address that may differ between the lanes that
//! run it together, and its uniform view where every read is at a uniform address, whatever the
//! GPU's identity.
//!
//! The kernels read a `constant` table of 64 words (`air.buffer_size` 256, a `Bounded` window):
//! `lane_table` at the thread's position, `loop_table` in a loop over a bound read from the table,
//! after an early return of the threads past it (a counter every lane that runs the loop holds
//! alike), and `field_table` at one constant offset.
//!
//! `llvm-as` assembles the kernels; without it the tests skip visibly.
use std::path::Path;
use crate::device::profile::DeviceProfile;
use crate::device::{Device, DeviceDescription, DevicePolicy};
use crate::pipeline::interface::{BufferForm, DescriptorView, SlotInterface};
use crate::pipeline::sym::{SlotClass, SlotRef, Stage};
use crate::pipeline::testing::{compile, link_and_validate, llvm_assemble_text, AssembleError};
const TABLES: &str = r#"define void @lane_table(ptr addrspace(2) noundef "air-buffer-no-alias" %0, ptr addrspace(1) noundef "air-buffer-no-alias" %1, i32 noundef %tid) {
entry:
%i = and i32 %tid, 63
%ix = zext i32 %i to i64
%p = getelementptr inbounds [64 x i32], ptr addrspace(2) %0, i64 0, i64 %ix
%v = load i32, ptr addrspace(2) %p, align 4
%tx = zext i32 %tid to i64
%o = getelementptr inbounds i32, ptr addrspace(1) %1, i64 %tx
store i32 %v, ptr addrspace(1) %o, align 4
ret void
}
define void @loop_table(ptr addrspace(2) noundef "air-buffer-no-alias" %0, ptr addrspace(1) noundef "air-buffer-no-alias" %1, i32 noundef %tid) {
entry:
%n = load i32, ptr addrspace(2) %0, align 4
%n6 = and i32 %n, 63
%in = icmp ult i32 %tid, %n6
br i1 %in, label %head, label %exit
head:
%i = phi i32 [ 1, %entry ], [ %i1, %head ]
%acc = phi i32 [ 0, %entry ], [ %acc1, %head ]
%ix = zext i32 %i to i64
%p = getelementptr inbounds [64 x i32], ptr addrspace(2) %0, i64 0, i64 %ix
%v = load i32, ptr addrspace(2) %p, align 4
%acc1 = add i32 %acc, %v
%i1 = add i32 %i, 1
%more = icmp ult i32 %i1, %n6
br i1 %more, label %head, label %done
done:
%tx = zext i32 %tid to i64
%o = getelementptr inbounds i32, ptr addrspace(1) %1, i64 %tx
store i32 %acc1, ptr addrspace(1) %o, align 4
br label %exit
exit:
ret void
}
define void @field_table(ptr addrspace(2) noundef "air-buffer-no-alias" %0, ptr addrspace(1) noundef "air-buffer-no-alias" %1, i32 noundef %tid) {
entry:
%p = getelementptr inbounds [64 x i32], ptr addrspace(2) %0, i64 0, i64 3
%v = load i32, ptr addrspace(2) %p, align 4
%tx = zext i32 %tid to i64
%o = getelementptr inbounds i32, ptr addrspace(1) %1, i64 %tx
store i32 %v, ptr addrspace(1) %o, align 4
ret void
}
!air.kernel = !{!1, !2, !3}
!air.version = !{!17}
!air.language_version = !{!18}
!1 = !{ptr @lane_table, !10, !11}
!2 = !{ptr @loop_table, !10, !11}
!3 = !{ptr @field_table, !10, !11}
!10 = !{}
!11 = !{!12, !13, !14}
!12 = !{i32 0, !"air.buffer", !"air.buffer_size", i32 256, !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.arg_type_size", i32 256, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"Table", !"air.arg_name", !"table"}
!13 = !{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"out"}
!14 = !{i32 2, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"tid"}
!17 = !{i32 2, i32 8, i32 0}
!18 = !{!"Metal", i32 4, i32 0, i32 0}
"#;
fn assemble() -> Option<Vec<u8>> {
match llvm_assemble_text(TABLES) {
Ok(b) => Some(b),
Err(AssembleError::Missing(why)) => {
eprintln!("SKIPPED: {why}");
None
}
Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected the tables: {why}"),
}
}
/// The profile of the committed capture `stem`, under the device ID `id` where one is given.
fn profile(stem: &str, id: Option<u32>) -> DeviceProfile {
let path = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../metal2vulkan-validation/profiles")
.join(format!("{stem}.json"));
let text = std::fs::read_to_string(path).expect("profile");
let mut desc = DeviceDescription::from_khronos_json(&text, None).expect("description");
if let Some(id) = id {
desc.device_id = id;
}
Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES)
.expect("device")
.profile()
.clone()
}
/// The form of the table's slot (Metal buffer 0) in `entry` on `p`, the module validated.
fn table_form(bc: &[u8], entry: &str, p: &DeviceProfile, what: &str) -> BufferForm {
let a = compile(bc, entry, p).unwrap_or_else(|e| panic!("{what} {entry}: {e}"));
link_and_validate(&a, p).unwrap_or_else(|e| panic!("{what} {entry}: L3: {e}"));
let slot = SlotRef {
stage: Stage::Kernel,
class: SlotClass::Buffer,
index: 0,
};
match a.interface.slots.get(&slot) {
Some(SlotInterface::Buffer(b)) => b.form,
other => panic!("{what} {entry}: {other:?}"),
}
}
/// The identity decides nothing: NVIDIA's captures under the IDs of the RTX 5080 Laptop GPU, the
/// RTX 3090 and the RTX 2080 give `lane_table`'s table its storage view and the other kernels'
/// their uniform view; and so does RADV.
#[test]
fn a_per_lane_constant_read_takes_its_storage_view_on_every_device() {
let Some(bc) = assemble() else {
return;
};
let uniform = BufferForm::Descriptor(DescriptorView::UniformWords);
let storage = BufferForm::Descriptor(DescriptorView::Storage);
for (stem, id) in [
("nvidia-rtx5080-laptop", None),
("nvidia-rtx5080-laptop", Some(0x2204)),
("nvidia-rtx5080-laptop", Some(0x1e87)),
("amd-780m-radv", None),
] {
let p = profile(stem, id);
for (entry, form) in [
("lane_table", storage),
("loop_table", uniform),
("field_table", uniform),
] {
assert_eq!(
table_form(&bc, entry, &p, stem),
form,
"{stem} {id:?} {entry}"
);
}
}
}
@@ -108,7 +108,7 @@ fn check_descriptor_only(a: &FunctionArtifact, p: &DeviceProfile, what: &str) {
for (slot, s) in &a.interface.slots {
if let SlotInterface::Buffer(b) = s {
assert!(
matches!(b.form, BufferForm::Descriptor(_)),
matches!(b.form, BufferForm::Descriptor),
"{what}: {slot:?} is {:?}",
b.form
);
@@ -30,7 +30,7 @@ use crate::library::{FunctionConstantValues, Library};
use crate::lower::select::LowerInputs;
use crate::pipeline::compile::{compile_bitcode, compile_bitcode_linked, EntryRef, LinkedSource};
use crate::pipeline::facts::RuntimeFact;
use crate::pipeline::interface::{AccessSet, BufferForm, DescriptorView, SlotInterface, Window};
use crate::pipeline::interface::{AccessSet, BufferForm, SlotInterface, Window};
use crate::pipeline::sym::{
AccelerationStructureLevel, Axis, PushField, ResourceKind, ResourceSlot, SlotClass, SlotRef,
SpecKey, Stage,
@@ -409,11 +409,7 @@ fn an_intersection_function_table_is_read_per_candidate() {
Some(SlotInterface::Buffer(b)) => {
assert_eq!(b.access, AccessSet::READ, "{stem}");
assert_eq!(b.window, Window::Whole, "{stem}");
assert_eq!(
b.form,
BufferForm::Descriptor(DescriptorView::Storage),
"{stem}"
);
assert_eq!(b.form, BufferForm::Descriptor, "{stem}");
}
other => panic!("{stem}: the table's slot is {other:?}"),
}
@@ -22,8 +22,7 @@ use crate::lower::select::LowerInputs;
use crate::pipeline::compile::{compile_bitcode, EntryRef};
use crate::pipeline::facts::RuntimeFact;
use crate::pipeline::interface::{
AccessSet, BufferForm, DescriptorView, PushLoc, SlotInterface, StageDescriptor, StageSpec,
Window,
AccessSet, BufferForm, PushLoc, SlotInterface, StageDescriptor, StageSpec, Window,
};
use crate::pipeline::link::{LinkInputs, LinkTable};
use crate::pipeline::relocate::relocate;
@@ -79,11 +78,7 @@ fn check_artifact(a: &FunctionArtifact, what: &str) {
};
assert_eq!(b.access, AccessSet::WRITE, "{what}");
assert_eq!(b.window, Window::Bounded { start: 0, len: 4 }, "{what}");
assert_eq!(
b.form,
BufferForm::Descriptor(DescriptorView::Storage),
"{what}"
);
assert_eq!(b.form, BufferForm::Descriptor, "{what}");
assert_eq!(i.slots.len(), 1, "{what}");
let placed: Vec<(PushField, PushLoc)> =
i.push.fields.iter().map(|f| (f.field, f.loc)).collect();
@@ -1,311 +0,0 @@
//! The variant a plan names for Profile F's per-stage storage-buffer fallback
//! (`VariantKey::storage_view_slots`) is a fixed point: the plan of the pipeline compiled under a
//! plan's key, for the same shape, states the same key (`BindingPlan::variant`'s contract).
//!
//! A synthetic vertex function (four read-only `device` arrays and a `[[stage_in]]` attribute)
//! fits Profile F's four storage buffers per stage (`runtime-floor` without device addresses, a
//! device below the runtime's floor) until a shape's unaligned vertex buffer asks
//! for the pulled-layout variant, whose pulled source is a fifth storage buffer; the owned kernel
//! `descriptor_limit_uniform_views` needs the fallback on its own. Every shape binds each array
//! small or large (a length class above `maxUniformBufferRange`).
use std::collections::BTreeSet;
use crate::bind::{BindState, BoundBuffer, StageTable};
use crate::budget::Budget;
use crate::device::{Device, DevicePolicy};
use crate::error::{Error, Feature};
use crate::library::Library;
use crate::metal::VertexFormat;
use crate::pipeline::descriptor::{
VertexAttributeDescriptor, VertexBufferLayoutDescriptor, VertexDescriptor,
};
use crate::pipeline::interface::{BufferForm, DescriptorView, SlotInterface};
use crate::pipeline::sym::{SlotClass, SlotRef, Stage};
use crate::pipeline::testing::{engine_dir, llvm_assemble, AssembleError, Scratch};
use crate::pipeline::{
ComputePipelineDescriptor, FunctionDescriptor, LoweringInputs, RenderPipeline,
RenderPipelineDescriptor, RuntimeFact, StageSource, UniformViewChoice,
};
/// Profile F: `runtime-floor` without device addresses, below the runtime's floor.
fn profile_f() -> Device {
crate::pipeline::testing::device_f(DevicePolicy::RESIDENT_TABLES).expect("Profile F")
}
fn assembled(result: Result<Vec<u8>, AssembleError>, name: &str) -> Option<Vec<u8>> {
match result {
Ok(b) => Some(b),
Err(AssembleError::Missing(why)) => {
eprintln!("SKIPPED: {why}");
None
}
Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected {name}: {why}"),
}
}
/// `text` assembled through a scratch file this test owns and removes.
fn assemble(name: &str, text: &str) -> Option<Vec<u8>> {
let scratch = Scratch::new(&format!("m2v-storage-view-variant-{name}"));
let dir = scratch.path();
let ll = dir.join(format!("{name}.ll"));
std::fs::write(&ll, text).expect("write");
let r = llvm_assemble(&ll);
assembled(r, name)
}
const VERTEX: &str = r#"target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32"
target triple = "air64_v28-apple-macosx26.0.0"
define <{ <4 x float> }> @probe(<4 x float> %0, ptr addrspace(1) noundef readonly "air-buffer-no-alias" %1, ptr addrspace(1) noundef readonly "air-buffer-no-alias" %2, ptr addrspace(1) noundef readonly "air-buffer-no-alias" %3, ptr addrspace(1) noundef readonly "air-buffer-no-alias" %4, i32 noundef %5) local_unnamed_addr #0 {
%z = zext i32 %5 to i64
%p1 = getelementptr inbounds float, ptr addrspace(1) %1, i64 %z
%v1 = load float, ptr addrspace(1) %p1, align 4
%p2 = getelementptr inbounds float, ptr addrspace(1) %2, i64 %z
%v2 = load float, ptr addrspace(1) %p2, align 4
%p3 = getelementptr inbounds float, ptr addrspace(1) %3, i64 %z
%v3 = load float, ptr addrspace(1) %p3, align 4
%p4 = getelementptr inbounds float, ptr addrspace(1) %4, i64 %z
%v4 = load float, ptr addrspace(1) %p4, align 4
%s1 = fadd float %v1, %v2
%s2 = fadd float %v3, %v4
%s = fadd float %s1, %s2
%x = extractelement <4 x float> %0, i64 0
%xs = fadd float %x, %s
%out = insertelement <4 x float> %0, float %xs, i64 0
%r = insertvalue <{ <4 x float> }> undef, <4 x float> %out, 0
ret <{ <4 x float> }> %r
}
attributes #0 = { nounwind }
!air.vertex = !{!9}
!llvm.module.flags = !{!3, !4, !5, !6, !7, !8}
!air.version = !{!73}
!air.language_version = !{!74}
!3 = !{i32 7, !"air.max_device_buffers", i32 31}
!4 = !{i32 7, !"air.max_constant_buffers", i32 31}
!5 = !{i32 7, !"air.max_threadgroup_buffers", i32 31}
!6 = !{i32 7, !"air.max_textures", i32 128}
!7 = !{i32 7, !"air.max_read_write_textures", i32 8}
!8 = !{i32 7, !"air.max_samplers", i32 16}
!9 = !{ptr @probe, !10, !16}
!10 = !{!11}
!11 = !{!"air.position", !"air.arg_type_name", !"float4", !"air.arg_name", !"position"}
!16 = !{!17, !21, !22, !23, !24, !25}
!17 = !{i32 0, !"air.vertex_input", !"air.location_index", i32 0, i32 1, !"air.arg_type_name", !"float4", !"air.arg_name", !"position"}
!21 = !{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"float", !"air.arg_name", !"a"}
!22 = !{i32 2, !"air.buffer", !"air.location_index", i32 2, i32 1, !"air.read", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"float", !"air.arg_name", !"b"}
!23 = !{i32 3, !"air.buffer", !"air.location_index", i32 3, i32 1, !"air.read", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"float", !"air.arg_name", !"c"}
!24 = !{i32 4, !"air.buffer", !"air.location_index", i32 4, i32 1, !"air.read", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"float", !"air.arg_name", !"d"}
!25 = !{i32 5, !"air.vertex_id", !"air.arg_type_name", !"uint", !"air.arg_name", !"vid"}
!73 = !{i32 2, i32 8, i32 0}
!74 = !{!"Metal", i32 4, i32 0, i32 0}
"#;
fn buf(length: u64, offset: u64, gpu: u64) -> BoundBuffer {
BoundBuffer::Buffer {
length,
offset,
gpu_address: gpu,
device_address: None,
attribute_stride: None,
}
}
fn slot(stage: Stage, index: u32) -> SlotRef {
SlotRef {
stage,
class: SlotClass::Buffer,
index,
}
}
/// A buffer length that fits a uniform range, and one whose length class does not.
const SMALL: u64 = 1024;
const LARGE: u64 = 65536;
/// The vertex pipeline: position from layout 0 (stride 16), arrays at buffers 1 to 4.
fn vertex_descriptor(dev: &Device, bc: &[u8]) -> (RenderPipelineDescriptor, RenderPipeline) {
let lib = Library::from_air(bc).expect("library");
let v = lib.function("probe").expect("probe");
let mut d = RenderPipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new(v)));
let mut vd = VertexDescriptor::new();
vd.layouts
.insert(0, VertexBufferLayoutDescriptor::new(Some(16)));
vd.attributes.insert(
0,
VertexAttributeDescriptor::new(VertexFormat::Float4, 0, 0),
);
d.vertex_descriptor = Some(vd);
let base = dev
.compile_render_pipeline(&d, &Budget::standard())
.expect("base compile");
(d, base)
}
/// The vertex shape: the vertex buffer at bind offset `offset`, and array `k` (buffer `k + 1`)
/// of `lengths[k]` bytes.
fn vertex_state(offset: u64, lengths: [u64; 4]) -> BindState {
let mut t = StageTable::default();
t.buffers.insert(0, buf(16 * 64, offset, 0x10_0000_0000));
for (k, len) in lengths.iter().enumerate() {
let index = k as u32 + 1;
t.buffers.insert(
index,
buf(*len, 0, 0x10_0000_0000 + u64::from(index) * 0x1_0000_0000),
);
}
let mut state = BindState::default();
state.stages.insert(Stage::Vertex, t);
state
}
fn form(slots: &std::collections::BTreeMap<SlotRef, SlotInterface>, s: SlotRef) -> BufferForm {
match slots.get(&s) {
Some(SlotInterface::Buffer(b)) => b.form,
other => panic!("{s:?}: {other:?}"),
}
}
/// The verifier's reproducer: four storage buffers fit, so the base pipeline runs no fallback,
/// yet states its candidates (`Spare`); an unaligned vertex buffer asks for the pulled variant,
/// whose fifth storage buffer makes its fallback view an array, and a large array at buffer 4.
/// The plan names buffer 4 kept already, so the variant views another array and its plan states
/// the same key.
#[test]
fn a_newly_pulled_layout_keeps_the_large_candidates_storage_views() {
let Some(bc) = assemble("vertex", VERTEX) else {
return;
};
let dev = profile_f();
let (d, base) = vertex_descriptor(&dev, &bc);
for index in 1..=4 {
let s = slot(Stage::Vertex, index);
assert_eq!(
form(&base.interface.slots, s),
BufferForm::Descriptor(DescriptorView::Storage)
);
assert!(base.dependencies.iter().any(|dep| dep.fact
== RuntimeFact::UniformViewRange {
slot: s,
choice: UniformViewChoice::Spare,
}));
}
let state = vertex_state(50, [SMALL, SMALL, SMALL, LARGE]);
let plan = base.plan(&dev, &state.shape()).expect("base plan");
assert_eq!(plan.variant.pulled_vertex_buffers, BTreeSet::from([0]));
assert_eq!(
plan.variant.storage_view_slots,
BTreeSet::from([slot(Stage::Vertex, 4)])
);
let var = dev
.compile_render_variant(&d, &plan.variant, &Budget::standard())
.expect("variant compile");
assert_eq!(
form(&var.interface.slots, slot(Stage::Vertex, 4)),
BufferForm::Descriptor(DescriptorView::Storage)
);
assert_eq!(
form(&var.interface.slots, slot(Stage::Vertex, 3)),
BufferForm::Descriptor(DescriptorView::UniformWords)
);
let vplan = var.plan(&dev, &state.shape()).expect("variant plan");
assert_eq!(vplan.variant, plan.variant, "a fixed point");
}
/// For every shape of the vertex pipeline (the vertex buffer aligned or not, each array small or
/// large), the plan of the pipeline compiled under the base plan's key states the same key, or
/// that compile refuses the per-stage limit (the pulled source with every array large).
#[test]
fn every_render_variant_plan_states_its_own_key() {
let Some(bc) = assemble("vertex_all", VERTEX) else {
return;
};
let dev = profile_f();
let (d, base) = vertex_descriptor(&dev, &bc);
let (mut variants, mut refused) = (0, 0);
for offset in [0, 50] {
for bits in 0..16u32 {
let lengths = [0, 1, 2, 3].map(|k| if bits >> k & 1 == 1 { LARGE } else { SMALL });
let state = vertex_state(offset, lengths);
let plan = base.plan(&dev, &state.shape()).expect("base plan");
if plan.variant.is_empty() {
continue;
}
variants += 1;
match dev.compile_render_variant(&d, &plan.variant, &Budget::standard()) {
Ok(var) => {
let vplan = var.plan(&dev, &state.shape()).expect("variant plan");
assert_eq!(vplan.variant, plan.variant, "{offset} {lengths:?}");
}
Err(Error::Unsupported(u)) if u.feature == Feature::DescriptorCount => {
assert_eq!(lengths, [LARGE; 4], "{offset}");
refused += 1;
}
Err(e) => panic!("{offset} {lengths:?}: {e}"),
}
}
}
assert_eq!((variants, refused), (16, 1), "every unaligned shape pulls");
}
/// For every shape of the owned kernel (each read-only array small or large), the plan of the
/// kernel compiled under the base plan's key states the same key, or that compile refuses the
/// per-stage limit (every candidate large).
#[test]
fn every_kernel_variant_plan_states_its_own_key() {
const ENTRY: &str = "descriptor_limit_uniform_views";
let Some(bc) = assembled(
llvm_assemble(&engine_dir().join(format!("{ENTRY}.ll"))),
ENTRY,
) else {
return;
};
let dev = profile_f();
let compile = |inputs: &LoweringInputs| {
let lib = Library::from_air(&bc).expect("library");
let f = lib.function(ENTRY).expect("function");
let compiled =
dev.compile_function(&FunctionDescriptor::new(f), inputs, &Budget::standard())?;
dev.compile_compute_pipeline(
&ComputePipelineDescriptor::new(StageSource::Compiled(compiled)),
&Budget::standard(),
)
};
let base = compile(&LoweringInputs::new()).expect("base");
let (mut variants, mut refused) = (0, 0);
for bits in 0..16u32 {
let mut t = StageTable::default();
for (k, index) in [0u32, 1, 2, 4].into_iter().enumerate() {
let len = if bits >> k & 1 == 1 { LARGE } else { SMALL };
t.buffers.insert(
index,
buf(len, 0, 0x10_0000_0000 + u64::from(index) * 0x1_0000_0000),
);
}
t.buffers.insert(3, buf(256, 0, 0x13_0000_0000));
t.buffers.insert(5, buf(SMALL, 0, 0x15_0000_0000));
let mut state = BindState::default();
state.stages.insert(Stage::Kernel, t);
let plan = base.plan(&dev, &state.shape()).expect("base plan");
if plan.variant.is_empty() {
continue;
}
variants += 1;
match compile(&plan.variant.lowering_inputs(Stage::Kernel)) {
Ok(var) => {
let vplan = var.plan(&dev, &state.shape()).expect("variant plan");
assert_eq!(vplan.variant, plan.variant, "{bits:04b}");
}
Err(Error::Unsupported(u)) if u.feature == Feature::DescriptorCount => refused += 1,
Err(e) => panic!("{bits:04b}: {e}"),
}
}
// A large `constant` array asks (8 shapes); of those, the ones leaving fewer than two small
// `device` arrays to view refuse.
assert!(
variants > 0 && refused > 0,
"{variants} variants, {refused} refused"
);
}
@@ -32,7 +32,7 @@ use crate::pipeline::descriptor::{
};
use crate::pipeline::facts::RuntimeFact;
use crate::pipeline::interface::{
AccessSet, BufferForm, BufferSlot, DescriptorView, PushLoc, SlotInterface, Window,
AccessSet, BufferForm, BufferSlot, PushLoc, SlotInterface, Window,
};
use crate::pipeline::link::vertex::vertex_fetch_projection;
use crate::pipeline::link::{link, LinkInputs};
@@ -298,7 +298,7 @@ fn pulled_attributes_compile_and_state_their_inputs() {
a.interface.slots.get(&slot(b)),
Some(SlotInterface::Buffer(s)) if s.access == AccessSet::READ
&& s.window == Window::Whole
&& s.form == BufferForm::Descriptor(DescriptorView::Storage)
&& s.form == BufferForm::Descriptor
),
"{what} {b}: {:?}",
a.interface.slots.get(&slot(b))
@@ -525,7 +525,7 @@ fn a_source_buffer_shares_its_arguments_slot() {
assert!(
s.is_some_and(|s| s.access == AccessSet::READ
&& s.window == Window::Whole
&& s.form == BufferForm::Descriptor(DescriptorView::Storage)),
&& s.form == BufferForm::Descriptor),
"{what}: {s:?}"
);
assert_eq!(buffer_slot(&a, 0), None, "{what}: buffer 0 is not read");
@@ -623,11 +623,7 @@ fn the_descriptor_limit_fallback_moves_source_buffers() {
assert_eq!(form(3), Some(BufferForm::Psb), "{stem}");
assert_eq!(form(2), Some(BufferForm::Psb), "{stem}");
for b in [0, 1] {
assert_eq!(
form(b),
Some(BufferForm::Descriptor(DescriptorView::Storage)),
"{stem} {b}"
);
assert_eq!(form(b), Some(BufferForm::Descriptor), "{stem} {b}");
}
let storage = a
.interface
@@ -827,11 +823,7 @@ fn a_written_or_atomic_argument_shares_its_slot() {
assert_eq!(s.access, AccessSet::READ_WRITE, "{what}");
assert_eq!(s.window, Window::Whole, "{what}");
if how == "shared" {
assert_eq!(
s.form,
BufferForm::Descriptor(DescriptorView::Storage),
"{what}"
);
assert_eq!(s.form, BufferForm::Descriptor, "{what}");
assert_eq!(
bindings_of(&a, 1),
[vk::DescriptorType::STORAGE_BUFFER],
-2
View File
@@ -93,7 +93,6 @@ mod engine_inline_asm;
mod engine_integer_median3;
mod engine_kernel_lod;
mod engine_kernel_stage_in;
mod engine_lane_reads;
mod engine_lazy_operands;
mod engine_line_band;
mod engine_link;
@@ -175,7 +174,6 @@ mod engine_stage_io_tail;
mod engine_stage_root_attributes;
mod engine_stencil;
mod engine_stitched;
mod engine_storage_view_variant;
mod engine_swizzled_storage;
mod engine_table_copies;
mod engine_tables;
+4 -25
View File
@@ -926,7 +926,6 @@ enum metal2vulkan::pipeline::BindingSource #[cfg_attr(feature = "serde", derive(
enum metal2vulkan::pipeline::BufferForm #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum BufferForm
enum metal2vulkan::pipeline::BufferKind #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum BufferKind
enum metal2vulkan::pipeline::ChannelWrite #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum ChannelWrite
enum metal2vulkan::pipeline::DescriptorView #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum DescriptorView
enum metal2vulkan::pipeline::EntryRef #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum EntryRef<'a>
enum metal2vulkan::pipeline::FactorLane #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum FactorLane
enum metal2vulkan::pipeline::HandleClass #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum HandleClass
@@ -955,7 +954,6 @@ enum metal2vulkan::pipeline::StorageFormatClass #[cfg_attr(feature = "serde", de
enum metal2vulkan::pipeline::StorageImageClass #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum StorageImageClass
enum metal2vulkan::pipeline::Symbol #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum Symbol
enum metal2vulkan::pipeline::SyntheticBinding #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum SyntheticBinding
enum metal2vulkan::pipeline::UniformViewChoice #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum UniformViewChoice
enum metal2vulkan::pipeline::VertexFetch #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum VertexFetch
enum metal2vulkan::pipeline::VertexStride #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum VertexStride
enum metal2vulkan::pipeline::Window #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum Window
@@ -2098,11 +2096,9 @@ field metal2vulkan::bind::BindState.stage_in_region pub stage_in_region: Option<
field metal2vulkan::bind::BindState.stages pub stages: BTreeMap<Stage, StageTable>
field metal2vulkan::bind::BindState.tessellation_factors pub tessellation_factors: TessellationFactors
field metal2vulkan::bind::BindState.tile_threadgroup pub tile_threadgroup: TileThreadgroupMemory
field metal2vulkan::bind::BindState.uniform_views_at_residual pub uniform_views_at_residual: bool
field metal2vulkan::bind::BindState.used_in_token_order pub used_in_token_order: bool
field metal2vulkan::bind::BindState.used_resources pub used_resources: Vec<UsedResource>
field metal2vulkan::bind::BindState.vertex_amplification pub vertex_amplification: VertexAmplification
field metal2vulkan::bind::BindState.view_base_alignment pub view_base_alignment: u32
field metal2vulkan::bind::BindState.viewport_count pub viewport_count: u32
field metal2vulkan::bind::BindState.zeroed_colors pub zeroed_colors: BTreeMap<u32, metal::PixelFormat>
field metal2vulkan::bind::BindingPlan.compute pub compute: Option<ComputeTemplate>
@@ -2127,7 +2123,6 @@ field metal2vulkan::bind::BufferExtent.window pub window: Window
field metal2vulkan::bind::BufferRange.offset pub offset: u64
field metal2vulkan::bind::BufferRange.range pub range: u64
field metal2vulkan::bind::BufferRanges.storage pub storage: u32
field metal2vulkan::bind::BufferRanges.uniform pub uniform: u32
field metal2vulkan::bind::ByteRange.len pub len: u64
field metal2vulkan::bind::ByteRange.offset pub offset: u64
field metal2vulkan::bind::DescriptorBytes.binding pub binding: u32
@@ -2372,7 +2367,6 @@ field metal2vulkan::bind::StageShape.samplers pub samplers: BTreeMap<u32, BoundS
field metal2vulkan::bind::StageShape.textures pub textures: BTreeMap<u32, TextureShape>
field metal2vulkan::bind::StageShape.threadgroup_lengths pub threadgroup_lengths: BTreeMap<u32, u32>
field metal2vulkan::bind::StageTable.acceleration_structures pub acceleration_structures: BTreeMap<u32, BoundAccelerationStructure>
field metal2vulkan::bind::StageTable.at_bind_views pub at_bind_views: u64
field metal2vulkan::bind::StageTable.buffer_ranges pub buffer_ranges: BufferRanges
field metal2vulkan::bind::StageTable.buffers pub buffers: BTreeMap<u32, BoundBuffer>
field metal2vulkan::bind::StageTable.samplers pub samplers: BTreeMap<u32, BoundSampler>
@@ -2494,7 +2488,6 @@ field metal2vulkan::cache::VariantKey.replay_bindings pub replay_bindings: bool
field metal2vulkan::cache::VariantKey.rotated_weights pub rotated_weights: bool
field metal2vulkan::cache::VariantKey.srgb_textures pub srgb_textures: BTreeSet<SlotRef>
field metal2vulkan::cache::VariantKey.storage_images pub storage_images: BTreeMap<SlotRef, StorageImageChoice>
field metal2vulkan::cache::VariantKey.storage_view_slots pub storage_view_slots: BTreeSet<SlotRef>
field metal2vulkan::cache::VariantKey.swizzled_storage pub swizzled_storage: BTreeSet<SlotRef>
field metal2vulkan::cache::VariantKey.texel_buffer_parts pub texel_buffer_parts: BTreeMap<SlotRef, u32>
field metal2vulkan::cache::VariantKey.texel_rows pub texel_rows: BTreeSet<SlotRef>
@@ -3020,7 +3013,6 @@ field metal2vulkan::pipeline::LoweringInputs.signed_color_attachments pub signed
field metal2vulkan::pipeline::LoweringInputs.srgb_textures pub srgb_textures: BTreeSet<SlotRef>
field metal2vulkan::pipeline::LoweringInputs.stage_input pub stage_input: Option<StageInputDescriptor>
field metal2vulkan::pipeline::LoweringInputs.storage_images pub storage_images: BTreeMap<SlotRef, StorageImageChoice>
field metal2vulkan::pipeline::LoweringInputs.storage_view_slots pub storage_view_slots: BTreeSet<SlotRef>
field metal2vulkan::pipeline::LoweringInputs.swizzled_storage pub swizzled_storage: BTreeSet<SlotRef>
field metal2vulkan::pipeline::LoweringInputs.texel_buffer_parts pub texel_buffer_parts: BTreeMap<SlotRef, u32>
field metal2vulkan::pipeline::LoweringInputs.texel_rows pub texel_rows: BTreeSet<SlotRef>
@@ -6782,8 +6774,8 @@ method metal2vulkan::bind::BindingPlan::sampler_tables pub fn sampler_tables(&se
method metal2vulkan::bind::BindingPlan::specialized_value pub fn specialized_value(&self, key: SpecKey) -> Option<u64>
method metal2vulkan::bind::BindingPlan::unit_axes_variant pub fn unit_axes_variant(&self, dispatch: &Dispatch) -> Result<Option<VariantKey>, BindError>
method metal2vulkan::bind::BoundAccelerationStructure::new pub fn new(instance_count: u32) -> BoundAccelerationStructure
method metal2vulkan::bind::BoundBuffer::same_shape pub fn same_shape(&self, other: &BoundBuffer, view_base_alignment: u32, ranges: BufferRanges) -> bool
method metal2vulkan::bind::BoundBuffer::shape pub fn shape(&self, view_base_alignment: u32, ranges: BufferRanges) -> BufferShape
method metal2vulkan::bind::BoundBuffer::same_shape pub fn same_shape(&self, other: &BoundBuffer, ranges: BufferRanges) -> bool
method metal2vulkan::bind::BoundBuffer::shape pub fn shape(&self, ranges: BufferRanges) -> BufferShape
method metal2vulkan::bind::BoundSampler::new pub fn new(desc: SamplerDescriptor) -> BoundSampler
method metal2vulkan::bind::BoundSampler::shape pub fn shape(&self) -> BoundSamplerShape
method metal2vulkan::bind::BoundTexture::shape pub fn shape(&self) -> TextureShape
@@ -6920,8 +6912,7 @@ method metal2vulkan::bind::SparseTileMap::tile pub fn tile(&self) -> [u32; 3]
method metal2vulkan::bind::SparseTileMap::to_bytes pub fn to_bytes(&self) -> Vec<u8>
method metal2vulkan::bind::SparseTileMap::update pub fn update(&mut self, mode: TileMapping, level: u32, slice: u32, origin: [u32; 3], size: [u32; 3]) -> Result<(), TileMapError>
method metal2vulkan::bind::StageInRegion::new pub fn new(origin: [u32; 3], size: [u32; 3]) -> StageInRegion
method metal2vulkan::bind::StageTable::class_alignment pub fn class_alignment(&self, index: u32, view_base_alignment: u32) -> u32
method metal2vulkan::bind::StageTable::shape pub fn shape(&self, view_base_alignment: u32) -> StageShape
method metal2vulkan::bind::StageTable::shape pub fn shape(&self) -> StageShape
method metal2vulkan::bind::StatusBits::contains pub const fn contains(self, other: StatusBits) -> bool
method metal2vulkan::bind::StatusWord::byte_offset pub const fn byte_offset(self) -> u32
method metal2vulkan::bind::StatusWord::index pub const fn index(self) -> u32
@@ -7218,7 +7209,6 @@ method metal2vulkan::pipeline::AliasView::new pub fn new(image_format: vk::Forma
method metal2vulkan::pipeline::AmplificationDraws::new pub fn new(layered: bool, viewports: bool) -> AmplificationDraws
method metal2vulkan::pipeline::BandPrimitive::patch_control_points pub fn patch_control_points(self) -> u32
method metal2vulkan::pipeline::BlendState::reads_second_output pub fn reads_second_output(&self) -> bool
method metal2vulkan::pipeline::BufferForm::uniform_view pub fn uniform_view(self) -> bool
method metal2vulkan::pipeline::ColorAttachmentDescriptor::new pub fn new(pixel_format: metal::PixelFormat) -> ColorAttachmentDescriptor
method metal2vulkan::pipeline::ColorAttachmentDescriptor::specialized #[must_use] pub fn specialized(&self) -> ColorAttachmentDescriptor
method metal2vulkan::pipeline::ColorAttachmentState::new pub fn new(format: vk::Format, write_mask: vk::ColorComponentFlags, blend: Option<BlendState>) -> ColorAttachmentState
@@ -9596,7 +9586,6 @@ variant metal2vulkan::bind::AccessClass::Sampled Sampled
variant metal2vulkan::bind::AccessClass::Storage Storage
variant metal2vulkan::bind::AccessClass::StorageImage StorageImage
variant metal2vulkan::bind::AccessClass::TexelRows TexelRows
variant metal2vulkan::bind::AccessClass::Uniform Uniform
variant metal2vulkan::bind::AccessClass::VertexInput VertexInput
variant metal2vulkan::bind::AccessClass::YCbCrPlanes YCbCrPlanes
variant metal2vulkan::bind::ArgumentLayoutError::ArrayOfArrays ArrayOfArrays { id: u32 }
@@ -10353,7 +10342,6 @@ variant metal2vulkan::error::BindError::SlotOutOfRange SlotOutOfRange { slot: Sl
variant metal2vulkan::error::BindError::TessellationFactorRange TessellationFactorRange { needed: u64, limit: u64 }
variant metal2vulkan::error::BindError::TexelBufferTooLarge TexelBufferTooLarge { slot: SlotRef, elements: u64, limit: u64 }
variant metal2vulkan::error::BindError::UnboundVertexBuffer UnboundVertexBuffer { slot: SlotRef }
variant metal2vulkan::error::BindError::UniformViewAliased UniformViewAliased { slot: SlotRef, written: SlotRef }
variant metal2vulkan::error::BindError::Unsupported Unsupported(Unsupported)
variant metal2vulkan::error::BitcodeError::BadDataLayout BadDataLayout
variant metal2vulkan::error::BitcodeError::BadIdentification BadIdentification
@@ -10784,7 +10772,7 @@ variant metal2vulkan::pipeline::BindingSource::Texture Texture(SlotRef)
variant metal2vulkan::pipeline::BindingSource::TileAttachment TileAttachment(u32)
variant metal2vulkan::pipeline::BindingSource::TileMap TileMap(SlotRef)
variant metal2vulkan::pipeline::BindingSource::YCbCrPlanes YCbCrPlanes(SlotRef)
variant metal2vulkan::pipeline::BufferForm::Descriptor Descriptor(DescriptorView)
variant metal2vulkan::pipeline::BufferForm::Descriptor Descriptor
variant metal2vulkan::pipeline::BufferForm::Psb Psb
variant metal2vulkan::pipeline::BufferKind::Buffer Buffer
variant metal2vulkan::pipeline::BufferKind::IntersectionFunctionTable IntersectionFunctionTable
@@ -10797,9 +10785,6 @@ variant metal2vulkan::pipeline::ChannelWrite::HalfUnorm HalfUnorm { bits: u8 }
variant metal2vulkan::pipeline::ChannelWrite::Snorm Snorm { bits: u8, blended: bool }
variant metal2vulkan::pipeline::ChannelWrite::Srgb Srgb
variant metal2vulkan::pipeline::ChannelWrite::Unorm Unorm { bits: u8 }
variant metal2vulkan::pipeline::DescriptorView::Storage Storage
variant metal2vulkan::pipeline::DescriptorView::UniformVec4 UniformVec4
variant metal2vulkan::pipeline::DescriptorView::UniformWords UniformWords
variant metal2vulkan::pipeline::EntryRef::Index Index(u32)
variant metal2vulkan::pipeline::EntryRef::Name Name(&'a str)
variant metal2vulkan::pipeline::FactorLane::One One
@@ -11074,8 +11059,6 @@ variant metal2vulkan::pipeline::RuntimeFact::TileFunction TileFunction
variant metal2vulkan::pipeline::RuntimeFact::TileImageblock TileImageblock { data_size: u32, alignment: u32 }
variant metal2vulkan::pipeline::RuntimeFact::TileThreadgroup TileThreadgroup { tile_sized: bool }
variant metal2vulkan::pipeline::RuntimeFact::TileThreadgroupMemory TileThreadgroupMemory { index: u32 }
variant metal2vulkan::pipeline::RuntimeFact::UniformViewAliasing UniformViewAliasing { slot: SlotRef }
variant metal2vulkan::pipeline::RuntimeFact::UniformViewRange UniformViewRange { slot: SlotRef, choice: UniformViewChoice }
variant metal2vulkan::pipeline::RuntimeFact::UnitAxes UnitAxes { axes: u8, relief: u8 }
variant metal2vulkan::pipeline::RuntimeFact::VertexBufferStride VertexBufferStride { layout: u32 }
variant metal2vulkan::pipeline::RuntimeFact::VertexFetch VertexFetch { attr: u32 }
@@ -11115,7 +11098,6 @@ variant metal2vulkan::pipeline::SpecKey::ObjectMultiRegion ObjectMultiRegion
variant metal2vulkan::pipeline::SpecKey::OffsetBaseAxes OffsetBaseAxes(SlotRef)
variant metal2vulkan::pipeline::SpecKey::OutOfBoundsAlpha OutOfBoundsAlpha(SlotRef)
variant metal2vulkan::pipeline::SpecKey::Presence Presence(SlotRef)
variant metal2vulkan::pipeline::SpecKey::RangeAtBindOffset RangeAtBindOffset(SlotRef)
variant metal2vulkan::pipeline::SpecKey::RenderAreaHeight RenderAreaHeight
variant metal2vulkan::pipeline::SpecKey::RenderAreaWidth RenderAreaWidth
variant metal2vulkan::pipeline::SpecKey::SampleCount SampleCount
@@ -11164,9 +11146,6 @@ variant metal2vulkan::pipeline::SyntheticBinding::RootTable RootTable
variant metal2vulkan::pipeline::SyntheticBinding::SamplerTable SamplerTable
variant metal2vulkan::pipeline::SyntheticBinding::TessellationFactors TessellationFactors
variant metal2vulkan::pipeline::SyntheticBinding::TileMemory TileMemory
variant metal2vulkan::pipeline::UniformViewChoice::Kept Kept
variant metal2vulkan::pipeline::UniformViewChoice::Spare Spare
variant metal2vulkan::pipeline::UniformViewChoice::Viewed Viewed
variant metal2vulkan::pipeline::VertexFetch::FixedFunction FixedFunction
variant metal2vulkan::pipeline::VertexFetch::Pulled Pulled { format: metal::VertexFormat, buffer_index: u32, offset: u32, step_function: metal::VertexStepFunction, step_rate: u32 }
variant metal2vulkan::pipeline::VertexFetch::SignedFixedFunction SignedFixedFunction
Can't render this file because it is too large.
-2
View File
@@ -367,7 +367,6 @@ surface! {
enum BufferKind N;
struct BufferSlot N;
struct CommandWrites E;
enum DescriptorView N;
struct LevelReads N;
enum NumberedSampler N;
enum PatchDomain N;
@@ -405,7 +404,6 @@ surface! {
struct RenderPipelineKeys N;
enum Mechanism N;
enum RuntimeFact N;
enum UniformViewChoice N;
enum AccelerationStructureLevel N;
struct AirUserKey E;
enum Axis N;
+13 -29
View File
@@ -1166,8 +1166,6 @@ for dependency in &pipeline.dependencies {
where it does not push set 0; the rest stay of their own types. Keep a binding of several
variables static on MoltenVK 1.4.1: its SPIRV-Cross writes Metal that does not compile for a
dynamic buffer an entry point uses through more than one variable.
- A buffer slot's uniform view is a `Uniform` block (`DescriptorView::UniformWords`, or
`UniformVec4` without `uniformBufferStandardLayout`).
- On MoltenVK, push set 0 (a push descriptor set layout) for a pipeline whose fragment stage writes
a storage buffer of set 0 inside its interlock (an interlock execution mode, and a `StorageBuffer`
variable of set 0 not decorated `NonWritable`): binding through Metal argument buffers, MoltenVK
@@ -1186,29 +1184,16 @@ for dependency in &pipeline.dependencies {
`half` result also specializes one bit of it: whether the class converts its texels to `half` by
rounding to nearest even alone (every class but those with 32-bit float channels, 16-bit
normalized ones and YCbCr fields on the grid `8192`), so a slot bound to both kinds of format
takes two pipelines. Other bound values (a slot's
presence, a sampler's word, whether a uniform buffer's descriptor range starts at its bind offset)
are specialization constants. The last lets a driver load the constants ahead of the shader:
inline bytes take that form, and so does a buffer bound at a multiple of
`max(minUniformBufferOffsetAlignment, 16)` at a slot whose table tells that alignment apart
(`state.view_base_alignment`, and the slot's bit in its table's `at_bind_views`). A buffer bound at any other offset, or at a slot left out, takes the other form, a
pipeline of its own: leave out a slot bound at offsets that move, so that its draws keep one
shape and one pipeline (the runtime leaves out each slot of a state once it finds one bound at
an offset the alignment does not divide). A consumer that draws and dispatches every key with
its uniform views at their residuals (each uniform view's `RangeAtBindOffset` at 0, as the
runtime does on every device whose driver is not measured to load such reads ahead of the
shader) says so with
`state.uniform_views_at_residual = true`: its uniform views then bind ranges their bind offsets
share (below), as a bounded storage view's do. No storage view declares the key: it reads at its
residual, its range from the buffer's start, so the bytes before a bind offset stay reachable.
takes two pipelines. Other bound values (a slot's presence, a sampler's word) are
specialization constants. A buffer slot's storage view reads at its residual, its range from
the buffer's start, so the bytes before a bind offset stay reachable.
- A bound buffer's length enters its shape only as a length class (`bind::length_class`), which a
plan compares with the device's `maxUniformBufferRange` and `maxStorageBufferRange` alone
(whether every range of the buffer fits each). Set each table's
`buffer_ranges = BufferRanges::of(limits)` and its shape tells apart only the classes those
limits tell apart (`BufferRanges::length_class`: a class rounded up to the greatest one that fits
the same limits), so commands over buffers of many sizes keep one shape and one plan: on a device
whose two limits are both 4 GiB, every buffer below 4 GiB. The default tells every class apart.
The runtime sets them on every table it reads.
plan compares with the device's `maxStorageBufferRange` alone (whether every range of the
buffer fits it). Set each table's `buffer_ranges = BufferRanges::of(limits)` and its shape tells
apart only the classes that limit tells apart (`BufferRanges::length_class`: a class rounded up
to the greatest one that fits the same limit), so commands over buffers of many sizes keep one
shape and one plan: on a device whose limit is 4 GiB, every buffer below 4 GiB. The default
tells every class apart. The runtime sets it on every table it reads.
- A two-plane YCbCr texture whose planes a function may read in place states them in its facts
(`TextureFacts::ycbcr_in_place`, a `YCbCrInPlace` of its planes). A slot whose function only samples it (nearest or linear, no comparison,
anisotropy or `min_lod_clamp`), gathers it or reads its size (`RuntimeFact::YCbCrInPlace`) takes the
@@ -1392,11 +1377,10 @@ lies at or past the padded end, the range starts at the bind offset aligned down
descriptor base alignment. An access that reaches back before the bind offset, inside the buffer,
reads the buffer's bytes there, as Metal's does.
A slot of a bounded window read at its residual -- a storage view's always, a uniform view's
where the state says `uniform_views_at_residual` -- takes a range its bind offsets share in the
same way: the buffer from 0 to its padded end where that fits the view's maximum range (a uniform
view's is `maxUniformBufferRange` capped at 64 KiB, its texel form's `maxTexelBufferElements`
texels) and 4 GiB, else the block of half that
A slot of a bounded window read at its residual (a storage view's) takes a range its bind offsets
share in the same way: the buffer from 0 to its padded end where that fits the view's maximum
range (`maxStorageBufferRange`; a texel form's is `maxTexelBufferElements` texels) and 4 GiB,
else the block of half that
maximum (rounded down to a power of two) its window starts in, to the maximum past the block's
start. A window of at most half the maximum starting in a block ends inside its block's range; a
longer one, or one at or past the padded end, takes the range from its bind offset, as every
+2 -4
View File
@@ -27,7 +27,7 @@ Columns:
| Kind | Variants | With a site | Reach system | Reach app | Reach rare | Reach none | Unassessed |
|---|---|---|---|---|---|---|---|
| Translator and front-end refusals | 118 | 118 | 6 | 26 | 66 | 20 | 0 |
| Binder refusals at a device limit | 9 | 9 | 0 | 1 | 7 | 1 | 0 |
| Binder refusals at a device limit | 8 | 8 | 0 | 1 | 6 | 1 | 0 |
| Translation caps | 14 | 14 | 0 | 0 | 7 | 7 | 0 |
| Rate maps the compile layer does not compile | 5 | 5 | 0 | 0 | 4 | 1 | 0 |
| The translation deadline | 1 | 1 | 0 | 0 | 0 | 1 | 0 |
@@ -41,7 +41,7 @@ Columns:
| Kind | `metal-measured` | `metal-documented` | `metal-takes` | `device` | `ours` | `unknown` | `delegated` | `-` |
|---|---|---|---|---|---|---|---|---|
| Translator and front-end refusals | 0 | 0 | 0 | 48 | 70 | 0 | 0 | 0 |
| Binder refusals at a device limit | 0 | 0 | 0 | 9 | 0 | 0 | 0 | 0 |
| Binder refusals at a device limit | 0 | 0 | 0 | 8 | 0 | 0 | 0 | 0 |
| Translation caps | 0 | 0 | 0 | 0 | 14 | 0 | 0 | 0 |
| Rate maps the compile layer does not compile | 0 | 0 | 0 | 0 | 5 | 0 | 0 | 0 |
| The translation deadline | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 |
@@ -184,7 +184,6 @@ Columns:
| `PatchIndexRange` | The patch indices a draw reads span more bytes (`needed`) than one storage-buffer descriptor can bind (`limit`, `maxStorageBufferRange`) | at the device's limit | `device` | 1: `crates/metal2vulkan/src/bind/graphics.rs (patch_binding)` | `rare`: patch indices past one storage descriptor |
| `ControlPointIndexRange` | The control-point indices a draw reads span more bytes (`needed`) than one storage-buffer descriptor can bind (`limit`, `maxStorageBufferRange`) | at the device's limit | `device` | 1: `crates/metal2vulkan/src/bind/graphics.rs (patch_binding)` | `rare`: control-point indices past one storage descriptor |
| `MissingStageInRegion` | The kernel reads the compute encoder's stage-in region (a `[[stage_in]]` attribute stepping by thread position, or `[[grid_origin]]` or... | at the device's limit | `device` | 1: `crates/metal2vulkan/src/bind/dispatch.rs (instantiate)` | `none`: a stage-in region never set, which Metal leaves undefined |
| `UniformViewAliased` | A `device` buffer slot the pipeline reads through a uniform view (Profile F's per-stage storage-buffer fallback,... | at the device's limit | `device` | 1: `crates/metal2vulkan/src/bind/instantiate.rs (check_uniform_aliasing)` | `rare`: Profile F's uniform-view fallback aliased by a write |
| `MissingDeviceAddress` | A device-address slot received a buffer without a device address | at the device's limit | `device` | 2: `crates/metal2vulkan/src/bind/plan/slots.rs (plan_buffer)`, `crates/metal2vulkan/src/bind/replay/draws.rs (parent_entries)` | `rare`: a slot reached through a pointer loaded from memory, bound with inline bytes or on a device without device addresses |
## 3. Translation caps (`Error::LimitExceeded(Limit)`)
@@ -511,7 +510,6 @@ Each refusal's sites, with the function that builds it.
- `bind::PatchIndexRange`: `crates/metal2vulkan/src/bind/graphics.rs (patch_binding)`
- `bind::ControlPointIndexRange`: `crates/metal2vulkan/src/bind/graphics.rs (patch_binding)`
- `bind::MissingStageInRegion`: `crates/metal2vulkan/src/bind/dispatch.rs (instantiate)`
- `bind::UniformViewAliased`: `crates/metal2vulkan/src/bind/instantiate.rs (check_uniform_aliasing)`
- `bind::MissingDeviceAddress`: `crates/metal2vulkan/src/bind/plan/slots.rs (plan_buffer)`; `crates/metal2vulkan/src/bind/replay/draws.rs (parent_entries)`
- `limit::InlinedInstructions`: `crates/metal2vulkan-air/src/canon/inline.rs (inline)`; `crates/metal2vulkan-air/src/canon/inline.rs (u32_of)`; `crates/metal2vulkan-air/src/canon/inline.rs (usize_of)`
- `limit::OutputBlocks`: `crates/metal2vulkan/src/structurize/irreducible.rs (round)`; `crates/metal2vulkan/src/structurize/mod.rs (structure_loops)`; `crates/metal2vulkan/src/structurize/structurizer_properties/mod.rs (output_cap_is_checked_before_allocating)`; `crates/metal2vulkan/src/structurize/structurizer_properties/trees.rs (the_output_cap_is_checked_before_emission)`
-1
View File
@@ -124,7 +124,6 @@ bind TessellationFactorRange rare tessellation factors past one storage descript
bind PatchIndexRange rare patch indices past one storage descriptor
bind ControlPointIndexRange rare control-point indices past one storage descriptor
bind MissingStageInRegion none a stage-in region never set, which Metal leaves undefined
bind UniformViewAliased rare Profile F's uniform-view fallback aliased by a write
bind MissingDeviceAddress rare a slot reached through a pointer loaded from memory, bound with inline bytes or on a device without device addresses
limit InlinedInstructions rare very large shaders after inlining
limit OutputBlocks rare very large control flow
Can't render this file because it contains an unexpected character in line 17 and column 65.
@@ -91,7 +91,6 @@ BIND_REFUSALS = [
"PatchIndexRange",
"ControlPointIndexRange",
"MissingStageInRegion",
"UniformViewAliased",
"MissingDeviceAddress",
]