diff --git a/crates/metal2vulkan/examples/api_preview.rs b/crates/metal2vulkan/examples/api_preview.rs index 345589b7e..fa7cd887e 100644 --- a/crates/metal2vulkan/examples/api_preview.rs +++ b/crates/metal2vulkan/examples/api_preview.rs @@ -128,6 +128,14 @@ pub fn main() -> Result<()> { pipeline.stage.entry_point, ); + // What the module the driver will compile contains: the verifier's counts of it. + let stats = pipeline.stage.stats; + println!( + "{} blocks, {} instructions", + stats.blocks, stats.instructions + ); + assert!(stats.reachable_blocks <= stats.blocks); + // The same kernel as an entry of a bare module, through the device's profile: no library, // the same compile, and its module linked alone. let bitcode = fixture_bitcode("sampling")?; diff --git a/crates/metal2vulkan/src/cache/codec.rs b/crates/metal2vulkan/src/cache/codec.rs index cd54b59ec..2b7490027 100644 --- a/crates/metal2vulkan/src/cache/codec.rs +++ b/crates/metal2vulkan/src/cache/codec.rs @@ -32,9 +32,9 @@ use crate::metal; use crate::metal::format::{ExtendedRange, WordAttachment, WordField}; use crate::metal::{CompareFunction, TextureWriteRoundingMode}; use crate::pipeline::artifact::{ - ComputePipeline, ComputePipelineMetalInfo, PrecisionNote, Reconvergence, RenderPipeline, - RuntimeDependency, SpecClause, SpecConstant, SpecTest, SpecializationLayout, SpecializedNote, - StageModule, StrategyCensus, StrategyUse, + ComputePipeline, ComputePipelineMetalInfo, ModuleStats, PrecisionNote, Reconvergence, + RenderPipeline, RuntimeDependency, SpecClause, SpecConstant, SpecTest, SpecializationLayout, + SpecializedNote, StageModule, StrategyCensus, StrategyUse, }; use crate::pipeline::descriptor::TessellationDescriptor; use crate::pipeline::facts::{Mechanism, RuntimeFact, UniformViewChoice}; @@ -743,6 +743,51 @@ impl Codec for SpirvCapability { } } +/// The module statistics, encoded in full and digested as zero: every count is a function of the +/// module's words, which the digest already covers, so including them would move every artifact's +/// digest without telling it anything. The destructuring is exhaustive, so a field added to +/// [`ModuleStats`] fails to compile until it is written here. +impl Codec for ModuleStats { + const LEAF: bool = false; + fn digest(&self) -> Node { + let ModuleStats { + functions: _, + blocks: _, + reachable_blocks: _, + instructions: _, + constructs: _, + loops: _, + } = self; + Node::ZERO + } + fn put(&self, w: &mut Writer) { + let ModuleStats { + functions, + blocks, + reachable_blocks, + instructions, + constructs, + loops, + } = self; + functions.put(w); + blocks.put(w); + reachable_blocks.put(w); + instructions.put(w); + constructs.put(w); + loops.put(w); + } + fn get(r: &mut Reader<'_>) -> Result { + Ok(ModuleStats { + functions: Codec::get(r)?, + blocks: Codec::get(r)?, + reachable_blocks: Codec::get(r)?, + instructions: Codec::get(r)?, + constructs: Codec::get(r)?, + loops: Codec::get(r)?, + }) + } +} + // Sampler state carries floats; `vk::SamplerDesc` compares them by bits, as `f32`'s codec // round-trips them. codec_struct! { @@ -1263,7 +1308,7 @@ codec_struct! { RelocatableModule { words, relocs, requirements } FunctionArtifact { key, module, interface, facts, subgroup, reconvergence, precision, strategies, blob, - requirements, variant_bits, profile, kernel, reflection, slot_writes, specialized, + requirements, variant_bits, profile, kernel, reflection, slot_writes, specialized, stats, } StageReflection { bindings, attributes } SlotWrite { name, parameter, binding_type, index, count, used, access, writes } @@ -1301,6 +1346,7 @@ codec_struct! { stage, entry_point, spirv, specialization, required_subgroup_size, stage_flags, reconvergence, precision_notes, strategies, constant_blob, rounded_colors, specialized_notes, half_bit_colors, own_pixel_textures, snapshot_textures, private_bytes, + stats, } SpecializedNote { note, when } SpecClause { all } diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index a483652c9..d998e6f1c 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -70,7 +70,7 @@ pub const SEMANTICS_VERSION: u32 = 1867; /// 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 = 450; +pub const ARTIFACT_FORMAT_VERSION: u32 = 451; /// 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/library/compiled.rs b/crates/metal2vulkan/src/library/compiled.rs index 524661438..3209934b5 100644 --- a/crates/metal2vulkan/src/library/compiled.rs +++ b/crates/metal2vulkan/src/library/compiled.rs @@ -13,7 +13,7 @@ use std::sync::Arc; use crate::cache::{write_hex, Hash256}; use crate::device::requirements::Requirements; use crate::device::subgroup::SubgroupRequirement; -use crate::pipeline::artifact::{PrecisionNote, Reconvergence, StrategyCensus}; +use crate::pipeline::artifact::{ModuleStats, PrecisionNote, Reconvergence, StrategyCensus}; use crate::pipeline::facts::RuntimeFact; use crate::pipeline::interface::{AttributeFetch, SlotInterface, StageInterface}; use crate::pipeline::lower_inputs::VertexFetch; @@ -97,6 +97,14 @@ impl CompiledFunction { self.0.reconvergence } + /// What the function's module contains: its functions, blocks, instructions, structured + /// constructs and loops, as its linked stage states them (`StageModule::stats`). Linking the + /// function resolves its symbols and adds no instruction, so these are the counts of the + /// module a pipeline of it hands the driver. + pub fn module_stats(&self) -> ModuleStats { + self.0.stats + } + /// The subgroup size the function's simd tier pins, if any (its stage's /// `requiredSubgroupSize`, `StageModule::required_subgroup_size`). pub fn required_subgroup_size(&self) -> Option { @@ -192,6 +200,9 @@ pub struct FunctionArtifact { pub reconvergence: Reconvergence, pub precision: Vec, pub strategies: StrategyCensus, + /// What the finalize verifier counted of the module: what its linked stage states as + /// `StageModule::stats`. + pub stats: ModuleStats, /// Constant data the function reads through `WriteSource::ConstantBlob`. pub blob: Option>, pub requirements: Requirements, diff --git a/crates/metal2vulkan/src/pipeline/api_tests.rs b/crates/metal2vulkan/src/pipeline/api_tests.rs index c2fc5599a..024c03a88 100644 --- a/crates/metal2vulkan/src/pipeline/api_tests.rs +++ b/crates/metal2vulkan/src/pipeline/api_tests.rs @@ -49,6 +49,7 @@ fn stage_module_bytes_are_little_endian_words() { snapshot_textures: Vec::new(), private_bytes: 0, specialized_notes: Vec::new(), + stats: ModuleStats::default(), }; assert_eq!( m.spirv_bytes(), @@ -117,6 +118,7 @@ fn a_stage_s_notes_under_a_specialization_are_its_held_clauses() { }], }, ], + stats: ModuleStats::default(), }; let key = |values: &[(u32, u32)]| { let mut k = SpecializationKey::new(); diff --git a/crates/metal2vulkan/src/pipeline/artifact.rs b/crates/metal2vulkan/src/pipeline/artifact.rs index e2168bb70..55c7c9ee3 100644 --- a/crates/metal2vulkan/src/pipeline/artifact.rs +++ b/crates/metal2vulkan/src/pipeline/artifact.rs @@ -153,6 +153,9 @@ pub struct StageModule { /// (`StageInterface::private_bytes`): what `PrecisionNote::FunctionStorageAssumed`'s /// announcement names. 0 for a stage the link makes itself. pub private_bytes: u64, + /// What [`spirv`](Self::spirv) contains: its functions, blocks, instructions, structured + /// constructs and loops. + pub stats: ModuleStats, } impl StageModule { @@ -285,6 +288,67 @@ impl StageModule { } } +/// What one translated module contains: the counts the finalize verifier takes of it on every +/// translation, in every build. +/// +/// They are the module [`StageModule::spirv`] holds: the verifier counts the module it checked, +/// and serialization and relocation assign literals without adding or removing an instruction. +/// [`CompiledFunction::module_stats`](crate::library::CompiledFunction::module_stats) states the +/// same counts for a function compiled on its own, which its linked stage repeats. +/// +/// A caller reads them to watch the size of what it hands a driver: a larger module costs more to +/// compile on the drivers measured. Canonicalization inlines every direct call before the module +/// is emitted, so the counts are the whole program's, not one function's. +/// +/// How closely [`blocks`](Self::blocks) stands for the program a driver compiles depends on +/// [`functions`](Self::functions). A driver inlines before it charges, so a module of few +/// functions is one whose blocks are the program's; a module that calls a many-block function from +/// many sites holds a program far larger than its own blocks, and the two cases read alike in +/// `blocks` alone. Lowering emits such functions itself: the handle-table and root-table searches +/// are unrolled branch-free steps, emitted once and called at every access. +/// +/// The counts compare one module against the next of the same shader, not one shader against +/// another. Measured cost per block differed several-fold between a synthetic module and a real +/// workload, so a per-block figure taken from one shader predicts nothing for the next; +/// [`instructions`](Self::instructions) is the second number for that reason. +/// +/// [`blocks`](Self::blocks) alone does not say whose blocks they are. Translation adds blocks of +/// its own (inlining, and the structurizer's layout of control flow as SPIR-V requires), and the +/// input has blocks of its own, and a count that has risen can be either. +/// [`loops`](Self::loops) and [`constructs`](Self::constructs) separate them: the structurizer +/// makes no loop the input does not have, so a `blocks` that rises while `loops` holds still is +/// translation's own work or a changed shape of the same control flow, not new control flow in the +/// shader. The AIR side of that comparison is the caller's own, through `metal2vulkan-air`: for +/// the counts the input itself holds, before inlining, decode it and count the blocks of each +/// function's body (`metal2vulkan_air::decode`, then each `ir::Function`'s `body`); for the ones +/// canonicalization produced, walk the entry +/// [`DeviceProfile::specialized_entry`](crate::device::DeviceProfile::specialized_entry) gives, +/// which is that AIR specialized and canonicalized. +#[non_exhaustive] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct ModuleStats { + /// Functions: the entry point, and the ones canonicalization and lowering left beside it. + /// A module of few functions is one whose [`blocks`](Self::blocks) stand for the whole + /// program a driver compiles. + pub functions: u32, + /// Basic blocks, over every function the module holds. + pub blocks: u32, + /// Blocks reachable from their function's entry, never above [`blocks`](Self::blocks). It is + /// below it by the merge blocks SPIR-V requires a construct to declare that no path reaches — + /// both arms of a conditional inside a loop leaving the construct, say — which the module + /// terminates with `OpUnreachable`. A bound, not a lever: the difference is blocks the driver + /// still reads and no invocation runs. + pub reachable_blocks: u32, + /// Instructions, phis and terminators. It moved with [`blocks`](Self::blocks) in every + /// module measured, and is cheaper to reason about. + pub instructions: u64, + /// Structured constructs: selection, switch and loop headers. + pub constructs: u32, + /// Loops. The structurizer makes none of its own, so this is the input's own loop count. + pub loops: u32, +} + /// A precision note a stage records only where a specialized module runs an arm that keeps its /// near-equivalent: the note holds under a specialization exactly when one of the clauses of `when` /// holds. diff --git a/crates/metal2vulkan/src/pipeline/compile.rs b/crates/metal2vulkan/src/pipeline/compile.rs index 6be8d8b8e..806f60cb9 100644 --- a/crates/metal2vulkan/src/pipeline/compile.rs +++ b/crates/metal2vulkan/src/pipeline/compile.rs @@ -2708,7 +2708,7 @@ fn compile_kept( precision.push(PrecisionNote::DeviceSampling); precision.sort_unstable(); } - crate::spirv::verify::verify(&module, p, m)?; + let stats = crate::spirv::verify::verify(&module, p, m)?; let kept = keep(&module); let mut symbols = crate::pipeline::link::contract::stage_symbols(&module, &plan.families.stage_io.interface)?; @@ -2902,6 +2902,7 @@ fn compile_kept( reconvergence: crate::lower::simd::reconvergence(&plan), precision, strategies: emitted_census(&plan, helper_guard), + stats, blob: plan.families.access.blob.as_ref().map(|b| b.bytes.clone()), requirements, variant_bits: 0, diff --git a/crates/metal2vulkan/src/pipeline/compile/api.rs b/crates/metal2vulkan/src/pipeline/compile/api.rs index aeecbdda1..3108d70ff 100644 --- a/crates/metal2vulkan/src/pipeline/compile/api.rs +++ b/crates/metal2vulkan/src/pipeline/compile/api.rs @@ -1111,7 +1111,7 @@ fn depth16_stage( return Ok(None); } let module = depth16::fragment_module(v.depth16_bias_raises)?; - crate::spirv::verify::verify(&module, p, m)?; + let stats = crate::spirv::verify::verify(&module, p, m)?; let module = crate::spirv::serialize::serialize_for(module, p)?; let words = crate::spirv::serialize::relocate(&module, &*linked)?; stages.push(StageModule { @@ -1131,6 +1131,7 @@ fn depth16_stage( own_pixel_textures: Vec::new(), snapshot_textures: Vec::new(), private_bytes: 0, + stats, }); let placement = depth16::fragment_placement(); if let Some((offset, size)) = placement.push_range { @@ -1618,6 +1619,9 @@ fn stage_module(a: &FunctionArtifact, linked: &Linked, i: usize) -> Result Result<(StageModule, Requirements), Error> { let module = vertex_module(r, last_first)?; - crate::spirv::verify::verify(&module, p, m)?; + let stats = crate::spirv::verify::verify(&module, p, m)?; let module = crate::spirv::serialize::serialize_for(module, p)?; let words = crate::spirv::serialize::relocate(&module, table)?; Ok(( @@ -155,6 +155,7 @@ pub fn synthesized_stage( own_pixel_textures: Vec::new(), snapshot_textures: Vec::new(), private_bytes: 0, + stats, }, module.requirements, )) diff --git a/crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs b/crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs index 6ed639f70..7a7025441 100644 --- a/crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs +++ b/crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs @@ -367,7 +367,7 @@ pub fn synthesized_stages( ]; let mut out = Vec::with_capacity(modules.len()); for (module, stage) in modules { - crate::spirv::verify::verify(&module, p, m)?; + let stats = crate::spirv::verify::verify(&module, p, m)?; let module = crate::spirv::serialize::serialize_for(module, p)?; let words = crate::spirv::serialize::relocate(&module, table)?; out.push(( @@ -388,6 +388,7 @@ pub fn synthesized_stages( own_pixel_textures: Vec::new(), snapshot_textures: Vec::new(), private_bytes: 0, + stats, }, module.requirements, )); diff --git a/crates/metal2vulkan/src/pipeline/link/tests.rs b/crates/metal2vulkan/src/pipeline/link/tests.rs index d4f0a2310..7d6e7ea57 100644 --- a/crates/metal2vulkan/src/pipeline/link/tests.rs +++ b/crates/metal2vulkan/src/pipeline/link/tests.rs @@ -157,6 +157,7 @@ pub(super) fn artifact( reconvergence: Reconvergence::Guaranteed, precision: Vec::new(), strategies: StrategyCensus::default(), + stats: crate::pipeline::artifact::ModuleStats::default(), blob: None, requirements, variant_bits: 0, diff --git a/crates/metal2vulkan/src/pipeline/mod.rs b/crates/metal2vulkan/src/pipeline/mod.rs index fd92ebe86..37c1f75b7 100644 --- a/crates/metal2vulkan/src/pipeline/mod.rs +++ b/crates/metal2vulkan/src/pipeline/mod.rs @@ -104,9 +104,9 @@ pub(crate) mod tile_map; pub(crate) mod vertex; pub use artifact::{ - ComputePipeline, ComputePipelineMetalInfo, EntryMath, PrecisionNote, Reconvergence, - RenderPipeline, RuntimeDependency, SpecClause, SpecConstant, SpecTest, SpecializationLayout, - SpecializedNote, StageModule, StrategyCensus, StrategyUse, + ComputePipeline, ComputePipelineMetalInfo, EntryMath, ModuleStats, PrecisionNote, + Reconvergence, RenderPipeline, RuntimeDependency, SpecClause, SpecConstant, SpecTest, + SpecializationLayout, SpecializedNote, StageModule, StrategyCensus, StrategyUse, }; pub use descriptor::{ ColorAttachmentDescriptor, ComputePipelineDescriptor, DynamicLibraries, FunctionDescriptor, diff --git a/crates/metal2vulkan/src/spirv/verify/cfg.rs b/crates/metal2vulkan/src/spirv/verify/cfg.rs index 9d2f41611..ebcbe23d7 100644 --- a/crates/metal2vulkan/src/spirv/verify/cfg.rs +++ b/crates/metal2vulkan/src/spirv/verify/cfg.rs @@ -6,7 +6,7 @@ use crate::spirv::error::Dangling; use crate::spirv::ids::{BlockId, FuncId, Value}; use crate::spirv::ir::{Block, Function, Inst, Merge, Terminator, Type, TypedModule, ValueOrigin}; -use super::{Ledger, VerifyError, VerifyReport, Violation}; +use super::{Ledger, ModuleStats, VerifyError, Violation}; /// "None" in the dense `u32` side tables. pub(super) const NONE: u32 = u32::MAX; @@ -501,7 +501,7 @@ pub(super) fn check_function( facts: &ModuleFacts<'_>, func: FuncId, cons: &mut ModuleConstructs, - report: &mut VerifyReport, + report: &mut ModuleStats, meter: &mut Meter, ) -> Result<(), VerifyError> { let ModuleFacts { @@ -539,7 +539,7 @@ fn check_function_in( ctx: &FnCtx<'_>, cons: &mut ModuleConstructs, tangled_fn: &[bool], - report: &mut VerifyReport, + report: &mut ModuleStats, meter: &mut Meter, ) -> Result<(), VerifyError> { let m = ctx.m; diff --git a/crates/metal2vulkan/src/spirv/verify/mod.rs b/crates/metal2vulkan/src/spirv/verify/mod.rs index a9583a5fe..40c26d830 100644 --- a/crates/metal2vulkan/src/spirv/verify/mod.rs +++ b/crates/metal2vulkan/src/spirv/verify/mod.rs @@ -43,6 +43,10 @@ //! `shaderZeroInitializeWorkgroupMemory`, and the requirements are a subset of the profile //! (`Internal(RequirementsExceedProfile)`). //! +//! A pass counts what it covered as it checks it, and that count is the module's public +//! [`ModuleStats`]: the verifier runs on every translation, so the statistics cost nothing beyond +//! it. +//! //! Work is linear in the module plus, per branch edge, the number of constructs it leaves; it is //! metered on the per-attempt [`Meter`] and every table is charged to its ledger. @@ -57,24 +61,11 @@ use std::fmt; use crate::budget::Meter; use crate::device::profile::DeviceProfile; use crate::error::{Capability, Error, InternalError, InternalKind}; +use crate::pipeline::artifact::ModuleStats; use crate::spirv::error::{BuildError, Dangling}; use crate::spirv::ids::{BlockId, FuncId, GlobalId, Value}; use crate::spirv::ir::TypedModule; -/// What a successful verification covered. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub struct VerifyReport { - pub functions: u32, - pub blocks: u32, - /// Blocks reachable from their function's entry. - pub reachable_blocks: u32, - /// Instructions, phis, and terminators. - pub instructions: u64, - /// Structured constructs (selections, switches, loops). - pub constructs: u32, - pub loops: u32, -} - /// A broken verifier rule, naming where. #[non_exhaustive] #[derive(Clone, Debug, PartialEq, Eq)] @@ -255,7 +246,7 @@ pub fn verify( m: &TypedModule, profile: &DeviceProfile, meter: &mut Meter, -) -> Result { +) -> Result { check(m, profile, meter).map_err(Error::from) } @@ -264,7 +255,7 @@ pub fn check( m: &TypedModule, profile: &DeviceProfile, meter: &mut Meter, -) -> Result { +) -> Result { let report = check_structure(m, meter)?; rules::profile_rules(m, profile)?; Ok(report) @@ -272,7 +263,7 @@ pub fn check( /// Every rule that does not depend on a device profile. Tests of builder families that no /// committed profile enables use this; products always run [`verify`]. -pub fn check_structure(m: &TypedModule, meter: &mut Meter) -> Result { +pub fn check_structure(m: &TypedModule, meter: &mut Meter) -> Result { let mut ledger = Ledger { bytes: 0 }; let r = check_in(m, meter, &mut ledger); meter.release(ledger.bytes); @@ -283,16 +274,16 @@ fn check_in( m: &TypedModule, meter: &mut Meter, ledger: &mut Ledger, -) -> Result { +) -> Result { let layout = cfg::Layout::build(m, meter, ledger)?; let defs = cfg::Defs::build(m, meter, ledger)?; let calls = rules::CallGraph::build(m, meter, ledger)?; let tangled_fn = calls.check_and_propagate(meter)?; - let mut report = VerifyReport { + let mut report = ModuleStats { functions: u32::try_from(m.functions.len()).unwrap_or(u32::MAX), blocks: u32::try_from(m.blocks.len()).unwrap_or(u32::MAX), loops: u32::try_from(m.loops.len()).unwrap_or(u32::MAX), - ..VerifyReport::default() + ..ModuleStats::default() }; let mut constructs = cfg::ModuleConstructs::new(m, meter, ledger)?; let facts = cfg::ModuleFacts { diff --git a/crates/metal2vulkan/src/spirv/verify/tests.rs b/crates/metal2vulkan/src/spirv/verify/tests.rs index 9780f19ff..497ac6761 100644 --- a/crates/metal2vulkan/src/spirv/verify/tests.rs +++ b/crates/metal2vulkan/src/spirv/verify/tests.rs @@ -254,7 +254,7 @@ fn meter() -> Meter { Meter::new(&Budget::default()) } -fn structure(m: &TypedModule) -> Result { +fn structure(m: &TypedModule) -> Result { check_structure(m, &mut meter()) } diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 8cb5bb2c9..a5bf7fbbb 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -4239,6 +4239,12 @@ field metal2vulkan::pipeline::MeshRecords.primitives pub primitives: u32 field metal2vulkan::pipeline::MeshRecords.slot_words pub slot_words: u32 field metal2vulkan::pipeline::MeshRecords.vertex_words pub vertex_words: u32 field metal2vulkan::pipeline::MeshRecords.vertices pub vertices: u32 +field metal2vulkan::pipeline::ModuleStats.blocks pub blocks: u32 +field metal2vulkan::pipeline::ModuleStats.constructs pub constructs: u32 +field metal2vulkan::pipeline::ModuleStats.functions pub functions: u32 +field metal2vulkan::pipeline::ModuleStats.instructions pub instructions: u64 +field metal2vulkan::pipeline::ModuleStats.loops pub loops: u32 +field metal2vulkan::pipeline::ModuleStats.reachable_blocks pub reachable_blocks: u32 field metal2vulkan::pipeline::PipelineInterface.command_writes pub command_writes: CommandWrites field metal2vulkan::pipeline::PipelineInterface.needs_handle_translation pub needs_handle_translation: bool field metal2vulkan::pipeline::PipelineInterface.needs_pointer_translation pub needs_pointer_translation: bool @@ -4376,6 +4382,7 @@ field metal2vulkan::pipeline::StageModule.specialized_notes pub specialized_note field metal2vulkan::pipeline::StageModule.spirv pub spirv: Arc<[u32]> field metal2vulkan::pipeline::StageModule.stage pub stage: vk::ShaderStage field metal2vulkan::pipeline::StageModule.stage_flags pub stage_flags: vk::PipelineShaderStageCreateFlags +field metal2vulkan::pipeline::StageModule.stats pub stats: ModuleStats field metal2vulkan::pipeline::StageModule.strategies pub strategies: StrategyCensus field metal2vulkan::pipeline::StandInUse.format pub format: vk::Format field metal2vulkan::pipeline::StandInUse.formatless pub formatless: bool @@ -8840,6 +8847,7 @@ method metal2vulkan::library::CompiledFunction::attribute_fetches pub fn attribu method metal2vulkan::library::CompiledFunction::from_bytes pub fn from_bytes(bytes: &[u8], device: &Device) -> Result method metal2vulkan::library::CompiledFunction::from_bytes_for_key pub fn from_bytes_for_key(bytes: &[u8], key: &FunctionCompileKey, device: &Device) -> Result method metal2vulkan::library::CompiledFunction::key pub fn key(&self) -> &FunctionCompileKey +method metal2vulkan::library::CompiledFunction::module_stats pub fn module_stats(&self) -> ModuleStats method metal2vulkan::library::CompiledFunction::numbered_samplers pub fn numbered_samplers(&self) -> &[crate::pipeline::NumberedSampler] method metal2vulkan::library::CompiledFunction::precision_notes pub fn precision_notes(&self) -> &[PrecisionNote] method metal2vulkan::library::CompiledFunction::reads_resident_roots pub fn reads_resident_roots(&self) -> bool @@ -9686,6 +9694,7 @@ struct metal2vulkan::pipeline::LinkedSource #[derive(Clone, Copy, Debug)] pub st struct metal2vulkan::pipeline::LoweringInputs #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub struct LoweringInputs struct metal2vulkan::pipeline::MeshPipelineDescriptor #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct MeshPipelineDescriptor struct metal2vulkan::pipeline::MeshRecords #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct MeshRecords +struct metal2vulkan::pipeline::ModuleStats #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct ModuleStats struct metal2vulkan::pipeline::PipelineInterface #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct PipelineInterface struct metal2vulkan::pipeline::PipelineLayout #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct PipelineLayout struct metal2vulkan::pipeline::PlacedField #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct PlacedField @@ -9947,6 +9956,7 @@ trait-impl metal2vulkan::metal::state::StencilDescriptor impl Default impl Defau trait-impl metal2vulkan::pipeline::ComputePipeline impl Fitted impl Fitted for ComputePipeline trait-impl metal2vulkan::pipeline::ComputePipeline impl PipelineArtifact impl PipelineArtifact for ComputePipeline trait-impl metal2vulkan::pipeline::LinkedFunction impl From impl From for LinkedFunction +trait-impl metal2vulkan::pipeline::ModuleStats impl Codec impl Codec for ModuleStats trait-impl metal2vulkan::pipeline::PrivateRenderState impl Default impl Default for PrivateRenderState trait-impl metal2vulkan::pipeline::PrivateRenderState impl Eq impl Eq for PrivateRenderState trait-impl metal2vulkan::pipeline::PrivateRenderState impl PartialEq impl PartialEq for PrivateRenderState diff --git a/crates/metal2vulkan/tests/api_surface.rs b/crates/metal2vulkan/tests/api_surface.rs index e545162a1..c67ea872b 100644 --- a/crates/metal2vulkan/tests/api_surface.rs +++ b/crates/metal2vulkan/tests/api_surface.rs @@ -336,6 +336,7 @@ surface! { struct LinkedSource O; struct StageEntries O; struct StandaloneModule N; + struct ModuleStats N; enum PrecisionNote E; enum Reconvergence N; struct RenderPipeline N; @@ -1216,6 +1217,87 @@ fn compiled_functions_round_trip_through_the_public_api() { } } +/// A stage's module statistics: filled by the compile, the same counts the compiled function +/// states before linking, kept across an artifact round-trip, and left out of the content digest, +/// which already covers the words they describe. +#[test] +fn a_stage_states_what_its_module_contains() { + let Some(bc) = fixture("store_const") else { + return; + }; + let dev = device("moltenvk-m3"); + let f = FunctionDescriptor::new( + Library::from_air(&bc) + .expect("library") + .function("store_const") + .expect("function"), + ); + let compiled = dev + .compile_function(&f, &LoweringInputs::new(), &Budget::standard()) + .expect("function"); + let pipeline = dev + .compile_compute_pipeline( + &ComputePipelineDescriptor::new(StageSource::Function(f)), + &Budget::standard(), + ) + .expect("pipeline"); + let stats = pipeline.stage.stats; + assert!( + stats.functions > 0 && stats.blocks > 0 && stats.instructions > 0, + "{stats:?}" + ); + assert_eq!( + stats.reachable_blocks, stats.blocks, + "a module with no construct declares no unreachable merge" + ); + assert!(stats.loops <= stats.constructs, "{stats:?}"); + assert_eq!( + compiled.module_stats(), + stats, + "linking adds no instruction" + ); + + let cached = ComputePipeline::from_bytes_for_key(&pipeline.to_bytes(), &pipeline.key, &dev) + .expect("pipeline decode"); + assert_eq!(cached.stage.stats, stats, "a cache hit states them too"); + + let mut miscounted = pipeline.clone(); + miscounted.stage.stats.blocks += 1; + assert_eq!( + miscounted.content_digest(), + pipeline.content_digest(), + "the counts describe the words the digest already covers" + ); + + // A kernel with control flow of its own: the constructs and loops are counted, and the + // structurizer makes no loop the input does not have. + let Some(bc) = fixture("kernel_nested_loop_constant_weight_walk") else { + return; + }; + let looping = dev + .compile_compute_pipeline( + &ComputePipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new( + Library::from_air(&bc) + .expect("library") + .function("nested_loop_constant_weight_walk") + .expect("function"), + ))), + &Budget::standard(), + ) + .expect("pipeline") + .stage + .stats; + assert!(looping.loops > 0, "{looping:?}"); + assert!(looping.constructs >= looping.loops, "{looping:?}"); + assert!(looping.blocks > stats.blocks, "{looping:?} over {stats:?}"); + // The selection merges SPIR-V requires this kernel's breaks and continues to declare are + // reached by no path, so its reachable blocks are below its blocks. + assert!( + looping.reachable_blocks < looping.blocks, + "{looping:?}: a declared merge no path reaches" + ); +} + /// The content digests are public: a pipeline's names what it says, not the build that compiled it. /// Another build of the crate, whose versions differ and so move every cache key, compiles the same /// content under another `key`; that key and another profile fingerprint leave the digest equal, diff --git a/docs/API.md b/docs/API.md index 215ef1fd0..e50761a53 100644 --- a/docs/API.md +++ b/docs/API.md @@ -334,8 +334,9 @@ budget, and exceeding one is `Error::LimitExceeded`, permanent for that input. A `ComputePipeline` is immutable plain data: - `stage`: a `StageModule` (SPIR-V 1.5 words valid for the device, the entry point, specialization - constants, a required subgroup size and stage flags, precision notes, and `private_bytes`, the - private memory a thread keeps, as `StageInterface::private_bytes` states it too); + constants, a required subgroup size and stage flags, precision notes, `private_bytes`, the + private memory a thread keeps, as `StageInterface::private_bytes` states it too, and `stats`, + what the module contains); - `layout`: the pipeline layout, dense and complete; create it as it is; - `interface`, `dependencies`: what it binds and what bind-time state it depends on (section 5); - `metal_info`: answers to Metal's per-pipeline queries (`maxTotalThreadsPerThreadgroup`, ...); @@ -349,6 +350,56 @@ placeholders (a kernel's local size is 1). Create each pipeline from a planned d one device pins only what that device can take; `DeviceProfile::check` tells whether another device can. +### What the module contains + +Every stage states the size and shape of its module, counted by the verifier that runs on every +translation, in every build: `stage.stats`, a `ModuleStats`. A function compiled on its own states +the same counts as `module_stats()`, before it is linked. Reading them is how a caller watches the +size of what it hands a driver, and what in it grew. + +```rust +let stats = pipeline.stage.stats; +println!( + "{} blocks, {} instructions", + stats.blocks, stats.instructions +); +assert!(stats.reachable_blocks <= stats.blocks); +``` + +- `blocks` and `instructions` are the module's size: a larger module costs more to compile on the + drivers measured. Canonicalization inlines every direct call before the module is emitted, so + they count the whole program, not one function. +- `functions` -- the entry point and the functions left beside it -- says how far `blocks` stands + for that program. A driver inlines before it charges, so a module of few functions is one whose + blocks are the program's, while a module that calls a many-block function from many sites holds + a program far larger than its own blocks; the two read alike in `blocks` alone. Lowering emits + such functions itself: the handle-table and root-table searches are unrolled branch-free steps, + emitted once and called at every access. +- Compare one module against the next of the same shader, not one shader against another. Measured + cost per block differed several-fold between a synthetic module and a real workload, so a + per-block figure taken from one shader predicts nothing for the next; `instructions` is the + second number for that reason. +- `constructs` (selection, switch and loop headers) and `loops` say whose blocks those are. + Translation adds blocks of its own -- inlining, and the structurizer's layout of control flow as + SPIR-V requires -- and the input has blocks of its own. The structurizer makes no loop the input + does not have, so a `blocks` that has risen while `loops` holds still is translation's work or a + changed shape of the same control flow, not new control flow in the shader. +- `reachable_blocks` is a bound, not a lever. It is never above `blocks`, and below it by the merge + blocks SPIR-V requires a construct to declare that no path reaches -- both arms of a conditional + inside a loop leaving the construct, say -- which the module terminates with `OpUnreachable`. The + difference is blocks the driver still reads and no invocation runs. +- The AIR side of the comparison is yours, through `metal2vulkan-air`. For the counts the input + itself holds, before inlining, decode it and count the blocks of each function's body + (`metal2vulkan_air::decode`, then each `ir::Function`'s `body`); for the ones canonicalization + produced, walk the entry `DeviceProfile::specialized_entry` gives, which is that AIR specialized + and canonicalized. A decoded function's `ir::InstKind::Call` sites give each callee's call + count, which is what turns its own blocks into the program inlining will make of it. + +The counts are of the module `spirv` holds: the verifier counts the module it checked, and +serialization and relocation assign link numbers without adding or removing an instruction. They +are part of the encoded artifact, so a cache hit states them too, and they are left out of +`content_digest`, which already covers the words they describe. + ### A kernel with `[[stage_in]]` A kernel's `[[stage_in]]` attributes are fetched in the shader, as Metal does. The compile asks for @@ -938,9 +989,9 @@ assert_eq!(linked, pipeline); - A compiled function states before linking what its stage will: `stage()`, `requirements()` (check it against another profile with `DeviceProfile::check`), `precision_notes()`, - `reconvergence()`, `required_subgroup_size()`, `requires_full_subgroups()`, and - `writes_memory()` (stores or atomics, which a render pipeline drawn in more than one color - group refuses). + `reconvergence()`, `required_subgroup_size()`, `requires_full_subgroups()`, `module_stats()` + (section 3) and `writes_memory()` (stores or atomics, which a render pipeline drawn in more than + one color group refuses). `compile_function_with_report` also returns a `CompileReport` of what the compile cost. - A render pipeline's stages compile under inputs that a decode of its functions learns. `render_pipeline_key` returns `RenderPipelineKeys`: each stage's function key, and the inputs to