SEMANTICS 2135 / RUNTIME 2458: No storage twins: a kernel's constant buffer on the Iris reads its uniform view alone

What: the Iris Xe RPL-P profile (DriverWorkaround::PushReadsLengthenThreadPayload) declares no
storage twin. A kernel's constant slot keeps its plain uniform view, read at its residual as on
every device without ConstantOffsetUniformReadsPreloaded; its set-0 layout binds the uniform view
alone. Deleted with it, everything only the twin used:
- translator: DescriptorView::UniformWithStorageTwin, BufferForm::storage_twin,
  ResourceKind::StorageTwin, BindingSource::StorageTwin, AccessPlan/Declared twins and the
  census's twin count, storage_twins, views::declare_twin/twin_symbol, emit's TwinMem, the twin's
  NonWritable statement (unwritten_buffer keeps its unaliased-argument use), PlannedBuffer::twin,
  the second DescriptorRange, buffer_uses back to buffer_use, range_at_bind_offset's unbound twin
  arm, planned_range's twin exclusion, rebinds_into's twin arm, the interpreter's twin binding,
  the codec's variants, and BindingPlan::read_only_buffer (its only reason was the twin);
- runtime: uniform_residual_form_of and reads_other_words (keyed_regions takes no flat_grid),
  the neutral zero buffer's STORAGE_BUFFER usage and plan-based read-only check (back to the
  descriptor type alone, binding::read_only_buffer);
- validation: out_of_bounds's twin arms;
- docs: API.md section 5's twin bullet, the workaround's profile doc, residual.rs, views.rs,
  ModuleBuilder::unwritten_buffer, non_writable.rs, neutral.rs, neutral_zeros_shared's docs;
  api_signatures.tsv drops the five items.
Kept: storage views' RangeAtBindOffset at offset 0 on that profile and its creation of both forms
(RUNTIME 2410), set-0 counting tests, the dispatch_chain example's arms.

