The first room renders right: byte-copied descriptor records are mirrored, views off their copy's elements get their own bytes, card room for the first world frame, levels on demand run on the card

- Descriptor records the title copies into its heap as bytes are mirrored
  before each submission (pull request #305 by Flyander, after upstream
  VIctory 86a5ed6), with a per-slot fingerprint so only records that
  changed are mirrored, the page read through the kernel, a switch
  (VICTORY_HEAP_SYNC=0) and a counter: about 40,000 records a frame on the
  test machine.
- A buffer view off its copy's elements gets a copy of its own bytes
  (after upstream 86a5ed6; VICTORY_VIEW_OWN_COPY=0: refused as before).
- Room on the card for the world's first-frame bursts: buffer copies
  (VICTORY_CARD_ROOM_FOR_BUFFERS, now on) and render targets
  (VICTORY_CARD_ROOM_FOR_TARGETS_MB, 3,072); a copy turned down gives its
  room up and is logged; the texture pass asks again every 32 MiB. 98
  buffer copies made (945 MB) where earlier runs made 1; 25 MB compared
  on the processor a frame where it was 550 to 710.
- Levels on demand: the fixes of pull request #747 by AscilCH. First run
  on a card (RTX 4070, VICTORY_LEVELS_ON_DEMAND=1): no device loss, 3.1 GB
  not allocated for levels the title does not hold. Still off by default.
- The guarded blocks under storage writes into physical pages are opened
  by default (VICTORY_PAGE_WRITES=0: counted only).
- Shaders: a program is translated with first-half interpolation pairs
  only if it was refused for one (with it on for every program 8,551
  working pixel programs came out changed); parked lane-mask pairs,
  f64 conversions and sums, lane permutations: 14 more programs translate.
- Counted, not fixed: an indirect compute pass asks for about 77,500
  groups in x and is cut to 65,535.

One five-minute game run of these changes on the test machine: no device
loss, no failed request. This merged tree was built; its test suites
were not run.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
fxcelessandClaude Fable 5.2 committed 2026-11-25 01:46:49 -05:00
1 parent 8dd30ab472
commit a26859fc5f
13 files changed
+1188 -58

No files matched your search

