Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/design.md

Large diffs are not rendered by default.

182 changes: 182 additions & 0 deletions tests/semantic/test_mask_as_data.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
"""Value tests for a lane mask read as a number (SHADER-MASK-AS-DATA, crosslane_fuzz.py "maskdata").

On hardware a lane mask is one word for the wave, a bit per lane; the translator keeps only each lane's own bit
(0 / ~0), so a 32-bit integer op that reads the mask has to rebuild the word. Wave32 and native wave64 run one whole
subgroup in spirv_mini_interp.py. Standard library only; no GPU, no LLVM, no game files.
"""
import os
import struct
import sys
import unittest

HERE = os.path.dirname(os.path.abspath(__file__))
sys.dont_write_bytecode = True
sys.path.insert(0, HERE)

import spirv_mini_interp as si # noqa: E402
import support # noqa: E402

rdna2spirv = support.rdna2spirv
M32 = 0xFFFFFFFF
K = 0x1234


def fssm_for(wave):
fssm = bytearray(0x148)
fssm[:4] = b"FSSM"
struct.pack_into("<I", fssm, 0xD4, 0x20 if wave == 32 else 0)
struct.pack_into("<4I", fssm, 0x138, 0x8088, wave, 1, 1)
return bytes(fssm)


TAIL = ["v_lshlrev_b32_e32 v9, 2, v0", "buffer_store_dword v4, v9, s[0:3], 0 offen", "s_endpgm"]


def translate(lines, wave):
return support.translate_lines("cs_mask_data", lines + TAIL, fssm=fssm_for(wave))


def run(lines, wave):
"""v4 of every lane."""
memory = si.run_workgroup(translate(lines, wave), wave, wave,
inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i},
push_constants=[0, 0, 0x1000, 0x31016FAC] + [0] * 28, memory={})
return [memory[4 * lane] for lane in range(wave)]


def mask_setup(wave, lanes):
"""(lines, [(source register, its word)]) for a mask of the lanes below `lanes`, in an SGPR and in VCC."""
bits = (1 << lanes) - 1
if wave == 32:
return [f"v_cmp_gt_u32_e64 s10, {lanes}, v0", f"v_cmp_gt_u32_e32 vcc_lo, {lanes}, v0"], \
[("s10", bits), ("vcc_lo", bits)]
return [f"v_cmp_gt_u32_e64 s[10:11], {lanes}, v0", f"v_cmp_gt_u32_e32 vcc, {lanes}, v0"], \
[("s10", bits & M32), ("s11", bits >> 32), ("vcc_lo", bits & M32), ("vcc_hi", bits >> 32)]


def signed(x):
return x - (1 << 32) if x >> 31 else x