Why: the twins are the confirmed cause of the Iris regression. Walk A (the tip with no twins) took
137.4 s of GPU time against 145.8 to 150.2 s for three walks with twins; Face Tracking 13.50 s
against 18.1 to 21.1, Super Resolution 25.78 against 28.2 to 28.4, Background Blur 4.93 against
5.7 to 6.4; Horizon Detection gives up about 1.3 s (17.78 against 16.2 to 16.8). No structural
rule separates where a twin pays (ftreg's report to main).

SEMANTICS and RUNTIME are bumped at landing; golden tables and the compile census are re-blessed
on development.

Test: engine_access::a_kernel_constant_slot_binds_its_uniform_view_alone. On
intel-irisxe-rplp-anv, with and without uniformBufferStandardLayout,
buffer_end_byte_load_constant's slot 0 is UniformWords/UniformVec4, its RangeAtBindOffset key is
read, and set 0 links exactly slot 0 at (0,0) and slot 1 at (0,1). A plan of nothing bound writes
those two alone in set 0 (UNIFORM_BUFFER, STORAGE_BUFFER), and only them on four other profiles.
At development the slot is UniformWithStorageTwin and set 0 holds a third binding, so it fails.

ARTIFACT_FORMAT_VERSION 524: the codec drops the twin variants.

Verified: m3-max-36704 (msi) at 2b88dec3f1 clippy --all-targets --all-features 0; m3-max-36706 clippy --cfg m2v_gpu 0. Rustdoc, the translator suites, clippy --cfg m2v_cpu_icd with the lavapipe runtime tests, and the negative control (the new test at development fails) run after the merge; golden tables and the compile census are re-blessed on development.
This commit is contained in:
Anees Iqbal committed 2026-11-16 07:51:36 -08:00
1 parent e10f3529c2
commit 8933378831
38 files changed
+208 -1347

No files matched your search

+40 -33
View File
@@ -1302,7 +1302,7 @@ pub(super) fn bind_into(
call,
device,
state,
(plan, command, tables),
(command, tables),
(write, element),
kept,
)?;
@@ -1328,7 +1328,7 @@ pub(super) fn bind_into(
call,
device,
state,
(plan, command, tables),
(command, tables),
(write, element),
kept,
)?;
@@ -1469,13 +1469,13 @@ fn written_at(
}
}
/// The write of `write`, one of `plan`'s descriptor writes, at `element`, for `command` over
/// The write of `write`, one of its plan's descriptor writes, at `element`, for `command` over
/// `tables` ([`bind_into`]): its image descriptor's sampler kept in `samplers`, through `memo`.
fn written(
call: &'static str,
device: &Device,
state: &mut State,
(plan, command, tables): (&BindingPlan, &Command<'_>, &Tables<'_>),
(command, tables): (&Command<'_>, &Tables<'_>),
(write, element): (&DescriptorWrite, u32),
(samplers, mut memo): (&mut Vec<Arc<OwnedSampler>>, Option<&mut BindMemo>),
) -> Result<Write, Error> {
@@ -1487,12 +1487,7 @@ fn written(
(_, ty) => match ty {
vk::DescriptorType::UNIFORM_BUFFER | vk::DescriptorType::STORAGE_BUFFER => {
let spaces = memo.as_deref_mut().map(|memo| &mut memo.spaces);
Info::Buffer(descriptor(
device,
state,
(plan, command, tables),
(write, spaces),
)?)
Info::Buffer(descriptor(device, state, command, tables, (write, spaces))?)
}
vk::DescriptorType::UNIFORM_TEXEL_BUFFER | vk::DescriptorType::STORAGE_TEXEL_BUFFER => {
let storage = ty == vk::DescriptorType::STORAGE_TEXEL_BUFFER;
@@ -1548,7 +1543,7 @@ pub(super) fn make_neutrals(device: &Device, plan: &BindingPlan) -> Result<(), E
// (the module docs' "no wait"), as it finds the images and samplers made.
WriteSource::Neutral(
NeutralResource::ZeroBuffer { min_bytes } | NeutralResource::Sink { min_bytes },
) if plan.read_only_buffer(write) => {
) if read_only_buffer(ty) => {
device.neutral_zero_buffer(padded(*min_bytes as usize))?;
}
WriteSource::Neutral(kind @ NeutralResource::Image { .. }) => {
@@ -2779,15 +2774,29 @@ fn unexpected(source: &WriteSource) -> Error {
}
}
/// The buffer descriptor of `write`.
/// Whether a buffer descriptor of `ty` is read-only to every shader that binds it: a uniform
/// buffer, whose block Vulkan and SPIR-V make read-only, so no store can reach it. A storage
/// buffer is not, whatever a particular shader does with it.
///
/// It decides which bindings may share the device's one neutral zero buffer (`neutral.rs`): a
/// writable binding keeps a region of its own, so nothing a shader stores is ever seen by another
/// command. Structural: the descriptor type alone, never a function or shader name.
fn read_only_buffer(ty: vk::DescriptorType) -> bool {
matches!(
ty,
vk::DescriptorType::UNIFORM_BUFFER | vk::DescriptorType::UNIFORM_BUFFER_DYNAMIC
)
}
/// Whether `plan` binds a zero region of each command's own: at a writable buffer binding that
/// nothing is bound to (not `BindingPlan::read_only_buffer`), a fresh region of the command
/// buffer's upload arena at every draw (`write_info`). A draw drawn again as it was kept, or
/// rebound, keeps the kept draw's set-0 writes at every slot but those that changed
/// (`rebind_into`), so it would bind the kept draw's region, which that draw may have written:
/// such a draw is not kept (`render/draw_again.rs`), counted as one that may write
/// (`WorkCounts::draws_unkept_writing`). It walks every write of the plan, one for each resource
/// its heap reaches in each heap array, so a draw asks its plan's facts (`render/plan_facts.rs`),
/// which hold the answer.
/// nothing is bound to ([`read_only_buffer`]), a fresh region of the command buffer's upload
/// arena at every draw (`write_info`). A draw drawn again as it was kept, or rebound, keeps the
/// kept draw's set-0 writes at every slot but those that changed (`rebind_into`), so it would
/// bind the kept draw's region, which that draw may have written: such a draw is not kept
/// (`render/draw_again.rs`), counted as one that may write (`WorkCounts::draws_unkept_writing`).
/// It walks every write of the plan, one for each resource its heap reaches in each heap array,
/// so a draw asks its plan's facts (`render/plan_facts.rs`), which hold the answer.
pub(super) fn binds_own_zeros(plan: &BindingPlan) -> bool {
#[cfg(all(test, debug_assertions, any(m2v_gpu, m2v_cpu_icd)))]
PLAN_WALKS.with(|walks| walks.set(walks.get() + plan.descriptors.len() as u64));
@@ -2796,7 +2805,7 @@ pub(super) fn binds_own_zeros(plan: &BindingPlan) -> bool {
write.source,
WriteSource::Neutral(NeutralResource::ZeroBuffer { .. } | NeutralResource::Sink { .. })
);
neutral && !plan.read_only_buffer(write)
neutral && !read_only_buffer(write.ty.into())
})
}
@@ -2861,15 +2870,15 @@ fn slot_descriptor(
}))
}
/// The buffer descriptor of `write`, one of `plan`'s descriptor writes, for `command` over
/// `tables`.
fn descriptor(
device: &Device,
state: &mut State,
(plan, command, tables): (&BindingPlan, &Command<'_>, &Tables<'_>),
command: &Command<'_>,
tables: &Tables<'_>,
(write, spaces): (&DescriptorWrite, Option<&mut KeptSpaces>),
) -> Result<vk::DescriptorBufferInfo, Error> {
let key = (write.set, write.binding);
let ty: vk::DescriptorType = write.ty.into();
let bytes = || {
(command.descriptor_bytes.iter())
.chain(command.heap_tables)
@@ -3007,20 +3016,18 @@ fn descriptor(
// The command buffer's status words, the ones every command of it writes, on a device
// that does not address buffers (`status_address` elsewhere).
WriteSource::ExecutionStatus => whole(state.status_words(device)?),
// A read-only binding (a uniform buffer, or a uniform view's storage twin:
// `BindingPlan::read_only_buffer`) takes the device's kept zero buffer, made once for its
// lifetime (`neutral.rs`): zeros of a length the device's own limits fix cannot have
// changed since it was made, and before this every draw and dispatch that bound one took
// a fresh zero-filled region, each past half the upload arena's chunk and so a dedicated
// 64 KiB `VkBuffer` allocated and written to zero. A WRITABLE binding keeps its own
// region, as every binding did: the one buffer is shared by every command of the device,
// so a shader that could store through the binding would write zeros another command
// reads.
// A read-only binding takes the device's kept zero buffer, made once for its lifetime
// (`neutral.rs`): zeros of a length the device's own limits fix cannot have changed since
// it was made, and before this every draw and dispatch that bound one took a fresh
// zero-filled region, each past half the upload arena's chunk and so a dedicated 64 KiB
// `VkBuffer` allocated and written to zero. A WRITABLE binding keeps its own region, as
// every binding did: the one buffer is shared by every command of the device, so a
// shader that could store through the binding would write zeros another command reads.
WriteSource::Neutral(
NeutralResource::ZeroBuffer { min_bytes } | NeutralResource::Sink { min_bytes },
) => {
let bytes = padded(*min_bytes as usize);
match plan.read_only_buffer(write) {
match read_only_buffer(ty) {
true => vk::DescriptorBufferInfo::default()
.buffer(device.neutral_zero_buffer(bytes)?)
.offset(0)
+8 -13
View File
@@ -304,10 +304,8 @@ impl Device {
/// Only a **read-only** binding may be served from it: every draw and dispatch of the device
/// binds the one buffer, so a shader that could store through the binding would be writing
/// zeros another command reads. A Vulkan uniform-buffer descriptor is read-only by
/// construction, and so is a uniform view's storage twin, a storage buffer its kernel only
/// loads from (`BindingPlan::read_only_buffer`): those are the bindings `binding::descriptor`
/// serves from here, so the buffer is a storage buffer too. A writable one keeps its own
/// region, as before.
/// construction, which is the binding `binding::descriptor` serves from here; a writable one
/// keeps its own region, as before.
pub(super) fn neutral_zero_buffer(&self, bytes: u64) -> Result<vk::Buffer, Error> {
let shared = self.shared();
let mut neutrals = lock(&shared.textures.neutrals);
@@ -330,18 +328,15 @@ impl Device {
/// A new zero buffer of `bytes` bytes: a `Private` buffer filled with zeros, as
/// [`Device::new_neutral_texels`] makes its one texel of zeros, so the fill is the device's
/// next submission's first work and waits for nothing. A uniform and a storage buffer
/// ([`neutral_zero_buffer`](Device::neutral_zero_buffer)).
/// next submission's first work and waits for nothing.
fn new_neutral_zeros(&self, bytes: u64) -> Result<Arc<NeutralZeros>, Error> {
let shared = self.shared();
let raw_device = shared.vk();
let info = shared
.sharing()
.buffer(vk::BufferCreateInfo::default().size(bytes).usage(
vk::BufferUsageFlags::UNIFORM_BUFFER
| vk::BufferUsageFlags::STORAGE_BUFFER
| vk::BufferUsageFlags::TRANSFER_DST,
));
let info = shared.sharing().buffer(
vk::BufferCreateInfo::default()
.size(bytes)
.usage(vk::BufferUsageFlags::UNIFORM_BUFFER | vk::BufferUsageFlags::TRANSFER_DST),
);
// SAFETY: the device is live and `info` valid.
let buffer = unsafe { crate::creation::buffer(raw_device, &info) }.map_err(vulkan)?;
// SAFETY: `buffer` is a live buffer of this device.
@@ -103,9 +103,7 @@ pub(super) use render::RenderVariant;
pub(super) use render::WeakRenderPipelineState;
/// The general and residual forms of a key (`render/residual.rs`), for `tests::general_form`.
#[cfg(test)]
pub(super) use render::{
general_form, reads_other_words, residual_form_of, uniform_residual_form_of,
};
pub(super) use render::{general_form, residual_form_of};
pub(super) use render::{reads_views_at_bind, residual_form, uniform_residual_form};
pub(super) use render::{GraphicsState, Kind as RenderStateKind, StateShared as RenderShared};
pub(super) use render::{ProgramName, Settled};
@@ -2327,22 +2325,17 @@ impl Variant {
/// `commands`' regions, each specialization with its uniform views at their residuals where
/// `device` reads no uniform view at its bind offset alone (`render/residual.rs`,
/// `uniform_residual_form`): what every region of a dispatch or a tile dispatch of the variant
/// takes before its key is looked up. A storage view's key keeps its value, and a uniform
/// view's with a storage twin where no other view of the key reads its residual and the
/// region reads no other word the binder writes for the kernel, its `DispatchRegion` words
/// among them where the region's `MultiRegion` is set or the variant runs a flat grid
/// (`uniform_residual_form_of`, `reads_other_words`).
/// takes before its key is looked up. A storage view's key keeps its value.
pub(crate) fn keyed_regions(&self, device: &Device, commands: &mut DispatchCommands) {
if reads_views_at_bind(device) {
return;
}
let constants = &self.pipeline.stage.specialization.constants;
let interface = &self.pipeline.interface;
let flat_grid = self.key.flat_grid;
for region in &mut commands.regions {
let specialization = &region.specialization;
if let Some(residual) =
uniform_residual_form(constants.iter(), interface, flat_grid, specialization)
uniform_residual_form(constants.iter(), interface, specialization)
{
region.specialization = residual;
}
@@ -97,9 +97,7 @@ pub(crate) use residual::views_read_at_bind;
/// The general and residual forms of a key, which `tests::general_form` reads from IDs and
/// meanings alone.
#[cfg(test)]
pub(crate) use residual::{
general_form, reads_other_words, residual_form_of, uniform_residual_form_of,
};
pub(crate) use residual::{general_form, residual_form_of};
pub(crate) use residual::{reads_views_at_bind, residual_form, uniform_residual_form};
/// A Metal render pipeline state (`MTLRenderPipelineState`): one that draws, or a tile pipeline's
@@ -62,16 +62,9 @@
//! specializations and the dispatches' regions take that form before any key is looked up
//! (`RenderVariant::plan`, `Variant::keyed_regions`): off that profile a state's creation makes
//! the one pipeline its draws at every bind offset take, and on it the two the module's
//! **Made at creation, both forms** names. A kernel's uniform view there has a storage twin
//! (`DescriptorView::UniformWithStorageTwin`), whose key the plan keeps where no other
//! `RangeAtBindOffset` constant of the key is 0 and the kernel reads no other word the binder
//! writes for it ([`reads_other_words`]: a root table's address, a multi-region or flat grid's
//! region): at 1 it reads the twin at its bind offset alone, not the uniform view, which pays
//! only where no such word is left to read ([`uniform_residual_form_of`]); beside a storage
//! view bound elsewhere, or such a word, it takes 0, and the uniform view at its residual. The
//! shapes and plans stay every device's (`argument_table::AtBindViews`): a bind offset the view
//! base alignment divides still makes a shape and a plan of its own, whose key's uniform views
//! alone take their residual form.
//! **Made at creation, both forms** names. The shapes and plans stay every device's
//! (`argument_table::AtBindViews`): a bind offset the view base alignment divides still makes a
//! shape and a plan of its own, whose key's uniform views alone take their residual form.
//! - **Only GPU time moves.** Until the key's making lands, its draws' uniform reads take the
//! residual: on ANV, loads where the key's form has pushed constants. `WorkCounts` counts the
//! draws and dispatches recorded so (`residual_form_draws`) and the makings begun so
@@ -126,10 +119,7 @@ use crate::pipeline::objects::RawPipeline;
use crate::render_target::RenderPassObject;
use metal2vulkan::cache::SpecializationKey;
use metal2vulkan::device::DriverFact;
use metal2vulkan::pipeline::{
PipelineInterface, PushField, SlotInterface, SlotRef, SpecConstant, SpecKey, Stage,
};
use metal2vulkan::vk::SpecializationMapEntry;
use metal2vulkan::pipeline::{PipelineInterface, SlotInterface, SlotRef, SpecConstant, SpecKey};
use std::collections::BTreeSet;
use std::sync::Arc;
@@ -163,7 +153,7 @@ impl RenderVariant {
.stages
.iter()
.flat_map(|module| &module.specialization.constants);
uniform_residual_form(constants, &self.pipeline.interface, false, specialization)
uniform_residual_form(constants, &self.pipeline.interface, specialization)
}
/// `key` with its specialization's general form ([`general_form`](Self::general_form)), where
@@ -236,130 +226,20 @@ pub(crate) fn residual_form<'a>(
/// stages') whose slot `interface` (the pipeline's) reads through a uniform view at 0, the key a
/// plan takes where the device reads its uniform views at their residuals (the module docs);
/// `None` where every one of them is 0 there already. A storage view's constant, which only a
/// profile taking `DriverWorkaround::PushReadsLengthenThreadPayload` declares, keeps its value:
/// at its bind offset alone it reads no residual word there. A uniform view's with a storage twin
/// (`DescriptorView::UniformWithStorageTwin`), declared there alone too, keeps its value where no
/// other `RangeAtBindOffset` constant of the key is 0 and its stage reads no other word the binder
/// writes for it ([`reads_other_words`], of the interface's push placements; `flat_grid`: the
/// pipeline is a kernel's flat-grid variant): at 1 it reads the twin, not the uniform view, which
/// pays only where it leaves no such word to read ([`uniform_residual_form_of`]). Where neither
/// declares the key this is [`residual_form`].
/// profile taking `DriverWorkaround::PushReadsLengthenThreadPayload` declares, keeps its value: its
/// bind at offset 0 reads no residual word there. Where no storage view declares the key this is
/// [`residual_form`].
pub(crate) fn uniform_residual_form<'a>(
constants: impl Iterator<Item = &'a SpecConstant> + Clone,
interface: &PipelineInterface,
flat_grid: bool,
specialization: &SpecializationKey,
) -> Option<SpecializationKey> {
let form = |slot| match interface.slots.get(&slot) {
Some(SlotInterface::Buffer(b)) => Some(b.form),
_ => None,
let uniform = |slot| {
matches!(interface.slots.get(&slot),
Some(SlotInterface::Buffer(b)) if b.form.uniform_view())
};
let uniform = |slot| form(slot).is_some_and(|f| f.uniform_view() && !f.storage_twin());
let twin = |slot| form(slot).is_some_and(|f| f.storage_twin());
let constants = constants.map(|constant| (constant.id, constant.key));
let placed = || {
(interface.push.iter())
.flat_map(|placement| (placement.fields.iter()).map(|f| (placement.stage, f.field)))
};
let other_words = |stage, key: &SpecializationKey| {
reads_other_words(placed(), constants.clone(), (stage, flat_grid), key)
};
uniform_residual_form_of(
constants.clone(),
uniform,
twin,
other_words,
specialization,
)
}
/// `specialization` with each `SpecKey::RangeAtBindOffset` constant of `constants` (a pipeline's
/// stages', each its ID and its meaning) whose slot `uniform` holds at 0, and each whose slot
/// `twin` holds (a uniform view with a storage twin) at 0 too where a `RangeAtBindOffset`
/// constant of that key is 0 (a view that reads its pushed residual word), or where `other_words`
/// holds of a twin's stage at 1 under that key (the stage reads another word the binder writes
/// for it, [`reads_other_words`]); `None` where every one of them is 0 there already. A constant
/// `specialization` gives no entry takes the module's default, 0.
///
/// A twin's key at 1 reads the twin, a storage view, at its bind offset, and pays where it leaves
/// no residual word to read: on ANV, Mesa 26.2.6 on the Iris Xe of RPL-P
/// (`DriverWorkaround::PushReadsLengthenThreadPayload`), `dispatch_chain`'s kernel of three
/// storage views and the word of 1 (4480 threadgroups of 256, 200 dispatches a command buffer,
/// medians of 7 interleaved rounds, job m3-max-34864) ran in 102.1 us a dispatch with its storage
/// views at offset 0 and the word inline (`--binds 4`) through the twin, against 142.8 us through
/// the uniform view at its residual; with two storage views and the word at offsets that move
/// every dispatch (`--binds moved`), which keeps the storage views' residual words, it ran in
/// 154.0 us through the twin against 143.1 us through the uniform view. The payload is the
/// stage's push reads' (job m3-max-34063: the runtime's module of a storage view ran in 120.24 us
/// a dispatch, and 55.69 us with its one push read replaced by a constant), so any other word the
/// stage reads keeps it long as a residual word does.
pub(crate) fn uniform_residual_form_of(
constants: impl Iterator<Item = (u32, SpecKey)> + Clone,
uniform: impl Fn(SlotRef) -> bool,
twin: impl Fn(SlotRef) -> bool,
other_words: impl Fn(Stage, &SpecializationKey) -> bool,
specialization: &SpecializationKey,
) -> Option<SpecializationKey> {
let plan = residual_form_of(constants.clone(), &uniform, specialization);
let key = plan.as_ref().unwrap_or(specialization);
let reads_residual = constants
.clone()
.any(|(id, key_of)| matches!(key_of, SpecKey::RangeAtBindOffset(_)) && !is_set(key, id));
let reads_other = constants.clone().any(|(id, key_of)| {
matches!(key_of, SpecKey::RangeAtBindOffset(slot)
if twin(slot) && is_set(key, id) && other_words(slot.stage, key))
});
match reads_residual || reads_other {
true => residual_form_of(
constants,
|slot| uniform(slot) || twin(slot),
specialization,
),
false => plan,
}
}
/// Whether `stage`, of a pipeline whose placed push fields are `fields` (each with its stage, the
/// interface's `PushPlacement`s) and whose stages' constants are `constants`, reads under
/// `specialization` a word the binder writes for it other than a residual the key's
/// `RangeAtBindOffset` constants leave unread (`flat_grid`: the pipeline is a kernel's flat-grid
/// variant). Each field placed for the stage, in its push window or its `ArgumentTable` (a
/// uniform buffer read at constant offsets, which ANV pushes too, the module docs), is read but:
/// a slot's `SlotBindOffset` residual where the key sets the slot's `RangeAtBindOffset`; and the
/// `DispatchRegion` words where the key leaves the stage's
/// `MultiRegion` 0 (a single-region threadgroup dispatch, `lower::dispatch`'s regions), but on a
/// flat-grid variant, whose one region reads them whatever that constant says
/// (`bind::dispatch`'s ragged grids). A root table's or the execution status's address, a replay's
/// region record, a slot's guest base, a texture's levels and every other field are read wherever
/// placed.
pub(crate) fn reads_other_words(
mut fields: impl Iterator<Item = (Stage, PushField)>,
constants: impl Iterator<Item = (u32, SpecKey)> + Clone,
(stage, flat_grid): (Stage, bool),
specialization: &SpecializationKey,
) -> bool {
let set = |wanted: SpecKey| {
(constants.clone()).any(|(id, key)| key == wanted && is_set(specialization, id))
};
let multi_region = match stage {
Stage::Object => SpecKey::ObjectMultiRegion,
_ => SpecKey::MultiRegion,
};
fields.any(|(of, field)| {
of == stage
&& match field {
PushField::SlotBindOffset(slot) => !set(SpecKey::RangeAtBindOffset(slot)),
PushField::DispatchRegion => flat_grid || set(multi_region),
_ => true,
}
})
}
/// Whether constant `id` of `specialization` is not 0; one it gives no entry takes the module's
/// default, 0.
fn is_set(specialization: &SpecializationKey, id: u32) -> bool {
(specialization.entries.iter())
.any(|entry| entry.constant_id == id && entry_set(specialization, entry))
residual_form_of(constants, uniform, specialization)
}
/// `specialization` with each `SpecKey::RangeAtBindOffset` constant of `constants` (a pipeline's
@@ -411,7 +291,11 @@ fn zeroed(
for entry in &specialization.entries {
let at = entry.offset as usize;
let range = at..at + entry.size as usize;
if entry_set(specialization, entry) && chosen(entry.constant_id) {
let set = specialization
.data
.get(range.clone())
.is_some_and(|bytes| bytes.iter().any(|&byte| byte != 0));
if set && chosen(entry.constant_id) {
let zeroed = zeroed.get_or_insert_with(|| specialization.clone());
zeroed.data[range].fill(0);
}
@@ -419,13 +303,6 @@ fn zeroed(
zeroed
}
/// Whether `entry` of `specialization` holds a value other than 0.
fn entry_set(specialization: &SpecializationKey, entry: &SpecializationMapEntry) -> bool {
let at = entry.offset as usize;
(specialization.data.get(at..at + entry.size as usize))
.is_some_and(|bytes| bytes.iter().any(|&byte| byte != 0))
}
/// Whether `device` reads a uniform view at its bind offset alone where the view's range starts
/// there (`SpecKey::RangeAtBindOffset` 1), a `VkPipeline` of its own beside the residual form's
/// (the module docs); where not, every key's uniform views take their residual form
@@ -4,11 +4,9 @@
//! plan takes where the device reads its uniform views at their residuals: those views' constants
//! alone at 0.
use crate::pipeline::{
general_form, reads_other_words, residual_form_of, uniform_residual_form_of,
};
use crate::pipeline::{general_form, residual_form_of};
use metal2vulkan::cache::SpecializationKey;
use metal2vulkan::pipeline::{PushField, SlotClass, SlotRef, SpecKey, Stage};
use metal2vulkan::pipeline::{SlotClass, SlotRef, SpecKey, Stage};
use metal2vulkan::vk::SpecializationMapEntry;
/// Fragment slot `index` of `class`.
@@ -117,173 +115,3 @@ fn a_plans_key_zeroes_its_uniform_views_and_keeps_its_storage_views() {
let kept = key([0, 1, 1, 1, 3]);
assert_eq!(residual_form_of(constants(), uniform_views, &kept), None);
}
/// A kernel slot's uniform view with a storage twin (`DescriptorView::UniformWithStorageTwin`)
/// keeps its plan's `RangeAtBindOffset` where every other one of the key holds, its twin read at
/// its bind offset then leaving no residual word to read; where one is 0, as a storage view bound
/// past offset 0 is, the twin's takes 0 too, and the kernel reads the uniform view at its residual
/// (`uniform_residual_form_of`). A uniform view of no twin takes 0 in either, and a constant of no
/// slot keeps its value.
#[test]
fn a_twin_keeps_its_key_only_where_no_other_view_reads_its_residual() {
let kernel = |index| SlotRef {
stage: Stage::Kernel,
class: SlotClass::Buffer,
index,
};
let (storage, moved, twin, other_twin) = (kernel(0), kernel(1), kernel(2), kernel(3));
let constants = || {
vec![
(0, SpecKey::RangeAtBindOffset(storage)),
(1, SpecKey::RangeAtBindOffset(moved)),
(2, SpecKey::RangeAtBindOffset(twin)),
(3, SpecKey::RangeAtBindOffset(other_twin)),
(4, SpecKey::BicubicTexels(slot(SlotClass::Texture, 0))),
]
.into_iter()
};
let no_uniform = |_: SlotRef| false;
let twins = |at: SlotRef| at == twin || at == other_twin;
let nothing_else = |_: Stage, _: &SpecializationKey| false;
// Every storage view at offset 0 and the constants inline or aligned: the plan's own key.
let at_bind = key([1, 1, 1, 1, 3]);
assert_eq!(
uniform_residual_form_of(constants(), no_uniform, twins, nothing_else, &at_bind),
None
);
// A storage view bound past offset 0 reads its residual: both twins read their uniform views.
let moved_off = key([1, 0, 1, 1, 3]);
assert_eq!(
uniform_residual_form_of(constants(), no_uniform, twins, nothing_else, &moved_off),
Some(key([1, 0, 0, 0, 3]))
);
// A twin bound at an offset no alignment divides reads its uniform view's residual, and so
// does the other.
let unaligned = key([1, 1, 0, 1, 3]);
assert_eq!(
uniform_residual_form_of(constants(), no_uniform, twins, nothing_else, &unaligned),
Some(key([1, 1, 0, 0, 3]))
);
// A uniform view of no twin takes its residual form, which reads its residual word.
let uniform = |at: SlotRef| at == moved;
assert_eq!(
uniform_residual_form_of(constants(), uniform, twins, nothing_else, &at_bind),
Some(key([1, 0, 0, 0, 3]))
);
// Off the profile that declares twins this is the uniform views' residual form alone.
let none = |_: SlotRef| false;
assert_eq!(
uniform_residual_form_of(constants(), uniform, none, nothing_else, &at_bind),
residual_form_of(constants(), uniform, &at_bind)
);
}
/// Kernel buffer slot `index`.
fn kernel(index: u32) -> SlotRef {
SlotRef {
stage: Stage::Kernel,
class: SlotClass::Buffer,
index,
}
}
/// A key giving IDs from 0 `values`, each four bytes, packed in order.
fn key_of(values: &[u32]) -> SpecializationKey {
let mut key = SpecializationKey::new();
for (id, &value) in (0..).zip(values) {
key.entries.push(SpecializationMapEntry {
constant_id: id,
offset: key.data.len() as u32,
size: 4,
});
key.data.extend_from_slice(&value.to_le_bytes());
}
key
}
/// A twin's key at 1 pays only where the kernel reads no word the binder writes for it beside the
/// views it reads at their bind offsets: where it reads one, which keeps the thread payload long
/// as a residual word does, the twin's key takes 0, and the kernel reads its uniform view at its
/// residual (`uniform_residual_form_of`'s `other_words`). The kernel here has a storage view and a
/// twin, both held; where it reads no other word the plan's own key stands.
#[test]
fn a_twin_takes_0_where_its_stage_reads_another_word() {
let (storage, twin) = (kernel(0), kernel(1));
let constants = || {
vec![
(0, SpecKey::RangeAtBindOffset(storage)),
(1, SpecKey::RangeAtBindOffset(twin)),
]
.into_iter()
};
let no_uniform = |_: SlotRef| false;
let twins = |at: SlotRef| at == twin;
let at_bind = key_of(&[1, 1]);
let kernel_reads = |stage: Stage, _: &SpecializationKey| stage == Stage::Kernel;
assert_eq!(
uniform_residual_form_of(constants(), no_uniform, twins, kernel_reads, &at_bind),
Some(key_of(&[1, 0])),
"a kernel that reads another word reads its twin's uniform view at its residual"
);
let none = |_: Stage, _: &SpecializationKey| false;
assert_eq!(
uniform_residual_form_of(constants(), no_uniform, twins, none, &at_bind),
None,
"a kernel that reads no other word keeps its twin's key"
);
// Another stage's word is not the kernel's.
let fragment_reads = |stage: Stage, _: &SpecializationKey| stage == Stage::Fragment;
assert_eq!(
uniform_residual_form_of(constants(), no_uniform, twins, fragment_reads, &at_bind),
None
);
}
/// The words a stage reads under a key beside its views' residuals (`reads_other_words`): a
/// `SlotBindOffset` residual only where the key leaves its slot's `RangeAtBindOffset` 0, or the
/// slot declares none; the `DispatchRegion` words only where the key sets the stage's
/// `MultiRegion`, or on a flat-grid variant whatever it says; every other field wherever it is
/// placed (a root table's address here). Fields of another stage are not the stage's.
#[test]
fn a_stage_reads_its_region_under_multi_region_and_every_other_word_it_places() {
let (storage, twin, undeclared) = (kernel(0), kernel(1), kernel(2));
let constants = || {
vec![
(0, SpecKey::RangeAtBindOffset(storage)),
(1, SpecKey::RangeAtBindOffset(twin)),
(2, SpecKey::MultiRegion),
]
.into_iter()
};
// The kernel's region words and its two views' residuals, and `extra`.
let fields = |extra: &[(Stage, PushField)]| {
let mut fields = vec![
(Stage::Kernel, PushField::DispatchRegion),
(Stage::Kernel, PushField::SlotBindOffset(storage)),
(Stage::Kernel, PushField::SlotBindOffset(twin)),
];
fields.extend_from_slice(extra);
fields
};
let reads = |fields: Vec<(Stage, PushField)>, flat_grid, values: [u32; 3]| {
let at = (Stage::Kernel, flat_grid);
reads_other_words(fields.into_iter(), constants(), at, &key_of(&values))
};
// A single-region dispatch with both views held reads none.
assert!(!reads(fields(&[]), false, [1, 1, 0]));
// A multi-region one reads its region.
assert!(reads(fields(&[]), false, [1, 1, 1]));
// A flat grid reads its region whatever `MultiRegion` says.
assert!(reads(fields(&[]), true, [1, 1, 0]));
// A storage view off its bind offset reads its residual.
assert!(reads(fields(&[]), false, [0, 1, 0]));
// A residual of a slot that declares no `RangeAtBindOffset` is read whatever the key says.
let unkeyed = [(Stage::Kernel, PushField::SlotBindOffset(undeclared))];
assert!(reads(fields(&unkeyed), false, [1, 1, 0]));
// A root table's address is read wherever it is placed.
let root = [(Stage::Kernel, PushField::RootTableAddress)];
assert!(reads(fields(&root), false, [1, 1, 0]));
// Another stage's fields are not the kernel's.
let fragment = [(Stage::Fragment, PushField::RootTableAddress)];
assert!(!reads(fields(&fragment), false, [1, 1, 0]));
}
@@ -19,13 +19,10 @@
//! # Why only a read-only binding
//!
//! One buffer shared by every command of the device is sound only where no shader can store
//! through the binding. A Vulkan uniform-buffer descriptor is read-only by construction, and so is
//! a uniform view's storage twin, a storage buffer its kernel only loads from (a kernel's
//! `constant` slot on a profile that takes `DriverWorkaround::PushReadsLengthenThreadPayload`,
//! where the unbound slot below binds both): those are the bindings served from it
//! (`BindingPlan::read_only_buffer`, decided from the plan's layout alone, never a function or
//! shader name). A writable binding keeps a region of its own, exactly as every binding did, so
//! nothing a shader stores is ever read by another command.
//! through the binding. A Vulkan uniform-buffer descriptor is read-only by construction, so that
//! is the binding served from it (`binding::read_only_buffer`, decided from the descriptor type
//! alone). A writable binding keeps a region of its own, exactly as every binding did, so nothing
//! a shader stores is ever read by another command.
//!
//! # Counts, not times
//!
@@ -17,8 +17,6 @@
//! bound to nothing as one bound at offset 0, and makes that key and its residual form both
//! ([`storage_views_keyed`]): `ubo_offsets_kernel`'s output, bound at offset 0, takes the
//! creation's key, and a draw binding a storage view elsewhere takes the residual form at once.
//! There a kernel's constants also have a storage twin, read where their key holds, which a
//! dispatch at an aligned offset or of inline bytes takes, the creation's key.
//!
//! A device test: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`,
//! `m2v_cpu_icd`), on the kind of device the cfg selects. The functions are those of the owned
@@ -962,96 +960,6 @@ fn kernel_constants_read_at_every_bind_offset() {
}
}
/// A kernel's constants bound at offsets the view base alignment divides (0 and 128, a multiple
/// of every device's) and as inline bytes take the key its creation predicted and made, and make
/// nothing; on a profile that takes `DriverWorkaround::PushReadsLengthenThreadPayload` that key
/// reads them through their storage twin (`DescriptorView::UniformWithStorageTwin`) at their bind
/// offset. Bound then at offset 4, which no alignment divides, they are read through the uniform
/// view at their residual: there a key of its own (the output still read at its bind offset 0),
/// taken through the creation's residual form at once while it is made on the pool, one
/// pipeline; elsewhere the creation's. With the device's pool held, each dispatch reads its bytes.
#[test]
fn kernel_constants_at_aligned_offsets_take_the_creations_key() {
let scratch = Scratch::new("uniform-twin-kernel");
let device = device(&scratch.0);
let queue = device.new_command_queue().unwrap();
let function = library(&device)
.new_function_with_name("ubo_offsets_kernel")
.unwrap();
let keyed = u64::from(storage_views_keyed(&device));
let state = kernel_state(&device, &function);
let created = idle(&device);
let [width, height, depth] = PREDICTED_THREADS;
let threads = Size::new(u64::from(width), u64::from(height), u64::from(depth));
let data = constants();
let constants = device
.new_buffer_with_bytes(&data, ResourceOptions::shared())
.unwrap();
// `None`: inline bytes from offset 8.
let offsets = [Some(0), Some(128), None, Some(4)];
let outputs: Vec<Buffer> = offsets
.iter()
.map(|_| device.new_buffer(16, ResourceOptions::shared()).unwrap())
.collect();
let took = |from: &crate::WorkCounts, to: &crate::WorkCounts| {
(
to.residual_form_draws - from.residual_form_draws,
to.dispatch_pipelines_pooled - from.dispatch_pipelines_pooled,
to.variant_pipelines_made - from.variant_pipelines_made,
)
};
let hold = crate::pipeline::pool::held::hold();
let command_buffer = queue.command_buffer().unwrap();
let mut encoder = command_buffer.compute_command_encoder().unwrap();
encoder.set_compute_pipeline_state(&state).unwrap();
let mut counts = vec![device.work_counts()];
for (offset, output) in offsets.iter().zip(&outputs) {
match offset {
Some(at) => encoder.set_buffer(Some(&constants), *at, 0).unwrap(),
None => encoder.set_bytes(&data[8..24], 0).unwrap(),
}
encoder.set_buffer(Some(output), 0, 1).unwrap();
encoder
.dispatch_threadgroups(Size::new(1, 1, 1), threads)
.unwrap();
counts.push(device.work_counts());
}
encoder.end_encoding().unwrap();
command_buffer.commit().unwrap();
command_buffer
.wait_until_completed_for(WAIT)
.expect("the dispatches' command buffer waits for no making");
assert_eq!(command_buffer.error(), None);
drop(hold);
assert_eq!(
took(&counts[0], &counts[3]),
(0, 0, 0),
"dispatches at 0 and 128 and of inline bytes: residual-form dispatches, regions pooled, \
pipelines made"
);
assert_eq!(
took(&counts[3], &counts[4]),
(keyed, keyed, 0),
"a dispatch at 4: residual-form dispatches, regions pooled, pipelines made"
);
assert_eq!(
idle(&device).variant_pipelines_made - created.variant_pipelines_made,
keyed,
"pipelines made once the pool ran"
);
for (offset, output) in offsets.iter().zip(&outputs) {
let at = offset.unwrap_or(8) as usize / 4;
let words = bytes_of(output);
let read = |w: usize| f32::from_le_bytes(words[w * 4..w * 4 + 4].try_into().unwrap());
let want = |i: usize| i as f32 / 255.0;
assert_eq!(
[read(0), read(1)],
[want(at), want(at + 2)],
"offset {offset:?}"
);
}
}
/// A kernel reads a `device` buffer through a storage view at bind offset 0, then at offsets past
/// it and at 0 again (`engine/buffer_end_byte_load.ll`: `out[0] = in[5]`), and each dispatch reads
/// the bound bytes, whichever form its key takes. On a device whose profile takes
@@ -556,10 +556,7 @@ pub fn containment(
(ContainmentForm::BufferAtomic, atomic_check)
}
DescriptorView::Storage => (ContainmentForm::StorageBuffer, robust),
// A storage twin reads the same range under the same robustness.
DescriptorView::UniformWords
| DescriptorView::UniformVec4
| DescriptorView::UniformWithStorageTwin => {
DescriptorView::UniformWords | DescriptorView::UniformVec4 => {
(ContainmentForm::UniformBuffer, robust)
}
_ => return unknown(),
@@ -653,8 +650,7 @@ pub fn containment(
BufferForm::Descriptor(
DescriptorView::Storage
| DescriptorView::UniformWords
| DescriptorView::UniformVec4
| DescriptorView::UniformWithStorageTwin,
| DescriptorView::UniformVec4,
) => made(target.form, Medium::DescriptorView, robust, false),
_ => unknown(),
},
@@ -84,7 +84,6 @@ fn template() -> ComputeTemplate {
length_class: crate::bind::state::length_class(4096),
},
disjoint: false,
twin: None,
}],
spec: vec![
spec(0, SpecKey::LocalSize(Axis::X)),
+6 -8
View File
@@ -331,7 +331,7 @@ use crate::bind::neutral::{zero_buffer_bytes, NeutralResource};
use crate::bind::plan::compute::{internal, not_implemented, spec_key, tile_memory};
use crate::bind::plan::resources::{separate_samplers, ResourcePlanner};
use crate::bind::plan::slots::{
address_map_variant, anisotropic_variant, bindings, bound_value, buffer_uses, check_slots,
address_map_variant, anisotropic_variant, bindings, bound_value, buffer_use, check_slots,
check_sparse_textures, cross_variant, cubic_variant, heap_raw, heap_ycbcr_writes,
large_view_candidates, mark_disjoint, plan_buffer, psb_variant, range_variant, record_noted,
record_specialized, snapshot_forms, srgb_variant, storage_view_variant,
@@ -2018,8 +2018,7 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<Bindin
)));
}
let source = match b.source {
// A uniform view's storage twin binds the slot's own buffer, at its own range.
BindingSource::Buffer(slot) | BindingSource::StorageTwin(slot) => {
BindingSource::Buffer(slot) => {
let pb = planned(slot).ok_or_else(|| {
internal(format!("binding of {slot:?} without an interface slot"))
})?;
@@ -2503,7 +2502,7 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<Bindin
let mut uses: Vec<ResourceUse> = buffers
.iter()
.filter(|b| matches!(b.bound, BoundKind::Buffer { .. }))
.flat_map(|b| buffer_uses(b, stage_flags(b.slot.stage)))
.map(|b| buffer_use(b, stage_flags(b.slot.stage)))
.collect();
// The factors: the control stage's, or an emulated pipeline's scan's.
if factor_binding.is_some()
@@ -5144,8 +5143,8 @@ fn rebinds_into(t: &GraphicsTemplate, slots: &[SlotRef], into: &mut SlotRebinds)
into.vertex.clear();
let changed = |slot: SlotRef| slot.class == SlotClass::Buffer && slots.contains(&slot);
// What the slots decide some other way than below: a stage's argument or root table, a mesh
// or patch draw's own reads, a de-indexed draw's layout, a uniform view a written slot may
// alias, and a uniform view's storage twin, a second range of its slot.
// or patch draw's own reads, a de-indexed draw's layout, and a uniform view a written slot
// may alias.
let other_reads = t
.stages
.iter()
@@ -5153,8 +5152,7 @@ fn rebinds_into(t: &GraphicsTemplate, slots: &[SlotRef], into: &mut SlotRebinds)
|| t.mesh.is_some()
|| t.tessellation.is_some()
|| t.deindexed.is_some()
|| (t.buffers.iter().any(|b| b.disjoint) && t.buffers.iter().any(|b| b.access.write))
|| t.buffers.iter().any(|b| b.twin.is_some());
|| (t.buffers.iter().any(|b| b.disjoint) && t.buffers.iter().any(|b| b.access.write));
// A texture slot's texels a texture buffer's range bounds, which the commands hold.
let texel_range = |slot: &SlotRef| t.resources.texel_buffers.iter().any(|pt| pt.slot == *slot);
let texels = slots
@@ -821,7 +821,6 @@ fn draws_bind_vertex_buffers_at_aligned_offsets_with_their_windows() {
length_class: length_class(4096),
},
disjoint: false,
twin: None,
}],
stages: Vec::new(),
vertex_buffers: vertex_buffers(),
+2 -14
View File
@@ -615,9 +615,7 @@ pub(crate) fn shared_range(
/// 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; not a uniform view with a storage twin
/// (`DescriptorView::UniformWithStorageTwin`), whose key reads the twin at its bind offset alone
/// whatever `views_at_residual` says;
/// [`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.
@@ -635,8 +633,7 @@ pub(crate) fn planned_range(
&& end <= pb.max_range
&& end <= 1 << 32;
if !from_start {
let at_residual = views_at_residual && !pb.form.storage_twin();
let shared = (storage || (at_residual && pb.form.uniform_view()))
let shared = (storage || (views_at_residual && pb.form.uniform_view()))
.then(|| shared_range(bind_offset, length, pb.window, pb.alignment, pb.max_range))
.flatten();
return match shared {
@@ -816,15 +813,6 @@ pub(crate) fn bind_buffers(
element: 0,
range,
});
// A uniform view's storage twin binds the same range.
if let Some((set, binding)) = pb.twin {
descriptor_ranges.push(DescriptorRange {
set,
binding,
element: 0,
range,
});
}
out.residuals.push(pb.slot, residual);
}
(BufferForm::Psb, _) => {
@@ -208,7 +208,6 @@ fn planned(window: Window, view: DescriptorView, alignment: u64, max_range: u64)
length_class: crate::bind::state::length_class(1 << 12),
},
disjoint: false,
twin: None,
}
}
@@ -485,59 +484,6 @@ fn bounded_slots_read_at_their_residual_share_one_range_along_a_buffer() {
}
}
/// A uniform view with a storage twin binds its range from its bind offset, its residual 0, also
/// where the consumer reads every uniform view at its residual: its key reads the twin at its
/// bind offset alone. A plain uniform view there shares one range from the buffer's start, the
/// negative control. `bind_buffers` writes the twin's binding with the uniform binding's range.
#[test]
fn a_uniform_view_with_a_storage_twin_binds_its_range_from_its_bind_offset() {
use crate::bind::state::{BindState, BoundBuffer, StageTable};
const CHUNK: u64 = 64 * 1024;
let bounded = Window::Bounded { start: 0, len: 16 };
let mut twin = planned(bounded, DescriptorView::UniformWithStorageTwin, 64, CHUNK);
let plain = planned(bounded, DescriptorView::UniformWords, 64, CHUNK);
for bind_offset in (0..CHUNK).step_by(256) {
for at_residual in [false, true] {
let (range, residual) = planned_range(&twin, bind_offset, CHUNK, at_residual).unwrap();
assert_eq!(
(range.offset, residual),
(bind_offset, 0),
"{bind_offset} {at_residual}"
);
}
let (range, residual) = planned_range(&plain, bind_offset, CHUNK, true).unwrap();
assert_eq!(
(range.offset, u64::from(residual)),
(0, bind_offset),
"{bind_offset}"
);
}
twin.twin = Some((0, 3));
let mut table = StageTable::default();
table.buffers.insert(
twin.slot.index,
BoundBuffer::Buffer {
gpu_address: 0x1_0000,
// `planned`'s length class.
length: 1 << 12,
offset: 256,
device_address: None,
attribute_stride: None,
},
);
let mut state = BindState::default();
state.stages.insert(twin.slot.stage, table);
state.uniform_views_at_residual = true;
let slot = twin.slot;
let (mut ranges, mut extents) = (Vec::new(), Vec::new());
let bound = bind_buffers(&[twin], &state, &mut ranges, &mut extents).unwrap();
let keys: Vec<_> = ranges.iter().map(|r| (r.set, r.binding)).collect();
assert_eq!(keys, [(0, 0), (0, 3)]);
assert_eq!(ranges[0].range, ranges[1].range);
assert_eq!(ranges[0].range.offset, 256);
assert_eq!(bound.residuals.of(slot), Some(0));
}
fn entry(host: u64, guest: u64, size: u64) -> RootEntry {
RootEntry {
host,
-24
View File
@@ -78,26 +78,6 @@ impl BindingPlan {
.find(|(k, _)| *k == key)
.map(|(_, v)| u64::from(*v))
}
/// Whether no function of the plan's pipeline can store through the buffer binding `write`
/// (one of [`descriptors`](Self::descriptors)) writes: a uniform buffer, whose block Vulkan
/// makes read-only, or a uniform view's storage twin (`DescriptorView::UniformWithStorageTwin`),
/// a storage buffer the function only loads from. A consumer may bind there one buffer that
/// every command shares, such as the zeros of a `NeutralResource::ZeroBuffer` it keeps for the
/// device's lifetime; through any other storage buffer a function may store, so such a binding
/// takes a buffer of its command's own.
pub fn read_only_buffer(&self, write: &DescriptorWrite) -> bool {
let at = (write.set, write.binding);
let twin = |buffers: &[PlannedBuffer]| buffers.iter().any(|b| b.twin == Some(at));
match write.ty {
vk::DescriptorType::UNIFORM_BUFFER | vk::DescriptorType::UNIFORM_BUFFER_DYNAMIC => true,
vk::DescriptorType::STORAGE_BUFFER => {
(self.compute.as_ref()).is_some_and(|c| twin(&c.buffers))
|| (self.graphics.as_ref()).is_some_and(|g| twin(&g.buffers))
}
_ => false,
}
}
}
// Adding a field to a plan type: a plan's content digest omits a field whose value is zero (`0`,
@@ -581,10 +561,6 @@ pub(crate) struct PlannedBuffer {
/// its window (`RuntimeFact::UniformViewAliasing`).
#[cfg_attr(feature = "serde", serde(default))]
pub disjoint: bool,
/// `(set, binding)` of the slot's storage twin (`DescriptorView::UniformWithStorageTwin`),
/// written with the slot's own buffer and range.
#[cfg_attr(feature = "serde", serde(default))]
pub twin: Option<(u32, u32)>,
}
/// What a shape binds at a buffer slot.
+3 -4
View File
@@ -61,7 +61,7 @@
use super::resources::{separate_samplers, ResourcePlanner};
use super::slots::{
address_map_variant, anisotropic_variant, bindings, bound_value, buffer_uses, check_slots,
address_map_variant, anisotropic_variant, bindings, bound_value, buffer_use, check_slots,
check_sparse_textures, cross_variant, cubic_variant, heap_raw, heap_ycbcr_writes,
mark_disjoint, open_cl_line_variant, plan_buffer, psb_variant, record_noted,
record_specialized, srgb_variant, storage_view_variant, texel_buffer_parts_variant, used_uses,
@@ -574,8 +574,7 @@ fn plan(p: &ComputePipeline, device: &Device, shape: &BindShape) -> Result<Bindi
)));
}
let source = match b.source {
// A uniform view's storage twin binds the slot's own buffer, at its own range.
BindingSource::Buffer(slot) | BindingSource::StorageTwin(slot) => {
BindingSource::Buffer(slot) => {
let pb = planned(slot).ok_or_else(|| {
internal(format!("binding of {slot:?} without an interface slot"))
})?;
@@ -829,7 +828,7 @@ fn plan(p: &ComputePipeline, device: &Device, shape: &BindShape) -> Result<Bindi
let mut uses: Vec<ResourceUse> = buffers
.iter()
.filter(|b| matches!(b.bound, BoundKind::Buffer { .. }))
.flat_map(|b| buffer_uses(b, compute_stage))
.map(|b| buffer_use(b, compute_stage))
.collect();
uses.extend(used_uses(
&shape.used,
+23 -44
View File
@@ -155,15 +155,6 @@ pub(crate) fn plan_buffer(
None
}
};
let twin = match b.form.storage_twin() {
true => Some(
bindings
.get(&BindingSource::StorageTwin(slot))
.copied()
.ok_or_else(|| internal(format!("slot {slot:?} has no storage twin binding")))?,
),
false => None,
};
Ok(PlannedBuffer {
slot,
window: b.window,
@@ -174,7 +165,6 @@ pub(crate) fn plan_buffer(
max_range,
bound,
disjoint: false,
twin,
})
}
@@ -192,9 +182,8 @@ pub(crate) fn plan_buffer(
/// nothing has the residual 0 (`instantiate::slot_field`), so either form reads the Metal offset
/// alone of the same descriptor: a uniform view's 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; a storage view's, and a uniform view's with a storage twin
/// (`DescriptorView::UniformWithStorageTwin`), whose key reads the twin, take what a bind at
/// offset 0 takes, the commonest bind, so that a plan of nothing bound, which a consumer makes before any draw binds
/// such slot at its residual; a storage view's takes what a bind at offset 0 takes, the
/// commonest bind, so that a plan of nothing bound, which a consumer makes before any draw binds
/// the slot (the runtime's creation, `pipeline/predicted.rs` and `pipeline/dispatch_making.rs`,
/// and a warm pass's replay of a dispatch, `pipeline/dispatch_record.rs`), names the key of the
/// draw that binds it there.
@@ -218,7 +207,7 @@ pub(crate) fn range_at_bind_offset(
offset_alignment, ..
}) => u64::from(offset_alignment),
Some(BufferShape::Bytes { .. }) => 0,
None if !b.form.uniform_view() || b.form.storage_twin() => 0,
None if !b.form.uniform_view() => 0,
None => return false,
};
let alignment = crate::memory::views::base_alignment(min);
@@ -1042,37 +1031,27 @@ 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` entries of a bound buffer slot: its proven access, `Uniform` for a uniform view and
/// 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; a uniform view's storage twin (`DescriptorView::UniformWithStorageTwin`) reads the
/// same bytes as a storage buffer, a `Storage` use of them beside the `Uniform` one.
pub(crate) fn buffer_uses(
b: &PlannedBuffer,
stages: vk::PipelineStageFlags2,
) -> impl Iterator<Item = ResourceUse> {
let class = if b.form.uniform_view() {
AccessClass::Uniform
} else {
AccessClass::Storage
};
let twin = b.form.storage_twin().then_some(AccessClass::Storage);
let (slot, access) = (b.slot, b.access);
let range = match b.window {
Window::Bounded { start, len } if start >= 0 => Some(ByteRange {
offset: start as u64,
len,
}),
_ => None,
};
std::iter::once(class)
.chain(twin)
.map(move |class| ResourceUse {
resource: UseTarget::Slot(slot),
access,
class,
stages,
range,
})
/// offset.
pub(crate) fn buffer_use(b: &PlannedBuffer, stages: vk::PipelineStageFlags2) -> ResourceUse {
ResourceUse {
resource: UseTarget::Slot(b.slot),
access: b.access,
class: if b.form.uniform_view() {
AccessClass::Uniform
} else {
AccessClass::Storage
},
stages,
range: match b.window {
Window::Bounded { start, len } if start >= 0 => Some(ByteRange {
offset: start as u64,
len,
}),
_ => None,
},
}
}
/// The `uses` of the used resources a pipeline can reach (the handback): buffers and heaps when a
@@ -66,7 +66,6 @@ fn planned(index: u32, bound: BoundKind, form: BufferForm) -> PlannedBuffer {
max_range: 0,
bound,
disjoint: false,
twin: None,
}
}
@@ -709,97 +708,6 @@ fn a_storage_range_starts_at_the_bind_offset_only_at_offset_0() {
}
}
/// A uniform view with a storage twin (`DescriptorView::UniformWithStorageTwin`) takes a uniform
/// view's `RangeAtBindOffset` wherever its slot is bound (a buffer at each offset class, inline
/// bytes), on every committed profile and under each window, and bound to nothing what a bind at
/// offset 0 takes, where a plain uniform view takes false. Its plan names the twin's binding, and
/// a plan of the layout without one is refused.
#[test]
fn a_storage_twin_takes_a_uniform_views_key_and_offset_0_s_unbound() {
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::Bounded { start: 0, len: 64 },
Window::Bounded { start: 4, len: 28 },
Window::Bounded { start: -8, len: 40 },
] {
let slot_of = |view| BufferSlot {
access: AccessSet::READ,
window,
form: BufferForm::Descriptor(view),
kind: BufferKind::Buffer,
};
let (twin, plain) = (
slot_of(DescriptorView::UniformWithStorageTwin),
slot_of(DescriptorView::UniformWords),
);
let what = format!("{stem} {window:?}");
for bind_offset in [0, 4, 16, 20, 64, 260, 1024] {
let shape = BoundBuffer::Buffer {
gpu_address: 0x1_0000,
length: 4096,
offset: bind_offset,
device_address: None,
attribute_stride: None,
}
.shape(alignment as u32, BufferRanges::default());
assert_eq!(
range_at_bind_offset(&twin, Some(&shape), limits),
range_at_bind_offset(&plain, Some(&shape), limits),
"{what} {bind_offset}"
);
}
let bytes = BufferShape::Bytes {
attribute_stride: None,
};
assert_eq!(
range_at_bind_offset(&twin, Some(&bytes), limits),
range_at_bind_offset(&plain, Some(&bytes), limits),
"{what} bytes"
);
let at_0 = BoundBuffer::Buffer {
gpu_address: 0x1_0000,
length: 4096,
offset: 0,
device_address: None,
attribute_stride: None,
}
.shape(alignment as u32, BufferRanges::default());
assert_eq!(
range_at_bind_offset(&twin, None, limits),
range_at_bind_offset(&twin, Some(&at_0), limits),
"{what} unbound"
);
assert!(
!range_at_bind_offset(&plain, None, limits),
"{what} unbound"
);
let both = [
(BindingSource::Buffer(slot(0)), (0, 0)),
(BindingSource::StorageTwin(slot(0)), (0, 3)),
]
.into();
let pb = plan_buffer((slot(0), &twin, Some(&at_0)), false, limits, &both)
.unwrap_or_else(|e| panic!("{what}: {e:?}"));
assert_eq!(
(pb.binding, pb.twin),
(Some((0, 0)), Some((0, 3))),
"{what}"
);
let pb = plan_buffer((slot(0), &plain, Some(&at_0)), false, limits, &both)
.unwrap_or_else(|e| panic!("{what}: {e:?}"));
assert_eq!(pb.twin, None, "{what}");
let alone = [(BindingSource::Buffer(slot(0)), (0, 0))].into();
assert!(
plan_buffer((slot(0), &twin, Some(&at_0)), false, limits, &alone).is_err(),
"{what}: no twin binding"
);
}
}
}
/// A slot whose function observes residency (`RuntimeFact::SparseTexture`) binds a texture that is
/// not sparse (or nothing) on every profile, and a sparse one where the module has the sparse arm
/// or the tile-map arm; without either a sparse texture is refused, naming
+1 -3
View File
@@ -873,7 +873,6 @@ codec_enum! {
SnapshotTexels(f0),
YCbCrPlanes(f0),
SamplerArray { compare, integer },
StorageTwin,
}
AccelerationStructureLevel { Primitive, Instance }
SamplerRef { Slot(f0), Constexpr(f0) }
@@ -1202,7 +1201,7 @@ codec_enum! {
Window { Bounded { start, len }, Whole }
BufferForm { Descriptor(f0), Psb }
BufferKind { Buffer, VisibleFunctionTable, IntersectionFunctionTable }
DescriptorView { Storage, UniformWords, UniformVec4, UniformWithStorageTwin }
DescriptorView { Storage, UniformWords, UniformVec4 }
PushLoc { Push { offset }, ArgumentTable { offset } }
IoRole {
Attribute { index }, Varying { user, interpolation },
@@ -1536,7 +1535,6 @@ codec_enum! {
SnapshotTexels(f0),
YCbCrPlanes(f0),
SamplerArray { stage, compare, integer },
StorageTwin(f0),
}
VertexStride { Static(f0), PerBind }
}
+3 -3
View File
@@ -61,7 +61,7 @@ mod tests;
/// unchanged version, and its bless records the version. Independent of the crate's version and of
/// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no
/// history.
pub const SEMANTICS_VERSION: u32 = 2134;
pub const SEMANTICS_VERSION: u32 = 2135;
/// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the
/// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another
@@ -71,7 +71,7 @@ pub const SEMANTICS_VERSION: u32 = 2134;
/// re-typed in an encoded type, its `codec` body or its `envelope`. A variant removed while its tag
/// stays unused needs no bump: an entry holding it fails to decode, which is a miss. The commit that
/// bumps it says what changed; this comment keeps no history.
pub const ARTIFACT_FORMAT_VERSION: u32 = 523;
pub const ARTIFACT_FORMAT_VERSION: u32 = 524;
/// The version of what this crate's runtime does with a compiled pipeline: instantiating a binding
/// plan (`BindingPlan::instantiate_*`: descriptor ranges, push bytes, root, argument, and handle
@@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 523;
/// changes no behaviour, and then updates that hash alone with the commit saying why, or changes
/// behaviour and also bumps this version. The commit that bumps it says what changed; this comment
/// keeps no history.
pub const RUNTIME_VERSION: u32 = 2457;
pub const RUNTIME_VERSION: u32 = 2458;
/// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex,
/// of the manifest, the build script, and exactly the files the crate roots' module tree compiles
@@ -894,9 +894,7 @@ const fn moltenvk_on_apple<F>(fact: F) -> Measured<F> {
/// reads its storage views at their bind offsets, which a command binding them at offset 0, the
/// commonest bind, takes, and its general form, which one binding a storage view elsewhere takes
/// at once; with the general form alone, every state's first command at offset 0 made a second
/// pipeline. There a kernel's uniform view also binds a storage twin of its range, which it
/// reads at its bind offset alone where its key holds (`DescriptorView::UniformWithStorageTwin`;
/// the workaround's own documentation holds the figures).
/// pipeline.
pub(crate) const DEFECTS: &[Measured<DriverWorkaround>] = &[
Measured {
fact: DriverWorkaround::BothBarycentricFormsRejected,
+6 -11
View File
@@ -1589,17 +1589,12 @@ pub enum DriverWorkaround {
/// alone is no faster there: a kernel of three storage views at offset 0 and inline bytes ran
/// in 161.8 us a dispatch with the bytes' uniform view read so and in 142.8 us with it read at
/// its residual, and in 102.1 us with the bytes read through a storage view at their bind
/// offset (job m3-max-34275). So a kernel's uniform view there also has a storage twin
/// (`DescriptorView::UniformWithStorageTwin`, `lower::access`): a storage
/// buffer of the uniform view's own range, decorated `NonWritable` as the uniform buffer is
/// read-only, which the kernel reads instead where the slot's
/// key holds (a bind offset the view base alignment divides, inline bytes, nothing bound), and
/// elsewhere the uniform view at its residual, as on every device without
/// `DriverFact::ConstantOffsetUniformReadsPreloaded`. The runtime keeps a twin's key only
/// where no other view of the key reads its residual and the kernel reads no other word the
/// binder writes for it (a root table's address, a multi-region or flat grid's region): beside
/// a storage view bound past offset 0 the kernel ran in 154.0 us a dispatch through the twin
/// and 143.1 us through the uniform view (job m3-max-34864). It changes no answer.
/// offset (job m3-max-34275). A kernel's uniform view there is read at its residual, as on
/// every device without `DriverFact::ConstantOffsetUniformReadsPreloaded`, and nothing else
/// binds its range: a second binding of that range as a storage buffer, read at its bind
/// offset where the slot's key held, took 145.8 to 150.2 s of GPU time over a walk of guest
/// compute workloads that took 137.4 s without it (three walks against one, Mesa 26.2.6). It
/// changes no answer.
PushReadsLengthenThreadPayload,
}
@@ -1120,9 +1120,8 @@ fn on_target(fb: &mut FunctionBuilder<'_>, p: Prepared, o: Op) -> BResult<Option
let addr = m.word_address(fb, word)?;
device_ptr(fb, addr, pointee)?
}
// Selection moved every slot of a typed atomic to its device address, and gives a slot
// with a storage twin, a uniform view's, none.
(Mem::View(_), Some(_)) | (Mem::Twin(_), _) => return Err(dangling()),
// Selection moved every slot of a typed atomic to its device address.
(Mem::View(_), Some(_)) => return Err(dangling()),
};
let at = At {
p: ptr,
+10 -125
View File
@@ -144,99 +144,10 @@ fn storage_ptr(fb: &mut FunctionBuilder<'_>, view: View, word: SValue) -> BResul
}
}
/// The word memory of a slot read through a uniform view and its storage twin
/// (`DescriptorView::UniformWithStorageTwin`): the binder binds both to one range, so one offset
/// names the same byte in each, and each read loads both and selects the twin's where the slot's
/// `RangeAtBindOffset` (`at_bind`) holds. Specialization fixes the constant, so a driver folds the
/// selection and drops the other load. Read-only: selection gives a uniform view no store or
/// atomic. Its units are the uniform view's, which the twin has too (`views::declare_twin`).
#[derive(Clone, Copy, Debug)]
pub(super) struct TwinMem {
uniform: ViewMem,
twin: ViewMem,
at_bind: SValue,
}
impl TwinMem {
fn stored(&self) -> crate::spirv::error::BuildError {
self.uniform.missing()
}
}
impl WordMem for TwinMem {
fn read(&mut self, fb: &mut FunctionBuilder<'_>, word: SValue) -> BResult<SValue> {
let twin = self.twin.read(fb, word)?;
let uniform = self.uniform.read(fb, word)?;
fb.select(self.at_bind, twin, uniform)
}
fn write(&mut self, _: &mut FunctionBuilder<'_>, _: SValue, _: SValue) -> BResult<()> {
Err(self.stored())
}
fn write_bits(
&mut self,
_: &mut FunctionBuilder<'_>,
_: SValue,
_: SValue,
_: SValue,
) -> BResult<()> {
Err(self.stored())
}
fn units(&self) -> Units {
self.uniform.units()
}
fn read_unit(
&mut self,
fb: &mut FunctionBuilder<'_>,
bytes: u32,
index: SValue,
) -> BResult<SValue> {
let twin = self.twin.read_unit(fb, bytes, index)?;
let uniform = self.uniform.read_unit(fb, bytes, index)?;
fb.select(self.at_bind, twin, uniform)
}
fn write_unit(
&mut self,
_: &mut FunctionBuilder<'_>,
_: u32,
_: SValue,
_: SValue,
) -> BResult<()> {
Err(self.stored())
}
fn read_vec(
&mut self,
fb: &mut FunctionBuilder<'_>,
lanes: u32,
index: SValue,
) -> BResult<SValue> {
let twin = self.twin.read_vec(fb, lanes, index)?;
let uniform = self.uniform.read_vec(fb, lanes, index)?;
fb.select(self.at_bind, twin, uniform)
}
fn write_vec(
&mut self,
_: &mut FunctionBuilder<'_>,
_: u32,
_: SValue,
_: SValue,
) -> BResult<()> {
Err(self.stored())
}
}
/// The word memory of one target: a descriptor view, a uniform view and its storage twin, or a
/// device address.
/// The word memory of one target: a descriptor view or a device address.
#[derive(Clone, Copy, Debug)]
pub(super) enum Mem {
View(ViewMem),
Twin(TwinMem),
Psb(PsbMem),
}
@@ -245,15 +156,6 @@ impl Mem {
pub(super) fn with(self, ops: WordOps) -> Mem {
match self {
Mem::View(ViewMem(view, _, units)) => Mem::View(ViewMem(view, ops, units)),
Mem::Twin(TwinMem {
uniform: ViewMem(uniform, _, uniform_units),
twin: ViewMem(twin, _, twin_units),
at_bind,
}) => Mem::Twin(TwinMem {
uniform: ViewMem(uniform, ops, uniform_units),
twin: ViewMem(twin, ops, twin_units),
at_bind,
}),
Mem::Psb(m) => Mem::Psb(m.with(ops)),
}
}
@@ -263,7 +165,6 @@ impl WordMem for Mem {
fn read(&mut self, fb: &mut FunctionBuilder<'_>, word: SValue) -> BResult<SValue> {
match self {
Mem::View(m) => m.read(fb, word),
Mem::Twin(m) => m.read(fb, word),
Mem::Psb(m) => m.read(fb, word),
}
}
@@ -271,7 +172,6 @@ impl WordMem for Mem {
fn write(&mut self, fb: &mut FunctionBuilder<'_>, word: SValue, value: SValue) -> BResult<()> {
match self {
Mem::View(m) => m.write(fb, word, value),
Mem::Twin(m) => m.write(fb, word, value),
Mem::Psb(m) => m.write(fb, word, value),
}
}
@@ -285,7 +185,6 @@ impl WordMem for Mem {
) -> BResult<()> {
match self {
Mem::View(m) => m.write_bits(fb, word, mask, bits),
Mem::Twin(m) => m.write_bits(fb, word, mask, bits),
Mem::Psb(m) => m.write_bits(fb, word, mask, bits),
}
}
@@ -293,7 +192,6 @@ impl WordMem for Mem {
fn units(&self) -> Units {
match self {
Mem::View(m) => m.units(),
Mem::Twin(m) => m.units(),
Mem::Psb(m) => m.units(),
}
}
@@ -306,7 +204,6 @@ impl WordMem for Mem {
) -> BResult<SValue> {
match self {
Mem::View(m) => m.read_vec(fb, lanes, index),
Mem::Twin(m) => m.read_vec(fb, lanes, index),
Mem::Psb(m) => m.read_vec(fb, lanes, index),
}
}
@@ -320,7 +217,6 @@ impl WordMem for Mem {
) -> BResult<()> {
match self {
Mem::View(m) => m.write_vec(fb, lanes, index, value),
Mem::Twin(m) => m.write_vec(fb, lanes, index, value),
Mem::Psb(m) => m.write_vec(fb, lanes, index, value),
}
}
@@ -333,7 +229,6 @@ impl WordMem for Mem {
) -> BResult<SValue> {
match self {
Mem::View(m) => m.read_unit(fb, bytes, index),
Mem::Twin(m) => m.read_unit(fb, bytes, index),
Mem::Psb(m) => m.read_unit(fb, bytes, index),
}
}
@@ -347,7 +242,6 @@ impl WordMem for Mem {
) -> BResult<()> {
match self {
Mem::View(m) => m.write_unit(fb, bytes, index, value),
Mem::Twin(m) => m.write_unit(fb, bytes, index, value),
Mem::Psb(m) => m.write_unit(fb, bytes, index, value),
}
}
@@ -398,10 +292,15 @@ pub(super) fn prepare(
// 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 at_bind = (cx.decl.families.access.at_bind.get(t.slot))
let off = match cx
.decl
.families
.access
.at_bind
.get(t.slot)
.copied()
.flatten();
let off = match at_bind {
.flatten()
{
Some(at_bind) => fb.select(at_bind, m, shifted)?,
None => shifted,
};
@@ -433,22 +332,8 @@ pub(super) fn prepare(
.get(t.slot)
.copied()
.unwrap_or(UnitViews::NONE);
let mem = ViewMem(view, ops, units);
// A uniform view's storage twin is read where its key holds, at the same offset.
let twin = (cx.decl.families.access.twins.get(t.slot))
.copied()
.flatten();
let mem = match (twin, at_bind) {
(Some((twin, twin_units)), Some(at_bind)) => Mem::Twin(TwinMem {
uniform: mem,
twin: ViewMem(twin, ops, twin_units),
at_bind,
}),
(Some(_), None) => return Err(cx.fail("a storage twin without its key")),
(None, _) => Mem::View(mem),
};
Ok(Prepared {
mem,
mem: Mem::View(ViewMem(view, ops, units)),
off,
inb,
guard_store,
+3 -87
View File
@@ -702,10 +702,6 @@ pub struct AccessPlan {
/// the slot at its bind offset alone, which reads no push word, is worth the key
/// ([`Declared::at_bind`]).
pub storage_at_bind: bool,
/// The memory-plan slots read through a uniform view and its storage twin
/// (`DescriptorView::UniformWithStorageTwin`, [`storage_twins`]): each read selects the twin's
/// load where the slot's `RangeAtBindOffset` holds ([`Declared::twins`]).
pub twins: BTreeSet<usize>,
/// The arenas the function uses.
pub local: local::LocalPlan,
/// The function's index extensions ([`index`]): planned before any instruction is selected
@@ -894,9 +890,6 @@ pub struct Declared {
/// 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>>,
/// The storage twin of each slot the plan gives one (`AccessPlan::twins`), its word view and
/// unit views (`views::declare_twin`), by memory-plan slot index.
pub twins: Vec<Option<(View, views::UnitViews)>>,
}
/// Slot `slot`'s `RangeAtBindOffset` specialization: a `bool`, false by default, fixed at pipeline
@@ -1156,8 +1149,6 @@ const SLOT_WORK_BYTES: usize = std::mem::size_of::<Option<SlotLowering>>()
struct Census {
storage: u32,
uniform: u32,
/// The uniform views' storage twins ([`storage_twins`]), storage buffers too.
twins: u32,
fields: BTreeSet<PushField>,
}
@@ -1173,7 +1164,6 @@ impl Census {
let mut c = Census {
storage: 0,
uniform: 0,
twins: 0,
fields: push.clone(),
};
let mut psb = dynamic;
@@ -1200,7 +1190,7 @@ impl Census {
DescriptorCounts {
uniform_buffers: u32::from(table::spills(stage, &self.fields))
.saturating_add(self.uniform),
storage_buffers: self.storage.saturating_add(self.twins),
storage_buffers: self.storage,
..DescriptorCounts::default()
}
}
@@ -1505,28 +1495,18 @@ fn place_slots(cx: &mut SelectCx<'_>, m: &mut Meter) -> Result<Vec<Option<SlotCh
}
}
}
let twins = storage_twins(cx, (&lowering, &windows, &viewed), &census);
census.twins = u32::try_from(twins.len()).unwrap_or(u32::MAX);
let mut slots = Vec::with_capacity(memory.slots.len());
let addressed_slot = |cx: &mut SelectCx<'_>, slot: SlotRef| {
cx.facts.insert(RuntimeFact::DeviceAddresses { slot });
cx.push.remove(&PushField::SlotBindOffset(slot));
cx.push.insert(PushField::RootTableAddress);
};
for (i, (plan, (l, w))) in memory
.slots
.iter()
.zip(lowering.iter().zip(&windows))
.enumerate()
{
for (plan, (l, w)) in memory.slots.iter().zip(lowering.iter().zip(&windows)) {
let (Some(l), Some(window)) = (l, w) else {
slots.push(None);
continue;
};
let form = match l {
SlotLowering::View(_) if twins.contains(&i) => {
BufferForm::Descriptor(DescriptorView::UniformWithStorageTwin)
}
SlotLowering::View(kind) => BufferForm::Descriptor(descriptor_view(*kind)),
SlotLowering::Psb { .. } => {
addressed_slot(cx, plan.slot);
@@ -1583,66 +1563,9 @@ fn place_slots(cx: &mut SelectCx<'_>, m: &mut Meter) -> Result<Vec<Option<SlotCh
cx.families.access.storage_at_bind = p
.workarounds()
.contains(&DriverWorkaround::PushReadsLengthenThreadPayload);
cx.families.access.twins = twins;
Ok(slots)
}
/// The memory-plan slots of a kernel on a profile that takes
/// `DriverWorkaround::PushReadsLengthenThreadPayload` whose uniform view also binds its range as a
/// storage buffer, a storage twin (`DescriptorView::UniformWithStorageTwin`): every slot whose
/// form `lowering` makes a uniform view by its own window, not the per-stage storage-buffer
/// fallback (`viewed`), and whose uniform range (`windows`) fits `maxStorageBufferRange`; none
/// where their storage buffers, beside the slots' forms (`census`) and the stage's other
/// descriptors, would pass a per-stage descriptor limit or `maxDescriptorSetStorageBuffers`.
///
/// On that profile a light kernel that reads a pushed word was measured at about 2.2 times the
/// time of one that reads none, and one that reads a uniform view at its bind offset alone took
/// the constant cache's block read, slower than the uniform view at its residual: the twin, read
/// at its bind offset alone where the slot's `RangeAtBindOffset` holds, reads neither. Elsewhere
/// the slot reads its uniform view at its residual.
fn storage_twins(
cx: &SelectCx<'_>,
(lowering, windows, viewed): (&[Option<SlotLowering>], &[Option<Window>], &[bool]),
census: &Census,
) -> BTreeSet<usize> {
let p = cx.profile;
let limits = &p.fields().limits;
let takes = cx.stage == crate::pipeline::sym::Stage::Kernel
&& p.workarounds()
.contains(&DriverWorkaround::PushReadsLengthenThreadPayload);
if !takes {
return BTreeSet::new();
}
let twins: BTreeSet<usize> = lowering
.iter()
.zip(windows)
.enumerate()
.filter_map(|(i, (l, w))| {
let uniform = matches!(
l,
Some(SlotLowering::View(
ViewKind::UniformWords { .. } | ViewKind::UniformVec4 { .. }
))
);
let fits = w
.and_then(|w| uniform_bytes(w, limits))
.is_some_and(|r| r <= limits.max_storage_buffer_range);
let fallback = viewed.get(i).copied().unwrap_or(false);
(uniform && fits && !fallback).then_some(i)
})
.collect();
let mut counts = census.counts(cx.stage);
let n = u32::try_from(twins.len()).unwrap_or(u32::MAX);
counts.storage_buffers = counts.storage_buffers.saturating_add(n);
let total = cx.descriptors.plus(&counts);
match total.exceeded(limits).is_none()
&& total.storage_buffers <= limits.max_descriptor_set_storage_buffers
{
true => twins,
false => BTreeSet::new(),
}
}
/// The string attribute by which Metal's compiler declares that a buffer argument's memory is
/// reached through no other argument: every buffer argument of the AIR it emits carries it.
const BUFFER_NO_ALIAS: &[u8] = b"air-buffer-no-alias";
@@ -1950,16 +1873,9 @@ pub fn declare(
.get(&i)
.copied()
.unwrap_or(Units::NONE);
let unit_views = match (s, view) {
d.units.push(match (s, view) {
(Some(c), Some(view)) => views::UnitViews::declare(mb, c.slot, view, units)?,
_ => views::UnitViews::NONE,
};
d.units.push(unit_views);
d.twins.push(match s {
Some(c) if plan.families.access.twins.contains(&i) => {
Some(views::declare_twin(mb, c.slot, unit_views.units())?)
}
_ => None,
});
}
Ok(d)
+1 -56
View File
@@ -28,15 +28,6 @@
//! alignment of 1 or 2 to the unit index, and the word view's `OpArrayLength` still contains every
//! access.
//!
//! A uniform slot of a kernel on a profile that takes
//! `DriverWorkaround::PushReadsLengthenThreadPayload` may also have a **storage twin**
//! ([`declare_twin`]): a storage word view, and its `uvec4` view where the uniform view has one,
//! at a binding of its own (`ResourceKind::StorageTwin`) that the binder writes with the uniform
//! binding's buffer and range, so one offset reads the same byte through either. Each read loads
//! both and selects the twin's where the slot's `SpecKey::RangeAtBindOffset` holds
//! (`lower::access`): specialization fixes the constant, and the driver drops the other load. The
//! twin's views are decorated `NonWritable`, as the uniform buffer is read-only.
//!
//! 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
@@ -123,43 +114,6 @@ pub fn binding_symbol(slot: SlotRef) -> ResourceSlot {
}
}
/// The `StorageTwin` descriptor binding symbol of `slot`, which its storage twin is declared at
/// ([`declare_twin`]).
pub fn twin_symbol(slot: SlotRef) -> ResourceSlot {
ResourceSlot {
stage: slot.stage,
kind: ResourceKind::StorageTwin,
index: slot.index,
}
}
/// Declare the storage twin of `slot`, a slot read through a uniform view whose unit views are
/// `units` (`DescriptorView::UniformWithStorageTwin`): a storage word view at the slot's
/// `StorageTwin` binding ([`twin_symbol`]), and beside it a `StorageBuffer { uvec4[] }` view where
/// the uniform view has its `uvec4` view, so every read of the uniform view's has the twin's
/// counterpart of the same units. No store goes through the twin, and the module states its
/// binding unwritten (`ModuleBuilder::unwritten_buffer`), so the serializer decorates its views
/// `NonWritable`: the twin binds the uniform view's own range of a Metal `constant` buffer, which
/// the dispatch only reads, as it reads the uniform buffer.
pub fn declare_twin(
mb: &mut ModuleBuilder,
slot: SlotRef,
units: crate::memory::leaf::Units,
) -> BResult<(View, UnitViews)> {
let sym = twin_symbol(slot);
mb.unwritten_buffer(sym);
let view = declare_at(mb, sym, ViewKind::Storage)?;
let vec4 = match units.vec4 {
true => Some(declare_vec_at(mb, sym, view, 4)?),
false => None,
};
let units = UnitViews {
vec4,
..UnitViews::NONE
};
Ok((view, units))
}
/// 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)
@@ -385,16 +339,7 @@ pub fn declare_vec(
view: View,
lanes: u32,
) -> BResult<VecView> {
declare_vec_at(mb, binding_symbol(slot), view, lanes)
}
/// [`declare_vec`] at binding symbol `sym`, whose word view is `view`.
fn declare_vec_at(
mb: &mut ModuleBuilder,
sym: ResourceSlot,
view: View,
lanes: u32,
) -> BResult<VecView> {
let sym = binding_symbol(slot);
let u32_ty = u32_type(mb)?;
let len = u8::try_from(lanes)
.ok()
+1 -21
View File
@@ -243,19 +243,9 @@ impl BufferForm {
pub fn uniform_view(self) -> bool {
matches!(
self,
BufferForm::Descriptor(
DescriptorView::UniformWords
| DescriptorView::UniformVec4
| DescriptorView::UniformWithStorageTwin
)
BufferForm::Descriptor(DescriptorView::UniformWords | DescriptorView::UniformVec4)
)
}
/// Whether the form reads through a uniform view and its storage twin
/// ([`DescriptorView::UniformWithStorageTwin`]).
pub fn storage_twin(self) -> bool {
self == BufferForm::Descriptor(DescriptorView::UniformWithStorageTwin)
}
}
/// The descriptor view kind of a descriptor-form slot.
@@ -269,16 +259,6 @@ pub enum DescriptorView {
UniformWords,
/// A uniform buffer viewed as a `uvec4` array (std140-valid everywhere).
UniformVec4,
/// A uniform buffer (viewed as `UniformWords` or `UniformVec4` is) and its storage twin: a
/// second set-0 binding of the slot (`ResourceKind::StorageTwin`,
/// `BindingSource::StorageTwin`), a storage buffer written with the uniform binding's own
/// buffer and descriptor range, which the function reads instead where the slot's
/// `SpecKey::RangeAtBindOffset` holds. A uniform view as the other two are
/// ([`BufferForm::uniform_view`]): its descriptor base alignment, range limit and key are a
/// uniform view's, but for a slot bound to nothing, whose key is a bind at offset 0's. Only a
/// kernel on a profile that takes `DriverWorkaround::PushReadsLengthenThreadPayload` reads a
/// slot so, and only where the twins fit the stage's descriptor limits.
UniformWithStorageTwin,
}
/// How a compiled function fetches one attribute it reads
@@ -152,10 +152,6 @@ pub enum BindingSource {
compare: bool,
integer: bool,
},
/// The storage twin of a Metal `[[buffer(n)]]` slot read through a uniform view
/// (`ResourceKind::StorageTwin`, `DescriptorView::UniformWithStorageTwin`): a storage buffer
/// written with the slot's own buffer and descriptor range, its uniform binding's.
StorageTwin(SlotRef),
}
/// One push-constant range of a [`PipelineLayout`]: a stage's fixed window (vertex `[0, 64)`,
-1
View File
@@ -836,7 +836,6 @@ fn binding_source(slot: ResourceSlot) -> BindingSource {
},
ResourceKind::TileAttachment(color) => BindingSource::TileAttachment(color),
ResourceKind::TileMap => BindingSource::TileMap(metal(SlotClass::Texture)),
ResourceKind::StorageTwin => BindingSource::StorageTwin(metal(SlotClass::Buffer)),
ResourceKind::SeparateTexture(sampler) => {
// The use is above the texture slot in the index (`ResourceSlot::separate_texture`).
let (texture, sampler) = ResourceSlot::separate_texture_parts(sampler, slot.index);
-5
View File
@@ -450,11 +450,6 @@ pub enum ResourceKind {
compare: bool,
integer: bool,
},
/// The storage twin of the stage's `[[buffer(n)]]` slot `ResourceSlot::index`, which the
/// function also reads through a uniform view (`DescriptorView::UniformWithStorageTwin`): a
/// read-only storage buffer of the same descriptor range, which the function reads instead
/// where the slot's `SpecKey::RangeAtBindOffset` holds.
StorageTwin,
}
/// What a bound acceleration structure holds: the binder binds a top-level structure, so a
@@ -943,13 +943,10 @@ impl ModuleBuilder {
}
}
/// State that nothing in the module writes the memory bound at buffer binding `sym`: a Metal
/// buffer argument no other binding or address reaches (it is unaliased) and no store or
/// atomic of the module reaches through its own views; or a uniform view's storage twin
/// (`memory::views::declare_twin`), bound to the uniform view's own range of a `constant`
/// buffer, which the dispatch only reads, as it reads the uniform buffer, and through which
/// nothing stores. The serializer decorates its storage views `NonWritable` where its own walk
/// of the module agrees (`spirv::serialize`).
/// State that nothing in the module writes the memory bound at buffer binding `sym`: no other
/// binding or address reaches it (its Metal argument is unaliased), and no store or atomic of
/// the module reaches it through its own views. The serializer decorates its storage views
/// `NonWritable` where its own walk of the module agrees (`spirv::serialize`).
pub fn unwritten_buffer(&mut self, sym: ResourceSlot) {
self.unwritten_buffers.insert(sym);
}
+1 -2
View File
@@ -348,8 +348,7 @@ impl Default for Config {
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Buffer {
/// The `StorageBuffer`/`Uniform` binding this buffer backs. The elements of a descriptor
/// array of buffers are the slot's consecutive buffers, in element order. A storage twin's
/// binding (`ResourceKind::StorageTwin`) with no buffer of its own reads its slot's.
/// array of buffers are the slot's consecutive buffers, in element order.
pub slot: Option<ResourceSlot>,
/// The device address of byte 0, for `PhysicalStorageBuffer` accesses.
pub address: Option<u64>,
+2 -16
View File
@@ -20,7 +20,7 @@ use std::cmp::Ordering;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::ops::Range;
use crate::pipeline::sym::{ResourceKind, ResourceSlot, SpecKey, VaryingKey};
use crate::pipeline::sym::{SpecKey, VaryingKey};
use crate::spirv::ids::{BlockId, ConstId, FuncId, GlobalId, TypeId, Value, VarId};
use crate::spirv::ir::{
ExecMode, ExecModel, GlobalKind, Inst, InstNode, Scope, StorageClass, Terminator, TypedModule,
@@ -143,21 +143,7 @@ impl<'m> Prog<'m> {
// buffers, element `e` the `e`th; `OpAccessChain` selects one and traps past
// them (and a sized array needs all of its elements bound).
GlobalKind::Resource(slot) => {
// A storage twin's binding holds the slot's own buffer, as the binder
// writes it (`DescriptorView::UniformWithStorageTwin`), unless a buffer
// of its own is bound there.
let own = |slot: ResourceSlot| {
res.buffers.iter().position(|b| b.slot == Some(slot))
};
let read = match (slot.kind, own(*slot)) {
(ResourceKind::StorageTwin, None) => ResourceSlot {
kind: ResourceKind::Buffer,
..*slot
},
_ => *slot,
};
let slot = &read;
let first = own(*slot);
let first = res.buffers.iter().position(|b| b.slot == Some(*slot));
let bound = |k: usize| {
res.buffers
.iter()
@@ -10,7 +10,7 @@
//!
//! A compute module's candidates are only the buffer bindings the lowering states unwritten
//! (`ModuleBuilder::unwritten_buffer`: an unaliased Metal buffer argument no write of the function
//! reaches, or a uniform view's storage twin), and the walk below must agree. The decoration says the module does not write the
//! reaches), and the walk below must agree. The decoration says the module does not write the
//! memory, which a device may read as read-only memory: RADV reads a uniform address of it with a
//! scalar load, which an aliasing write would not be ordered with.
//!
+60 -231
View File
@@ -529,209 +529,52 @@ fn a_storage_view_reads_its_residual_without_the_row() {
}
}
/// The storage twin binding symbol of kernel buffer slot `index`.
fn twin_slot(index: u32) -> ResourceSlot {
ResourceSlot {
stage: Stage::Kernel,
kind: ResourceKind::StorageTwin,
index,
}
}
/// The variables of compiled module `a` bound at `sym`, each with whether it is decorated
/// `NonWritable`.
fn views_at(a: &crate::library::FunctionArtifact, sym: ResourceSlot) -> Vec<(u32, bool)> {
let (words, relocs) = (&a.module.words, &a.module.relocs);
let (_, non_writable) = buffer_views(words, relocs);
(relocs.iter())
.filter_map(|(s, at)| match s {
Symbol::Binding(slot) if *slot == sym => {
words.get((*at as usize).checked_sub(2)?).copied()
}
_ => None,
})
.map(|id| (id, non_writable.contains(&id)))
.collect()
}
/// The form of buffer slot `index` of `a`.
fn form_of(a: &crate::library::FunctionArtifact, index: u32) -> BufferForm {
match a.interface.slots.get(&sref(index)) {
Some(SlotInterface::Buffer(b)) => b.form,
other => panic!("slot {index}: {other:?}"),
}
}
/// On the profile that takes `DriverWorkaround::PushReadsLengthenThreadPayload`, a kernel's
/// uniform view has a storage twin (`DescriptorView::UniformWithStorageTwin`), with
/// `uniformBufferStandardLayout` (`u32[]`) and without (`uvec4[]`): a `StorageTwin` binding that
/// link numbers after every buffer binding of the stage, beside the slot's uniform one. At
/// `RangeAtBindOffset` 1 a load reads the twin at the Metal offset alone, and no value the slot's
/// `SlotBindOffset` word reaches is read once the key is folded ([`reads_push_word`]); at 0, the
/// negative control, it reads the uniform view at the residual plus the offset. The interpreter
/// binds the two to different bytes, so the value read names the view read. Every variable of the
/// twin's binding is decorated `NonWritable`: the twin binds the uniform view's own range of a
/// `constant` buffer, read-only as the uniform buffer is, and a driver merges, reuses and moves a
/// storage buffer's loads only where its variable says so (Mesa's `nir_opt_access`, which ANV
/// runs, where the kernel writes any buffer, as this one writes slot 1).
/// A kernel's `constant` slot reads through a uniform view, and its layout binds nothing for it
/// but that view: on the profile that takes `DriverWorkaround::PushReadsLengthenThreadPayload`,
/// 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_uniform_view_reads_its_storage_twin_at_its_bind_offset() {
let entry = "buffer_end_byte_load_constant";
let Some(bc) = assemble_file(entry) else {
return;
};
let key = SpecKey::RangeAtBindOffset(sref(0));
let field = PushField::SlotBindOffset(sref(0));
for standard in [true, false] {
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}"));
assert_eq!(
form_of(&a, 0),
BufferForm::Descriptor(DescriptorView::UniformWithStorageTwin),
"{what}"
);
assert_eq!(
form_of(&a, 1),
BufferForm::Descriptor(DescriptorView::Storage),
"{what}"
);
assert!(a.interface.read_keys().contains(&key), "{what}");
let (table, _) = link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}"));
let twin = table.bindings.get(&twin_slot(0)).copied();
let buffers = [kslot(0), kslot(1)].map(|s| table.bindings.get(&s).copied());
assert_eq!(
(buffers, twin),
([Some((0, 0)), Some((0, 1))], Some((0, 2))),
"{what}"
);
let views = views_at(&a, twin_slot(0));
assert!(
!views.is_empty() && views.iter().all(|&(_, non_writable)| non_writable),
"{what}: the twin's variables and whether each is NonWritable: {views:?}"
);
let (plan, m) = typed_module(&bc, entry, &p).expect("module");
assert!(!reads_push_word(&m, field, (key, true)), "{what} at 1");
assert!(reads_push_word(&m, field, (key, false)), "{what} at 0");
// A residual of 8 pushed: byte 5 of the twin when the key holds, byte 13 of the uniform
// view (its padding) when it does not.
let uniform_bytes = [9u8, 8, 7, 6, 5, 0xC3];
let twin_bytes = [1u8, 2, 3, 4, 5, 0x5A];
for (at_bind, want) in [(1u64, 0x5Au8), (0, 0x44)] {
let mut ubo = bound(0, 0, &uniform_bytes, 0x44);
ubo.bytes.resize(512, 0x44);
let mut ssbo = bound(0, 0, &twin_bytes, 0x77);
ssbo.slot = Some(twin_slot(0));
ssbo.bytes.resize(512, 0x77);
let res = Resources {
buffers: vec![ubo, ssbo, 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[2][..4],
[want, 0, 0, 0],
"{what} at_bind={at_bind}"
);
}
}
}
/// A storage twin is a kernel's alone, on the profile that takes
/// `DriverWorkaround::PushReadsLengthenThreadPayload` alone, and only where the twins fit the
/// stage's limits: a fragment function's uniform view on that profile, and a kernel's on every
/// other tested profile (the same driver's on another GPU among them, `intel-irisxe-anv`), keep
/// the plain uniform view and declare no `StorageTwin` binding; and on that profile with
/// `maxPerStageDescriptorStorageBuffers` lowered to the kernel's one storage view, the twin, a
/// storage buffer more, does not fit, so the plan declares none, where one more lets it.
#[test]
fn a_storage_twin_is_a_kernels_on_its_profile_within_the_limits() {
let entry = "buffer_end_byte_load_constant";
let Some(bc) = assemble_file(entry) else {
return;
};
let plain = |a: &crate::library::FunctionArtifact, p: &DeviceProfile, what: &str| {
let form = match a.interface.slots.values().next() {
Some(SlotInterface::Buffer(b)) => b.form,
other => panic!("{what}: {other:?}"),
};
assert!(
matches!(
form,
BufferForm::Descriptor(DescriptorView::UniformWords | DescriptorView::UniformVec4)
),
"{what}: {form:?}"
);
let (table, _) = link_and_validate(a, p).unwrap_or_else(|e| panic!("{what}: L3: {e}"));
assert!(
!table
.bindings
.keys()
.any(|s| s.kind == ResourceKind::StorageTwin),
"{what}"
);
};
for stem in PROFILES.into_iter().chain(["intel-irisxe-anv"]) {
let p = profile_with(stem, true, true);
let a = compile(&bc, entry, &p).unwrap_or_else(|e| panic!("{stem}: {e}"));
assert_ne!(
form_of(&a, 0),
BufferForm::Descriptor(DescriptorView::UniformWithStorageTwin)
);
plain(&a, &p, stem);
}
let fragment = assemble_file("a2c_coverage");
if let Some(fragment) = fragment {
let p = profile_with(AT_BIND_PROFILE, true, true);
let a = compile(&fragment, "a2c_color", &p).unwrap_or_else(|e| panic!("a2c_color: {e}"));
plain(&a, &p, "a2c_color");
}
let limited = |storage: u32| {
let path = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../metal2vulkan-validation/profiles")
.join(format!("{AT_BIND_PROFILE}.json"));
let text = std::fs::read_to_string(path).expect("profile");
let mut desc = DeviceDescription::from_khronos_json(&text, None).expect("description");
desc.limits.max_per_stage_descriptor_storage_buffers = storage;
Device::new(desc, policy())
.expect("device")
.profile()
.clone()
};
let p = limited(1);
let a = compile(&bc, entry, &p).unwrap_or_else(|e| panic!("limited: {e}"));
assert_eq!(
form_of(&a, 0),
BufferForm::Descriptor(DescriptorView::UniformWords)
);
plain(&a, &p, "limited");
let p = limited(2);
let a = compile(&bc, entry, &p).unwrap_or_else(|e| panic!("room: {e}"));
assert_eq!(
form_of(&a, 0),
BufferForm::Descriptor(DescriptorView::UniformWithStorageTwin)
);
link_and_validate(&a, &p).unwrap_or_else(|e| panic!("room: L3: {e}"));
}
/// A plan states which of its buffer writes no function stores through
/// (`BindingPlan::read_only_buffer`), so a consumer may bind one buffer every command shares
/// there. On the profile that takes `DriverWorkaround::PushReadsLengthenThreadPayload`, a kernel's
/// `constant` slot bound to nothing writes its uniform binding and its storage twin from the
/// `ZeroBuffer` neutral, and both are read-only: the twin's is a storage buffer, so its descriptor
/// type alone would call it writable. The written `device` slot's storage view is not read-only. On
/// every other tested profile, the negative control, the slot has no twin, and a write is
/// read-only exactly where it is a uniform buffer's.
#[test]
fn an_unbound_constant_slot_s_storage_twin_is_a_read_only_write() {
use crate::bind::{BindState, DescriptorWrite, NeutralResource, WriteSource};
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);
@@ -751,42 +594,28 @@ fn an_unbound_constant_slot_s_storage_twin_is_a_read_only_write() {
.find(|b| b.binding == write.binding)
.map(|b| b.source)
};
let mut writes = BTreeMap::new();
for write in &plan.descriptors {
let Some(at @ (BindingSource::Buffer(_) | BindingSource::StorageTwin(_))) =
source(write)
else {
continue;
};
assert!(
matches!(
write.source,
WriteSource::Neutral(NeutralResource::ZeroBuffer { .. })
),
"{stem} {at:?}: {:?}",
write.source
);
writes.insert(at, (write.ty, plan.read_only_buffer(write)));
}
let uniform = crate::vk::DescriptorType::UNIFORM_BUFFER;
let storage = crate::vk::DescriptorType::STORAGE_BUFFER;
let twin = BindingSource::StorageTwin(sref(0));
match stem == AT_BIND_PROFILE {
true => assert_eq!(
writes,
BTreeMap::from([
(BindingSource::Buffer(sref(0)), (uniform, true)),
(BindingSource::Buffer(sref(1)), (storage, false)),
(twin, (storage, true)),
]),
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}"
),
false => {
assert!(!writes.contains_key(&twin), "{stem}");
for (at, (ty, read_only)) in &writes {
assert_eq!(*read_only, *ty == uniform, "{stem} {at:?}");
}
}
);
}
}
}
@@ -300,11 +300,6 @@ fn symbol(source: BindingSource) -> ResourceSlot {
kind: ResourceKind::Synthetic(binding),
index: 0,
},
BindingSource::StorageTwin(slot) => ResourceSlot {
stage: slot.stage,
kind: ResourceKind::StorageTwin,
index: slot.index,
},
other => panic!("a compute binding {other:?}"),
}
}
@@ -1127,12 +1122,7 @@ fn host_replay(
.range;
let guest = slots[&slot.index];
let (o, n) = (r.offset as usize, r.range as usize);
// A storage twin is only read: nothing of it returns.
let returns = sym.kind != ResourceKind::StorageTwin;
(
memory[&guest][o..o + n].to_vec(),
returns.then_some((guest, o)),
)
(memory[&guest][o..o + n].to_vec(), Some((guest, o)))
}
WriteSource::Neutral(_) => (vec![0; 4096], None),
WriteSource::ArgumentTable { .. } => (
@@ -9532,7 +9532,6 @@ method metal2vulkan::bind::BindingPlan::instantiate_draw pub fn instantiate_draw
method metal2vulkan::bind::BindingPlan::instantiate_draw_apart_into pub fn instantiate_draw_apart_into(&self, state: &BindState, draw: &DrawCall, commands: &mut DrawCommands) -> Result<(), BindError>
method metal2vulkan::bind::BindingPlan::instantiate_draw_into pub fn instantiate_draw_into(&self, state: &BindState, draw: &DrawCall, commands: &mut DrawCommands) -> Result<(), BindError>
method metal2vulkan::bind::BindingPlan::instantiate_replay pub fn instantiate_replay(&self, state: &BindState, threads_per_group: [u32; 3]) -> Result<DispatchCommands, BindError>
method metal2vulkan::bind::BindingPlan::read_only_buffer pub fn read_only_buffer(&self, write: &DescriptorWrite) -> bool
method metal2vulkan::bind::BindingPlan::rebind_draw_slots_into pub fn rebind_draw_slots_into(&self, state: &BindState, slots: &[SlotRef], commands: &mut DrawCommands) -> Result<bool, BindError>
method metal2vulkan::bind::BindingPlan::rebind_draw_slots_with pub fn rebind_draw_slots_with(&self, rebinds: &SlotRebinds, state: &BindState, commands: &mut DrawCommands) -> Result<bool, BindError>
method metal2vulkan::bind::BindingPlan::redraw_apart_into pub fn redraw_apart_into(&self, state: &BindState, (from, draw): (&DrawCall, &DrawCall), commands: &mut DrawCommands) -> Result<bool, BindError>
@@ -10174,7 +10173,6 @@ method metal2vulkan::pipeline::AmplificationDraws::new pub fn new(layered: bool,
method metal2vulkan::pipeline::BandPrimitive::patch_control_points pub fn patch_control_points(self) -> u32
method metal2vulkan::pipeline::BlendEquation::of pub fn of(c: &crate::pipeline::descriptor::ColorAttachmentDescriptor) -> Option<BlendEquation>
method metal2vulkan::pipeline::BlendState::reads_second_output pub fn reads_second_output(&self) -> bool
method metal2vulkan::pipeline::BufferForm::storage_twin pub fn storage_twin(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
@@ -15040,7 +15038,6 @@ variant metal2vulkan::pipeline::BindingSource::SamplerArray SamplerArray { stage
variant metal2vulkan::pipeline::BindingSource::SeparateSampler SeparateSampler { stage: Stage, sampler: CombinedSampler }
variant metal2vulkan::pipeline::BindingSource::SeparateTexture SeparateTexture { texture: SlotRef, sampler: CombinedSampler }
variant metal2vulkan::pipeline::BindingSource::SnapshotTexels SnapshotTexels(u32)
variant metal2vulkan::pipeline::BindingSource::StorageTwin StorageTwin(SlotRef)
variant metal2vulkan::pipeline::BindingSource::Synthetic Synthetic { stage: Stage, binding: SyntheticBinding }
variant metal2vulkan::pipeline::BindingSource::Texture Texture(SlotRef)
variant metal2vulkan::pipeline::BindingSource::TileAttachment TileAttachment(u32)
@@ -15061,7 +15058,6 @@ 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::UniformWithStorageTwin UniformWithStorageTwin
variant metal2vulkan::pipeline::DescriptorView::UniformWords UniformWords
variant metal2vulkan::pipeline::EntryMath::Fast Fast
variant metal2vulkan::pipeline::EntryMath::Precise Precise
@@ -15258,7 +15254,6 @@ variant metal2vulkan::pipeline::ResourceKind::SamplerArray SamplerArray { compar
variant metal2vulkan::pipeline::ResourceKind::SeparateSampler SeparateSampler(SamplerRef)
variant metal2vulkan::pipeline::ResourceKind::SeparateTexture SeparateTexture(SamplerRef)
variant metal2vulkan::pipeline::ResourceKind::SnapshotTexels SnapshotTexels(u32)
variant metal2vulkan::pipeline::ResourceKind::StorageTwin StorageTwin
variant metal2vulkan::pipeline::ResourceKind::Synthetic Synthetic(SyntheticBinding)
variant metal2vulkan::pipeline::ResourceKind::Texture Texture
variant metal2vulkan::pipeline::ResourceKind::TileAttachment TileAttachment(u32)
Can't render this file because it is too large.
-32
View File
@@ -1505,38 +1505,6 @@ for dependency in &pipeline.dependencies {
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.
- On that profile a kernel's uniform view also has a **storage twin**, where the twins fit the
stage's descriptor limits (`maxPerStageDescriptorStorageBuffers`, `maxPerStageResources` and
`maxDescriptorSetStorageBuffers`; past one, no slot of the stage has one). Its slot's form is
`DescriptorView::UniformWithStorageTwin`, a uniform view (`BufferForm::uniform_view`) whose
`BufferForm::storage_twin` holds, and its layout has a second set-0 binding for it
(`ResourceKind::StorageTwin`, `BindingSource::StorageTwin`): a storage buffer. Link numbers set 0
in `ResourceSlot` order, whose kind comes before its index, so a stage's twins follow every
other binding of the stage, in buffer index order. Write the twin with the uniform binding's own
buffer, offset and range, from the same bind offset: a plan writes both from the slot's own
source (`WriteSource::Buffer`, `InlineBytes` or `Neutral`), an instance's `DescriptorRange`s
give both bindings one range, and the plan's `uses` hold a `Storage` read of the slot beside the
`Uniform` one. No function stores through the twin, and the module decorates the twin's
variables `NonWritable`: it binds the uniform view's own range of a `constant` buffer, which the
dispatch only reads. `BindingPlan::read_only_buffer` holds for both of the slot's writes, as for every uniform buffer's, so a slot bound to nothing may bind
one zero buffer that every command shares at both (the runtime's, made as a uniform and a
storage buffer); a write it does not hold for may be stored through. Where the
slot's `RangeAtBindOffset` holds, the kernel reads the twin at its bind offset alone; elsewhere
the uniform view at its residual, so the same specialization and range serve either. The key is
a uniform view's (a bind offset the view base alignment divides, at a slot whose table tells it
apart; inline bytes) but for a slot bound to nothing, which takes a bind at offset 0's value as a
storage view does. Where the runtime takes the uniform views' residual form it keeps a twin's
key only where no other `RangeAtBindOffset` of the key is 0, and sets it to 0 beside one that
is (a storage view bound past offset 0, a twin at an offset no alignment divides), and where the
twin's stage reads any other word the binder writes for it under the key, in its push range or
its `ArgumentTable` (`PushPlacement::fields`: a root table's address, a multi-region region's
`DispatchRegion` words, a flat grid's region, a replay's region record): the twin's read pays
only where it leaves no such word to read. `state.uniform_views_at_residual`
shares no twin's range: it starts at its bind offset. There a kernel of three storage views at
offset 0 and inline bytes ran in 102.1 us a dispatch with the bytes read through the twin
(job m3-max-34864), against the 142.8 us above; with two of its storage views and its constant's
buffer at offsets that move every dispatch, 154.0 us through the twin and 143.1 us through the
uniform view at its residual.
- 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; the runtime states one on a
device whose memory is the host's, `DeviceProfile::reads_ycbcr_planes_in_place`: an integrated