+185 -10
View File
@@ -1016,6 +1016,26 @@ fn own_bits_on() -> bool {
*ON.get_or_init(|| std::env::var_os("VICTORY_WAVE_OWN_BITS").is_none_or(|v| v != "0"))
}
/// The refusal of a first half of an interpolation whose result is read
/// as data ([`Lower::interp`]).
pub(super) const FIRST_HALF: &str = "the first half of an interpolation";
thread_local! {
/// Whether first halves of interpolations are evaluated as the pair
/// they start ([`with_first_half_pairs`]).
static FIRST_HALF_PAIRS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
/// Runs `translate` with first halves of interpolations evaluated as the
/// pair they start: the translation of a program refused with
/// [`FIRST_HALF`] (`VICTORY_FIRST_HALF=0`: refused again, as before).
pub(super) fn with_first_half_pairs<R>(translate: impl FnOnce() -> R) -> R {
let before = FIRST_HALF_PAIRS.replace(true);
let result = translate();
FIRST_HALF_PAIRS.set(before);
result
}
pub(super) fn host_max_wave() -> u32 {
#[cfg(test)]
if let Some(lanes) = TEST_HOST_WAVE.get() {
@@ -1497,7 +1517,9 @@ impl<'a> Lower<'a> {
// the other half of its dst, PS_DeferredTextured): evaluated as the pair it
// starts. Approximate for those other bits (P0 + i P10 on the console); a
// first half only the second half reads is gone before lowering.
if std::env::var_os("VICTORY_FIRST_HALF").is_none_or(|v| v != "0") {
// Only in the second translation of a program the first
// one refused for it ([`with_first_half_pairs`]).
if FIRST_HALF_PAIRS.get() && std::env::var_os("VICTORY_FIRST_HALF").is_none_or(|v| v != "0") {
for (_, i) in &x.io.interps {
if let Interp::Interpolated { first, .. } = i {
for s in first {
@@ -2083,8 +2105,9 @@ impl<'a> Lower<'a> {
if !every {
if halves {
need(self.cur_ir);
return Err(WHERE);
}
return Err(WHERE);
return Ok(self.half_sum_present(x));
}
let c = self.cur;
let i32t = self.s.t.i32;
@@ -2112,6 +2135,61 @@ impl<'a> Lower<'a> {
Ok(self.s.m.bin(c, Bin::Or, first, total))
}
/// [`Self::half_sum`] in one host wave of 64 where some lanes have left (a thread past
/// the end of the data returns early): the console runs the sum in every lane, a lane
/// outside EXEC with +0, so after step k every lane of an aligned run of 2^k lanes holds
/// that run's partial sum, the lanes that left included. A lane reads its partner run's
/// sum from the first lane of that run that is here, and +0 where none is (every lane of
/// the run left, so its terms were all +0). Lane 0's high half likewise: 0 if it left.
fn half_sum_present(&mut self, x: V) -> V {
let c = self.cur;
let i32t = self.s.t.i32;
self.s.flags |= flags::WAVE_OPS;
let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]);
let here = self.s.m.bool(true);
let ballot = self.s.op(c, "waveActiveBallot", Attr::NoUnwind, four, 116, &[here]);
let (blo, bhi) = (self.s.m.extract(c, ballot, 0), self.s.m.extract(c, ballot, 1));
let lane = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]);
let [zero, k31, k32] = [0, 31, 32].map(|k| self.s.m.i32(k));
// The lanes of the run of `size` lanes at `base` that are here, from bit 0.
let present = |l: &mut Self, base: V, size: u32| -> V {
let upper = l.s.m.cmp(c, pred::IUGE, base, k32);
let word = l.s.m.select(c, upper, bhi, blo);
let at = l.s.m.bin(c, Bin::And, base, k31);
let bits = l.s.m.bin(c, Bin::LShr, word, at);
if size >= 32 {
bits
} else {
let m = l.s.m.i32((1u32 << size) - 1);
l.s.m.bin(c, Bin::And, bits, m)
}
};
let mut sum = x;
for step in 0..6u32 {
let size = 1u32 << step;
let (bit, run) = (self.s.m.i32(size), self.s.m.i32(!(size - 1)));
let other = self.s.m.bin(c, Bin::Xor, lane, bit);
let base = self.s.m.bin(c, Bin::And, other, run);
let bits = present(self, base, size);
// FirstbitLo (dx.op 32): the run's first lane that is here
let first = self.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[bits]);
let any = self.s.m.cmp(c, pred::NE, bits, zero);
let first = self.s.m.select(c, any, first, zero);
let from = self.s.m.bin(c, Bin::Add, base, first);
let theirs = self.read_lane(sum, from);
let theirs = self.s.m.select(c, any, theirs, zero);
sum = self.add_halves(sum, theirs);
}
let (high, low, one) = (self.s.m.i32(0xFFFF_0000), self.s.m.i32(0xFFFF), self.s.m.i32(1));
let lane0 = self.s.m.bin(c, Bin::And, blo, one);
let lane0 = self.s.m.cmp(c, pred::NE, lane0, zero);
let first = self.read_lane(x, zero);
let first = self.s.m.select(c, lane0, first, zero);
let first = self.s.m.bin(c, Bin::And, first, high);
let sum = self.s.m.bin(c, Bin::And, sum, low);
self.s.m.bin(c, Bin::Or, first, sum)
}
fn run(mut self) -> Result<Lowered, Stop> {
let p = self.x.p;
let order = crate::ir::reverse_postorder(&p.blocks);
@@ -5617,6 +5695,18 @@ impl<'a> Lower<'a> {
.find_map(|(s, _)| use_of(*s))
};
let use_at = use_of(site).or_else(twin);
// A descriptor nothing uses as one, whose size the code reads all the same (a
// texture picked from the heap by an index in a constant buffer, its width and
// height turned into a texel size; a buffer tested for being empty by its record
// count): the kind from its dwords and its used-resource entry.
let unused = if use_at.is_none() {
self.unused_descriptor_kind(inst, site, code, count)
} else {
None
};
let (first, props, image, uav, used) = if let Some(kind) = unused {
kind
} else {
let Some((at, first)) = use_at else {
// A descriptor kept per lane in VGPRs (`Resources::lane_copied`): the code only
// copies its dwords and compares them, lane against first lane, and every load
@@ -5726,6 +5816,9 @@ impl<'a> Lower<'a> {
}
_ => return Err("a scalar memory read as data"),
};
(first, props, image, uav, used)
};
let src = Source::Loaded { load: site, first };
let h = self.handle(site, &src, false, props)?;
let c = self.cur;
let i32t = self.s.t.i32;
@@ -5793,8 +5886,10 @@ impl<'a> Lower<'a> {
inst.write(Reg::S(code + first + k))
.is_some_and(|v| self.computed_with(v, 6))
});
// (A descriptor nothing uses as one gets it whenever the host can tell it, as
// a buffer whose address alone is read does.)
if first == 0
&& computed
&& (computed || unused.is_some())
&& let Some((lo, hi)) = self.view_address(site)
{
words.extend([(0, lo), (1, hi)]);
@@ -5817,6 +5912,67 @@ impl<'a> Lower<'a> {
Ok(())
}
/// What [`Self::descriptor_data`] makes of a descriptor load that nothing uses as a
/// descriptor but whose dwords the code reads: the first dword, the handle properties,
/// the image kind (none for a buffer), whether it is an unordered view, and its
/// used-resource entry. An image's eight dwords read as a 2D texture's, a buffer's four
/// as a raw view's where the code reads its record count (dword 2); none for anything
/// else (a constant buffer, a sampler, a buffer whose address alone is read).
// shortcut: an image whose kind nothing tells is taken for a 2D texture (the title's
// reads are texel sizes of 2D textures: puddle masks, shadow masks); a host view of
// another kind would answer its own sizes.
#[allow(clippy::type_complexity)]
fn unused_descriptor_kind(
&self,
inst: &Inst,
site: Site,
code: u8,
count: u32,
) -> Option<(u8, (u32, u32), Option<u32>, bool, Option<&'a UsedResource>)> {
// Kept per lane and compared (`Resources::lane_copied`), or a sampler's: the cases
// `descriptor_data` handles on their own.
if self.x.res.lane_copied.contains(&site)
|| self.x.res.descriptors.iter().any(|d| {
d.role == Role::Sampler
&& d.source.leaves().into_iter().any(
|l| matches!(*l, Source::Loaded { load, .. } if load == site),
)
})
{
return None;
}
let used = self.used_kind(&Source::Loaded {
load: site,
first: 0,
});
if used.is_some_and(|u| !matches!(u.kind, ResourceType::Srv | ResourceType::Uav)) {
return None;
}
let read = |k: u32| {
inst.write(Reg::S(code + k as u8)).is_some_and(|v| {
self.x
.p
.blocks
.iter()
.flat_map(|b| &b.insts)
.any(|i| i.reads.iter().any(|r| r.1 == v))
})
};
let uav = used.is_some_and(|u| u.kind == ResourceType::Uav);
let u = if uav { 0x1000 } else { 0 };
match count {
// width (dwords 1-2), height (2), levels (3), depth (4)
8 if (1..5).any(read) && used.is_none_or(|u| u.dwords == 8) => {
Some((0, (2 | u, 0x409), Some(2), uav, used))
}
// the record count
4 if read(2) && used.is_none_or(|u| u.dwords == 4) => {
Some((0, (11 | u, 0), None, uav, used))
}
_ => None,
}
}
/// `s_load_dword*` from the program's constant table.
fn code_smem(&mut self, inst: &Inst, a: Address) -> Result<(), Why> {
let Fields::Smem {
@@ -7115,12 +7271,6 @@ impl<'a> Lower<'a> {
let r = self.read_lane(x, from);
int(self, r)
}
"v_cvt_f32_f64" => {
let (lo, hi) = self.f64_pair(inst, 0)?;
let bits = self.f64_to_f32_bits(lo, hi);
let r = self.as_float(bits);
float(self, r)
}
"v_cvt_f32_i32" | "v_cvt_f32_u32" | "v_cvt_f32_ubyte0" | "v_cvt_f32_ubyte1"
| "v_cvt_f32_ubyte2" | "v_cvt_f32_ubyte3" => {
let mut a = s(self, 0)?;
@@ -7138,6 +7288,12 @@ impl<'a> Lower<'a> {
let r = self.s.m.cast(c, op, a, self.s.t.f32);
float(self, r)
}
"v_cvt_f32_f64" => {
let (lo, hi) = self.f64_pair(inst, 0)?;
let bits = self.f64_to_f32_bits(lo, hi);
let r = self.as_float(bits);
float(self, r)
}
"v_fma_mix_f32" | "v_fma_mixlo_f16" | "v_fma_mixhi_f16" => {
// Each source is f32, or with op_sel_hi the low (op_sel: high)
// f16 half; neg_hi is the absolute value here.
@@ -8902,7 +9058,26 @@ impl<'a> Lower<'a> {
fn interp(&mut self, inst: &Inst, site: Site) -> Result<(), Why> {
let Some(&interp) = self.interps.get(&site) else {
return Err("the first half of an interpolation");
// The first half of a pair: its second half interpolates the
// attribute itself, so nothing needs this half's partial sum.
// But an f16 second half that writes the high half of the
// register this one wrote keeps the low half as it was (the
// console compiler reuses the register; the low half is not
// read), so the register needs a value: 0.
let name = inst.name();
if name == "v_interp_p1_f32" || name == "v_interp_p1ll_f16" {
let dst = match &inst.fields {
Fields::Vintrp { dst, .. } => Some(*dst),
Fields::Valu(v) => v.dst,
_ => None,
};
if let Some(Operand::Vector { reg, .. }) = dst {
let zero = self.s.m.i32(0);
self.write(inst, Reg::V(reg), zero, None);
return Ok(());
}
}
return Err(FIRST_HALF);
};
let name = inst.name();
let (dst, src) = match &inst.fields {
+16
View File
@@ -297,7 +297,23 @@ pub struct UserData {
/// Translates the vertex, pixel, compute or mesh program of a console
/// shader container.
///
/// A program refused because the first half of an interpolation is read as
/// data is translated once more with first halves evaluated as the pair
/// they start (`lower::with_first_half_pairs`), and only such a program:
/// with that on for every program, 8,551 pixel programs of the title that
/// already translated came out changed (an extra evaluation in each), for
/// the sake of 9 that did not translate.
pub fn translate(container: &[u8]) -> Result<HostShader, ShaderError> {
match translate_plain(container) {
Err(ShaderError::Unsupported { what, .. }) if what == lower::FIRST_HALF => {
lower::with_first_half_pairs(|| translate_plain(container))
}
other => other,
}
}
fn translate_plain(container: &[u8]) -> Result<HostShader, ShaderError> {
let c = Container::parse(container)?;
let dxil = c
.part(FourCC::DXIL)
+81 -1
View File
@@ -95,10 +95,20 @@ fn native_of(body: &[u32], wave64: bool, threads: u32) -> NativeProgram {
/// `program()` for a host of 32-lane waves, with the branches closing `wide` taken wave-wide.
fn lowered(native: &NativeProgram, p: &ir::Program, wide: &HashSet<usize>) -> Result<HostShader, ShaderError> {
lowered_on(native, p, wide, 32)
}
/// [`lowered`] for a host whose waves have at most `host_wave` lanes.
fn lowered_on(
native: &NativeProgram,
p: &ir::Program,
wide: &HashSet<usize>,
host_wave: u32,
) -> Result<HostShader, ShaderError> {
let st = structure::structure_wide(p, wide).expect("structure");
let res = resource::track(p, &native.layout, native.stage, Some(&st)).expect("resource::track");
let io = io::raise(p, native).expect("io::raise");
let was = lower::TEST_HOST_WAVE.replace(Some(32));
let was = lower::TEST_HOST_WAVE.replace(Some(host_wave));
let lowered = lower::lower(&lower::Parts {
native,
p,
@@ -199,6 +209,76 @@ fn a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit() {
eprintln!("ran on the hardware device: the sum {:#x} of the console's tree", tree[0]);
}
/// The console's 16-bit wave sum where the lanes at or past s0 have left the program (a
/// thread past the end of the data): on the console they add +0, and after each step of the
/// tree they hold their run's partial sum all the same. On a host of 64-lane waves (AMD) the
/// lanes that are here read each partner run's sum from a lane of it that is here.
#[test]
fn a_sum_of_halves_where_lanes_have_left_is_the_consoles_tree_bit_for_bit() {
let mut words = vec![
0x7DA8_0000, // v_cmpx_gt_u32 exec, s0, v0: the lanes below s0 stay
0, // s_cbranch_execz to the end (filled in below)
0x340C_0085, // v_lshlrev_b32 v6, 5, v0
0x340E_0082, // v_lshlrev_b32 v7, 2, v0
0x4A0E_0F06, // v_add_nc_u32 v7, v6, v7
0x4A0E_0F00, // v_add_nc_u32 v7, v0, v7
0x4A0E_0EFF,
0x0000_3C00, // v_add_nc_u32 v7, 0x3c00, v7
];
words.extend(super::wave::WAVE_OR_V7_TO_S7.iter().map(|&w| if w >> 25 == 28 { w & 0x01FF_FFFF | 50 << 25 } else { w }));
words.extend_from_slice(&[
0x7E00_0207, // v_mov_b32 v0, s7
0x38 << 26 | 0x1C << 18,
0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0
]);
// past every word after it, to the program's end
words[1] = 0xBF88_0000 | (words.len() as u32 - 2);
let native = native(&words);
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
let shader = lowered_on(&native, &p, &HashSet::new(), 64).expect("lower");
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
let mut copy = shader.dxil.clone();
v.validate(&mut copy).expect("DXIL validation failed");
}
let wide = |h: u16| {
if h == 0 {
0.0
} else {
f32::from_bits((u32::from(h >> 10) + 112) << 23 | u32::from(h & 0x3FF) << 13)
}
};
let narrow = |f: f32| {
if f == 0.0 {
return 0;
}
let b = f.to_bits();
let h = ((b >> 23) - 112) << 10 | (b >> 13 & 0x3FF);
let rest = b & 0x1FFF;
(h + u32::from(rest > 0x1000 || rest == 0x1000 && h & 1 == 1)) as u16
};
let add = |a: u16, b: u16| narrow(wide(a) + wide(b));
let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
let mut ran = false;
for stay in [64u32, 63, 40, 33, 32, 17, 5, 1] {
let terms: Vec<u16> = (0..64u32)
.map(|t| if t < stay { (0x3C00 + 37 * t) as u16 } else { 0 })
.collect();
let mut tree = terms.clone();
while tree.len() > 1 {
tree = tree.chunks(2).map(|c| add(c[0], c[1])).collect();
}
let Some(got) = on_the_card(&shader, [stay, 0]) else {
return;
};
ran = true;
// (the high half is lane 0's term's: zero)
assert_eq!(got, u32::from(tree[0]), "{stay} lanes stay: got {got:#x}, the console's tree {:#x}", tree[0]);
}
if ran {
eprintln!("ran on the hardware device: the console's tree with lanes gone, in every case");
}
}
/// One `v_add_f16` whose exact result lies between two halves: 1 + 3/1024 (0x3C03) plus 2
/// (0x4000) is 3 + 1.5 steps of that range, which the console rounds up to 0x4202. The
/// host's `f32tof16` may give 0x4201 (toward zero); with `VICTORY_F16_NEAREST=1` the