From f25f3904064f729b867c3f411b410b8593508110 Mon Sep 17 00:00:00 2001 From: Jerkin42 <66524771+Jerkin42@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:46:31 +0000 Subject: [PATCH 1/2] xshader: read whole lane masks where a program counts one A translated thread holds only its own bit of a lane mask, so counting a mask's lanes (s_bcnt1), finding its first one (s_ff1) or counting those before a lane (v_mbcnt) gave 0 or 1 for a whole wave. Compute programs that hand out list slots this way gave the same few slots to every thread: in ProjectScarlett the shadow mask tiles of lit surfaces, which showed as 16-pixel blocks. Find the masks such instructions read by their reaching definitions, take the wave's ballot right after each one, while every lane that can be in it is there, and read that. A register that holds anything else on some path keeps the old translation. One-word masks need 32-lane waves. Two words hold a wave of any size, so wave64 programs gain no requirement and still run on adapters that only have wave32. Co-Authored-By: Claude Opus 5.5 --- docs/SHADERS.md | 6 + tools/check_lockstep_gpu.py | 4 +- tools/check_mask_ballots_gpu.py | 204 ++++++++++++++++++ tools/check_packed_integer_gpu.py | 4 +- tools/check_translator_gpu.py | 1 + .../shader-compiler/examples/mask_ballots.rs | 30 +++ tools/shader-compiler/src/hlsl.rs | 3 + .../src/hlsl/driver/pipeline.rs | 19 +- .../src/hlsl/emitter/instruction.rs | 3 + .../src/hlsl/emitter/scalar.rs | 12 +- .../shader-compiler/src/hlsl/emitter/setup.rs | 1 + .../src/hlsl/emitter/vector.rs | 2 +- .../shader-compiler/src/hlsl/mask_ballots.rs | 201 +++++++++++++++++ .../src/tests/hlsl/mask_ballots.rs | 106 +++++++++ 14 files changed, 587 insertions(+), 9 deletions(-) create mode 100644 tools/check_mask_ballots_gpu.py create mode 100644 tools/shader-compiler/examples/mask_ballots.rs create mode 100644 tools/shader-compiler/src/hlsl/mask_ballots.rs create mode 100644 tools/shader-compiler/src/tests/hlsl/mask_ballots.rs diff --git a/docs/SHADERS.md b/docs/SHADERS.md index 4a2d01ae..7ceae9e0 100644 --- a/docs/SHADERS.md +++ b/docs/SHADERS.md @@ -146,6 +146,12 @@ The console branches once per wave, but the translator normally branches once pe A [GPU check](../tools/check_lockstep_gpu.py) compares both paths with a model of the console on an RTX 4070 Ti SUPER: 245 cases match. Programs that translate through the targeted checks still branch once per thread. With the final branch that routes them to whole-wave translation removed, 160 of 210 cases of the same programs give wrong results, so some shaders that translate today are likely to compute wrong values. This hasn't been traced to anything visible in a game. +### Lane masks read as numbers + +Each thread of a translated program holds only its own bit of a lane mask. Counting a mask's lanes, finding its first one or counting those before a lane reads the other bits too, and gave 0 or 1 for a whole wave. Compute programs now take the wave's ballot where such a mask is computed and read that ([analysis](../tools/shader-compiler/src/hlsl/mask_ballots.rs)). It has to be a lane mask on every path to the read. Programs with one-word masks need 32-lane waves. Two words hold a wave of any size, so wave64 programs still run on adapters that only have wave32. + +A [GPU check](../tools/check_mask_ballots_gpu.py) compares both widths with a model of the console on an RX 9060 XT: 300 cases match, and 200 of them don't without the ballots. In ProjectScarlett this affects the passes that hand out shadow mask tiles, where most lit tiles shared a few slots and shadows showed as 16-pixel blocks. + Most wave reduction refusals come from programs over 6,000 instructions, where the translator doesn't try its one-lane-per-wave form. In a trial on an earlier set of 1,442 such compute shaders, removing that limit translated 1,211. Six sampled outputs compiled in 2 to 12 seconds with DXC optimization off, and mostly produced 1 to 2 MB of DXIL. Large compiles in a recorded run took the driver 6 minutes or more, so the limit stays until the generated code compiles faster. The outputs weren't tested in a game. ### Earlier survey diff --git a/tools/check_lockstep_gpu.py b/tools/check_lockstep_gpu.py index 33e14f1c..ca102cb2 100644 --- a/tools/check_lockstep_gpu.py +++ b/tools/check_lockstep_gpu.py @@ -83,11 +83,11 @@ def program(body, resolve=False): ] -def words_of(items, llvm_mc): +def words_of(items, llvm_mc, *options): lines = [item for item in items if isinstance(item, str)] sizes, encoded = [], [] for line in lines: - encoded.append(assemble([line], llvm_mc)) + encoded.append(assemble([line], llvm_mc, *options)) offsets, position, queue = {}, 0, iter(encoded) for item in items: if isinstance(item, str): diff --git a/tools/check_mask_ballots_gpu.py b/tools/check_mask_ballots_gpu.py new file mode 100644 index 00000000..52ca63c8 --- /dev/null +++ b/tools/check_mask_ballots_gpu.py @@ -0,0 +1,204 @@ +#!/usr/bin/env python3 +"""Check on a real GPU that lane masks read as numbers hold the whole wave's lanes. + +Each synthetic program counts a mask's lanes, finds its first one or counts +those before each lane, some of them after EXEC was narrowed to one elected +lane. The reference models the console. A wave64 program is modelled on the +host's own wave, which can be 32 lanes: every part of the wave is a wave of its +own there. Only the translator's input and output are instrumented. No game +data is needed. +""" +import argparse +import json +from pathlib import Path +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +sys.path.insert(0, str(ROOT / "tools")) +from check_lockstep_gpu import LIMIT, branch, label, words_of # noqa: E402 +from check_wave_guard import cases # noqa: E402 +from frosty_gpu_guest import run_gpu_guest # noqa: E402 +from project_tuxbox.inspect import digest # noqa: E402 + +# Results go to v10, v11 and v12. s12 holds the entry EXEC and v14 the lane's index. +WAVE_OPTIONS = {32: (), 64: ("-mattr=-wavefrontsize32,+wavefrontsize64",)} +WAVE32 = { + # A compare's own mask. + "compare": ["v_cmp_lt_u32_e32 vcc_lo, 0x3e8, v0", "s_bcnt1_i32_b32 s20, vcc_lo", "v_mov_b32_e32 v10, s20", + "v_mbcnt_lo_u32_b32 v11, vcc_lo, 0", "s_ff1_i32_b32 s21, vcc_lo", "v_mov_b32_e32 v12, s21"], + # A copy of EXEC, read after one lane of it was elected. + "elected": ["v_mbcnt_lo_u32_b32 v14, -1, 0", "v_cmp_lt_u32_e32 vcc_lo, 0x3e8, v0", + "s_and_saveexec_b32 s10, vcc_lo", branch("s_cbranch_execz", "end"), + "s_mov_b32 s11, exec_lo", "v_mbcnt_lo_u32_b32 v11, s11, 0", + "s_ff1_i32_b32 s21, s11", "v_mov_b32_e32 v12, s21", + "v_cmpx_eq_u32_e32 s21, v14", "s_bcnt1_i32_b32 s20, s11", "v_mov_b32_e32 v10, s20", + label("end")], + # A mask gathered over a loop. + "gathered": ["s_mov_b32 s11, 0", "s_mov_b32 s22, 0", label("again"), + "v_and_b32_e32 v15, 3, v0", "v_cmp_eq_u32_e32 vcc_lo, s22, v15", "s_or_b32 s11, s11, vcc_lo", + "s_add_u32 s22, s22, 1", "s_cmp_lt_u32 s22, 3", branch("s_cbranch_scc1", "again"), + "s_bcnt1_i32_b32 s20, s11", "v_mov_b32_e32 v10, s20", "v_mbcnt_lo_u32_b32 v11, s11, 0", + "v_mov_b32_e32 v12, 0"], + # The lanes left out, and a branch on their number. + "others": ["v_cmp_lt_u32_e32 vcc_lo, 0x3e8, v0", "s_andn2_b32 s11, exec_lo, vcc_lo", + "s_bcnt1_i32_b32 s20, s11", branch("s_cbranch_scc0", "end"), "v_mov_b32_e32 v10, s20", + "v_mbcnt_lo_u32_b32 v11, s11, 0", "v_mov_b32_e32 v12, 1", label("end")], +} +WAVE64 = { + "compare": ["v_cmp_lt_u32_e32 vcc, 0x3e8, v0", "s_bcnt1_i32_b64 s20, vcc", "v_mov_b32_e32 v10, s20", + "v_mbcnt_lo_u32_b32 v11, vcc_lo, 0", "v_mbcnt_hi_u32_b32 v11, vcc_hi, v11", + "s_ff1_i32_b64 s21, vcc", "v_mov_b32_e32 v12, s21"], + "elected": ["v_mbcnt_lo_u32_b32 v14, -1, 0", "v_mbcnt_hi_u32_b32 v14, -1, v14", + "v_cmp_lt_u32_e32 vcc, 0x3e8, v0", "s_and_saveexec_b64 s[10:11], vcc", branch("s_cbranch_execz", "end"), + "s_mov_b64 s[14:15], exec", "v_mbcnt_lo_u32_b32 v11, s14, 0", "v_mbcnt_hi_u32_b32 v11, s15, v11", + "s_ff1_i32_b64 s21, s[14:15]", "v_mov_b32_e32 v12, s21", + "v_cmpx_eq_u32_e32 s21, v14", "s_bcnt1_i32_b64 s20, s[14:15]", "v_mov_b32_e32 v10, s20", + label("end")], + "gathered": ["s_mov_b64 s[14:15], 0", "s_mov_b32 s22, 0", label("again"), + "v_and_b32_e32 v15, 3, v0", "v_cmp_eq_u32_e32 vcc, s22, v15", "s_or_b64 s[14:15], s[14:15], vcc", + "s_add_u32 s22, s22, 1", "s_cmp_lt_u32 s22, 3", branch("s_cbranch_scc1", "again"), + "s_bcnt1_i32_b64 s20, s[14:15]", "v_mov_b32_e32 v10, s20", + "v_mbcnt_lo_u32_b32 v11, s14, 0", "v_mbcnt_hi_u32_b32 v11, s15, v11", "v_mov_b32_e32 v12, 0"], + "others": ["v_cmp_lt_u32_e32 vcc, 0x3e8, v0", "s_andn2_b64 s[14:15], exec, vcc", + "s_bcnt1_i32_b64 s20, s[14:15]", branch("s_cbranch_scc0", "end"), "v_mov_b32_e32 v10, s20", + "v_mbcnt_lo_u32_b32 v11, s14, 0", "v_mbcnt_hi_u32_b32 v11, s15, v11", "v_mov_b32_e32 v12, 1", + label("end")], +} + + +def program(body, width): + size = "64" if width == 64 else "32" + exec_, saved = ("exec", "s[12:13]") if width == 64 else ("exec_lo", "s12") + return [f"s_mov_b{size} {saved}, {exec_}", *body, f"s_mov_b{size} {exec_}, {saved}", "s_endpgm"] + + +def model(name, active, values, host): + """v10, v11 and v12 of every lane, with the group run as waves of `host` lanes.""" + rows = [] + for start in range(0, len(values), host): + lanes = range(host) + on = [active[start + i] for i in lanes] + value = values[start:start + host] + over = [on[i] and value[i] > LIMIT for i in lanes] + mask = {"compare": over, "elected": over, "gathered": [on[i] and value[i] & 3 < 3 for i in lanes], + "others": [on[i] and not over[i] for i in lanes]}[name] + count, first = sum(mask), mask.index(True) if any(mask) else 0xffffffff + for i in lanes: + rank = sum(mask[:i]) + if not on[i] or not any(mask) and name in ("elected", "others"): + rows.append((0, 0, 0)) + elif name == "compare": + rows.append((count, rank, first)) + elif name == "elected": + rows.append((count if i == first else 0, rank, first) if mask[i] else (0, 0, 0)) + else: + rows.append((count, rank, int(name == "others"))) + return rows + + +def instrument(hlsl, width): + start = " v0 = gtid.x; v1 = gtid.y; v2 = gtid.z;" + load = (" uint input = output[gtid.x];\n exec_lo = input >> 31;\n" + " v0 = input & 0x7fffffffu; v1 = gtid.y; v2 = gtid.z;") + if hlsl.count(start) != 1 or "WaveActiveBallot" not in hlsl or ("[WaveSize(32)]" in hlsl) != (width == 32): + raise ValueError("fixture must take a ballot, in 32-lane waves only if its masks have one word") + stores = (f" output[{width}u + gtid.x] = v10 | (v11 << 8u) | (WaveGetLaneCount() << 16u);\n" + f" output[{2 * width}u + gtid.x] = v12;\n") + hlsl = hlsl.replace(start, load) + end = hlsl.rstrip().rfind("}") + return "RWBuffer output : register(u0);\n" + hlsl[:end] + stores + "}\n" + + +def inputs(width): + yield from cases(width) + yield "below", (1 << width) - 1, list(range(width)) + yield "one_above", (1 << width) - 1, [LIMIT + 1 if lane == 17 else lane for lane in range(width)] + yield "some_above", (1 << width) - 1, [LIMIT - 20 + lane for lane in range(width)] + yield "inactive_above", 0x0000ffff, [lane if lane < 16 else LIMIT + lane for lane in range(width)] + + +def seed_for(mask, values): + width = len(values) + seed = [0x76540000 + i for i in range(384)] + seed[96:96 + width] = [v | (((mask >> lane) & 1) << 31) for lane, v in enumerate(values)] + return seed + + +def difference(name, seed, mask, values, data): + """The first word that is wrong, if any.""" + if len(data) != 4 * len(seed): + return "no readback" + actual, expected, width = struct.unpack("<384I", data), list(seed), len(values) + host = actual[96 + width] >> 16 + if host not in (8, 16, 32, 64) or host > width or width == 32 and host != 32: + return f"host wave of {host}" + rows = model(name, [bool((mask >> lane) & 1) for lane in range(width)], values, host) + for lane, (count, rank, last) in enumerate(rows): + expected[96 + width + lane] = count | rank << 8 | host << 16 + expected[96 + 2 * width + lane] = last + return next((dict(word=i, got=a, wanted=b) for i, (a, b) in enumerate(zip(actual, expected)) if a != b), None) + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + for name in ("emitter", "llvm-mc", "dxc", "dxv", "provider", "proton", "prefix", "compiler-dir", "work", + "output"): + parser.add_argument("--" + name, type=Path, required=True) + parser.add_argument("--adapter", required=True) + args = parser.parse_args(argv) + work = args.work.resolve() + work.mkdir(parents=True, exist_ok=True) + with TemporaryDirectory(dir=work) as tmp: + trial = Path(tmp) + trials, shaders = {}, {} + for width, bodies in ((32, WAVE32), (64, WAVE64)): + for name, body in bodies.items(): + words = words_of(program(body, width), args.llvm_mc, *WAVE_OPTIONS[width]) + emitted = subprocess.check_output( + [args.emitter.resolve(), str(width), *(f"{word:08x}" for word in words)], text=True, timeout=30) + source = trial / f"{name}{width}.hlsl" + source.write_text(instrument(emitted, width)) + blob = trial / f"{name}{width}.cso" + subprocess.run([args.dxc, "-T", "cs_6_6", "-E", "main", "-Fo", blob, source], check=True, timeout=30, + capture_output=True) + subprocess.run([args.dxv, blob], check=True, timeout=30, capture_output=True) + shaders[f"{name}{width}"] = dict(hlsl_sha256=digest(source), dxil_sha256=digest(blob)) + for case, mask, values in inputs(width): + trial_name = f"{name}{width}_{case}" + trials[trial_name] = name, seed_for(mask, values), mask, values + (trial / f"{trial_name}.seed").write_bytes(struct.pack("<384I", *trials[trial_name][1])) + (trial / f"{trial_name}.cso").hardlink_to(blob) + (trial / "cases.txt").write_text("".join(f"{name} 0 uint 1\n" for name in trials)) + exe, status, fields = run_gpu_guest( + ROOT / "tools/reference/independent-shaders/compute.cpp", "ballots.exe", trial, work, + args.proton.resolve(), args.prefix, args.provider, args.compiler_dir) + wrong = {} + for trial_name, (name, seed, mask, values) in trials.items(): + path = trial / f"{trial_name}.bin" + found = difference(name, seed, mask, values, path.read_bytes() if path.is_file() else b"") + if found: + wrong[trial_name] = found + passed = status == 0 and fields.get("adapter") == args.adapter and not wrong + report = dict(passed=passed, scope="Synthetic programs reading lane masks as numbers", + adapter=fields.get("adapter"), guest_exit=status, cases=len(trials), + compared_words=len(trials) * 384, wrong=wrong, shaders=shaders, + emitter_sha256=digest(args.emitter), guest_sha256=digest(exe)) + if fields.get("error"): + report["error"] = fields["error"] + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n") + for name, detail in wrong.items(): + print(f"WRONG {name}: {detail}") + if not passed: + print(f"FAIL: {len(wrong)} of {len(trials)} cases, guest exit {status}") + return 1 + print(f"PASS: {len(trials)} cases, {len(trials) * 384} words, adapter {fields['adapter']}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/check_packed_integer_gpu.py b/tools/check_packed_integer_gpu.py index 41b11c07..53460942 100644 --- a/tools/check_packed_integer_gpu.py +++ b/tools/check_packed_integer_gpu.py @@ -30,8 +30,8 @@ def digest(path): return hashlib.sha256(path.read_bytes()).hexdigest() -def assemble(lines,llvm): - result=subprocess.run([str(llvm),"-triple=amdgcn-amd-amdhsa","-mcpu=gfx1030","-show-encoding"], +def assemble(lines,llvm,*options): + result=subprocess.run([str(llvm),"-triple=amdgcn-amd-amdhsa","-mcpu=gfx1030","-show-encoding",*options], input="\n".join(lines)+"\n",text=True,capture_output=True,check=True,timeout=20) encoded=re.findall(r"encoding: \[([^\]]+)\]",result.stdout) if len(encoded)!=len(lines): diff --git a/tools/check_translator_gpu.py b/tools/check_translator_gpu.py index 8785d1ef..36f00a1d 100644 --- a/tools/check_translator_gpu.py +++ b/tools/check_translator_gpu.py @@ -53,6 +53,7 @@ def assembled(tool, *extra): extra=("--width", str(width), "--variant", variant)) for width in (32, 64) for variant in ("original", "chain", "chain-zero")}, "lockstep": Check("check_lockstep_gpu", emitter="lockstep", llvm=True, dxc=True), + "mask-ballots": Check("check_mask_ballots_gpu", emitter="mask_ballots", llvm=True, dxc=True), "dpp8-exchange": Check("check_dpp8_exchange", emitter="lone_lane_probe", dxc=True), "pixel-heap-offsets": Check("check_pixel_heap_offsets", emitter="pixel_heap_offsets", dxc=True), "pixel-link": Check("check_portable_pixel_link", emitter="xshader", dxc=True), diff --git a/tools/shader-compiler/examples/mask_ballots.rs b/tools/shader-compiler/examples/mask_ballots.rs new file mode 100644 index 00000000..fddaf678 --- /dev/null +++ b/tools/shader-compiler/examples/mask_ballots.rs @@ -0,0 +1,30 @@ +//! Translate a synthetic compute program, supplied as native words, that reads +//! lane masks as numbers. Its thread group is one guest wave. +use tuxbox_xshader::{ShaderExtract, Stage, hlsl}; + +mod fixture { + include!(concat!(env!("CARGO_MANIFEST_DIR"), "/examples/support/wave_guard_fixture.rs")); +} + +fn main() { + let mut args = std::env::args().skip(1); + let width: u32 = args.next().expect("wave width").parse().expect("integer"); + assert!(matches!(width, 32 | 64)); + let words: Vec = args.map(|s| u32::from_str_radix(&s, 16).expect("hex native word")).collect(); + assert!(!words.is_empty() && words.len() <= 512 && words.last() == Some(&0xbf810000)); + let (mut shader, _, _): (ShaderExtract, _, _) = fixture::shader(width); + shader.isa = words.iter().flat_map(|word| word.to_le_bytes()).collect(); + shader.isa_data = shader.isa.clone(); + assert!(matches!(shader.stage, Stage::Compute)); + match hlsl::translate(&shader) { + Ok(result) => { + // A mask of two words is read on any host wave. + assert_eq!(result.required_wave_size, (width == 32).then_some(32)); + print!("{}", result.hlsl); + } + Err(reason) => { + eprintln!("{reason}"); + std::process::exit(65); + } + } +} diff --git a/tools/shader-compiler/src/hlsl.rs b/tools/shader-compiler/src/hlsl.rs index 2b320999..82c5125f 100644 --- a/tools/shader-compiler/src/hlsl.rs +++ b/tools/shader-compiler/src/hlsl.rs @@ -101,6 +101,7 @@ mod fspx_wave; mod singleton_wave; mod wave_sum; mod lockstep; +mod mask_ballots; mod wave_loops; mod raw_index; mod reflection_compact; @@ -328,6 +329,8 @@ struct Emitter<'a> { compute_swizzle: bool, vote_defs: BTreeSet, vote_uses: BTreeMap, + /// Lane masks read as numbers. + mask_ballots: Option, exec_snapshots: exec_snapshot::Snapshots, reflected_lds_words: Option, hoisted_swizzle: Option, diff --git a/tools/shader-compiler/src/hlsl/driver/pipeline.rs b/tools/shader-compiler/src/hlsl/driver/pipeline.rs index a3dd57df..63266704 100644 --- a/tools/shader-compiler/src/hlsl/driver/pipeline.rs +++ b/tools/shader-compiler/src/hlsl/driver/pipeline.rs @@ -222,6 +222,10 @@ pub(in crate::hlsl) fn translate_outputs_once(ex: &ShaderExtract, feeds_ps: Opti em.vote_uses.insert(count, def); em.regs.insert(format!("tb_votes{def}")); } + if ex.stage == Stage::Compute && !lone_lane::on() && !wave_cull && !page_waves && !indexed_lane + && em.fspx_wave.is_none() && !hair_multisample { + em.mask_ballots = mask_ballots::find(&em.insns); + } // Lane-spill slots beyond the tracked range are function-scope temporaries. for ins in &em.insns { for o in ins.dst.iter().chain(ins.src.iter()) { @@ -356,6 +360,19 @@ pub(in crate::hlsl) fn translate_outputs_once(ex: &ShaderExtract, feeds_ps: Opti && !hair_visibility_indirect && !hair_visibility_single && hair_compact.is_none() && !subsurface_setup && !material_classify && !classify_tiles && !reflection && !group_extrema && (straight_exchange || wave_sum::portable_single_wave(&em.insns)); + // One mask word holds 32 lanes. Two hold any wave the host can have, so a wave64 + // program still runs on adapters without one. + let required_wave_size = match em.mask_ballots.as_ref().map(|b| b.width) { + Some(32) if required_wave_size == Some(64) => { + em.mask_ballots = None; + required_wave_size + } + Some(32) => Some(32), + _ => required_wave_size, + }; + if em.portable_wave64 { em.mask_ballots = None; } + em.required_wave_size = required_wave_size; + em.regs.extend(em.mask_ballots.iter().flat_map(mask_ballots::Ballots::names).collect::>()); if straight_exchange && !em.portable_wave64 { return Err("straight DPP8 exchange conflicts with a specialized lowering".into()); } @@ -500,7 +517,7 @@ pub(in crate::hlsl) fn translate_outputs_once(ex: &ShaderExtract, feeds_ps: Opti "cs_6_6" } else if em.uses_heap_sampler || em.resource_heap_base.is_some() || em.pixel_heap { "ps_6_6" - } else if probe_trace { + } else if probe_trace || em.mask_ballots.is_some() { "cs_6_5" } else if is_ps && !em.uav.is_empty() { "ps_5_1" diff --git a/tools/shader-compiler/src/hlsl/emitter/instruction.rs b/tools/shader-compiler/src/hlsl/emitter/instruction.rs index fa0c917a..5d09e6b3 100644 --- a/tools/shader-compiler/src/hlsl/emitter/instruction.rs +++ b/tools/shader-compiler/src/hlsl/emitter/instruction.rs @@ -4,6 +4,9 @@ use super::*; impl<'a> Emitter<'a> { pub(in crate::hlsl) fn emit_insn(&mut self, idx: usize, ins: &Insn, is_ps: bool, br: Option) -> Result<(), String> { self.emit_insn_body(idx, ins, is_ps, br)?; + for line in mask_ballots::capture(self, idx) { + self.line(&line); + } if let Some(vote) = self.lockstep.as_ref().and_then(|votes| votes.get(&idx)).cloned() { let mask = r(&vote.mask)?; let not = if vote.none { "!" } else { "" }; diff --git a/tools/shader-compiler/src/hlsl/emitter/scalar.rs b/tools/shader-compiler/src/hlsl/emitter/scalar.rs index dbf8a874..49e3efd9 100644 --- a/tools/shader-compiler/src/hlsl/emitter/scalar.rs +++ b/tools/shader-compiler/src/hlsl/emitter/scalar.rs @@ -323,12 +323,14 @@ impl<'a> Emitter<'a> { // Population count of a 64-bit value — typically the number of active // lanes (wave-level allocation). One invocation = one lane, so a lane // mask counts as 0 or 1. - let ah = r(&hi(&s[0]))?; + let a = mask_ballots::word(self, idx, &s[0]).unwrap_or(a); + let ah = mask_ballots::word(self, idx, &hi(&s[0])).map_or_else(|| r(&hi(&s[0])), Ok)?; self.ws(&d, &format!("(countbits({a}) + countbits({ah}))"))?; self.line(&format!("scc = ({} != 0u) ? 1u : 0u;", name(&d)?)); Ok(()) } "s_bcnt1_i32_b32" => { + let a = mask_ballots::word(self, idx, &s[0]).unwrap_or(a); self.ws(&d, &format!("countbits({a})"))?; self.line(&format!("scc = ({} != 0u) ? 1u : 0u;", name(&d)?)); Ok(()) @@ -345,12 +347,16 @@ impl<'a> Emitter<'a> { let ah = r(&hi(&s[0]))?; self.ws(&d, &ff0_b64_expr(&a, &ah)) } - "s_ff1_i32_b32" => self.ws(&d, &format!("firstbitlow({a})")), + "s_ff1_i32_b32" => { + let a = mask_ballots::word(self, idx, &s[0]).unwrap_or(a); + self.ws(&d, &format!("firstbitlow({a})")) + } // s_ff1_i32_b64 is firstbitlow over the 64-bit value: the low word // decides when it is nonzero, otherwise the high word. "s_ff1_i32_b64" => { self.touch(&hi(&s[0])); - let ah = r(&hi(&s[0]))?; + let a = mask_ballots::word(self, idx, &s[0]).unwrap_or(a); + let ah = mask_ballots::word(self, idx, &hi(&s[0])).map_or_else(|| r(&hi(&s[0])), Ok)?; self.ws(&d, &ff1_b64_expr(&a, &ah)) } "s_sext_i32_i8" => self.ws(&d, &format!("asuint(asint({a} << 24) >> 24)")), diff --git a/tools/shader-compiler/src/hlsl/emitter/setup.rs b/tools/shader-compiler/src/hlsl/emitter/setup.rs index a3a45c27..a08d1b0c 100644 --- a/tools/shader-compiler/src/hlsl/emitter/setup.rs +++ b/tools/shader-compiler/src/hlsl/emitter/setup.rs @@ -112,6 +112,7 @@ impl<'a> Emitter<'a> { compute_swizzle: false, vote_defs: BTreeSet::new(), vote_uses: BTreeMap::new(), + mask_ballots: None, exec_snapshots: Default::default(), reflected_lds_words: None, hoisted_swizzle: None, diff --git a/tools/shader-compiler/src/hlsl/emitter/vector.rs b/tools/shader-compiler/src/hlsl/emitter/vector.rs index 0b32b2ad..b10ccbb8 100644 --- a/tools/shader-compiler/src/hlsl/emitter/vector.rs +++ b/tools/shader-compiler/src/hlsl/emitter/vector.rs @@ -622,7 +622,7 @@ impl<'a> Emitter<'a> { } else if matches!(s[0], Opnd::ExecLo | Opnd::ExecHi) && !self.resolve_wave32 { // Each invocation holds only its own EXEC bit; the guest reads the wave mask. format!("WaveActiveBallot((exec_lo & 1u) != 0u).{}", if s[0] == Opnd::ExecLo { "x" } else { "y" }) - } else { a }; + } else { mask_ballots::word(self, self.cur_idx, &s[0]).unwrap_or(a) }; self.line(&format!("uint t{t} = countbits({a} & {});", low_mask(lane))); self.line("#else"); self.line(&format!("uint t{t} = 0u;")); diff --git a/tools/shader-compiler/src/hlsl/mask_ballots.rs b/tools/shader-compiler/src/hlsl/mask_ballots.rs new file mode 100644 index 00000000..6a76c286 --- /dev/null +++ b/tools/shader-compiler/src/hlsl/mask_ballots.rs @@ -0,0 +1,201 @@ +//! Lane masks read as numbers. +//! +//! One invocation holds only its own bit of a lane mask. Counting a mask's lanes, finding +//! the first one or counting those before this lane reads all of them, often after EXEC has +//! been narrowed to one elected lane. Take the ballot where the mask is computed, while +//! every lane that can be in it is there, and let each lane keep it. +use super::{Emitter, Enc, Insn, Opnd}; +use std::collections::{BTreeMap, BTreeSet}; + +const VCC: u8 = 106; + +/// The scalar register an operand names. VCC follows the ordinary registers. +pub(super) fn register(o: &Opnd) -> Option { + match *o { + Opnd::Sgpr(n) => Some(n), + Opnd::VccLo => Some(VCC), + Opnd::VccHi => Some(VCC + 1), + _ => None, + } +} + +pub(super) fn name(register: u8) -> String { format!("tb_bal{register}") } + +/// First scalar register written and how many. +fn written(ins: &Insn, wide: bool) -> Option<(u8, u8)> { + let m = ins.mnemonic.as_str(); + let d = ins.dst.first()?; + if m.starts_with("s_load_") || m.starts_with("s_buffer_load_") { + let width = ["x16", "x8", "x4", "x2"].iter().zip([16, 8, 4, 2]).find(|(s, _)| m.ends_with(*s)).map_or(1, |(_, w)| w); + return Some((register(d)?, width)); + } + if m.starts_with("s_") { + if m.starts_with("s_cmp") || m.starts_with("s_bitcmp") { return None; } + let single = ["s_bcnt", "s_ff", "s_flbit"].iter().any(|p| m.starts_with(p)); + return Some((register(d)?, if m.ends_with("64") && !single { 2 } else { 1 })); + } + if m == "v_readlane_b32" { + return match *d { Opnd::Vgpr(n) | Opnd::Sgpr(n) => Some((n, 1)), _ => register(d).map(|n| (n, 1)) }; + } + if m.starts_with("v_cmpx") { return None; } + if m.starts_with("v_") && m != "v_readfirstlane_b32" { + let mask = ins.dst.iter().find_map(register)?; + return Some((mask, if wide { 2 } else { 1 })); + } + Some((register(d)?, if m.starts_with("tb_") && m.ends_with("64") { 2 } else { 1 })) +} + +enum Kind { Mask, Of(Vec), AllLanes, Number } + +/// What an instruction's scalar result is made of. +fn kind(ins: &Insn) -> Kind { + let m = ins.mnemonic.as_str(); + if m.starts_with("v_cmp") || m.contains("_co_") || m.starts_with("v_div_scale") { return Kind::Mask; } + if m.contains("saveexec") { return Kind::Mask; } + let combines = ["s_mov_b", "s_and_b", "s_or_b", "s_xor_b", "s_andn2_b", "s_orn2_b", "s_nand_b", "s_nor_b", + "s_xnor_b", "s_not_b", "s_wqm_b", "s_cselect_b"]; + if !combines.iter().any(|p| m.strip_prefix(p).is_some_and(|rest| matches!(rest, "32" | "64"))) { return Kind::Number; } + let (mut exec, mut from) = (false, Vec::new()); + for o in &ins.src { + match o { + Opnd::ExecLo => exec = true, + Opnd::ConstInt(0 | -1) => (), + _ => match register(o) { Some(n) => from.push(n), None => return Kind::Number }, + } + } + match (exec, from.is_empty()) { + (_, false) => Kind::Of(from), + (true, true) => Kind::Mask, + (false, true) if ins.src.contains(&Opnd::ConstInt(-1)) => Kind::AllLanes, + (false, true) => Kind::Of(Vec::new()), + } +} + +fn predecessors(insns: &[Insn]) -> Vec> { + let at: BTreeMap = insns.iter().enumerate().map(|(i, x)| (x.offset as i64, i)).collect(); + let mut from = vec![Vec::new(); insns.len()]; + for (i, ins) in insns.iter().enumerate() { + let sopp = ins.enc == Enc::Sopp; + if i + 1 < insns.len() && !(sopp && matches!(ins.op, 1 | 2)) { from[i + 1].push(i); } + if sopp && Emitter::branch_cond(ins.op).is_some() { + if let Some(&t) = at.get(&(ins.offset as i64 + 4 + 4 * ins.aux.imm)) { from[t].push(i); } + } + } + from +} + +struct Reach<'a> { insns: &'a [Insn], from: Vec>, wide: bool } + +impl Reach<'_> { + /// The writes of `register` that reach `at`. None when its entry value does. + fn defs(&self, at: usize, register: u8) -> Option> { + let (mut found, mut seen, mut todo) = (BTreeSet::new(), BTreeSet::new(), vec![at]); + while let Some(i) = todo.pop() { + if i == 0 { return None; } + // Padding after an unconditional branch is never entered. + for &p in &self.from[i] { + if !seen.insert(p) { continue; } + match written(&self.insns[p], self.wide) { + Some((first, count)) if (first..first.saturating_add(count)).contains(®ister) => { found.insert(p); } + _ => todo.push(p), + } + } + } + Some(found) + } + + /// The definitions of a mask read at `at`, if every value that reaches it is one. + fn mask(&self, at: usize, register: u8) -> Option> { + let direct = self.defs(at, register)?; + let (mut seen, mut todo, mut rooted) = (BTreeSet::new(), direct.iter().copied().collect::>(), false); + while let Some(d) = todo.pop() { + if !seen.insert(d) { continue; } + match kind(&self.insns[d]) { + Kind::Number => return None, + // Counted itself, it holds lanes that are not running. + Kind::AllLanes if direct.contains(&d) => return None, + Kind::AllLanes => (), + Kind::Mask => rooted = true, + Kind::Of(regs) => for n in regs { todo.extend(self.defs(d, n)?); }, + } + } + rooted.then_some(direct) + } +} + +fn counted(ins: &Insn) -> bool { + matches!(ins.mnemonic.as_str(), "s_bcnt1_i32_b32" | "s_bcnt1_i32_b64" | "s_ff1_i32_b32" | "s_ff1_i32_b64" + | "v_mbcnt_lo_u32_b32" | "v_mbcnt_hi_u32_b32") +} + +pub(super) struct Ballots { + /// Registers to take a ballot of after an instruction. + pub defs: BTreeMap>, + /// Instructions that read ballots instead of their mask operand. + pub uses: BTreeSet, + pub width: u32, +} + +impl Ballots { + /// The variables the ballots are kept in. + pub(super) fn names(&self) -> Vec { + let words = u8::from(self.width == 64); + self.defs.values().flatten().flat_map(|&n| [n, n + words]).map(name).collect() + } +} + +/// Masks of a compute program that are read as numbers. +pub(super) fn find(insns: &[Insn]) -> Option { + if insns.iter().any(|i| matches!(i.mnemonic.as_str(), "s_setpc_b64" | "s_swappc_b64" | "s_call_b64") + || i.mnemonic.starts_with("s_movrel")) { return None; } + let masks = |bits: &str| insns.iter().any(|i| i.mnemonic.starts_with("s_") && i.mnemonic.ends_with(bits) + && (i.mnemonic.contains("saveexec") || i.src.contains(&Opnd::ExecLo) || i.dst.contains(&Opnd::ExecLo))); + let wide = match (masks("_b32"), masks("_b64")) { (true, false) => false, (false, true) => true, _ => return None }; + let reach = Reach { insns, from: predecessors(insns), wide }; + let mut found = Ballots { defs: BTreeMap::new(), uses: BTreeSet::new(), width: if wide { 64 } else { 32 } }; + for (i, ins) in insns.iter().enumerate().filter(|(_, i)| counted(i)) { + let Some(source) = ins.src.first() else { continue }; + // The emitter already takes the ballot of EXEC for the other two. + if matches!(source, Opnd::ExecLo | Opnd::ExecHi) { + if ins.mnemonic.starts_with("s_bcnt1") || ins.mnemonic == "s_ff1_i32_b32" { found.uses.insert(i); } + continue; + } + let Some(register) = register(source) else { continue }; + let Some(defs) = reach.mask(i, register) else { + continue + }; + for d in defs { + let (first, count) = written(&insns[d], wide).expect("a definition writes"); + found.defs.entry(d).or_default().insert(if count == 2 { first } else { register }); + } + found.uses.insert(i); + } + (!found.uses.is_empty()).then_some(found) +} + +/// The text of a mask word read by instruction `at`. +pub(super) fn word(em: &Emitter<'_>, at: usize, o: &Opnd) -> Option { + let ballots = em.mask_ballots.as_ref().filter(|b| b.uses.contains(&at))?; + match o { + Opnd::ExecLo => Some("WaveActiveBallot((exec_lo & 1u) != 0u).x".into()), + Opnd::ExecHi => Some(if ballots.width == 64 { "WaveActiveBallot((exec_lo & 1u) != 0u).y" } else { "0u" }.into()), + _ => register(o).map(name), + } +} + +/// Statements that take the ballots due after instruction `at`. +pub(super) fn capture(em: &Emitter<'_>, at: usize) -> Vec { + let Some(ballots) = &em.mask_ballots else { return Vec::new() }; + ballots.defs.get(&at).into_iter().flatten().map(|&n| { + let mask = if n == VCC { "vcc_lo".to_owned() } else { format!("s{n}") }; + if ballots.width == 64 { + format!("{{ uint4 tb_b = WaveActiveBallot(({mask} & 1u) != 0u); {} = tb_b.x; {} = tb_b.y; }}", name(n), name(n + 1)) + } else { + format!("{} = WaveActiveBallot(({mask} & 1u) != 0u).x;", name(n)) + } + }).collect() +} + +#[cfg(test)] +#[path = "../tests/hlsl/mask_ballots.rs"] +mod tests; diff --git a/tools/shader-compiler/src/tests/hlsl/mask_ballots.rs b/tools/shader-compiler/src/tests/hlsl/mask_ballots.rs new file mode 100644 index 00000000..24e63047 --- /dev/null +++ b/tools/shader-compiler/src/tests/hlsl/mask_ballots.rs @@ -0,0 +1,106 @@ +use super::*; +use crate::{hlsl::translate, ShaderExtract, Stage}; + +mod fixture { + include!("../../../examples/support/wave_guard_fixture.rs"); +} + +fn insn(mnemonic: &str, enc: Enc, dst: Vec, src: Vec) -> Insn { + Insn { offset: 0, dwords: 1, enc, op: 0, raw: vec![0], mnemonic: mnemonic.into(), dst, src, aux: Default::default() } +} + +fn program(mut ops: Vec) -> Vec { + // Something that tells the wave's width. + ops.insert(0, scalar("s_mov_b32", 100, vec![Opnd::ExecLo])); + ops.push(Insn { op: 1, ..insn("s_endpgm", Enc::Sopp, vec![], vec![]) }); + for (i, op) in ops.iter_mut().enumerate() { op.offset = i * 4; } + ops +} + +fn scalar(mnemonic: &str, dst: u8, src: Vec) -> Insn { + insn(mnemonic, if src.len() == 1 { Enc::Sop1 } else { Enc::Sop2 }, vec![Opnd::Sgpr(dst)], src) +} + +fn compare() -> Insn { + insn("v_cmp_gt_u32", Enc::Vopc, vec![Opnd::VccLo], vec![Opnd::Vgpr(0), Opnd::Vgpr(1)]) +} + +fn count(source: Opnd) -> Insn { scalar("s_bcnt1_i32_b32", 20, vec![source]) } + +fn branch(op: u32, over: i64) -> Insn { + let mut branch = insn("s_cbranch", Enc::Sopp, vec![], vec![]); + (branch.op, branch.aux.imm) = (op, over); + branch +} + +/// Index of the definitions a program's counts take their ballots from. +fn ballots(ops: Vec) -> Option> { + let found = find(&program(ops))?; + Some(found.defs.iter().flat_map(|(&at, regs)| regs.iter().map(move |&r| (at, r))).collect()) +} + +#[test] +fn a_mask_is_captured_where_it_is_computed() { + assert_eq!(ballots(vec![compare(), count(Opnd::VccLo)]), Some(vec![(1, 106)])); + // Through copies and EXEC, past the point where EXEC is narrowed. + let saved = ballots(vec![ + compare(), + scalar("s_and_saveexec_b32", 10, vec![Opnd::VccLo]), + scalar("s_mov_b32", 11, vec![Opnd::ExecLo]), + insn("v_cmpx_eq_u32", Enc::Vopc, vec![Opnd::ExecLo], vec![Opnd::Sgpr(9), Opnd::Vgpr(1)]), + count(Opnd::Sgpr(11)), + ]); + assert_eq!(saved, Some(vec![(3, 11)])); + // Both of the masks that can reach the count, one of them empty. + let gathered = ballots(vec![ + scalar("s_mov_b32", 11, vec![Opnd::ConstInt(0)]), + compare(), + scalar("s_or_b32", 11, vec![Opnd::Sgpr(11), Opnd::VccLo]), + count(Opnd::Sgpr(11)), + branch(5, -4), + ]); + assert_eq!(gathered, Some(vec![(3, 11)])); +} + +#[test] +fn numbers_are_not_masks() { + for ops in [ + vec![scalar("s_mov_b32", 11, vec![Opnd::Sgpr(0)]), count(Opnd::Sgpr(11))], + vec![scalar("s_mov_b32", 11, vec![Opnd::Literal(0xff)]), count(Opnd::Sgpr(11))], + vec![scalar("s_add_u32", 11, vec![Opnd::Sgpr(0), Opnd::Sgpr(1)]), count(Opnd::Sgpr(11))], + // Every lane, running or not. + vec![scalar("s_mov_b32", 11, vec![Opnd::ConstInt(-1)]), count(Opnd::Sgpr(11))], + // Part number. + vec![compare(), scalar("s_and_b32", 11, vec![Opnd::VccLo, Opnd::Sgpr(0)]), count(Opnd::Sgpr(11))], + // A mask on one path only. + vec![ + scalar("s_mov_b32", 11, vec![Opnd::Sgpr(0)]), + branch(4, 2), + compare(), + scalar("s_mov_b32", 11, vec![Opnd::VccLo]), + count(Opnd::Sgpr(11)), + ], + ] { + assert_eq!(ballots(ops), None); + } +} + +#[test] +fn counts_read_the_ballot() { + // v_cmp_lt_u32 vcc, 1000, v0; s_bcnt1 s20, vcc; v_mov v10, s20 + let words = |bcnt: u32| vec![0x7d82_00ff, 1000, bcnt, 0x7e14_0214]; + for (width, bcnt, save) in [(32, 0xbe94_0f6a, 0xbe8c_037eu32), (64, 0xbe94_106a, 0xbe8c_047e)] { + let (mut ex, _, _): (ShaderExtract, _, _) = fixture::shader(width); + assert!(matches!(ex.stage, Stage::Compute)); + let words = [vec![save], words(bcnt), vec![0xbf81_0000]].concat(); + ex.isa = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + ex.isa_data = ex.isa.clone(); + let shader = translate(&ex).unwrap(); + assert!(shader.hlsl.contains("WaveActiveBallot((vcc_lo & 1u) != 0u)"), "{}", shader.hlsl); + let wanted = if width == 32 { "countbits(tb_bal106)" } else { "(countbits(tb_bal106) + countbits(tb_bal107))" }; + assert!(shader.hlsl.contains(wanted), "{}", shader.hlsl); + // Two mask words hold a wave of any size, one holds 32 lanes. + assert_eq!(shader.required_wave_size, (width == 32).then_some(32)); + assert_eq!(shader.profile, "cs_6_5"); + } +} From 12706549bcac7a894815992c5fcb5f38d51e7838 Mon Sep 17 00:00:00 2001 From: Jerkin42 <66524771+Jerkin42@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:17:02 +0000 Subject: [PATCH 2/2] xshader: take mask ballots only where they hold the guest's wave Review fixes for reading lane masks as numbers: - Ray tracing resolve programs keep whole masks already. A ballot of one lane's bit broke their counts in about 1,000 programs. - Both words of a wave64 mask must come from the same definitions, and a 64-bit count must start at the first word. - v_readfirstlane, v_readlane and the scalar carry of VOP3B instructions count as writes, and a VOP2 carry writes VCC. - Masks are moved and combined only at the wave's width, and a program that uses both widths of EXEC, or the second word in a 32-lane wave, gets no ballots. S_WQM is not followed. - A ballot is taken only where the lanes that can be in the mask run together: not where a branch on another mask skips or repeats, and not after an early exit. A branch on EXEC keeps the running lanes together. - The width is applied before the complete-wave check. A group that is not made of whole waves keeps the old translation, and a wave64 program needs wave64 instead of reading half a wave on a 32-lane host. Over the 24,463 ProjectScarlett programs I have, 76 change against main and none is newly refused. Co-Authored-By: Claude Opus 5.5 --- docs/SHADERS.md | 2 +- tools/check_mask_ballots_gpu.py | 13 +- .../shader-compiler/examples/mask_ballots.rs | 4 +- .../src/hlsl/driver/pipeline.rs | 26 +-- .../shader-compiler/src/hlsl/mask_ballots.rs | 181 ++++++++++++++---- .../src/tests/hlsl/exec_group_wave32.rs | 11 ++ .../src/tests/hlsl/mask_ballots.rs | 136 ++++++++++++- 7 files changed, 308 insertions(+), 65 deletions(-) diff --git a/docs/SHADERS.md b/docs/SHADERS.md index 7ceae9e0..e67d8e3c 100644 --- a/docs/SHADERS.md +++ b/docs/SHADERS.md @@ -148,7 +148,7 @@ A [GPU check](../tools/check_lockstep_gpu.py) compares both paths with a model o ### Lane masks read as numbers -Each thread of a translated program holds only its own bit of a lane mask. Counting a mask's lanes, finding its first one or counting those before a lane reads the other bits too, and gave 0 or 1 for a whole wave. Compute programs now take the wave's ballot where such a mask is computed and read that ([analysis](../tools/shader-compiler/src/hlsl/mask_ballots.rs)). It has to be a lane mask on every path to the read. Programs with one-word masks need 32-lane waves. Two words hold a wave of any size, so wave64 programs still run on adapters that only have wave32. +Each thread of a translated program holds only its own bit of a lane mask. Counting a mask's lanes, finding its first one or counting those before a lane reads the other bits too, and gave 0 or 1 for a whole wave. Compute programs now take the wave's ballot where such a mask is computed and read that ([analysis](../tools/shader-compiler/src/hlsl/mask_ballots.rs)). Both words of a wave64 mask have to come from the same lane masks on every path to the read, and the ballot is only taken where every lane that can be in the mask runs together: not in code that a branch on another mask skips or repeats, nor after some lanes have left. The program then runs in complete waves of the guest's width, so a wave64 one needs an adapter with wave64. Ray tracing resolve programs keep whole masks already and are left alone. Otherwise the old translation stays. A [GPU check](../tools/check_mask_ballots_gpu.py) compares both widths with a model of the console on an RX 9060 XT: 300 cases match, and 200 of them don't without the ballots. In ProjectScarlett this affects the passes that hand out shadow mask tiles, where most lit tiles shared a few slots and shadows showed as 16-pixel blocks. diff --git a/tools/check_mask_ballots_gpu.py b/tools/check_mask_ballots_gpu.py index 52ca63c8..87f82d68 100644 --- a/tools/check_mask_ballots_gpu.py +++ b/tools/check_mask_ballots_gpu.py @@ -3,10 +3,9 @@ Each synthetic program counts a mask's lanes, finds its first one or counts those before each lane, some of them after EXEC was narrowed to one elected -lane. The reference models the console. A wave64 program is modelled on the -host's own wave, which can be 32 lanes: every part of the wave is a wave of its -own there. Only the translator's input and output are instrumented. No game -data is needed. +lane. The reference models the console. Each program runs in waves of its own +width. Only the translator's input and output are instrumented. No game data is +needed. """ import argparse import json @@ -104,8 +103,8 @@ def instrument(hlsl, width): start = " v0 = gtid.x; v1 = gtid.y; v2 = gtid.z;" load = (" uint input = output[gtid.x];\n exec_lo = input >> 31;\n" " v0 = input & 0x7fffffffu; v1 = gtid.y; v2 = gtid.z;") - if hlsl.count(start) != 1 or "WaveActiveBallot" not in hlsl or ("[WaveSize(32)]" in hlsl) != (width == 32): - raise ValueError("fixture must take a ballot, in 32-lane waves only if its masks have one word") + if hlsl.count(start) != 1 or "WaveActiveBallot" not in hlsl or f"[WaveSize({width})]" not in hlsl: + raise ValueError("fixture must take a ballot in waves of its own width") stores = (f" output[{width}u + gtid.x] = v10 | (v11 << 8u) | (WaveGetLaneCount() << 16u);\n" f" output[{2 * width}u + gtid.x] = v12;\n") hlsl = hlsl.replace(start, load) @@ -134,7 +133,7 @@ def difference(name, seed, mask, values, data): return "no readback" actual, expected, width = struct.unpack("<384I", data), list(seed), len(values) host = actual[96 + width] >> 16 - if host not in (8, 16, 32, 64) or host > width or width == 32 and host != 32: + if host != width: return f"host wave of {host}" rows = model(name, [bool((mask >> lane) & 1) for lane in range(width)], values, host) for lane, (count, rank, last) in enumerate(rows): diff --git a/tools/shader-compiler/examples/mask_ballots.rs b/tools/shader-compiler/examples/mask_ballots.rs index fddaf678..32fc6ccf 100644 --- a/tools/shader-compiler/examples/mask_ballots.rs +++ b/tools/shader-compiler/examples/mask_ballots.rs @@ -18,8 +18,8 @@ fn main() { assert!(matches!(shader.stage, Stage::Compute)); match hlsl::translate(&shader) { Ok(result) => { - // A mask of two words is read on any host wave. - assert_eq!(result.required_wave_size, (width == 32).then_some(32)); + // A ballot holds the lanes of one guest wave. + assert_eq!(result.required_wave_size, Some(width)); print!("{}", result.hlsl); } Err(reason) => { diff --git a/tools/shader-compiler/src/hlsl/driver/pipeline.rs b/tools/shader-compiler/src/hlsl/driver/pipeline.rs index 63266704..0db338b4 100644 --- a/tools/shader-compiler/src/hlsl/driver/pipeline.rs +++ b/tools/shader-compiler/src/hlsl/driver/pipeline.rs @@ -222,8 +222,9 @@ pub(in crate::hlsl) fn translate_outputs_once(ex: &ShaderExtract, feeds_ps: Opti em.vote_uses.insert(count, def); em.regs.insert(format!("tb_votes{def}")); } + // Ray tracing resolve keeps whole masks already. if ex.stage == Stage::Compute && !lone_lane::on() && !wave_cull && !page_waves && !indexed_lane - && em.fspx_wave.is_none() && !hair_multisample { + && em.fspx_wave.is_none() && !hair_multisample && !resolve_wave32 { em.mask_ballots = mask_ballots::find(&em.insns); } // Lane-spill slots beyond the tracked range are function-scope temporaries. @@ -297,6 +298,16 @@ pub(in crate::hlsl) fn translate_outputs_once(ex: &ShaderExtract, feeds_ps: Opti (election == Some(ElectionLowering::Native32) && (!em.exec_snapshots.sites.is_empty() || em.insns.iter().any(|i| i.mnemonic == "tb_first_active_lane" || i.mnemonic == "s_ff1_i32_b64"))).then_some(32) }); + // A ballot holds the guest's own lanes, so it needs whole waves of the guest's width. + let reductions_wave_size = required_wave_size; + let required_wave_size = match em.mask_ballots.as_ref().map(|b| b.width) { + Some(width) if reductions_wave_size.is_none_or(|w| w == width) + && compute_group(ex).into_iter().try_fold(1u32, u32::checked_mul).is_some_and(|n| n > 0 && n % width == 0) => Some(width), + _ => { + em.mask_ballots = None; + reductions_wave_size + } + }; em.required_wave_size = required_wave_size; // DS bit-mask mode operates on the low five lane bits in wave32 and wave64. // Map guest lanes by workgroup index, independently of the Vulkan subgroup layout. @@ -348,7 +359,7 @@ pub(in crate::hlsl) fn translate_outputs_once(ex: &ShaderExtract, feeds_ps: Opti return Err(format!("wave operation requires complete {width}-lane compute waves")); } } - em.portable_wave64 = (straight_exchange || (required_wave_size == Some(64) + em.portable_wave64 = (straight_exchange || (reductions_wave_size == Some(64) && compute_group(ex) == [64, 1, 1])) && em.lockstep.is_none() && ex.stage == Stage::Compute @@ -360,18 +371,7 @@ pub(in crate::hlsl) fn translate_outputs_once(ex: &ShaderExtract, feeds_ps: Opti && !hair_visibility_indirect && !hair_visibility_single && hair_compact.is_none() && !subsurface_setup && !material_classify && !classify_tiles && !reflection && !group_extrema && (straight_exchange || wave_sum::portable_single_wave(&em.insns)); - // One mask word holds 32 lanes. Two hold any wave the host can have, so a wave64 - // program still runs on adapters without one. - let required_wave_size = match em.mask_ballots.as_ref().map(|b| b.width) { - Some(32) if required_wave_size == Some(64) => { - em.mask_ballots = None; - required_wave_size - } - Some(32) => Some(32), - _ => required_wave_size, - }; if em.portable_wave64 { em.mask_ballots = None; } - em.required_wave_size = required_wave_size; em.regs.extend(em.mask_ballots.iter().flat_map(mask_ballots::Ballots::names).collect::>()); if straight_exchange && !em.portable_wave64 { return Err("straight DPP8 exchange conflicts with a specialized lowering".into()); diff --git a/tools/shader-compiler/src/hlsl/mask_ballots.rs b/tools/shader-compiler/src/hlsl/mask_ballots.rs index 6a76c286..0ca10445 100644 --- a/tools/shader-compiler/src/hlsl/mask_ballots.rs +++ b/tools/shader-compiler/src/hlsl/mask_ballots.rs @@ -21,40 +21,61 @@ pub(super) fn register(o: &Opnd) -> Option { pub(super) fn name(register: u8) -> String { format!("tb_bal{register}") } -/// First scalar register written and how many. -fn written(ins: &Insn, wide: bool) -> Option<(u8, u8)> { +/// The scalar registers written: the first of each group and how many. +fn written(ins: &Insn, wide: bool) -> Vec<(u8, u8)> { let m = ins.mnemonic.as_str(); - let d = ins.dst.first()?; + let mask = if wide { 2 } else { 1 }; + let Some(d) = ins.dst.first() else { return Vec::new() }; + let one = |count: u8| register(d).map(|n| (n, count)).into_iter().collect::>(); if m.starts_with("s_load_") || m.starts_with("s_buffer_load_") { - let width = ["x16", "x8", "x4", "x2"].iter().zip([16, 8, 4, 2]).find(|(s, _)| m.ends_with(*s)).map_or(1, |(_, w)| w); - return Some((register(d)?, width)); + return one(["x16", "x8", "x4", "x2"].iter().zip([16, 8, 4, 2]).find(|(s, _)| m.ends_with(*s)).map_or(1, |(_, w)| w)); } if m.starts_with("s_") { - if m.starts_with("s_cmp") || m.starts_with("s_bitcmp") { return None; } + if m.starts_with("s_cmp") || m.starts_with("s_bitcmp") { return Vec::new(); } let single = ["s_bcnt", "s_ff", "s_flbit"].iter().any(|p| m.starts_with(p)); - return Some((register(d)?, if m.ends_with("64") && !single { 2 } else { 1 })); + let pair = m.ends_with("64") || matches!(m, "s_bitreplicate_b64_b32" | "s_memtime" | "s_memrealtime"); + return one(if pair && !single { 2 } else { 1 }); } - if m == "v_readlane_b32" { - return match *d { Opnd::Vgpr(n) | Opnd::Sgpr(n) => Some((n, 1)), _ => register(d).map(|n| (n, 1)) }; + if matches!(m, "v_readlane_b32" | "v_readfirstlane_b32") { + // The VOP3 encoding keeps the scalar destination in the vector field. + return match *d { Opnd::Vgpr(n) => vec![(n, 1)], _ => one(1) }; } - if m.starts_with("v_cmpx") { return None; } - if m.starts_with("v_") && m != "v_readfirstlane_b32" { - let mask = ins.dst.iter().find_map(register)?; - return Some((mask, if wide { 2 } else { 1 })); + if m.starts_with("v_cmpx") { return Vec::new(); } + if m.starts_with("v_cmp") { return one(mask); } + if m.starts_with("v_") { + let carry = m.contains("_co_"); + return match ins.enc { + Enc::Vop3 if carry || matches!(m, "v_mad_u64_u32" | "v_mad_i64_i32") || m.starts_with("v_div_scale") => + vec![(((ins.raw[0] >> 8) & 127) as u8, mask)], + Enc::Vop2 if carry => vec![(VCC, mask)], + _ => ins.dst.iter().filter_map(register).map(|n| (n, mask)).collect(), + }; } - Some((register(d)?, if m.starts_with("tb_") && m.ends_with("64") { 2 } else { 1 })) + one(if m.starts_with("tb_") && m.ends_with("64") { 2 } else { 1 }) } +/// Whether the lanes of an instruction's mask are all running it. Other masks can also +/// hold lanes that went another way. +fn running(ins: &Insn) -> bool { + let m = ins.mnemonic.as_str(); + !BITWISE.iter().any(|p| m.starts_with(p)) || m.contains("saveexec") + || ins.src.iter().enumerate().any(|(k, o)| *o == Opnd::ExecLo + && (m.starts_with("s_mov_b") || m.starts_with("s_and_b") || (m.starts_with("s_andn2_b") && k == 0))) +} + +const BITWISE: [&str; 11] = ["s_mov_b", "s_and_b", "s_or_b", "s_xor_b", "s_andn2_b", "s_orn2_b", "s_nand_b", "s_nor_b", + "s_xnor_b", "s_not_b", "s_cselect_b"]; + enum Kind { Mask, Of(Vec), AllLanes, Number } /// What an instruction's scalar result is made of. -fn kind(ins: &Insn) -> Kind { +fn kind(ins: &Insn, wide: bool) -> Kind { let m = ins.mnemonic.as_str(); if m.starts_with("v_cmp") || m.contains("_co_") || m.starts_with("v_div_scale") { return Kind::Mask; } - if m.contains("saveexec") { return Kind::Mask; } - let combines = ["s_mov_b", "s_and_b", "s_or_b", "s_xor_b", "s_andn2_b", "s_orn2_b", "s_nand_b", "s_nor_b", - "s_xnor_b", "s_not_b", "s_wqm_b", "s_cselect_b"]; - if !combines.iter().any(|p| m.strip_prefix(p).is_some_and(|rest| matches!(rest, "32" | "64"))) { return Kind::Number; } + let size = if wide { "64" } else { "32" }; + if m.contains("saveexec") { return if m.ends_with(size) { Kind::Mask } else { Kind::Number }; } + // A mask is moved and combined as a whole. + if !BITWISE.iter().any(|p| m.strip_prefix(p) == Some(size)) { return Kind::Number; } let (mut exec, mut from) = (false, Vec::new()); for o in &ins.src { match o { @@ -84,7 +105,67 @@ fn predecessors(insns: &[Insn]) -> Vec> { from } -struct Reach<'a> { insns: &'a [Insn], from: Vec>, wide: bool } +/// Which lanes of a wave run an instruction together. +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +enum Together { All, Running, Some } + +/// Branches of the console take the whole wave, those of the translation one lane. Lanes +/// part in what a branch on a mask jumps over or repeats and after an early exit. A branch on +/// EXEC keeps the running ones together. +fn together(insns: &[Insn]) -> Vec { + let branches = || insns.iter().enumerate().filter(|(_, x)| x.enc == Enc::Sopp && Emitter::branch_cond(x.op).is_some()); + let target = |x: &Insn| x.offset as i64 + 4 + 4 * x.aux.imm; + let targets: BTreeSet = branches().map(|(_, x)| target(x)).collect(); + let end = |x: &Insn| x.enc == Enc::Sopp && x.op == 1; + let exits = insns.iter().position(end).is_some_and(|first| insns[first..].iter().any(|x| !end(x) && x.enc != Enc::Sopp)); + let mut found = vec![Together::All; insns.len()]; + for (i, branch) in branches() { + let (from, to) = (branch.offset as i64, target(branch)); + let lanes = match branch.op { + 2 => continue, + 4 | 5 if uniform_condition(insns, i, &targets) => continue, + 8 if to > from => Together::Running, + 9 if to <= from => Together::Running, + _ => Together::Some, + }; + for (k, x) in insns.iter().enumerate() { + if (from.min(to)..from.max(to)).contains(&(x.offset as i64)) || exits && k > i { found[k] = found[k].max(lanes); } + } + } + found +} + +/// Whether the condition code a branch tests is that of numbers every lane agrees on. +fn uniform_condition(insns: &[Insn], branch: usize, targets: &BTreeSet) -> bool { + // A lane mask, or something that could be one. + let mask = |x: &Insn| { + let m = x.mnemonic.as_str(); + let number = |o: &Opnd| matches!(o, Opnd::Literal(_)) || matches!(o, Opnd::ConstInt(n) if !matches!(n, 0 | -1)); + m.starts_with("v_") && !m.contains("lane") || m.contains("saveexec") || m.starts_with("s_bcnt") || m.starts_with("s_ff") + || BITWISE.iter().any(|p| m.starts_with(p)) && !x.src.iter().any(number) + && x.src.iter().any(|o| register(o).is_some() || matches!(o, Opnd::ExecLo | Opnd::ExecHi)) + }; + let number = |o: &Opnd| match register(o) { + Some(n) => !insns.iter().any(|x| mask(x) && written(x, true).iter().any(|&(first, count)| (first..first + count).contains(&n))), + None => matches!(o, Opnd::ConstInt(_) | Opnd::ConstF32(_) | Opnd::Literal(_)), + }; + let mut at = branch; + while at > 0 && !targets.contains(&(insns[at].offset as i64)) { + at -= 1; + let x = &insns[at]; + let m = x.mnemonic.as_str(); + if m.starts_with("s_cmp") || m.starts_with("s_bitcmp") { + let compared = x.dst.iter().filter(|_| x.enc == Enc::Sopk); + return x.src.iter().chain(compared).all(number); + } + // These leave the condition code alone. + let leaves = ["s_mov", "s_cselect", "s_cmov", "s_ff1", "s_mul", "s_load", "s_buffer_load", "s_nop", "s_waitcnt", "s_inst_prefetch"]; + if m.starts_with("s_") && !leaves.iter().any(|p| m.starts_with(p)) { return false; } + } + false +} + +struct Reach<'a> { insns: &'a [Insn], from: Vec>, together: Vec, wide: bool } impl Reach<'_> { /// The writes of `register` that reach `at`. None when its entry value does. @@ -95,31 +176,50 @@ impl Reach<'_> { // Padding after an unconditional branch is never entered. for &p in &self.from[i] { if !seen.insert(p) { continue; } - match written(&self.insns[p], self.wide) { - Some((first, count)) if (first..first.saturating_add(count)).contains(®ister) => { found.insert(p); } - _ => todo.push(p), - } + if self.writes(p, register).is_some() { found.insert(p); } else { todo.push(p); } } } Some(found) } - /// The definitions of a mask read at `at`, if every value that reaches it is one. - fn mask(&self, at: usize, register: u8) -> Option> { + /// The group of registers instruction `at` writes that `register` is part of. + fn writes(&self, at: usize, register: u8) -> Option<(u8, u8)> { + written(&self.insns[at], self.wide).into_iter().find(|&(first, count)| (first..first.saturating_add(count)).contains(®ister)) + } + + /// The definitions of a mask read at `at` and its first register, if every value that + /// reaches any of its words is a whole mask. + fn mask(&self, at: usize, register: u8) -> Option<(u8, BTreeSet)> { let direct = self.defs(at, register)?; + let words = if self.wide { 2 } else { 1 }; + let mut first = None; + for &d in &direct { + let (n, count) = self.writes(d, register)?; + if count != words || first.is_some_and(|f| f != n) { return None; } + first = Some(n); + } + let first = first?; + // The words of a pair are read and written together. + if (first..first + words).any(|n| self.defs(at, n).as_ref() != Some(&direct)) { return None; } let (mut seen, mut todo, mut rooted) = (BTreeSet::new(), direct.iter().copied().collect::>(), false); while let Some(d) = todo.pop() { if !seen.insert(d) { continue; } - match kind(&self.insns[d]) { + let captured = direct.contains(&d); + // Lanes that went another way would be missing from its ballot. + let whole = match self.together[d] { Together::All => true, Together::Running => running(&self.insns[d]), Together::Some => false }; + if captured && !whole { return None; } + match kind(&self.insns[d], self.wide) { Kind::Number => return None, // Counted itself, it holds lanes that are not running. - Kind::AllLanes if direct.contains(&d) => return None, + Kind::AllLanes if captured => return None, Kind::AllLanes => (), Kind::Mask => rooted = true, - Kind::Of(regs) => for n in regs { todo.extend(self.defs(d, n)?); }, + Kind::Of(regs) => for n in regs { + for word in n..n + words { todo.extend(self.defs(d, word)?); } + }, } } - rooted.then_some(direct) + rooted.then_some((first, direct)) } } @@ -150,8 +250,14 @@ pub(super) fn find(insns: &[Insn]) -> Option { || i.mnemonic.starts_with("s_movrel")) { return None; } let masks = |bits: &str| insns.iter().any(|i| i.mnemonic.starts_with("s_") && i.mnemonic.ends_with(bits) && (i.mnemonic.contains("saveexec") || i.src.contains(&Opnd::ExecLo) || i.dst.contains(&Opnd::ExecLo))); - let wide = match (masks("_b32"), masks("_b64")) { (true, false) => false, (false, true) => true, _ => return None }; - let reach = Reach { insns, from: predecessors(insns), wide }; + // Only a wave of 64 lanes has a second word. + let second = insns.iter().any(|i| i.mnemonic == "v_mbcnt_hi_u32_b32" || i.src.iter().chain(&i.dst).any(|o| *o == Opnd::ExecHi)); + let wide = match (masks("_b32"), masks("_b64")) { + (true, false) if !second => false, + (_, true) if !masks("_b32") || second => true, + _ => return None, + }; + let reach = Reach { insns, from: predecessors(insns), together: together(insns), wide }; let mut found = Ballots { defs: BTreeMap::new(), uses: BTreeSet::new(), width: if wide { 64 } else { 32 } }; for (i, ins) in insns.iter().enumerate().filter(|(_, i)| counted(i)) { let Some(source) = ins.src.first() else { continue }; @@ -161,13 +267,10 @@ pub(super) fn find(insns: &[Insn]) -> Option { continue; } let Some(register) = register(source) else { continue }; - let Some(defs) = reach.mask(i, register) else { - continue - }; - for d in defs { - let (first, count) = written(&insns[d], wide).expect("a definition writes"); - found.defs.entry(d).or_default().insert(if count == 2 { first } else { register }); - } + let Some((first, defs)) = reach.mask(i, register) else { continue }; + // A 64-bit count starts at the mask's first word, and narrow waves have no second. + if ins.mnemonic.ends_with("_b64") && (!wide || register != first) { continue; } + for d in defs { found.defs.entry(d).or_default().insert(first); } found.uses.insert(i); } (!found.uses.is_empty()).then_some(found) diff --git a/tools/shader-compiler/src/tests/hlsl/exec_group_wave32.rs b/tools/shader-compiler/src/tests/hlsl/exec_group_wave32.rs index 52fb8e3d..aaf5677d 100644 --- a/tools/shader-compiler/src/tests/hlsl/exec_group_wave32.rs +++ b/tools/shader-compiler/src/tests/hlsl/exec_group_wave32.rs @@ -486,3 +486,14 @@ fn real_translate_coalesces_wave32_and_wave64_intrinsics_and_temps() { ); assert_eq!(t64.hlsl.matches("if (exec_lo & 1u)").count(), 1); } + +#[test] +fn resolve_counts_its_whole_masks() { + // s_mov_b32 s12, exec_lo; v_cmp_lt_u32 s21, 1000, v0; s_bcnt1_i32_b32 s20, s21; v_mov_b32 v10, s20 + let words = [0xbe8c_037e, 0xd4c1_0015, 0x0002_00ff, 1000, 0xbe94_0f15, 0x7e14_0214, 0xbf81_0000]; + let shader = translate(&synthetic_resolve_wave32(&words)).expect("translate wave32"); + assert!(shader.hlsl.contains("uint tb_lane_bit"), "{}", shader.hlsl); + // Its masks hold every lane already. A ballot of one lane's bit would not. + assert!(shader.hlsl.contains("s20 = countbits(s21);"), "{}", shader.hlsl); + assert!(!shader.hlsl.contains("tb_bal"), "{}", shader.hlsl); +} diff --git a/tools/shader-compiler/src/tests/hlsl/mask_ballots.rs b/tools/shader-compiler/src/tests/hlsl/mask_ballots.rs index 24e63047..98e711bd 100644 --- a/tools/shader-compiler/src/tests/hlsl/mask_ballots.rs +++ b/tools/shader-compiler/src/tests/hlsl/mask_ballots.rs @@ -57,7 +57,8 @@ fn a_mask_is_captured_where_it_is_computed() { compare(), scalar("s_or_b32", 11, vec![Opnd::Sgpr(11), Opnd::VccLo]), count(Opnd::Sgpr(11)), - branch(5, -4), + insn("s_cmp_lt_u32", Enc::Sopc, vec![Opnd::Scc], vec![Opnd::Sgpr(22), Opnd::ConstInt(3)]), + branch(5, -5), ]); assert_eq!(gathered, Some(vec![(3, 11)])); } @@ -85,6 +86,133 @@ fn numbers_are_not_masks() { } } +/// The same in a wave of 64 lanes. +fn wide(mut ops: Vec) -> Option> { + ops.insert(0, scalar("s_mov_b64", 98, vec![Opnd::ExecLo])); + ops.push(Insn { op: 1, ..insn("s_endpgm", Enc::Sopp, vec![], vec![]) }); + for (i, op) in ops.iter_mut().enumerate() { op.offset = i * 4; } + let found = find(&ops)?; + Some(found.defs.iter().flat_map(|(&at, regs)| regs.iter().map(move |&r| (at, r))).collect()) +} + +fn count64(source: Opnd) -> Insn { scalar("s_bcnt1_i32_b64", 20, vec![source]) } + +/// A VOP3 operation whose carry or borrow goes to `mask`. +fn carry(mnemonic: &str, mask: u8) -> Insn { + let mut ins = insn(mnemonic, Enc::Vop3, vec![Opnd::Vgpr(3)], vec![Opnd::Vgpr(0), Opnd::Vgpr(1)]); + ins.raw[0] = u32::from(mask) << 8; + ins +} + +#[test] +fn both_words_of_a_mask_come_from_the_same_place() { + assert_eq!(wide(vec![compare(), count64(Opnd::VccLo)]), Some(vec![(1, 106)])); + // The second word alone. + let mut second = compare(); + (second.mnemonic, second.dst) = ("v_mbcnt_hi_u32_b32".into(), vec![Opnd::Vgpr(4)]); + second.src = vec![Opnd::VccHi, Opnd::Vgpr(3)]; + assert_eq!(wide(vec![compare(), second]), Some(vec![(1, 106)])); + for ops in [ + // The second word is a number, always or on one path. + vec![compare(), scalar("s_mov_b32", 107, vec![Opnd::Sgpr(0)]), count64(Opnd::VccLo)], + vec![compare(), branch(4, 1), scalar("s_mov_b32", 107, vec![Opnd::Sgpr(0)]), count64(Opnd::VccLo)], + // Two halves of different masks. + vec![compare(), scalar("s_mov_b32", 10, vec![Opnd::VccLo]), scalar("s_mov_b32", 11, vec![Opnd::VccLo]), count64(Opnd::Sgpr(10))], + // A pair that starts in the middle of a mask. + vec![ + compare(), + scalar("s_mov_b64", 10, vec![Opnd::VccLo]), + scalar("s_mov_b64", 12, vec![Opnd::VccLo]), + count64(Opnd::Sgpr(11)), + ], + ] { + assert_eq!(wide(ops), None); + } +} + +#[test] +fn every_scalar_write_is_seen() { + let first = |enc, dst| insn("v_readfirstlane_b32", enc, vec![dst], vec![Opnd::Vgpr(0)]); + for op in [ + first(Enc::Vop1, Opnd::Sgpr(11)), + first(Enc::Vop3, Opnd::Vgpr(11)), + insn("v_readlane_b32", Enc::Vop3, vec![Opnd::Vgpr(11)], vec![Opnd::Vgpr(0), Opnd::ConstInt(0)]), + carry("v_mad_u64_u32", 11), + ] { + let kept = vec![compare(), scalar("s_mov_b32", 11, vec![Opnd::VccLo]), count(Opnd::Sgpr(11))]; + assert_eq!(ballots(kept.clone()), Some(vec![(2, 11)])); + let mut replaced = kept; + replaced.insert(2, op); + assert_eq!(ballots(replaced), None); + } + // A carry is a mask of its own. + assert_eq!(ballots(vec![compare(), carry("v_add_co_u32", 106), count(Opnd::VccLo)]), Some(vec![(2, 106)])); + assert_eq!(wide(vec![compare(), carry("v_add_co_u32", 10), count64(Opnd::Sgpr(10))]), Some(vec![(2, 10)])); + let mut short = carry("v_add_co_ci_u32", 0); + short.enc = Enc::Vop2; + assert_eq!(ballots(vec![compare(), short, count(Opnd::VccLo)]), Some(vec![(2, 106)])); +} + +#[test] +fn a_pair_is_not_a_mask_of_32_lanes() { + // Two masks moved at once, and one mask with its neighbour. + let pair = |from, read| ballots(vec![ + compare(), + scalar("s_mov_b32", 12, vec![Opnd::VccLo]), + scalar("s_mov_b32", 13, vec![Opnd::VccLo]), + scalar("s_mov_b64", 10, vec![from]), + count(read), + ]); + assert_eq!(pair(Opnd::Sgpr(12), Opnd::Sgpr(10)), None); + assert_eq!(pair(Opnd::Sgpr(12), Opnd::Sgpr(11)), None); + assert_eq!(ballots(vec![compare(), count64(Opnd::VccLo)]), None); + // Widths that contradict each other. + assert_eq!(wide(vec![compare(), scalar("s_mov_b32", 99, vec![Opnd::ExecLo]), count(Opnd::VccLo)]), None); + // The second word of EXEC does not exist in 32 lanes. + assert_eq!(ballots(vec![compare(), scalar("s_mov_b32", 99, vec![Opnd::ExecHi]), count(Opnd::VccLo)]), None); +} + +#[test] +fn lanes_that_parted_are_not_counted() { + let gather = || scalar("s_or_b32", 11, vec![Opnd::Sgpr(11), Opnd::VccLo]); + let empty = || scalar("s_mov_b32", 11, vec![Opnd::ConstInt(0)]); + // Jumped over by the lanes a branch on a mask takes with it. + for op in [6, 7, 8, 9] { + assert_eq!(ballots(vec![empty(), compare(), branch(op, 1), gather(), count(Opnd::Sgpr(11))]), None, "{op}"); + } + // The condition code of a mask operation, and of a comparison with a mask. + let code = |op: Insn| ballots(vec![empty(), compare(), op, branch(5, 1), gather(), count(Opnd::Sgpr(11))]); + assert_eq!(code(scalar("s_and_b32", 30, vec![Opnd::VccLo, Opnd::ExecLo])), None); + let compared = |o| insn("s_cmp_eq_u32", Enc::Sopc, vec![Opnd::Scc], vec![o, Opnd::ConstInt(0)]); + assert_eq!(code(compared(Opnd::VccLo)), None); + assert!(code(compared(Opnd::Sgpr(0))).is_some()); + // Lanes that are running arrive together. + let saved = vec![compare(), branch(8, 1), scalar("s_mov_b32", 11, vec![Opnd::ExecLo]), branch(8, 0), count(Opnd::Sgpr(11))]; + assert_eq!(ballots(saved), None, "entry value"); + let inside = |op| ballots(vec![compare(), branch(op, 2), scalar("s_mov_b32", 11, vec![Opnd::ExecLo]), count(Opnd::Sgpr(11))]); + assert_eq!(inside(8), Some(vec![(3, 11)])); + assert_eq!(inside(6), None); + // Some left the program. + let left = |op| vec![compare(), branch(op, 1), Insn { op: 1, ..insn("s_endpgm", Enc::Sopp, vec![], vec![]) }, + scalar("s_mov_b32", 11, vec![Opnd::ConstInt(0)]), gather(), count(Opnd::Sgpr(11))]; + assert_eq!(ballots(left(7)), None); + assert_eq!(ballots(left(9)), None); +} + +#[test] +fn partial_waves_keep_the_old_translation() { + let words = [0xbe8c_037e, 0x7d82_00ff, 1000, 0xbe94_0f6a, 0x7e14_0214, 0xbf81_0000u32]; + for (threads, whole) in [([64, 1, 1], true), ([8, 8, 1], true), ([16, 1, 1], false), ([33, 1, 1], false)] { + let (mut ex, _, _): (ShaderExtract, _, _) = fixture::shader(32); + ex.isa = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + ex.isa_data = ex.isa.clone(); + ex.psv_threads = Some(threads); + let shader = translate(&ex).unwrap(); + assert_eq!(shader.hlsl.contains("WaveActiveBallot"), whole, "{threads:?}"); + assert_eq!(shader.required_wave_size, whole.then_some(32), "{threads:?}"); + } +} + #[test] fn counts_read_the_ballot() { // v_cmp_lt_u32 vcc, 1000, v0; s_bcnt1 s20, vcc; v_mov v10, s20 @@ -99,8 +227,10 @@ fn counts_read_the_ballot() { assert!(shader.hlsl.contains("WaveActiveBallot((vcc_lo & 1u) != 0u)"), "{}", shader.hlsl); let wanted = if width == 32 { "countbits(tb_bal106)" } else { "(countbits(tb_bal106) + countbits(tb_bal107))" }; assert!(shader.hlsl.contains(wanted), "{}", shader.hlsl); - // Two mask words hold a wave of any size, one holds 32 lanes. - assert_eq!(shader.required_wave_size, (width == 32).then_some(32)); + // Every word is declared, and the wave is the guest's. + assert!(shader.hlsl.contains("tb_bal106 = 0u"), "{}", shader.hlsl); + assert_eq!(shader.hlsl.contains("tb_bal107 = 0u"), width == 64); + assert_eq!(shader.required_wave_size, Some(width)); assert_eq!(shader.profile, "cs_6_5"); } }