shader: coalesce single-pred blocks and fold dead diamonds in DXIL opt

This commit is contained in:
nidea1
2026-11-29 16:04:15 +03:00
parent 829188e969
commit dbdd6adafc

View File

@ -466,6 +466,12 @@ impl Module {
}
if passes & FOLD != 0 {
changed |= self.prune();
if passes & DEAD != 0 {
// Drop dead ALU and unread phis first so dead diamonds
// become empty trampolines for `simplify_cfg`.
self.drop_dead_insts();
}
changed |= self.simplify_cfg();
}
if passes & LICM != 0 {
changed |= self.licm();
@ -2594,6 +2600,237 @@ impl Module {
true
}
/// [`FOLD`]: simplifies the reachable CFG by folding same-target
/// conditional branches (`CondBr(_, t, t)` -> `Br(t)`), threading empty
/// phi-free trampolines into phi-free targets, and coalescing
/// single-predecessor unconditional chains (`a: Br(b)` into `a`).
///
/// Keeping fallthrough blocks unified exposes cross-block [`LOADS`] reuse
/// and [`BARRIERS`] coalescing on the next round and trims DXIL blocks.
fn simplify_cfg(&mut self) -> bool {
let n = self.blocks.len();
if n <= 1 {
return false;
}
let mut reached = self.reached();
let mut pred_count = vec![0usize; n];
for b in 0..n {
if !reached[b] {
continue;
}
for &s in successors(self.blocks[b].term).iter() {
pred_count[s] += 1;
}
}
let mut repl: Vec<Option<V>> = vec![None; self.insts.len()];
let mut any_changed = false;
let mut any_phi_replaced = false;
loop {
let mut round = false;
// 1. Fold `CondBr(_, t, t)` -> `Br(t)` when every phi in `t`
// agrees on a single incoming value for `b`.
for b in 0..n {
if !reached[b] {
continue;
}
let Some(Term::CondBr(_, t, f)) = self.blocks[b].term else {
continue;
};
if t != f {
continue;
}
let mut can_fold = true;
for &p in &self.blocks[t].phis {
let Op::Phi(incoming) = &self.insts[p as usize].op else {
can_fold = false;
break;
};
let mut vals = incoming
.iter()
.filter(|&&(_, from)| from == b)
.map(|&(v, _)| resolve(&repl, v));
if let Some(first) = vals.next()
&& !vals.all(|v| v == first)
{
can_fold = false;
break;
}
}
if !can_fold {
continue;
}
for &p in &self.blocks[t].phis {
if let Op::Phi(incoming) = &mut self.insts[p as usize].op {
let mut kept_one = false;
incoming.retain(|&(_, from)| {
if from == b {
if kept_one {
return false;
}
kept_one = true;
}
true
});
}
}
self.blocks[b].term = Some(Term::Br(t));
pred_count[t] -= 1;
round = true;
any_changed = true;
}
// 2. Coalesce single-predecessor unconditional fallthrough `a -> b`
// first so chains stay anchored at their head block without an
// extra predecessor scan.
for a in 0..n {
if !reached[a] {
continue;
}
while let Some(Term::Br(b)) = self.blocks[a].term {
if b == 0 || b == a || pred_count[b] != 1 {
break;
}
let mut phi_vals: Vec<(u32, V)> = Vec::new();
let mut ok = true;
for &p in &self.blocks[b].phis {
let Op::Phi(incoming) = &self.insts[p as usize].op else {
ok = false;
break;
};
let mut from_a = incoming
.iter()
.filter(|&&(_, from)| from == a)
.map(|&(v, _)| resolve(&repl, v));
let Some(first) = from_a.next() else {
ok = false;
break;
};
if !from_a.all(|v| v == first) {
ok = false;
break;
}
if let V::Inst(id) = first
&& self.blocks[b].phis.contains(&id)
{
ok = false;
break;
}
phi_vals.push((p, first));
}
if !ok {
break;
}
for (p, v) in phi_vals {
repl[p as usize] = Some(v);
any_phi_replaced = true;
}
let b_body = std::mem::take(&mut self.blocks[b].body);
let b_term = self.blocks[b].term.take();
self.blocks[b].phis.clear();
self.blocks[a].body.extend(b_body);
self.blocks[a].term = b_term;
reached[b] = false;
pred_count[b] = 0;
let succs = successors(b_term);
for (idx, &s) in succs.iter().enumerate() {
if succs[..idx].contains(&s) {
continue;
}
for &q in &self.blocks[s].phis {
if let Op::Phi(incoming) = &mut self.insts[q as usize].op {
for (_, from) in incoming.iter_mut() {
if *from == b {
*from = a;
}
}
}
}
}
round = true;
any_changed = true;
}
}
// 3. Thread jumps through empty phi-free trampolines (`e: Br(t)`)
// into phi-free targets `t` (`e != 0`, `t != e`).
for e in 1..n {
if !reached[e] {
continue;
}
if !self.blocks[e].phis.is_empty() || !self.blocks[e].body.is_empty() {
continue;
}
let Some(Term::Br(t)) = self.blocks[e].term else {
continue;
};
if t == e || !self.blocks[t].phis.is_empty() {
continue;
}
for p in 0..n {
if !reached[p] || p == e {
continue;
}
match self.blocks[p].term {
Some(Term::Br(dst)) if dst == e => {
self.blocks[p].term = Some(Term::Br(t));
pred_count[e] -= 1;
pred_count[t] += 1;
}
Some(Term::CondBr(c, mut a, mut b)) if a == e || b == e => {
if a == e {
a = t;
pred_count[e] -= 1;
pred_count[t] += 1;
}
if b == e {
b = t;
pred_count[e] -= 1;
pred_count[t] += 1;
}
self.blocks[p].term = Some(Term::CondBr(c, a, b));
}
_ => {}
}
}
debug_assert_eq!(pred_count[e], 0);
reached[e] = false;
self.blocks[e].term = None;
pred_count[t] -= 1;
round = true;
any_changed = true;
}
if !round {
break;
}
}
if any_phi_replaced {
for b in 0..n {
if !reached[b] {
continue;
}
if let Some(Term::CondBr(c, t, f)) = self.blocks[b].term {
self.blocks[b].term = Some(Term::CondBr(resolve(&repl, c), t, f));
}
}
let (blocks, insts) = (&self.blocks, &mut self.insts);
for (b, blk) in blocks.iter().enumerate() {
if !reached[b] {
continue;
}
for &i in blk.phis.iter().chain(&blk.body) {
map_operands(&mut insts[i as usize].op, |v| resolve(&repl, v));
}
}
}
any_changed
}
/// Whether instruction `i` must stay whatever reads it.
fn has_effect(&self, effects: &[Effect], i: u32) -> bool {
match &self.insts[i as usize].op {
@ -2603,10 +2840,9 @@ impl Module {
}
}
/// [`DEAD`]: keeps the instructions with an effect, the branch
/// conditions, and what they read, transitively; the rest leave their
/// blocks. Blocks no branch reaches are emptied (they are not written).
fn drop_dead(&mut self) {
/// Removes dead instructions and phis from reachable blocks and empties
/// unreachable blocks (leaving function/global tables to [`Self::drop_dead`]).
fn drop_dead_insts(&mut self) {
let effects = self.effects();
let reached = self.reached();
let mut live = vec![false; self.insts.len()];
@ -2646,6 +2882,13 @@ impl Module {
blk.phis.clear();
}
}
}
/// [`DEAD`]: keeps the instructions with an effect, the branch
/// conditions, and what they read, transitively; the rest leave their
/// blocks. Blocks no branch reaches are emptied (they are not written).
fn drop_dead(&mut self) {
self.drop_dead_insts();
self.drop_unused_functions();
self.drop_unused_globals();
}
@ -3231,14 +3474,17 @@ mod tests {
m.set_phi(q, vec![(p, meet), (y, other)]);
m.call(join, writes, vec![q, q]);
m.optimise(ALL);
assert!(matches!(m.blocks[then].term, Some(Term::Br(t)) if t == deep));
assert_eq!(stores(&m, meet), [[x, x]]);
// `then -> deep -> meet` coalesces straight into `then -> join`.
assert!(matches!(m.blocks[then].term, Some(Term::Br(t)) if t == join));
assert_eq!(stores(&m, then), [[x, x]]);
assert!(m.blocks[meet].phis.is_empty());
assert_eq!(body(&m, deep), 0, "absorbed into then");
assert_eq!(body(&m, meet), 0, "absorbed into then");
assert_eq!(body(&m, never), 0, "emptied: nothing reaches it");
let Op::Phi(incoming) = &m.insts[m.blocks[join].phis[0] as usize].op else {
panic!()
};
assert_eq!(incoming, &vec![(x, meet), (y, other)]);
assert_eq!(incoming, &vec![(x, then), (y, other)]);
let _ = b;
m.write();
}
@ -6835,4 +7081,142 @@ mod tests {
assert_eq!(k.m.float_k(V::Inst(u32::MAX)), None);
assert_eq!(k.m.int_bits(Ty(u32::MAX)), None);
}
#[test]
fn simplify_cfg_coalesces_chains_dead_diamonds_and_unlocks_cross_block_opts() {
// 1. Chain `entry -> b1 -> b2` with chained single-pred phis, duplicate
// shared loads, and adjacent barriers split across block boundaries:
// coalescing into `entry` must unlock both `LOADS` reuse and `BARRIERS`
// elimination on the next round.
let mut k = kit();
let i32t = k.m.int(32);
let void = k.m.void();
let arr = k.m.array(4, i32t);
let lds = k.m.global("lds", arr, 3);
let bty = k.m.func_ty(void, vec![i32t, i32t]);
let barrier = k.m.function("dx.op.barrier", bty, Some(Attr::NoDuplicate), false);
let (k0, k1, k9, k80) = (k.m.i32(0), k.m.i32(1), k.m.i32(9), k.m.i32(80));
let (b1, b2) = (k.m.new_block(), k.m.new_block());
let ptr0 = k.m.element(k.b, lds, k0);
let ld0 = k.m.load(k.b, ptr0);
k.m.call(k.b, barrier, vec![k80, k9]);
k.m.terminate(k.b, Term::Br(b1));
let p1 = k.m.phi(b1, i32t);
k.m.set_phi(p1, vec![(ld0, k.b)]);
// Adjacent barrier across the former `entry -> b1` boundary.
k.m.call(b1, barrier, vec![k80, k9]);
let ld1 = k.m.load(b1, ptr0);
k.m.terminate(b1, Term::Br(b2));
let p2 = k.m.phi(b2, i32t);
k.m.set_phi(p2, vec![(p1, b1)]);
// Duplicate shared load across the former `b1 -> b2` boundary.
let ld2 = k.m.load(b2, ptr0);
let sum = k.m.bin(b2, Bin::Add, p2, ld1);
let sum2 = k.m.bin(b2, Bin::Add, sum, ld2);
k.m.call(b2, k.writes, vec![sum2, k1]);
k.m.terminate(b2, Term::Ret);
k.m.optimise(FOLD | REUSE | LOADS | BARRIERS | DEAD);
// All three blocks coalesced into `entry` alone.
let reached = k.m.reached();
assert_eq!(reached.iter().filter(|&&r| r).count(), 1);
assert!(matches!(k.m.blocks[k.b].term, Some(Term::Ret)));
// The two adjacent barriers across `entry -> b1` coalesced into one.
let barrier_count = k.m.blocks[k.b]
.body
.iter()
.filter(|&&id| {
matches!(
k.m.insts[id as usize].op,
Op::Call(f, _) if k.m.funcs[f as usize].name == "dx.op.barrier"
)
})
.count();
assert_eq!(barrier_count, 1, "cross-block adjacent barrier must coalesce");
// `ld1` and `ld2` (after the barrier) merged into a single load (`ld0` before + one after).
let load_count = k.m.blocks[k.b]
.body
.iter()
.filter(|&&id| matches!(k.m.insts[id as usize].op, Op::Load(_)))
.count();
assert_eq!(load_count, 2, "cross-block duplicate LDS load after barrier must reuse");
k.m.write();
// 2. Empty dead diamond (`CondBr(c, then, other)` where both arms become
// empty `Br(join)` and `join` has no phis) collapses completely into
// a single straight-line block.
let Diamond {
k: Kit { mut m, b, writes, .. },
x,
y,
then,
other,
join,
..
} = diamond();
let dead_then = m.bin(then, Bin::Add, x, y);
let _ = dead_then;
let dead_other = m.bin(other, Bin::Xor, x, y);
let _ = dead_other;
let i32t = m.int(32);
let p = m.phi(join, i32t);
// Both sides bring the same value -> `merge` folds `p` -> `join` becomes phi-free.
m.set_phi(p, vec![(x, then), (x, other)]);
m.call(join, writes, vec![p, y]);
m.optimise(ALL);
let reached = m.reached();
assert_eq!(reached.iter().filter(|&&r| r).count(), 1, "dead diamond must collapse to 1 block");
assert!(matches!(m.blocks[b].term, Some(Term::Ret)));
assert_eq!(stores(&m, b), [[x, y]]);
m.write();
// 3. Negative controls:
// (a) Multi-predecessor target with live phi is NOT absorbed or broken.
// (b) Self-loop (`loop_blk -> loop_blk`) is NOT falsely absorbed.
// (c) Degenerate dead phi cycle in a single-pred block does not hang.
let mut k = kit();
let i32t = k.m.int(32);
let (k0, k1, k4) = (k.m.i32(0), k.m.i32(1), k.m.i32(4));
let (head, pre, dead_cyc, exit) =
(k.m.new_block(), k.m.new_block(), k.m.new_block(), k.m.new_block());
k.m.terminate(k.b, Term::Br(head));
let iv = k.m.phi(head, i32t);
let next = k.m.bin(head, Bin::Add, iv, k1);
let more = k.m.cmp(head, pred::IULT, next, k4);
k.m.terminate(head, Term::CondBr(more, head, pre));
k.m.set_phi(iv, vec![(k0, k.b), (next, head)]);
// `pre -> Br(dead_cyc)` feeds a degenerate dead phi cycle; `simplify_cfg`
// must refuse coalescing `dead_cyc` into `pre` without hanging.
k.m.call(pre, k.writes, vec![next, k0]);
k.m.terminate(pre, Term::Br(dead_cyc));
let ca = k.m.phi(dead_cyc, i32t);
let cb = k.m.phi(dead_cyc, i32t);
k.m.set_phi(ca, vec![(cb, pre)]);
k.m.set_phi(cb, vec![(ca, pre)]);
k.m.call(dead_cyc, k.writes, vec![next, k1]);
k.m.terminate(dead_cyc, Term::Br(exit));
k.m.terminate(exit, Term::Ret);
// Without DEAD first, `dead_cyc`'s self-referencing phi must block merging into `pre`.
k.m.optimise(FOLD);
assert!(matches!(k.m.blocks[pre].term, Some(Term::Br(t)) if t == dead_cyc));
assert!(!k.m.blocks[dead_cyc].phis.is_empty());
k.m.write();
// With FULL passes (`ALL`), `drop_dead_insts` clears the dead cycle and
// `pre -> dead_cyc -> exit` coalesces cleanly.
k.m.optimise(ALL);
assert!(matches!(k.m.blocks[pre].term, Some(Term::Ret)));
assert_eq!(
run(&k.m, &[0]),
vec![
("dx.op.bufferStore.i32".into(), vec![4, 0]),
("dx.op.bufferStore.i32".into(), vec![4, 1]),
("ret".into(), vec![]),
]
);
k.m.write();
}
}