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
77 changes: 51 additions & 26 deletions d3d12/crates/leonida-shader/src/ir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result<Program, ShaderErr
}
leaders.sort_unstable();
leaders.dedup();
let parked = unspill(&mut list, &flows, &leaders, wave64, lanes, vgprs);
let (parked, mut cache) = unspill(&mut list, &flows, &leaders, wave64, lanes, vgprs);
let block_at = |offset: usize| {
leaders
.binary_search(&offset)
Expand All @@ -174,18 +174,27 @@ pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result<Program, ShaderErr
.collect();
for (n, ((machine, flow), next)) in list.into_iter().zip(flows).zip(next_offsets).enumerate() {
let b = leaders.partition_point(|&l| l <= machine.offset) - 1;
let name = machine.name().ok_or(ShaderError::Unsupported {
offset: machine.offset,
what: "unknown opcode",
})?;
let mut fields = machine.fields(wave64);
let cached = cache.as_mut().and_then(|c| c.get_mut(n)).and_then(|slot| slot.take());
let (name, mut fields, mut cached_effects) = match cached {
Some(d) => (d.name, d.fields, d.effects),
None => (
machine.name().ok_or(ShaderError::Unsupported {
offset: machine.offset,
what: "unknown opcode",
})?,
machine.fields(wave64),
None,
),
};
// A move to or from a scalar parked in a VGPR lane (`unspill`): its register
// codes may be ones the machine word cannot hold.
if let Ok(k) = parked.binary_search_by_key(&n, |m| m.0)
&& let Fields::Sop { dst: Some(Operand::Scalar { code: to, .. }), src, .. } = &mut fields
&& let Some(Operand::Scalar { code: from, .. }) = src.first_mut()
{
(*to, *from) = (parked[k].1, parked[k].2);
// The register effects were worked out before this substitution.
cached_effects = None;
}
let fallthrough = || block_at(next.ok_or(isa(machine.offset, "falls off the code"))?);
// A conditional SOPP branch to fallthrough has no register effects
Expand All @@ -210,7 +219,11 @@ pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result<Program, ShaderErr
Flow::Stop => Exit::End,
};
}
if let Some((mut reads, writes)) = effects(&machine, &fields, name, lanes, vgprs)? {
let effects = match cached_effects {
Some(e) => Some(e),
None => effects(&machine, &fields, name, lanes, vgprs)?,
};
if let Some((mut reads, writes)) = effects {
// Lanes disabled in EXEC keep the old value.
for w in writes.iter().filter(|w| matches!(w, Reg::V(_))) {
if !reads.contains(w) {
Expand Down Expand Up @@ -266,22 +279,31 @@ pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result<Program, ShaderErr
/// a scalar later, say. Where that keeps a pair from being one, each life of a
/// lane (the saves that reach a restore in common, and those restores) is a
/// store of its own.
/// Fields and register effects decoded once for an instruction. `unspill`
/// has to walk every instruction to find parked scalars, and `build` walks
/// them again; without this, a program with a lane save decodes each twice.
struct Decoded {
name: &'static str,
fields: Fields,
effects: Option<(Vec<Reg>, Vec<Reg>)>,
}

fn unspill(
list: &mut [gfx10::Instruction],
flows: &[Flow],
leaders: &[usize],
wave64: bool,
lanes: u8,
vgprs: u16,
) -> Vec<(usize, u8, u8)> {
) -> (Vec<(usize, u8, u8)>, Option<Vec<Option<Decoded>>>) {
// Nothing is parked in a lane unless the code has a save or a restore of one, and the scan
// takes the fields and the effects of every instruction to find that out: most programs
// have none.
if !list
.iter()
.any(|i| matches!(i.name(), Some("v_writelane_b32" | "v_readlane_b32")))
{
return Vec::new();
return (Vec::new(), None);
}
unspill_scan(list, flows, leaders, wave64, lanes, vgprs)
}
Expand All @@ -295,7 +317,7 @@ fn unspill_scan(
wave64: bool,
lanes: u8,
vgprs: u16,
) -> Vec<(usize, u8, u8)> {
) -> (Vec<(usize, u8, u8)>, Option<Vec<Option<Decoded>>>) {
/// `v_writelane_b32 vN, sX, K` / `v_readlane_b32 sX, vN, K`: (save, N, X, K).
fn parked(inst: &gfx10::Instruction, fields: &Fields) -> Option<(bool, u8, u8, u32)> {
let Fields::Valu(v) = fields else { return None };
Expand Down Expand Up @@ -324,22 +346,23 @@ fn unspill_scan(
let mut parks: Vec<Option<(bool, u8, u8, u32)>> = Vec::with_capacity(list.len());
let mut written: Vec<Vec<u8>> = Vec::with_capacity(list.len());
let mut read: Vec<Vec<u8>> = Vec::with_capacity(list.len());
let mut cache: Vec<Option<Decoded>> = Vec::with_capacity(list.len());
for inst in list.iter() {
let Some(name) = inst.name() else { return Vec::new() };
let Some(name) = inst.name() else { return (Vec::new(), None) };
let fields = inst.fields(wave64);
let park = parked(inst, &fields);
let Ok(effects) = effects(inst, &fields, name, lanes, vgprs) else {
return Vec::new();
return (Vec::new(), None);
};
let mut codes = Vec::new();
let mut from = Vec::new();
if let Some((reads, writes)) = effects {
for &reg in &writes {
if let Some((reads, writes)) = &effects {
for &reg in writes {
if let Reg::S(c) = reg {
codes.push(c);
}
}
for &reg in &reads {
for &reg in reads {
if let Reg::S(c) = reg {
from.push(c);
}
Expand All @@ -350,7 +373,7 @@ fn unspill_scan(
// ordinary ones. (Relative writes still do.)
let relative = name == "v_movrels_b32";
let n_reads = reads.len();
for (k, reg) in reads.into_iter().chain(writes).enumerate() {
for (k, &reg) in reads.iter().chain(writes.iter()).enumerate() {
if relative && k < n_reads && matches!(reg, Reg::V(_)) {
continue;
}
Expand All @@ -365,6 +388,7 @@ fn unspill_scan(
parks.push(park);
written.push(codes);
read.push(from);
cache.push(Some(Decoded { name, fields, effects }));
}
let leader = |i: usize| leaders.binary_search(&list[i].offset).is_ok();
for reg in 0..256 {
Expand All @@ -391,7 +415,7 @@ fn unspill_scan(
}
}
if parks.iter().all(Option::is_none) {
return Vec::new();
return (Vec::new(), None);
}
// Lane pairs (register, lower lane) that always move together: each
// save of the lower lane is followed, in the same block and before its
Expand Down Expand Up @@ -583,7 +607,7 @@ fn unspill_scan(
}
Some((of, pairs, codes.into_iter().flatten().collect()))
};
let Some(mut chosen) = plan(false) else { return Vec::new() };
let Some(mut chosen) = plan(false) else { return (Vec::new(), None) };
let lonely = |(of, pairs, _): &(Vec<usize>, Vec<(usize, usize)>, Vec<u8>)| {
(0..list.len()).any(|i| {
parks[i].is_some_and(|p| p.0)
Expand All @@ -599,8 +623,9 @@ fn unspill_scan(
chosen = split;
}
let (store, pairs, codes) = chosen;
let put = |list: &mut [gfx10::Instruction], i: usize, encoding, opcode: u16, word: u32| {
let put = |list: &mut [gfx10::Instruction], cache: &mut [Option<Decoded>], i: usize, encoding, opcode: u16, word: u32| {
list[i] = gfx10::Instruction::new(list[i].offset, encoding, opcode, vec![word]);
cache[i] = None;
};
// `s_mov_b32` / `s_mov_b64 dst, src` (SOP1, opcodes 3 and 4); `s_nop`. A code
// from `PARKED` up does not fit the word: s0 stands in for it there.
Expand All @@ -614,7 +639,7 @@ fn unspill_scan(
};
let slot = codes[store[i]];
if pairs.iter().any(|p| p.0 == store[i]) {
let Some(j) = partner(i) else { return Vec::new() };
let Some(j) = partner(i) else { return (Vec::new(), None) };
// A save moves the pair where its second half is saved; a
// restore where its first half is restored.
let (at, gone) = if save { (j, i) } else { (i, j) };
Expand All @@ -632,14 +657,14 @@ fn unspill_scan(
for (i, edit) in edits {
match edit {
Some((wide, dst, src)) => {
put(list, i, gfx10::Encoding::Sop1, 3 + u16::from(wide), mov(wide, dst, src));
put(list, &mut cache, i, gfx10::Encoding::Sop1, 3 + u16::from(wide), mov(wide, dst, src));
moves.push((i, dst, src));
}
None => put(list, i, gfx10::Encoding::Sopp, 0, NOP),
None => put(list, &mut cache, i, gfx10::Encoding::Sopp, 0, NOP),
}
}
moves.sort_unstable();
moves
(moves, Some(cache))
}

/// Rename register reads and writes after changing edges in a reducible graph.
Expand Down Expand Up @@ -1904,11 +1929,11 @@ mod tests {
let mut scanned = quick.clone();
let by_unspill = unspill(&mut quick, &flows, &leaders, wave64, lanes, 256);
let by_scan = unspill_scan(&mut scanned, &flows, &leaders, wave64, lanes, 256);
assert_eq!(by_unspill, by_scan, "{name}, wave64 {wave64}");
assert_eq!(by_unspill.0, by_scan.0, "{name}, wave64 {wave64}");
assert_eq!(quick, scanned, "{name}, wave64 {wave64}");
// The cases that park something do have the scan make moves.
assert_eq!(!by_scan.is_empty(), parks, "{name}, wave64 {wave64}");
found += by_scan.len();
assert_eq!(!by_scan.0.is_empty(), parks, "{name}, wave64 {wave64}");
found += by_scan.0.len();
}
}
assert!(found >= 8, "{found}");
Expand Down