diff --git a/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs b/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs index b61cb4323..fa546ea9b 100644 --- a/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs +++ b/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs @@ -15,6 +15,7 @@ pub(super) mod indices; pub(super) mod places; mod render; pub(super) mod second; +pub(super) mod unbound; pub(super) mod unwritten; use super::args::{arg, data, metal, option_sets, refuse, uint, variant, Fields}; @@ -222,6 +223,8 @@ pub struct NewRuntime { skips: Skips, /// The frame and the stream position of the call being played (`Backend::locate`). at: (u64, u64), + /// The draws and dispatches whose pipeline state reads a buffer argument nothing is bound to. + unbound: unbound::Unbound, substitutes: Substitutes, /// Each open encoder's command buffer. owners: HashMap, @@ -498,6 +501,7 @@ impl NewRuntime { completed: 0, skips: Skips::default(), at: (0, 0), + unbound: unbound::Unbound::default(), substitutes: Substitutes::default(), owners: HashMap::new(), managed: None, @@ -1150,11 +1154,13 @@ impl NewRuntime { let d = rt::ComputePipelineDescriptor::new(rt::StageSource::Function( function.descriptor, )); + self.unbound.compute(call.result, &d); let state = self.timed_state(call, &d, function.kernel)?; unaddressed(Object::ComputePipeline(state)) } "newComputePipelineStateWithDescriptor:options:reflection:error:" => { let (d, kernel) = self.compute_pipeline(call)?; + self.unbound.compute(call.result, &d); let state = self.timed_state(call, &d, kernel)?; unaddressed(Object::ComputePipeline(state)) } @@ -1602,6 +1608,7 @@ impl Backend for NewRuntime { // Skipped encoders too: what the program's GPU passes reach is the stream's. let compute = matches!(self.objects.get(&call.receiver), Some(Object::Compute(_))); self.unwritten.encoded(call, command_buffer, compute); + self.unbound.encoded(call, self.at.0, self.at.1); let mut named = Vec::new(); objects_named(&call.args, &mut named); named.retain(|id| matches!(self.objects.get(id), Some(Object::Buffer(_, Some(_))))); @@ -1942,6 +1949,7 @@ impl Backend for NewRuntime { ("skipped_calls", self.skips.calls), ("skipped_resource_ids", self.skips.resource_ids), ("gap_pipeline_ids", self.unanswered_pipeline_ids), + ("unbound_buffer_reads", self.unbound.count()), ]) } @@ -2025,6 +2033,7 @@ impl Backend for NewRuntime { lines.push(self.asides.line()); lines.push(self.unwritten.line()); lines.push(self.indices.line()); + lines.push(self.unbound.line()); lines } diff --git a/crates/metal2vulkan-validation/src/replay/new_runtime/render.rs b/crates/metal2vulkan-validation/src/replay/new_runtime/render.rs index 6b4f6adba..deb2bba08 100644 --- a/crates/metal2vulkan-validation/src/replay/new_runtime/render.rs +++ b/crates/metal2vulkan-validation/src/replay/new_runtime/render.rs @@ -127,6 +127,7 @@ impl NewRuntime { function.descriptor.with_linked(linked), ))) })?; + self.unbound.render(call.result, &descriptor); let made = self.numbered(|device, ids| { device.new_render_pipeline_state(&descriptor, |samplers| ids(samplers)) }); diff --git a/crates/metal2vulkan-validation/src/replay/new_runtime/unbound.rs b/crates/metal2vulkan-validation/src/replay/new_runtime/unbound.rs new file mode 100644 index 000000000..fd8b3e49d --- /dev/null +++ b/crates/metal2vulkan-validation/src/replay/new_runtime/unbound.rs @@ -0,0 +1,208 @@ +//! The draws and dispatches whose pipeline state reads a buffer argument that nothing is bound +//! to when they run: what Metal leaves undefined, counted, never stood in for. A state's reads +//! are the buffer bindings its reflection lists as used (`isUsed`, the translator's +//! [`ComputePipelineDescriptor::reflection`](rt::ComputePipelineDescriptor::reflection) and +//! [`RenderPipelineDescriptor::reflection`](rt::RenderPipelineDescriptor::reflection)); an +//! encoder's bound indices are those its `setBuffer`, `setBuffers` and `setBytes` calls of each +//! stage set to something since it was made, a `nil` buffer unsetting one, until its +//! `endEncoding`. Every call of an +//! encoder counts, a skipped object's included: what the program's GPU passes reach is the +//! stream's. + +use super::super::args::range; +use super::super::stream::Call; +use super::super::value::Value; +use metal2vulkan_rt as rt; +use std::collections::{BTreeSet, HashMap}; + +/// The stages a buffer argument is read in. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub(in crate::replay) enum Stage { + Kernel, + Vertex, + Fragment, +} + +/// The first draws and dispatches with a buffer argument unbound that the line names. +const FIRST: usize = 8; + +/// One draw or dispatch that reads a buffer argument unbound: its frame and stream position, its +/// pipeline state, and the first argument unbound. +#[derive(Clone, Copy, Debug)] +struct Read { + frame: u64, + position: u64, + state: u64, + stage: Stage, + index: u32, +} + +#[derive(Default)] +pub(in crate::replay) struct Unbound { + /// Each pipeline state's used buffer arguments. + reads: HashMap>, + /// The pipeline states the translator gave no reflection of, which nothing is counted for. + unreflected: u64, + /// Each encoder's pipeline state and bound buffer indices. + encoders: HashMap, BTreeSet<(Stage, u32)>)>, + /// The draws and dispatches that read a buffer argument unbound, and the states they ran. + count: u64, + states: BTreeSet, + first: Vec, +} + +/// A buffer binding of a reflection's that the function uses. +fn used(bindings: &[metal2vulkan::reflection::Binding], stage: Stage) -> Vec<(Stage, u32)> { + (bindings.iter()) + .filter(|b| b.is_used() && b.buffer().is_some()) + .map(|b| (stage, b.index())) + .collect() +} + +impl Unbound { + /// Compute pipeline state `state` of `descriptor` made. + pub(super) fn compute(&mut self, state: u64, descriptor: &rt::ComputePipelineDescriptor) { + match descriptor.reflection(&metal2vulkan::Budget::default()) { + Ok(reflection) => { + let reads = used(reflection.bindings(), Stage::Kernel); + self.reads.insert(state, reads.into_iter().collect()); + } + Err(_) => self.unreflected += 1, + } + } + + /// Render pipeline state `state` of `descriptor` made. + pub(super) fn render(&mut self, state: u64, descriptor: &rt::RenderPipelineDescriptor) { + match descriptor.reflection(&metal2vulkan::Budget::default()) { + Ok(reflection) => { + let mut reads = used(reflection.vertex_bindings(), Stage::Vertex); + reads.extend(used(reflection.fragment_bindings(), Stage::Fragment)); + self.reads.insert(state, reads.into_iter().collect()); + } + Err(_) => self.unreflected += 1, + } + } + + /// Pipeline state `state` made, reading `reads`: what [`compute`](Self::compute) and + /// [`render`](Self::render) find in a reflection. + #[cfg(test)] + pub(in crate::replay) fn made(&mut self, state: u64, reads: &[(Stage, u32)]) { + self.reads.insert(state, reads.iter().copied().collect()); + } + + /// A call of encoder `call.receiver`, at `frame` and stream `position`. + pub(in crate::replay) fn encoded(&mut self, call: &Call, frame: u64, position: u64) { + let selector = &*call.selector; + if selector == "endEncoding" { + self.encoders.remove(&call.receiver); + return; + } + let stage = match selector { + s if s.starts_with("setVertex") => Stage::Vertex, + s if s.starts_with("setFragment") => Stage::Fragment, + _ => Stage::Kernel, + }; + let encoder = self.encoders.entry(call.receiver).or_default(); + let set = |bound: &mut BTreeSet<(Stage, u32)>, buffer: Option<&Value>, at: u64| { + let Ok(at) = u32::try_from(at) else { + return; + }; + match buffer { + Some(Value::Nil | Value::Object(0)) => bound.remove(&(stage, at)), + _ => bound.insert((stage, at)), + }; + }; + let uint = |at: usize| match call.args.get(at) { + Some(Value::Uint(v)) => Some(*v), + _ => None, + }; + match selector { + "setComputePipelineState:" | "setRenderPipelineState:" => { + encoder.0 = match call.args.first() { + Some(Value::Object(state)) if *state != 0 => Some(*state), + _ => None, + }; + } + "setBuffer:offset:atIndex:" + | "setVertexBuffer:offset:atIndex:" + | "setFragmentBuffer:offset:atIndex:" => { + if let Some(at) = uint(2) { + set(&mut encoder.1, call.args.first(), at); + } + } + "setBytes:length:atIndex:" + | "setVertexBytes:length:atIndex:" + | "setFragmentBytes:length:atIndex:" => { + if let Some(at) = uint(2) { + set(&mut encoder.1, None, at); + } + } + "setBuffers:offsets:withRange:" + | "setVertexBuffers:offsets:withRange:" + | "setFragmentBuffers:offsets:withRange:" => { + let (Some(Value::List(buffers)), Some(span)) = + (call.args.first(), call.args.get(2)) + else { + return; + }; + let Ok(span) = range(call, span) else { + return; + }; + for (at, buffer) in span.zip(buffers) { + set(&mut encoder.1, Some(buffer), at); + } + } + s if s.starts_with("draw") || s.starts_with("dispatch") => { + let Some(state) = encoder.0 else { + return; + }; + let Some(reads) = self.reads.get(&state) else { + return; + }; + let Some(&(stage, index)) = reads.difference(&encoder.1).next() else { + return; + }; + self.count += 1; + self.states.insert(state); + if self.first.len() < FIRST { + self.first.push(Read { + frame, + position, + state, + stage, + index, + }); + } + } + _ => {} + } + } + + /// The draws and dispatches that read a buffer argument unbound so far. + pub(super) fn count(&self) -> u64 { + self.count + } + + /// The `unbound buffer reads N: ...` line. + pub(in crate::replay) fn line(&self) -> String { + let first: Vec = (self.first.iter()) + .map(|r| { + format!( + "position {} frame {} state #{} {:?} buffer {}", + r.position, r.frame, r.state, r.stage, r.index + ) + }) + .collect(); + format!( + "unbound buffer reads {}: draws and dispatches whose pipeline state reads a buffer \ + argument nothing is bound to, of {} states; {} states unreflected; first: {}", + self.count, + self.states.len(), + self.unreflected, + match first.is_empty() { + true => "none".to_owned(), + false => first.join(", "), + } + ) + } +} diff --git a/crates/metal2vulkan-validation/src/replay/tests.rs b/crates/metal2vulkan-validation/src/replay/tests.rs index cdcbf2d73..aecae36e4 100644 --- a/crates/metal2vulkan-validation/src/replay/tests.rs +++ b/crates/metal2vulkan-validation/src/replay/tests.rs @@ -5,6 +5,7 @@ use super::addresses::AddressMap; use super::new_runtime::indices::Indices; use super::new_runtime::places::Waiting; use super::new_runtime::second::merge; +use super::new_runtime::unbound::{Stage, Unbound}; use super::new_runtime::unwritten::Unwritten; use super::player::{ Backend, Counters, Counts, IdDiffers, Made, PlayError, Player, PrivateBytes, Relaid, Report, @@ -1469,6 +1470,65 @@ fn a_frame_end_reports_the_gauges_as_they_stand() { assert!(ends[1].ends_with(" live calls=3"), "{lines:?}"); } +/// A draw or dispatch is counted where its pipeline state reads a buffer argument its encoder +/// set nothing at, or set to `nil`, since the encoder was made; bytes bind one, and a state with +/// no reflection is counted for nothing. +#[test] +fn a_draw_reading_a_buffer_argument_nothing_is_bound_to_is_counted() { + let call = |selector: &str, receiver: u64, args: Vec| Call { + selector: selector.into(), + receiver, + result: 0, + args, + answers: Vec::new(), + }; + let draw = |encoder: u64| call("drawPrimitives:vertexStart:vertexCount:", encoder, vec![]); + let mut unbound = Unbound::default(); + unbound.made(7, &[(Stage::Vertex, 0), (Stage::Fragment, 1)]); + let calls = [ + call("setRenderPipelineState:", 9, vec![Value::Object(7)]), + call( + "setVertexBuffer:offset:atIndex:", + 9, + vec![Value::Object(3), Value::Uint(0), Value::Uint(0)], + ), + // Fragment buffer 1 unbound: counted. + draw(9), + call( + "setFragmentBytes:length:atIndex:", + 9, + vec![Value::Bytes(vec![0; 4]), Value::Uint(4), Value::Uint(1)], + ), + draw(9), + // Unset again: counted. + call( + "setFragmentBuffer:offset:atIndex:", + 9, + vec![Value::Nil, Value::Uint(0), Value::Uint(1)], + ), + draw(9), + call("endEncoding", 9, vec![]), + // A state with no reflection: nothing counted. + call("setComputePipelineState:", 10, vec![Value::Object(8)]), + call("dispatchThreads:threadsPerThreadgroup:", 10, vec![]), + ]; + for (position, call) in (0..).zip(&calls) { + unbound.encoded(call, 4, position); + } + let line = unbound.line(); + assert!( + line.starts_with("unbound buffer reads 2: ") && line.contains(" of 1 states; "), + "{line}" + ); + assert!( + line.ends_with( + "first: position 2 frame 4 state #7 Fragment buffer 1, \ + position 6 frame 4 state #7 Fragment buffer 1" + ), + "{line}" + ); +} + /// The new runtime's `unwritten` line counts, once, a Shared buffer a committed dispatch read /// before anything recorded reached its bytes: not one written through its block, one a blit /// names, one written before the commit, one an earlier commit's dispatch bound or one released diff --git a/docs/REPLAY-STREAM.md b/docs/REPLAY-STREAM.md index 3498ef80b..c680658d8 100644 --- a/docs/REPLAY-STREAM.md +++ b/docs/REPLAY-STREAM.md @@ -569,7 +569,13 @@ counted from 0), completes the work committed so far, reports as at the stream's the runtime back a block or heap of the stream at its release (`release_block`), and gives textures and sampler states indices from the whole of each index class (section 5): its `indices named N: ...` line counts the objects placed at the index the stream named, those - whose named index the runtime refused, and the indices the program reserved. Its readback serves + whose named index the runtime refused, and the indices the program reserved. Its + `unbound buffer reads N: ...` line counts the draws and dispatches whose pipeline state reads a + buffer argument (one its reflection lists as used) that its encoder bound nothing to: no + `setBuffer`, `setBuffers` or `setBytes` of that stage at that index since the encoder was made, + or a `nil` buffer there; with the states they ran, the states the translator gave no reflection + of, and the first eight by stream position and frame. `unbound_buffer_reads` counts them per + frame. Metal leaves such a read undefined; the player plays it as the stream has it. Its readback serves Shared and Managed buffers only; a check of anything else is a refusal. The runtime gives a compute or render pipeline state no `gpuResourceID`, so each one the program saw is reported on an `id` line as `none` and counted (`gap_pipeline_ids`); each skipped object's the program saw