SCALAR = {
"s_add_u32 s20, {m}, 0x1234": lambda m: m + K,
"s_add_i32 s20, 0x1234, {m}": lambda m: m + K,
"s_sub_u32 s20, {m}, 0x1234": lambda m: m - K,
"s_sub_i32 s20, 0x1234, {m}": lambda m: K - m,
"s_mul_i32 s20, {m}, 0x1234": lambda m: m * K,
"s_mul_hi_u32 s20, {m}, 0x1234": lambda m: (m * K) >> 32,
"s_lshl_b32 s20, {m}, 3": lambda m: m << 3,
"s_lshr_b32 s20, {m}, 3": lambda m: m >> 3,
"s_ashr_i32 s20, {m}, 3": lambda m: signed(m) >> 3,
"s_bfe_u32 s20, {m}, 0x60002": lambda m: (m >> 2) & 63,
"s_min_u32 s20, {m}, 0x1234": lambda m: min(m, K),
"s_max_u32 s20, {m}, 0x1234": lambda m: max(m, K),
"s_brev_b32 s20, {m}": lambda m: int(f"{m:032b}"[::-1], 2),
"s_lshl2_add_u32 s20, {m}, 0x1234": lambda m: (m << 2) + K,
}
VECTOR = {
"v_mov_b32_e32 v4, {m}": lambda m: m,
"v_add_nc_u32_e32 v4, {m}, v3": lambda m: m + K,
"v_sub_nc_u32_e32 v4, {m}, v3": lambda m: m - K,
"v_subrev_nc_u32_e32 v4, {m}, v3": lambda m: K - m,
"v_lshlrev_b32_e64 v4, 3, {m}": lambda m: m << 3,
"v_lshrrev_b32_e64 v4, 3, {m}": lambda m: m >> 3,
"v_ashrrev_i32_e64 v4, 3, {m}": lambda m: signed(m) >> 3,
"v_mul_lo_u32 v4, {m}, v3": lambda m: m * K,
"v_min_u32_e32 v4, {m}, v3": lambda m: min(m, K),
"v_max_u32_e32 v4, {m}, v3": lambda m: max(m, K),
"v_bfe_u32 v4, {m}, 2, 6": lambda m: (m >> 2) & 63,
"v_add3_u32 v4, {m}, v3, v3": lambda m: m + 2 * K,
"v_lshl_add_u32 v4, {m}, 2, v3": lambda m: (m << 2) + K,
"v_bcnt_u32_b32 v4, {m}, v3": lambda m: bin(m).count("1") + K,
}


class MaskAsDataTests(unittest.TestCase):
def check(self, lines, wave, want):
self.assertEqual({hex(x) for x in run(lines, wave)}, {hex(want & M32)})

def test_scalar_ops(self):
for wave, lanes in ((32, 10), (64, 43)):
setup, sources = mask_setup(wave, lanes)
for (op, fn), (reg, word) in ((o, s) for o in SCALAR.items() for s in sources):
with self.subTest(wave=wave, op=op, reg=reg):
self.check(setup + [op.format(m=reg), "v_mov_b32_e32 v4, s20"], wave, fn(word))

def test_vector_ops(self):
for wave, lanes in ((32, 10), (64, 43)):
setup, sources = mask_setup(wave, lanes)
for (op, fn), (reg, word) in ((o, s) for o in VECTOR.items() for s in sources):
with self.subTest(wave=wave, op=op, reg=reg):
self.check(setup + [f"v_mov_b32_e32 v3, {K:#x}", op.format(m=reg)], wave, fn(word))

def test_exec_as_data(self):
self.check(["v_mov_b32_e32 v4, exec_lo"], 32, M32)
self.check(["v_cmp_gt_u32_e32 vcc_lo, 10, v0", "s_and_saveexec_b32 s12, vcc_lo", "s_add_u32 s20, exec_lo, 1",
"s_mov_b32 exec_lo, s12", "v_mov_b32_e32 v4, s20"], 32, 0x400)

def test_copied_mask(self):
self.check(["v_cmp_gt_u32_e64 s10, 10, v0", "s_mov_b32 s11, s10", "s_add_u32 s20, s11, 1",
"v_mov_b32_e32 v4, s20"], 32, 0x400)

def test_both_sources_are_masks(self):
self.check(["v_cmp_gt_u32_e64 s10, 10, v0", "v_cmp_gt_u32_e64 s11, 4, v0", "s_sub_u32 s20, s10, s11",
"v_mov_b32_e32 v4, s20"], 32, 0x3FF - 0xF)

def test_v_mov_under_exec_keeps_inactive_lanes_and_sees_every_lane(self):
# lanes 5-31 are off at the v_mov: they keep v4, and the active lanes still get the whole 10-lane mask
got = run(["v_mov_b32_e32 v4, 7", "v_cmp_gt_u32_e64 s10, 10, v0", "v_cmp_gt_u32_e32 vcc_lo, 5, v0",
"s_and_saveexec_b32 s12, vcc_lo", "v_mov_b32_e32 v4, s10", "s_mov_b32 exec_lo, s12"], 32)
self.assertEqual(got, [0x3FF] * 5 + [7] * 27)

