mirror of
https://github.com/ivall/xcl.git
synced 2026-11-24 05:14:57 +01:00
Wave64 VS / PS in 32-lane waves: the lanes 32..63 they read
On a GPU with 32-lane waves only (NVIDIA) the driver runs a console wave64 VS / PS in waves of 32: a console wave whose lanes 32..63 are not populated. Those lanes exist on the console (inactive) and hold what v_writelane or whole-wave code put there; here they do not exist, and WaveReadLaneAt of a lane >= 32 reads lane & 31. The 749 programs wave_hazards flagged in the retail pack (748 PS, 1 VS): - 1 082 reads in 436 programs: whole-wave reductions (identity into the lanes outside the mask, DPP8 xor 1/2/4, row_mirror, v_permlanex16, v_readlane 32 for the upper half; min_u32 / max_u32 / or_b32). Right only because lane 32 reads lane 0 and those ops are idempotent. - 355 reads in 353 programs: waterfall reads, v_readlane v, s_ff1(mask & EXEC) - a lane < 32. Right. - 200 reads in 11 programs: SGPR spill slots in lanes 32..47. Wrong: the v_writelane is lost, the read gets another slot. upper_lanes.rs follows what the console's lanes 32..63 hold through the program (forward pass: EXEC's upper word through the SGPRs as 0 / all ones / anything; per VGPR lane unwritten / a constant / a spill slot / unknown, evaluating whole-wave moves, selects, integer min / max / logic / add and their DPP forms). With split_wave64 a wave64 VS / PS reads a lane >= 32 that holds a constant as the constant, and a spill slot from a scalar shadow its v_writelanes also write, when WaveGetLaneCount() < 64. Spill slots < 32 come from their shadows at any wave size: a lane a partial wave did not launch loses its slot (287 PS spill to lanes < 32). Only programs with such a read get the form (613 of the pack; DXC compiles all). Without split_wave64 the HLSL of all 26 698 programs is unchanged, and so is the 32-lane form of the other modes (digests compared with main, retail_wave64_graphics_lane_forms). wave_hazards now reports only reads the pass cannot follow: none in the pack. GPU tests on an RTX 5070 Ti: gpu_wave64_ps_whole_wave_reductions (the pack's reduction as min and as a sum, and the waterfall read, per hardware wave against a console wave of the same lanes), gpu_wave64_ps_spill_slots (full target and a 6-pixel triangle), gpu_wave64_vs_spill_slots_and_identity (3 vertices). With the old form all three fail there. Not exact yet, on every GPU: whole-wave code in a partial wave reads lanes the PC never launched. On the 5070 Ti they read 0, so a min reduction gives 0 in a partial pixel wave (325 programs have one); max / or are right. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+26
-2
@@ -1690,7 +1690,31 @@ of the title (it writes to address 0 after a failed D3D12 call: `call 0x14068c76
|
||||
title screen right with a warm cache. With a cold cache the title screen's text comes ~15 s after the logo. Also merged: #92 (the VFS hook guard keeps
|
||||
GetLastError – GNU builds' TLS access reset it), #93 (under Wine PEB.ImageBaseAddress stays the real image).
|
||||
- Still open on NVIDIA: wave64 VS / PS with readlane of lanes 32..63 (`wave_hazards`; the driver picks 32-lane
|
||||
waves, lanes ≥ 32 do not exist – `WaveReadLaneAt` wraps to lane & 31 there).
|
||||
waves, lanes ≥ 32 do not exist – `WaveReadLaneAt` wraps to lane & 31 there). Done next (below).
|
||||
|
||||
## Wave64 VS / PS in 32-lane waves (NVIDIA), 2026-11-23
|
||||
- Census of the 749 flagged programs (748 PS, 1 VS; `retail_wave64_graphics_lane_census`, ignored): 1 082 reads in
|
||||
436 programs are a whole-wave reduction (identity into the lanes outside the mask, DPP8 xor
|
||||
1/2/4, row_mirror, `v_permlanex16`, `v_readlane` 32 for the upper half; min_u32 / max_u32 / or_b32) – right on
|
||||
NVIDIA only because lane 32 reads lane 0 and those ops are idempotent; 355 reads in 353 programs are waterfall
|
||||
reads (`v_readlane v, s_ff1(mask & EXEC)`), lane < 32 – right; 200 reads in 11 programs are SGPR spill slots in
|
||||
lanes 32..47 – wrong (the write is lost, the read gets slot lane & 31). No `ds_bpermute`.
|
||||
- `upper_lanes.rs`: a forward pass over the program follows what the console's lanes 32..63 hold (EXEC's upper word
|
||||
through the SGPRs as 0 / all ones / anything; per VGPR lane ≥ 32 unwritten / a constant / a spill slot / unknown,
|
||||
evaluating whole-wave moves, selects, integer min / max / logic / add and their DPP forms). With `split_wave64`
|
||||
a wave64 VS / PS reads a constant lane as the constant and a slot from a scalar shadow its `v_writelane`s also
|
||||
write, when `WaveGetLaneCount() < 64` (`xcl_hw32`); spill slots < 32 (287 PS, 3 540 reads) come from their shadows
|
||||
at any wave size – a lane a partial wave did not launch loses its slot. `wave_hazards` now reports only reads the
|
||||
pass cannot follow: 0 in the pack (was 749 programs). Native HLSL (no `split_wave64`) identical for all 26 698
|
||||
programs, and so is the 32-lane form of every other mode (digests, `retail_wave64_graphics_lane_forms`).
|
||||
- Tests on the RTX 5070 Ti: `gpu_wave64_ps_whole_wave_reductions` (the pack's reduction as min and as a sum, and the
|
||||
waterfall read, per hardware wave against a console wave of the same lanes), `gpu_wave64_ps_spill_slots` (full
|
||||
target and a 6-pixel triangle), `gpu_wave64_vs_spill_slots_and_identity` (3 vertices). With the old form all three
|
||||
fail there: slots 32..47 sum to slots 0..15, the sum reduction doubles, the VS keeps only its 3 lanes' slots.
|
||||
- Not exact yet, on every GPU: whole-wave code in a partial wave reads lanes the PC never launched (the console's
|
||||
inactive lanes run it). Measured on the 5070 Ti: such lanes read 0 – a min reduction (identity -1) gives 0 in a
|
||||
3-quad wave, max / or / sum are right. 325 of the 436 reduction programs have a min reduction. Needs the reduction
|
||||
recognised as a whole (`docs/wave64-on-wave32.md`, "Vertex and pixel shaders").
|
||||
|
||||
## Next steps (priority)
|
||||
Little is left to do without the exe – the rest needs an actual run of the game.
|
||||
@@ -1705,6 +1729,6 @@ Little is left to do without the exe – the rest needs an actual run of the gam
|
||||
pipe/packer configuration for the _X modes (`texture::CONSOLE_PIPES`), MSAA.
|
||||
4. Audio: Opus is decoded (0x704F voices); with the exe check how the title feeds it (voice format, buffer framing, or a
|
||||
console API); XMA2 low priority (the game has none).
|
||||
5. Smaller: 749 wave64 programs at risk in a 32-wide wave (only if they show up), `image_sample_o` with an offset from a VGPR,
|
||||
5. Smaller: whole-wave reductions in partial waves (325 PS with a min reduction, every GPU), `image_sample_o` with an offset from a VGPR,
|
||||
smaller HLSL, further XGameRuntime APIs (XGameUI, XNetworking…), GameInput → system GameInput.dll,
|
||||
mapping physical pages at the game's address.
|
||||
|
||||
@@ -4,6 +4,7 @@ use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::fmt::Write as _;
|
||||
|
||||
use super::{elements_at, param_registers, ps_attribute_slot, ps_input_vgpr, ps_slot_attribute, ranked, vs_param_register, Mode, MsInterface, Options, KERNEL_EXPORTS, KERNEL_LANES, KERNEL_SCC_SLOT, KERNEL_SGPRS, KERNEL_SPLIT_MAGIC, KERNEL_SPLIT_SGPRS, KERNEL_VGPRS, MESH_HEADER};
|
||||
use super::upper_lanes::Read;
|
||||
use crate::gpu::dxbc::SigElement;
|
||||
use crate::gpu::rdna2::{self, Decoded, Encoding, Operand, Variant};
|
||||
|
||||
@@ -42,6 +43,9 @@ pub(super) struct Em {
|
||||
/// split wave64: pc → SGPRs whose whole value may be read after that instruction
|
||||
/// (`x64_masks`); a mask written to none of them stays in its half (no exchange)
|
||||
pub x64_whole_live: BTreeMap<u64, u128>,
|
||||
/// wave64 VS / PS on a GPU with 32-lane waves only: what the console's lanes 32..63 hold
|
||||
/// where the program reads them (`upper_lanes`), used when the wave has 32 lanes
|
||||
pub upper: Option<super::upper_lanes::UpperLanes>,
|
||||
/// pc of the instruction being emitted
|
||||
cur_pc: u64,
|
||||
/// MIMG instruction address → its sampler's S# when the code builds it from constants
|
||||
@@ -450,6 +454,7 @@ impl Em {
|
||||
uses_scratch: false,
|
||||
x64_words: 1,
|
||||
x64_whole_live: BTreeMap::new(),
|
||||
upper: None,
|
||||
cur_pc: 0,
|
||||
static_ss: BTreeMap::new(),
|
||||
static_used: Vec::new(),
|
||||
@@ -3334,7 +3339,21 @@ impl Em {
|
||||
"v_readlane_b32" => {
|
||||
let t = self.t();
|
||||
let rla = self.rla_uniform_fn();
|
||||
self.line(&format!("uint {t} = {rla}({a}, {b} & {wmask}u);"));
|
||||
let read = format!("{rla}({a}, {b} & {wmask}u)");
|
||||
// wave64 VS / PS (`upper_lanes`): in a 32-lane wave, lanes 32..63 without a lane
|
||||
// read; a spill slot < 32 from its shadow whatever the wave size (its lane may
|
||||
// not have been launched)
|
||||
let slot = super::upper_lanes::slot(d);
|
||||
match (self.upper.as_ref().and_then(|u| u.reads.get(&d.pc)).copied(), slot) {
|
||||
(Some(Read::Const(c)), Some(_)) => self.line(&format!("uint {t} = {c:#010x}u; if (!xcl_hw32) {t} = {read};")),
|
||||
(Some(Read::Const(c)), None) => {
|
||||
self.line(&format!("uint {t} = {read};"));
|
||||
self.line(&format!("{t} = select(and(xcl_hw32, ({b} & 63u) >= 32u), {c:#010x}u, {t});"));
|
||||
}
|
||||
(Some(Read::Shadow), Some((v, l))) if l < 32 => self.line(&format!("uint {t} = xcl_sh{v}_{l};")),
|
||||
(Some(Read::Shadow), Some((v, l))) => self.line(&format!("uint {t} = xcl_sh{v}_{l}; if (!xcl_hw32) {t} = {read};")),
|
||||
_ => self.line(&format!("uint {t} = {read};")),
|
||||
}
|
||||
self.write32(&dst, &t);
|
||||
return Ok(());
|
||||
}
|
||||
@@ -3343,6 +3362,11 @@ impl Em {
|
||||
if let Dst::V(n) = &dst {
|
||||
let v = self.vreg(*n);
|
||||
self.line(&format!("if (lane_id == ({b} & {wmask}u)) {v} = {a};"));
|
||||
// a spill slot some read takes from its shadow (`upper_lanes`)
|
||||
let slot = super::upper_lanes::slot(d).filter(|s| self.upper.as_ref().is_some_and(|u| u.shadows.contains(s)));
|
||||
if let Some((v, l)) = slot {
|
||||
self.line(&format!("xcl_sh{v}_{l} = {a};"));
|
||||
}
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
@@ -3768,6 +3792,10 @@ impl Em {
|
||||
"rla"
|
||||
};
|
||||
self.line(&format!("uint {t} = {rla}({v}, {t}_l);"));
|
||||
// a 32-lane wave of a wave64 VS / PS: lanes 32..63 hold a constant (`upper_lanes`)
|
||||
if let Some(Read::Const(c)) = self.upper.as_ref().and_then(|u| u.reads.get(&d.pc)).copied() {
|
||||
self.line(&format!("{t} = select(and(xcl_hw32, {t}_l >= 32u), {c:#010x}u, {t});"));
|
||||
}
|
||||
self.line(&format!("{t} = select(lanebit_at({el}, {eh}, {t}_l), {t}, 0u);"));
|
||||
let dst = Dst::V(f("VDST"));
|
||||
self.write32(&dst, &t);
|
||||
@@ -4025,6 +4053,13 @@ impl Em {
|
||||
if self.x64() {
|
||||
self.x64_prelude(&mut h);
|
||||
}
|
||||
if let Some(u) = &self.upper {
|
||||
// wave64 VS / PS on a GPU with 32-lane waves only (`upper_lanes`)
|
||||
h.push_str("// the wave has 32 lanes: it is a console wave whose lanes 32..63 are not populated\nstatic bool xcl_hw32 = false;\n");
|
||||
for (v, l) in &u.shadows {
|
||||
let _ = writeln!(h, "static uint xcl_sh{v}_{l} = 0u; // v_writelane slot: v{v} lane {l}");
|
||||
}
|
||||
}
|
||||
let infos: Vec<String> = (0..BUF_FORMATS.len()).map(|i| format!("0x{:08X}u", buf_format_info(i))).collect();
|
||||
let _ = writeln!(h, "static const uint FMT_INFO[78] = {{ {} }};", infos.join(", "));
|
||||
h.push_str(PRELUDE_MEM);
|
||||
@@ -4098,6 +4133,9 @@ impl Em {
|
||||
out_struct(&mut h, "XclOut", &vs.outputs);
|
||||
h.push_str("XclOut main(XclIn xi)\n{\n XclOut xo = (XclOut)0;\n");
|
||||
h.push_str(if self.opt.wave64 { " lane_id = WaveGetLaneIndex();\n" } else { " uint xcl_hw_lane = WaveGetLaneIndex();\n xcl_w32 = WaveGetLaneCount() > 32u;\n xcl_half = xcl_w32 ? xcl_hw_lane >> 5 : 0u;\n lane_id = xcl_hw_lane & 31u;\n" });
|
||||
if self.upper.is_some() {
|
||||
h.push_str(" xcl_hw32 = WaveGetLaneCount() < 64u;\n");
|
||||
}
|
||||
load_sgprs(&mut h);
|
||||
h.push_str(" uint scc = 0u;\n { uint2 e0 = ballot(true); exec_lo = e0.x; exec_hi = e0.y; }\n");
|
||||
for &v in &self.vgprs {
|
||||
@@ -4405,6 +4443,9 @@ impl Em {
|
||||
}
|
||||
h.push_str("};\nXclOut main(XclIn xi)\n{\n XclOut xo = (XclOut)0;\n bool xcl_live = false;\n");
|
||||
h.push_str(if self.opt.wave64 { " lane_id = WaveGetLaneIndex();\n" } else { " uint xcl_hw_lane = WaveGetLaneIndex();\n xcl_w32 = WaveGetLaneCount() > 32u;\n xcl_half = xcl_w32 ? xcl_hw_lane >> 5 : 0u;\n lane_id = xcl_hw_lane & 31u;\n" });
|
||||
if self.upper.is_some() {
|
||||
h.push_str(" xcl_hw32 = WaveGetLaneCount() < 64u;\n");
|
||||
}
|
||||
load_sgprs(&mut h);
|
||||
h.push_str(" uint scc = 0u;\n { uint2 e0 = ballot(true); exec_lo = e0.x; exec_hi = e0.y; }\n");
|
||||
let sys = |bit: u32| ps_input_vgpr(ps.input_ena, bit);
|
||||
|
||||
@@ -61,6 +61,7 @@ pub use emit::mesh_passthrough;
|
||||
pub mod runner;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
pub mod upper_lanes;
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
@@ -473,7 +474,9 @@ pub struct Options {
|
||||
/// the GPU runs only 32-lane waves (`D3D12_FEATURE_DATA_D3D12_OPTIONS1::WaveLaneCountMax`
|
||||
/// < 64, e.g. NVIDIA): each console wave of a wave64 kernel / compute / mesh / geometry
|
||||
/// program runs as two hardware wave32 halves that exchange masks and lane values through
|
||||
/// groupshared memory (`docs/wave64-on-wave32.md`). No effect on wave32 programs, VS / PS.
|
||||
/// groupshared memory (`docs/wave64-on-wave32.md`). A wave64 VS / PS (wave size picked by
|
||||
/// the driver) gets the values of lanes 32..63 it reads where a 32-lane wave lacks them
|
||||
/// (`upper_lanes`). No effect on wave32 programs.
|
||||
pub split_wave64: bool,
|
||||
/// first register (space 1) of the program's static samplers (another stage of the same
|
||||
/// pipeline may come first)
|
||||
@@ -1081,38 +1084,27 @@ fn emit_range(c: &Ctx, em: &mut emit::Em, body: &mut String, lo: u64, hi: u64, d
|
||||
}
|
||||
}
|
||||
|
||||
/// Instructions of a wave64 program that break when the GPU runs it in waves of 32 lanes
|
||||
/// (VS / PS: the driver picks the wave size): reads of a lane ≥ 32 or of a lane chosen at run
|
||||
/// time. A wave32 program in 64-lane waves is handled (the halves act as separate waves).
|
||||
/// Cross-lane reads of a wave64 program that are still wrong when the GPU runs it in waves of
|
||||
/// 32 lanes (VS / PS: the driver picks the wave size), by kind: reads of a lane ≥ 32 – or of a
|
||||
/// lane chosen at run time – whose value `upper_lanes` cannot follow. The form for 32-lane
|
||||
/// GPUs (`Options::split_wave64`) resolves the others. A wave32 program in 64-lane waves is
|
||||
/// handled (the halves act as separate waves).
|
||||
pub fn wave_hazards(code: &[u8]) -> BTreeSet<&'static str> {
|
||||
let mut out = BTreeSet::new();
|
||||
wave_lane_reads(code).0
|
||||
}
|
||||
|
||||
/// `wave_hazards` and the kinds of reads `upper_lanes` resolves.
|
||||
pub fn wave_lane_reads(code: &[u8]) -> (BTreeSet<&'static str>, BTreeSet<&'static str>) {
|
||||
let mut insts = Vec::new();
|
||||
let mut off = 0;
|
||||
while off + 4 <= code.len() {
|
||||
let Ok(d) = rdna2::decode(&code[off..], off as u64) else { break };
|
||||
off += d.len;
|
||||
match d.inst.name {
|
||||
"V_READLANE_B32" | "V_WRITELANE_B32" => {
|
||||
let lane = rdna2::field_value(d.enc, &d.words, "SRC1").unwrap_or(0);
|
||||
match lane {
|
||||
0..=105 => {
|
||||
out.insert("v_readlane/writelane: lane number from an SGPR");
|
||||
}
|
||||
160..=192 => {
|
||||
out.insert("v_readlane/writelane: lane ≥ 32");
|
||||
}
|
||||
255 if d.literal.is_some_and(|l| l & 63 >= 32) => {
|
||||
out.insert("v_readlane/writelane: lane ≥ 32");
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
"DS_BPERMUTE_B32" | "DS_PERMUTE_B32" => {
|
||||
out.insert("ds_(b)permute: arbitrary lane");
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
insts.push(d);
|
||||
}
|
||||
out
|
||||
rdna2::resolve_far_jumps(&mut insts);
|
||||
let a = upper_lanes::analyze(&insts);
|
||||
(a.hazards(&insts), a.resolved())
|
||||
}
|
||||
|
||||
/// Operations that cannot be split into two independent native wave32 halves while
|
||||
@@ -1342,6 +1334,15 @@ pub fn translate(code: &[u8], opt: &Options) -> Result<Translation, String> {
|
||||
if opt.wave64 && opt.split_wave64 && matches!(opt.mode, Mode::Kernel | Mode::Compute(_) | Mode::Mesh(_)) && std::env::var_os("XCL_X64_ALL_MASKS").is_none() {
|
||||
em.x64_whole_live = x64_masks::by_pc(&insts, matches!(opt.mode, Mode::Kernel));
|
||||
}
|
||||
// a wave64 VS / PS on a GPU with 32-lane waves only: what lanes 32..63 hold where the
|
||||
// program reads them (the driver may still pick 64 lanes: decided at run time); only a
|
||||
// program with a read to change gets the form
|
||||
if opt.wave64 && opt.split_wave64 && matches!(opt.mode, Mode::Vertex(_) | Mode::Pixel(_)) {
|
||||
let a = upper_lanes::analyze(&insts);
|
||||
if a.reads.values().any(|r| matches!(r, upper_lanes::Read::Const(_) | upper_lanes::Read::Shadow)) {
|
||||
em.upper = Some(a);
|
||||
}
|
||||
}
|
||||
em.max_vgpr = insts
|
||||
.iter()
|
||||
.flat_map(|d| {
|
||||
|
||||
@@ -1637,6 +1637,272 @@ fn gpu_graphics_vs_ps_draw() {
|
||||
}
|
||||
}
|
||||
|
||||
/// One instruction (programs built in loops).
|
||||
fn ins(name: &str, enc: &str, fields: &[(&str, u64)], lit: Option<u32>) -> Vec<u8> {
|
||||
encode(name, enc, fields, lit).unwrap_or_else(|x| panic!("{name}: {x}"))
|
||||
}
|
||||
|
||||
/// A program from instructions, ending in `s_endpgm`.
|
||||
fn program_of(parts: &[Vec<u8>]) -> Vec<u8> {
|
||||
let mut v: Vec<u8> = parts.concat();
|
||||
v.extend(ins("S_ENDPGM", "ENC_SOPP", &[], None));
|
||||
v
|
||||
}
|
||||
|
||||
/// The pixel interface of `gpu_graphics_vs_ps_draw`: v0 / v1 = i / j, v2 / v3 = pixel centre
|
||||
/// x / y, attribute 0 = COLOR.
|
||||
fn draw_psi() -> super::PsInterface {
|
||||
super::PsInterface {
|
||||
inputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF), el("COLOR", 0, 0, 3, 1, 0xF)],
|
||||
outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)],
|
||||
input_ena: 0x302,
|
||||
attrs: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The vertex interface of `gpu_graphics_vs_ps_draw`: POSITION in v4 / v5, COLOR in v8..v11;
|
||||
/// exports pos0 and param0 (COLOR).
|
||||
fn draw_vsi() -> super::VsInterface {
|
||||
super::VsInterface {
|
||||
inputs: vec![el("POSITION", 0, 0, 3, 0, 3), el("COLOR", 0, 0, 3, 1, 0xF)],
|
||||
outputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF), el("COLOR", 0, 0, 3, 1, 0xF)],
|
||||
attr_base: 4,
|
||||
params: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Draw console wave64 VS + PS (`vs` None: position and COLOR passed through; `ps` None:
|
||||
/// COLOR interpolated) with triangles given in pixels of a 16 × 16 target, cleared to -1.
|
||||
/// Translated for this adapter (`runner::options`: on a GPU with 32-lane waves only, the
|
||||
/// form of `upper_lanes`).
|
||||
fn draw_console(vs: Option<&[u8]>, ps: Option<&[u8]>, tris_px: &[[f32; 2]]) -> Vec<[f32; 4]> {
|
||||
use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R32G32B32A32_FLOAT, DXGI_FORMAT_R32G32_FLOAT};
|
||||
let pass_vs = prog(&[
|
||||
("V_MOV_B32", "ENC_VOP1", &[("VDST", 0), ("SRC0", V + 4)], None),
|
||||
("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", V + 5)], None),
|
||||
("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 128)], None),
|
||||
("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 242)], None),
|
||||
("EXP", "ENC_EXP", &[("TGT", 12), ("EN", 0xF), ("VSRC0", 0), ("VSRC1", 1), ("VSRC2", 2), ("VSRC3", 3), ("DONE", 1)], None),
|
||||
("EXP", "ENC_EXP", &[("TGT", 32), ("EN", 0xF), ("VSRC0", 8), ("VSRC1", 9), ("VSRC2", 10), ("VSRC3", 11)], None),
|
||||
]);
|
||||
let pass_ps = prog(&[
|
||||
("V_INTERP_P1_F32", "ENC_VINTRP", &[("VDST", 4), ("VSRC", 0), ("ATTR", 0), ("ATTRCHAN", 0)], None),
|
||||
("V_INTERP_P2_F32", "ENC_VINTRP", &[("VDST", 4), ("VSRC", 1), ("ATTR", 0), ("ATTRCHAN", 0)], None),
|
||||
("V_INTERP_P1_F32", "ENC_VINTRP", &[("VDST", 5), ("VSRC", 0), ("ATTR", 0), ("ATTRCHAN", 1)], None),
|
||||
("V_INTERP_P2_F32", "ENC_VINTRP", &[("VDST", 5), ("VSRC", 1), ("ATTR", 0), ("ATTRCHAN", 1)], None),
|
||||
("V_INTERP_P1_F32", "ENC_VINTRP", &[("VDST", 6), ("VSRC", 0), ("ATTR", 0), ("ATTRCHAN", 2)], None),
|
||||
("V_INTERP_P2_F32", "ENC_VINTRP", &[("VDST", 6), ("VSRC", 1), ("ATTR", 0), ("ATTRCHAN", 2)], None),
|
||||
("V_INTERP_P1_F32", "ENC_VINTRP", &[("VDST", 7), ("VSRC", 0), ("ATTR", 0), ("ATTRCHAN", 3)], None),
|
||||
("V_INTERP_P2_F32", "ENC_VINTRP", &[("VDST", 7), ("VSRC", 1), ("ATTR", 0), ("ATTRCHAN", 3)], None),
|
||||
("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 4), ("VSRC1", 5), ("VSRC2", 6), ("VSRC3", 7), ("DONE", 1), ("VM", 1)], None),
|
||||
]);
|
||||
let compile = |code: &[u8], mode: Mode, profile: &str| {
|
||||
let t = translate(code, &runner::options(mode)).unwrap();
|
||||
assert!(t.complete(), "{:?}", t.unsupported_why);
|
||||
super::dxc::compile(&t.hlsl, "main", profile, &[]).unwrap_or_else(|e| panic!("{e}\n{}", t.hlsl))
|
||||
};
|
||||
let vsb = compile(vs.unwrap_or(&pass_vs), Mode::Vertex(draw_vsi()), "vs_6_6");
|
||||
let psb = compile(ps.unwrap_or(&pass_ps), Mode::Pixel(draw_psi()), "ps_6_6");
|
||||
// pixels → NDC (y down), COLOR 0
|
||||
let verts: Vec<f32> = tris_px.iter().flat_map(|p| [p[0] / 8.0 - 1.0, 1.0 - p[1] / 8.0, 0.0, 0.0, 0.0, 0.0]).collect();
|
||||
let layout = [
|
||||
runner::VertexElement { semantic: "POSITION", index: 0, format: DXGI_FORMAT_R32G32_FLOAT, offset: 0 },
|
||||
runner::VertexElement { semantic: "COLOR", index: 0, format: DXGI_FORMAT_R32G32B32A32_FLOAT, offset: 8 },
|
||||
];
|
||||
runner::draw(&vsb, &psb, &layout, &verts, 24, &[], &[], 16, [-1.0; 4]).unwrap()
|
||||
}
|
||||
|
||||
/// 48 SGPR spill slots in lanes 0..47 of v30 (`v_writelane` / `v_readlane`, as 287 retail
|
||||
/// pixel shaders do – 11 up to lane 47): slot k = `slot(k)`, then s44 = the sum of slots
|
||||
/// 0..31, s45 = the sum of slots 32..47.
|
||||
fn spill_slots(slot: fn(u32) -> u32) -> Vec<u8> {
|
||||
let mut code = Vec::new();
|
||||
for k in 0..48u32 {
|
||||
code.extend(ins("S_MOV_B32", "ENC_SOP1", &[("SDST", 20), ("SSRC0", 255)], Some(slot(k))));
|
||||
code.extend(ins("V_WRITELANE_B32", "ENC_VOP3", &[("VDST", 30), ("SRC0", 20), ("SRC1", 128 + k as u64)], None));
|
||||
}
|
||||
code.extend(ins("S_MOV_B32", "ENC_SOP1", &[("SDST", 44), ("SSRC0", 128)], None));
|
||||
code.extend(ins("S_MOV_B32", "ENC_SOP1", &[("SDST", 45), ("SSRC0", 128)], None));
|
||||
for k in 0..48u64 {
|
||||
code.extend(ins("V_READLANE_B32", "ENC_VOP3", &[("VDST", 20), ("SRC0", V + 30), ("SRC1", 128 + k)], None));
|
||||
let sum = if k < 32 { 44 } else { 45 };
|
||||
code.extend(ins("S_ADD_U32", "ENC_SOP2", &[("SDST", sum), ("SSRC0", sum), ("SSRC1", 20)], None));
|
||||
}
|
||||
code
|
||||
}
|
||||
|
||||
/// The whole-wave reduction of the retail pixel shaders (`upper_lanes`), run as a wave64 PS:
|
||||
/// identity into the lanes outside the mask, DPP8 xor 1 / 2 / 4, row_mirror, the other row
|
||||
/// through `v_permlanex16`, `v_readlane` 32 for the upper half's result, `v_readlane` 0 for
|
||||
/// the total – as min (identity -1, as in the pack) and as a sum (identity 0: wrong if lane
|
||||
/// 32 is read as anything but the identity, e.g. as lane 0, where a 32-lane GPU's wave read
|
||||
/// wraps). Over the odd pixels of each wave; also the waterfall read of the pack
|
||||
/// (`v_readlane` of the lane `s_ff1` picks from mask & EXEC). The waves are found from the
|
||||
/// pixels: each exports its wave's `v_readfirstlane` of the pixel number and its lane
|
||||
/// (`v_mbcnt`), and the CPU computes what a console wave of those lanes gives.
|
||||
#[test]
|
||||
fn gpu_wave64_ps_whole_wave_reductions() {
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
if !gpu_ready() {
|
||||
return;
|
||||
}
|
||||
let reduce = |op: &str, identity: u64, out: u64| -> Vec<u8> {
|
||||
let mut c = vec![
|
||||
ins("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 30), ("SSRC0", 193)], None),
|
||||
ins("S_AND_B64", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 18), ("SSRC1", 30)], None),
|
||||
ins("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", identity), ("SRC1", V + 13), ("SRC2", 10)], None),
|
||||
];
|
||||
let names = ["LANE_SEL_0", "LANE_SEL_1", "LANE_SEL_2", "LANE_SEL_3", "LANE_SEL_4", "LANE_SEL_5", "LANE_SEL_6", "LANE_SEL_7"];
|
||||
for sel in [[1u64, 0, 3, 2, 5, 4, 7, 6], [2, 3, 0, 1, 6, 7, 4, 5], [4, 5, 6, 7, 0, 1, 2, 3]] {
|
||||
let mut f = vec![("VDST", 6u64), ("SRC0", 0xE9), ("VSRC0", 6), ("VSRC1", 6)];
|
||||
f.extend(names.iter().copied().zip(sel));
|
||||
c.push(ins(op, "VOP2_VOP_DPP8", &f, None));
|
||||
}
|
||||
c.extend([
|
||||
ins(op, "VOP2_VOP_DPP16", &[("VDST", 6), ("SRC0", 0xFA), ("VSRC0", 6), ("VSRC1", 6), ("DPP_CTRL", 0x140), ("ROW_MASK", 0xF), ("BANK_MASK", 0xF)], None),
|
||||
ins("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 7), ("SRC0", V + 6), ("SRC1", 128), ("SRC2", 128)], None),
|
||||
ins(op, "ENC_VOP2", &[("VDST", 6), ("SRC0", V + 7), ("VSRC1", 6)], None),
|
||||
ins("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 6), ("SRC1", 128 + 32)], None),
|
||||
ins(op, "ENC_VOP2", &[("VDST", 6), ("SRC0", 10), ("VSRC1", 6)], None),
|
||||
ins("V_READLANE_B32", "ENC_VOP3", &[("VDST", out), ("SRC0", V + 6), ("SRC1", 128)], None),
|
||||
ins("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 30)], None),
|
||||
]);
|
||||
c.concat()
|
||||
};
|
||||
let code = program_of(&[
|
||||
// v12 = pixel number y·16 + x, v13 = v12 + 1, s[18:19] = the odd pixels
|
||||
ins("V_CVT_U32_F32", "ENC_VOP1", &[("VDST", 10), ("SRC0", V + 2)], None),
|
||||
ins("V_CVT_U32_F32", "ENC_VOP1", &[("VDST", 11), ("SRC0", V + 3)], None),
|
||||
ins("V_LSHL_ADD_U32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 11), ("SRC1", 128 + 4), ("SRC2", V + 10)], None),
|
||||
ins("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 13), ("SRC0", 129), ("VSRC1", 12)], None),
|
||||
ins("V_AND_B32", "ENC_VOP2", &[("VDST", 14), ("SRC0", 129), ("VSRC1", 12)], None),
|
||||
ins("V_CMP_NE_U32", "ENC_VOPC", &[("SRC0", 128), ("VSRC1", 14)], None),
|
||||
ins("S_MOV_B64", "ENC_SOP1", &[("SDST", 18), ("SSRC0", 106)], None),
|
||||
// the wave: its first lane's pixel number; the lane
|
||||
ins("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 62), ("SRC0", V + 12)], None),
|
||||
ins("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 15), ("SRC0", 193), ("SRC1", 128)], None),
|
||||
ins("V_MBCNT_HI_U32_B32", "ENC_VOP3", &[("VDST", 15), ("SRC0", 193), ("SRC1", V + 15)], None),
|
||||
reduce("V_MIN_U32", 193, 40),
|
||||
reduce("V_ADD_NC_U32", 128, 41),
|
||||
ins("S_AND_B64", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 18), ("SSRC1", 126)], None),
|
||||
ins("S_FF1_I32_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 0)], None),
|
||||
ins("V_READLANE_B32", "ENC_VOP3", &[("VDST", 43), ("SRC0", V + 13), ("SRC1", 0)], None),
|
||||
ins("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 20), ("SRC0", 40)], None),
|
||||
ins("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 21), ("SRC0", 41)], None),
|
||||
ins("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 22), ("SRC0", 43)], None),
|
||||
ins("V_LSHL_ADD_U32", "ENC_VOP3", &[("VDST", 23), ("SRC0", 62), ("SRC1", 128 + 6), ("SRC2", V + 15)], None),
|
||||
ins("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 23), ("SRC0", V + 23)], None),
|
||||
ins("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 20), ("VSRC1", 21), ("VSRC2", 22), ("VSRC3", 23), ("DONE", 1), ("VM", 1)], None),
|
||||
]);
|
||||
let px = draw_console(None, Some(&code), &[[0.0, 0.0], [0.0, 32.0], [32.0, 0.0]]);
|
||||
// by wave (its first lane's pixel number): (pixel number, lane, results)
|
||||
let mut waves: BTreeMap<u32, Vec<(u32, u32, [f32; 4])>> = BTreeMap::new();
|
||||
for (id, p) in px.iter().enumerate() {
|
||||
let kl = p[3] as u32;
|
||||
waves.entry(kl >> 6).or_default().push((id as u32, kl & 63, *p));
|
||||
}
|
||||
println!("waves of {:?} pixels", waves.values().map(|w| w.len()).collect::<Vec<_>>());
|
||||
for (first, w) in &waves {
|
||||
let lanes: BTreeSet<u32> = w.iter().map(|x| x.1).collect();
|
||||
assert_eq!(lanes.len(), w.len(), "wave of pixel {first}: a lane twice");
|
||||
let lowest = w.iter().min_by_key(|x| x.1).unwrap();
|
||||
assert_eq!(lowest.0, *first, "v_readfirstlane: the wave's lowest lane");
|
||||
let odd: Vec<&(u32, u32, [f32; 4])> = w.iter().filter(|x| x.0 % 2 == 1).collect();
|
||||
let Some(first_odd) = odd.iter().min_by_key(|x| x.1) else { continue };
|
||||
let want = [odd.iter().map(|x| x.0 + 1).min().unwrap(), odd.iter().map(|x| x.0 + 1).sum(), first_odd.0 + 1];
|
||||
for (id, lane, p) in w {
|
||||
let got = [p[0] as u32, p[1] as u32, p[2] as u32];
|
||||
assert_eq!(got, want, "pixel {id} (lane {lane}, wave of pixel {first}): min / sum over the odd pixels, waterfall read");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// SGPR spill slots in lanes 0..47 of a VGPR (`spill_slots`) in a wave64 PS: slots ≥ 32 do
|
||||
/// not exist in a 32-lane wave, and a slot in a lane that was not launched is lost in a
|
||||
/// partial wave (a primitive's edge). Drawn over the whole target and as a 6-pixel triangle.
|
||||
#[test]
|
||||
fn gpu_wave64_ps_spill_slots() {
|
||||
if !gpu_ready() {
|
||||
return;
|
||||
}
|
||||
let slot: fn(u32) -> u32 = |k| k * k + 7 * k + 1;
|
||||
let code = program_of(&[
|
||||
spill_slots(slot),
|
||||
ins("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 20), ("SRC0", 44)], None),
|
||||
ins("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 21), ("SRC0", 45)], None),
|
||||
ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 22), ("SRC0", 242)], None),
|
||||
ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 23), ("SRC0", 242)], None),
|
||||
ins("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 20), ("VSRC1", 21), ("VSRC2", 22), ("VSRC3", 23), ("DONE", 1), ("VM", 1)], None),
|
||||
]);
|
||||
let want = [(0..32).map(slot).sum::<u32>() as f32, (32..48).map(slot).sum::<u32>() as f32];
|
||||
let full = draw_console(None, Some(&code), &[[0.0, 0.0], [0.0, 32.0], [32.0, 0.0]]);
|
||||
for (i, p) in full.iter().enumerate() {
|
||||
assert_eq!([p[0], p[1]], want, "pixel {i}, full waves: slots 0..31, 32..47");
|
||||
}
|
||||
// pixels (0..2, 0), (0..1, 1), (0, 2): three quads
|
||||
let small = draw_console(None, Some(&code), &[[0.0, 0.0], [3.2, 0.0], [0.0, 3.2]]);
|
||||
let covered: Vec<(usize, &[f32; 4])> = small.iter().enumerate().filter(|(_, p)| p[3] == 1.0).collect();
|
||||
assert_eq!(covered.len(), 6);
|
||||
// the 32-lane form keeps slots < 32 whatever the wave size, slots ≥ 32 in 32-lane waves;
|
||||
// the native form (GPUs with 64-lane waves) still loses the slots of lanes not launched
|
||||
let (lo, hi) = (runner::split_wave64(), runner::wave64_supported() == Ok(false));
|
||||
for (i, p) in covered {
|
||||
println!("pixel {i}, partial wave: {:?} (want {want:?})", &p[..2]);
|
||||
if lo {
|
||||
assert_eq!(p[0], want[0], "pixel {i}, partial wave: slots 0..31");
|
||||
}
|
||||
if hi {
|
||||
assert_eq!(p[1], want[1], "pixel {i}, partial wave: slots 32..47");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A wave64 VS with SGPR spill slots in lanes 0..47 (`spill_slots`) and a whole-wave identity
|
||||
/// read from lane 32 (`v_cndmask` with the saved EXEC, `v_readlane` 32): three vertices, so a
|
||||
/// wave of three lanes. The VS exports the slots' sums and whether lane 32 held the identity
|
||||
/// as param0, which the PS interpolates (the same at every vertex: exact).
|
||||
#[test]
|
||||
fn gpu_wave64_vs_spill_slots_and_identity() {
|
||||
if !gpu_ready() {
|
||||
return;
|
||||
}
|
||||
let slot: fn(u32) -> u32 = |k| 3 * k * k + k + 5;
|
||||
let code = program_of(&[
|
||||
ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 0), ("SRC0", V + 4)], None),
|
||||
ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", V + 5)], None),
|
||||
ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 128)], None),
|
||||
ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 242)], None),
|
||||
spill_slots(slot),
|
||||
ins("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 30), ("SSRC0", 193)], None),
|
||||
ins("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", 193), ("SRC1", V), ("SRC2", 30)], None),
|
||||
ins("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 6), ("SRC1", 128 + 32)], None),
|
||||
ins("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 30)], None),
|
||||
ins("S_CMP_EQ_U32", "ENC_SOPC", &[("SSRC0", 10), ("SSRC1", 193)], None),
|
||||
ins("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 11), ("SSRC0", 242), ("SSRC1", 128)], None),
|
||||
ins("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 8), ("SRC0", 44)], None),
|
||||
ins("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 9), ("SRC0", 45)], None),
|
||||
ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 10), ("SRC0", 11)], None),
|
||||
ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 11), ("SRC0", 242)], None),
|
||||
ins("EXP", "ENC_EXP", &[("TGT", 12), ("EN", 0xF), ("VSRC0", 0), ("VSRC1", 1), ("VSRC2", 2), ("VSRC3", 3), ("DONE", 1)], None),
|
||||
ins("EXP", "ENC_EXP", &[("TGT", 32), ("EN", 0xF), ("VSRC0", 8), ("VSRC1", 9), ("VSRC2", 10), ("VSRC3", 11)], None),
|
||||
]);
|
||||
let px = draw_console(Some(&code), None, &[[0.0, 0.0], [0.0, 32.0], [32.0, 0.0]]);
|
||||
let want = [(0..32).map(slot).sum::<u32>() as f32, (32..48).map(slot).sum::<u32>() as f32, 1.0, 1.0];
|
||||
// as in `gpu_wave64_ps_spill_slots`: slots < 32 in the 32-lane form; slots ≥ 32 and the
|
||||
// identity in lane 32 in 32-lane waves (in a 64-lane wave of three vertices, lane 32 was
|
||||
// not launched either)
|
||||
let (lo, hi) = (runner::split_wave64(), runner::wave64_supported() == Ok(false));
|
||||
println!("{:?} (want {want:?})", px[0]);
|
||||
for (i, p) in px.iter().enumerate() {
|
||||
if lo {
|
||||
assert_eq!(p[0], want[0], "pixel {i}: slots 0..31");
|
||||
}
|
||||
if hi {
|
||||
assert_eq!(&p[1..], &want[1..], "pixel {i}: slots 32..47, lane 32");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// XCL image descriptor (T#, GFX10 layout): BASE_ADDRESS = SRV heap index, FORMAT, TYPE.
|
||||
fn tsharp(index: u32, format: u32, ty: u32) -> [u32; 8] {
|
||||
[index, format << 20, 0, ty << 28, 0, 0, 0, 0]
|
||||
@@ -4600,6 +4866,211 @@ fn retail_swizzle_and_setpc_census() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Every cross-lane read `upper_lanes` resolves (or not) in the pack's wave64 VS / PS
|
||||
/// programs, with the instructions around it: `XCL_SAMPLE_RPF`, `XCL_CENSUS_OUT=<file>` (the
|
||||
/// listing; marks `>>` unresolved, `C ` constant, `S ` shadow, `N ` native), `XCL_CENSUS_FULL=1`
|
||||
/// (whole programs), `XCL_CENSUS_UNKNOWN=1` (only programs with an unresolved read). Prints
|
||||
/// sites and programs (all, and distinct code) per resolution.
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn retail_wave64_graphics_lane_census() {
|
||||
use super::upper_lanes::Read;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::Mutex;
|
||||
let (Ok(path), Ok(out)) = (std::env::var("XCL_SAMPLE_RPF"), std::env::var("XCL_CENSUS_OUT")) else { return };
|
||||
let full = std::env::var_os("XCL_CENSUS_FULL").is_some();
|
||||
let only_unknown = std::env::var_os("XCL_CENSUS_UNKNOWN").is_some();
|
||||
let data = std::fs::read(path).unwrap();
|
||||
let records = crate::gpu::pack::scan(&data, 0x40);
|
||||
let text: Mutex<Vec<(String, String)>> = Mutex::new(Vec::new());
|
||||
// resolution → (sites, programs, distinct programs by code hash)
|
||||
let stats: Mutex<BTreeMap<&'static str, (usize, usize, BTreeSet<u64>)>> = Mutex::new(BTreeMap::new());
|
||||
let next = AtomicUsize::new(0);
|
||||
std::thread::scope(|s| {
|
||||
for _ in 0..std::thread::available_parallelism().map_or(4, |n| n.get()) {
|
||||
s.spawn(|| loop {
|
||||
let i = next.fetch_add(1, Ordering::Relaxed);
|
||||
let Some(r) = records.get(i) else { break };
|
||||
let Some(blob) = crate::gpu::pack::inflate(&data, r) else { continue };
|
||||
let Some(sh) = crate::gpu::xbox::parse(&blob) else { continue };
|
||||
for (fi, f) in sh.fssm.iter().enumerate() {
|
||||
let mode = match super::interface(&blob, &sh, f) {
|
||||
Some(Mode::Vertex(_)) => "VS",
|
||||
Some(Mode::Pixel(_)) => "PS",
|
||||
_ => continue,
|
||||
};
|
||||
for p in &f.programs {
|
||||
let code = &f.data[p.offset..p.offset + p.len];
|
||||
if !super::detect_wave64(code) {
|
||||
continue;
|
||||
}
|
||||
let mut insts = Vec::new();
|
||||
let mut off = 0;
|
||||
while off + 4 <= code.len() {
|
||||
let Ok(d) = crate::gpu::rdna2::decode(&code[off..], off as u64) else { break };
|
||||
off += d.len;
|
||||
insts.push(d);
|
||||
}
|
||||
crate::gpu::rdna2::resolve_far_jumps(&mut insts);
|
||||
let a = super::upper_lanes::analyze(&insts);
|
||||
if a.reads.is_empty() || (only_unknown && !a.reads.values().any(|r| *r == Read::Unknown)) {
|
||||
continue;
|
||||
}
|
||||
let hash = crate::gpu::shader::fnv64(code);
|
||||
{
|
||||
let mut st = stats.lock().unwrap();
|
||||
let mut kinds = BTreeSet::new();
|
||||
for r in a.reads.values() {
|
||||
let k = match r {
|
||||
Read::Native => "native (lanes >= 32 unwritten / inactive)",
|
||||
Read::Const(_) => "constant (whole-wave identity)",
|
||||
Read::Shadow => "spill slot shadow",
|
||||
Read::Unknown => "unresolved",
|
||||
};
|
||||
st.entry(k).or_default().0 += 1;
|
||||
kinds.insert(k);
|
||||
}
|
||||
for k in kinds {
|
||||
let e = st.entry(k).or_default();
|
||||
e.1 += 1;
|
||||
e.2.insert(hash);
|
||||
}
|
||||
}
|
||||
let lines = crate::gpu::rdna2::disassemble(code, 0, false);
|
||||
let mut s = format!("=== {} FSSM#{fi} {mode} {} B {hash:016x}
|
||||
", r.name, code.len());
|
||||
if a.reads.values().any(|r| *r == Read::Unknown) {
|
||||
// where EXEC's upper word and the VGPRs' lanes ≥ 32 stopped being known
|
||||
super::upper_lanes::TRACE.with(|t| *t.borrow_mut() = Some(Vec::new()));
|
||||
super::upper_lanes::analyze(&insts);
|
||||
for l in super::upper_lanes::TRACE.with(|t| t.borrow_mut().take()).unwrap_or_default() {
|
||||
s.push_str(&format!(" trace {l}
|
||||
"));
|
||||
}
|
||||
}
|
||||
let mark = |pc: u64| match a.reads.get(&pc) {
|
||||
Some(Read::Unknown) => ">>",
|
||||
Some(Read::Const(_)) => "C ",
|
||||
Some(Read::Shadow) => "S ",
|
||||
Some(Read::Native) => "N ",
|
||||
None => " ",
|
||||
};
|
||||
let sites: Vec<usize> = lines.iter().enumerate().filter(|(_, l)| a.reads.contains_key(&l.pc)).map(|(k, _)| k).collect();
|
||||
let mut shown = 0usize;
|
||||
for &k in &sites {
|
||||
let (from, to) = if full { (0, lines.len()) } else { (k.saturating_sub(40), (k + 8).min(lines.len())) };
|
||||
let from = from.max(shown);
|
||||
if from > shown || shown == 0 {
|
||||
s.push_str(" ...
|
||||
");
|
||||
}
|
||||
for l in &lines[from..to.max(from)] {
|
||||
s.push_str(&format!("{} {:05x}: {}
|
||||
", mark(l.pc), l.pc, l.text));
|
||||
}
|
||||
shown = shown.max(to);
|
||||
}
|
||||
text.lock().unwrap().push((r.name.clone(), s));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
let mut v = text.into_inner().unwrap();
|
||||
v.sort();
|
||||
println!("{} programs listed", v.len());
|
||||
for (k, (sites, progs, distinct)) in stats.into_inner().unwrap() {
|
||||
println!(" {k:<45} {sites:>6} sites {progs:>6} programs {:>6} distinct", distinct.len());
|
||||
}
|
||||
std::fs::write(out, v.into_iter().map(|(_, s)| s).collect::<String>()).unwrap();
|
||||
}
|
||||
|
||||
/// The 32-lane form of the pack's wave64 VS / PS (`upper_lanes`): every program whose
|
||||
/// translation it changes is compiled with DXC. Digests of every program's translation in the
|
||||
/// native form (`split_wave64` off – the form a GPU with 64-lane waves gets) and of the other
|
||||
/// modes' 32-lane form are printed, to compare with another build: `XCL_SAMPLE_RPF`;
|
||||
/// `XCL_FORMS_NO_DXC=1` skips the compiles.
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn retail_wave64_graphics_lane_forms() {
|
||||
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
|
||||
use std::sync::Mutex;
|
||||
let Ok(path) = std::env::var("XCL_SAMPLE_RPF") else { return };
|
||||
let dxc = std::env::var_os("XCL_FORMS_NO_DXC").is_none();
|
||||
let data = std::fs::read(path).unwrap();
|
||||
let records = crate::gpu::pack::scan(&data, 0x40);
|
||||
let (digest, programs, changed, compiled) = (AtomicU64::new(0), AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0));
|
||||
let split_digest = AtomicU64::new(0);
|
||||
let errors: Mutex<Vec<String>> = Mutex::new(Vec::new());
|
||||
let next = AtomicUsize::new(0);
|
||||
std::thread::scope(|s| {
|
||||
for _ in 0..std::thread::available_parallelism().map_or(4, |n| n.get()) {
|
||||
s.spawn(|| loop {
|
||||
let i = next.fetch_add(1, Ordering::Relaxed);
|
||||
let Some(r) = records.get(i) else { break };
|
||||
let Some(blob) = crate::gpu::pack::inflate(&data, r) else { continue };
|
||||
let Some(sh) = crate::gpu::xbox::parse(&blob) else { continue };
|
||||
for (fi, f) in sh.fssm.iter().enumerate() {
|
||||
let mode = super::interface(&blob, &sh, f).unwrap_or(Mode::Kernel);
|
||||
for p in &f.programs {
|
||||
let code = &f.data[p.offset..p.offset + p.len];
|
||||
let wave64 = super::detect_wave64(code);
|
||||
let opt = Options { mode: mode.clone(), wave64, ..Default::default() };
|
||||
let Ok(native) = translate(code, &opt) else { continue };
|
||||
programs.fetch_add(1, Ordering::Relaxed);
|
||||
let key = format!("{} FSSM#{fi} {:x}", r.name, p.offset);
|
||||
let h = crate::gpu::shader::fnv64(format!("{key}
|
||||
{}", native.hlsl).as_bytes());
|
||||
digest.fetch_add(h, Ordering::Relaxed);
|
||||
let profile = match &mode {
|
||||
Mode::Vertex(_) => "vs_6_6",
|
||||
Mode::Pixel(_) => "ps_6_6",
|
||||
_ => {
|
||||
// the other modes' 32-lane form: unchanged by `upper_lanes`
|
||||
if let Ok(t) = translate(code, &Options { split_wave64: true, ..opt }) {
|
||||
split_digest.fetch_add(crate::gpu::shader::fnv64(format!("{key}\\n{}", t.hlsl).as_bytes()), Ordering::Relaxed);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if !wave64 {
|
||||
continue;
|
||||
}
|
||||
let t = translate(code, &Options { split_wave64: true, ..opt }).unwrap();
|
||||
if t.hlsl == native.hlsl {
|
||||
continue;
|
||||
}
|
||||
changed.fetch_add(1, Ordering::Relaxed);
|
||||
if dxc {
|
||||
match super::dxc::compile(&t.hlsl, "main", profile, &[]) {
|
||||
Ok(_) => {
|
||||
compiled.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
Err(e) => errors.lock().unwrap().push(format!("{key}: {}", e.lines().take(4).collect::<Vec<_>>().join(" | "))),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
let errors = errors.into_inner().unwrap();
|
||||
println!(
|
||||
"{} programs, native-form digest {:016x}, 32-lane-form digest of the other modes {:016x}; 32-lane form differs for {} wave64 VS / PS, {} compiled, {} DXC errors",
|
||||
programs.into_inner(),
|
||||
digest.into_inner(),
|
||||
split_digest.into_inner(),
|
||||
changed.into_inner(),
|
||||
compiled.into_inner(),
|
||||
errors.len()
|
||||
);
|
||||
for e in errors.iter().take(10) {
|
||||
println!(" {e}");
|
||||
}
|
||||
assert!(errors.is_empty());
|
||||
}
|
||||
|
||||
/// `ds_swizzle_b32`'s four modes against the RDNA ISA (its FFT examples, rotate, quad
|
||||
/// permute, and the bit mode with xor ≥ 16, which retail compute shaders use to swap the
|
||||
/// 16-lane halves: 0x401F).
|
||||
|
||||
@@ -0,0 +1,934 @@
|
||||
//! Wave64 vertex / pixel shaders in 32-lane hardware waves (docs/wave64-on-wave32.md,
|
||||
//! "Vertex and pixel shaders"): what the console's lanes 32..63 hold where the program reads
|
||||
//! them.
|
||||
//!
|
||||
//! The driver picks the wave size of a VS or PS, and a GPU with only 32-lane waves (NVIDIA)
|
||||
//! runs a console wave64 program in waves of 32. Such a wave stands for a console wave whose
|
||||
//! lanes 32..63 are not populated, as in the last wave of a draw: inactive, but on the console
|
||||
//! their VGPRs exist and can still be written – by `v_writelane`, which ignores EXEC, and by
|
||||
//! whole-wave code (EXEC's upper word set, `s_or_saveexec_b64 s, -1`). Here those lanes do
|
||||
//! not exist. A read of one – `v_readlane` of a lane ≥ 32 or of a lane from an SGPR,
|
||||
//! `ds_bpermute` – needs the value the console lane would hold. This forward analysis follows
|
||||
//! it per VGPR lane:
|
||||
//! - *unwritten*: nothing wrote the lane, it holds what an earlier wave left in the register.
|
||||
//! A program cannot depend on that, so any value is as right as the console's;
|
||||
//! - a *constant*: whole-wave code wrote it – the identity a wave reduction puts into the
|
||||
//! lanes outside its mask, which the DPP / `v_permlanex16` steps keep, since they only
|
||||
//! combine lanes of the same 32-lane half;
|
||||
//! - a *shadow*: `v_writelane` wrote it (SGPR spill slots); the emitter keeps a scalar copy.
|
||||
//!
|
||||
//! Lanes < 32 exist but need not have been launched (a partial wave, as pixel waves at a
|
||||
//! primitive's edge often are), and a lane that was not launched loses what `v_writelane`
|
||||
//! put there: a spill slot < 32 is read from its shadow too – whatever the wave size – as long
|
||||
//! as no other instruction has written the VGPR since its `v_writelane`.
|
||||
//!
|
||||
//! Which instructions write lanes 32..63 depends on EXEC's upper word, followed through the
|
||||
//! SGPRs as 32-bit words known to be 0, all ones, or anything: 0 at the start; a VALU mask
|
||||
//! (`v_cmp*`, carries) has a 0 upper word while EXEC's is 0; bitwise SALU and the saveexec
|
||||
//! forms combine words; everything else is "anything". A VALU write while EXEC's upper word
|
||||
//! is 0 leaves lanes 32..63 alone; while it is all ones it writes them with the value
|
||||
//! evaluated here (moves, selects, integer min / max / and / or / xor / add, their DPP forms,
|
||||
//! `v_permlane(x)16`), and otherwise their state becomes unknown.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use super::emit::ext_encoding;
|
||||
use crate::gpu::rdna2::{self, Decoded, Variant, F_CONDITIONAL, F_INDIRECT, F_TERMINATOR};
|
||||
|
||||
/// An SGPR's value as far as the analysis needs it.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
enum Word {
|
||||
Zero,
|
||||
Ones,
|
||||
Any,
|
||||
}
|
||||
|
||||
impl Word {
|
||||
fn of(v: u32) -> Word {
|
||||
match v {
|
||||
0 => Word::Zero,
|
||||
u32::MAX => Word::Ones,
|
||||
_ => Word::Any,
|
||||
}
|
||||
}
|
||||
fn join(self, o: Word) -> Word {
|
||||
if self == o {
|
||||
self
|
||||
} else {
|
||||
Word::Any
|
||||
}
|
||||
}
|
||||
fn not(self) -> Word {
|
||||
match self {
|
||||
Word::Zero => Word::Ones,
|
||||
Word::Ones => Word::Zero,
|
||||
Word::Any => Word::Any,
|
||||
}
|
||||
}
|
||||
fn and(self, o: Word) -> Word {
|
||||
match (self, o) {
|
||||
(Word::Zero, _) | (_, Word::Zero) => Word::Zero,
|
||||
(Word::Ones, Word::Ones) => Word::Ones,
|
||||
_ => Word::Any,
|
||||
}
|
||||
}
|
||||
fn or(self, o: Word) -> Word {
|
||||
self.not().and(o.not()).not()
|
||||
}
|
||||
fn xor(self, o: Word) -> Word {
|
||||
match (self, o) {
|
||||
(Word::Any, _) | (_, Word::Any) => Word::Any,
|
||||
(a, b) if a == b => Word::Zero,
|
||||
_ => Word::Ones,
|
||||
}
|
||||
}
|
||||
/// The 32-bit value, when it is one.
|
||||
fn value(self) -> Option<u32> {
|
||||
match self {
|
||||
Word::Zero => Some(0),
|
||||
Word::Ones => Some(u32::MAX),
|
||||
Word::Any => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A bitwise SALU operation by its name's second part (`S_ANDN2_SAVEEXEC_B64` → "ANDN2").
|
||||
fn bitop(op: &str, a: Word, b: Word) -> Option<Word> {
|
||||
Some(match op {
|
||||
"AND" => a.and(b),
|
||||
"OR" => a.or(b),
|
||||
"XOR" => a.xor(b),
|
||||
"ANDN2" => a.and(b.not()),
|
||||
"ORN2" => a.or(b.not()),
|
||||
"NAND" => a.and(b).not(),
|
||||
"NOR" => a.or(b).not(),
|
||||
"XNOR" => a.xor(b).not(),
|
||||
"ANDN1" => a.not().and(b),
|
||||
"ORN1" => a.not().or(b),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// What a lane ≥ 32 of a VGPR holds on the console.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
enum Hi {
|
||||
Unwritten,
|
||||
Const(u32),
|
||||
Shadow,
|
||||
Unknown,
|
||||
}
|
||||
|
||||
impl Hi {
|
||||
/// Either of the two (two paths, or a lane a mask may or may not select): an unwritten
|
||||
/// lane accepts any value, so it takes the other's.
|
||||
fn join(self, o: Hi) -> Hi {
|
||||
match (self, o) {
|
||||
(Hi::Unwritten, x) | (x, Hi::Unwritten) => x,
|
||||
(a, b) if a == b => a,
|
||||
_ => Hi::Unknown,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const UNWRITTEN: [Hi; 32] = [Hi::Unwritten; 32];
|
||||
|
||||
#[derive(Clone, PartialEq)]
|
||||
struct State {
|
||||
s: [Word; 128],
|
||||
/// VGPR → its lanes 32..63 (absent: all unwritten)
|
||||
hi: BTreeMap<u64, [Hi; 32]>,
|
||||
/// VGPR → its lanes < 32 (bit n: lane n) whose last write was a `v_writelane`
|
||||
lo: BTreeMap<u64, u32>,
|
||||
}
|
||||
|
||||
impl State {
|
||||
fn entry() -> State {
|
||||
let mut s = [Word::Any; 128];
|
||||
s[125] = Word::Zero; // NULL
|
||||
s[127] = Word::Zero; // EXEC's upper word: lanes 32..63 are not populated
|
||||
State { s, hi: BTreeMap::new(), lo: BTreeMap::new() }
|
||||
}
|
||||
|
||||
fn join(&self, o: &State) -> State {
|
||||
let mut s = self.s;
|
||||
for (a, b) in s.iter_mut().zip(o.s) {
|
||||
*a = a.join(b);
|
||||
}
|
||||
let mut hi = self.hi.clone();
|
||||
for (v, l) in &o.hi {
|
||||
let e = hi.entry(*v).or_insert(UNWRITTEN);
|
||||
for (a, b) in e.iter_mut().zip(l) {
|
||||
*a = a.join(*b);
|
||||
}
|
||||
}
|
||||
let lo = self
|
||||
.lo
|
||||
.iter()
|
||||
.filter_map(|(v, m)| {
|
||||
let m = m & o.lo.get(v).copied().unwrap_or(0);
|
||||
(m != 0).then_some((*v, m))
|
||||
})
|
||||
.collect();
|
||||
State { s, hi, lo }
|
||||
}
|
||||
|
||||
fn upper(&self, v: u64) -> [Hi; 32] {
|
||||
self.hi.get(&v).copied().unwrap_or(UNWRITTEN)
|
||||
}
|
||||
|
||||
fn set_upper(&mut self, v: u64, lanes: [Hi; 32]) {
|
||||
if lanes == UNWRITTEN {
|
||||
self.hi.remove(&v);
|
||||
} else {
|
||||
self.hi.insert(v, lanes);
|
||||
}
|
||||
}
|
||||
|
||||
fn set(&mut self, r: u64, w: Word) {
|
||||
if r < 128 && r != 125 {
|
||||
self.s[r as usize] = w;
|
||||
}
|
||||
}
|
||||
|
||||
/// A 32-bit scalar source (operand code).
|
||||
fn src32(&self, d: &Decoded, code: u64) -> Word {
|
||||
match code {
|
||||
0..=124 | 126 | 127 => self.s[code as usize],
|
||||
125 | 128 => Word::Zero,
|
||||
193 => Word::Ones,
|
||||
255 => d.literal.map_or(Word::Any, Word::of),
|
||||
_ => Word::Any,
|
||||
}
|
||||
}
|
||||
|
||||
/// A 64-bit scalar source (operand code) as (low, high) words; a 32-bit literal is the
|
||||
/// low word of an integer operand, inline integers are sign-extended (as `Em::code64`).
|
||||
fn src64(&self, d: &Decoded, code: u64) -> (Word, Word) {
|
||||
match code {
|
||||
0..=123 | 126 => (self.s[code as usize], self.s[code as usize + 1]),
|
||||
125 | 128 => (Word::Zero, Word::Zero),
|
||||
129..=192 => (Word::Any, Word::Zero),
|
||||
193 => (Word::Ones, Word::Ones),
|
||||
194..=208 => (Word::Any, Word::Ones),
|
||||
255 => (d.literal.map_or(Word::Any, Word::of), Word::Zero),
|
||||
_ => (Word::Any, Word::Any),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How the 32-lane form resolves a lane read (`UpperLanes::reads`).
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
pub enum Read {
|
||||
/// the read as it is: the lanes ≥ 32 it can reach are unwritten (or, for `ds_bpermute`,
|
||||
/// inactive, which reads 0 here as on the console)
|
||||
Native,
|
||||
/// a lane ≥ 32 holds this constant
|
||||
Const(u32),
|
||||
/// a spill slot: from the shadow `v_writelane` keeps
|
||||
Shadow,
|
||||
/// not followed: the read stays a hazard
|
||||
Unknown,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct UpperLanes {
|
||||
/// pc → resolution, for every cross-lane read that can reach a lane ≥ 32 and every
|
||||
/// `v_readlane` of a spill slot
|
||||
pub reads: BTreeMap<u64, Read>,
|
||||
/// (VGPR, lane) slots read from their shadow: their `v_writelane`s also write it
|
||||
pub shadows: BTreeSet<(u64, u32)>,
|
||||
}
|
||||
|
||||
impl UpperLanes {
|
||||
/// Reads that stay hazards, by kind (`super::wave_hazards`).
|
||||
pub fn hazards(&self, insts: &[Decoded]) -> BTreeSet<&'static str> {
|
||||
let mut out = BTreeSet::new();
|
||||
for d in insts {
|
||||
if self.reads.get(&d.pc) == Some(&Read::Unknown) {
|
||||
out.insert(match (d.inst.name, lane_operand(d)) {
|
||||
("V_READLANE_B32", Lane::Const(_)) => "v_readlane: lane ≥ 32",
|
||||
("V_READLANE_B32", _) => "v_readlane: lane number from an SGPR",
|
||||
_ => "ds_(b)permute: arbitrary lane",
|
||||
});
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Reads resolved, by kind (for `xcl shaders --recomp`).
|
||||
pub fn resolved(&self) -> BTreeSet<&'static str> {
|
||||
self.reads
|
||||
.values()
|
||||
.filter_map(|r| match r {
|
||||
Read::Native => Some("lanes ≥ 32 never written (or inactive)"),
|
||||
Read::Const(_) => Some("lane ≥ 32 holds a constant (whole-wave identity)"),
|
||||
Read::Shadow => Some("spill slot from its v_writelane shadow"),
|
||||
Read::Unknown => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// A read that can reach a lane ≥ 32 whatever the state (`classify` follows it).
|
||||
fn reaches_upper(d: &Decoded) -> bool {
|
||||
match d.inst.name {
|
||||
"V_READLANE_B32" => !matches!(lane_operand(d), Lane::Const(l) if l < 32),
|
||||
"DS_BPERMUTE_B32" | "DS_PERMUTE_B32" => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The (VGPR, lane) of a `v_readlane` / `v_writelane` with a constant lane: the slot of its
|
||||
/// shadow (`UpperLanes::shadows`).
|
||||
pub fn slot(d: &Decoded) -> Option<(u64, u32)> {
|
||||
let f = |n: &str| rdna2::field_value(d.enc, &d.words, n).unwrap_or(0);
|
||||
let v = match d.inst.name {
|
||||
"V_READLANE_B32" => f("SRC0").checked_sub(256)?,
|
||||
"V_WRITELANE_B32" => f("VDST"),
|
||||
_ => return None,
|
||||
};
|
||||
match lane_operand(d) {
|
||||
Lane::Const(l) => Some((v, l)),
|
||||
Lane::Sgpr => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The lane operand (SRC1) of `v_readlane` / `v_writelane`.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
enum Lane {
|
||||
Const(u32),
|
||||
Sgpr,
|
||||
}
|
||||
|
||||
fn lane_operand(d: &Decoded) -> Lane {
|
||||
let code = rdna2::field_value(d.enc, &d.words, "SRC1").unwrap_or(0);
|
||||
match code {
|
||||
128..=192 => Lane::Const((code - 128) as u32 & 63),
|
||||
193..=208 => Lane::Const((-((code - 192) as i32)) as u32 & 63),
|
||||
240..=248 => Lane::Const(f32_inline(code).unwrap_or(0) & 63),
|
||||
255 => d.literal.map_or(Lane::Sgpr, |l| Lane::Const(l & 63)),
|
||||
125 => Lane::Const(0),
|
||||
_ => Lane::Sgpr,
|
||||
}
|
||||
}
|
||||
|
||||
/// Source lane of a DPP16 control for `lane` (None: no source), as `emit::dpp16_src`.
|
||||
fn dpp16_lane(ctrl: u64, lane: u32) -> Option<Option<u32>> {
|
||||
let n = (ctrl & 15) as u32;
|
||||
let row = lane & !15;
|
||||
let i = lane & 15;
|
||||
Some(match ctrl {
|
||||
0x000..=0x0FF => Some((lane & !3) | ((ctrl as u32 >> (2 * (lane & 3))) & 3)),
|
||||
0x101..=0x10F => (i + n < 16).then_some(lane + n),
|
||||
0x111..=0x11F => (i >= n).then(|| lane - n),
|
||||
0x121..=0x12F => Some(row | ((i.wrapping_sub(n)) & 15)),
|
||||
0x140 => Some(row | (15 - i)),
|
||||
0x141 => Some(row | (i & 8) | (7 - (i & 7))),
|
||||
0x150..=0x15F => Some(row | n),
|
||||
0x160..=0x16F => Some(lane ^ n),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
fn f32_inline(code: u64) -> Option<u32> {
|
||||
Some(
|
||||
match code {
|
||||
240 => 0.5f32,
|
||||
241 => -0.5,
|
||||
242 => 1.0,
|
||||
243 => -1.0,
|
||||
244 => 2.0,
|
||||
245 => -2.0,
|
||||
246 => 4.0,
|
||||
247 => -4.0,
|
||||
248 => 0.159_154_94,
|
||||
_ => return None,
|
||||
}
|
||||
.to_bits(),
|
||||
)
|
||||
}
|
||||
|
||||
/// A VALU source (9-bit operand code) in console lane `32 + l`.
|
||||
fn operand(st: &State, d: &Decoded, code: u64, l: usize) -> Hi {
|
||||
match code {
|
||||
256..=511 => st.upper(code - 256)[l],
|
||||
128..=192 => Hi::Const((code - 128) as u32),
|
||||
193..=208 => Hi::Const((-((code - 192) as i32)) as u32),
|
||||
240..=248 => Hi::Const(f32_inline(code).unwrap_or(0)),
|
||||
255 => d.literal.map_or(Hi::Unknown, Hi::Const),
|
||||
_ => st.src32(d, code).value().map_or(Hi::Unknown, Hi::Const),
|
||||
}
|
||||
}
|
||||
|
||||
/// A two-source integer operation on the values of one lane.
|
||||
fn binary(name: &str, a: Hi, b: Hi) -> Option<Hi> {
|
||||
let f: fn(u32, u32) -> u32 = match name {
|
||||
"V_MIN_U32" => |a, b| a.min(b),
|
||||
"V_MAX_U32" => |a, b| a.max(b),
|
||||
"V_MIN_I32" => |a, b| (a as i32).min(b as i32) as u32,
|
||||
"V_MAX_I32" => |a, b| (a as i32).max(b as i32) as u32,
|
||||
"V_OR_B32" => |a, b| a | b,
|
||||
"V_AND_B32" => |a, b| a & b,
|
||||
"V_XOR_B32" => |a, b| a ^ b,
|
||||
"V_ADD_NC_U32" => |a, b| a.wrapping_add(b),
|
||||
_ => return None,
|
||||
};
|
||||
Some(match (a, b) {
|
||||
(Hi::Const(x), Hi::Const(y)) => Hi::Const(f(x, y)),
|
||||
(Hi::Unknown | Hi::Shadow, _) | (_, Hi::Unknown | Hi::Shadow) => Hi::Unknown,
|
||||
_ => Hi::Unwritten, // computed from a lane nothing wrote
|
||||
})
|
||||
}
|
||||
|
||||
/// Lanes 32..63 of `vdst` after a VALU instruction that writes all of them (EXEC's upper
|
||||
/// word all ones); None: not followed.
|
||||
fn evaluate(d: &Decoded, st: &State, vdst: u64) -> Option<[Hi; 32]> {
|
||||
let name = d.inst.name;
|
||||
let fv = |f: &str| rdna2::field_value(d.enc, &d.words, f).unwrap_or(0);
|
||||
let old = st.upper(vdst);
|
||||
if d.enc.name == "ENC_VOP3" && (fv("ABS") != 0 || fv("NEG") != 0 || fv("CLAMP") != 0 || fv("OMOD") != 0) {
|
||||
return None;
|
||||
}
|
||||
if matches!(name, "V_PERMLANE16_B32" | "V_PERMLANEX16_B32") {
|
||||
// lane i reads a lane chosen at run time in its own 32-lane half (rows 2 and 3 here):
|
||||
// followed when they all hold the same; FI / bound_ctrl only matter for inactive
|
||||
// sources, and EXEC's upper word is all ones
|
||||
let src = st.upper(fv("SRC0").checked_sub(256)?);
|
||||
let first = src[0];
|
||||
return src.iter().all(|&x| x == first).then_some([first; 32]).filter(|_| first != Hi::Shadow);
|
||||
}
|
||||
// source operands: (code of src0 as a 9-bit operand or a VGPR + 256, src1 code)
|
||||
let (mut src0, src1, src2) = match d.enc.name {
|
||||
"ENC_VOP1" => (fv("SRC0"), None, None),
|
||||
"ENC_VOP2" => (fv("SRC0"), Some(256 + fv("VSRC1")), None),
|
||||
"ENC_VOP3" => (fv("SRC0"), Some(fv("SRC1")), Some(fv("SRC2"))),
|
||||
_ => return None,
|
||||
};
|
||||
let mut dpp16 = None;
|
||||
let mut dpp8 = None;
|
||||
match d.variant {
|
||||
Variant::Plain => {}
|
||||
Variant::Sdwa => return None,
|
||||
Variant::Dpp16 => {
|
||||
let e = ext_encoding(d)?;
|
||||
let x = |n: &str| rdna2::field_value(e, &d.words, n).unwrap_or(0);
|
||||
src0 = 256 + x("VSRC0");
|
||||
dpp16 = Some((x("DPP_CTRL"), x("BOUND_CTRL") == 1, x("ROW_MASK"), x("BANK_MASK")));
|
||||
}
|
||||
Variant::Dpp8 => {
|
||||
let e = ext_encoding(d)?;
|
||||
let x = |n: &str| rdna2::field_value(e, &d.words, n).unwrap_or(0);
|
||||
src0 = 256 + x("VSRC0");
|
||||
let sel: Vec<u32> = (0..8).map(|i| x(&format!("LANE_SEL_{i}")) as u32).collect();
|
||||
dpp8 = Some(sel);
|
||||
}
|
||||
}
|
||||
let mut out = old;
|
||||
for (l, o) in out.iter_mut().enumerate() {
|
||||
let lane = 32 + l as u32;
|
||||
// src0 of this lane after DPP, or None: the lane is not written
|
||||
let a = if let Some((ctrl, bound, rm, bm)) = dpp16 {
|
||||
if (rm >> (lane >> 4)) & 1 == 0 || (bm >> ((lane >> 2) & 3)) & 1 == 0 {
|
||||
continue;
|
||||
}
|
||||
// every lane ≥ 32 is active (FI does not matter)
|
||||
match dpp16_lane(ctrl, lane)? {
|
||||
Some(s) => operand(st, d, src0, s as usize - 32),
|
||||
None if bound => Hi::Const(0),
|
||||
None => continue,
|
||||
}
|
||||
} else if let Some(sel) = &dpp8 {
|
||||
let s = (lane & !7) | sel[(lane & 7) as usize];
|
||||
operand(st, d, src0, s as usize - 32)
|
||||
} else {
|
||||
operand(st, d, src0, l)
|
||||
};
|
||||
*o = match name {
|
||||
"V_MOV_B32" if src1.is_none() => match a {
|
||||
Hi::Shadow => Hi::Unknown,
|
||||
x => x,
|
||||
},
|
||||
"V_CNDMASK_B32" => {
|
||||
let b = operand(st, d, src1?, l);
|
||||
// the mask's upper word: VCC (VOP2) or SRC2
|
||||
let m = match src2 {
|
||||
None => st.s[107],
|
||||
Some(c) => st.src64(d, c).1,
|
||||
};
|
||||
let r = match m {
|
||||
Word::Zero => a,
|
||||
Word::Ones => b,
|
||||
Word::Any => a.join(b),
|
||||
};
|
||||
if r == Hi::Shadow {
|
||||
Hi::Unknown
|
||||
} else {
|
||||
r
|
||||
}
|
||||
}
|
||||
_ => binary(name, a, operand(st, d, src1?, l))?,
|
||||
};
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// SGPRs an instruction may write (first register, count), from its output operands.
|
||||
fn sgpr_outputs(d: &Decoded) -> Vec<(u64, u64)> {
|
||||
let mut out = Vec::new();
|
||||
for o in d.ienc.operands.iter().filter(|o| o.output) {
|
||||
let n = (o.size as u64).div_ceil(32).max(1);
|
||||
match (o.field, o.ty) {
|
||||
(_, "OPR_VCC") => out.push((106, 2)),
|
||||
(_, "OPR_EXEC" | "OPR_SDST_EXEC") => out.push((126, 2)),
|
||||
(_, "OPR_SDST_M0") => out.push((124, 1)),
|
||||
(Some(f), ty) if !ty.starts_with("OPR_VGPR") && ty != "OPR_SRC_VGPR" => {
|
||||
let v = rdna2::field_value(d.enc, &d.words, f).unwrap_or(0) * rdna2::register_scale(f);
|
||||
if v < 128 {
|
||||
out.push((v, n));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
// an SDWA compare with SD = 1 writes its SDST instead of VCC
|
||||
if d.variant == Variant::Sdwa && d.enc.name == "ENC_VOPC" {
|
||||
if let Some(e) = ext_encoding(d) {
|
||||
let x = |n: &str| rdna2::field_value(e, &d.words, n).unwrap_or(0);
|
||||
out.retain(|&(r, _)| r != 106);
|
||||
out.push(if x("SD") == 1 { (x("SDST"), 2) } else { (106, 2) });
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn is_valu(d: &Decoded) -> bool {
|
||||
d.enc.name.starts_with("ENC_VOP") || d.enc.name.starts_with("VOP")
|
||||
}
|
||||
|
||||
/// The fetch-shader call at the start of a VS (`s_swappc_b64 s[n:n+1], s[n:n+1]`), which the
|
||||
/// emitter drops.
|
||||
fn fetch_call(d: &Decoded) -> bool {
|
||||
let f = |n: &str| rdna2::field_value(d.enc, &d.words, n);
|
||||
d.inst.name == "S_SWAPPC_B64" && f("SDST") == f("SSRC0")
|
||||
}
|
||||
|
||||
/// VGPRs an instruction writes: `rdna2::vgpr_uses`, with an image load's data registers
|
||||
/// counted from its DMASK (the operand tables give four).
|
||||
fn vgpr_writes(d: &Decoded) -> Vec<u64> {
|
||||
let (_, mut w) = rdna2::vgpr_uses(d);
|
||||
let n = d.inst.name;
|
||||
let dmask_counts = n.starts_with("IMAGE_SAMPLE") || n.starts_with("IMAGE_GATHER4") || n.starts_with("IMAGE_LOAD") || n == "IMAGE_GET_LOD";
|
||||
if d.enc.name.starts_with("ENC_MIMG") && dmask_counts && !w.is_empty() {
|
||||
let f = |n: &str| rdna2::field_value(d.enc, &d.words, n).unwrap_or(0);
|
||||
let mut n = if d.inst.name.starts_with("IMAGE_GATHER4") { 4 } else { f("DMASK").count_ones().max(1) as u64 };
|
||||
if f("D16") == 1 {
|
||||
n = n.div_ceil(2);
|
||||
}
|
||||
n += (f("TFE") | f("LWE")) & 1;
|
||||
w.truncate(n as usize);
|
||||
}
|
||||
w
|
||||
}
|
||||
|
||||
/// One instruction's effect.
|
||||
fn step(d: &Decoded, st: &mut State) {
|
||||
let name = d.inst.name;
|
||||
let fv = |f: &str| rdna2::field_value(d.enc, &d.words, f).unwrap_or(0);
|
||||
let exec_hi = st.s[127];
|
||||
if name.starts_with("S_MOVRELD") {
|
||||
// writes s[dst + m0]: any SGPR
|
||||
st.s = [Word::Any; 128];
|
||||
st.s[125] = Word::Zero;
|
||||
st.s[127] = exec_hi;
|
||||
return;
|
||||
}
|
||||
// VGPR lanes
|
||||
if name == "V_WRITELANE_B32" {
|
||||
let v = fv("VDST");
|
||||
match lane_operand(d) {
|
||||
Lane::Const(l) if l >= 32 => {
|
||||
let mut u = st.upper(v);
|
||||
u[l as usize - 32] = Hi::Shadow;
|
||||
st.set_upper(v, u);
|
||||
}
|
||||
Lane::Const(l) => *st.lo.entry(v).or_default() |= 1 << l,
|
||||
Lane::Sgpr => {
|
||||
let u = st.upper(v).map(|x| x.join(Hi::Unknown));
|
||||
st.set_upper(v, u);
|
||||
st.lo.remove(&v);
|
||||
}
|
||||
}
|
||||
} else if name.starts_with("V_MOVREL") {
|
||||
// writes v[dst + m0]: any VGPR
|
||||
st.lo.clear();
|
||||
if exec_hi != Word::Zero {
|
||||
let all: Vec<u64> = (0..256).collect();
|
||||
for v in all {
|
||||
let u = st.upper(v).map(|x| x.join(Hi::Unknown));
|
||||
st.set_upper(v, u);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let writes = vgpr_writes(d);
|
||||
let single = writes.len() == 1 && is_valu(d);
|
||||
// with only some lanes ≥ 32 active, DPP and v_permlane sources may be inactive: not followed
|
||||
let cross = d.variant != Variant::Plain || name.starts_with("V_PERMLANE");
|
||||
let mut new = Vec::new();
|
||||
for &v in &writes {
|
||||
st.lo.remove(&v);
|
||||
let lanes = match exec_hi {
|
||||
Word::Zero => continue,
|
||||
Word::Ones => match single.then(|| evaluate(d, st, v)).flatten() {
|
||||
Some(x) => x,
|
||||
None => [Hi::Unknown; 32],
|
||||
},
|
||||
Word::Any => {
|
||||
let n = (single && !cross).then(|| evaluate(d, st, v)).flatten().unwrap_or([Hi::Unknown; 32]);
|
||||
let mut o = st.upper(v);
|
||||
for (a, b) in o.iter_mut().zip(n) {
|
||||
*a = a.join(b);
|
||||
}
|
||||
o
|
||||
}
|
||||
};
|
||||
new.push((v, lanes));
|
||||
}
|
||||
for (v, lanes) in new {
|
||||
st.set_upper(v, lanes);
|
||||
}
|
||||
}
|
||||
// SGPRs
|
||||
let op = name.split('_').nth(1).unwrap_or("");
|
||||
let b64 = name.ends_with("_B64");
|
||||
if name.contains("SAVEEXEC") || name.contains("WREXEC") {
|
||||
let s0 = st.src64(d, fv("SSRC0"));
|
||||
let (el, eh) = (st.s[126], st.s[127]);
|
||||
let nl = bitop(op, s0.0, el).unwrap_or(Word::Any);
|
||||
let nh = bitop(op, s0.1, eh).unwrap_or(Word::Any);
|
||||
let dst = fv("SDST");
|
||||
let wr = name.contains("WREXEC");
|
||||
if b64 {
|
||||
st.s[126] = nl;
|
||||
st.s[127] = nh;
|
||||
st.set(dst, if wr { nl } else { el });
|
||||
st.set(dst + 1, if wr { nh } else { eh });
|
||||
} else {
|
||||
st.s[126] = nl;
|
||||
st.set(dst, if wr { nl } else { el });
|
||||
}
|
||||
return;
|
||||
}
|
||||
if d.enc.name == "ENC_SOP1" || d.enc.name == "ENC_SOP2" {
|
||||
let dst = fv("SDST");
|
||||
let a = |st: &State| if b64 { st.src64(d, fv("SSRC0")) } else { (st.src32(d, fv("SSRC0")), Word::Zero) };
|
||||
let b = |st: &State| if b64 { st.src64(d, fv("SSRC1")) } else { (st.src32(d, fv("SSRC1")), Word::Zero) };
|
||||
let r: Option<(Word, Word)> = match op {
|
||||
"MOV" if d.enc.name == "ENC_SOP1" => Some(a(st)),
|
||||
"NOT" if d.enc.name == "ENC_SOP1" => {
|
||||
let x = a(st);
|
||||
Some((x.0.not(), x.1.not()))
|
||||
}
|
||||
// a word of 0 / all ones stays 0 / all ones
|
||||
"WQM" if d.enc.name == "ENC_SOP1" => Some(a(st)),
|
||||
"CMOV" if d.enc.name == "ENC_SOP1" => {
|
||||
let x = a(st);
|
||||
let o = (st.s[dst.min(127) as usize], st.s[(dst + 1).min(127) as usize]);
|
||||
Some((x.0.join(o.0), x.1.join(o.1)))
|
||||
}
|
||||
"CSELECT" => {
|
||||
let (x, y) = (a(st), b(st));
|
||||
Some((x.0.join(y.0), x.1.join(y.1)))
|
||||
}
|
||||
_ if d.enc.name == "ENC_SOP2" => {
|
||||
let (x, y) = (a(st), b(st));
|
||||
bitop(op, x.0, y.0).zip(bitop(op, x.1, y.1))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
if let Some((lo, hi)) = r {
|
||||
st.set(dst, lo);
|
||||
if b64 {
|
||||
st.set(dst + 1, hi);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
let valu = is_valu(d);
|
||||
for (r, n) in sgpr_outputs(d) {
|
||||
if valu && n == 2 {
|
||||
// a lane mask: bits of inactive lanes are 0
|
||||
st.set(r, Word::Any);
|
||||
st.set(r + 1, if exec_hi == Word::Zero { Word::Zero } else { Word::Any });
|
||||
} else {
|
||||
for k in r..r + n {
|
||||
st.set(k, Word::Any);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The resolution of a cross-lane read in state `st` (before the instruction), if it is one.
|
||||
fn classify(d: &Decoded, st: &State) -> Option<(Read, Option<(u64, u32)>)> {
|
||||
let fv = |f: &str| rdna2::field_value(d.enc, &d.words, f).unwrap_or(0);
|
||||
// all lanes ≥ 32 together (a lane chosen per lane or at run time)
|
||||
let any_upper = |v: u64| -> Read {
|
||||
match st.upper(v).iter().fold(Hi::Unwritten, |m, &x| m.join(x)) {
|
||||
Hi::Unwritten => Read::Native,
|
||||
Hi::Const(c) => Read::Const(c),
|
||||
_ => Read::Unknown,
|
||||
}
|
||||
};
|
||||
match d.inst.name {
|
||||
"V_READLANE_B32" => {
|
||||
let v = fv("SRC0").checked_sub(256)?;
|
||||
match lane_operand(d) {
|
||||
Lane::Const(l) if l >= 32 => Some(match st.upper(v)[l as usize - 32] {
|
||||
Hi::Unwritten => (Read::Native, None),
|
||||
Hi::Const(c) => (Read::Const(c), None),
|
||||
Hi::Shadow => (Read::Shadow, Some((v, l))),
|
||||
Hi::Unknown => (Read::Unknown, None),
|
||||
}),
|
||||
Lane::Const(l) => (st.lo.get(&v).copied().unwrap_or(0) >> l & 1 == 1).then_some((Read::Shadow, Some((v, l)))),
|
||||
Lane::Sgpr => Some((any_upper(v), None)),
|
||||
}
|
||||
}
|
||||
"DS_BPERMUTE_B32" => {
|
||||
// source lanes ≥ 32 inactive: 0, as `Em::ds` gives for them
|
||||
Some((if st.s[127] == Word::Zero { Read::Native } else { any_upper(fv("DATA0")) }, None))
|
||||
}
|
||||
"DS_PERMUTE_B32" => Some((Read::Unknown, None)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Successors of each instruction (index); None: unknown (an indirect jump).
|
||||
fn successors(insts: &[Decoded], pcs: &BTreeMap<u64, usize>) -> Vec<Option<Vec<usize>>> {
|
||||
insts
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, d)| {
|
||||
let next = insts.get(i + 1).map(|n| n.pc).and_then(|pc| pcs.get(&pc).copied());
|
||||
if let Some(t) = d.far_target {
|
||||
return Some(vec![*pcs.get(&t)?]);
|
||||
}
|
||||
if fetch_call(d) {
|
||||
return Some(next.into_iter().collect());
|
||||
}
|
||||
if d.inst.flags & F_INDIRECT != 0 || d.inst.name == "S_SETPC_B64" || d.inst.name == "S_SWAPPC_B64" {
|
||||
return None;
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
if let Some(t) = rdna2::branch_target(d) {
|
||||
out.push(*pcs.get(&t)?);
|
||||
if d.inst.flags & F_CONDITIONAL != 0 {
|
||||
out.extend(next);
|
||||
}
|
||||
} else if d.inst.flags & F_TERMINATOR == 0 {
|
||||
out.extend(next);
|
||||
}
|
||||
Some(out)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Some: `analyze` notes where EXEC's upper word changes and VGPR lanes ≥ 32 become
|
||||
/// unknown (`tests::retail_wave64_graphics_lane_census`)
|
||||
pub static TRACE: std::cell::RefCell<Option<Vec<String>>> = const { std::cell::RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// The analysis of a whole program (instructions in address order, far jumps resolved).
|
||||
pub fn analyze(insts: &[Decoded]) -> UpperLanes {
|
||||
let mut out = UpperLanes::default();
|
||||
if insts.is_empty() {
|
||||
return out;
|
||||
}
|
||||
let pcs: BTreeMap<u64, usize> = insts.iter().enumerate().map(|(i, d)| (d.pc, i)).collect();
|
||||
// (a loop that runs out of its iteration budget, `LOOP_GUARD`, leaves from wherever it is:
|
||||
// not followed – the program's results are wrong by then anyway)
|
||||
let succ = successors(insts, &pcs);
|
||||
let mut at: Vec<Option<State>> = vec![None; insts.len()];
|
||||
at[0] = Some(State::entry());
|
||||
let mut work = BTreeSet::from([0usize]);
|
||||
while let Some(i) = work.pop_first() {
|
||||
let mut st = at[i].clone().expect("queued with a state");
|
||||
#[cfg(test)]
|
||||
let before = st.clone();
|
||||
step(&insts[i], &mut st);
|
||||
#[cfg(test)]
|
||||
TRACE.with(|t| {
|
||||
if let Some(t) = t.borrow_mut().as_mut() {
|
||||
let d = &insts[i];
|
||||
if before.s[127] != st.s[127] {
|
||||
t.push(format!("{:05x}: {} -> exec_hi {:?}", d.pc, rdna2::format(d), st.s[127]));
|
||||
}
|
||||
for (v, l) in &st.hi {
|
||||
if before.hi.get(v) != Some(l) && l.contains(&Hi::Unknown) {
|
||||
t.push(format!("{:05x}: {} -> v{v} upper {:?}", d.pc, rdna2::format(d), l[0]));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
let Some(s) = &succ[i] else {
|
||||
// an indirect jump (the emitter does not translate one either): nothing is
|
||||
// known, every read that may reach a lane ≥ 32 stays a hazard
|
||||
for d in insts.iter().filter(|d| reaches_upper(d)) {
|
||||
out.reads.insert(d.pc, Read::Unknown);
|
||||
}
|
||||
return out;
|
||||
};
|
||||
for &j in s {
|
||||
let new = match &at[j] {
|
||||
None => st.clone(),
|
||||
Some(old) => old.join(&st),
|
||||
};
|
||||
if at[j].as_ref() != Some(&new) {
|
||||
at[j] = Some(new);
|
||||
work.insert(j);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (d, st) in insts.iter().zip(&at) {
|
||||
let Some(st) = st else {
|
||||
// unreachable: never runs
|
||||
continue;
|
||||
};
|
||||
if let Some((r, slot)) = classify(d, st) {
|
||||
if let (Read::Shadow, Some(s)) = (r, slot) {
|
||||
out.shadows.insert(s);
|
||||
}
|
||||
out.reads.insert(d.pc, r);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::gpu::rdna2::encode;
|
||||
|
||||
const V: u64 = 256;
|
||||
type I = (&'static str, &'static str, &'static [(&'static str, u64)], Option<u32>);
|
||||
|
||||
fn program(lines: &[I]) -> Vec<Decoded> {
|
||||
let mut bytes: Vec<u8> = lines.iter().flat_map(|(n, e, f, l)| encode(n, e, f, *l).unwrap_or_else(|x| panic!("{n}: {x}"))).collect();
|
||||
bytes.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap());
|
||||
let mut out = Vec::new();
|
||||
let mut off = 0usize;
|
||||
while off < bytes.len() {
|
||||
let d = rdna2::decode(&bytes[off..], off as u64).unwrap();
|
||||
off += d.len;
|
||||
out.push(d);
|
||||
}
|
||||
rdna2::resolve_far_jumps(&mut out);
|
||||
out
|
||||
}
|
||||
|
||||
fn reads(lines: &[I]) -> Vec<Read> {
|
||||
let p = program(lines);
|
||||
let a = analyze(&p);
|
||||
p.iter().filter_map(|d| a.reads.get(&d.pc).copied()).collect()
|
||||
}
|
||||
|
||||
// the reduction of the retail pixel shaders: identity into the lanes outside the mask,
|
||||
// min over 8 lanes (DPP8 xor 1, 2, 4), row_mirror, the other row (v_permlanex16), then
|
||||
// v_readlane 32 for the upper half's result
|
||||
const WWM: I = ("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 30), ("SSRC0", 193)], None);
|
||||
const MASK: I = ("S_AND_B64", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 18), ("SSRC1", 30)], None);
|
||||
const SEED: I = ("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", 193), ("SRC1", V + 55), ("SRC2", 10)], None);
|
||||
const X1: I = ("V_MIN_U32", "VOP2_VOP_DPP8", &[("VDST", 6), ("SRC0", 0xE9), ("VSRC0", 6), ("VSRC1", 6), ("LANE_SEL_0", 1), ("LANE_SEL_1", 0), ("LANE_SEL_2", 3), ("LANE_SEL_3", 2), ("LANE_SEL_4", 5), ("LANE_SEL_5", 4), ("LANE_SEL_6", 7), ("LANE_SEL_7", 6)], None);
|
||||
const MIRROR: I = ("V_MIN_U32", "VOP2_VOP_DPP16", &[("VDST", 6), ("SRC0", 0xFA), ("VSRC0", 6), ("VSRC1", 6), ("DPP_CTRL", 0x140), ("ROW_MASK", 0xF), ("BANK_MASK", 0xF)], None);
|
||||
const PX16: I = ("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 7), ("SRC0", V + 6), ("SRC1", 128), ("SRC2", 128)], None);
|
||||
const COMBINE: I = ("V_MIN_U32", "ENC_VOP2", &[("VDST", 6), ("SRC0", V + 7), ("VSRC1", 6)], None);
|
||||
const READ32: I = ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 6), ("SRC1", 128 + 32)], None);
|
||||
const RESTORE: I = ("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 30)], None);
|
||||
|
||||
#[test]
|
||||
fn a_whole_wave_reduction_reads_its_identity() {
|
||||
assert_eq!(reads(&[WWM, MASK, SEED, X1, MIRROR, PX16, COMBINE, READ32, RESTORE]), vec![Read::Const(u32::MAX)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_identity_is_only_known_while_the_mask_leaves_the_upper_lanes_out() {
|
||||
// the mask from s[18:19] alone: its upper word may select v55's lanes
|
||||
const MASK_ANY: I = ("S_MOV_B64", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 18)], None);
|
||||
assert_eq!(reads(&[WWM, MASK_ANY, SEED, X1, READ32, RESTORE]), vec![Read::Const(u32::MAX)], "v55 unwritten: either is right");
|
||||
// v55's upper lanes written (with something unknown) before: not followed
|
||||
const V55: I = ("V_MOV_B32", "ENC_VOP1", &[("VDST", 55), ("SRC0", 20)], None);
|
||||
assert_eq!(reads(&[WWM, V55, MASK_ANY, SEED, X1, READ32, RESTORE]), vec![Read::Unknown]);
|
||||
// with the saved EXEC in the mask, v55 does not matter
|
||||
assert_eq!(reads(&[WWM, V55, MASK, SEED, X1, READ32, RESTORE]), vec![Read::Const(u32::MAX)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dpp_shift_with_bound_ctrl_breaks_the_constant() {
|
||||
// row_shr:1 with bound_ctrl: the first lane of each row takes 0 – min(0, -1) = 0 there
|
||||
const SHR: I = ("V_MIN_U32", "VOP2_VOP_DPP16", &[("VDST", 6), ("SRC0", 0xFA), ("VSRC0", 6), ("VSRC1", 6), ("DPP_CTRL", 0x111), ("ROW_MASK", 0xF), ("BANK_MASK", 0xF), ("BOUND_CTRL", 1)], None);
|
||||
const READ48: I = ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 6), ("SRC1", 128 + 48)], None);
|
||||
const READ49: I = ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 6), ("SRC1", 128 + 49)], None);
|
||||
assert_eq!(reads(&[WWM, MASK, SEED, SHR, READ48, READ49, RESTORE]), vec![Read::Const(0), Read::Const(u32::MAX)]);
|
||||
// the permlane of lanes that differ is not followed
|
||||
assert_eq!(reads(&[WWM, MASK, SEED, SHR, PX16, ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 7), ("SRC1", 128 + 32)], None), RESTORE]), vec![Read::Unknown]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outside_whole_wave_code_the_upper_lanes_stay_unwritten() {
|
||||
// a waterfall loop's read: s_ff1 of the active lanes picks the lane
|
||||
let r = reads(&[
|
||||
("V_MOV_B32", "ENC_VOP1", &[("VDST", 51), ("SRC0", 20)], None),
|
||||
("S_AND_B64", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 72), ("SSRC1", 126)], None),
|
||||
("S_FF1_I32_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 0)], None),
|
||||
("V_READLANE_B32", "ENC_VOP3", &[("VDST", 4), ("SRC0", V + 51), ("SRC1", 0)], None),
|
||||
("DS_BPERMUTE_B32", "ENC_DS", &[("VDST", 1), ("ADDR", 2), ("DATA0", 51)], None),
|
||||
]);
|
||||
assert_eq!(r, vec![Read::Native, Read::Native]);
|
||||
// after s_mov_b64 exec, -1 (no saved copy) the same move writes the upper lanes
|
||||
let r = reads(&[
|
||||
("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 193)], None),
|
||||
("V_MOV_B32", "ENC_VOP1", &[("VDST", 51), ("SRC0", 20)], None),
|
||||
("V_READLANE_B32", "ENC_VOP3", &[("VDST", 4), ("SRC0", V + 51), ("SRC1", 0)], None),
|
||||
("DS_BPERMUTE_B32", "ENC_DS", &[("VDST", 1), ("ADDR", 2), ("DATA0", 51)], None),
|
||||
]);
|
||||
assert_eq!(r, vec![Read::Unknown, Read::Unknown]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spill_slots_come_from_their_shadow() {
|
||||
let wl = |lane: u64, s: u64| -> I {
|
||||
let f: &'static [(&'static str, u64)] = Box::leak(vec![("VDST", 96), ("SRC0", s), ("SRC1", 128 + lane)].into_boxed_slice());
|
||||
("V_WRITELANE_B32", "ENC_VOP3", f, None)
|
||||
};
|
||||
let rl = |lane: u64| -> I {
|
||||
let f: &'static [(&'static str, u64)] = Box::leak(vec![("VDST", 20), ("SRC0", V + 96), ("SRC1", 128 + lane)].into_boxed_slice());
|
||||
("V_READLANE_B32", "ENC_VOP3", f, None)
|
||||
};
|
||||
let p = program(&[wl(5, 20), wl(36, 21), rl(5), rl(36), rl(37), ("V_MOV_B32", "ENC_VOP1", &[("VDST", 96), ("SRC0", 20)], None), rl(5), rl(36)]);
|
||||
let a = analyze(&p);
|
||||
let r: Vec<Read> = p.iter().filter_map(|d| a.reads.get(&d.pc).copied()).collect();
|
||||
// lane 37 was never written: anything; after the move lane 5 is the move's (a
|
||||
// native read, not listed), lane 36 still the spill
|
||||
assert_eq!(r, vec![Read::Shadow, Read::Shadow, Read::Native, Read::Shadow]);
|
||||
assert_eq!(a.shadows, BTreeSet::from([(96, 5), (96, 36)]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paths_join() {
|
||||
// one path writes the spill slot, the other a whole-wave constant: not followed
|
||||
let r = reads(&[
|
||||
("S_CBRANCH_SCC0", "ENC_SOPP", &[("SIMM16", 3)], None),
|
||||
("V_WRITELANE_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", 20), ("SRC1", 128 + 32)], None),
|
||||
("S_BRANCH", "ENC_SOPP", &[("SIMM16", 5)], None),
|
||||
WWM,
|
||||
MASK,
|
||||
SEED,
|
||||
RESTORE,
|
||||
READ32,
|
||||
]);
|
||||
assert_eq!(r, vec![Read::Unknown]);
|
||||
// both paths the same constant (or nothing): the constant
|
||||
let r = reads(&[("S_CBRANCH_SCC0", "ENC_SOPP", &[("SIMM16", 4)], None), WWM, MASK, SEED, RESTORE, READ32]);
|
||||
assert_eq!(r, vec![Read::Const(u32::MAX)]);
|
||||
}
|
||||
}
|
||||
@@ -304,6 +304,8 @@ struct RecompAgg {
|
||||
graphics_wave32: usize,
|
||||
graphics_wave64: usize,
|
||||
wave_hazards: BTreeMap<String, usize>,
|
||||
/// … and the reads of lanes ≥ 32 the 32-lane form resolves (kind → programs)
|
||||
wave_resolved: BTreeMap<String, usize>,
|
||||
/// `--example MNEMONIC`: listing of the first program missing it, its HLSL and profile
|
||||
example: Option<(String, String, &'static str)>,
|
||||
}
|
||||
@@ -337,6 +339,9 @@ impl RecompAgg {
|
||||
for (k, v) in o.wave_hazards {
|
||||
*self.wave_hazards.entry(k).or_default() += v;
|
||||
}
|
||||
for (k, v) in o.wave_resolved {
|
||||
*self.wave_resolved.entry(k).or_default() += v;
|
||||
}
|
||||
for (k, (a, b)) in o.by_mode {
|
||||
let e = self.by_mode.entry(k).or_default();
|
||||
e.0 += a;
|
||||
@@ -366,10 +371,16 @@ impl RecompAgg {
|
||||
if matches!(label, "VS" | "PS") {
|
||||
if wave64 {
|
||||
self.graphics_wave64 += 1;
|
||||
let hz = recomp::wave_hazards(code);
|
||||
let (hz, resolved) = recomp::wave_lane_reads(code);
|
||||
for k in &hz {
|
||||
*self.wave_hazards.entry(k.to_string()).or_default() += 1;
|
||||
}
|
||||
for k in &resolved {
|
||||
*self.wave_resolved.entry(k.to_string()).or_default() += 1;
|
||||
}
|
||||
if !resolved.is_empty() {
|
||||
*self.wave_resolved.entry("(programs)".into()).or_default() += 1;
|
||||
}
|
||||
if !hz.is_empty() {
|
||||
*self.wave_hazards.entry("(programs at risk)".into()).or_default() += 1;
|
||||
}
|
||||
@@ -1061,8 +1072,8 @@ fn print(path: &Path, what: &str, agg: Agg, top: usize, json: bool, t0: std::tim
|
||||
println!(" {k:<60} {v:>6}");
|
||||
}
|
||||
println!(
|
||||
"VS/PS and the wave size (the driver picks it): wave32 {} (handled – the halves of a 64-wide wave run separately), wave64 {}; hazards in 32-thread waves: {:?}",
|
||||
rc.graphics_wave32, rc.graphics_wave64, rc.wave_hazards
|
||||
"VS/PS and the wave size (the driver picks it): wave32 {} (handled – the halves of a 64-wide wave run separately), wave64 {}; hazards in 32-thread waves: {:?}; reads of lanes ≥ 32 resolved (32-lane GPUs): {:?}",
|
||||
rc.graphics_wave32, rc.graphics_wave64, rc.wave_hazards, rc.wave_resolved
|
||||
);
|
||||
if let Some((x, hlsl, profile)) = &rc.example {
|
||||
println!("example:
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
# Wave64 console programs on 32-lane GPUs
|
||||
|
||||
Status: implemented for compute / kernel mode, the mesh (NGG) first pass and ES+GS
|
||||
(`gpu/recomp/emit.rs`, `PRELUDE_X64`). The native path is untouched: the form below is only
|
||||
(`gpu/recomp/emit.rs`, `PRELUDE_X64`); wave64 VS / PS, which cannot be paired, get the values
|
||||
of the lanes ≥ 32 they read instead (`upper_lanes.rs`, "Vertex and pixel shaders" below).
|
||||
The native path is untouched: the form below is only
|
||||
generated when the adapter cannot run 64-lane waves (`D3D12_FEATURE_DATA_D3D12_OPTIONS1`
|
||||
`WaveLaneCountMax < 64`, e.g. NVIDIA, whose D3D12 range is 32..32). On such an adapter a
|
||||
`[WaveSize(64)]` compute shader is rejected at PSO creation, so until now wave64 compute
|
||||
@@ -138,8 +140,10 @@ destination, 0 in every lane), which are the same in both halves either way.
|
||||
A wave64 program pays one exchange per mask write that is read whole (`v_cmp*` feeding
|
||||
`s_and_saveexec`, `s_cbranch_vccz`, `s_bcnt1`, …) and per readlane / readfirstlane /
|
||||
ds_bpermute / coherent scalar load, nothing per ALU, memory or DPP instruction, nor for
|
||||
masks read lane by lane (selects, 64-bit carry chains). Wave32 programs, VS / PS and everything on GPUs with 64-lane waves are
|
||||
unchanged (the HLSL of every native translation the test suite makes is byte-identical).
|
||||
masks read lane by lane (selects, 64-bit carry chains). Wave32 programs and everything on GPUs with 64-lane waves are
|
||||
unchanged (the HLSL of every native translation the test suite makes is byte-identical). A
|
||||
wave64 VS / PS pays nothing for a lane ≥ 32 read as a constant (the lane read is skipped) and
|
||||
one scalar per spill slot read from its shadow.
|
||||
|
||||
Measured on an RTX 5070 Ti (`bench_split_wave64`, an ignored test): a loop of 8
|
||||
instructions with one exchange, 2^18 threads × 32 768 iterations, wave32 program (no
|
||||
@@ -179,6 +183,92 @@ What is left is readlane / readfirstlane, `ds_bpermute`, coherent scalar loads a
|
||||
read whole. Not measured on real compute shaders (none on that machine); Minecraft's 273
|
||||
wave64 programs, translated as compute, have 38 mask writes, all only read lane by lane.
|
||||
|
||||
## Vertex and pixel shaders
|
||||
|
||||
The driver picks the wave size of a VS or PS (HLSL has no `[WaveSize]` for them), and on a
|
||||
GPU with 32-lane waves only a console wave64 VS / PS runs in waves of 32. Nothing pairs two of
|
||||
them (no groupshared memory), so such a wave stands for a console wave whose lanes 32..63 are
|
||||
not populated, as in the last, partial wave of a draw. Per-lane code is exact as it is, and so
|
||||
are masks (their upper word is 0: those lanes are inactive), DPP / `ds_swizzle` /
|
||||
`v_permlane(x)16` (inside a 32-lane half) and `v_readfirstlane`. What is not: a read of a lane
|
||||
≥ 32 – `v_readlane` with a constant lane ≥ 32 or a lane from an SGPR, `ds_bpermute` – and
|
||||
`v_writelane` to one. On the console those lanes exist, inactive, and hold what `v_writelane`
|
||||
(which ignores EXEC) or whole-wave code (EXEC's upper word set, `s_or_saveexec_b64 s, -1`)
|
||||
put there; here they do not exist, and `WaveReadLaneAt(v, l)` with l ≥ 32 is undefined (NVIDIA
|
||||
gives lane l & 31).
|
||||
|
||||
### What the retail pack does
|
||||
|
||||
`retail_wave64_graphics_lane_census` (an ignored test) lists every such read in the pack's
|
||||
wave64 VS / PS (13 210 programs; 749 – 748 PS, 1 VS – were flagged by the old `wave_hazards`):
|
||||
|
||||
| pattern | reads | programs (distinct code) | the console lane ≥ 32 holds | before |
|
||||
|---|---|---|---|---|
|
||||
| whole-wave reduction: the identity into the lanes outside the mask (`v_cndmask` with mask & saved EXEC), DPP8 xor 1 / 2 / 4, row_mirror, `v_permlanex16`, `v_readlane` 32 for the upper half, `v_readlane` 0 for the total; `v_min_u32` (identity -1), `v_max_u32` (0), `v_or_b32` (0) | 1 082 | 436 (434) | the identity | right by chance: NVIDIA reads lane 0 for lane 32, and min / max / or are idempotent (a sum would double) |
|
||||
| waterfall / uniformity check: `v_readlane v, s` with s = `s_ff1_i32_b64(mask & EXEC)` | 355 | 353 (351) | nothing (the lane is < 32 unless the mask is empty; then 63, never written) | right |
|
||||
| SGPR spill slots: `v_writelane` / `v_readlane` of lanes 0..47 of one VGPR | 200 | 11 | the spilled SGPR | wrong: the write is lost, the read returns another slot (lane & 31) |
|
||||
| `ds_bpermute` | 0 | | | |
|
||||
|
||||
### The form
|
||||
|
||||
For a wave64 VS / PS with `split_wave64`, `upper_lanes.rs` follows what the console's lanes
|
||||
32..63 hold through the program, a forward data-flow pass over its control flow:
|
||||
- EXEC's upper word, with the SGPRs as words known to be 0, all ones, or anything: 0 at the
|
||||
start, 0 in every mask a VALU instruction writes while it is 0, combined by the bitwise SALU
|
||||
and saveexec forms. While it is 0 no VALU instruction writes lanes 32..63.
|
||||
- per VGPR lane ≥ 32: unwritten, a constant, a spill slot, or unknown. A VALU write while
|
||||
EXEC's upper word is all ones is evaluated (moves, `v_cndmask`, integer min / max / and / or /
|
||||
xor / add, their DPP16 / DPP8 forms, `v_permlane(x)16` of lanes that all hold the same);
|
||||
`v_writelane` makes the lane a slot. Paths join lane by lane (an unwritten lane takes the
|
||||
other path's value: any value is right for it).
|
||||
|
||||
Each read then gets:
|
||||
- unwritten: the read as it is – the console reads what an earlier wave left in the register,
|
||||
which no program can depend on;
|
||||
- a constant: that constant (`uint t = c; if (!xcl_hw32) t = rla(…);`);
|
||||
- a slot: its shadow `xcl_sh<vgpr>_<lane>`, a scalar every `v_writelane` of that slot also
|
||||
writes;
|
||||
- unknown: stays a hazard – `wave_hazards` reports only these.
|
||||
|
||||
Spill slots < 32 are read from their shadows as well, whatever the wave size, as long as no
|
||||
other instruction has written the VGPR since the slot's `v_writelane`: in a partial wave (a
|
||||
primitive's edge) a lane that was not launched loses what `v_writelane` put there. 287 pixel
|
||||
shaders of the pack (3 540 reads) spill to lanes < 32.
|
||||
|
||||
The wave size is checked at run time (`xcl_hw32 = WaveGetLaneCount() < 64`), so a driver that
|
||||
picks 64 lanes runs the program as before. Without `split_wave64` (a GPU with 64-lane waves)
|
||||
nothing changes: the HLSL of every program of the pack is identical to the one before
|
||||
(`retail_wave64_graphics_lane_forms` prints digests of the native form, and of the other modes'
|
||||
32-lane form, to compare builds).
|
||||
|
||||
In the pack every read resolves: 1 082 constants, 355 unwritten, 3 740 slot reads; none is
|
||||
left unsafe. Only a program with a constant or a slot to read gets the form: the HLSL changes
|
||||
for 613 programs (the 436 reductions and the 287 with spill slots, which overlap), all of
|
||||
which DXC compiles. Tests on the GPU: `gpu_wave64_ps_whole_wave_reductions`
|
||||
(the pack's reduction as min and as a sum, and the waterfall read, checked per hardware wave
|
||||
against a console wave of the same lanes), `gpu_wave64_ps_spill_slots` (whole target and a
|
||||
6-pixel triangle), `gpu_wave64_vs_spill_slots_and_identity` (a wave of 3 vertices).
|
||||
|
||||
### What is still not exact
|
||||
|
||||
**Lanes the PC did not launch, inside a wave** – on every GPU and wave size, and before this
|
||||
change too. The console runs whole-wave code in all 64 lanes, inactive ones included; the
|
||||
translation runs it only in the lanes the PC GPU launched. In a partial wave, the reduction's
|
||||
DPP / `v_permlanex16` steps read lanes that were never launched (undefined) instead of the
|
||||
identity the console put there – not only lanes 32..63. The lanes ≥ 32 of a 32-lane wave are
|
||||
handled above because they are all missing and all hold the identity; a lane missing among
|
||||
launched ones holds a partial result that the translation does not have. Making that exact
|
||||
needs the reduction recognised as a whole (`WaveActiveMin` / `Max` / `BitOr` over the
|
||||
launched lanes, with the identity for the lanes outside the mask) – not done. Measured on an
|
||||
RTX 5070 Ti (the reduction of `gpu_wave64_ps_whole_wave_reductions` drawn as a 3-quad
|
||||
triangle, lanes 12..31 not launched): those lanes read 0, so a min reduction (identity -1)
|
||||
gives 0, while max / or / sum (identity 0) and the waterfall read are right. 325 of the 436
|
||||
reduction programs have a min reduction (322 a max, 433 an or).
|
||||
|
||||
Spill slots of lanes that were not launched are also still lost in the native form (GPUs with
|
||||
64-lane waves, which keep the HLSL as it was), and in the 32-lane form for slots ≥ 32 when the
|
||||
driver picks 64 lanes.
|
||||
|
||||
## Relation to earlier work
|
||||
|
||||
* **PR #33** (ElHombreAlex, draft): first wave64 → wave32 "rendezvous" through groupshared
|
||||
|
||||
Reference in New Issue
Block a user