diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 10e55a4ff..855a640f5 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -60,7 +60,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 = 2293; +pub const SEMANTICS_VERSION: u32 = 2294; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another diff --git a/crates/metal2vulkan/src/lower/emit.rs b/crates/metal2vulkan/src/lower/emit.rs index 651047d40..1e775420c 100644 --- a/crates/metal2vulkan/src/lower/emit.rs +++ b/crates/metal2vulkan/src/lower/emit.rs @@ -184,9 +184,8 @@ pub struct EmitCx<'a> { entry_block: Option, /// The block the entry hooks end in, where the walk of the body starts: it dominates every /// block of the body, so its memo entries outlive the block that emitted them too. It is the - /// entry block but where a hook closed a construct there: a kernel's tail guard - /// (`EmitCx::emit_tail_guard`) or a dispatch past its grid (`dispatch::emit_entry`) returns - /// from an arm, and the hooks after it, the sink's address + /// entry block but where a hook closed a construct there: a dispatch past its grid + /// (`dispatch::emit_entry`) returns from an arm, and the hooks after it, the sink's address /// among them (`access::dynamic::emit_entry`), run in its merge. hooks_block: Option, /// While a workgroup synchronization of a predicated walk is emitted, the calling invocation's @@ -509,56 +508,48 @@ impl<'a> EmitCx<'a> { /// load, so a read that canonicalization deletes cannot make the others load it again; a placed /// field no instruction reads leaves with the other unused values (`spirv::dead`). /// - /// A kernel loads its fields in placement order, then returns where its tail holds what the - /// consumer never pushes ([`EmitCx::emit_tail_guard`]). A render stage loads the fields read - /// from their push members first, then folds the tail into them ([`EmitCx::fold_tail`]), then - /// the spilled fields and those the function derives, which may read through the folded values - /// (the parameter block's address, a slot table's). + /// The fields read from their push members load first, then the tail folds into them + /// ([`EmitCx::fold_tail`]), then the spilled fields and those the function derives, which may + /// read through the folded values (the parameter block's address, a slot table's). fn load_push_fields(&mut self, fb: &mut FunctionBuilder<'_>) -> BResult<()> { - if self.plan.stage == Stage::Kernel { - self.load_fields(fb, |_, _| true)?; - return self.emit_tail_guard(fb); - } + let plan: &Plan = self.plan; let member = |s: &Self, field: PushField| { !s.derives(field) && s.decl.push.iter().any(|m| m.field == field) }; - self.load_fields(fb, member)?; - self.fold_tail(fb)?; - self.load_fields(fb, |s, field| !member(s, field)) - } - - /// Load each field the plan places that `which` takes, in placement order. - fn load_fields( - &mut self, - fb: &mut FunctionBuilder<'_>, - which: impl Fn(&Self, PushField) -> bool, - ) -> BResult<()> { - let plan: &Plan = self.plan; - for placed in &plan.push.fields { - if !which(self, placed.field) { - continue; + for read in [true, false] { + for placed in &plan.push.fields { + if member(self, placed.field) != read { + continue; + } + match placed.field { + PushField::SlotBounds(slot) => { + self.slot_bounds(fb, slot)?; + } + field => { + self.push_field(fb, field)?; + } + } } - match placed.field { - PushField::SlotBounds(slot) => { - self.slot_bounds(fb, slot)?; - } - field => { - self.push_field(fb, field)?; - } + if read { + self.fold_tail(fb)?; } } Ok(()) } /// Where the plan's placement ends with a tail (`lower::push::tail`): read it from the push - /// block, and test whether it holds the value the consumer never pushes there - /// ([`crate::lower::push::tail_never_pushed`]); `None` where there is no tail or no such - /// value. A tail field the function reads from its member is the load - /// [`EmitCx::load_push_fields`] made in this block, so the member is loaded once; the tail - /// word, and a field the function derives elsewhere, are loaded here. - fn tail_test(&mut self, fb: &mut FunctionBuilder<'_>) -> BResult> { + /// block, test whether it holds the value the consumer never pushes there + /// ([`crate::lower::push::tail_never_pushed`]), and make each other field read from its push + /// member, as the function's every use recalls it, the member's value where the test fails and + /// the null of its type where it holds ([`crate::lower::push::fold_never_pushed`]): the tail's + /// read lives while any other push read does, and no branch makes the body depend on it. A + /// tail field the function reads from its member is the load [`EmitCx::load_push_fields`] made + /// in this block, so the member is loaded once; the tail word, and a field the function + /// derives elsewhere, are loaded here. A tail field of the function's own folds into the + /// others alone: its own uses need no select to read it. + fn fold_tail(&mut self, fb: &mut FunctionBuilder<'_>) -> BResult<()> { let Some(field) = crate::lower::push::tail(&self.plan.push) else { - return Ok(None); + return Ok(()); }; let member = (self.decl.push.iter()).find(|m| m.field == field); let (Some(member), Some(push)) = (member, self.decl.push_global) else { @@ -568,30 +559,7 @@ impl<'a> EmitCx<'a> { true => self.push_field(fb, field)?, false => Self::load_member(fb, push, member.index)?, }; - let never = crate::lower::push::tail_never_pushed(fb, value, field)?; - Ok(never.map(|never| (field, never))) - } - - /// A kernel's tail ([`EmitCx::tail_test`]): return from the function where it holds the value - /// the consumer never pushes there ([`crate::lower::push::return_never_pushed`]). The branch - /// is never taken; everything the function does after it depends on the tail's read. A return - /// at entry is a kernel's own shape: its entry also returns invocations before its body where - /// its dispatch passes its grid (`dispatch::emit_entry`). - fn emit_tail_guard(&mut self, fb: &mut FunctionBuilder<'_>) -> BResult<()> { - match self.tail_test(fb)? { - Some((_, never)) => crate::lower::push::return_never_pushed(fb, never), - None => Ok(()), - } - } - - /// A render stage's tail ([`EmitCx::tail_test`]): make each other field read from its push - /// member, as the function's every use recalls it, the member's value where the test fails and - /// the null of its type where it holds ([`crate::lower::push::fold_never_pushed`]): the tail's - /// read lives while any other push read does, and no branch makes the body depend on it - /// (`lower::push`: a fragment stage has no other return at its entry). A tail field of the - /// function's own folds into the others alone: its own uses need no select to read it. - fn fold_tail(&mut self, fb: &mut FunctionBuilder<'_>) -> BResult<()> { - let Some((field, never)) = self.tail_test(fb)? else { + let Some(never) = crate::lower::push::tail_never_pushed(fb, value, field)? else { return Ok(()); }; let plan: &Plan = self.plan; @@ -1649,8 +1617,7 @@ pub fn emit_module(e: &Entry, plan: &Plan, m: &mut Meter) -> Result Result<(), String> /// In the open block of a function whose push block holds the stage's tail `field` ([`tail`]), /// `value` its member as the block read it: whether it holds the value the consumer never pushes /// there: the tail word non-zero, a two-word field with both words all ones, an address all ones. -/// `None` for a tail of another shape, which has no such value. A kernel returns where the test -/// holds ([`return_never_pushed`]); a render stage folds it into each other pushed field's value -/// ([`fold_never_pushed`]). Either way no optimizer drops the read while it keeps any other push -/// read. +/// `None` for a tail of another shape, which has no such value. The function folds the test into +/// each other pushed field's value ([`fold_never_pushed`]), so no optimizer drops the read while +/// it keeps any other push read, and no branch makes the body depend on it. pub(crate) fn tail_never_pushed( fb: &mut crate::spirv::builder::FunctionBuilder<'_>, value: crate::spirv::ids::Value, @@ -477,23 +473,7 @@ pub(crate) fn tail_never_pushed( Ok(Some(set)) } -/// A kernel's tail test `never` ([`tail_never_pushed`]): return from the function where it holds. -/// The branch is never taken; the return keeps the read from any optimizer, as everything the -/// function does after it depends on it. -pub(crate) fn return_never_pushed( - fb: &mut crate::spirv::builder::FunctionBuilder<'_>, - never: crate::spirv::ids::Value, -) -> crate::spirv::error::BResult<()> { - use crate::spirv::builder::constructs::{ArmEnd, ArmFn}; - let leave: ArmFn<'_, ()> = Box::new(|fb, _| { - fb.ret(None)?; - Ok(ArmEnd::Exits) - }); - fb.if_(&mut (), never, leave, None)?; - Ok(()) -} - -/// A render stage's `value`, a pushed field's value as its member was read, where the stage's tail does not hold +/// `value`, a pushed field's value as its member was read, where the stage's tail does not hold /// the value the consumer never pushes there (`never`, [`tail_never_pushed`]), else the null of /// its type: the value the consumer's push gives, through a select whose condition is the tail's /// test, so the field's every use reads the tail too. diff --git a/crates/metal2vulkan/src/tests/engine_device_arena.rs b/crates/metal2vulkan/src/tests/engine_device_arena.rs index fa9b46e5f..83e4b0656 100644 --- a/crates/metal2vulkan/src/tests/engine_device_arena.rs +++ b/crates/metal2vulkan/src/tests/engine_device_arena.rs @@ -10,8 +10,8 @@ //! plan keeps the arena in device memory, with the default lowering inputs and as a kernel whose //! threadgroups may be partial, the invocation's slot (`EmitCx::arena_slot`) is derived once in //! the function, and each push-block or `ArgumentTable` member, the arena's address among them, -//! is loaded once: the floor's tail guard (`EmitCx::emit_tail_guard`) reads the tail from the load -//! the first block made, and a hook after the guard's construct recalls the first block's loads. +//! is loaded once: the floor's tail (`EmitCx::fold_tail`) reads the tail from the load the first +//! block made, and a hook after a construct of the entry hooks recalls the first block's loads. //! //! What one access of the arena emits, on a generated module: each shape is two kernels, one that //! makes the access once and one that makes it twice, everything else equal, as in diff --git a/crates/metal2vulkan/src/tests/engine_identity.rs b/crates/metal2vulkan/src/tests/engine_identity.rs index a6167ffb7..706496204 100644 --- a/crates/metal2vulkan/src/tests/engine_identity.rs +++ b/crates/metal2vulkan/src/tests/engine_identity.rs @@ -2528,17 +2528,10 @@ const READS: u32 = 20; /// A kernel reading one `uint` from each of `reads` buffers and storing their ordered fold /// (`s · 3 + v`, so two swapped addresses change it) to the next buffer. fn many_of(reads: u32) -> String { - many_in(false, reads) -} - -/// [`many_of`]'s kernel, or where `fragment`, a fragment function reading the same `reads` -/// buffers, with no output buffer, and returning the fold's bits as its color's `x`. -fn many_in(fragment: bool, reads: u32) -> String { let mut params = Vec::new(); let mut body = String::new(); let mut meta = Vec::new(); - let slots = reads + u32::from(!fragment); - for k in 0..slots { + for k in 0..=reads { params.push(format!( "ptr addrspace(1) noundef \"air-buffer-no-alias\" %{k}" )); @@ -2559,27 +2552,13 @@ fn many_in(fragment: bool, reads: u32) -> String { )); } let last = reads - 1; - let args: Vec = (0..slots).map(|k| format!("!{}", 100 + k)).collect(); - let (ty, end, stage, returned) = match fragment { - true => ( - "<4 x float>", - format!(" %f = bitcast i32 %s{last} to float\n %c = insertelement <4 x float> zeroinitializer, float %f, i64 0\n ret <4 x float> %c\n"), - "fragment", - "!12}\n!12 = !{!\"air.render_target\", i32 0, i32 0, !\"air.arg_type_name\", !\"float4\"", - ), - false => ( - "void", - format!(" store i32 %s{last}, ptr addrspace(1) %{reads}, align 4\n ret void\n"), - "kernel", - "", - ), - }; + let args: Vec = (0..=reads).map(|k| format!("!{}", 100 + k)).collect(); format!( "target datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32\"\n\ target triple = \"air64_v28-apple-macosx26.0.0\"\n\n\ -define {ty} @many({}) {{\nentry:\n{body}{end}}}\n\n\ -!air.{stage} = !{{!9}}\n!air.version = !{{!17}}\n!air.language_version = !{{!18}}\n\ -!9 = !{{ptr @many, !10, !11}}\n!10 = !{{{returned}}}\n!11 = !{{{}}}\n{}\n\ +define void @many({}) {{\nentry:\n{body} store i32 %s{last}, ptr addrspace(1) %{reads}, align 4\n ret void\n}}\n\n\ +!air.kernel = !{{!9}}\n!air.version = !{{!17}}\n!air.language_version = !{{!18}}\n\ +!9 = !{{ptr @many, !10, !11}}\n!10 = !{{}}\n!11 = !{{{}}}\n{}\n\ !17 = !{{i32 2, i32 8, i32 0}}\n!18 = !{{!\"Metal\", i32 4, i32 0, i32 0}}\n", params.join(", "), args.join(", "), @@ -2713,109 +2692,80 @@ fn the_window_pushes_a_kernel_s_slot_addresses_below_its_tail_word() { } } -/// What [`many_in`]`(fragment, reads)` compiles to on `stem`'s `Device::from_queries` profile -/// under the identity domains: its pushed fields, which a tail word ends, and the uses of the -/// tail's test, a compare of the word's load that a select or a branch takes as its condition: -/// the selects and the branches whose condition it is, and the module's returns. Checks the -/// module passes L3 and holds one such test. -fn tail_test_uses(stem: &str, fragment: bool, reads: u32) -> Option<(usize, usize, usize, usize)> { - use crate::spirv::ir::{BinOp, Inst, Terminator, Type}; - let bc = assemble_text("many", &many_in(fragment, reads))?; - let desc = crate::pipeline::testing::description(stem).unwrap_or_else(|e| panic!("{e}")); - let device = Device::from_queries(desc, identity()).unwrap_or_else(|e| panic!("{e}")); - let p = device.profile(); - let (a, plan, m) = compile_kept(&bc, "many", p).unwrap_or_else(|e| panic!("{stem}: {e}")); - link_and_validate(&a, p).unwrap_or_else(|e| panic!("{stem}: L3: {e}")); - assert!(plan.push.tail_word.is_some(), "{stem}: no tail word"); - let pushed = (plan.push.fields.iter()) - .filter(|f| matches!(f.loc, PushLoc::Push { .. })) - .count(); - let insts: Vec<_> = m.blocks().iter().flat_map(|b| &b.insts).collect(); - let push_load = |v: crate::spirv::ids::Value| { - insts.iter().any(|n| match (&n.inst, n.result) { - (Inst::Load { ptr, .. }, Some(r)) if r == v => { - matches!( - m.value(*ptr).and_then(|d| m.types().get(d.ty)), - Ok(Type::Pointer { - class: crate::spirv::ir::StorageClass::PushConstant, - .. - }) - ) - } - _ => false, - }) - }; - let selects = |c: crate::spirv::ids::Value| { - (insts.iter()) - .filter(|n| matches!(n.inst, Inst::Select { cond, .. } if cond == c)) - .count() - }; - let branches = |c: crate::spirv::ids::Value| { - (m.blocks().iter()) - .filter(|b| matches!(b.term, Terminator::CondBranch { cond, .. } if cond == c)) - .count() - }; - let tests: Vec<_> = (insts.iter()) - .filter_map(|n| match (&n.inst, n.result) { - ( - Inst::Binary { - op: BinOp::INotEqual, - a, - .. - }, - Some(r), - ) if push_load(*a) => Some(r), - _ => None, - }) - .filter(|&c| selects(c) + branches(c) > 0) - .collect(); - assert_eq!(tests.len(), 1, "{stem}: the tail's tests"); - let returns = (m.blocks().iter()) - .filter(|b| matches!(b.term, Terminator::Return)) - .count(); - Some((pushed, selects(tests[0]), branches(tests[0]), returns)) -} - -/// On `PROFILES` and in `runtime-floor`'s window, [`many_in`]`(true, 3)`, a fragment function, -/// pushes its 3 slot addresses below its tail word, and its straight-line module returns once: -/// the tail's test, a compare of the word's load, is the condition of one select per other pushed -/// field and of no branch (`EmitCx::fold_tail`), so the body depends on the tail through those -/// values alone. AMD's open driver (2025.Q2.1) dies making a fragment stage whose body runs under -/// a never-taken return there and holds a loop of convergent instructions under -/// `MaximallyReconvergesKHR`. +/// On `PROFILES` and in `runtime-floor`'s window, [`many_of`]`(3)` pushes its 4 slot addresses +/// below its tail word, and its straight-line module returns once: the tail's test, a compare of +/// the word's load, is the condition of one select per other pushed field and of no branch +/// (`EmitCx::fold_tail`), so the body depends on the tail through those values alone. AMD's open +/// driver (2025.Q2.1) dies making a fragment stage whose body runs under a never-taken return +/// there and holds a loop of convergent instructions under `MaximallyReconvergesKHR`. #[test] -fn a_render_stage_s_tail_folds_into_its_other_pushed_fields_with_no_branch() { +fn the_floor_s_tail_folds_into_the_other_pushed_fields_with_no_branch() { + use crate::spirv::ir::{BinOp, Inst, Terminator, Type}; + let reads = 3; + let Some(bc) = assemble_text("many", &many_of(reads)) else { + return; + }; for stem in PROFILES.iter().copied().chain(["runtime-floor"]) { - let Some((pushed, selects, branches, returns)) = tail_test_uses(stem, true, 3) else { - return; + let desc = crate::pipeline::testing::description(stem).unwrap_or_else(|e| panic!("{e}")); + let device = Device::from_queries(desc, identity()).unwrap_or_else(|e| panic!("{e}")); + let p = device.profile(); + let (a, plan, m) = compile_kept(&bc, "many", p).unwrap_or_else(|e| panic!("{stem}: {e}")); + link_and_validate(&a, p).unwrap_or_else(|e| panic!("{stem}: L3: {e}")); + assert!(plan.push.tail_word.is_some(), "{stem}: no tail word"); + let pushed = (plan.push.fields.iter()) + .filter(|f| matches!(f.loc, PushLoc::Push { .. })) + .count(); + assert_eq!(pushed, (reads + 1) as usize, "{stem}"); + let insts: Vec<_> = m.blocks().iter().flat_map(|b| &b.insts).collect(); + let push_load = |v: crate::spirv::ids::Value| { + insts.iter().any(|n| match (&n.inst, n.result) { + (Inst::Load { ptr, .. }, Some(r)) if r == v => { + matches!( + m.value(*ptr).and_then(|d| m.types().get(d.ty)), + Ok(Type::Pointer { + class: crate::spirv::ir::StorageClass::PushConstant, + .. + }) + ) + } + _ => false, + }) }; - assert_eq!(pushed, 3, "{stem}"); + // The tail's tests: a compare of a push load that some select takes as its condition. + let tests: Vec<_> = (insts.iter()) + .filter_map(|n| match (&n.inst, n.result) { + ( + Inst::Binary { + op: BinOp::INotEqual, + a, + .. + }, + Some(r), + ) if push_load(*a) => Some(r), + _ => None, + }) + .filter(|c| { + (insts.iter()).any(|n| matches!(n.inst, Inst::Select { cond, .. } if cond == *c)) + }) + .collect(); + assert_eq!(tests.len(), 1, "{stem}: the tail's tests"); + let test = tests[0]; + let selects = (insts.iter()) + .filter(|n| matches!(n.inst, Inst::Select { cond, .. } if cond == test)) + .count(); assert_eq!(selects, pushed, "{stem}: one select per other pushed field"); + let branches = (m.blocks().iter()) + .filter(|b| matches!(b.term, Terminator::CondBranch { cond, .. } if cond == test)) + .count(); assert_eq!(branches, 0, "{stem}: a branch on the tail"); + let returns = (m.blocks().iter()) + .filter(|b| matches!(b.term, Terminator::Return)) + .count(); assert_eq!(returns, 1, "{stem}: the module's returns"); println!("{stem}: the tail folds into {selects} pushed fields; one return"); } } -/// On `PROFILES` and in `runtime-floor`'s window, [`many_of`]`(3)`, a kernel, pushes its 4 slot -/// addresses below its tail word and returns at entry where the word is not zero: the tail's -/// test, a compare of the word's load in the first block, is the condition of one branch, whose -/// arm returns, and of no select (`EmitCx::emit_tail_guard`), so the module returns twice and -/// every pushed field reads its member's load alone. -#[test] -fn a_kernel_returns_at_entry_where_its_tail_holds_what_is_never_pushed() { - for stem in PROFILES.iter().copied().chain(["runtime-floor"]) { - let Some((pushed, selects, branches, returns)) = tail_test_uses(stem, false, 3) else { - return; - }; - assert_eq!(pushed, 4, "{stem}"); - assert_eq!(selects, 0, "{stem}: a select on the tail"); - assert_eq!(branches, 1, "{stem}: the branch on the tail"); - assert_eq!(returns, 2, "{stem}: the module's returns"); - println!("{stem}: the tail's test returns at entry; {pushed} pushed fields, no select"); - } -} - /// A kernel storing, at its position in the grid `y · grid.x + x`, the grid's threads along `x` and /// `y` (bits 0-7, 8-15) and its threadgroups along `x` and `y` (bits 16-23, 24-31). fn grid_kernel(name: &str) -> String { diff --git a/docs/API.md b/docs/API.md index 34a955bea..b037fa401 100644 --- a/docs/API.md +++ b/docs/API.md @@ -169,11 +169,10 @@ and so do the command line, the compile worker and every validation tool. It hol zero word `PushField::TailWord` at `PushPlacement::tail_word`, with which its `push_range` ends; a function that pushes one field of 8 bytes or fewer has none. A driver that uploads a stage's push bytes up to the highest one the stage reads then holds every load it widens from the other - fields. The function reads its tail at its start and tests whether it holds what the consumer - never pushes there (a tail word other than zero, bounds whose two words are both all ones, a - zero-range address of all ones): a kernel returns there, and in a render pipeline's function - each of its other pushed fields reads as null there, with no branch. So the consumer pushes the - tail word zero with the other fields; the bytes of the hole are not read. A kernel that reads a grid builtin reads `PushField::DispatchRegion` on + fields. The function reads its tail at its start, and each of its other pushed fields reads as + null where the tail holds what the consumer never pushes there (a tail word other than zero, + bounds whose two words are both all ones, a zero-range address of all ones), so the consumer + pushes the tail word zero with the other fields; the bytes of the hole are not read. A kernel that reads a grid builtin reads `PushField::DispatchRegion` on every dispatch: a dispatch the host knows states Metal's grid and its piece's first threadgroup there, and an indirect dispatch a zero grid, whose kernel takes `NumWorkgroups` times its workgroup size. It reads its first threadgroup from every region (0 where the