def test_a_mask_that_goes_through_a_vgpr_stays_a_mask(self):
# v_mov / v_or3 / v_readfirstlane and back into EXEC: the idiom keeps each lane's own bit, no rebuild
lines = ["v_cmp_gt_u32_e64 s10, 10, v0", "v_cmp_lt_u32_e64 s11, 20, v0", "v_mov_b32_e32 v5, s10",
"v_or3_b32 v5, v5, s11, s11", "v_readfirstlane_b32 s14, v5", "v_mov_b32_e32 v4, 1",
"s_and_saveexec_b32 s12, s14", "v_mov_b32_e32 v4, 2", "s_mov_b32 exec_lo, s12"]
self.assertEqual(run(lines, 32), [2 if i < 10 or i > 20 else 1 for i in range(32)])

def test_a_register_reused_for_another_mask(self):
# v5 goes through the idiom first; the second mask copied into it is only read as a number
lines = ["v_cmp_gt_u32_e64 s10, 10, v0", "v_mov_b32_e32 v5, s10", "v_readfirstlane_b32 s14, v5",
"v_cmp_gt_u32_e64 s11, 4, v0", "v_mov_b32_e32 v5, s11", "v_add_nc_u32_e32 v4, 1, v5"]
self.check(lines, 32, 0x10)

def test_a_number_before_the_register_is_used_for_the_idiom(self):
lines = ["v_cmp_gt_u32_e64 s11, 4, v0", "v_mov_b32_e32 v5, s11", "v_add_nc_u32_e32 v4, 1, v5",
"v_cmp_gt_u32_e64 s10, 10, v0", "v_mov_b32_e32 v5, s10", "v_readfirstlane_b32 s14, v5",
"s_and_saveexec_b32 s12, s14", "v_mov_b32_e32 v4, 2", "s_mov_b32 exec_lo, s12"]
self.assertEqual(run(lines, 32), [2 if i < 10 else 0x10 for i in range(32)])

def test_copies_of_the_vgpr(self):
# a chain of VGPR copies read as a number, and one that ends in the idiom
head = ["v_cmp_gt_u32_e64 s10, 10, v0", "v_mov_b32_e32 v5, s10", "v_mov_b32_e32 v6, v5"]
self.check(head + ["v_mov_b32_e32 v4, v6"], 32, 0x3FF)
self.assertEqual(run(head + ["v_mov_b32_e32 v4, 1", "v_readfirstlane_b32 s14, v6", "s_and_saveexec_b32 s12, s14",
"v_mov_b32_e32 v4, 2", "s_mov_b32 exec_lo, s12"], 32),
[2 if i < 10 else 1 for i in range(32)])

def test_two_moves_that_meet_at_a_mask_read(self):
# one of two copies on two paths, then read as a mask: both keep the lane's own bit
lines = ["v_cmp_gt_u32_e64 s10, 10, v0", "v_cmp_gt_u32_e64 s11, 4, v0", "v_mov_b32_e32 v5, s10",
"v_mov_b32_e32 v6, s11", "v_or_b32_e32 v5, v5, v6", "v_readfirstlane_b32 s14, v5",
"v_mov_b32_e32 v4, 1", "s_and_saveexec_b32 s12, s14", "v_mov_b32_e32 v4, 2", "s_mov_b32 exec_lo, s12"]
self.assertEqual(run(lines, 32), [2 if i < 10 else 1 for i in range(32)])

def test_plain_data_is_untouched(self):
lines = ["s_mov_b32 s10, 0x3ff", "s_add_u32 s20, s10, 1", "v_mov_b32_e32 v4, s20"]
self.check(lines, 32, 0x400)
self.assertNotIn("OpGroupNonUniform", translate(lines, 32))

