"""Semantic interpreter tests for vector conditional move (v_cndmask_b32) with VCC and EXEC masks. AMD RDNA2 VALU Instruction Set Architecture: v_cndmask_b32_e32 dst, src0, src1 - Implicit condition mask: VCC (vcc_lo in Wave32, vcc in Wave64). - For each lane i in the SIMD wave: if EXEC[i] == 1: dst[i] = src1[i] if (VCC[i] == 1) else src0[i] else: dst[i] = dst_previous[i] (inactive lanes preserve background state) v_cndmask_b32_e64 dst, src0, src1, cond_mask - Explicit condition mask: any SGPR, SGPR pair, or VCC. - Operates under EXEC mask identically to the e32 encoding. Divergence Scenarios: 1. Uniform Conditions: - All lanes condition 0 (VCC == 0): all active lanes select src0. - All lanes condition 1 (VCC == ~0): all active lanes select src1. 2. Alternating / Checkered Divergence: - Alternating bit patterns (0x55555555 / 0xAAAAAAAA) across active lanes. 3. Half-Wave and Strided Divergence: - Divergent execution across low-half vs high-half (lanes 0..15 vs 16..31 in Wave32; lanes 0..31 vs 32..63 in Wave64). - Power-of-two strided clusters (blocks of 2, 4, 8, 16 lanes). 4. Sparse Single-Bit Divergence: - Exact one-hot / one-cold condition masks walking across all lane indices. 5. Data-Dependent Divergence: - Dynamic condition masks generated by vector comparisons (v_cmp_*). 6. EXEC Mask Inactive Preservation: - Lanes masked out by EXEC (EXEC[i] == 0) MUST preserve their previous VGPR values without corruption, regardless of src0, src1, or VCC. - Zero EXEC (EXEC == 0): whole-wave no-op across all vector registers. 7. Correlated and Orthogonal Divergence: - Structured If-Then-Else: Then block (EXEC = EXEC & VCC) and Else block (EXEC = EXEC & ~VCC) executing v_cndmask_b32 independently and re-converging. - Orthogonal masks: partial wave execution where EXEC and VCC vary independently. 8. Wave64 Cross-Half Divergence: - Independent condition patterns in low half (lanes 0..31) and high half (lanes 32..63). - Half-disabled waves (EXEC low-half only or high-half only). - Boundary transitions across the 32-lane boundary (lane 31 vs lane 32). 9. SPIR-V Translation and Interpretation: - Translation through tools/rdna2spirv.py emitting OpSelect with lane %active. - Execution via tests/semantic/spirv_mini_interp.py. 10. Negative Controls and Invariant Mutations: - Condition inversion, operand swapping, and single-bit flip sensitivity. Standard library only: zero game data, no external dependencies, Python 3.9+ compatible. """ from __future__ import annotations import gc import os import random import struct import sys import tempfile import unittest import warnings HERE = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.dirname(os.path.dirname(HERE)) TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") if TOOLS_DIR not in sys.path: sys.path.insert(0, TOOLS_DIR) if HERE not in sys.path: sys.path.insert(0, HERE) import rdna2spirv # noqa: E402 import spirv_mini_interp as si # noqa: E402 MASK32 = 0xFFFFFFFF MASK64 = (1 << 64) - 1 STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: """AMD RDNA2 v_cndmask_b32 per-lane mathematical reference oracle. Lane semantics: - If exec_bit == 0: lane is inactive, dst is preserved (returns prev_dst & MASK32). - If exec_bit == 1: lane is active: - If cond_bit == 0: selects src0 & MASK32. - If cond_bit != 0: selects src1 & MASK32. """ if not (exec_bit & 1): return prev_dst & MASK32 return (src1 if (cond_bit & 1) else src0) & MASK32 def ref_cndmask_wave( src0_lanes: list[int], src1_lanes: list[int], cond_mask: int, exec_mask: int, prev_dst_lanes: list[int] | None = None, wave_size: int = 32, ) -> list[int]: """Whole-wave vector conditional move reference oracle across divergent lanes.""" if prev_dst_lanes is None: prev_dst_lanes = [0] * wave_size res: list[int] = [] for lane in range(wave_size): c_bit = (cond_mask >> lane) & 1 e_bit = (exec_mask >> lane) & 1 s0 = src0_lanes[lane] s1 = src1_lanes[lane] old = prev_dst_lanes[lane] res.append(ref_cndmask_lane(s0, s1, c_bit, e_bit, old)) return res # ----------------------------------------------------------------------------- # 2. Multi-Lane Wave SIMD Interpreter # ----------------------------------------------------------------------------- class CndmaskWaveInterpreter: """Simulates a SIMD wave executing vector instructions with VCC and EXEC masks. Models: - Wave32 (32 lanes) and Wave64 (64 lanes). - VGPRs: per-lane independent 32-bit vector registers (v0..v255). - SGPRs: uniform 32-bit scalar registers shared across the wave (s0..s127). - VCC: condition mask register (32-bit vcc_lo in Wave32, 64-bit vcc in Wave64). - EXEC: execution mask register (32-bit exec_lo in Wave32, 64-bit exec in Wave64). - Instructions: v_mov_b32, v_cndmask_b32_e32, v_cndmask_b32_e64, v_cmp_eq/ne/lt/gt/le/ge_u32, s_mov_b32/b64, s_and_saveexec_b32/b64, s_or_exec_b32/b64, s_and_b32/b64, s_or_b32/b64, s_not_b32/b64. """ def __init__(self, wave_size: int = 32, initial_exec: int | None = None) -> None: if wave_size not in (32, 64): raise ValueError(f"Unsupported wave_size: {wave_size}") self.wave_size = wave_size self.mask_all = (1 << wave_size) - 1 self.exec_mask = self.mask_all if initial_exec is None else (initial_exec & self.mask_all) self.vcc = 0 self.sgprs = [0] * 128 self.vgprs = [[0] * 256 for _ in range(wave_size)] def is_lane_active(self, lane: int) -> bool: return bool((self.exec_mask >> lane) & 1) def set_exec(self, mask: int) -> None: self.exec_mask = mask & self.mask_all def set_vcc(self, mask: int) -> None: self.vcc = mask & self.mask_all def get_vgpr(self, reg_idx: int) -> list[int]: return [self.vgprs[lane][reg_idx] for lane in range(self.wave_size)] def set_vgpr_lane(self, reg_idx: int, lane: int, val: int) -> None: self.vgprs[lane][reg_idx] = val & MASK32 def init_vgpr(self, reg_idx: int, values: list[int] | int) -> None: if isinstance(values, int): val = values & MASK32 for lane in range(self.wave_size): self.vgprs[lane][reg_idx] = val else: for lane in range(min(len(values), self.wave_size)): self.vgprs[lane][reg_idx] = values[lane] & MASK32 def read_operand(self, op: int | str, lane: int) -> int: if isinstance(op, int): return op & MASK32 op_str = str(op).strip().lower() if op_str.startswith("v"): reg_idx = int(op_str[1:]) return self.vgprs[lane][reg_idx] & MASK32 elif op_str.startswith("s"): reg_idx = int(op_str[1:]) return self.sgprs[reg_idx] & MASK32 elif op_str in ("vcc", "vcc_lo"): return (self.vcc >> lane) & 1 elif op_str == "vcc_hi": return (self.vcc >> (lane + 32)) & 1 if self.wave_size == 64 else self.sgprs[1] elif op_str in ("exec", "exec_lo"): return (self.exec_mask >> lane) & 1 else: raise ValueError(f"Unsupported operand: {op}") def execute_v_mov(self, dst_v: int, src: int | str) -> None: """v_mov_b32 dst_v, src: only active lanes are updated.""" for lane in range(self.wave_size): if self.is_lane_active(lane): self.vgprs[lane][dst_v] = self.read_operand(src, lane) def execute_v_cndmask_e32(self, dst_v: int, src0: int | str, src1: int | str) -> None: """v_cndmask_b32_e32 dst, src0, src1 with implicit VCC condition.""" for lane in range(self.wave_size): if self.is_lane_active(lane): s0 = self.read_operand(src0, lane) s1 = self.read_operand(src1, lane) c_bit = (self.vcc >> lane) & 1 self.vgprs[lane][dst_v] = s1 if c_bit else s0 def execute_v_cndmask_e64( self, dst_v: int, src0: int | str, src1: int | str, cond_src: str | int, ) -> None: """v_cndmask_b32_e64 dst, src0, src1, cond_src with explicit condition mask.""" for lane in range(self.wave_size): if self.is_lane_active(lane): s0 = self.read_operand(src0, lane) s1 = self.read_operand(src1, lane) if isinstance(cond_src, int): c_bit = (cond_src >> lane) & 1 elif cond_src in ("vcc", "vcc_lo"): c_bit = (self.vcc >> lane) & 1 elif cond_src.startswith("s[") and ":" in cond_src: lo_hi = cond_src[2:-1].split(":") lo = int(lo_hi[0]) mask = (self.sgprs[lo] & MASK32) | ((self.sgprs[lo + 1] & MASK32) << 32) c_bit = (mask >> lane) & 1 elif cond_src.startswith("s"): reg = int(cond_src[1:]) c_bit = (self.sgprs[reg] >> (lane % 32)) & 1 else: raise ValueError(f"Unknown cond_src: {cond_src}") self.vgprs[lane][dst_v] = s1 if c_bit else s0 def execute_v_cmp( self, rel: str, src0: int | str, src1: int | str, dst_mask: str = "vcc", ) -> None: """v_cmp__u32/i32: inactive lanes in EXEC write 0 to condition mask.""" mask = 0 for lane in range(self.wave_size): if self.is_lane_active(lane): s0 = self.read_operand(src0, lane) s1 = self.read_operand(src1, lane) taken = False if rel == "eq": taken = (s0 == s1) elif rel == "ne": taken = (s0 != s1) elif rel == "lt_u32": taken = (s0 < s1) elif rel == "le_u32": taken = (s0 <= s1) elif rel == "gt_u32": taken = (s0 > s1) elif rel == "ge_u32": taken = (s0 >= s1) else: raise NotImplementedError(f"Unsupported cmp rel: {rel}") if taken: mask |= (1 << lane) if dst_mask in ("vcc", "vcc_lo"): self.vcc = mask & self.mask_all elif dst_mask.startswith("s[") and ":" in dst_mask: lo_hi = dst_mask[2:-1].split(":") lo = int(lo_hi[0]) self.sgprs[lo] = mask & MASK32 self.sgprs[lo + 1] = (mask >> 32) & MASK32 elif dst_mask.startswith("s"): reg = int(dst_mask[1:]) self.sgprs[reg] = mask & MASK32 def execute_s_and_saveexec(self, dst_s: int, mask_src: str | int) -> None: """s_and_saveexec_b32 / s_and_saveexec_b64: save EXEC and narrow it.""" self.sgprs[dst_s] = self.exec_mask & MASK32 if self.wave_size == 64: self.sgprs[dst_s + 1] = (self.exec_mask >> 32) & MASK32 if isinstance(mask_src, int): m = mask_src elif mask_src in ("vcc", "vcc_lo"): m = self.vcc elif mask_src.startswith("s[") and ":" in mask_src: lo = int(mask_src[2:-1].split(":")[0]) m = (self.sgprs[lo] & MASK32) | ((self.sgprs[lo + 1] & MASK32) << 32) elif mask_src.startswith("s"): m = self.sgprs[int(mask_src[1:])] else: raise ValueError(f"Unknown mask_src: {mask_src}") self.exec_mask = (self.exec_mask & m) & self.mask_all def execute_s_or_exec(self, mask_src: str | int) -> None: """s_or_exec_b32 / s_or_exec_b64: EXEC |= mask.""" if isinstance(mask_src, int): m = mask_src elif mask_src in ("vcc", "vcc_lo"): m = self.vcc elif mask_src.startswith("s[") and ":" in mask_src: lo = int(mask_src[2:-1].split(":")[0]) m = (self.sgprs[lo] & MASK32) | ((self.sgprs[lo + 1] & MASK32) << 32) elif mask_src.startswith("s"): m = self.sgprs[int(mask_src[1:])] else: raise ValueError(f"Unknown mask_src: {mask_src}") self.exec_mask = (self.exec_mask | m) & self.mask_all # ----------------------------------------------------------------------------- # 3. Synthetic Shader Runner via rdna2spirv & spirv_mini_interp # ----------------------------------------------------------------------------- _TMP_DIR: tempfile.TemporaryDirectory | None = None _SRC_PATH: str | None = None def setUpModule() -> None: global _TMP_DIR, _SRC_PATH _TMP_DIR = tempfile.TemporaryDirectory() disasm_dir = os.path.join(_TMP_DIR.name, "disasm") os.mkdir(disasm_dir) _SRC_PATH = os.path.join(disasm_dir, "ps_cndmask.s") with open(os.path.join(_TMP_DIR.name, "ps_cndmask.dxbc"), "wb") as f: f.write(STUB_DXBC) def tearDownModule() -> None: global _TMP_DIR if _TMP_DIR is not None: _TMP_DIR.cleanup() _TMP_DIR = None def run_synthetic_ps(lines: list[str]) -> tuple[int, int, int, int]: """Translates synthetic assembly lines and executes with spirv_mini_interp.""" if _TMP_DIR is None: setUpModule() assert _SRC_PATH is not None asm = ( "; ps_cndmask\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v0, v1, v2, v3 done vm\n\ts_endpgm\n" ) with open(_SRC_PATH, "w", encoding="utf-8") as f: f.write(asm) with warnings.catch_warnings(): warnings.simplefilter("ignore", ResourceWarning) spv = rdna2spirv.translate(_SRC_PATH) res = si.run_fragment(spv)["%out_mrt0"] return tuple(res) # ----------------------------------------------------------------------------- # 4. Test Suites # ----------------------------------------------------------------------------- class TestCndmaskReferenceOracle(unittest.TestCase): """Verifies core mathematical reference oracle, truth table, and invariants.""" def test_truth_table_active_lane(self) -> None: """For active lanes, cond_bit=0 selects src0, cond_bit=1 selects src1.""" src0 = 0x11111111 src1 = 0x22222222 prev = 0x99999999 self.assertEqual(ref_cndmask_lane(src0, src1, cond_bit=0, exec_bit=1, prev_dst=prev), src0) self.assertEqual(ref_cndmask_lane(src0, src1, cond_bit=1, exec_bit=1, prev_dst=prev), src1) def test_inactive_lane_preservation(self) -> None: """When exec_bit=0, previous dst is preserved regardless of cond, src0, or src1.""" src0 = 0xAAAAAAAA src1 = 0xBBBBBBBB prev = 0xDEADBEEF self.assertEqual(ref_cndmask_lane(src0, src1, cond_bit=0, exec_bit=0, prev_dst=prev), prev) self.assertEqual(ref_cndmask_lane(src0, src1, cond_bit=1, exec_bit=0, prev_dst=prev), prev) def test_complement_duality(self) -> None: """Duality: cndmask(src0, src1, cond) == cndmask(src1, src0, 1 - cond).""" rng = random.Random(20261122) for _ in range(100): s0 = rng.getrandbits(32) s1 = rng.getrandbits(32) for c in (0, 1): res_normal = ref_cndmask_lane(s0, s1, cond_bit=c, exec_bit=1) res_dual = ref_cndmask_lane(s1, s0, cond_bit=1 - c, exec_bit=1) self.assertEqual(res_normal, res_dual) def test_idempotence(self) -> None: """Idempotence: cndmask(x, x, cond) == x for any condition when active.""" rng = random.Random(20261122) for _ in range(50): x = rng.getrandbits(32) self.assertEqual(ref_cndmask_lane(x, x, cond_bit=0, exec_bit=1), x) self.assertEqual(ref_cndmask_lane(x, x, cond_bit=1, exec_bit=1), x) def test_extreme_32bit_values(self) -> None: """Bit patterns including 0, max uint, signed limits, and float bit patterns.""" extremes = [ 0x00000000, 0xFFFFFFFF, 0x7FFFFFFF, 0x80000000, 0x3F800000, 0xBF800000, 0x7F800000, 0xFF800000, ] for s0 in extremes: for s1 in extremes: self.assertEqual(ref_cndmask_lane(s0, s1, 0, 1), s0) self.assertEqual(ref_cndmask_lane(s0, s1, 1, 1), s1) class TestCndmaskWave32Divergence(unittest.TestCase): """Verifies SIMD Wave32 execution across divergent lane patterns.""" def test_uniform_all_false_vcc(self) -> None: """All 32 lanes active with VCC = 0x00000000 (all select src0).""" wave = CndmaskWaveInterpreter(wave_size=32) src0_vals = [0x1000 + i for i in range(32)] src1_vals = [0x2000 + i for i in range(32)] wave.init_vgpr(0, src0_vals) wave.init_vgpr(1, src1_vals) wave.set_vcc(0x00000000) wave.set_exec(0xFFFFFFFF) wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") self.assertEqual(wave.get_vgpr(2), src0_vals) def test_uniform_all_true_vcc(self) -> None: """All 32 lanes active with VCC = 0xFFFFFFFF (all select src1).""" wave = CndmaskWaveInterpreter(wave_size=32) src0_vals = [0x1000 + i for i in range(32)] src1_vals = [0x2000 + i for i in range(32)] wave.init_vgpr(0, src0_vals) wave.init_vgpr(1, src1_vals) wave.set_vcc(0xFFFFFFFF) wave.set_exec(0xFFFFFFFF) wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") self.assertEqual(wave.get_vgpr(2), src1_vals) def test_checkered_divergence(self) -> None: """Alternating lanes: VCC = 0x55555555 (even lanes select src1, odd lanes select src0).""" wave = CndmaskWaveInterpreter(wave_size=32) src0_vals = [0xA000 + i for i in range(32)] src1_vals = [0xB000 + i for i in range(32)] wave.init_vgpr(0, src0_vals) wave.init_vgpr(1, src1_vals) vcc_mask = 0x55555555 wave.set_vcc(vcc_mask) wave.set_exec(0xFFFFFFFF) wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") expected = [src1_vals[i] if (i % 2 == 0) else src0_vals[i] for i in range(32)] self.assertEqual(wave.get_vgpr(2), expected) def test_inverted_checkered_divergence(self) -> None: """Alternating lanes: VCC = 0xAAAAAAAA (odd lanes select src1, even lanes select src0).""" wave = CndmaskWaveInterpreter(wave_size=32) src0_vals = [0xC000 + i for i in range(32)] src1_vals = [0xD000 + i for i in range(32)] wave.init_vgpr(0, src0_vals) wave.init_vgpr(1, src1_vals) vcc_mask = 0xAAAAAAAA wave.set_vcc(vcc_mask) wave.set_exec(0xFFFFFFFF) wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") expected = [src1_vals[i] if (i % 2 == 1) else src0_vals[i] for i in range(32)] self.assertEqual(wave.get_vgpr(2), expected) def test_half_wave_divergence(self) -> None: """Half-wave divergence: lanes 0..15 select src1, lanes 16..31 select src0.""" wave = CndmaskWaveInterpreter(wave_size=32) src0_vals = [100 + i for i in range(32)] src1_vals = [200 + i for i in range(32)] wave.init_vgpr(0, src0_vals) wave.init_vgpr(1, src1_vals) wave.set_vcc(0x0000FFFF) wave.set_exec(0xFFFFFFFF) wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") expected = [src1_vals[i] if i < 16 else src0_vals[i] for i in range(32)] self.assertEqual(wave.get_vgpr(2), expected) def test_power_of_two_strides(self) -> None: """Power-of-two stride clusters: blocks of 2, 4, 8, 16 divergent lanes.""" for stride in (2, 4, 8, 16): with self.subTest(stride=stride): wave = CndmaskWaveInterpreter(wave_size=32) src0_vals = [1000 + i for i in range(32)] src1_vals = [2000 + i for i in range(32)] wave.init_vgpr(0, src0_vals) wave.init_vgpr(1, src1_vals) vcc = 0 for i in range(32): if (i // stride) % 2 == 1: vcc |= (1 << i) wave.set_vcc(vcc) wave.set_exec(0xFFFFFFFF) wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") expected = [src1_vals[i] if ((i // stride) % 2 == 1) else src0_vals[i] for i in range(32)] self.assertEqual(wave.get_vgpr(2), expected) def test_sparse_single_bit_walk(self) -> None: """Walks each bit 0..31 with only that single lane condition true, then inverted.""" wave = CndmaskWaveInterpreter(wave_size=32) src0 = [0x10 + i for i in range(32)] src1 = [0x80 + i for i in range(32)] wave.init_vgpr(0, src0) wave.init_vgpr(1, src1) wave.set_exec(0xFFFFFFFF) for bit in range(32): wave.set_vcc(1 << bit) wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") expected_one_hot = [src1[i] if i == bit else src0[i] for i in range(32)] self.assertEqual(wave.get_vgpr(2), expected_one_hot) wave.set_vcc(~(1 << bit) & MASK32) wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") expected_one_cold = [src0[i] if i == bit else src1[i] for i in range(32)] self.assertEqual(wave.get_vgpr(2), expected_one_cold) def test_data_dependent_divergence_from_cmp(self) -> None: """Divergence created dynamically by v_cmp_gt_u32.""" wave = CndmaskWaveInterpreter(wave_size=32) # v0 contains lane IDs: 0, 1, 2, ..., 31 wave.init_vgpr(0, list(range(32))) wave.init_vgpr(1, 111) # src0 wave.init_vgpr(2, 222) # src1 wave.set_exec(0xFFFFFFFF) # Condition: lane_id > 10 (lanes 0..10 false, lanes 11..31 true) wave.execute_v_cmp("gt_u32", "v0", 10, dst_mask="vcc") self.assertEqual(wave.vcc, 0xFFFFF800) wave.execute_v_cndmask_e32(dst_v=3, src0="v1", src1="v2") expected = [222 if i > 10 else 111 for i in range(32)] self.assertEqual(wave.get_vgpr(3), expected) def test_destination_register_aliasing(self) -> None: """In-place conditional move: dst == src0 or dst == src1.""" wave = CndmaskWaveInterpreter(wave_size=32) v0_init = [0xAA00 + i for i in range(32)] v1_init = [0xBB00 + i for i in range(32)] wave.init_vgpr(0, v0_init) wave.init_vgpr(1, v1_init) wave.set_vcc(0x55555555) wave.set_exec(0xFFFFFFFF) # dst == src0: v_cndmask_b32 v0, v0, v1, vcc wave.execute_v_cndmask_e32(dst_v=0, src0="v0", src1="v1") expected = [v1_init[i] if (i % 2 == 0) else v0_init[i] for i in range(32)] self.assertEqual(wave.get_vgpr(0), expected) class TestCndmaskExecMaskInteraction(unittest.TestCase): """Verifies EXEC mask gating, non-destructive inactive preservation, and control flow.""" def test_partial_exec_preservation(self) -> None: """Inactive lanes (EXEC[i] == 0) must strictly preserve previous VGPR values.""" wave = CndmaskWaveInterpreter(wave_size=32) background = [0xDEAD0000 + i for i in range(32)] wave.init_vgpr(2, background) wave.init_vgpr(0, 0x11111111) wave.init_vgpr(1, 0x22222222) # Only low 16 lanes are active wave.set_exec(0x0000FFFF) # Checkered VCC across all lanes wave.set_vcc(0x55555555) wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") result = wave.get_vgpr(2) for lane in range(16): expected = 0x22222222 if (lane % 2 == 0) else 0x11111111 self.assertEqual(result[lane], expected) for lane in range(16, 32): self.assertEqual(result[lane], background[lane], f"Lane {lane} was corrupted") def test_zero_exec_wave_nop(self) -> None: """Whole-wave inactive (EXEC == 0): conditional move is a complete no-op.""" wave = CndmaskWaveInterpreter(wave_size=32) initial_dst = [0xCAFEBABE + i for i in range(32)] wave.init_vgpr(2, initial_dst) wave.init_vgpr(0, 0x12345678) wave.init_vgpr(1, 0x87654321) wave.set_exec(0x00000000) wave.set_vcc(0xFFFFFFFF) wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") self.assertEqual(wave.get_vgpr(2), initial_dst) def test_single_active_lane(self) -> None: """Only one lane active in the wave.""" for active_lane in (0, 7, 15, 23, 31): with self.subTest(active_lane=active_lane): wave = CndmaskWaveInterpreter(wave_size=32) bg = [0x5000 + i for i in range(32)] wave.init_vgpr(2, bg) wave.init_vgpr(0, 0x10) wave.init_vgpr(1, 0x20) wave.set_exec(1 << active_lane) wave.set_vcc(1 << active_lane) wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") res = wave.get_vgpr(2) for lane in range(32): if lane == active_lane: self.assertEqual(res[lane], 0x20) else: self.assertEqual(res[lane], bg[lane]) def test_structured_if_then_else_divergence(self) -> None: """Simulates structured divergent branching: v_cmp_gt_u32 -> s_and_saveexec (Then) -> v_cndmask -> s_and (Else) -> v_cndmask -> restore. """ wave = CndmaskWaveInterpreter(wave_size=32) # v0 = lane_id wave.init_vgpr(0, list(range(32))) # Target registers wave.init_vgpr(1, 0xAAAA0000) # then_val wave.init_vgpr(2, 0xBBBB0000) # else_val wave.init_vgpr(3, 0x00000000) # destination # 1. Evaluate condition: lane_id < 16 wave.execute_v_cmp("lt_u32", "v0", 16, dst_mask="vcc") self.assertEqual(wave.vcc, 0x0000FFFF) # 2. Enter THEN branch: s_and_saveexec_b32 s4, vcc_lo wave.execute_s_and_saveexec(dst_s=4, mask_src="vcc") self.assertEqual(wave.exec_mask, 0x0000FFFF) # In THEN block: execute cndmask wave.execute_v_cndmask_e32(dst_v=3, src0=0, src1="v1") # Lanes 0..15 have then_val; lanes 16..31 still 0 for i in range(16): self.assertEqual(wave.vgprs[i][3], 0xAAAA0000) for i in range(16, 32): self.assertEqual(wave.vgprs[i][3], 0x00000000) # 3. Enter ELSE branch: invert mask # EXEC = saved_exec & ~vcc saved_exec = wave.sgprs[4] wave.set_exec(saved_exec & (~wave.vcc & MASK32)) self.assertEqual(wave.exec_mask, 0xFFFF0000) # In ELSE block: execute cndmask with condition inverted wave.set_vcc(~wave.vcc & MASK32) wave.execute_v_cndmask_e32(dst_v=3, src0=0, src1="v2") # 4. Re-converge: restore EXEC wave.set_exec(saved_exec) self.assertEqual(wave.exec_mask, 0xFFFFFFFF) # Both halves must have their respective values intact res = wave.get_vgpr(3) expected = [0xAAAA0000 if i < 16 else 0xBBBB0000 for i in range(32)] self.assertEqual(res, expected) def test_orthogonal_exec_and_vcc(self) -> None: """Outer EXEC disabling lanes 16..31 while inner VCC alternates.""" wave = CndmaskWaveInterpreter(wave_size=32) initial = [0x77770000 + i for i in range(32)] wave.init_vgpr(3, initial) wave.init_vgpr(1, 0x1111) wave.init_vgpr(2, 0x2222) wave.set_exec(0x0000FFFF) # lanes 16..31 disabled wave.set_vcc(0x55555555) # alternating VCC wave.execute_v_cndmask_e32(dst_v=3, src0="v1", src1="v2") res = wave.get_vgpr(3) for lane in range(16): self.assertEqual(res[lane], 0x2222 if (lane % 2 == 0) else 0x1111) for lane in range(16, 32): self.assertEqual(res[lane], initial[lane]) class TestCndmaskWave64Divergence(unittest.TestCase): """Verifies 64-lane wave execution, cross-half divergence, and 64-bit masks.""" def test_wave64_uniform_conditions(self) -> None: """Wave64 with all 64 lanes active: uniform false and true.""" wave = CndmaskWaveInterpreter(wave_size=64) src0 = [0x100 + i for i in range(64)] src1 = [0x200 + i for i in range(64)] wave.init_vgpr(0, src0) wave.init_vgpr(1, src1) wave.set_exec(MASK64) wave.set_vcc(0) wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") self.assertEqual(wave.get_vgpr(2), src0) wave.set_vcc(MASK64) wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") self.assertEqual(wave.get_vgpr(2), src1) def test_wave64_cross_half_divergence(self) -> None: """Low half (lanes 0..31) has pattern A, high half (lanes 32..63) has pattern B.""" wave = CndmaskWaveInterpreter(wave_size=64) src0 = [0x1000 + i for i in range(64)] src1 = [0x2000 + i for i in range(64)] wave.init_vgpr(0, src0) wave.init_vgpr(1, src1) wave.set_exec(MASK64) # Low half VCC: 0x55555555 (even lanes true) # High half VCC: 0xAAAAAAAA (odd lanes true) vcc64 = 0x55555555 | (0xAAAAAAAA << 32) wave.set_vcc(vcc64) wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") expected = [] for lane in range(64): c = (vcc64 >> lane) & 1 expected.append(src1[lane] if c else src0[lane]) self.assertEqual(wave.get_vgpr(2), expected) def test_wave64_half_disabled_wave(self) -> None: """Wave64 with low-half active only, or high-half active only.""" wave = CndmaskWaveInterpreter(wave_size=64) bg = [0x9900 + i for i in range(64)] wave.init_vgpr(2, bg) wave.init_vgpr(0, 0x11) wave.init_vgpr(1, 0x22) wave.set_vcc(MASK64) # Low half active only wave.set_exec(0x00000000FFFFFFFF) wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") res = wave.get_vgpr(2) self.assertEqual(res[:32], [0x22] * 32) self.assertEqual(res[32:], bg[32:]) # Reset and high half active only wave.init_vgpr(2, bg) wave.set_exec(0xFFFFFFFF00000000) wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") res = wave.get_vgpr(2) self.assertEqual(res[:32], bg[:32]) self.assertEqual(res[32:], [0x22] * 32) def test_wave64_boundary_lanes(self) -> None: """Verifies boundary lanes 31 (end of low half) and 32 (start of high half).""" wave = CndmaskWaveInterpreter(wave_size=64) src0 = [1000 + i for i in range(64)] src1 = [2000 + i for i in range(64)] wave.init_vgpr(0, src0) wave.init_vgpr(1, src1) wave.set_exec(MASK64) # Only lane 31 and 32 set in VCC wave.set_vcc((1 << 31) | (1 << 32)) wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") res = wave.get_vgpr(2) for i in range(64): if i in (31, 32): self.assertEqual(res[i], src1[i]) else: self.assertEqual(res[i], src0[i]) def test_wave64_randomized_divergence_stress(self) -> None: """50 pseudo-random 64-bit masks cross-checked against reference oracle.""" rng = random.Random(20261122) for trial in range(50): with self.subTest(trial=trial): wave = CndmaskWaveInterpreter(wave_size=64) src0 = [rng.getrandbits(32) for _ in range(64)] src1 = [rng.getrandbits(32) for _ in range(64)] prev = [rng.getrandbits(32) for _ in range(64)] cond = rng.getrandbits(64) exec_m = rng.getrandbits(64) wave.init_vgpr(0, src0) wave.init_vgpr(1, src1) wave.init_vgpr(2, prev) wave.set_vcc(cond) wave.set_exec(exec_m) wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") oracle_expected = ref_cndmask_wave(src0, src1, cond, exec_m, prev, wave_size=64) self.assertEqual(wave.get_vgpr(2), oracle_expected) class TestCndmaskE64Encoding(unittest.TestCase): """Verifies v_cndmask_b32_e64 with explicit condition masks (SGPRs).""" def test_e64_with_sgpr_scalar_mask(self) -> None: """e64 encoding reading condition mask from SGPR s4.""" wave = CndmaskWaveInterpreter(wave_size=32) src0 = [0x10 + i for i in range(32)] src1 = [0x50 + i for i in range(32)] wave.init_vgpr(0, src0) wave.init_vgpr(1, src1) wave.set_exec(0xFFFFFFFF) # Condition mask in s4 = 0x00FF00FF wave.sgprs[4] = 0x00FF00FF # VCC intentionally set to 0 to verify s4 is used, not VCC wave.set_vcc(0x00000000) wave.execute_v_cndmask_e64(dst_v=2, src0="v0", src1="v1", cond_src="s4") expected = [src1[i] if ((0x00FF00FF >> i) & 1) else src0[i] for i in range(32)] self.assertEqual(wave.get_vgpr(2), expected) self.assertEqual(wave.vcc, 0, "VCC was modified by e64 reading SGPR") def test_e64_distinct_condition_registers(self) -> None: """Multiple e64 instructions using different SGPRs in sequence.""" wave = CndmaskWaveInterpreter(wave_size=32) wave.init_vgpr(0, 10) wave.init_vgpr(1, 20) wave.init_vgpr(2, 30) wave.set_exec(0xFFFFFFFF) wave.sgprs[4] = 0x0000FFFF wave.sgprs[6] = 0xFFFF0000 wave.execute_v_cndmask_e64(dst_v=10, src0="v0", src1="v1", cond_src="s4") wave.execute_v_cndmask_e64(dst_v=11, src0="v0", src1="v2", cond_src="s6") exp10 = [20 if i < 16 else 10 for i in range(32)] exp11 = [30 if i >= 16 else 10 for i in range(32)] self.assertEqual(wave.get_vgpr(10), exp10) self.assertEqual(wave.get_vgpr(11), exp11) class TestCndmaskSpirvTranslation(unittest.TestCase): """Verifies end-to-end SPIR-V translation and execution via rdna2spirv & spirv_mini_interp.""" def test_spirv_e32_true_false_selection(self) -> None: """Translates v_cndmask_b32_e32 with true and false conditions.""" # True condition (vcc_lo = 1): selects src1 lines_true = [ "v_mov_b32 v10, 42", "v_mov_b32 v11, 99", "v_cmp_eq_u32_e32 vcc_lo, 1, 1", "v_cndmask_b32_e32 v0, v10, v11, vcc_lo", "v_mov_b32 v1, 0", "v_mov_b32 v2, 0", "v_mov_b32 v3, 0", ] out_true = run_synthetic_ps(lines_true) self.assertEqual(out_true[0], 99) # False condition (vcc_lo = 0): selects src0 lines_false = [ "v_mov_b32 v10, 42", "v_mov_b32 v11, 99", "v_cmp_eq_u32_e32 vcc_lo, 1, 0", "v_cndmask_b32_e32 v0, v10, v11, vcc_lo", "v_mov_b32 v1, 0", "v_mov_b32 v2, 0", "v_mov_b32 v3, 0", ] out_false = run_synthetic_ps(lines_false) self.assertEqual(out_false[0], 42) def test_spirv_e64_sgpr_condition_mask(self) -> None: """Translates v_cndmask_b32_e64 with SGPR condition mask.""" lines = [ "s_mov_b32 s4, 1", "s_mov_b32 s6, 0", "v_mov_b32 v10, 100", "v_mov_b32 v11, 200", "v_cndmask_b32_e64 v0, v10, v11, s4", "v_cndmask_b32_e64 v1, v10, v11, s6", "v_mov_b32 v2, 0", "v_mov_b32 v3, 0", ] out = run_synthetic_ps(lines) self.assertEqual(out[0], 200, "e64 with s4=1 should select src1") self.assertEqual(out[1], 100, "e64 with s6=0 should select src0") def test_spirv_immediate_sources(self) -> None: """v_cndmask_b32 with immediate values 0 and 1 (carry extraction idiom).""" lines = [ "v_cmp_gt_u32_e32 vcc_lo, 5, 3", "v_cndmask_b32_e32 v0, 0, 1, vcc_lo", "v_cmp_gt_u32_e32 vcc_lo, 3, 5", "v_cndmask_b32_e32 v1, 0, 1, vcc_lo", "v_mov_b32 v2, 0", "v_mov_b32 v3, 0", ] out = run_synthetic_ps(lines) self.assertEqual(out[0], 1) self.assertEqual(out[1], 0) def test_spirv_multiplexer_min_max(self) -> None: """Constructs branchless min and max using v_cmp and v_cndmask.""" test_pairs = [(10, 20), (50, 30), (0, 0xFFFFFFFF), (0x7FFFFFFF, 0x80000000)] for a, b in test_pairs: lines = [ f"v_mov_b32 v10, {a:#x}", f"v_mov_b32 v11, {b:#x}", "v_cmp_lt_u32_e32 vcc_lo, v10, v11", # min: if a < b select a (src1) else b (src0) -> v_cndmask_b32 v0, b, a "v_cndmask_b32_e32 v0, v11, v10, vcc_lo", # max: if a < b select b (src1) else a (src0) -> v_cndmask_b32 v1, a, b "v_cndmask_b32_e32 v1, v10, v11, vcc_lo", "v_mov_b32 v2, 0", "v_mov_b32 v3, 0", ] out = run_synthetic_ps(lines) expected_min = min(a, b) expected_max = max(a, b) self.assertEqual(out[0], expected_min) self.assertEqual(out[1], expected_max) def test_spirv_cascaded_ternary_select(self) -> None: """Chained conditional moves selecting between 3 candidate values.""" # if x == 1 -> 100; elif x == 2 -> 200; else -> 300 for x_val, expected in ((1, 100), (2, 200), (3, 300), (0, 300)): lines = [ f"v_mov_b32 v10, {x_val}", # default = 300 "v_mov_b32 v20, 300", # check x == 2 -> select 200 else default "v_cmp_eq_u32_e32 vcc_lo, 2, v10", "v_cndmask_b32_e32 v21, v20, 200, vcc_lo", # check x == 1 -> select 100 else v21 "v_cmp_eq_u32_e32 vcc_lo, 1, v10", "v_cndmask_b32_e32 v0, v21, 100, vcc_lo", "v_mov_b32 v1, 0", "v_mov_b32 v2, 0", "v_mov_b32 v3, 0", ] out = run_synthetic_ps(lines) self.assertEqual(out[0], expected) class TestCndmaskNegativeControls(unittest.TestCase): """Negative controls and sensitivity verification against corruptions.""" def test_vcc_inversion_mutation(self) -> None: """Inverting VCC must invert selection for every differing lane.""" wave = CndmaskWaveInterpreter(wave_size=32) s0 = [0x100 + i for i in range(32)] s1 = [0x200 + i for i in range(32)] wave.init_vgpr(0, s0) wave.init_vgpr(1, s1) wave.set_exec(0xFFFFFFFF) vcc = 0x12345678 wave.set_vcc(vcc) wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") res_normal = wave.get_vgpr(2) wave.set_vcc(~vcc & MASK32) wave.execute_v_cndmask_e32(dst_v=3, src0="v0", src1="v1") res_inverted = wave.get_vgpr(3) self.assertNotEqual(res_normal, res_inverted) for i in range(32): self.assertNotEqual(res_normal[i], res_inverted[i]) def test_exec_clearing_prevents_updates(self) -> None: """Clearing EXEC mask ensures destination is completely unmodified.""" wave = CndmaskWaveInterpreter(wave_size=32) init_val = [0xFEED0000 + i for i in range(32)] wave.init_vgpr(2, init_val) wave.init_vgpr(0, 1) wave.init_vgpr(1, 2) wave.set_vcc(0xFFFFFFFF) wave.set_exec(0x00000000) # corrupt EXEC to 0 wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") self.assertEqual(wave.get_vgpr(2), init_val) def test_single_bit_flip_sensitivity(self) -> None: """Flipping exactly one bit in VCC alters strictly and only that lane.""" wave = CndmaskWaveInterpreter(wave_size=32) s0 = [10 + i for i in range(32)] s1 = [90 + i for i in range(32)] wave.init_vgpr(0, s0) wave.init_vgpr(1, s1) wave.set_exec(0xFFFFFFFF) base_vcc = 0x55555555 wave.set_vcc(base_vcc) wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") base_res = wave.get_vgpr(2) for flip_lane in range(32): flipped_vcc = base_vcc ^ (1 << flip_lane) wave.set_vcc(flipped_vcc) wave.execute_v_cndmask_e32(dst_v=3, src0="v0", src1="v1") flipped_res = wave.get_vgpr(3) for lane in range(32): if lane == flip_lane: self.assertNotEqual(flipped_res[lane], base_res[lane]) else: self.assertEqual(flipped_res[lane], base_res[lane]) if __name__ == "__main__": unittest.main()