Read only the slots calls changed when a draw brings a stage table in place

Content: the tree of `development` at 9cbf7c95db, unchanged.
This commit is contained in:
Anees Iqbal committed 2026-10-26 13:19:04 +02:00
1 parent f864c34b29
commit b073ccfa4e
5 files changed
+338 -13

No files matched your search

@@ -53,6 +53,7 @@ use metal2vulkan::pipeline::{
use std::any::Any;
use std::collections::btree_map::Entry;
use std::collections::{BTreeMap, BTreeSet};
use std::ops::Range;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
@@ -161,6 +162,8 @@ pub(super) struct ArgumentTable {
retained: Retained,
/// Its contents' stamp, drawn afresh by every call that may change them.
stamp: Stamp,
/// The slots its last calls changed, by the stamps they took ([`Changes`]).
changes: Changes,
}
/// A copy binds what the table binds, under a stamp of its own: a copy changed in place (a
@@ -178,6 +181,7 @@ impl Clone for ArgumentTable {
bytes: self.bytes.clone(),
retained: self.retained.clone(),
stamp: Stamp::fresh(),
changes: Changes::default(),
}
}
}
@@ -204,6 +208,58 @@ impl Default for Stamp {
}
}
/// The most slots a table keeps of its last calls' changes ([`Changes`]): a reader that read it
/// before those reads it whole.
const CHANGES_KEPT: usize = 16;
/// The slots a table's last calls changed (or may have: a refused call's too), each with the
/// stamp the table took at that call, oldest first, and the stamp before the oldest: a reader that
/// read the table under one of those stamps brings in the slots changed since alone
/// ([`ArgumentTable::refresh_changed`]); a reader under any other stamp reads it whole. A copy of
/// a table keeps none (its stamp is its own).
#[derive(Default)]
struct Changes {
since: Option<Stamp>,
slots: Vec<(Stamp, SlotClass, u32)>,
}
impl Changes {
/// Note a call that took the table from `before` to `after`, changing the slots of `class`
/// at `indices`: of more slots than are kept, it leaves none to read from.
fn note(&mut self, (before, after): (Stamp, Stamp), class: SlotClass, indices: Range<u32>) {
if indices.len() > CHANGES_KEPT {
self.since = None;
self.slots.clear();
return;
}
if self.slots.is_empty() {
self.since = Some(before);
}
self.slots
.extend(indices.map(|index| (after, class, index)));
// The oldest calls go whole: a reader under the stamp one of them took saw its slots.
while self.slots.len() > CHANGES_KEPT {
let oldest = self.slots[0].0;
let gone = self.slots.partition_point(|&(stamp, ..)| stamp == oldest);
self.slots.drain(..gone);
self.since = Some(oldest);
}
}
/// The slots changed since the table's stamp was `read`, where it keeps them.
fn since(&self, read: Stamp) -> Option<impl Iterator<Item = (SlotClass, u32)> + '_> {
let from = match self.since == Some(read) {
true => 0,
false => self.slots.iter().rposition(|&(stamp, ..)| stamp == read)? + 1,
};
Some(
self.slots[from..]
.iter()
.map(|&(_, class, index)| (class, index)),
)
}
}
/// The core an argument table was last retained into ([`EncoderCore::id`]) and the table's stamp
/// then ([`ArgumentTable::retain`]): while both hold, that core holds every object the table
/// binds.
@@ -435,6 +491,15 @@ impl ArgumentTable {
self.stamp
}
/// A call that may change the slots of `class` at `indices` (before its checks: a refused one
/// may have changed nothing, which a reader then reads again): a fresh stamp, and the slots
/// noted ([`Changes`]).
fn changed(&mut self, class: SlotClass, indices: Range<u32>) {
let before = self.stamp;
self.stamp = Stamp::fresh();
self.changes.note((before, self.stamp), class, indices);
}
/// Refuse `buffer` at `offset` in `call` of an encoder of `core`: a buffer of another device,
/// and, in a render stage's table, an offset past its length (a compute table holds it).
fn check_buffer(
@@ -478,7 +543,7 @@ impl ArgumentTable {
stride: u64,
index: u32,
) -> Result<(), Error> {
self.stamp = Stamp::fresh();
self.changed(SlotClass::Buffer, index..index.saturating_add(1));
check_index(call, index, BUFFER_SLOTS)?;
let stride = attribute_stride(stride);
if let Some(buffer) = buffer {
@@ -521,7 +586,7 @@ impl ArgumentTable {
strides: Option<&[u64]>,
first: u32,
) -> Result<(), Error> {
self.stamp = Stamp::fresh();
self.changed(SlotClass::Buffer, span(first, buffers.len()));
if buffers.len() != offsets.len() || strides.is_some_and(|s| s.len() != buffers.len()) {
return Err(invalid(call, Problem::LengthMismatch));
}
@@ -582,7 +647,7 @@ impl ArgumentTable {
stride: u64,
index: u32,
) -> Result<(), Error> {
self.stamp = Stamp::fresh();
self.changed(SlotClass::Buffer, index..index.saturating_add(1));
check_index(call, index, BUFFER_SLOTS)?;
let stride = attribute_stride(stride);
if let Some(len) = self.bytes.get(&index).map(|bytes| bytes.len) {
@@ -648,7 +713,7 @@ impl ArgumentTable {
stride: Option<u64>,
index: u32,
) -> Result<(), Error> {
self.stamp = Stamp::fresh();
self.changed(SlotClass::Buffer, index..index.saturating_add(1));
check_index(call, index, BUFFER_SLOTS)?;
let length = bytes.len() as u64;
if length > INLINE_BYTES_LIMIT {
@@ -698,7 +763,7 @@ impl ArgumentTable {
textures: &[Option<&Texture>],
first: u32,
) -> Result<(), Error> {
self.stamp = Stamp::fresh();
self.changed(SlotClass::Texture, span(first, textures.len()));
check_range(call, first, textures.len(), TEXTURE_SLOTS)?;
for texture in textures.iter().flatten() {
core.check_device(call, texture.device())?;
@@ -724,7 +789,7 @@ impl ArgumentTable {
clamps: Option<(&[f32], &[f32])>,
first: u32,
) -> Result<(), Error> {
self.stamp = Stamp::fresh();
self.changed(SlotClass::Sampler, span(first, samplers.len()));
if let Some((min, max)) = clamps {
if min.len() != samplers.len() || max.len() != samplers.len() {
return Err(invalid(call, Problem::LengthMismatch));
@@ -754,7 +819,7 @@ impl ArgumentTable {
tables: &[Option<&VisibleFunctionTable>],
first: u32,
) -> Result<(), Error> {
self.stamp = Stamp::fresh();
self.changed(SlotClass::Buffer, span(first, tables.len()));
check_range(call, first, tables.len(), BUFFER_SLOTS)?;
for table in tables.iter().flatten() {
core.check_device(call, table.device())?;
@@ -1032,6 +1097,103 @@ impl ArgumentTable {
self.check_reading(kept, read, (maps, views));
}
/// [`refresh_reading`](Self::refresh_reading) of `kept`, read last under the stamp `read`
/// through the same interface and maps: only the slots the table's calls changed since, where
/// it keeps them ([`Changes`]) and its slots that tell the view base alignment apart are as
/// `kept` holds them, so every other slot's binding and shape are as read then. Whether it
/// brought them in; else nothing is changed, and the table is to be read whole.
pub(super) fn refresh_changed(
&self,
(kept, read): (&mut StageTable, Stamp),
(stage, interface): (Stage, &PipelineInterface),
(maps, views): (&SamplerMaps, &AtBindViews),
reshape: &mut Reshape,
) -> bool {
let Some(changed) = self.changes.since(read) else {
return false;
};
// A buffer's shape reads these slots: where they changed, every buffer is read again.
if self.at_bind_views(stage, views) != kept.at_bind_views {
return false;
}
let alignment = views.alignment;
for (class, index) in changed {
match class {
SlotClass::Buffer => {
self.refresh_buffer((kept, index), (stage, interface), alignment, reshape)
}
SlotClass::Texture => match self.textures.get(&index) {
Some(texture) => reshape.slot(
&mut kept.textures,
index,
bound_texture(texture),
BoundTexture::shape,
),
None => {
if kept.textures.remove(&index).is_some() {
reshape.unbound();
}
}
},
SlotClass::Sampler => match self.samplers.get(&index) {
Some((sampler, clamps)) => {
let slot = SlotRef {
stage,
class: SlotClass::Sampler,
index,
};
let desc = maps.sampler(slot, bound_sampler(sampler, *clamps));
reshape.slot(
&mut kept.samplers,
index,
BoundSampler::new(desc),
BoundSampler::shape,
);
}
None => {
if kept.samplers.remove(&index).is_some() {
reshape.unbound();
}
}
},
}
}
#[cfg(debug_assertions)]
self.check_reading(kept, (stage, interface), (maps, views));
true
}
/// Buffer slot `index` of `kept` brought in place as [`refresh_reading`](Self::refresh_reading)
/// brings it: unbound where the function reads it unbound or nothing within its length is
/// bound there, else its inline bytes or buffer, its shape of the class `alignment` tells it.
fn refresh_buffer(
&self,
(kept, index): (&mut StageTable, u32),
read: (Stage, &PipelineInterface),
alignment: u32,
reshape: &mut Reshape,
) {
let bound = !self.reads_unbound(read, index)
&& (self.bytes.contains_key(&index)
|| (self.buffers.get(&index))
.is_some_and(|(buffer, offset)| *offset <= buffer.length()));
if !bound {
if kept.buffers.remove(&index).is_some() {
reshape.unbound();
}
return;
}
let a = kept.class_alignment(index, alignment);
if let Some(bytes) = self.bytes.get(&index) {
reshape.slot(&mut kept.buffers, index, bound_bytes(bytes), |b| b.shape(a));
} else if let Some((buffer, offset)) = self.buffers.get(&index) {
let stride = self.attribute_strides.get(&index).copied();
if let Some(bound) = bound_buffer(buffer, *offset, stride) {
reshape.slot(&mut kept.buffers, index, bound, |b| b.shape(a));
}
}
}
/// That `kept`, brought in place by [`refresh_reading`](Self::refresh_reading) (or kept unread
/// while nothing it reads changed: `live_bind::ReadFrom`), is the table `stage`'s function of
/// `interface` reads whole ([`stage_table_reading`](Self::stage_table_reading)), each sampler
@@ -1263,6 +1425,11 @@ fn retain_into(
}
}
/// The `count` indices from `first`, as many as lie below `u32::MAX`.
fn span(first: u32, count: usize) -> Range<u32> {
first..first.saturating_add(u32::try_from(count).unwrap_or(u32::MAX))
}
/// The objects a table's `buffers`, `textures` and `samplers` bind, in the table's order: its
/// buffers, then its textures, then its sampler states, each by index.
fn bound_in<'a>(
+10 -1
View File
@@ -10,7 +10,10 @@
//! (`argument_table::AtBindViews`, which another table's offsets may shrink), and that no rebind
//! or detach of a no-copy buffer may have changed (which changes a bound buffer's binding with
//! no call: `buffer::host_cells_moved`), is not read again ([`ReadFrom`]; checked whole in debug
//! builds).
//! builds). Where only calls changed it since it was so read, and the table keeps the slots
//! they changed (`ArgumentTable::refresh_changed`), only those slots are brought in: every
//! other slot's binding is a function of what the table bound under the stamp read, the
//! interface, the maps and the moves, none of which changed (checked whole in debug builds).
//! Every other field is computed as before and compared ([`Reshape::field`]), as much of it as
//! the shape reads ([`Reshape::shaped`]; a value no shape reads, such as the depth/stencil state,
//! the stencil references or the blend color, is stored uncompared). The new value is always
@@ -249,6 +252,12 @@ impl ReadFrom {
self.tables[at] == Some(stamp)
}
/// The stamp the table at `at` in the reading order was read under, if any: one whose calls
/// since it keeps brings in their slots alone (`ArgumentTable::refresh_changed`).
pub(super) fn read_under(&self, at: usize) -> Option<Stamp> {
self.tables[at]
}
/// The tables of `stamps` read now through `interface` (of the drawing state `state` gives)
/// with `maps` at `moved` moves.
pub(super) fn read(
@@ -5246,6 +5246,14 @@ impl RenderCommandEncoder {
continue;
}
counts.stage_table_read();
// Only the slots calls changed since it was read, where the table keeps them.
if let Some(read) = live.read_from.read_under(at).filter(|_| same && views_held) {
let read = (&mut *kept, read);
if table.refresh_changed(read, (stage, interface), (maps, views), &mut reshape) {
counts.stage_table_read_in_part();
continue;
}
}
table.refresh_reading(kept, (stage, interface), (maps, views), &mut reshape);
}
let stamps = tables.map(|(_, table)| table.stamp());
@@ -172,6 +172,7 @@ pub(crate) struct Counters {
argument_samplers_taken: AtomicU64,
bind_views_worked_out: AtomicU64,
stage_tables_read: AtomicU64,
stage_tables_read_in_part: AtomicU64,
no_copy_lies_read: AtomicU64,
commands_noted_as_before: AtomicU64,
draws_settled: AtomicU64,
@@ -1251,6 +1252,13 @@ impl Counters {
self.stage_tables_read.fetch_add(1, Ordering::Relaxed);
}
/// One of those reads brought in only the slots calls changed since the table was read
/// (`ArgumentTable::refresh_changed`).
pub(crate) fn stage_table_read_in_part(&self) {
self.stage_tables_read_in_part
.fetch_add(1, Ordering::Relaxed);
}
/// A look at where a no-copy buffer's bytes lie, which takes its pages' lock
/// (`buffer::HostCell`).
pub(crate) fn no_copy_lie_read(&self) {
@@ -2922,6 +2930,9 @@ pub struct WorkCounts {
/// interface, with the same samplers' address-mode maps, while no no-copy buffer was rebound
/// or detached (`live_bind::ReadFrom`).
pub stage_tables_read: u64,
/// Those reads that brought in only the slots calls changed since the table was read, the
/// table keeping them (`ArgumentTable::refresh_changed`): every other slot is as it was read.
pub stage_tables_read_in_part: u64,
/// Looks at where a no-copy buffer's bytes lie, each of which takes its pages' lock
/// (`buffer::HostCell`): a draw's read of a table binding one takes one for the binding, its
/// base and device address read together (`argument_table::bound_buffer`), and a descriptor
@@ -3817,6 +3828,7 @@ impl Device {
argument_samplers_taken: counters.argument_samplers_taken.load(Ordering::Relaxed),
bind_views_worked_out: counters.bind_views_worked_out.load(Ordering::Relaxed),
stage_tables_read: counters.stage_tables_read.load(Ordering::Relaxed),
stage_tables_read_in_part: counters.stage_tables_read_in_part.load(Ordering::Relaxed),
no_copy_lies_read: counters.no_copy_lies_read.load(Ordering::Relaxed),
commands_noted_as_before: counters.commands_noted_as_before.load(Ordering::Relaxed),
draws_settled: counters.draws_settled.load(Ordering::Relaxed),
@@ -29,8 +29,9 @@
//! its own.
//! - **Stage tables.** A draw reads into its encoder's bind state only the stage tables a call
//! changed since a draw read them, through the same pipeline state's interface
//! (`WorkCounts::stage_tables_read`), and looks at where a no-copy buffer a table binds lies
//! once for its binding and once for its descriptor (`WorkCounts::no_copy_lies_read`).
//! (`WorkCounts::stage_tables_read`), of each only the slots its calls changed where it keeps
//! them (`WorkCounts::stage_tables_read_in_part`), and looks at where a no-copy buffer a table
//! binds lies once for its binding and once for its descriptor (`WorkCounts::no_copy_lies_read`).
//! - **Pipelines.** A draw of a pipeline state one of whose last draws found its `VkPipeline`
//! made, of the same variant and an equal key, finds that entry again without looking the key
//! up (`WorkCounts::graphics_pipelines_looked_up`), states and keys switched between included.
@@ -69,7 +70,7 @@ use metal2vulkan::library::{FunctionConstantValue, FunctionConstantValues};
use metal2vulkan::metal::state::DepthStencilDescriptor;
use metal2vulkan::metal::{
BlendFactor, CompareFunction, DataType, DepthClipMode, PixelFormat, PrimitiveType,
SamplerMinMagFilter, TextureUsage,
SamplerMinMagFilter, SamplerMipFilter, TextureUsage,
};
use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource};
use metal2vulkan_devtools::{engine_dir, llvm_assemble};
@@ -410,11 +411,124 @@ fn a_pass_that_draws_as_the_one_before_makes_no_render_pass() {
});
}
/// Draws each after a call of another setter form, its column's corners and its texel's color
/// set by the calls alone: a draw that reads its tables in part (`WorkCounts::
/// stage_tables_read_in_part`) brings in every slot such a call changed. The vertex slot's
/// corners come from a buffer of every column's at the column's offset (`set_vertex_buffer`,
/// `set_vertex_buffer_offset`, `set_vertex_buffers`) or from bytes (`set_vertex_bytes`); the color
/// from the texture bound (`set_fragment_texture`, `set_fragment_textures`) and from the level a
/// sampler's LOD clamps pick of a two-level texture, red then green (`set_fragment_sampler_state`,
/// `set_fragment_sampler_states` with clamps and without, the same state again). A slot a call
/// changed that the read left as it was would draw a column elsewhere, or in the other color.
#[test]
fn a_draw_reading_its_tables_in_part_brings_in_each_setters_slot() {
on_device(|device, _| {
let scene = Scene::new(device);
let corners: Vec<u8> = (0..SIDE).flat_map(column).collect();
let corners = buffer_with(device, &corners).unwrap();
let at = |c: u64| c * 16;
// Two levels: red, then green.
let mut levels = TextureDescriptor::texture_2d(
PixelFormat::RGBA8Unorm,
TEXTURE_SIDE,
TEXTURE_SIDE,
true,
);
levels.usage = TextureUsage::SHADER_READ;
levels.resource_options = ResourceOptions::shared();
let levels = device.new_texture(&levels).unwrap();
for (level, color) in [(0, RED), (1, GREEN), (2, GREEN)] {
let side = (TEXTURE_SIDE >> level).max(1);
let texels: Vec<u8> = (0..side * side).flat_map(|_| color).collect();
levels
.replace_region(
Region::new_2d(0, 0, side, side),
level,
0,
&texels,
4 * side,
0,
)
.unwrap();
}
let green = solid(device, PixelFormat::RGBA8Unorm, GREEN);
// Each samples one level: the target is twice the texture's side, so the draws' LOD is
// below 0 and the clamps decide it.
let sampler = |lod: f32| {
let mut descriptor = SamplerDescriptor::new();
descriptor.mip_filter = SamplerMipFilter::Nearest;
descriptor.lod_min_clamp = lod;
descriptor.lod_max_clamp = lod;
device.new_sampler_state(&descriptor).unwrap()
};
let (first, second) = (sampler(0.0), sampler(1.0));
let (command_buffer, mut encoder) = scene.encoder(device);
encoder.set_vertex_buffer(Some(&corners), at(0), 0).unwrap();
encoder.set_fragment_texture(Some(&levels), 0).unwrap();
encoder.set_fragment_sampler_state(Some(&first), 0).unwrap();
draw(&mut encoder);
let before = device.work_counts();
for c in 1..SIDE {
match c {
1 => {
encoder.set_vertex_buffer_offset(at(1), 0).unwrap();
encoder
.set_fragment_sampler_state(Some(&second), 0)
.unwrap();
}
2 => {
encoder.set_vertex_bytes(&column(2), 0).unwrap();
encoder.set_fragment_sampler_state(Some(&first), 0).unwrap();
}
3 => {
encoder
.set_vertex_buffers(&[Some(&corners)], &[at(3)], 0)
.unwrap();
encoder.set_fragment_textures(&[Some(&green)], 0).unwrap();
}
4 => {
encoder.set_vertex_buffer(Some(&corners), at(4), 0).unwrap();
encoder.set_fragment_texture(Some(&levels), 0).unwrap();
}
5 => {
encoder.set_vertex_buffer_offset(at(5), 0).unwrap();
let clamps: (&[f32], &[f32]) = (&[1.0], &[1.0]);
(encoder.set_fragment_sampler_states(&[Some(&first)], Some(clamps), 0))
.unwrap();
}
6 => {
encoder.set_vertex_buffer_offset(at(6), 0).unwrap();
(encoder.set_fragment_sampler_states(&[Some(&first)], None, 0)).unwrap();
}
_ => encoder.set_vertex_buffer_offset(at(c), 0).unwrap(),
}
draw(&mut encoder);
}
let after = device.work_counts();
encoder.end_encoding().unwrap();
let colors = [RED, GREEN, RED, GREEN, RED, GREEN, RED, RED];
let pixels = scene.pixels(&command_buffer);
for (i, &pixel) in pixels.iter().enumerate() {
let want = colors[i % SIDE as usize];
assert_eq!(pixel, want, "pixel {i}: {pixels:?}");
}
// Every later draw reads the vertex table in part; those that changed a fragment slot, the
// fragment table too.
let fragment_reads = 6;
assert_eq!(
grew(&before, &after, |c| c.stage_tables_read_in_part),
(SIDE - 1) + fragment_reads
);
});
}
/// Draws read into their encoder's kept bind state only the stage tables a call changed since a
/// draw read them (`WorkCounts::stage_tables_read`): each column's first draw the vertex table,
/// whose bytes it sets, and the fragment table too where it binds another texture; its second
/// draw, with no call before it, none; and every table at the draw after another pipeline state
/// is set, whose interface they are read through. Each second draw's uses are its first's, which
/// is set, whose interface they are read through. A table read through the same interface reads
/// only the slot its call changed (`WorkCounts::stage_tables_read_in_part`); the encoder's first
/// draw and the draw through another interface read theirs whole. Each second draw's uses are its first's, which
/// its encoder noted already (`WorkCounts::commands_noted_as_before`); so are each first draw's
/// the draw's before it, inline bytes being no use (they lie in the command buffer's upload
/// arena, which hazard tracking leaves alone), another pipeline state of the same stages too, but
@@ -431,8 +545,10 @@ fn draws_read_only_the_stage_tables_a_call_changed() {
encoder.set_fragment_texture(Some(&red), 0).unwrap();
let read = || device.work_counts().stage_tables_read;
let noted = || device.work_counts().commands_noted_as_before;
let parted = || device.work_counts().stage_tables_read_in_part;
let mut counts = Vec::new();
let mut notes = Vec::new();
let mut parts = Vec::new();
for c in 0..SIDE {
match c {
3 => encoder.set_fragment_texture(Some(&green), 0).unwrap(),
@@ -440,12 +556,14 @@ fn draws_read_only_the_stage_tables_a_call_changed() {
_ => {}
}
encoder.set_vertex_bytes(&column(c), 0).unwrap();
let (before, noted_before) = (read(), noted());
let (before, noted_before, parted_before) = (read(), noted(), parted());
draw(&mut encoder);
let (first, noted_first) = (read() - before, noted() - noted_before);
let parted_first = parted() - parted_before;
draw(&mut encoder);
counts.push((first, read() - before - first));
notes.push((noted_first, noted() - noted_before - noted_first));
parts.push((parted_first, parted() - parted_before - parted_first));
}
encoder.end_encoding().unwrap();
let as_before = [
@@ -471,6 +589,17 @@ fn draws_read_only_the_stage_tables_a_call_changed() {
(1, 0),
];
assert_eq!(counts, reads, "{counts:?}");
let in_part = [
(0, 0),
(1, 0),
(1, 0),
(2, 0),
(1, 0),
(0, 0),
(1, 0),
(1, 0),
];
assert_eq!(parts, in_part, "{parts:?}");
let pixels = scene.pixels(&command_buffer);
for (i, &pixel) in pixels.iter().enumerate() {
let want = match i as u64 % SIDE >= 3 {