diff --git a/crates/metal2vulkan/src/cache/codec.rs b/crates/metal2vulkan/src/cache/codec.rs index 157b81b47..8beea6163 100644 --- a/crates/metal2vulkan/src/cache/codec.rs +++ b/crates/metal2vulkan/src/cache/codec.rs @@ -1140,8 +1140,8 @@ codec_struct! { stage, slots, threadgroup, push, descriptors, spec, needs_pointer_translation, needs_handle_translation, io, tessellation, writes_memory, mesh_records, mesh_corners, emulated_payload, - payload, reaches_command_buffers, command_writes, writes_textures, numbered_samplers, - own_pixel_textures, + payload, reaches_command_buffers, command_writes, writes_textures, + reads_unbound_resources, writes_unbound_resources, numbered_samplers, own_pixel_textures, snapshot_textures, snapshot_refusals, level_reads, private_bytes, sampler_arrays, } SamplerArray { slot, samplers } @@ -1400,8 +1400,8 @@ codec_struct! { } PipelineInterface { slots, threadgroup, needs_pointer_translation, needs_handle_translation, push, - reaches_command_buffers, command_writes, texture_writing_stages, numbered_samplers, - stage_in, + reaches_command_buffers, command_writes, texture_writing_stages, + reads_unbound_resources, writes_unbound_resources, numbered_samplers, stage_in, } PipelineLayout { sets, push_constants, push_descriptor_eligible } DescriptorSetLayout { set, bindings, flags } diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 7aed45e2c..164b73466 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -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 = 2143; +pub const SEMANTICS_VERSION: u32 = 2144; /// 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 = 2143; /// 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 = 525; +pub const ARTIFACT_FORMAT_VERSION: u32 = 526; /// 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 diff --git a/crates/metal2vulkan/src/pipeline/api_tests.rs b/crates/metal2vulkan/src/pipeline/api_tests.rs index 93b31ff67..7777cd39b 100644 --- a/crates/metal2vulkan/src/pipeline/api_tests.rs +++ b/crates/metal2vulkan/src/pipeline/api_tests.rs @@ -767,6 +767,8 @@ mod serde_round_trips { kinds: CommandWrites::RENDER_COMMANDS, }, texture_writing_stages: vec![Stage::Vertex, Stage::Fragment], + reads_unbound_resources: true, + writes_unbound_resources: false, numbered_samplers: vec![ ( Stage::Fragment, diff --git a/crates/metal2vulkan/src/pipeline/compile.rs b/crates/metal2vulkan/src/pipeline/compile.rs index db5d7d471..d91aa5d87 100644 --- a/crates/metal2vulkan/src/pipeline/compile.rs +++ b/crates/metal2vulkan/src/pipeline/compile.rs @@ -22,6 +22,7 @@ mod partition; mod stage_bound; #[cfg(test)] mod tests; +mod unbound; use std::collections::{BTreeMap, BTreeSet, VecDeque}; use std::panic::{catch_unwind, AssertUnwindSafe}; @@ -2669,6 +2670,7 @@ struct Planned { before: reflection::UnspecializedReads, plan: Plan, kernel: KernelFacts, + unbound: unbound::Unbound, } /// What [`specialize_one`] makes: the AIR hash, the entry name, the specialized entry, and what @@ -2789,8 +2791,8 @@ fn plan_one( } /// What [`plan_one`] reads of a request before it selects: the ordered entry, what its code read -/// before specialization, the inputs it lowers under, its key, its memory plan and the partition -/// it observes. A plan made again past the stage bound (`stage_bound`) selects from it again, +/// before specialization, the inputs it lowers under, its key, its memory plan, the partition +/// it observes, and what it reads and writes through anything but its bound slots. A plan made again past the stage bound (`stage_bound`) selects from it again, /// without decoding, specializing, ordering or analyzing the entry again. struct Analyzed { key: FunctionCompileKey, @@ -2799,6 +2801,7 @@ struct Analyzed { inputs: LowerInputs, memory: crate::memory::plan::MemoryPlan, observed: Partition, + unbound: unbound::Unbound, } impl Analyzed { @@ -2843,6 +2846,7 @@ impl Analyzed { before: self.before, plan, kernel, + unbound: self.unbound, } } } @@ -2894,6 +2898,7 @@ fn analyze_one(r: &Request<'_>, p: &DeviceProfile, m: &mut Meter) -> Result, p: &DeviceProfile, m: &mut Meter) -> Result( before, plan, kernel, + unbound, }, crate::lower::emit::Emitted { mut module, merged }, ) = stage_bound::emit(r, p, (word_cap, bounds), m)?; @@ -3139,6 +3146,7 @@ fn compile_bounded( (reaches_command_buffers, command_writes), (writes_textures, numbered_samplers), (own_pixel_textures, snapshot_textures, level_reads), + unbound, ); let mut requirements = module.requirements.clone(); // Pairs only the device's simdgroup lockstep orders. @@ -3436,8 +3444,9 @@ fn emitted_census( /// store's atomics read the word they modify. A buffer slot at an index of `function_tables` holds /// a visible-function table read as its words. `reaches_command_buffers` is the canonical entry's /// `Entry::may_encode_indirect_commands`, `command_writes` its `Entry::command_writes`, -/// `writes_textures` its `Entry::may_write_textures`, and -/// `numbered_samplers` the samplers a pipeline state numbers for it (`numbered::samplers`). +/// `writes_textures` its `Entry::may_write_textures`, +/// `numbered_samplers` the samplers a pipeline state numbers for it (`numbered::samplers`), and +/// `unbound` what it reads and writes through anything but its bound slots (`unbound`). fn stage_interface( plan: &Plan, symbols: crate::pipeline::link::contract::StageSymbols, @@ -3451,6 +3460,7 @@ fn stage_interface( crate::spirv::requirements::Judged, Vec, ), + unbound: unbound::Unbound, ) -> StageInterface { use crate::pipeline::interface::{BufferKind, BufferSlot}; use crate::pipeline::sym::PushField; @@ -3513,6 +3523,8 @@ fn stage_interface( reaches_command_buffers, command_writes, writes_textures, + reads_unbound_resources: unbound.reads, + writes_unbound_resources: unbound.writes, numbered_samplers, own_pixel_textures, snapshot_textures: snapshots.slots, diff --git a/crates/metal2vulkan/src/pipeline/compile/tests.rs b/crates/metal2vulkan/src/pipeline/compile/tests.rs index 926ae08f5..59793698e 100644 --- a/crates/metal2vulkan/src/pipeline/compile/tests.rs +++ b/crates/metal2vulkan/src/pipeline/compile/tests.rs @@ -3021,6 +3021,56 @@ fn the_interface_states_whether_the_function_writes_textures() { } } +/// The interface states whether the function reads or writes a resource through anything but +/// its bound slots, from its AIR and memory plan. Through bound slots alone: textures selected +/// between two arguments or between an argument and null, a texture array argument indexed at +/// run time (`handles`), and atomics on a bound buffer (`rd_touch`, and a fragment function's +/// `a3_rog_buffer_rmw`). Through an argument buffer's texture: a read (`argument_buffer_read`) +/// and a write (`argument_buffer_array_write`), the argument buffer's own words being a bound +/// slot. Through an address the function loads from a buffer: loads and stores +/// (`ob2_loaded_pointer`) and an atomic, which reads and writes (`rd_tally_fragment`). A +/// standalone kernel's pipeline states its function's. +#[test] +fn the_interface_states_what_the_function_reaches_beyond_its_bound_slots() { + let p = + crate::pipeline::testing::profile("lavapipe", DevicePolicy::default()).expect("profile"); + for (stem, entry, reads, writes) in [ + ("handles", "select_read", false, false), + ("handles", "select_null_write", false, false), + ("handles", "array_read", false, false), + ("resident_draws", "rd_touch", false, false), + ("a3_rog_buffer_rmw", "a3_rog_buffer_rmw", false, false), + ("handles", "argument_buffer_read", true, false), + ("handles", "argument_buffer_array_write", false, true), + ("ob2_loaded_pointer", "ob2_loaded_pointer", true, true), + ("resident_draws", "rd_tally_fragment", true, true), + ] { + let Some(bc) = fixture(stem) else { + return; + }; + let a = crate::pipeline::testing::compile(&bc, entry, &p) + .unwrap_or_else(|e| panic!("{entry}: {e}")); + let facts = ( + a.interface.reads_unbound_resources, + a.interface.writes_unbound_resources, + ); + assert_eq!(facts, (reads, writes), "{entry}"); + if a.interface.stage == crate::pipeline::sym::Stage::Kernel { + let linked = crate::pipeline::link::link( + &[&*a], + &crate::pipeline::link::LinkInputs::standalone(), + &p, + ) + .unwrap_or_else(|e| panic!("{entry}: link: {e}")); + let linked_facts = ( + linked.interface.reads_unbound_resources, + linked.interface.writes_unbound_resources, + ); + assert_eq!(linked_facts, (reads, writes), "{entry}: pipeline"); + } + } +} + /// A render pipeline whose fragment function reads `[[sample_id]]` and `[[point_coord]]` /// (`stage_io_fragment_point`) compiles at one sample and at four, where Vulkan's sample shading /// may move the point coordinate to the sample while Metal keeps it at the pixel's: there its diff --git a/crates/metal2vulkan/src/pipeline/compile/unbound.rs b/crates/metal2vulkan/src/pipeline/compile/unbound.rs new file mode 100644 index 000000000..587523d57 --- /dev/null +++ b/crates/metal2vulkan/src/pipeline/compile/unbound.rs @@ -0,0 +1,158 @@ +//! What a function reads and writes through anything but its bound slots, decided from the +//! specialized entry's AIR and its memory plan: `StageInterface::reads_unbound_resources` and +//! `StageInterface::writes_unbound_resources`. +//! +//! A bound slot is what the encoder sets: a buffer, texture or sampler argument, an element of a +//! buffer-table argument, and the words of an argument buffer bound at a buffer index. An access +//! is through something else where the pointer or texture it goes through may come from memory or +//! an integer (a root set holding `Root::Dynamic`: an argument buffer's buffers and textures, an +//! address stored in a buffer, a resource ID, `inttoptr`), or from an intrinsic call +//! (`Root::Call`). Metal requires such resources to be declared with `useResource` or `useHeap`; +//! the runtime orders them by these two facts. The accesses are: +//! +//! - loads, stores and atomics of device and constant memory, and the coherent, simdgroup-matrix, +//! asynchronous-copy and `llvm.mem*` forms of them; +//! - texture operations that touch texels: samples, gathers, reads and block reads (reads), +//! writes and imageblock slices (writes), atomics (both). Queries, null tests and fences touch +//! no texel. +//! +//! Some operations are both, whatever their operands: an indirect command buffer's operations +//! (its records are only reached through an argument buffer), ray tracing, and a call the +//! entry cannot see into (a visible function's, an unknown intrinsic). + +use crate::air; +use crate::air::intrinsics::{ + AccessKind, AirIntrinsic, AtomicOp, LlvmIntrinsic, SimdMatrix, TexOp, +}; +use crate::air::ir::{AddrSpace, Callee, InstKind, Type, Value}; +use crate::memory::plan::MemoryPlan; +use crate::memory::provenance::{HandleClass, Repr, Root}; + +/// What a function reads and writes through anything but its bound slots (see the module). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) struct Unbound { + pub(super) reads: bool, + pub(super) writes: bool, +} + +impl Unbound { + const BOTH: Unbound = Unbound { + reads: true, + writes: true, + }; + + fn add(&mut self, reads: bool, writes: bool) { + self.reads |= reads; + self.writes |= writes; + } +} + +/// What entry `e` reads and writes through anything but its bound slots (see the module). +pub(super) fn unbound(e: &air::Entry, memory: &MemoryPlan) -> Unbound { + let Some(body) = e.module.func(e.func).and_then(|f| f.body.as_ref()) else { + return Unbound::default(); + }; + let space = |v: Value| match e + .module + .value_ty(e.func, v) + .map(|t| e.module.types().get(t)) + { + Some(Some(Type::Ptr { space })) => Some(*space), + _ => None, + }; + let buffer = |v: Value| matches!(space(v), Some(AddrSpace::Device | AddrSpace::Constant)); + let texture = |v: Value| { + matches!( + memory.repr(v), + Some(Repr::Handle { + class: HandleClass::Texture, + .. + }) + ) + }; + // A pointer or handle that may come from memory, an integer or an intrinsic call. + let loaded = |v: Value| { + memory + .roots_of(v) + .is_some_and(|r| r.iter().any(|r| matches!(r, Root::Dynamic | Root::Call(_)))) + }; + let through = |v: Value| buffer(v) && loaded(v); + let mut out = Unbound::default(); + for inst in body.insts.values() { + match &inst.kind { + InstKind::Load { ptr, .. } => out.add(through(*ptr), false), + InstKind::Store { ptr, .. } => out.add(false, through(*ptr)), + InstKind::AtomicRmw { ptr, .. } | InstKind::CmpXchg { ptr, .. } => { + let t = through(*ptr); + out.add(t, t); + } + InstKind::Call(call) => { + let args = &call.args; + let any = |f: &dyn Fn(Value) -> bool| args.iter().any(|a| f(*a)); + let buffers = any(&through); + match &call.callee { + Callee::Air { op, .. } => match op { + AirIntrinsic::Atomic(a) => { + out.add(buffers, buffers && a.op != AtomicOp::Load) + } + AirIntrinsic::Coherent(c) => { + let store = c.kind == AccessKind::Store; + out.add(buffers && !store, buffers && store); + } + AirIntrinsic::SimdMatrix(m) => { + let store = matches!( + m, + SimdMatrix::Store8x8 { .. } | SimdMatrix::Store8x8Legacy { .. } + ); + out.add(buffers && !store, buffers && store); + } + AirIntrinsic::Texture(t) => { + let handle = any(&|a| texture(a) && loaded(a)); + let (reads, writes) = match t.op { + TexOp::Write | TexOp::WriteImageblockSlice => (false, true), + TexOp::Atomic(_) => (true, true), + TexOp::Query(_) + | TexOp::IsNull + | TexOp::GetNull + | TexOp::Fence + | TexOp::CalculateLod { .. } => (false, false), + TexOp::Sample { .. } + | TexOp::SampleGrad { .. } + | TexOp::Gather { .. } + | TexOp::Read + | TexOp::BlockRead => (true, false), + }; + out.add(handle && reads, handle && writes); + } + AirIntrinsic::IndirectCommand(_) + | AirIntrinsic::AccelerationStructure(_) + | AirIntrinsic::Intersect(_) => out = Unbound::BOTH, + // An asynchronous copy writes one side and reads the other; any other + // intrinsic given such a pointer may only read through it. + AirIntrinsic::AsyncCopy(_) => out.add(buffers, buffers), + _ => out.add(buffers, false), + }, + Callee::Llvm { op, .. } => match op { + LlvmIntrinsic::Memcpy { .. } | LlvmIntrinsic::Memmove { .. } => { + let at = |i: usize| args.get(i).is_some_and(|a| through(*a)); + out.add(at(1), at(0)); + } + LlvmIntrinsic::Memset { .. } => { + out.add(false, args.first().is_some_and(|a| through(*a))) + } + _ => out.add(buffers, buffers), + }, + Callee::Direct(_) + | Callee::Indirect { .. } + | Callee::UnknownIntrinsic(_) + | Callee::Unbound { .. } => out = Unbound::BOTH, + } + } + _ => {} + } + if out == Unbound::BOTH { + break; + } + } + out +} diff --git a/crates/metal2vulkan/src/pipeline/interface.rs b/crates/metal2vulkan/src/pipeline/interface.rs index 3a5174684..a23962643 100644 --- a/crates/metal2vulkan/src/pipeline/interface.rs +++ b/crates/metal2vulkan/src/pipeline/interface.rs @@ -45,6 +45,16 @@ pub struct PipelineInterface { /// pipeline's stage order: a stage not listed writes no texture, which is proven. #[cfg_attr(feature = "serde", serde(default))] pub texture_writing_stages: Vec, + /// Some stage's function may read a resource through something other than its bound slots + /// (`StageInterface::reads_unbound_resources`); `false` is proven of every function of the + /// pipeline. + #[cfg_attr(feature = "serde", serde(default))] + pub reads_unbound_resources: bool, + /// Some stage's function may write a resource through something other than its bound slots + /// (`StageInterface::writes_unbound_resources`); `false` is proven of every function of the + /// pipeline. + #[cfg_attr(feature = "serde", serde(default))] + pub writes_unbound_resources: bool, /// The samplers a pipeline state numbers for each of its Metal functions /// (`StageInterface::numbered_samplers`, [`NumberedSampler`]), each function's in Metal's /// order, the functions in the pipeline's stage order: what the runtime gives sampler @@ -395,6 +405,22 @@ pub struct StageInterface { /// buffer a texture views are not texture writes. #[cfg_attr(feature = "serde", serde(default))] pub writes_textures: bool, + /// The function may read a resource through something other than its bound slots, of the + /// entry its function constants specialized; `false` only where it provably reads none so. + /// A bound slot is a buffer, texture or sampler argument, an element of a buffer-table + /// argument, or the words of an argument buffer bound at a buffer index. A read is through + /// something else where its pointer or texture may come from memory or an integer (an + /// argument buffer's buffers and textures, an address stored in a buffer, a resource ID), or + /// from an intrinsic call; an indirect command buffer's operations, ray tracing, and a call + /// the entry cannot see into count too. Metal requires such resources to be declared with + /// `useResource` or `useHeap`. Texture queries and null tests read no texel. + #[cfg_attr(feature = "serde", serde(default))] + pub reads_unbound_resources: bool, + /// The function may write a resource through something other than its bound slots, as + /// [`reads_unbound_resources`](Self::reads_unbound_resources) states for reads: a store, an + /// atomic, a texture write or atomic, or a copy into one. `false` is proven. + #[cfg_attr(feature = "serde", serde(default))] + pub writes_unbound_resources: bool, /// The samplers a pipeline state of the function numbers for it, of the entry its function /// constants specialized, in Metal's order ([`NumberedSampler`]): the runtime gives each a /// sampler resource ID as Metal's pipeline creation does. diff --git a/crates/metal2vulkan/src/pipeline/link.rs b/crates/metal2vulkan/src/pipeline/link.rs index 9060e3adb..f0711cc54 100644 --- a/crates/metal2vulkan/src/pipeline/link.rs +++ b/crates/metal2vulkan/src/pipeline/link.rs @@ -1646,6 +1646,8 @@ fn pipeline_interface(ifaces: &[&StageInterface]) -> PipelineInterface { if i.writes_textures { out.texture_writing_stages.push(i.stage); } + out.reads_unbound_resources |= i.reads_unbound_resources; + out.writes_unbound_resources |= i.writes_unbound_resources; out.numbered_samplers .push((i.stage, i.numbered_samplers.clone())); out.push.push(i.push.clone()); diff --git a/crates/metal2vulkan/src/pipeline/link/tests.rs b/crates/metal2vulkan/src/pipeline/link/tests.rs index b80522ad0..679c0dd04 100644 --- a/crates/metal2vulkan/src/pipeline/link/tests.rs +++ b/crates/metal2vulkan/src/pipeline/link/tests.rs @@ -136,6 +136,8 @@ pub(super) fn iface( reaches_command_buffers: false, command_writes: Default::default(), writes_textures: false, + reads_unbound_resources: false, + writes_unbound_resources: false, numbered_samplers: Vec::new(), own_pixel_textures: Vec::new(), snapshot_textures: Vec::new(), diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 56ca31d4b..d0d2f1487 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -5436,10 +5436,12 @@ field metal2vulkan::pipeline::PipelineInterface.needs_pointer_translation pub ne field metal2vulkan::pipeline::PipelineInterface.numbered_samplers pub numbered_samplers: Vec<(Stage, Vec)> field metal2vulkan::pipeline::PipelineInterface.push pub push: Vec field metal2vulkan::pipeline::PipelineInterface.reaches_command_buffers pub reaches_command_buffers: bool +field metal2vulkan::pipeline::PipelineInterface.reads_unbound_resources pub reads_unbound_resources: bool field metal2vulkan::pipeline::PipelineInterface.slots pub slots: BTreeMap field metal2vulkan::pipeline::PipelineInterface.stage_in pub stage_in: Vec field metal2vulkan::pipeline::PipelineInterface.texture_writing_stages pub texture_writing_stages: Vec field metal2vulkan::pipeline::PipelineInterface.threadgroup pub threadgroup: Vec +field metal2vulkan::pipeline::PipelineInterface.writes_unbound_resources pub writes_unbound_resources: bool field metal2vulkan::pipeline::PipelineLayout.push_constants pub push_constants: Vec field metal2vulkan::pipeline::PipelineLayout.push_descriptor_eligible pub push_descriptor_eligible: bool field metal2vulkan::pipeline::PipelineLayout.sets pub sets: Vec diff --git a/docs/API.md b/docs/API.md index 2d3fc400c..4c630eb45 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1622,6 +1622,13 @@ for dependency in &pipeline.dependencies { records they reach: the indirect-command operations they may call, and the primitive types their draws may pass (a draw's constant type, or all five where it is not a constant). A clear bit is proven. +- `interface.reads_unbound_resources` and `interface.writes_unbound_resources` say, provably, + whether a pipeline's functions may read or write a resource through anything but their bound + slots: through a pointer or texture they load from memory or make from an integer (an argument + buffer's resources, an address stored in a buffer, a resource ID), an indirect command buffer, + ray tracing, or a call the function cannot see into. Metal requires such resources to be + declared with `useResource` or `useHeap`. With each slot's `access`, they are what a compute + encoder needs to place a barrier only on a hazard. ### Plans