def test_wave64_emulate_translates_with_an_exchange(self):
old = rdna2spirv.WAVE64_EMULATE
rdna2spirv.WAVE64_EMULATE = True
try:
spv = translate(["v_cmp_gt_u32_e64 s[10:11], 43, v0", "s_add_u32 s20, s11, 1", "v_mov_b32_e32 v4, s20"], 64)
finally:
rdna2spirv.WAVE64_EMULATE = old
self.assertIn("%x_buf", spv)


if __name__ == "__main__":
unittest.main()
4 changes: 2 additions & 2 deletions tests/semantic/test_salu64_bitwise_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -558,9 +558,9 @@ def test_wave32_all_six_ops_and_scc_vote(self):
"v_mov_b32 v3, 0",
]
outs, _ = run_ps_wave(lines, wave=32)
want_word = sum(1 << lane for lane in range(32) if pred(lane)) # v_mov_b32 reads the mask's word
for lane in range(32):
want_bit = MASK32 if pred(lane) else 0
self.assertEqual(outs[lane], (want_cnt, want_scc, want_bit, 0), f"lane={lane}")
self.assertEqual(outs[lane], (want_cnt, want_scc, want_word, 0), f"lane={lane}")

# Empty mask intersection -> SCC=0 across all lanes, and null dst on lane-mask path sets SCC.
lines = [
Expand Down
2 changes: 1 addition & 1 deletion tests/semantic/test_salu_movrels_lane_mask.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ def test_finding_reproducer(self):
with self.subTest(lane=lane):
self.assertEqual((d, bits), (5, 2))
self.assertEqual(ctl_bits, 2)
self.assertEqual(ctl_d, 0xFFFFFFFF if lane in (0, 2) else 0) # a copy stays a mask
self.assertEqual(ctl_d, 5) # the copy stays a mask; store()'s v_mov reads its word

def test_index_from_m0_hits_mask_and_data_neighbours(self):
# s10 data, s11 a v_cmp mask (lanes 1, 4, 9), s12 data; M0 picks each in turn from a base of s9.
Expand Down
2 changes: 1 addition & 1 deletion tests/semantic/test_scselect_b64_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -383,7 +383,7 @@ def test_wave32_vcc_exec_and_sgpr_masks(self):
for lane in range(32):
in_mask = (lane < 10) if scc else (lane >= 16)
want_v1 = 0x55 if (scc == 0 or in_mask) else 0xAA
want_s4 = MASK32 if in_mask else 0
want_s4 = 0x3FF if scc else 0xFFFF0000 # v_mov_b32 reads the mask's word
self.assertEqual(outs[lane], (want_cnt, want_v1, scc, want_s4), f"lane={lane}")

def test_wave64_vcc_exec_and_sgpr_masks(self):
Expand Down
6 changes: 1 addition & 5 deletions tests/semantic/test_slot67_operand_forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,7 @@ def test_wave64_bitreplicate_exec_reenables_lanes_and_keeps_scc(self):
expected = {i * 4: 7 for i in (0, 1, 32, 33, 62, 63)}
self.assertEqual(_run_cs("cs_bitreplicate_exec", lines), expected)

# The merge into main kept main's wave32 VCC_HI model (47494e725: VCC_HI that holds a compare result is a
# per-lane mask), not this branch's packed-word form (1f001c739). On hardware `s_mov_b32 s8, vcc_hi` copies the
# packed 32-bit word (0x80000004 here); main's translator gives each lane its own mask value instead, so this
# case fails there. Kept as the expectation the translator should meet.
@unittest.expectedFailure
# `s_mov_b32 s8, vcc_hi` then `v_mov_b32 v1, s8` is the packed 32-bit word (0x80000004 here): SHADER-MASK-AS-DATA.
def test_wave32_compare_high_word_preserves_low_and_clears_inactive_bits(self):
lines = [
"v_cmp_lt_u32_e64 vcc_lo, v0, 6",
Expand Down
94 changes: 89 additions & 5 deletions tools/lane_masks.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,19 @@
VECTOR_BITWISE = ("v_mov_b32", "v_or3_b32", "v_or_b32", "v_and_b32", "v_and_or_b32",
"v_xor_b32", "v_xor3_b32", "v_xnor_b32", "v_bfi_b32", "v_not_b32")

# 32-bit integer ops that use their sources as numbers: a lane mask they read has to be the wave's mask word, so the
# translator rebuilds it from the lanes' bits (SHADER-MASK-AS-DATA). Bitwise ops, selects and compares are not here:
# they work on the lane's own bit, or have a mask path of their own.
NUMBER_READERS = frozenset((
"s_add_u32", "s_add_i32", "s_sub_u32", "s_sub_i32", "s_addc_u32", "s_subb_u32", "s_mul_i32", "s_mul_hi_u32",
"s_mul_hi_i32", "s_lshl_b32", "s_lshr_b32", "s_ashr_i32", "s_bfe_u32", "s_bfe_i32", "s_min_u32", "s_min_i32",
"s_max_u32", "s_max_i32", "s_brev_b32", "s_lshl1_add_u32", "s_lshl2_add_u32", "s_lshl3_add_u32",
"s_lshl4_add_u32",
"v_add_nc_u32", "v_sub_nc_u32", "v_subrev_nc_u32", "v_lshlrev_b32", "v_lshrrev_b32", "v_ashrrev_i32",
"v_mul_lo_u32", "v_mul_hi_u32", "v_min_u32", "v_max_u32", "v_min_i32", "v_max_i32", "v_bfe_u32", "v_bfe_i32",
"v_add3_u32", "v_lshl_add_u32", "v_add_lshl_u32", "v_bcnt_u32_b32",
))


def base_op(op):
for suffix in ("_e32", "_e64", "_sdwa", "_dpp"):
Expand Down Expand Up @@ -152,7 +165,78 @@ def wave32_vcc_pair_op(op, args):
return len(args) == 3 and vcc[0] and ((vcc[1] and pairs[2]) or (pairs[1] and vcc[2]))


def step(state, ins, wave64=True):
def mask_word_source(state, a, wave64=True):
"""Whether operand `a` is one 32-bit scalar register that holds a lane mask (or half of one) in `state`."""
if a["k"] == "special":
t = a.get("t", "")
if t == "exec_lo" or (t == "exec_hi" and wave64):
return True
if t in ("vcc_lo", "vcc_hi"):
return state.get("vcc_hi" if t == "vcc_hi" and not wave64 else "vcc") in MASK_KINDS
return False
return a["k"] == "sgpr" and a.get("n", 1) == 1 and state.get(a["r"]) in MASK_KINDS


def _plain_move(ins):
a = ins["args"]
return (base_op(ins["op"]) == "v_mov_b32" and not ins["op"].endswith(("_sdwa", "_dpp", "_dpp8")) and len(a) == 2
and not ins.get("mods") and a[0]["k"] == "vgpr"
and not any(a[1].get(m) for m in ("neg", "abs", "sext")))


def number_moves(blocks, succ, masks, wave64=True):
"""The v_mov_b32 of a mask into a VGPR whose value nothing reads as a mask: ids of the instructions.

A value is read as a mask when a vector bitwise op or v_readfirstlane reads the VGPR while it holds one (the
v_mov / v_or3 / v_readfirstlane idiom). Each move is followed forward, through VGPR copies, while the register holds
a mask, so reuse of the register for another mask does not matter; moves that meet at such a read are all left as they were."""
moves = {id(ins): ins["args"][0]["r"] for blk in blocks for ins in blk
if _plain_move(ins) and mask_word_source(masks.get(id(ins), {}), ins["args"][1], wave64)}
if not moves:
return set()
used, entry = set(), [None] * len(blocks) # entry: VGPR -> the moves whose value it may hold
entry[0] = {}
work = [0]
while work:
n = work.pop()
reach = dict(entry[n])
for ins in blocks[n]:
op, a, state = base_op(ins["op"]), ins["args"], masks.get(id(ins), {})
reach = {r: ids for r, ids in reach.items() if ("v", r) in state}
copied = None
if _plain_move(ins) and a[1]["k"] == "vgpr":
copied = reach.get(a[1]["r"]) # a copy of the value: what reads the copy decides
elif id(ins) not in moves and (op in VECTOR_BITWISE or op == "v_readfirstlane_b32"):
for x in a[1:]:
if x["k"] == "vgpr":
used |= reach.get(x["r"], frozenset())
if id(ins) in moves:
reach[moves[id(ins)]] = frozenset((id(ins),))
elif a and a[0]["k"] == "vgpr": # written again: a mask computed in the VGPR is not a move
for r in range(a[0]["r"], a[0]["r"] + a[0].get("n", 1)):
reach.pop(r, None)
if copied:
reach[a[0]["r"]] = copied
for s in succ[n]:
old = entry[s]
merged = dict(old or {})
for r, ids in reach.items():
merged[r] = merged.get(r, frozenset()) | ids
if old is None or merged != old:
entry[s] = merged
work.append(s)
return set(moves) - used


def mask_word_operands(ins, state, moves=frozenset(), wave64=True):
"""Indices of the operands of `ins` that read a lane mask as a number."""
op, a = base_op(ins["op"]), ins["args"]
if id(ins) not in moves and (op not in NUMBER_READERS or ins["op"].endswith(("_sdwa", "_dpp", "_dpp8"))):
return ()
return tuple(i for i in range(1, len(a)) if mask_word_source(state, a[i], wave64))


def step(state, ins, wave64=True, moves=frozenset()):
"""Update `state` (register -> MASK | MASK_LO | MASK_HI | EITHER) for one instruction. True if it writes a mask to a VGPR.

`wave64` False: the program runs in 32-lane waves, where a 64-bit s_bfm_b64 result can't be a lane mask."""
Expand Down Expand Up @@ -224,7 +308,7 @@ def step(state, ins, wave64=True):
written = range(a[0]["r"], a[0]["r"] + a[0].get("n", 1))
for key in [k for k in state if isinstance(k, tuple) and k[1] in written]:
del state[key]
if None not in kinds and any(k in MASK_KINDS for k in kinds):
if id(ins) not in moves and None not in kinds and any(k in MASK_KINDS for k in kinds):
ms = {k for k in kinds if k in MASK_KINDS}
state[("v", a[0]["r"])] = ms.pop() if len(ms) == 1 else MASK
# A plain copy (v_mov_b32) is an ordinary VALU write: inactive lanes keep the old
Expand Down Expand Up @@ -288,7 +372,7 @@ def parked(blocks, masks):
return sorted(found)


def analyse(blocks, succ, *, include_either=False, wave64=True):
def analyse(blocks, succ, *, include_either=False, wave64=True, moves=frozenset()):
entry = [None] * len(blocks) # None: not reached yet
if blocks:
entry[0] = {}
Expand All @@ -297,7 +381,7 @@ def analyse(blocks, succ, *, include_either=False, wave64=True):
n = work.pop()
state = dict(entry[n])
for ins in blocks[n]:
step(state, ins, wave64)
step(state, ins, wave64, moves)
for s in succ[n]:
if entry[s] is None:
merged = dict(state)
Expand All @@ -323,6 +407,6 @@ def analyse(blocks, succ, *, include_either=False, wave64=True):
out[id(ins)] = {r: k for r, k in state.items() if k in MASK_KINDS}
if include_either:
either[id(ins)] = {r for r, k in state.items() if k == EITHER}
if step(state, ins, wave64):
if step(state, ins, wave64, moves):
writes.add(id(ins))
return (out, writes, either) if include_either else (out, writes)
Loading
Loading