diff --git a/crates/metal2vulkan/src/lower/emit.rs b/crates/metal2vulkan/src/lower/emit.rs index 6300eb3a3..8b7c1f71d 100644 --- a/crates/metal2vulkan/src/lower/emit.rs +++ b/crates/metal2vulkan/src/lower/emit.rs @@ -232,8 +232,8 @@ enum Invariant { /// A fragment function's tile's first word in the pass's tile memory buffer /// (`access::tile_memory::base`), computed at entry (`access::tile_memory::emit_entry`). TileBase, - /// A kernel's slot of the runtime's private arena ([`EmitCx::arena_slot`]), computed at entry - /// (`dispatch::emit_entry`). + /// A kernel's slot of the runtime's private arena ([`EmitCx::arena_slot`]), computed in the + /// function's first block. ArenaSlot, /// The table word of the argument buffer's sampler of a handle, tested for a cubic filter /// (`sampler::emit`'s reach test): an operation through the same handle where an earlier test @@ -319,6 +319,15 @@ impl<'a> EmitCx<'a> { Some(at) == self.entry_block || Some(at) == self.hooks_block } + /// Record the function's entry block before the entry hooks run: a hook that runs after one + /// closed a construct (the floor's tail guard) recalls what the first block holds, a push + /// field [`EmitCx::load_push_fields`] loaded there, rather than loading it again where the + /// hooks stand. + fn begin_hooks(&mut self, fb: &FunctionBuilder<'_>) -> BResult<()> { + self.entry_block = fb.entry_block(); + Ok(()) + } + /// Record the open block as the one the entry hooks end in, where the walk starts. fn end_hooks(&mut self, fb: &FunctionBuilder<'_>) -> BResult<()> { self.hooks_block = fb.current_block(); @@ -405,8 +414,11 @@ impl<'a> EmitCx<'a> { /// The device address of the invocation's slot of the runtime's memory that holds the /// kernel's private arena (`dispatch::KernelDecl::arena_slot`, of the pushed /// `PushField::PrivateArenaAddress` and the slot's bytes, `RuntimeFact::PrivateArena`), - /// computed once where it dominates: `dispatch::emit_entry` computes it in the function's - /// first block. + /// computed once in the function's first block, wherever it is first asked for: its operands + /// are that push field, which [`EmitCx::load_push_fields`] loads there, the invocation's + /// built-ins and constants, so it dominates every access of the arena. Made where it is asked + /// for, it would be made again in every block of the body: `dispatch::emit_entry` asks after + /// the floor's tail guard closed a construct, and later hooks may close more before the walk. pub(crate) fn arena_slot(&mut self, fb: &mut FunctionBuilder<'_>) -> BResult { if let Some(v) = self.recall(fb, Invariant::ArenaSlot) { return Ok(v); @@ -418,13 +430,15 @@ impl<'a> EmitCx<'a> { let Some(slot_bytes) = slot_bytes else { return Err(self.fail("a private arena in device memory without its slot's bytes")); }; - let arena = self.push_field(fb, PushField::PrivateArenaAddress)?; let decl: &Declared = self.decl; let Some(kernel) = decl.families.dispatch.kernel.as_ref() else { return Err(self.fail("a private arena in device memory without its kernel")); }; - let v = kernel.arena_slot(fb, arena, slot_bytes)?; - self.remember(fb, Invariant::ArenaSlot, v); + let v = fb.in_entry_block(|fb| { + let arena = self.push_field(fb, PushField::PrivateArenaAddress)?; + kernel.arena_slot(fb, arena, slot_bytes) + })?; + self.remember_at_entry(fb, Invariant::ArenaSlot, v); Ok(v) } @@ -499,18 +513,22 @@ impl<'a> EmitCx<'a> { /// Where the plan's placement ends with a tail (`lower::push::tail`): read it from the push /// block, and return where it holds the value the consumer never pushes there - /// ([`crate::lower::push::emit_tail_guard`]). + /// ([`crate::lower::push::emit_tail_guard`]). 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 emit_tail_guard(&mut self, fb: &mut FunctionBuilder<'_>) -> BResult<()> { let Some(field) = crate::lower::push::tail(&self.plan.push) else { return Ok(()); }; let member = (self.decl.push.iter()).find(|m| m.field == field); - match (member, self.decl.push_global) { - (Some(member), Some(push)) => { - crate::lower::push::emit_tail_guard(fb, push, member.index, field) - } - _ => Err(self.fail("a placed tail the push block does not hold")), - } + let (Some(member), Some(push)) = (member, self.decl.push_global) else { + return Err(self.fail("a placed tail the push block does not hold")); + }; + let value = match field != PushField::TailWord && !self.derives(field) { + true => self.push_field(fb, field)?, + false => Self::load_member(fb, push, member.index)?, + }; + crate::lower::push::emit_tail_guard(fb, value, field) } /// Checked slot `slot`'s bounds (`PushField::SlotBounds`), split: its buffer's bytes before @@ -589,44 +607,52 @@ impl<'a> EmitCx<'a> { Ok(v) } + /// Whether the function derives push field `field` from something other than its own + /// member or `ArgumentTable` entry ([`EmitCx::load_push_field`]). A device-replay variant + /// reads a slot's Metal address from its root entry, and its dispatch region from the region + /// record of its command and region; a flat variant reads its grid from its dispatch's region + /// record, and a folded variant its region and group counts; a merged draw's functions read + /// their command's slot tables. + fn derives(&self, field: PushField) -> bool { + let flat = self + .plan + .dispatch + .as_ref() + .is_some_and(|d| d.flat_grid || d.folded_groups); + let families = &self.plan.families; + match field { + PushField::RootTableAddress => { + families.stage_io.merged.is_some() || families.stage_io.merged_fragment.is_some() + } + PushField::SlotGuestBase(_) => families.access.replay, + PushField::DispatchRegion => families.access.replay || flat, + _ => false, + } + } + /// Load push field `field` in the open block. fn load_push_field( &mut self, fb: &mut FunctionBuilder<'_>, field: PushField, ) -> BResult { - // A device-replay variant reads a slot's Metal address from its root entry, and its - // dispatch region from the region record of its command and region; a flat variant reads - // its grid from its dispatch's region record, and a folded variant its region and group - // counts. - let flat = self - .plan - .dispatch - .as_ref() - .is_some_and(|d| d.flat_grid || d.folded_groups); - match field { - // A merged draw's vertex function reads its command's slot table. - PushField::RootTableAddress if self.plan.families.stage_io.merged.is_some() => { - return match self.merged_draw { - Some(m) => Ok(m.table), - None => Err(self.fail("a merged draw's slot table read before its entry")), - }; - } - // A merged draw's fragment function reads its command's fragment slot table. - PushField::RootTableAddress - if self.plan.families.stage_io.merged_fragment.is_some() => - { - return self.merged_fragment_table.ok_or_else(|| { + if self.derives(field) { + return match field { + // A merged draw's vertex function reads its command's slot table. + PushField::RootTableAddress if self.plan.families.stage_io.merged.is_some() => { + match self.merged_draw { + Some(m) => Ok(m.table), + None => Err(self.fail("a merged draw's slot table read before its entry")), + } + } + // A merged draw's fragment function reads its command's fragment slot table. + PushField::RootTableAddress => self.merged_fragment_table.ok_or_else(|| { self.fail("a merged draw's fragment slot table read before its entry") - }); - } - PushField::SlotGuestBase(slot) if self.plan.families.access.replay => { - return access::replay_guest_base(self, fb, slot) - } - PushField::DispatchRegion if self.plan.families.access.replay || flat => { - return access::replay_region(self, fb) - } - _ => {} + }), + PushField::SlotGuestBase(slot) => access::replay_guest_base(self, fb, slot), + PushField::DispatchRegion => access::replay_region(self, fb), + _ => Err(self.fail("a derived push field without its source")), + }; } let member = self.decl.push.iter().find(|m| m.field == field).copied(); let (Some(member), Some(g)) = (member, self.decl.push_global) else { @@ -634,8 +660,13 @@ impl<'a> EmitCx<'a> { // access family declares and reads. return access::table_field(self, fb, field); }; - let base = fb.module().global_value(g)?; - let index = fb.u32_const(member.index)?; + Self::load_member(fb, g, member.index) + } + + /// Load member `index` of push block `push` in the open block. + fn load_member(fb: &mut FunctionBuilder<'_>, push: GlobalId, index: u32) -> BResult { + let base = fb.module().global_value(push)?; + let index = fb.u32_const(index)?; let index = fb.module().const_value(index)?; let ptr = fb.access_chain(base, &[index])?; fb.load(ptr, MemAccess::default()) @@ -1515,7 +1546,8 @@ pub fn emit_module(e: &Entry, plan: &Plan, m: &mut Meter) -> Result Result<(), String> { } } -/// In the open block of a function whose push block `push` holds the stage's tail `field` as -/// member `member` ([`tail`]): read it, and return from the function where it holds the value the +/// 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: return from the function where 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. 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 emit_tail_guard( fb: &mut crate::spirv::builder::FunctionBuilder<'_>, - push: crate::spirv::ids::GlobalId, - member: u32, + value: crate::spirv::ids::Value, field: PushField, ) -> crate::spirv::error::BResult<()> { use crate::spirv::builder::constructs::{ArmEnd, ArmFn}; - use crate::spirv::ir::{BinOp, ConstBits, Constant, MemAccess}; - let base = fb.module().global_value(push)?; - let index = fb.u32_const(member)?; - let index = fb.module().const_value(index)?; - let ptr = fb.access_chain(base, &[index])?; - let value = fb.load(ptr, MemAccess::default())?; + use crate::spirv::ir::{BinOp, ConstBits, Constant}; let set = match (field, shape(field)) { (PushField::TailWord, _) => { let zero = fb.u32_const(0)?; diff --git a/crates/metal2vulkan/src/tests/engine_device_arena.rs b/crates/metal2vulkan/src/tests/engine_device_arena.rs new file mode 100644 index 000000000..1fe281607 --- /dev/null +++ b/crates/metal2vulkan/src/tests/engine_device_arena.rs @@ -0,0 +1,145 @@ +//! A kernel's private arena in the runtime's device memory (`memory::plan::ArenaLayout::device`) +//! under the identity domains, the runtime's. +//! +//! Owned synthetic kernel `branches` keeps a private array of 7176 words (28,704 bytes, past the +//! floor's 16 KiB, so it lives in the runtime's memory): it writes the word its thread ID picks in +//! the entry block, reads one in one arm of a branch, writes one and reads one in the other, and +//! reads one after the branch joins. +//! +//! On every committed profile `Device::from_queries` derives under the identity domains whose +//! 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 (`push::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. +//! +//! `llvm-as` assembles the kernel; without it the test skips visibly. + +use super::engine_dispatch::field_loads; +use super::engine_word_phases::identity_profiles; +use crate::lower::select::LowerInputs; +use crate::pipeline::testing::{compile_with, link_and_validate, typed_module_with, AssembleError}; +use crate::spirv::ir::{BinOp, Inst, TypedModule, ValueOrigin}; + +/// The arena's words. +const WORDS: u32 = 7176; + +/// The module holding `branches`. +fn module() -> Option> { + let n = WORDS; + let text = format!( + r#"; Owned synthetic kernel: a private array of {n} words reached in several blocks. +source_filename = "device_arena.metal" + +define void @branches(ptr addrspace(1) %out, i32 %gid) {{ +entry: + %a = alloca [{n} x i32], align 4 + %w = urem i32 %gid, {n} + %p = getelementptr inbounds [{n} x i32], ptr %a, i32 0, i32 %w + store i32 %gid, ptr %p, align 4 + %c = icmp ult i32 %gid, 4 + br i1 %c, label %left, label %right +left: + %r1 = mul i32 %gid, 7 + %i1 = urem i32 %r1, {n} + %q1 = getelementptr inbounds [{n} x i32], ptr %a, i32 0, i32 %i1 + %x1 = load i32, ptr %q1, align 4 + br label %done +right: + %r2 = mul i32 %gid, 11 + %i2 = urem i32 %r2, {n} + %q2 = getelementptr inbounds [{n} x i32], ptr %a, i32 0, i32 %i2 + store i32 %r2, ptr %q2, align 4 + %x2 = load i32, ptr %p, align 4 + br label %done +done: + %x = phi i32 [ %x1, %left ], [ %x2, %right ] + %r3 = mul i32 %gid, 13 + %i3 = urem i32 %r3, {n} + %q3 = getelementptr inbounds [{n} x i32], ptr %a, i32 0, i32 %i3 + %y = load i32, ptr %q3, align 4 + %s = add i32 %x, %y + %g = zext i32 %gid to i64 + %o = getelementptr inbounds i32, ptr addrspace(1) %out, i64 %g + store i32 %s, ptr addrspace(1) %o, align 4 + ret void +}} + +!air.kernel = !{{!0}} +!0 = !{{ptr @branches, !1, !2}} +!1 = !{{}} +!2 = !{{!3, !4}} +!3 = !{{i32 0, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"out"}} +!4 = !{{i32 1, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"gid"}} +"# + ); + assemble(&text) +} + +/// `text` assembled, or `None` where `llvm-as` is missing. +fn assemble(text: &str) -> Option> { + match metal2vulkan_devtools::llvm_assemble_text(text) { + Ok(b) => Some(b), + Err(AssembleError::Missing(why)) => { + eprintln!("SKIPPED: {why}"); + None + } + Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected the kernels: {why}"), + } +} + +/// How many times `m` derives the invocation's slot of an arena of `slot_bytes` a slot: the +/// multiplications by the slot's bytes (`dispatch::KernelDecl::arena_slot`, `i ยท slot_bytes`). +fn slot_derivations(m: &TypedModule, slot_bytes: u32) -> usize { + let is_bytes = |v| match m.value(v).map(|d| d.origin) { + Ok(ValueOrigin::Const(c)) => { + m.consts().scalar_bits(c).map(|b| b.0) == Some(u64::from(slot_bytes)) + } + _ => false, + }; + m.blocks() + .iter() + .flat_map(|b| &b.insts) + .filter(|n| { + matches!(&n.inst, Inst::Binary { op: BinOp::IMul, a, b, .. } + if is_bytes(*a) || is_bytes(*b)) + }) + .count() +} + +/// The slot is derived once and every push field, the arena's address among them, is loaded +/// once, however many blocks reach the arena: with the default lowering inputs, and as a kernel +/// whose threadgroups may be partial (`LowerInputs::partial_threadgroups`), whose entry hooks +/// return past the grid in a construct after the slot is asked for. +#[test] +fn the_arena_slot_is_made_once_and_its_push_field_read_once() { + let Some(bc) = module() else { + return; + }; + let partial = LowerInputs { + partial_threadgroups: true, + ..LowerInputs::new() + }; + let mut checked = 0; + for (stem, p) in identity_profiles() { + for (what, inputs) in [("default", &LowerInputs::new()), ("partial", &partial)] { + let a = compile_with(&bc, "branches", &p, inputs) + .unwrap_or_else(|e| panic!("{stem} {what}: {e}")); + link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem} {what}: L3: {e}")); + let (plan, m) = typed_module_with(&bc, "branches", &p, inputs) + .unwrap_or_else(|e| panic!("{stem} {what}: {e}")); + if !plan.families.access.local.private_device { + continue; + } + checked += 1; + assert_eq!(slot_derivations(&m, 4 * WORDS), 1, "{stem} {what}"); + let loads = field_loads(&m); + assert!(!loads.is_empty(), "{stem} {what}: no push field read"); + assert!(loads.values().all(|&n| n == 1), "{stem} {what}: {loads:?}"); + } + } + assert!( + checked > 0, + "no identity profile keeps the arena in device memory" + ); +} diff --git a/crates/metal2vulkan/src/tests/engine_dispatch.rs b/crates/metal2vulkan/src/tests/engine_dispatch.rs index e394c6280..cafdd35a3 100644 --- a/crates/metal2vulkan/src/tests/engine_dispatch.rs +++ b/crates/metal2vulkan/src/tests/engine_dispatch.rs @@ -786,7 +786,7 @@ fn a_position_first_used_in_sibling_arms_is_derived_once() { /// How many times `m` loads each push-block or `ArgumentTable` member: a load through an access /// chain with constant indices into a `PushConstant` or `Uniform` variable, keyed by the chain. -fn field_loads(m: &TypedModule) -> BTreeMap<(u32, Vec), usize> { +pub(super) fn field_loads(m: &TypedModule) -> BTreeMap<(u32, Vec), usize> { let chains: BTreeMap)> = m .blocks() .iter() diff --git a/crates/metal2vulkan/src/tests/mod.rs b/crates/metal2vulkan/src/tests/mod.rs index d84214ee4..9a2a9d7c1 100644 --- a/crates/metal2vulkan/src/tests/mod.rs +++ b/crates/metal2vulkan/src/tests/mod.rs @@ -45,6 +45,7 @@ mod engine_dead_reads; mod engine_debug_info; mod engine_declared_varyings; mod engine_depth_range; +mod engine_device_arena; mod engine_device_replay; mod engine_dispatch; mod engine_divergent_barriers;