Shader clean-up passes; a test that needs a card skips without one

- Clean-up passes over each translated module (VICTORY_SHADER_OPT bits: dead
  code, folding, reuse, branch facts, loads within a block, wave64 first-lane
  exchange), part of the shader cache key. About 43 % fewer host instructions
  over the pack; about 20 ms less GPU time per frame on the test machine.
- translate: a census of the emitted code.
- Checked with plain game runs of this tree on the test machine.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
fxcelessandClaude Fable 5.2 committed 2026-11-24 15:13:27 -05:00
1 parent df7b68f167
commit d7823e8a38
10 files changed
+2495 -16

No files matched your search

+3 -1
View File
@@ -24,7 +24,7 @@ Take-Two Interactive.
## Status of this fork (2026-11-25)
**Not playable yet: 2 to 4 frames per second, and shadowed areas are black.**
**Not playable yet: 2.5 to 4 frames per second, and shadowed areas are black.**
Tested on one machine: Windows 11, Intel i7-14700KF, NVIDIA RTX 4070 12 GB,
32 GB RAM. The Series X profile is used throughout.
@@ -58,6 +58,8 @@ Speed and memory:
- The bindless texture queue no longer uploads stale views; the view table no longer grows without bound; the pipeline library is mapped instead of read into memory.
- An intermittent device loss was traced to the pipeline library file being replaced while mapped; fixed.
- Translated shaders get clean-up passes over the finished module (dead code, constant folding, reuse of values, branch facts); the pack's host instruction count falls by about 43 %, worth about 20 ms of GPU time per frame on the test machine (`VICTORY_SHADER_OPT=0` turns them off).
Most of the newer speed changes sit behind environment switches that are off
by default (`VICTORY_LATE_WAIT`, `VICTORY_RELAY`, `VICTORY_WIDE_BACK`,
`VICTORY_CARD_BUFFERS_MIN_MB`, `VICTORY_INPLACE`, `VICTORY_BVH_BUILDER`, ...).
+46
View File
@@ -440,6 +440,7 @@ fn translate_programs(container: &Container, programs: Vec<NativeProgram>, examp
*counter(t, p.stage, 0) += 1;
match emit::emit(container, &p, &program, &s, &i, &r) {
Ok(shader) => {
census_line(&label(), &p, &program, &shader);
*counter(t, p.stage, 1) += 1;
check(shader, t, checks, label);
}
@@ -462,6 +463,51 @@ fn translate_programs(container: &Container, programs: Vec<NativeProgram>, examp
}
}
/// `VICTORY_SHADER_CENSUS=<file>`: one line per emitted program, appended:
/// its label, the console program's instructions by encoding class (a
/// static count of the whole program, not of one thread's path), and the
/// host module's instructions by kind (`emit::census::KINDS`).
fn census_line(label: &str, native: &NativeProgram, p: &ir::Program, shader: &emit::HostShader) {
use std::io::Write;
use victory_shader::gfx10::Fields;
static OUT: std::sync::OnceLock<Option<Mutex<std::fs::File>>> = std::sync::OnceLock::new();
let Some(out) = OUT.get_or_init(|| {
let path = std::env::var_os("VICTORY_SHADER_CENSUS")?;
let file = std::fs::OpenOptions::new().create(true).append(true).open(path).ok()?;
Some(Mutex::new(file))
}) else {
return;
};
let Some(census) = emit::census::take(&shader.dxil) else {
return;
};
// total, vector, scalar, descriptor loads, buffer and memory, image, LDS, control, other
let mut console = [0u32; 9];
for inst in p.blocks.iter().flat_map(|b| &b.insts) {
console[0] += 1;
let k = match &inst.fields {
Fields::Valu(_) => 1,
Fields::Sop { .. } => 2,
Fields::Smem { .. } => 3,
Fields::Buffer { .. } | Fields::Flat { .. } => 4,
Fields::Image { .. } => 5,
Fields::Ds { .. } => 6,
Fields::Sopp { .. } => 7,
_ => 8,
};
console[k] += 1;
}
let mut line = format!("{label}\twave64={}", u8::from(native.wave64));
for (name, n) in ["c_total", "c_valu", "c_sop", "c_smem", "c_buffer", "c_image", "c_ds", "c_sopp", "c_other"].iter().zip(console) {
line.push_str(&format!("\t{name}={n}"));
}
for (name, n) in emit::census::KINDS.iter().zip(census.counts) {
line.push_str(&format!("\t{name}={n}"));
}
line.push('\n');
let _ = lock(out).write_all(line.as_bytes());
}
/// Validates an emitted shader if asked to.
fn check(
mut shader: emit::HostShader,
+2
View File
@@ -73,6 +73,8 @@ fn build() -> &'static [u8; 32] {
}
bytes.push(0);
}
// And which clean-up passes ran over the translated code.
bytes.extend_from_slice(&victory_shader::emit::shader_opt().to_le_bytes());
*blake3::hash(&bytes).as_bytes()
}
Err(e) => {
+27
View File
@@ -7,9 +7,24 @@
use std::collections::HashMap;
pub mod census;
pub mod opt;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub(crate) struct Ty(u32);
/// What the lowering made an instruction for, where it says so (counted by
/// [`census`], nothing else reads it).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Tag {
/// The select that keeps a register's old value in lanes a guard masks.
Guard,
/// An index clamp the translation adds (the console has none).
Clamp,
/// The iteration counter and limit test the translation adds to a loop.
Counter,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum TypeDef {
Void,
@@ -208,6 +223,8 @@ pub(crate) struct Module {
blocks: Vec<Block>,
mds: Vec<MdDef>,
named: Vec<(String, Vec<Md>)>,
/// See [`Tag`]: by instruction.
tags: HashMap<u32, Tag>,
}
impl Module {
@@ -355,6 +372,16 @@ impl Module {
g
}
/// Notes what instruction `v` is for (see [`Tag`]); only when modules
/// are counted.
pub fn tag(&mut self, v: V, tag: Tag) {
if let V::Inst(i) = v
&& census::enabled()
{
self.tags.insert(i, tag);
}
}
pub fn new_block(&mut self) -> usize {
self.blocks.push(Block::default());
self.blocks.len() - 1
@@ -0,0 +1,174 @@
//! Counts of a module's instructions by kind (a diagnostic): what a
//! translated program costs before the driver's compiler sees it.
//!
//! `VICTORY_SHADER_CENSUS` (any value) turns the counting on; the counts of
//! the module a thread wrote last are read with [`take`]. The `translate`
//! command writes them as a table (see `apps/victory/src/translate.rs`).
use super::{Cast, Module, Op, Tag, Term, V};
use std::cell::RefCell;
/// The kinds, in the order of [`Census::counts`].
pub const KINDS: [&str; 26] = [
"total",
"arith",
"math_call",
"bitcast",
"cast",
"select",
"guard_select",
"phi",
"extract",
"buffer_load",
"cbuffer_load",
"texture_read",
"lds_load",
"buffer_store",
"lds_store",
"atomic",
"handle",
"annotate",
"dimensions",
"barrier",
"wave_op",
"io_other",
"gep",
"clamp",
"loop_counter",
"blocks",
];
/// Instruction counts of one written module, by [`KINDS`].
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Census {
pub counts: [u32; KINDS.len()],
}
thread_local! {
/// The modules this thread wrote since the last [`take`]: the length and
/// a hash of each one's bitcode, with its counts (a program may be
/// emitted in several forms before one is kept).
static WRITTEN: RefCell<Vec<(usize, u64, Census)>> = const { RefCell::new(Vec::new()) };
}
fn fnv(bytes: &[u8]) -> u64 {
bytes.iter().fold(0xcbf2_9ce4_8422_2325, |h, &b| {
(h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3)
})
}
/// Whether modules are counted (`VICTORY_SHADER_CENSUS` set).
pub fn enabled() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_SHADER_CENSUS").is_some())
}
/// The counts of the module whose bitcode the container `dxil` holds, if
/// this thread wrote it since the last call (which forgets the others).
pub fn take(dxil: &[u8]) -> Option<Census> {
let written = WRITTEN.with(|l| std::mem::take(&mut *l.borrow_mut()));
let at = dxil.windows(4).position(|w| w == b"BC\xC0\xDE")?;
written
.into_iter()
.rev()
.find(|(len, hash, _)| dxil.get(at..at + len).is_some_and(|b| fnv(b) == *hash))
.map(|w| w.2)
}
/// Counts `m`, whose written form is `bitcode`, and keeps the result for
/// [`take`].
pub(crate) fn note(m: &Module, bitcode: &[u8]) {
if !enabled() {
return;
}
let c = m.census();
WRITTEN.with(|l| l.borrow_mut().push((bitcode.len(), fnv(bitcode), c)));
}
fn kind(name: &str) -> usize {
let n = name.strip_prefix("dx.op.").unwrap_or(name);
let n = n.split('.').next().unwrap_or(n);
let k = |s: &str| KINDS.iter().position(|k| *k == s).expect("kind");
match n {
"unary" | "binary" | "tertiary" | "unaryBits" | "legacyF16ToF32" | "legacyF32ToF16"
| "isSpecialFloat" | "dot2" | "dot3" | "dot4" | "quaternary" => k("math_call"),
"bufferLoad" | "rawBufferLoad" => k("buffer_load"),
"cbufferLoadLegacy" | "cbufferLoad" => k("cbuffer_load"),
"bufferStore" | "rawBufferStore" | "textureStore" => k("buffer_store"),
"atomicBinOp" | "atomicCompareExchange" => k("atomic"),
"createHandle" | "createHandleFromBinding" | "createHandleFromHeap" => k("handle"),
"annotateHandle" => k("annotate"),
"getDimensions" => k("dimensions"),
"barrier" => k("barrier"),
_ if n.starts_with("wave") || n.starts_with("quad") => k("wave_op"),
_ if n.starts_with("textureLoad")
|| n.starts_with("sample")
|| n.starts_with("textureGather")
|| n.starts_with("calculateLOD") =>
{
k("texture_read")
}
_ => k("io_other"),
}
}
impl Module {
/// The instructions [`Module::write`] writes, by kind.
pub(crate) fn census(&self) -> Census {
let k = |s: &str| KINDS.iter().position(|k| *k == s).expect("kind");
let call_kind: Vec<usize> = self.funcs.iter().map(|f| kind(&f.name)).collect();
let live = self.live();
// The blocks `write` lays out: those reached from the entry.
let mut seen = vec![false; self.blocks.len()];
let mut stack = vec![0usize];
if !self.blocks.is_empty() {
seen[0] = true;
}
while let Some(b) = stack.pop() {
for &s in super::successors(self.blocks[b].term).iter() {
if !seen[s] {
seen[s] = true;
stack.push(s);
}
}
}
let mut c = Census::default();
for (b, blk) in self.blocks.iter().enumerate() {
if !seen[b] {
continue;
}
c.counts[k("blocks")] += 1;
let _: Option<Term> = blk.term;
for &i in blk
.phis
.iter()
.filter(|&&i| live[i as usize])
.chain(&blk.body)
{
c.counts[0] += 1;
let at = match &self.insts[i as usize].op {
Op::Bin(..) | Op::Cmp(..) => k("arith"),
Op::Cast(Cast::Bitcast, _) => k("bitcast"),
Op::Cast(..) => k("cast"),
Op::Select(..) => k("select"),
Op::Extract(..) => k("extract"),
Op::Phi(_) => k("phi"),
Op::Gep(..) => k("gep"),
Op::Load(_) => k("lds_load"),
Op::Store(..) => k("lds_store"),
Op::AtomicRmw(..) | Op::CmpXchg(..) => k("atomic"),
Op::Call(f, _) => call_kind[*f as usize],
};
c.counts[at] += 1;
match self.tags.get(&i) {
Some(Tag::Guard) => c.counts[k("guard_select")] += 1,
Some(Tag::Clamp) => c.counts[k("clamp")] += 1,
Some(Tag::Counter) => c.counts[k("loop_counter")] += 1,
None => {}
}
let _ = V::Inst(i);
}
}
c
}
}
File diff suppressed because it is too large. Load diff
+31 -13
View File
@@ -9,7 +9,7 @@
use std::collections::{BTreeMap, HashMap, HashSet};
use super::UserData;
use super::bitcode::{Attr, Bin, Cast, Rmw, Term, V, pred};
use super::bitcode::{Attr, Bin, Cast, Rmw, Tag, Term, V, pred};
use super::container::SigElement;
use super::shader::{Shader, flags};
use crate::ShaderError;
@@ -2645,6 +2645,7 @@ impl<'a> Lower<'a> {
let page = self
.s
.op(c, "binary.i32", Attr::ReadNone, i32t, 40, &[page, last]);
self.s.m.tag(page, Tag::Clamp);
let k3 = k(self, 3);
let at = self.s.m.bin(c, Bin::Shl, page, k3);
let directory = self.s.root_srv_handle(SLOT_MEMORY);
@@ -3787,7 +3788,9 @@ impl<'a> Lower<'a> {
// The validator refuses reads of undef.
_ => self.s.m.i32(0),
};
self.s.m.select(self.cur, g, x, old)
let v = self.s.m.select(self.cur, g, x, old);
self.s.m.tag(v, Tag::Guard);
v
}
_ => x,
};
@@ -6175,6 +6178,7 @@ impl<'a> Lower<'a> {
let last = self.s.m.i32(super::shader::SLOT_STRIDES_COUNT - 1);
let i32t = self.s.t.i32;
let slot = self.s.op(c, "binary.i32", Attr::ReadNone, i32t, 40, &[slot, last]);
self.s.m.tag(slot, Tag::Clamp);
let two = self.s.m.i32(2);
let byte = self.s.m.bin(c, Bin::Shl, slot, two);
let h = self.s.root_srv_handle(super::shader::SLOT_STRIDES);
@@ -7288,16 +7292,26 @@ impl<'a> Lower<'a> {
return Err("a first-lane read where not every lane runs");
}
let c = self.cur;
let i32t = self.s.t.i32;
let has = self.s.m.cast(c, Cast::ZExt, any, i32t);
let (lo_has, hi_has) = self.exchange_halves(c, has);
let (lo, hi) = self.exchange_halves(c, mine);
let z = self.s.m.i32(0);
let in_lo = self.s.m.cmp(c, pred::NE, lo_has, z);
let in_hi = self.s.m.cmp(c, pred::NE, hi_has, z);
// neither half has a lane in EXEC: the console reads lane 0
let hi = self.s.m.select(c, in_hi, hi, lo);
self.s.m.select(c, in_lo, lo, hi)
if guard.is_none() && super::shader_opt() & super::bitcode::opt::FIRST != 0 {
// Every lane is in EXEC: the console's first lane is
// lane 0, which the lower half of every console wave
// has. No half needs to ask the other whether it has
// a lane (an exchange of the constant 1: two group
// barriers), and the lower half's value is the answer.
let (lo, _) = self.exchange_halves(c, mine);
lo
} else {
let i32t = self.s.t.i32;
let has = self.s.m.cast(c, Cast::ZExt, any, i32t);
let (lo_has, hi_has) = self.exchange_halves(c, has);
let (lo, hi) = self.exchange_halves(c, mine);
let z = self.s.m.i32(0);
let in_lo = self.s.m.cmp(c, pred::NE, lo_has, z);
let in_hi = self.s.m.cmp(c, pred::NE, hi_has, z);
// neither half has a lane in EXEC: the console reads lane 0
let hi = self.s.m.select(c, in_hi, hi, lo);
self.s.m.select(c, in_lo, lo, hi)
}
} else {
mine
};
@@ -10511,6 +10525,8 @@ impl<'a> Lower<'a> {
let (phi, _) = self.counters[&to];
let one = self.s.m.i32(1);
let next = self.s.m.bin(c, Bin::Add, phi, one);
self.s.m.tag(phi, Tag::Counter);
self.s.m.tag(next, Tag::Counter);
// Per stage unless the switch names one: a loop that never meets its
// exit (a count read from a buffer the host has not got yet, say)
// runs to the limit in every lane. A million iterations a pixel
@@ -10534,7 +10550,9 @@ impl<'a> Lower<'a> {
.expect("header")
.1
.push((next, c));
self.s.m.cmp(c, p, next, limit)
let over = self.s.m.cmp(c, p, next, limit);
self.s.m.tag(over, Tag::Counter);
over
}
/// The block a lane stopped by [`LOOP_LIMIT`] leaves through.
+44
View File
@@ -108,6 +108,7 @@ use crate::dxbc::{Container, FourCC};
use crate::native::{HwStage, NativeProgram, RootType};
use crate::{ShaderError, io, ir, resource, structure};
pub use bitcode::census;
pub use sampler::StaticSampler;
pub use lower::set_host_max_wave;
pub use rect::rect_list_gs;
@@ -167,6 +168,38 @@ pub fn group_sync() -> u8 {
})
}
/// The clean-up passes that run over a translated program before it is
/// written (`bitcode::opt`): a set of that module's pass bits. Every pass
/// is exact, so the switch is for telling a translator fault from a
/// clean-up fault, and for measuring what the clean-up is worth.
/// `VICTORY_SHADER_OPT`:
/// - unset: every pass.
/// - `0`: none (the module as the lowering made it).
/// - a number (decimal or `0x` hex): those passes; 1 dead code, 2 constants
/// and identities, 4 one instruction for one value, 8 what a branch taken
/// says about its condition, 16 one read for one place within a block,
/// 32 a first-lane read of two host waves without the round that asks
/// which half has a lane (where every lane has one).
///
/// Part of the translation: the shader cache keys on it (`victory-gpu`'s
/// does).
pub fn shader_opt() -> u32 {
static PASSES: std::sync::OnceLock<u32> = std::sync::OnceLock::new();
*PASSES.get_or_init(|| parse_shader_opt(std::env::var("VICTORY_SHADER_OPT").ok().as_deref()))
}
/// `VICTORY_SHADER_OPT`'s value; every pass when it is unset or
/// unreadable. Pure, for testing.
fn parse_shader_opt(value: Option<&str>) -> u32 {
let parsed = value
.map(str::trim)
.and_then(|v| match v.strip_prefix("0x") {
Some(hex) => u32::from_str_radix(hex, 16).ok(),
None => v.parse().ok(),
});
parsed.map_or(bitcode::opt::ALL, |n| n & bitcode::opt::ALL)
}
/// `VICTORY_SHADER_LOOP_LIMIT`'s value; the default when it is unset,
/// unreadable or 0. Pure, for testing.
fn parse_loop_limit(value: Option<&str>) -> u32 {
@@ -727,6 +760,17 @@ mod tests {
use super::lower::LOOP_LIMIT;
use super::parse_loop_limit;
#[test]
fn the_clean_up_switch_parses_or_runs_every_pass() {
let all = super::bitcode::opt::ALL;
assert_eq!(parse_shader_opt(None), all);
assert_eq!(parse_shader_opt(Some("0")), 0);
assert_eq!(parse_shader_opt(Some(" 1 ")), 1);
assert_eq!(parse_shader_opt(Some("0x1")), 1);
assert_eq!(parse_shader_opt(Some("0xffffffff")), all);
assert_eq!(parse_shader_opt(Some("on")), all);
}
#[test]
fn the_loop_limit_switch_parses_or_falls_back() {
assert_eq!(parse_loop_limit(None), LOOP_LIMIT);
+27 -2
View File
@@ -402,7 +402,9 @@ impl Shader {
let index = if !sampler && limit != 0 {
let null = self.m.i32(limit);
let i32t = self.t.i32;
self.op(block, "binary.i32", Attr::ReadNone, i32t, 40, &[index, null])
let v = self.op(block, "binary.i32", Attr::ReadNone, i32t, 40, &[index, null]);
self.m.tag(v, super::bitcode::Tag::Clamp);
v
} else if sampler {
// A sampler heap has at most 2,048 samplers on any host: an
// index past that (a number read from memory the host has not
@@ -411,7 +413,9 @@ impl Shader {
// heap smaller than 2,048 would need.
let last = self.m.i32(2047);
let i32t = self.t.i32;
self.op(block, "binary.i32", Attr::ReadNone, i32t, 40, &[index, last])
let v = self.op(block, "binary.i32", Attr::ReadNone, i32t, 40, &[index, last]);
self.m.tag(v, super::bitcode::Tag::Clamp);
v
} else {
index
};
@@ -437,6 +441,26 @@ impl Shader {
pub fn finish(mut self) -> Vec<u8> {
let ud_size = (self.user_data * 4).next_multiple_of(16);
self.fix_user_data_size(ud_size);
// The clean-up, before anything is declared about the code: a
// feature whose last use it removed must not be declared (the
// validator compares the flags with what the code uses).
let passes = super::shader_opt() & super::bitcode::opt::MODULE;
if passes != 0 {
self.m.optimise(passes);
let used = self.m.usage();
for (flag, used) in [
(flags::WAVE_OPS, used.wave_ops),
(flags::INT64, used.int64),
(flags::TYPED_UAV_LOADS, used.typed_uav_loads),
(flags::RESOURCE_HEAP, used.heap_views),
(flags::SAMPLER_HEAP, used.heap_samplers),
(flags::ATOMIC_TYPED64 | flags::ATOMIC_HEAP64, used.atomic64),
] {
if !used {
self.flags &= !flag;
}
}
}
let mut resources = None;
let mut bindings = Vec::new();
let i32c = |s: &mut Self, v: u32| {
@@ -737,6 +761,7 @@ impl Shader {
self.m.named_md("dx.entryPoints", vec![entry]);
let bitcode = self.m.write();
super::bitcode::census::note(&self.m, &bitcode);
let mut dxil = Vec::with_capacity(24 + bitcode.len());
dxil.extend((kind << 16 | 0x66).to_le_bytes());
dxil.extend((((24 + bitcode.len()) / 4) as u32).to_le_bytes());
@@ -251,6 +251,11 @@ fn run_cases_on(
}
ran += 1;
}
if ran == 0 && devices.iter().all(|&(_, warp)| !warp) {
// A case for the hardware adapter alone, on a machine without one.
eprintln!("no SM 6.6 hardware device; a hardware-only case not run");
return;
}
assert!(ran > 0, "no SM 6.6 device available ({devices:?})");
}