diff --git a/crates/xcl/src/gpu/dxil/compact.rs b/crates/xcl/src/gpu/dxil/compact.rs index 65c1a51b00..ca41682e63 100644 --- a/crates/xcl/src/gpu/dxil/compact.rs +++ b/crates/xcl/src/gpu/dxil/compact.rs @@ -237,7 +237,7 @@ impl Plan { (bits(self.rep.len()), pb) } - /// 32-bit words of the tables. + /// 32-bit words of the tables, the block-PC and literal ones included. pub fn words(&self) -> usize { let (cb, pb) = self.widths(); let extra = match self.next_enc { @@ -245,8 +245,48 @@ impl Plan { NextEnc::Inline => 0, NextEnc::TargetPool => self.targets.len(), }; - (self.mblocks.len() * (cb + pb) as usize).div_ceil(32) + 1 + extra + let packed = |w: u32| (self.mblocks.len() * w as usize).div_ceil(32) + 1; + let pc = if self.use_pc { packed(self.pc_width()) } else { 0 }; + let lit = if self.use_lit { + let (pool, _) = self.lit_pool(); + packed(entry_bits(pool.len())) + pool.len() + } else { + 0 + }; + packed(cb + pb) + extra + pc + lit + } + + /// Bits of a block's PC entry in `xcl_pc` (PCs in dwords). + fn pc_width(&self) -> u32 { + let max_pc_dw = self.mblocks.iter().map(|blk| (blk.pc >> 2) as usize).max().unwrap_or(0); + entry_bits(max_pc_dw + 1) } + + /// The distinct parameterized literals (0 first, for blocks without one) and each block's + /// index into them. + fn lit_pool(&self) -> (Vec, Vec) { + let mut pool: Vec = vec![0]; + let mut idx_map: HashMap = HashMap::from([(0, 0)]); + let blk_idx = self + .blk_lit + .iter() + .map(|&opt| { + let val = opt.unwrap_or(0); + *idx_map.entry(val).or_insert_with(|| { + pool.push(val); + pool.len() as u32 - 1 + }) + }) + .collect(); + (pool, blk_idx) + } +} + +/// Bits of an entry of a per-block table that takes `n` values: a power of two, so no entry +/// straddles two words and a lookup reads one word. AMD's driver (RDNA2 / RDNA3) got the +/// literal pool index wrong from a two-word extraction (every literal read 0). +fn entry_bits(n: usize) -> u32 { + bits(n).next_power_of_two().min(32) } /// A consumed atomic result prevents cutting a dispatch into independent pipelines. @@ -318,7 +358,7 @@ fn single_param_lit(cfg: &Cfg, blk: &MicroBlock) -> Option { } /// Sorts the reachable blocks into classes the lowering would emit the same for. -/// On large shaders, repeated heavy memory instructions (appearing `>= 4` times) are split +/// On large shaders, repeated heavy memory instructions (appearing `>= 2` times) are split /// into standalone micro-blocks so each unique buffer/SMEM/image lowering is emitted once /// instead of once per surrounding ALU context. pub fn plan(cfg: &Cfg, lw: &Lw) -> Option { @@ -340,7 +380,7 @@ pub fn plan(cfg: &Cfg, lw: &Lw) -> Option { } } - // Pass 1: split blocks around repeated heavy memory ops (`>= 4` occurrences). + // Pass 1: split blocks around repeated heavy memory ops (`>= 2` occurrences). let mut segs_per_orig: Vec<(usize, Vec>)> = Vec::with_capacity(orig_order.len()); let mut orig_to_mb = vec![END; cfg.blocks.len()]; let mut mb_cursor = 0u32; @@ -595,7 +635,8 @@ pub fn plan(cfg: &Cfg, lw: &Lw) -> Option { let only_lit = if has_getpc { build(true, false) } else { cand.clone() }; let saved_pc = only_lit.1.len().saturating_sub(cand.1.len()); if has_getpc && saved_pc >= 64 && saved_pc * 60 > mblocks.len() * 2 { - (true, true, cand) + // (no literal tables when no block has a literal to take from them) + (cand.3.iter().any(Option::is_some), true, cand) } else if base.1.len().saturating_sub(only_lit.1.len()) >= 64 && base.1.len().saturating_sub(only_lit.1.len()) * 60 > mblocks.len() * 2 { @@ -776,8 +817,7 @@ pub fn emit_with_nest(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block let steps = (p.next_enc == NextEnc::Steps).then(|| table(lw, "xcl_steps", &steps)); let target_pool = (p.next_enc == NextEnc::TargetPool).then(|| table(lw, "xcl_targets", &p.targets)); let pc_table = p.use_pc.then(|| { - let max_pc_dw = p.mblocks.iter().map(|blk| (blk.pc >> 2) as usize).max().unwrap_or(0); - let pc_w = bits(max_pc_dw + 1).min(32); + let pc_w = p.pc_width(); let mut pc_packed = vec![0u32; (n * pc_w as usize).div_ceil(32) + 1]; for (b, blk) in p.mblocks.iter().enumerate() { let v = (blk.pc >> 2) as u64; @@ -788,20 +828,9 @@ pub fn emit_with_nest(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block (table(lw, "xcl_pc", &pc_packed), pc_w) }); let lit_table = p.use_lit.then(|| { - // Deduplicate unique 32-bit literals into a pool and bit-pack pool indices per block. - let mut pool: Vec = vec![0]; - let mut idx_map: HashMap = HashMap::from([(0, 0)]); - let mut blk_idx: Vec = Vec::with_capacity(n); - for &opt in &p.blk_lit { - let val = opt.unwrap_or(0); - let idx = *idx_map.entry(val).or_insert_with(|| { - let id = pool.len() as u32; - pool.push(val); - id - }); - blk_idx.push(idx); - } - let lit_w = bits(pool.len()).min(32); + // the distinct literals in a pool, and each block's pool index bit-packed + let (pool, blk_idx) = p.lit_pool(); + let lit_w = entry_bits(pool.len()); let mut idx_packed = vec![0u32; (n * lit_w as usize).div_ceil(32) + 1]; for (b, &id) in blk_idx.iter().enumerate() { let v = id as u64; @@ -841,13 +870,7 @@ pub fn emit_with_nest(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block let pi = lw.lshrc(pbit, 5); let psh = lw.andc(pbit, 31); let plo = word(lw, pc_tbl, pi); - let pi1 = lw.addc(pi, 1); - let phi = word(lw, pc_tbl, pi1); - let plo = lw.lshr(plo, psh); - let phi = lw.shlc(phi, 1); - let pup = lw.sub(k31, psh); - let phi = lw.shl(phi, pup); - let pe = lw.or(plo, phi); + let pe = lw.lshr(plo, psh); lw.andc(pe, (1u32 << pc_w) - 1) }; lw.shlc(pm, 2) @@ -861,13 +884,7 @@ pub fn emit_with_nest(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block let li = lw.lshrc(lbit, 5); let lsh = lw.andc(lbit, 31); let llo = word(lw, idx_tbl, li); - let li1 = lw.addc(li, 1); - let lhi = word(lw, idx_tbl, li1); - let llo = lw.lshr(llo, lsh); - let lhi = lw.shlc(lhi, 1); - let lup = lw.sub(k31, lsh); - let lhi = lw.shl(lhi, lup); - let le = lw.or(llo, lhi); + let le = lw.lshr(llo, lsh); lw.andc(le, (1u32 << lit_w) - 1) }; word(lw, pool_tbl, id) diff --git a/crates/xcl/src/gpu/dxil/compact_tests.rs b/crates/xcl/src/gpu/dxil/compact_tests.rs index cf56c97c85..3e542fa207 100644 --- a/crates/xcl/src/gpu/dxil/compact_tests.rs +++ b/crates/xcl/src/gpu/dxil/compact_tests.rs @@ -151,6 +151,141 @@ fn loads_and_literals(copies: usize) -> Vec { v } +/// `copies` blocks that each read their own PC (`s_getpc_b64 s[10:11]`) and add it to s1; s0 +/// counts them, and the early out after the copy where s0 == s4 goes to `s_mov s5, 1`. +fn pcs(copies: usize) -> Vec { + let i = |n: &str, e: &str, f: &[(&str, u64)]| encode(n, e, f, None).unwrap_or_else(|x| panic!("{n}: {x}")); + let mut v = Vec::new(); + for k in 0..copies { + v.extend(i("S_GETPC_B64", "ENC_SOP1", &[("SDST", 10)])); + v.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 1), ("SSRC1", 10)])); + v.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 129)])); + v.extend(i("S_CMP_EQ_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 4)])); + // to the s_mov after the last copy: 5 dwords per copy + v.extend(i("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", ((copies - 1 - k) * 5) as u64)])); + } + v.extend(i("S_MOV_B32", "ENC_SOP1", &[("SDST", 5), ("SSRC0", 129)])); + v.extend(i("S_ENDPGM", "ENC_SOPP", &[])); + v +} + +/// Blocks that differ only in where their `s_getpc_b64` is share a class and read the block's PC +/// from `xcl_pc`; the result is the plain form's. +#[test] +fn gpu_compact_form_with_a_block_pc_table_runs_as_the_plain_form() { + match (runner::adapter(), runner::wave64_programs_supported(), crate::gpu::recomp::dxc::location()) { + (Ok(_), Ok(true), Ok(_)) => {} + (a, _, d) => return runner::skip_test(if a.is_err() { "no GPU" } else if d.is_err() { "no DXC" } else { "no wave64" }), + } + let code = pcs(200); + let cfg = super::cfg::Cfg::build(&code).unwrap(); + let leaders = cfg.blocks.iter().filter_map(|b| b.insts.first().map(|&i| cfg.insts[i].pc)).collect(); + let o = KernelOptions { wave64: true, split: runner::split_wave64(), mem_windows: 1, sampler_base: 0 }; + let lw = super::lower::Lw::new(&cfg.insts, &leaders, o, &super::kernel::Entry::Kernel); + let p = super::compact::plan(&cfg, &lw).unwrap(); + assert!(p.use_pc && p.rep.len() < 8, "block PC table {}, {} classes", p.use_pc, p.rep.len()); + let mut st = KernelState::default(); + st.sgpr[4] = 10; + let run = |compact: bool| { + let k = translate_full_as(&code, o, compact).unwrap_or_else(|e| panic!("compact {compact}: {e}")); + runner::run_with_statics(&k.dxil, &st, &[], &[], &[], &k.static_samplers).expect("GPU run") + }; + let (c, p) = (run(true), run(false)); + // copy k starts at 20 k; its s_getpc_b64 gives the address after it, 20 k + 4 + assert_eq!((c.sgpr[0], c.sgpr[1], c.sgpr[5]), (10, (0..10).map(|k| 20 * k + 4).sum::(), 1)); + assert_eq!((c.sgpr, c.vgpr, c.scc), (p.sgpr, p.vgpr, p.scc)); +} + +/// `copies` blocks that each add 1 to s0 and go to the next one through a far-jump veneer +/// (`s_getpc_b64 s[10:11]`, `s_add_u32` / `s_addc_u32`, `s_setpc_b64`). +fn far_jumps(copies: usize) -> Vec { + let i = |n: &str, e: &str, f: &[(&str, u64)], lit: Option| encode(n, e, f, lit).unwrap_or_else(|x| panic!("{n}: {x}")); + let mut v = Vec::new(); + for _ in 0..copies { + v.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 129)], None)); + v.extend(i("S_GETPC_B64", "ENC_SOP1", &[("SDST", 10)], None)); + // the next copy is 16 bytes after the address s_getpc_b64 gives (24 bytes a copy) + v.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 10), ("SSRC1", 255)], Some(16))); + v.extend(i("S_ADDC_U32", "ENC_SOP2", &[("SDST", 11), ("SSRC0", 11), ("SSRC1", 128)], None)); + v.extend(i("S_SETPC_B64", "ENC_SOP1", &[("SSRC0", 10)], None)); + } + v.extend(i("S_ENDPGM", "ENC_SOPP", &[], None)); + v +} + +/// A far-jump veneer whose address registers and SCC nobody reads after the jump is left out of +/// the compact form: in a compute program (nothing is live at its end) all of them, in the +/// kernel form of the tests (every register is read at the end) all but the last. +#[test] +fn dead_far_jump_veneers_are_left_out() { + let code = far_jumps(70); + let cfg = super::cfg::Cfg::build(&code).unwrap(); + let leaders = cfg.blocks.iter().filter_map(|b| b.insts.first().map(|&i| cfg.insts[i].pc)).collect(); + let o = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 }; + let cs = crate::gpu::recomp::CsInterface { threads: [64, 1, 1], user_sgprs: 4, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let getpcs = |entry: &super::kernel::Entry| { + let lw = super::lower::Lw::new(&cfg.insts, &leaders, o, entry); + let p = super::compact::plan(&cfg, &lw).unwrap(); + p.mblocks.iter().flat_map(|b| &b.insts).filter(|&&i| cfg.insts[i].inst.name == "S_GETPC_B64").count() + }; + assert_eq!(getpcs(&super::kernel::Entry::Compute(cs)), 0); + assert_eq!(getpcs(&super::kernel::Entry::Kernel), 1); +} + +/// With the veneers left out, the kernel form still ends as the plain one (the last veneer's +/// address in s[10:11] included). +#[test] +fn gpu_compact_form_without_dead_veneers_runs_as_the_plain_form() { + match (runner::adapter(), runner::wave64_programs_supported(), crate::gpu::recomp::dxc::location()) { + (Ok(_), Ok(true), Ok(_)) => {} + (a, _, d) => return runner::skip_test(if a.is_err() { "no GPU" } else if d.is_err() { "no DXC" } else { "no wave64" }), + } + let code = far_jumps(70); + let o = KernelOptions { wave64: true, split: runner::split_wave64(), mem_windows: 1, sampler_base: 0 }; + let st = KernelState::default(); + let run = |compact: bool| { + let k = translate_full_as(&code, o, compact).unwrap_or_else(|e| panic!("compact {compact}: {e}")); + runner::run_with_statics(&k.dxil, &st, &[], &[], &[], &k.static_samplers).expect("GPU run") + }; + let (c, p) = (run(true), run(false)); + assert_eq!((c.sgpr[0], c.sgpr[10]), (70, 69 * 24 + 8 + 16)); + assert_eq!((c.sgpr, c.vgpr, c.scc), (p.sgpr, p.vgpr, p.scc)); +} + +/// The plan's word count is what the tables take, the block-PC and literal ones included. +#[test] +fn the_word_count_includes_the_pc_and_literal_tables() { + for (code, what) in [(loads_and_literals(300), "literals"), (pcs(200), "pcs")] { + let o = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 }; + let cfg = super::cfg::Cfg::build(&code).unwrap(); + let leaders = cfg.blocks.iter().filter_map(|b| b.insts.first().map(|&i| cfg.insts[i].pc)).collect(); + let lw = super::lower::Lw::new(&cfg.insts, &leaders, o, &super::kernel::Entry::Kernel); + let p = super::compact::plan(&cfg, &lw).unwrap(); + assert!(p.use_lit || p.use_pc, "{what}: no parameterized table"); + let k = translate_full_as(&code, o, true).expect("compact form"); + let dis = super::validate::disassemble(&k.dxil).expect("disassemble"); + let words: usize = dis + .lines() + .filter(|l| l.starts_with("@xcl_") && l.contains("internal constant [")) + .map(|l| l.split("internal constant [").nth(1).unwrap().split(" x i32]").next().unwrap().parse::().unwrap()) + .sum(); + assert_eq!(p.words(), words, "{what}"); + } +} + +/// Each block's literal index sits in one word of `xcl_lit_idx` (a power-of-two width), so the +/// lookup reads one word: AMD's driver got the index wrong from a two-word extraction. +#[test] +fn a_literal_index_is_read_from_one_word() { + for copies in [200, 300] { + let o = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 }; + let k = translate_full_as(&loads_and_literals(copies), o, true).expect("compact form"); + let dis = super::validate::disassemble(&k.dxil).expect("disassemble"); + let reads = dis.lines().filter(|l| l.contains("getelementptr") && l.contains("@xcl_lit_idx,")).count(); + assert_eq!(reads, 1, "{copies} copies: {reads} reads of the literal index table"); + } +} + #[test] fn repeated_loads_split_into_micro_blocks_and_literals_into_a_table() { let code = loads_and_literals(200); @@ -174,15 +309,18 @@ fn gpu_compact_form_with_micro_blocks_and_literal_table_runs_as_the_plain_form() let mut st = KernelState::default(); // s[2:3] = 0: the loads read mem[0]; the early out is taken in the 10th copy st.sgpr[4] = 50; - let code = loads_and_literals(200); let o = KernelOptions { wave64: true, split: runner::split_wave64(), mem_windows: 1, sampler_base: 0 }; - let run = |compact: bool| { - let k = translate_full_as(&code, o, compact).unwrap_or_else(|e| panic!("compact {compact}: {e}")); - runner::run_with_statics(&k.dxil, &st, &[5, 0, 0, 0], &[], &[], &k.static_samplers).expect("GPU run") - }; - let (c, p) = (run(true), run(false)); - assert_eq!((c.sgpr[0], c.sgpr[1], c.sgpr[5], c.sgpr[8]), (50, (1000..1010).sum::(), 1, 5)); - assert_eq!((c.sgpr, c.vgpr, c.scc), (p.sgpr, p.vgpr, p.scc)); + // 200 copies: 8-bit literal indices; 300: 9 bits, which the table stores in 16 + for copies in [200, 300] { + let code = loads_and_literals(copies); + let run = |compact: bool| { + let k = translate_full_as(&code, o, compact).unwrap_or_else(|e| panic!("compact {compact}: {e}")); + runner::run_with_statics(&k.dxil, &st, &[5, 0, 0, 0], &[], &[], &k.static_samplers).expect("GPU run") + }; + let (c, p) = (run(true), run(false)); + assert_eq!((c.sgpr[0], c.sgpr[1], c.sgpr[5], c.sgpr[8]), (50, (1000..1010).sum::(), 1, 5), "{copies} copies"); + assert_eq!((c.sgpr, c.vgpr, c.scc), (p.sgpr, p.vgpr, p.scc), "{copies} copies"); + } } #[test]