upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/tools/buffer_swizzle_probe.py
diff options
context:
space:
mode:
authorVonsek <45567075+Vonsek@users.noreply.github.com>2026-11-22 19:07:53 +0100
committerVonsek <45567075+Vonsek@users.noreply.github.com>2026-11-22 19:07:53 +0100
commit46a196cde9328e2a232ee15c19556eb962cda0ab (patch)
treed1cd03326530912d925ee1a7ba7fa735006f004f /tools/buffer_swizzle_probe.py
parentd3fab00a78967adf357596996190afdf33dc09d5 (diff)
parentec8ec4c9a46c6623f1a9c125afd3566da97f1e0c (diff)
Merge upstream main into first-light shader identity
Diffstat (limited to 'tools/buffer_swizzle_probe.py')
-rw-r--r--tools/buffer_swizzle_probe.py665
1 files changed, 665 insertions, 0 deletions
diff --git a/tools/buffer_swizzle_probe.py b/tools/buffer_swizzle_probe.py
new file mode 100644
index 000000000..16c5c8a75
--- /dev/null
+++ b/tools/buffer_swizzle_probe.py
@@ -0,0 +1,665 @@
1r"""SHADER-343: Native RDNA2 hardware probe for swizzled buffer addressing (V# SWIZZLE_ENABLE, ADD_TID_ENABLE).
2
3Runs self-contained MUBUF/MTBUF buffer-swizzle kernels natively on an AMD GPU through tools/hw_oracle (wave32 and
4wave64) and compares every output word with Leonida's live translator (tools/rdna2spirv.py ->
5tests/semantic/spirv_mini_interp.py). Standard library only; no game files.
6
7Groups covered (docs/design.md, Swizzled buffer addressing):
8 swizzle_basic IS=8/16/32/64 formula, index >= IS, non-4-mult stride, inst_offset, mode 0 soffset, stride 0
9 idxen_ignores_tid idxen=1 ignores ADD_TID_ENABLE (linear & swizzled, address & bounds, load/typed/atomic)
10 swizzle_activation SWIZZLE_ENABLE=1 with idxen=0 and ADD_TID_ENABLE=0 stays linear and RAW in mode 3
11 multi_dword_stepping scratch swizzle (+4*IS) vs indexed swizzle (+4 linear, crossing IS), loads/stores & per-dword OOB
12 typed_and_atomic_x2 scratch swizzle suppresses typed >4B & atomic_*_x2 even in mode 2; indexed swizzle steps +4
13 oob_mode3_soffset OOB_SELECT 3 with active swizzle and stride != 0 checks (index + soffset) >= num_records
14 offset_wrap uint32(voff + inst_offset) wraps at 32 bits; RAW mode 3 uint64(off) + uint64(soff) does not
15 add_tid_wave_lane 64-thread ADD_TID_ENABLE wraps at wave lane 32 on wave32 vs 64 on wave64
16
17Usage:
18 python -I tools/buffer_swizzle_probe.py # translator side only (CPU)
19 python -I tools/buffer_swizzle_probe.py --oracle hw # native AMD GPU only (wave32 + wave64)
20 python -I tools/buffer_swizzle_probe.py --oracle both # compare hardware vs translator
21 python -I tools/buffer_swizzle_probe.py --oracle both --strict # fail on known divergences too
22 python -I tools/buffer_swizzle_probe.py --self-test
23
24Exit codes:
25 0 all unexpected comparisons match (and wave32 == wave64 on wave-invariant cases)
26 1 at least one unexpected mismatch, unexpected wave32/64 diff, or known divergence under --strict
27 2 bad CLI arguments or harness error
28 77 hardware oracle requested but unavailable on this machine
29"""
30import argparse
31import json
32import os
33import struct
34import sys
35import tempfile
36import warnings
37
38HERE = os.path.dirname(os.path.abspath(__file__))
39ROOT = os.path.dirname(HERE)
40sys.dont_write_bytecode = True
41for p in (HERE, os.path.join(ROOT, "tests", "semantic")):
42 if p not in sys.path:
43 sys.path.insert(0, p)
44
45import rdna2spirv # noqa: E402
46import spirv_mini_interp # noqa: E402
47
48# Buffer layout in the allocated buffer (s[0:3] RAW V# at offset 0):
49# 0x000..0x0FF (64 dwords): output words out[0..63]
50# 0x100..0x7FF (448 dwords): data region DATA_BASE (s[16:17]), seeded with 0x5EED0000 + offset
51OUT_WORDS = 512
52DATA_OFF = 0x100
53DATA_DWORDS = OUT_WORDS - (DATA_OFF // 4)
54SEED_BASE = 0x5EED0000
55OUT_V_W3 = 0x31016FAC
56V_W3_BASE = 0x01000FAC
57
58KNOWN_DIVERGENCES = {}
59
60
61def _cs_fssm(threads):
62 header = bytearray(0x148)
63 struct.pack_into("<4I", header, 0x138, 0x8088, threads, 1, 1)
64 return bytes(header)
65
66
67def _vsharp_lines(stride, nr, istride, mode, *, swz=True, tid=False, fmt=22):
68 """Build probed V# in s[4:7] anchored at DATA_BASE (s[16:17])."""
69 w1_hi = (stride << 16) | (int(swz) << 31)
70 w3 = V_W3_BASE | (fmt << 12) | (istride << 21) | (int(tid) << 23) | (mode << 28)
71 return [
72 "s_mov_b32 s4, s16",
73 f"s_or_b32 s5, s17, {w1_hi:#x}",
74 f"s_mov_b32 s6, {nr:#x}",
75 f"s_mov_b32 s7, {w3:#x}",
76 ]
77
78
79class Case:
80 """One self-contained buffer-swizzle probe kernel.
81
82 `body` runs after s[0:3] is the RAW output V# (base 0) and s[16:17] is DATA_BASE (base + 0x100), with the data
83 region seeded to `0x5EED0000 + byte_offset`. `body` stores `words` output dwords into out[0..words-1] via s[0:3].
84 """
85
86 __slots__ = ("group", "name", "body", "note", "threads", "words", "wave_dependent")
87
88 def __init__(self, group, name, body, note="", *, threads=1, words=4, wave_dependent=False):
89 self.group = group
90 self.name = name
91 self.body = tuple(body)
92 self.note = note
93 self.threads = threads
94 self.words = words
95 self.wave_dependent = wave_dependent
96
97
98def _single_lane(lines):
99 return ["v_cmpx_eq_u32_e32 0, v0", *lines]
100
101
102def build_cases():
103 cases = []
104
105 # 1. Baseline swizzled addressing formula (IS=8/16/32/64, index>=IS, non-4-mult stride, inst_offset, mode 0 soffset)
106 cases += [
107 Case("swizzle_basic", "is8_idx_off", _single_lane([
108 *_vsharp_lines(8, 16, 0, 3),
109 "v_mov_b32 v1, 1", "v_mov_b32 v2, 4",
110 "buffer_load_dword v8, v[1:2], s[4:7], 0 idxen offen", # (0*8+4)*8 + 1*4 = 0x24
111 "v_mov_b32 v1, 9", "v_mov_b32 v2, 0",
112 "buffer_load_dword v9, v[1:2], s[4:7], 0 idxen offen", # (1*8+0)*8 + 1*4 = 0x44
113 "v_mov_b32 v1, 1",
114 "buffer_load_dword v10, v1, s[4:7], 0 idxen offset:4", # inst_offset=4 -> 0x24
115 *_vsharp_lines(8, 4, 0, 1),
116 "v_mov_b32 v1, 3", "v_mov_b32 v2, 0x20",
117 "buffer_load_dword v11, v[1:2], s[4:7], 0 idxen offen", # mode 1: (0*8+0x20)*8 + 3*4 = 0x10c
118 "s_waitcnt vmcnt(0)",
119 "buffer_store_dwordx4 v[8:11], off, s[0:3], 0",
120 ]), "IS=8 idx/off, idx>=IS, inst_offset, and mode 1 large off"),
121
122 Case("swizzle_basic", "is16_32_64_non4_stride", _single_lane([
123 *_vsharp_lines(8, 8, 1, 0), # IS=16
124 "v_mov_b32 v1, 3", "v_mov_b32 v2, 4",
125 "buffer_load_dword v8, v[1:2], s[4:7], 0 idxen offen", # (0*8+4)*16 + 3*4 = 0x4c
126 *_vsharp_lines(16, 64, 2, 1), # IS=32
127 "v_mov_b32 v1, 35", "v_mov_b32 v2, 4",
128 "buffer_load_dword v9, v[1:2], s[4:7], 0 idxen offen", # (1*16+4)*32 + 3*4 = 0x28c
129 *_vsharp_lines(8, 100, 3, 1), # IS=64
130 "v_mov_b32 v1, 65",
131 "buffer_load_dword v10, v1, s[4:7], 0 idxen", # (1*8)*64 + 1*4 = 0x204
132 *_vsharp_lines(18, 16, 0, 0), # IS=8, non-4-multiple stride 18
133 "v_mov_b32 v1, 9", "v_mov_b32 v2, 4",
134 "buffer_load_dword v11, v[1:2], s[4:7], 0 idxen offen", # (1*18+4)*8 + 1*4 = 0xb4
135 "s_waitcnt vmcnt(0)",
136 "buffer_store_dwordx4 v[8:11], off, s[0:3], 0",
137 ]), "IS=16/32/64 and non-4-multiple stride 18"),
138
139 Case("swizzle_basic", "stride0_and_mode0_soff", _single_lane([
140 *_vsharp_lines(0, 0x40, 0, 3), # stride=0, idxen=1: swizzled addr + RAW check
141 "v_mov_b32 v1, 2", "v_mov_b32 v2, 0x30",
142 "buffer_load_dword v8, v[1:2], s[4:7], 0 idxen offen", # (0*0+0x30)*8 + 2*4 = 0x188
143 *_vsharp_lines(8, 16, 0, 0), # mode 0: soffset added after swizzle, not checked
144 "s_mov_b32 s8, 0x100",
145 "v_mov_b32 v1, 1", "v_mov_b32 v2, 4",
146 "buffer_load_dword v9, v[1:2], s[4:7], s8 idxen offen", # 0x24 + 0x100 = 0x124
147 *_vsharp_lines(8, 4, 0, 2), # mode 2: disabled bounds
148 "v_mov_b32 v1, 5",
149 "buffer_load_dword v10, v1, s[4:7], 0 idxen", # 5*4 = 0x14
150 *_vsharp_lines(8, 16, 0, 0), # mode 0: idx 16 >= 16 -> OOB
151 "v_mov_b32 v1, 16",
152 "buffer_load_dword v11, v1, s[4:7], 0 idxen", # 0
153 "s_waitcnt vmcnt(0)",
154 "buffer_store_dwordx4 v[8:11], off, s[0:3], 0",
155 ]), "stride=0 RAW with idxen, mode 0 soffset, mode 2, and mode 0 OOB"),
156 ]
157
158 # 2. idxen == 1 ignores ADD_TID_ENABLE (linear & swizzled, address & bounds, load/typed/atomic)
159 cases += [
160 Case("idxen_ignores_tid", "linear_idxen_tid", [
161 *_vsharp_lines(4, 5, 0, 1, swz=False, tid=True),
162 "v_mov_b32 v1, 2",
163 "buffer_load_dword v8, v1, s[4:7], 0 idxen", # every lane reads idx=2 (< 5) -> 0x08
164 "s_waitcnt vmcnt(0)",
165 "v_lshlrev_b32 v2, 2, v0",
166 "buffer_store_dword v8, v2, s[0:3], 0 offen",
167 ], "linear idxen=1 ignores ADD_TID_ENABLE for both address and bounds", threads=8, words=8),
168
169 Case("idxen_ignores_tid", "swizzled_idxen_tid", [
170 *_vsharp_lines(8, 16, 0, 3, swz=True, tid=True),
171 "v_mov_b32 v1, 4",
172 "buffer_load_dword v8, v1, s[4:7], 0 idxen", # every lane reads idx=4 -> 0x10
173 "s_waitcnt vmcnt(0)",
174 "v_lshlrev_b32 v2, 2, v0",
175 "buffer_store_dword v8, v2, s[0:3], 0 offen",
176 ], "swizzled idxen=1 ignores ADD_TID_ENABLE across lanes", threads=8, words=8),
177
178 Case("idxen_ignores_tid", "typed_and_atomic_idxen_tid", [
179 "v_cmpx_eq_u32_e32 3, v0", # run on lane 3 so lane != 0
180 *_vsharp_lines(8, 16, 0, 0, swz=True, tid=True, fmt=20),
181 "v_mov_b32 v1, 1",
182 "buffer_load_format_x v8, v1, s[4:7], 0 idxen", # idx=1 -> 0x04
183 "v_mov_b32 v1, 2",
184 "tbuffer_load_format_x v9, v1, s[4:7], 0 format:[BUF_FMT_32_UINT] idxen", # idx=2 -> 0x08
185 "v_mov_b32 v1, 3", "v_mov_b32 v10, 0x77777777",
186 "buffer_atomic_swap v10, v1, s[4:7], 0 idxen glc", # idx=3 -> old 0x0c
187 "s_waitcnt vmcnt(0)",
188 "buffer_load_dword v11, off, s[0:3], 0 offset:0x10c", # verify swap wrote 0x0c, not (3+3)*4=0x18
189 "s_waitcnt vmcnt(0)",
190 "buffer_store_dwordx4 v[8:11], off, s[0:3], 0",
191 ], "lane 3 typed MUBUF, MTBUF, and atomic with idxen=1 ignore ADD_TID_ENABLE", threads=4, words=4),
192 ]
193
194 # 3. SWIZZLE_ENABLE=1 with idxen=0 and ADD_TID_ENABLE=0 has zero effect (linear + mode 3 stays RAW)
195 cases += [
196 Case("swizzle_activation", "no_idx_no_tid_linear", _single_lane([
197 *_vsharp_lines(8, 4, 0, 1, swz=True, tid=False),
198 "v_mov_b32 v1, 0x10",
199 "buffer_load_dword v8, v1, s[4:7], 0 offen", # linear 0x10 (not 0x80)
200 *_vsharp_lines(8, 0x40, 0, 3, swz=True, tid=False),
201 "v_mov_b32 v1, 0x30",
202 "buffer_load_dword v9, v1, s[4:7], 0 offen", # stays RAW linear 0x30 despite stride 8
203 *_vsharp_lines(0x40, 4, 0, 0, swz=True, tid=False),
204 "v_mov_b32 v1, 0x10",
205 "buffer_load_dword v10, v1, s[4:7], 0 offen", # mode 0 linear 0x10
206 *_vsharp_lines(8, 4, 0, 2, swz=True, tid=False),
207 "v_mov_b32 v1, 0x10",
208 "buffer_load_dword v11, v1, s[4:7], 0 offen", # mode 2 linear 0x10
209 "s_waitcnt vmcnt(0)",
210 "buffer_store_dwordx4 v[8:11], off, s[0:3], 0",
211 ]), "SWIZZLE_ENABLE=1 with idxen=0 and ADD_TID_ENABLE=0 stays linear across modes 0..3"),
212 ]
213
214 # 4. Multi-dword stepping: scratch swizzle (+4*IS) vs indexed swizzle (+4 linear)
215 cases += [
216 Case("multi_dword_stepping", "scratch_swz_load_x4", [
217 "v_cmpx_eq_u32_e32 2, v0",
218 *_vsharp_lines(16, 4, 0, 0, swz=True, tid=True), # IS=8, lane=2 -> 0x08, 0x28, 0x48, 0x68
219 "buffer_load_dwordx4 v[8:11], off, s[4:7], 0",
220 "s_waitcnt vmcnt(0)",
221 "buffer_store_dwordx4 v[8:11], off, s[0:3], 0",
222 ], "scratch swizzle (idxen=0, ADD_TID=1) x4 load steps by +4*IS", threads=4, words=4),
223
224 Case("multi_dword_stepping", "scratch_swz_load_x4_oob", [
225 "v_cmpx_eq_u32_e32 2, v0",
226 *_vsharp_lines(8, 4, 0, 0, swz=True, tid=True), # stride=8: dwords 0..1 IN, 2..3 OOB
227 "buffer_load_dwordx4 v[8:11], off, s[4:7], 0",
228 "s_waitcnt vmcnt(0)",
229 "buffer_store_dwordx4 v[8:11], off, s[0:3], 0",
230 ], "scratch swizzle x4 load per-dword OOB at stride=8", threads=4, words=4),
231
232 Case("multi_dword_stepping", "scratch_swz_store_x2", [
233 "v_cmpx_eq_u32_e32 5, v0",
234 *_vsharp_lines(8, 16, 1, 3, swz=True, tid=True), # IS=16, lane=5 -> writes 0x14 and 0x54
235 "v_mov_b32 v1, 0xaaaa0001", "v_mov_b32 v2, 0xaaaa0002",
236 "buffer_store_dwordx2 v[1:2], off, s[4:7], 0",
237 "s_waitcnt vmcnt(0)",
238 "buffer_load_dword v8, off, s[0:3], 0 offset:0x114",
239 "buffer_load_dword v9, off, s[0:3], 0 offset:0x118",
240 "buffer_load_dword v10, off, s[0:3], 0 offset:0x154",
241 "buffer_load_dword v11, off, s[0:3], 0 offset:0x158",
242 "s_waitcnt vmcnt(0)",
243 "buffer_store_dwordx4 v[8:11], off, s[0:3], 0",
244 ], "scratch swizzle x2 store steps by +4*IS (IS=16 -> +0x40)", threads=8, words=4),
245
246 Case("multi_dword_stepping", "indexed_swz_load_x4", _single_lane([
247 *_vsharp_lines(16, 4, 0, 0, swz=True, tid=False), # IS=8, idx=2 -> 0x08, 0x0c, 0x10, 0x14
248 "v_mov_b32 v1, 2",
249 "buffer_load_dwordx4 v[8:11], v1, s[4:7], 0 idxen",
250 "s_waitcnt vmcnt(0)",
251 "buffer_store_dwordx4 v[8:11], off, s[0:3], 0",
252 ]), "indexed swizzle (idxen=1) x4 load steps linearly by +4"),
253
254 Case("multi_dword_stepping", "indexed_swz_load_x2_cross_is_and_oob", _single_lane([
255 *_vsharp_lines(8, 16, 0, 3, swz=True, tid=True), # IS=8, idx=7 -> 0x1c, 0x20 (linear across IS)
256 "v_mov_b32 v1, 7",
257 "buffer_load_dwordx2 v[8:9], v1, s[4:7], 0 idxen",
258 *_vsharp_lines(8, 16, 1, 3, swz=True, tid=False), # IS=16, idx=5, off=4 -> 0x54, 0 (dword 1 OOB)
259 "v_mov_b32 v1, 5", "v_mov_b32 v2, 4",
260 "buffer_load_dwordx2 v[10:11], v[1:2], s[4:7], 0 idxen offen",
261 "s_waitcnt vmcnt(0)",
262 "buffer_store_dwordx4 v[8:11], off, s[0:3], 0",
263 ]), "indexed swizzle x2 crosses IS=8 linearly and enforces per-dword stride OOB"),
264
265 Case("multi_dword_stepping", "indexed_swz_store_x2", _single_lane([
266 *_vsharp_lines(8, 16, 0, 3, swz=True, tid=False), # IS=8, idx=2 -> writes 0x08 and 0x0c
267 "v_mov_b32 v1, 2", "v_mov_b32 v2, 0xbbbb0001", "v_mov_b32 v3, 0xbbbb0002",
268 "buffer_store_dwordx2 v[2:3], v1, s[4:7], 0 idxen",
269 "s_waitcnt vmcnt(0)",
270 "buffer_load_dword v8, off, s[0:3], 0 offset:0x108",
271 "buffer_load_dword v9, off, s[0:3], 0 offset:0x10c",
272 "buffer_load_dword v10, off, s[0:3], 0 offset:0x128",
273 "buffer_load_dword v11, off, s[0:3], 0 offset:0x12c",
274 "s_waitcnt vmcnt(0)",
275 "buffer_store_dwordx4 v[8:11], off, s[0:3], 0",
276 ]), "indexed swizzle x2 store steps linearly by +4 (leaves +4*IS untouched)"),
277 ]
278
279 # 5. Typed formats and buffer_atomic_*_x2 in indexed vs scratch swizzle
280 cases += [
281 Case("typed_and_atomic_x2", "indexed_swz_fmt16_load", _single_lane([
282 *_vsharp_lines(16, 4, 0, 1, swz=True, tid=False, fmt=75), # 32_32_32_32_UINT, idx=1 -> 0x04..0x10
283 "v_mov_b32 v1, 1",
284 "buffer_load_format_xyzw v[8:11], v1, s[4:7], 0 idxen",
285 "s_waitcnt vmcnt(0)",
286 "buffer_store_dwordx4 v[8:11], off, s[0:3], 0",
287 ]), "indexed swizzle 16B typed load steps linearly by +4"),
288
289 Case("typed_and_atomic_x2", "indexed_swz_fmt16_store", _single_lane([
290 *_vsharp_lines(16, 4, 0, 1, swz=True, tid=False, fmt=75),
291 "v_mov_b32 v1, 1",
292 "v_mov_b32 v2, 0xcccc0001", "v_mov_b32 v3, 0xcccc0002",
293 "v_mov_b32 v4, 0xcccc0003", "v_mov_b32 v5, 0xcccc0004",
294 "buffer_store_format_xyzw v[2:5], v1, s[4:7], 0 idxen",
295 "s_waitcnt vmcnt(0)",
296 "buffer_load_dword v8, off, s[0:3], 0 offset:0x104",
297 "buffer_load_dword v9, off, s[0:3], 0 offset:0x108",
298 "buffer_load_dword v10, off, s[0:3], 0 offset:0x124",
299 "buffer_load_dword v11, off, s[0:3], 0 offset:0x144",
300 "s_waitcnt vmcnt(0)",
301 "buffer_store_dwordx4 v[8:11], off, s[0:3], 0",
302 ]), "indexed swizzle 16B typed store writes contiguous dwords"),
303
304 Case("typed_and_atomic_x2", "scratch_swz_fmt16_suppressed", [
305 "v_cmpx_eq_u32_e32 5, v0",
306 *_vsharp_lines(16, 16, 0, 2, swz=True, tid=True, fmt=75), # mode 2 (DISABLED), yet suppressed -> all 0
307 "buffer_load_format_xyzw v[8:11], off, s[4:7], 0",
308 "s_waitcnt vmcnt(0)",
309 "buffer_store_dwordx4 v[8:11], off, s[0:3], 0",
310 ], "scratch swizzle suppresses 16B typed MUBUF load even in OOB_SELECT 2", threads=8, words=4),
311
312 Case("typed_and_atomic_x2", "scratch_swz_mtbuf_atomic_x2_and_4b_ctrl", [
313 "v_cmpx_eq_u32_e32 4, v0", # lane 4 -> addr +0x10 (8-byte aligned)
314 *_vsharp_lines(16, 16, 0, 2, swz=True, tid=True, fmt=20), # mode 2, 32_UINT (4B) in V#
315 "tbuffer_load_format_xy v[2:3], off, s[4:7], 0 format:[BUF_FMT_32_32_UINT]", # 8B -> suppressed (0, 0)
316 "v_mov_b32 v4, 0xeeeeeeee", "v_mov_b32 v5, 0xffffffff",
317 "buffer_atomic_swap_x2 v[4:5], off, s[4:7], 0 glc", # 8B -> suppressed (0, 0, mem untouched)
318 "buffer_load_format_x v10, off, s[4:7], 0", # 4B control -> 0x5eed0010
319 "s_waitcnt vmcnt(0)",
320 "v_or_b32 v8, v2, v3", # 0
321 "v_or_b32 v9, v4, v5", # 0
322 "buffer_load_dword v11, off, s[0:3], 0 offset:0x110", # mem untouched -> 0x5eed0010
323 "s_waitcnt vmcnt(0)",
324 "buffer_store_dwordx4 v[8:11], off, s[0:3], 0",
325 ], "scratch swizzle suppresses 8B MTBUF & atomic_swap_x2 while 4B typed control succeeds", threads=8, words=4),
326
327 Case("typed_and_atomic_x2", "indexed_swz_atomic_x2", _single_lane([
328 *_vsharp_lines(16, 16, 0, 0, swz=True, tid=False),
329 "v_mov_b32 v1, 2", # addr +0x08 (8-byte aligned)
330 "v_mov_b32 v8, 0xdddd0001", "v_mov_b32 v9, 0xdddd0002",
331 "buffer_atomic_swap_x2 v[8:9], v1, s[4:7], 0 idxen glc", # old [0x5eed0008, 0x5eed000c]
332 "s_waitcnt vmcnt(0)",
333 "buffer_load_dword v10, off, s[0:3], 0 offset:0x108", # new 0xdddd0001
334 "buffer_load_dword v11, off, s[0:3], 0 offset:0x10c", # new 0xdddd0002
335 "s_waitcnt vmcnt(0)",
336 "buffer_store_dwordx4 v[8:11], off, s[0:3], 0",
337 ]), "indexed swizzle 8B buffer_atomic_swap_x2 executes linearly at aligned address"),
338 ]
339
340 # 6. OOB_SELECT 3 with active swizzle and stride != 0 checks (index + soffset) >= num_records
341 cases += [
342 Case("oob_mode3_soffset", "indexed_mode3_soff_edge", _single_lane([
343 *_vsharp_lines(8, 16, 0, 3, swz=True, tid=False),
344 "s_mov_b32 s8, 0x100",
345 "v_mov_b32 v1, 1", "v_mov_b32 v2, 4",
346 "buffer_load_dword v8, v[1:2], s[4:7], s8 idxen offen", # 1 + 0x100 >= 16 -> 0 (OOB)
347 "s_mov_b32 s8, 12",
348 "v_mov_b32 v1, 3", "v_mov_b32 v2, 4",
349 "buffer_load_dword v9, v[1:2], s[4:7], s8 idxen offen", # 3 + 12 = 15 < 16 -> 0x38
350 "v_mov_b32 v1, 4", "v_mov_b32 v2, 4",
351 "buffer_load_dword v10, v[1:2], s[4:7], s8 idxen offen", # 4 + 12 = 16 >= 16 -> 0 (OOB)
352 *_vsharp_lines(8, 14, 0, 3, swz=True, tid=False),
353 "s_mov_b32 s8, 8",
354 "v_mov_b32 v1, 5",
355 "buffer_load_dword v11, v1, s[4:7], s8 idxen", # 5 + 8 = 13 < 14 -> 0x14 + 8 = 0x1c
356 "s_waitcnt vmcnt(0)",
357 "buffer_store_dwordx4 v[8:11], off, s[0:3], 0",
358 ]), "mode 3 swizzled with stride != 0 checks (index + soffset) < num_records"),
359
360 Case("oob_mode3_soffset", "scratch_mode3_soff_lanes", [
361 *_vsharp_lines(8, 10, 0, 3, swz=True, tid=True),
362 "s_mov_b32 s8, 4",
363 "buffer_load_dword v8, off, s[4:7], s8", # lanes 0..5 IN (lane+4 < 10), 6..15 OOB
364 "s_waitcnt vmcnt(0)",
365 "v_lshlrev_b32 v2, 2, v0",
366 "buffer_store_dword v8, v2, s[0:3], 0 offen",
367 ], "scratch swizzle mode 3 with soffset=4 and NR=10: lanes 0..5 IN, 6..15 OOB", threads=16, words=16),
368 ]
369
370 # 7. 32-bit wrap on uint32(voff + inst_offset) vs 64-bit no-wrap on RAW mode 3 (off + soffset)
371 cases += [
372 Case("offset_wrap", "voff_inst_wrap_and_soff_nowrap", _single_lane([
373 *_vsharp_lines(8, 16, 0, 3, swz=True, tid=False),
374 "v_mov_b32 v1, 1", "v_mov_b32 v2, 0xfffffffc",
375 "buffer_load_dword v8, v[1:2], s[4:7], 0 idxen offen offset:8", # off wraps to 4 -> 0x24
376 *_vsharp_lines(0, 0x40, 0, 3, swz=False, tid=False),
377 "v_mov_b32 v1, 0xfffffffc",
378 "buffer_load_dword v9, v1, s[4:7], 0 offen offset:8", # linear off wraps to 4 -> 0x04
379 *_vsharp_lines(0, 0xffffffff, 0, 3, swz=False, tid=False),
380 "s_mov_b32 s8, 0xfffffff0",
381 "v_mov_b32 v1, 0x20",
382 "buffer_load_dword v10, v1, s[4:7], s8 offen", # 0x20 + 0xfffffff0 = 0x100000010 -> OOB
383 *_vsharp_lines(0, 0xffffffff, 0, 3, swz=True, tid=False),
384 "v_mov_b32 v1, 1", "v_mov_b32 v2, 0x20",
385 "buffer_load_dword v11, v[1:2], s[4:7], s8 idxen offen", # swizzled stride=0 RAW -> OOB
386 "s_waitcnt vmcnt(0)",
387 "buffer_store_dwordx4 v[8:11], off, s[0:3], 0",
388 ]), "uint32(voff + inst_offset) wraps at 32 bits; RAW mode 3 off + soffset does not"),
389 ]
390
391 # 8. 64-thread ADD_TID_ENABLE uses wave lane (0..31 in wave32, 0..63 in wave64), not workgroup thread ID
392 cases += [
393 Case("add_tid_wave_lane", "tid_wave32_vs_wave64", [
394 *_vsharp_lines(8, 64, 0, 1, swz=True, tid=True),
395 "buffer_load_dword v8, off, s[4:7], 0",
396 "s_waitcnt vmcnt(0)",
397 "v_lshlrev_b32 v2, 2, v0",
398 "buffer_store_dword v8, v2, s[0:3], 0 offen",
399 ], "64 threads with ADD_TID_ENABLE: wave32 wraps lanes 32..63 to 0..31, wave64 uses 0..63",
400 threads=64, words=64, wave_dependent=True),
401 ]
402
403 return cases
404
405
406def _hw_kernel_lines(case, idx, wave):
407 """Wrap `case.body` for hw_oracle (raw=True, s[2:3] = output buffer base address)."""
408 lbl = f".Lseed_{idx}"
409 lbl_done = f".Lseed_done_{idx}"
410 # Build RAW V# in s[0:3] from s[2:3], compute DATA_BASE = base + DATA_OFF in s[16:17], and seed DATA_BASE on
411 # lane 0 (preserving EXEC with wave-sized save/restore so all threads participate in the body afterwards).
412 if wave == 32:
413 save_exec = ["s_mov_b32 s28, exec_lo", "v_cmpx_eq_u32_e32 0, v0"]
414 restore_exec = ["s_mov_b32 exec_lo, s28"]
415 else:
416 save_exec = ["s_mov_b64 s[28:29], exec", "v_cmpx_eq_u32_e32 0, v0"]
417 restore_exec = ["s_mov_b64 exec, s[28:29]"]
418 lines = [
419 "s_mov_b32 s0, s2",
420 "s_and_b32 s1, s3, 0xffff",
421 "s_mov_b32 s2, 0xffffffff",
422 f"s_mov_b32 s3, {OUT_V_W3:#x}",
423 f"s_add_u32 s16, s0, {DATA_OFF:#x}",
424 "s_addc_u32 s17, s1, 0",
425 "s_and_b32 s17, s17, 0xffff",
426 *save_exec,
427 "s_mov_b32 s20, 0",
428 f"{lbl}:",
429 f"s_cmp_ge_u32 s20, {DATA_DWORDS * 4:#x}",
430 f"s_cbranch_scc1 {lbl_done}",
431 f"s_add_u32 s21, s20, {SEED_BASE:#x}",
432 "v_mov_b32 v30, s21",
433 f"s_add_u32 s22, s20, {DATA_OFF:#x}",
434 "buffer_store_dword v30, off, s[0:3], s22",
435 "s_add_u32 s20, s20, 4",
436 f"s_branch {lbl}",
437 f"{lbl_done}:",
438 "s_waitcnt vmcnt(0)",
439 *restore_exec,
440 ]
441 if case.threads > 1:
442 lines.append("s_barrier")
443 lines.extend(case.body)
444 lines.append("s_endpgm")
445 return lines
446
447
448def _translate_case(work, case, wave=32):
449 os.makedirs(os.path.join(work, "disasm"), exist_ok=True)
450 os.makedirs(os.path.join(work, "fssm"), exist_ok=True)
451 name = f"cs_swz_probe_{case.name}_w{wave}"
452 src = os.path.join(work, "disasm", name + ".s")
453 wave_tag = "s_mov_b64 s[28:29], exec" if wave == 64 else "s_mov_b32 s28, exec_lo"
454 body = [
455 wave_tag,
456 f"s_add_u32 s16, s0, {DATA_OFF:#x}",
457 "s_addc_u32 s17, s1, 0",
458 "s_and_b32 s17, s17, 0xffff",
459 *case.body,
460 "s_endpgm",
461 ]
462 with open(src, "w", encoding="utf-8", newline="\n") as f:
463 f.write(f"; {name}\n" + "".join(f"\t{ln}\n" for ln in body))
464 with open(os.path.join(work, "fssm", name + ".fssm"), "wb") as f:
465 f.write(_cs_fssm(case.threads))
466 with warnings.catch_warnings():
467 warnings.simplefilter("ignore", ResourceWarning)
468 spv = rdna2spirv.translate(src)
469 memory = {a: 0 for a in range(0, DATA_OFF, 4)}
470 for off in range(0, DATA_DWORDS * 4, 4):
471 memory[DATA_OFF + off] = SEED_BASE + off
472 spirv_mini_interp.run_workgroup(
473 spv, case.threads, wave,
474 inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i % wave},
475 push_constants=[0, 0, 0xFFFFFFFF, OUT_V_W3] + [0] * 28,
476 memory=memory,
477 )
478 return [memory.get(4 * i, 0) for i in range(case.words)]
479
480
481def run_translator(cases, waves=(32, 64)):
482 per_wave = {}
483 with tempfile.TemporaryDirectory(prefix="buf_swz_probe_") as work:
484 for wave in waves:
485 out = {}
486 for case in cases:
487 if wave != waves[0] and not case.wave_dependent:
488 out[case.name] = per_wave[waves[0]][case.name]
489 continue
490 try:
491 out[case.name] = _translate_case(work, case, wave=wave)
492 except Exception as e:
493 out[case.name] = f"error: {type(e).__name__}: {e}"
494 per_wave[wave] = out
495 return per_wave
496
497
498def run_hw(cases, arch=None, waves=(32, 64)):
499 from hw_oracle import asm, runner # noqa: E402
500 oracle = runner.open_oracle(arch=arch)
501 try:
502 device = oracle.device
503 per_wave = {}
504 for wave in waves:
505 kernels = [
506 asm.Kernel(_hw_kernel_lines(case, idx, wave), wave=wave, threads=case.threads,
507 words=OUT_WORDS, raw=True)
508 for idx, case in enumerate(cases)
509 ]
510 res = oracle.run(kernels, words=OUT_WORDS)
511 per_wave[wave] = {case.name: (r[:case.words] if isinstance(r, list) else r) for case, r in zip(cases, res)}
512 return device, per_wave
513 finally:
514 oracle.close()
515
516
517def _fmt_words(w):
518 if isinstance(w, list):
519 if len(w) <= 8:
520 return " ".join(f"0x{x:08x}" for x in w)
521 head = " ".join(f"0x{x:08x}" for x in w[:4])
522 tail = " ".join(f"0x{x:08x}" for x in w[-4:])
523 return f"[{len(w)} words: {head} ... {tail}]"
524 return str(w)
525
526
527def self_test():
528 cases = build_cases()
529 names = [c.name for c in cases]
530 assert len(names) == len(set(names)), "duplicate case names"
531 for name in KNOWN_DIVERGENCES:
532 assert name in names, f"unknown KNOWN_DIVERGENCES key: {name}"
533 res = run_translator(cases, waves=(32, 64))
534 for w in (32, 64):
535 errors = {k: v for k, v in res[w].items() if not isinstance(v, list)}
536 assert not errors, f"translator wave{w} errors: {errors}"
537 assert res[32]["tid_wave32_vs_wave64"] != res[64]["tid_wave32_vs_wave64"], "wave32/64 ADD_TID must differ"
538 print(f"self-test: {len(cases)} cases across {len({c.group for c in cases})} groups translated and ran on CPU OK")
539 return 0
540
541
542def main(argv=None):
543 ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
544 ap.add_argument("--oracle", choices=("translator", "hw", "both"), default="translator")
545 ap.add_argument("--wave", choices=("32", "64", "both"), default="both")
546 ap.add_argument("--group", action="append", default=[], help="run only named group(s)")
547 ap.add_argument("--hw-arch", default=None, help="override GPU architecture for hw_oracle")
548 ap.add_argument("--list-groups", action="store_true")
549 ap.add_argument("--strict", action="store_true", help="treat known translator divergences as failures")
550 ap.add_argument("--json", dest="json_out", default=None, help="write raw results to a JSON file")
551 ap.add_argument("--self-test", action="store_true")
552 args = ap.parse_args(argv)
553
554 if args.self_test:
555 return self_test()
556
557 cases = build_cases()
558 groups = []
559 for c in cases:
560 if c.group not in groups:
561 groups.append(c.group)
562 if args.list_groups:
563 for g in groups:
564 n = sum(1 for c in cases if c.group == g)
565 print(f"{g:<22} ({n} cases)")
566 return 0
567
568 if args.group:
569 unknown = [g for g in args.group if g not in groups]
570 if unknown:
571 print(f"unknown group(s): {', '.join(unknown)}", file=sys.stderr)
572 return 2
573 want = set(args.group)
574 cases = [c for c in cases if c.group in want]
575
576 waves = (32, 64) if args.wave == "both" else (int(args.wave),)
577 tr_res = run_translator(cases, waves=waves) if args.oracle in ("translator", "both") else None
578 hw_device, hw_res = None, None
579 if args.oracle in ("hw", "both"):
580 from hw_oracle import runner # noqa: E402
581 try:
582 hw_device, hw_res = run_hw(cases, arch=args.hw_arch, waves=waves)
583 except runner.Unavailable as e:
584 print(f"hardware oracle unavailable: {e}", file=sys.stderr)
585 return 77
586 print(f"hardware oracle: {hw_device} (waves: {','.join(str(w) for w in waves)})")
587
588 mismatches = 0
589 known_diffs = 0
590 wave_diffs = 0
591 records = []
592 for c in cases:
593 t32 = tr_res[32][c.name] if tr_res and 32 in tr_res else None
594 t64 = tr_res[64][c.name] if tr_res and 64 in tr_res else None
595 h32 = hw_res[32][c.name] if hw_res and 32 in hw_res else None
596 h64 = hw_res[64][c.name] if hw_res and 64 in hw_res else None
597 status = "OK"
598 tag = None
599 if not c.wave_dependent and h32 is not None and h64 is not None and h32 != h64:
600 status = "WAVE_DIFF"
601 wave_diffs += 1
602 elif c.wave_dependent and h32 is not None and h64 is not None and h32 == h64:
603 status = "WAVE_SAME"
604 mismatches += 1
605 elif any(v is not None and not isinstance(v, list) for v in (t32, t64, h32, h64)):
606 status = "ERROR"
607 mismatches += 1
608 else:
609 bad = ((t32 is not None and h32 is not None and t32 != h32)
610 or (t64 is not None and h64 is not None and t64 != h64))
611 if bad:
612 hw_ref = h32 if h32 is not None else h64
613 known = KNOWN_DIVERGENCES.get(c.name)
614 if known and hw_ref == known[1]:
615 status = "KNOWN_DIFF"
616 tag = known[0]
617 known_diffs += 1
618 else:
619 status = "MISMATCH"
620 mismatches += 1
621 records.append({
622 "group": c.group, "name": c.name, "note": c.note, "wave_dependent": c.wave_dependent,
623 "status": status, "known_tag": tag,
624 "translator_w32": t32, "translator_w64": t64, "hw_w32": h32, "hw_w64": h64,
625 })
626 if status != "OK" or args.oracle != "both":
627 label = f"{status}:{tag}" if tag else status
628 print(f"[{label:<22}] {c.group}/{c.name}: {c.note}")
629 if h32 is not None:
630 print(f" hw_w32: {_fmt_words(h32)}")
631 if h64 is not None and h64 != h32:
632 print(f" hw_w64: {_fmt_words(h64)}")
633 if t32 is not None:
634 print(f" tr_w32: {_fmt_words(t32)}")
635 if t64 is not None and t64 != t32:
636 print(f" tr_w64: {_fmt_words(t64)}")
637
638 total = len(cases)
639 matched = total - mismatches - known_diffs - wave_diffs
640 print(f"summary: {total} cases: {matched} match, {known_diffs} known divergence, "
641 f"{mismatches} unexpected mismatch, {wave_diffs} wave32/64 diff")
642
643 if args.json_out:
644 out_path = os.path.abspath(args.json_out)
645 if os.path.isdir(out_path):
646 print(f"ERROR: --json path is a directory: {out_path}", file=sys.stderr)
647 return 2
648 parent = os.path.dirname(out_path)
649 if parent:
650 os.makedirs(parent, exist_ok=True)
651 with open(out_path, "w", encoding="utf-8", newline="\n") as f:
652 json.dump({"device": hw_device, "waves": list(waves), "cases": records}, f, indent=2)
653 f.write("\n")
654
655 if mismatches or wave_diffs or (args.strict and known_diffs):
656 return 1
657 return 0
658
659
660if __name__ == "__main__":
661 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
662 sys.stdout.reconfigure(errors="replace")
663 except (AttributeError, ValueError, OSError):
664 pass
665 sys.exit(main())