Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
244 changes: 225 additions & 19 deletions d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,12 @@
//! condition was made of (both terms of an `and` that held, the opposite
//! comparison). The lowering branches on a lane's condition and then
//! guards each instruction behind the branch with the same condition.
//! - [`LOADS`]: within a block, a read of the same place as an earlier read
//! gives that one's result while no store, atomic, barrier or other call
//! with an effect stands between them (another thread's unsynchronised
//! store may fall between any two reads or before both: the title's code
//! cannot tell which).
//! - [`LOADS`]: a read of the same place as an earlier dominating read gives
//! that one's result while no store, atomic, barrier or other call with an
//! effect can occur between them (including across blocks along the
//! dominator tree when no path from the immediate dominator writes; wave
//! and quad operations stay block-local because active lanes can change
//! across branches).
//!
//! - [`GUARDS`]: a value kept for the lanes a guard leaves out (`select(g, new, old)`,
//! what a console instruction under EXEC writes) that is read only where `g` holds, or by
Expand Down Expand Up @@ -815,22 +816,72 @@ impl Module {
}
}
}
// Precompute per-block write presence and immediate dominators so `LOADS`
// can reuse dominating `Effect::Reads` across blocks whenever no path
// from the immediate dominator can execute an `Effect::Writes`.
let (has_write, idom) = if passes & LOADS != 0 {
let has_write: Vec<bool> = self
.blocks
.iter()
.map(|blk| {
blk.body
.iter()
.any(|&i| self.class(&effects, i) == Effect::Writes)
})
.collect();
let mut idom = vec![None; self.blocks.len()];
for (p, children) in tree.children.iter().enumerate() {
for &c in children {
idom[c] = Some(p);
}
}
(has_write, idom)
} else {
(Vec::new(), Vec::new())
};
let path_has_write = |b: usize, dom: usize| -> bool {
if tree.preds[b].as_slice() == [dom] {
return false;
}
let mut visited = vec![false; has_write.len()];
let mut stack = Vec::new();
for &p in &tree.preds[b] {
if p != dom && !visited[p] {
visited[p] = true;
stack.push(p);
}
}
while let Some(u) = stack.pop() {
if has_write[u] {
return true;
}
for &p in &tree.preds[u] {
if p != dom && !visited[p] {
visited[p] = true;
stack.push(p);
}
}
}
false
};
// The values every path to the block being walked has computed
// (those of the blocks above it in the tree, and its own so far).
let mut known: HashMap<Key, V> = HashMap::new();
// The reads of the block being walked since its last store.
let mut read: HashMap<Key, V> = HashMap::new();
// Dominating memory reads still valid (no `Effect::Writes` since).
let mut dom_reads: HashMap<Key, V> = HashMap::new();
// Wave/quad operations in the current block (active lanes stay fixed within a block).
let mut lane_reads: HashMap<Key, V> = HashMap::new();
let mut facts = Facts::default();
let (yes, no) = (self.bool(true), self.bool(false));
enum Step {
Enter(usize),
Leave(Vec<Key>, Learned),
Leave(Vec<Key>, Learned, Vec<Key>, Option<HashMap<Key, V>>),
}
let mut steps = vec![Step::Enter(0)];
while let Some(step) = steps.pop() {
let b = match step {
Step::Enter(b) => b,
Step::Leave(keys, learned) => {
Step::Leave(keys, learned, added_reads, saved_reads) => {
for k in keys {
known.remove(&k);
}
Expand All @@ -840,10 +891,19 @@ impl Module {
for k in learned.compares {
facts.compares.remove(&k);
}
if let Some(prev) = saved_reads {
dom_reads = prev;
} else {
for k in added_reads {
dom_reads.remove(&k);
}
}
continue;
}
};
let mut added = Vec::new();
let mut added_reads = Vec::new();
let mut saved_reads = None;
// Reached from one block alone, by one side of its branch: the
// condition is that side's, here and in every block below.
let mut learned = Learned::default();
Expand All @@ -859,7 +919,13 @@ impl Module {
Some(false) => no,
None => v,
};
read.clear();
lane_reads.clear();
if passes & LOADS != 0
&& b != 0
&& idom[b].is_none_or(|dom| path_has_write(b, dom))
{
saved_reads = Some(std::mem::take(&mut dom_reads));
}
// Two joins of the same values from the same blocks are one.
if passes & REUSE != 0 && self.blocks[b].phis.len() > 1 {
let mut joins: HashMap<Vec<(usize, V)>, V> = HashMap::new();
Expand Down Expand Up @@ -926,21 +992,46 @@ impl Module {
known.insert(key.clone(), V::Inst(i));
added.push(key);
}
// Reads of memory, and wave operations (the same lanes run
// the whole block): the block's own earlier one.
// Reads of memory (valid across blocks along the dominator tree
// while no `Effect::Writes` intervenes), and wave operations
// (block-local: the same lanes run the whole block).
if passes & LOADS != 0
&& matches!(class, Effect::Reads | Effect::Lanes)
&& let Some(key) = self.key(i)
{
if let Some(&first) = read.get(&key) {
repl[i as usize] = Some(first);
changed = true;
continue;
match class {
Effect::Reads => {
if let Some(&first) = dom_reads.get(&key) {
repl[i as usize] = Some(first);
changed = true;
continue;
}
if saved_reads.is_none() {
added_reads.push(key.clone());
}
dom_reads.insert(key, V::Inst(i));
}
Effect::Lanes => {
if let Some(&first) = lane_reads.get(&key) {
repl[i as usize] = Some(first);
changed = true;
continue;
}
lane_reads.insert(key, V::Inst(i));
}
_ => {}
}
read.insert(key, V::Inst(i));
}
if class == Effect::Writes {
read.clear();
lane_reads.clear();
if saved_reads.is_none() {
for k in added_reads.drain(..) {
dom_reads.remove(&k);
}
saved_reads = Some(std::mem::take(&mut dom_reads));
} else {
dom_reads.clear();
}
}
kept.push(i);
}
Expand All @@ -949,7 +1040,7 @@ impl Module {
let c = known_bit(&facts, resolve(&repl, c));
self.blocks[b].term = Some(Term::CondBr(c, t, f));
}
steps.push(Step::Leave(added, learned));
steps.push(Step::Leave(added, learned, added_reads, saved_reads));
for &c in tree.children[b].iter().rev() {
steps.push(Step::Enter(c));
}
Expand Down Expand Up @@ -2621,6 +2712,121 @@ mod tests {
g.k.m
}

#[test]
fn cross_block_reads_reuse_dominating_load_without_writes() {
let Diamond {
k: Kit { mut m, b: entry, reads, writes, .. },
then,
other,
join,
..
} = diamond();
let seven = m.i32(7);
let i32t = m.int(32);
let top = m.call(entry, reads, vec![seven, seven]);
let in_then = m.call(then, reads, vec![seven, seven]);
let in_other = m.call(other, reads, vec![seven, seven]);
let joined = m.phi(join, i32t);
m.set_phi(joined, vec![(in_then, then), (in_other, other)]);
let in_join = m.call(join, reads, vec![seven, seven]);
let sum = m.bin(join, Bin::Add, joined, in_join);
m.call(join, writes, vec![sum, top]);
m.optimise(LOADS | DEAD);
let stores = super::tests::stores(&m, join);
assert_eq!(stores.len(), 1);
let V::Inst(sum_id) = stores[0][0] else { panic!() };
assert!(
matches!(m.insts[sum_id as usize].op, Op::Bin(Bin::Add, _, z) if z == top),
"join should reuse entry's dominating read when neither branch writes"
);
assert!(
m.blocks[then].body.is_empty() && m.blocks[other].body.is_empty(),
"redundant reads in both branches should be eliminated"
);
assert_eq!(
m.blocks[join].body.len(),
2,
"join should keep only sum and the store (redundant read eliminated)"
);
m.write();
}

#[test]
fn cross_block_reads_invalidated_when_branch_writes() {
let Diamond {
k: Kit { mut m, b: entry, reads, writes, .. },
then,
other,
join,
..
} = diamond();
let seven = m.i32(7);
let top = m.call(entry, reads, vec![seven, seven]);
// `then` writes, so a read after the write in `then` and any read in `join` must stay fresh.
m.call(then, writes, vec![top, seven]);
let after_write = m.call(then, reads, vec![seven, seven]);
m.call(then, writes, vec![after_write, seven]);
// `other` is a sibling of `then` and has no write before its read: it can still reuse `top`.
let in_other = m.call(other, reads, vec![seven, seven]);
m.call(other, writes, vec![in_other, seven]);
// `join` is reachable from `then` (which wrote), so it must NOT reuse `top`.
let in_join = m.call(join, reads, vec![seven, seven]);
m.call(join, writes, vec![in_join, seven]);
m.optimise(LOADS | DEAD);
assert_eq!(super::tests::stores(&m, then)[1][0], after_write);
assert_eq!(super::tests::stores(&m, other)[0][0], top, "sibling branch without prior write reuses entry read");
assert_eq!(super::tests::stores(&m, join)[0][0], in_join, "merge after writing branch must not reuse entry read");
m.write();
}

#[test]
fn cross_block_reads_in_loop_respect_backedge_writes() {
// Loop WITH a write in the latch: header must NOT reuse preheader read.
let Kit { mut m, b: entry, reads, writes, .. } = kit();
let header = m.new_block();
let latch = m.new_block();
let exit = m.new_block();
let one = m.i32(1);
let pre = m.call(entry, reads, vec![one, one]);
m.terminate(entry, Term::Br(header));
let in_header = m.call(header, reads, vec![one, one]);
let cond = m.cmp(header, pred::NE, in_header, one);
m.terminate(header, Term::CondBr(cond, latch, exit));
m.call(latch, writes, vec![in_header, pre]);
m.terminate(latch, Term::Br(header));
m.call(exit, writes, vec![in_header, pre]);
m.terminate(exit, Term::Ret);
m.optimise(LOADS | DEAD);
assert_eq!(
super::tests::stores(&m, exit)[0][0],
in_header,
"loop header must re-read when backedge writes"
);
m.write();

// Loop WITHOUT any write: header reuses preheader read.
let Kit { mut m, b: entry, reads, writes, .. } = kit();
let header = m.new_block();
let latch = m.new_block();
let exit = m.new_block();
let one = m.i32(1);
let pre = m.call(entry, reads, vec![one, one]);
m.terminate(entry, Term::Br(header));
let in_header = m.call(header, reads, vec![one, one]);
let cond = m.cmp(header, pred::NE, in_header, one);
m.terminate(header, Term::CondBr(cond, latch, exit));
m.terminate(latch, Term::Br(header));
m.call(exit, writes, vec![in_header, pre]);
m.terminate(exit, Term::Ret);
m.optimise(LOADS | DEAD);
assert_eq!(
super::tests::stores(&m, exit)[0][0],
pre,
"write-free loop header should reuse preheader read"
);
m.write();
}

#[test]
fn every_pass_leaves_what_random_programs_store() {
let mut removed = 0;
Expand Down