Translator: a device private arena's slot is made in the first block, and each push member is loaded once
EmitCx::arena_slot remembered the slot where it was first asked for.
dispatch::emit_entry asks in the entry hooks, after the floor's tail
guard (push::emit_tail_guard) closed a construct, and the memo keeps an
entry only where it was made in the entry block, the block the hooks
end in or the open block's spine: a later hook construct leaves the
slot behind, and every block that reaches the arena derives it again
(24 instructions each). Lane ksizeread counted 2,965 such derivations
in the 780M library's 628,489-weight kernel.
- The slot is now made in the function's first block wherever it is
first asked for (FunctionBuilder::in_entry_block, remembered at
entry): its operands are the pushed arena address load_push_fields
loads there, the invocation's built-ins and constants.
- The entry block is recorded before the hooks run (begin_hooks), so a
hook after the tail guard's construct recalls the push fields the
first block loaded instead of loading them again.
- The tail guard reads the tail field from that same load where the
function reads the field from its member (EmitCx::derives names the
fields a function derives elsewhere); the tail word, and a derived
field, are still loaded by the guard.
Test: tests/engine_device_arena.rs, an owned kernel whose 7176-word
arena is reached in four blocks. On every identity profile, with the
default inputs and with partial_threadgroups, the slot is derived once
and each push member is loaded once. Without this change, on the same
kernel at 0429ff1bd4 (m3-max-64752), one member was loaded twice by
default and one three times with partial threadgroups; the slot was
derived once there, so the kernel does not reproduce the re-derivation
the 628,489 kernel shows.
This commit is contained in:
1 parent
65cd6f18f9
commit
690dc4e44e
5 files changed
+231
-59
No files matched your search
@@ -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<SValue> {
|
||||
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<SValue> {
|
||||
// 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<SValue> {
|
||||
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<Emitted, Err
|
||||
// the walk.
|
||||
let r = em
|
||||
.cx
|
||||
.load_push_fields(&mut fb)
|
||||
.begin_hooks(&fb)
|
||||
.and_then(|()| em.cx.load_push_fields(&mut fb))
|
||||
// The floor's tail, read in the first block (`lower::push::emit_tail_guard`).
|
||||
.and_then(|()| em.cx.emit_tail_guard(&mut fb))
|
||||
.and_then(|()| dispatch::emit_entry(&mut em.cx, &mut fb))
|
||||
|
||||
@@ -420,24 +420,18 @@ pub fn check_floor(placement: &PushPlacement) -> 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)?;
|
||||
|
||||
@@ -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<Vec<u8>> {
|
||||
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<Vec<u8>> {
|
||||
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"
|
||||
);
|
||||
}
|
||||
@@ -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<u32>), usize> {
|
||||
pub(super) fn field_loads(m: &TypedModule) -> BTreeMap<(u32, Vec<u32>), usize> {
|
||||
let chains: BTreeMap<u32, (u32, Vec<u32>)> = m
|
||||
.blocks()
|
||||
.iter()
|
||||
|
||||
@@ -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;
|
||||
|
||||
Reference in new issue
Block a user