diff options
| author | tunczzzz <r.ampage.warrior017@gmail.com> | 2026-11-21 23:57:57 +0000 |
|---|---|---|
| committer | tunczzzz <r.ampage.warrior017@gmail.com> | 2026-11-22 00:02:16 +0000 |
| commit | 71a16c11cf1538aaf4b2ca59fee59aec454da702 (patch) | |
| tree | ecba90a2d2bd0eee2000820cc32456a229d48a0b /tools/cf_diff.py | |
| parent | 4abd54571b6efa02d97eda4711792fa00b455dc3 (diff) | |
FUZZ-8: control-flow/EXEC differential fuzzer; wave32 SCC of mask ops is wave-wide
tools/cf_diff.py generates seeded wave32/wave64 pixel shaders from the
control-flow shapes compilers emit (saveexec if/else, v_cmpx, VCC- and
SCC-voted branches, uniform and per-lane loops, two-entry cycles) and
compares every lane's export between:
* tools/cf_ref.py: cpu_ref's Machine plus branches, compares, v_cmpx,
saveexec and 64-bit masks (the ISA model, one wave)
* rdna2spirv + tests/semantic/spirv_wave_interp.py: every invocation of
one subgroup in lockstep, split at selections and rejoined at merges,
with the subgroup operations the translator emits
in both the structured and the dispatch-loop form; --spirv-val also
validates each module, --minimize reduces a mismatch.
Finding (fixed here): in a wave32 program s_and/or/xor/andn2/orn2/nand/
nor/xnor_b32 on lane masks set SCC from the lane's own bit instead of the
whole mask, so `s_and_b32 s0, vcc_lo, exec_lo; s_cbranch_scc0` and loops
closed by `s_andn2_b32 exec_lo, ...; s_cbranch_scc1` split the wave. SCC
is now the same subgroup vote as for the _b64 forms. GPU test
ps_scc_mask32 (not run on a GPU yet).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'tools/cf_diff.py')
| -rw-r--r-- | tools/cf_diff.py | 645 |
1 files changed, 645 insertions, 0 deletions
diff --git a/tools/cf_diff.py b/tools/cf_diff.py new file mode 100644 index 000000000..aa1f41f73 --- /dev/null +++ b/tools/cf_diff.py | |||
| @@ -0,0 +1,645 @@ | |||
| 1 | r"""FUZZ-8: differential fuzzer for control flow and EXEC (standard library only). | ||
| 2 | |||
| 3 | Generates seeded RDNA2 pixel-shader programs built from the control-flow shapes compilers emit, runs every lane | ||
| 4 | of a wave through two independent sides and compares each lane's export bit for bit: | ||
| 5 | |||
| 6 | * tools/cf_ref.py: the ISA model (cpu_ref's Machine plus branches, compares, v_cmpx and saveexec), one wave | ||
| 7 | * tools/rdna2spirv.py + tests/semantic/spirv_wave_interp.py: the translated SPIR-V, every invocation of one | ||
| 8 | subgroup run in lockstep with structured reconvergence (subgroup size = wave size, the translator's contract) | ||
| 9 | |||
| 10 | Shapes (each nests, up to --depth): | ||
| 11 | if v_cmp -> s_and_saveexec -> [s_cbranch_execz] -> body -> s_or exec (LLVM SI_IF / SI_END_CF) | ||
| 12 | ifelse ... s_xor saveexec mask, s_or_saveexec + s_xor exec for the else side (LLVM SI_ELSE) | ||
| 13 | cmpx s_mov save, exec -> v_cmpx -> [s_cbranch_execz] -> body -> s_mov exec, save | ||
| 14 | vccz v_cmp -> s_cbranch_vccz/vccnz over a body that every active lane runs (wave-uniform branch) | ||
| 15 | sif s_cmp -> s_cbranch_scc0/1 [-> s_branch over an else] (uniform branch) | ||
| 16 | sloop uniform counter loop closed by s_cbranch_scc1 (natural loop) | ||
| 17 | vloop per-lane trip counts: break mask, s_andn2 exec, s_cbranch_execnz (LLVM SI_LOOP) | ||
| 18 | irr two-entry cycle on uniform SCC branches (irreducible graph) | ||
| 19 | sccmask s_and/andn2/or/xor of VCC and EXEC -> s_cbranch_scc0/1 (SCC = whole mask != 0) | ||
| 20 | csel the same SCC read by s_cselect_b32 into a uniform SGPR | ||
| 21 | (vloop also closes some loops with s_cbranch_scc1 on the SCC of its s_andn2 exec.) | ||
| 22 | Bodies mix integer VALU and SALU ops with "probes": v11 = v11 * 33 + K at each site, so v11 records which sites | ||
| 23 | each lane ran, in which order and how often. v8/v9 carry data, v10 the uniform SGPRs. Immediates stay in the | ||
| 24 | inline-constant range so every instruction has a known size, and the listing carries `; encoding:` bytes of | ||
| 25 | those sizes (zeros: the translator reads only their length), which places the branch targets. | ||
| 26 | |||
| 27 | Usage: | ||
| 28 | python -I tools/cf_diff.py [--programs N] [--seed S] [--wave 32|64|both] [--dispatch-loop] [--depth D] | ||
| 29 | python -I tools/cf_diff.py --self-test | ||
| 30 | python -I tools/cf_diff.py --spirv-val ... # also spirv-as + spirv-val each module | ||
| 31 | python -I tools/cf_diff.py --seed S --program K --show [--minimize] # print (and shrink) one program | ||
| 32 | |||
| 33 | Exit code 0 when every program matches, 1 on a mismatch (case, seed, lane, the expected and actual words and the | ||
| 34 | listing; with --minimize also a reduced listing), 2 on harness errors. Skips are counted with reasons. | ||
| 35 | """ | ||
| 36 | import argparse | ||
| 37 | import gc | ||
| 38 | import os | ||
| 39 | import random | ||
| 40 | import shutil | ||
| 41 | import struct | ||
| 42 | import subprocess | ||
| 43 | import sys | ||
| 44 | import tempfile | ||
| 45 | import warnings | ||
| 46 | |||
| 47 | HERE = os.path.dirname(os.path.abspath(__file__)) | ||
| 48 | sys.dont_write_bytecode = True | ||
| 49 | if HERE not in sys.path: | ||
| 50 | sys.path.insert(0, HERE) | ||
| 51 | SEM_DIR = os.path.join(os.path.dirname(HERE), "tests", "semantic") | ||
| 52 | if SEM_DIR not in sys.path: | ||
| 53 | sys.path.insert(0, SEM_DIR) | ||
| 54 | |||
| 55 | import cf_ref # noqa: E402 | ||
| 56 | import cpu_ref # noqa: E402 | ||
| 57 | import rdna2spirv # noqa: E402 | ||
| 58 | from spirv_wave_interp import UnsupportedConstruct, run_wave # noqa: E402 | ||
| 59 | |||
| 60 | STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4) | ||
| 61 | DATA = (1, 2, 3, 8, 9) # VGPRs the bodies compute on (v0 = lane id is kept intact) | ||
| 62 | SREGS = (10, 11, 12, 13) # uniform SGPRs the bodies compute on | ||
| 63 | CCS = ("eq", "ne", "lt", "le", "gt", "ge") | ||
| 64 | VOP3 = ("v_mul_lo_u32", "v_mbcnt_lo_u32_b32", "v_mbcnt_hi_u32_b32") | ||
| 65 | |||
| 66 | |||
| 67 | # ---- program tree -------------------------------------------------------------------------------------------- | ||
| 68 | # A program is a list of nodes. ("op", line) is one instruction; compound nodes hold child lists and are expanded | ||
| 69 | # by Emitter into instructions, labels and branches. Keeping the tree lets --minimize delete whole structures. | ||
| 70 | |||
| 71 | class Gen: | ||
| 72 | def __init__(self, rng, wave, max_depth, budget): | ||
| 73 | self.r, self.wave, self.max_depth, self.budget = rng, wave, max_depth, budget | ||
| 74 | self.site = 0 | ||
| 75 | |||
| 76 | def cmp(self): | ||
| 77 | """A per-lane condition: (cc, type, constant, vgpr). Constants near 0 and 64 make some conditions | ||
| 78 | true or false for every lane, so the execz/vccz skips are taken too.""" | ||
| 79 | r = self.r | ||
| 80 | k = r.choice((0, 1, 2, 3, 4, 5, 7, 8, 12, 16, 31, 32, 63, 64, -1, -16)) | ||
| 81 | return (r.choice(CCS), r.choice(("u32", "u32", "i32")), k, r.choice((0, 0, 1, 2, 3, 8, 9))) | ||
| 82 | |||
| 83 | def probe(self): | ||
| 84 | self.site += 1 | ||
| 85 | return ("probe", 1 + (self.site * 37) % 64) | ||
| 86 | |||
| 87 | def leaf(self): | ||
| 88 | r = self.r | ||
| 89 | d, s = r.choice(DATA), r.choice(DATA) | ||
| 90 | k = r.randrange(-16, 65) | ||
| 91 | sr = r.choice(SREGS) | ||
| 92 | choices = [ | ||
| 93 | ("op", f"v_add_nc_u32 v{d}, {k}, v{s}"), | ||
| 94 | ("op", f"v_sub_nc_u32 v{d}, v{s}, v{r.choice(DATA)}"), | ||
| 95 | ("op", f"v_xor_b32 v{d}, s{sr}, v{s}"), | ||
| 96 | ("op", f"v_and_b32 v{d}, {r.randrange(0, 65)}, v{s}"), | ||
| 97 | ("op", f"v_or_b32 v{d}, v{r.choice(DATA)}, v{s}"), | ||
| 98 | ("op", f"v_lshlrev_b32 v{d}, {r.randrange(0, 8)}, v{s}"), | ||
| 99 | ("op", f"v_lshrrev_b32 v{d}, {r.randrange(0, 8)}, v{s}"), | ||
| 100 | ("op", f"v_mul_lo_u32 v{d}, v{s}, {r.randrange(0, 65)}"), | ||
| 101 | ("op", f"v_mov_b32 v{d}, s{sr}"), | ||
| 102 | ("op", f"v_add_nc_u32 v{d}, s{sr}, v{s}"), | ||
| 103 | ("op", f"s_add_u32 s{sr}, s{sr}, {r.randrange(0, 65)}"), | ||
| 104 | ("op", f"s_xor_b32 s{sr}, s{r.choice(SREGS)}, {r.randrange(0, 65)}"), | ||
| 105 | ("op", f"s_mov_b32 s{sr}, {r.randrange(-16, 65)}"), | ||
| 106 | ("cnd", d, s, self.cmp()), | ||
| 107 | ] | ||
| 108 | return r.choice(choices) | ||
| 109 | |||
| 110 | def block(self, depth): | ||
| 111 | out = [] | ||
| 112 | n = self.r.randrange(1, 4) | ||
| 113 | for _ in range(n): | ||
| 114 | if self.budget <= 0: | ||
| 115 | break | ||
| 116 | self.budget -= 1 | ||
| 117 | if depth < self.max_depth and self.r.random() < 0.55: | ||
| 118 | out.append(self.compound(depth + 1)) | ||
| 119 | else: | ||
| 120 | out.append(self.leaf()) | ||
| 121 | if self.r.random() < 0.6: | ||
| 122 | out.append(self.probe()) | ||
| 123 | return out | ||
| 124 | |||
| 125 | def compound(self, depth): | ||
| 126 | r = self.r | ||
| 127 | kind = r.choice(("if", "if", "ifelse", "ifelse", "cmpx", "vccz", "sif", "sloop", "vloop", "vloop", "irr", | ||
| 128 | "sccmask", "csel")) | ||
| 129 | if kind == "sccmask": | ||
| 130 | return ("sccmask", self.cmp(), r.choice(("and", "andn2", "or", "xor")), | ||
| 131 | r.choice(("s_cbranch_scc0", "s_cbranch_scc1")), [self.probe()] + self.block(depth)) | ||
| 132 | if kind == "csel": | ||
| 133 | return ("csel", self.cmp(), r.choice(("and", "andn2", "or", "xor")), r.choice(SREGS)) | ||
| 134 | if kind == "if": | ||
| 135 | return ("if", self.cmp(), r.random() < 0.7, [self.probe()] + self.block(depth)) | ||
| 136 | if kind == "ifelse": | ||
| 137 | return ("ifelse", self.cmp(), [self.probe()] + self.block(depth), [self.probe()] + self.block(depth)) | ||
| 138 | if kind == "cmpx": | ||
| 139 | return ("cmpx", self.cmp(), r.random() < 0.7, [self.probe()] + self.block(depth)) | ||
| 140 | if kind == "vccz": | ||
| 141 | return ("vccz", self.cmp(), r.choice(("s_cbranch_vccz", "s_cbranch_vccnz")), | ||
| 142 | [self.probe()] + self.block(depth)) | ||
| 143 | if kind == "sif": | ||
| 144 | other = [self.probe()] + self.block(depth) if r.random() < 0.5 else None | ||
| 145 | return ("sif", (r.choice(CCS), r.choice(SREGS), r.randrange(0, 65)), r.random() < 0.5, | ||
| 146 | [self.probe()] + self.block(depth), other) | ||
| 147 | if kind == "sloop": | ||
| 148 | return ("sloop", r.randrange(1, 4), [self.probe()] + self.block(depth)) | ||
| 149 | if kind == "vloop": | ||
| 150 | return ("vloop", (r.choice((0, 1, 2, 3)), r.choice((1, 3)), r.random() < 0.3), | ||
| 151 | self.cmp() if r.random() < 0.4 else None, [self.probe()] + self.block(depth)) | ||
| 152 | return ("irr", (r.choice(SREGS), r.randrange(0, 65)), [self.probe()] + self.block(depth), | ||
| 153 | [self.probe()] + self.block(depth)) | ||
| 154 | |||
| 155 | |||
| 156 | def generate(rng, wave, max_depth=3, budget=10): | ||
| 157 | g = Gen(rng, wave, max_depth, budget) | ||
| 158 | body = [] | ||
| 159 | while g.budget > 0: | ||
| 160 | body.extend(g.block(0)) | ||
| 161 | body.append(g.probe()) | ||
| 162 | return body | ||
| 163 | |||
| 164 | |||
| 165 | class Emitter: | ||
| 166 | """Expands a program tree into tab-less instruction lines with sizes, labels and symbolic branches.""" | ||
| 167 | |||
| 168 | def __init__(self, wave): | ||
| 169 | self.wave = wave | ||
| 170 | self.items = [] # ("ins", text) | ("label", name) | ("br", mnemonic, label) | ||
| 171 | self.n_labels = 0 | ||
| 172 | self.depth = 0 | ||
| 173 | |||
| 174 | # register names ------------------------------------------------------------------------------------------- | ||
| 175 | def exec_(self): | ||
| 176 | return "exec" if self.wave == 64 else "exec_lo" | ||
| 177 | |||
| 178 | def vcc(self): | ||
| 179 | return "vcc" if self.wave == 64 else "vcc_lo" | ||
| 180 | |||
| 181 | def b(self): | ||
| 182 | return "b64" if self.wave == 64 else "b32" | ||
| 183 | |||
| 184 | def sreg(self, base): | ||
| 185 | """A mask SGPR for the current nesting depth (an aligned pair in wave64).""" | ||
| 186 | n = base + 2 * self.depth | ||
| 187 | return f"s[{n}:{n + 1}]" if self.wave == 64 else f"s{n}" | ||
| 188 | |||
| 189 | def label(self): | ||
| 190 | self.n_labels += 1 | ||
| 191 | return f"L{self.n_labels}" | ||
| 192 | |||
| 193 | def ins(self, text): | ||
| 194 | self.items.append(("ins", text)) | ||
| 195 | |||
| 196 | def br(self, mnemonic, label): | ||
| 197 | self.items.append(("br", mnemonic, label)) | ||
| 198 | |||
| 199 | def place(self, label): | ||
| 200 | self.items.append(("label", label)) | ||
| 201 | |||
| 202 | def vcmp(self, c, dst=None): | ||
| 203 | cc, ty, k, v = c | ||
| 204 | self.ins(f"v_cmp_{cc}_{ty}_e32 {dst or self.vcc()}, {k}, v{v}") | ||
| 205 | |||
| 206 | # program ------------------------------------------------------------------------------------------------------ | ||
| 207 | def program(self, body): | ||
| 208 | if self.wave == 64: | ||
| 209 | self.ins("v_mbcnt_lo_u32_b32 v0, -1, 0") | ||
| 210 | self.ins("v_mbcnt_hi_u32_b32 v0, -1, v0") | ||
| 211 | else: | ||
| 212 | self.ins("v_mbcnt_lo_u32_b32 v0, -1, 0") | ||
| 213 | self.ins("v_and_b32 v1, 7, v0") | ||
| 214 | self.ins("v_lshrrev_b32 v2, 2, v0") | ||
| 215 | self.ins("v_mul_lo_u32 v3, v0, 5") | ||
| 216 | self.ins("v_and_b32 v3, 15, v3") | ||
| 217 | self.ins("v_xor_b32 v8, 9, v0") | ||
| 218 | self.ins("v_mov_b32 v9, 0") | ||
| 219 | self.ins("v_mov_b32 v11, 1") | ||
| 220 | for i, s in enumerate(SREGS): | ||
| 221 | self.ins(f"s_mov_b32 s{s}, {(3, 5, 0, 12)[i]}") | ||
| 222 | self.nodes(body) | ||
| 223 | self.ins(f"v_mov_b32 v10, s{SREGS[0]}") | ||
| 224 | for s in SREGS[1:]: | ||
| 225 | self.ins("v_lshlrev_b32 v10, 3, v10") | ||
| 226 | self.ins(f"v_xor_b32 v10, s{s}, v10") | ||
| 227 | self.ins("exp mrt0 v8, v9, v10, v11 done vm") | ||
| 228 | self.ins("s_endpgm") | ||
| 229 | |||
| 230 | def nodes(self, nodes): | ||
| 231 | for n in nodes: | ||
| 232 | self.node(n) | ||
| 233 | |||
| 234 | def node(self, n): | ||
| 235 | kind = n[0] | ||
| 236 | w = self.b() | ||
| 237 | ex = self.exec_() | ||
| 238 | if kind == "op": | ||
| 239 | self.ins(n[1]) | ||
| 240 | elif kind == "probe": | ||
| 241 | self.ins("v_mul_lo_u32 v11, v11, 33") | ||
| 242 | self.ins(f"v_add_nc_u32 v11, {n[1]}, v11") | ||
| 243 | elif kind == "cnd": | ||
| 244 | _, d, s, c = n | ||
| 245 | self.vcmp(c) | ||
| 246 | self.ins(f"v_cndmask_b32_e32 v{d}, 7, v{s}, {self.vcc()}") | ||
| 247 | elif kind == "if": | ||
| 248 | _, c, skip, body = n | ||
| 249 | save, end = self.sreg(20), self.label() | ||
| 250 | self.vcmp(c) | ||
| 251 | self.ins(f"s_and_saveexec_{w} {save}, {self.vcc()}") | ||
| 252 | if skip: | ||
| 253 | self.br("s_cbranch_execz", end) | ||
| 254 | self.depth += 1 | ||
| 255 | self.nodes(body) | ||
| 256 | self.depth -= 1 | ||
| 257 | self.place(end) | ||
| 258 | self.ins(f"s_or_{w} {ex}, {ex}, {save}") | ||
| 259 | elif kind == "ifelse": | ||
| 260 | _, c, then, other = n | ||
| 261 | save, els, end = self.sreg(20), self.label(), self.label() | ||
| 262 | self.vcmp(c) | ||
| 263 | self.ins(f"s_and_saveexec_{w} {save}, {self.vcc()}") | ||
| 264 | self.ins(f"s_xor_{w} {save}, {ex}, {save}") | ||
| 265 | self.br("s_cbranch_execz", els) | ||
| 266 | self.depth += 1 | ||
| 267 | self.nodes(then) | ||
| 268 | self.depth -= 1 | ||
| 269 | self.place(els) | ||
| 270 | self.ins(f"s_or_saveexec_{w} {save}, {save}") | ||
| 271 | self.ins(f"s_xor_{w} {ex}, {ex}, {save}") | ||
| 272 | self.br("s_cbranch_execz", end) | ||
| 273 | self.depth += 1 | ||
| 274 | self.nodes(other) | ||
| 275 | self.depth -= 1 | ||
| 276 | self.place(end) | ||
| 277 | self.ins(f"s_or_{w} {ex}, {ex}, {save}") | ||
| 278 | elif kind == "cmpx": | ||
| 279 | _, (cc, ty, k, v), skip, body = n | ||
| 280 | save, end = self.sreg(20), self.label() | ||
| 281 | self.ins(f"s_mov_{w} {save}, {ex}") | ||
| 282 | self.ins(f"v_cmpx_{cc}_{ty}_e32 {k}, v{v}") | ||
| 283 | if skip: | ||
| 284 | self.br("s_cbranch_execz", end) | ||
| 285 | self.depth += 1 | ||
| 286 | self.nodes(body) | ||
| 287 | self.depth -= 1 | ||
| 288 | self.place(end) | ||
| 289 | self.ins(f"s_mov_{w} {ex}, {save}") | ||
| 290 | elif kind == "vccz": | ||
| 291 | _, c, mnemonic, body = n | ||
| 292 | end = self.label() | ||
| 293 | self.vcmp(c) | ||
| 294 | self.br(mnemonic, end) | ||
| 295 | self.nodes(body) | ||
| 296 | self.place(end) | ||
| 297 | elif kind == "sif": | ||
| 298 | _, (cc, sr, k), on_one, then, other = n | ||
| 299 | els, end = self.label(), self.label() | ||
| 300 | self.ins(f"s_cmp_{cc}_u32 s{sr}, {k}") | ||
| 301 | self.br("s_cbranch_scc0" if on_one else "s_cbranch_scc1", els if other else end) | ||
| 302 | self.nodes(then) | ||
| 303 | if other: | ||
| 304 | self.br("s_branch", end) | ||
| 305 | self.place(els) | ||
| 306 | self.nodes(other) | ||
| 307 | self.place(end) | ||
| 308 | elif kind == "sloop": | ||
| 309 | _, trips, body = n | ||
| 310 | ctr, head = 14 + self.depth, self.label() | ||
| 311 | self.ins(f"s_mov_b32 s{ctr}, 0") | ||
| 312 | self.place(head) | ||
| 313 | self.depth += 1 | ||
| 314 | self.nodes(body) | ||
| 315 | self.depth -= 1 | ||
| 316 | self.ins(f"s_add_u32 s{ctr}, s{ctr}, 1") | ||
| 317 | self.ins(f"s_cmp_lt_u32 s{ctr}, {trips}") | ||
| 318 | self.br("s_cbranch_scc1", head) | ||
| 319 | elif kind == "sccmask": | ||
| 320 | # SCC of a mask op is (whole result != 0): one value for the wave, like a vote. | ||
| 321 | _, c, logic, mnemonic, body = n | ||
| 322 | tmp, end = self.sreg(50), self.label() | ||
| 323 | self.vcmp(c) | ||
| 324 | self.ins(f"s_{logic}_{w} {tmp}, {self.vcc()}, {ex}") | ||
| 325 | self.br(mnemonic, end) | ||
| 326 | self.nodes(body) | ||
| 327 | self.place(end) | ||
| 328 | elif kind == "csel": | ||
| 329 | _, c, logic, sr = n | ||
| 330 | self.vcmp(c) | ||
| 331 | self.ins(f"s_{logic}_{w} {self.sreg(50)}, {self.vcc()}, {ex}") | ||
| 332 | self.ins(f"s_cselect_b32 s{sr}, s{sr}, 17") | ||
| 333 | elif kind == "vloop": | ||
| 334 | _, (src, mask, scc_exit), brk, body = n | ||
| 335 | it, lim, brk_mask, head = 4 + self.depth, 30 + self.depth, self.sreg(40), self.label() | ||
| 336 | self.ins(f"v_and_b32 v{lim}, {mask}, v{src}") | ||
| 337 | self.ins(f"v_add_nc_u32 v{lim}, 1, v{lim}") | ||
| 338 | self.ins(f"v_mov_b32 v{it}, 0") | ||
| 339 | self.ins(f"s_mov_{w} {brk_mask}, 0") | ||
| 340 | self.place(head) | ||
| 341 | self.depth += 1 | ||
| 342 | self.nodes(body) | ||
| 343 | self.depth -= 1 | ||
| 344 | if brk is not None: | ||
| 345 | # An early exit (SI_IF_BREAK): lanes meeting `brk` join the break mask for this iteration. | ||
| 346 | self.vcmp(brk) | ||
| 347 | self.ins(f"s_or_{w} {brk_mask}, {self.vcc()}, {brk_mask}") | ||
| 348 | self.ins(f"v_add_nc_u32 v{it}, 1, v{it}") | ||
| 349 | self.ins(f"v_cmp_ge_u32_e32 {self.vcc()}, v{it}, v{lim}") | ||
| 350 | self.ins(f"s_or_{w} {brk_mask}, {self.vcc()}, {brk_mask}") | ||
| 351 | self.ins(f"s_andn2_{w} {ex}, {ex}, {brk_mask}") | ||
| 352 | # Loop again while any lane is left: EXECNZ, or SCC of the s_andn2 (= new EXEC != 0). | ||
| 353 | self.br("s_cbranch_scc1" if scc_exit else "s_cbranch_execnz", head) | ||
| 354 | self.ins(f"s_or_{w} {ex}, {ex}, {brk_mask}") | ||
| 355 | elif kind == "irr": | ||
| 356 | _, (sr, k), part_a, part_b = n | ||
| 357 | ctr, a_lbl, b_lbl, end = 14 + self.depth, self.label(), self.label(), self.label() | ||
| 358 | self.ins(f"s_mov_b32 s{ctr}, 0") | ||
| 359 | self.ins(f"s_cmp_lt_u32 s{sr}, {k}") | ||
| 360 | self.br("s_cbranch_scc0", b_lbl) | ||
| 361 | self.place(a_lbl) | ||
| 362 | self.depth += 1 | ||
| 363 | self.nodes(part_a) | ||
| 364 | self.ins(f"s_add_u32 s{ctr}, s{ctr}, 1") | ||
| 365 | self.ins(f"s_cmp_lt_u32 s{ctr}, 4") | ||
| 366 | self.br("s_cbranch_scc0", end) | ||
| 367 | self.place(b_lbl) | ||
| 368 | self.nodes(part_b) | ||
| 369 | self.depth -= 1 | ||
| 370 | self.ins(f"s_add_u32 s{ctr}, s{ctr}, 2") | ||
| 371 | self.ins(f"s_cmp_lt_u32 s{ctr}, 7") | ||
| 372 | self.br("s_cbranch_scc1", a_lbl) | ||
| 373 | self.place(end) | ||
| 374 | else: | ||
| 375 | raise ValueError(f"unknown node {kind}") | ||
| 376 | |||
| 377 | def assemble(self): | ||
| 378 | """Lines with real branch offsets: [(text, size_in_bytes)].""" | ||
| 379 | pc, where, sized = 0, {}, [] | ||
| 380 | for it in self.items: | ||
| 381 | if it[0] == "label": | ||
| 382 | where[it[1]] = pc | ||
| 383 | continue | ||
| 384 | size = 4 if it[0] == "br" else _size(it[1]) | ||
| 385 | sized.append((it, pc, size)) | ||
| 386 | pc += size | ||
| 387 | out = [] | ||
| 388 | for it, at, size in sized: | ||
| 389 | if it[0] == "br": | ||
| 390 | off = (where[it[2]] - (at + 4)) // 4 | ||
| 391 | out.append((f"{it[1]} {off}", size)) | ||
| 392 | else: | ||
| 393 | out.append((it[1], size)) | ||
| 394 | return out | ||
| 395 | |||
| 396 | |||
| 397 | def _size(text): | ||
| 398 | op = text.split()[0] | ||
| 399 | if op == "exp" or op.endswith("_e64") or op in VOP3: | ||
| 400 | return 8 | ||
| 401 | return 4 | ||
| 402 | |||
| 403 | |||
| 404 | def listing_text(lines, name): | ||
| 405 | out = [f"; {name} code 0x0..0x{sum(s for _, s in lines):x}"] | ||
| 406 | for text, size in lines: | ||
| 407 | out.append("\t" + text + " ; encoding: [" + ",".join(["0x00"] * size) + "]") | ||
| 408 | return "\n".join(out) + "\n" | ||
| 409 | |||
| 410 | |||
| 411 | def build(body, wave): | ||
| 412 | e = Emitter(wave) | ||
| 413 | e.program(body) | ||
| 414 | return e.assemble() | ||
| 415 | |||
| 416 | |||
| 417 | # ---- one comparison ------------------------------------------------------------------------------------------ | ||
| 418 | |||
| 419 | def run_case(name, body, wave, structured=True): | ||
| 420 | """Returns (status, detail): status in {"match", "mismatch", "skip"}.""" | ||
| 421 | lines = build(body, wave) | ||
| 422 | text = listing_text(lines, name) | ||
| 423 | with tempfile.TemporaryDirectory(prefix="cf-diff-") as tmp: | ||
| 424 | dis = os.path.join(tmp, "disasm") | ||
| 425 | os.mkdir(dis) | ||
| 426 | path = os.path.join(dis, name + ".s") | ||
| 427 | with open(path, "w", encoding="utf-8", newline="\n") as f: | ||
| 428 | f.write(text) | ||
| 429 | with open(os.path.join(tmp, name + ".dxbc"), "wb") as f: | ||
| 430 | f.write(STUB_DXBC) | ||
| 431 | try: | ||
| 432 | ref = cf_ref.run(path, wave=wave) | ||
| 433 | except cpu_ref.CpuRefError as e: | ||
| 434 | return ("skip", f"cf_ref: {e}") | ||
| 435 | old = rdna2spirv.STRUCTURED | ||
| 436 | rdna2spirv.STRUCTURED = structured | ||
| 437 | try: | ||
| 438 | with warnings.catch_warnings(): | ||
| 439 | warnings.simplefilter("ignore", ResourceWarning) | ||
| 440 | spv = rdna2spirv.translate(path) | ||
| 441 | gen = rdna2spirv.translate.last_gen | ||
| 442 | gc.collect() | ||
| 443 | except rdna2spirv.Unsupported as e: | ||
| 444 | return ("skip", f"translator unsupported: {e}") | ||
| 445 | finally: | ||
| 446 | rdna2spirv.STRUCTURED = old | ||
| 447 | if SPIRV_VAL: | ||
| 448 | bad = _spirv_val(spv, tmp) | ||
| 449 | if bad: | ||
| 450 | return ("mismatch", f"spirv-val: {bad}") | ||
| 451 | if bool(getattr(gen, "wave64", False)) != (wave == 64): | ||
| 452 | return ("mismatch", f"translator detected wave{64 if gen.wave64 else 32}, the program is wave{wave}") | ||
| 453 | try: | ||
| 454 | got = run_wave(spv, wave=wave)["outputs"] | ||
| 455 | except UnsupportedConstruct as e: | ||
| 456 | return ("skip", f"wave interp: {e}") | ||
| 457 | for lane in range(wave): | ||
| 458 | want = ref["exports"].get(lane) | ||
| 459 | have = (got[lane] or {}).get("%out_mrt0") if got[lane] is not None else None | ||
| 460 | if want == have: | ||
| 461 | continue | ||
| 462 | if want is None or have is None: | ||
| 463 | return ("mismatch", f"lane {lane}: export {'missing' if have is None else 'unexpected'} in the " | ||
| 464 | f"translation (reference {_words(want)}, translation {_words(have)})") | ||
| 465 | bad = [i for i in range(4) if want[i] != have[i]] | ||
| 466 | what = {0: "v8 (data)", 1: "v9 (data)", 2: "v10 (uniform SGPRs)", 3: "v11 (path probes)"} | ||
| 467 | return ("mismatch", f"lane {lane}: {', '.join(what[i] for i in bad)} differ: reference {_words(want)}, " | ||
| 468 | f"translation {_words(have)}") | ||
| 469 | return ("match", "") | ||
| 470 | |||
| 471 | |||
| 472 | SPIRV_VAL = False # --spirv-val: also assemble and validate every translation (spirv-as/spirv-val on PATH) | ||
| 473 | |||
| 474 | |||
| 475 | def _spirv_val(spv, tmp): | ||
| 476 | """First spirv-as/spirv-val error for the module (Vulkan 1.2, as tests/conftest.py), or None.""" | ||
| 477 | sa, sv = os.path.join(tmp, "m.spvasm"), os.path.join(tmp, "m.spv") | ||
| 478 | with open(sa, "w", encoding="utf-8", newline="\n") as f: | ||
| 479 | f.write(spv) | ||
| 480 | for cmd in (["spirv-as", sa, "-o", sv, "--target-env", "vulkan1.2"], | ||
| 481 | ["spirv-val", "--target-env", "vulkan1.2", sv]): | ||
| 482 | r = subprocess.run(cmd, capture_output=True, text=True) | ||
| 483 | if r.returncode: | ||
| 484 | return (cmd[0] + ": " + (r.stderr or r.stdout).strip().splitlines()[0]) if (r.stderr or r.stdout) \ | ||
| 485 | else f"{cmd[0]} exited with {r.returncode}" | ||
| 486 | return None | ||
| 487 | |||
| 488 | |||
| 489 | def _words(w): | ||
| 490 | return "none" if w is None else "(" + ", ".join(f"0x{x:08x}" for x in w) + ")" | ||
| 491 | |||
| 492 | |||
| 493 | # ---- reduction ----------------------------------------------------------------------------------------------- | ||
| 494 | |||
| 495 | def _variants(body): | ||
| 496 | """Smaller programs: each node deleted, and each compound node replaced by one of its child lists.""" | ||
| 497 | for i, n in enumerate(body): | ||
| 498 | yield body[:i] + body[i + 1:] | ||
| 499 | kids = [x for x in n[1:] if isinstance(x, list)] | ||
| 500 | for k in kids: | ||
| 501 | yield body[:i] + k + body[i + 1:] | ||
| 502 | for j, x in enumerate(n): | ||
| 503 | if isinstance(x, list): | ||
| 504 | for v in _variants(x): | ||
| 505 | m = list(n) | ||
| 506 | m[j] = v | ||
| 507 | yield body[:i] + [tuple(m)] + body[i + 1:] | ||
| 508 | |||
| 509 | |||
| 510 | def minimize(body, wave, structured=True): | ||
| 511 | """Greedy reduction that keeps a mismatch.""" | ||
| 512 | changed = True | ||
| 513 | while changed: | ||
| 514 | changed = False | ||
| 515 | for cand in _variants(body): | ||
| 516 | status, _ = run_case("ps_cf_min", cand, wave, structured) | ||
| 517 | if status == "mismatch": | ||
| 518 | body, changed = cand, True | ||
| 519 | break | ||
| 520 | return body | ||
| 521 | |||
| 522 | |||
| 523 | # ---- suite --------------------------------------------------------------------------------------------------- | ||
| 524 | |||
| 525 | def program_for(seed, index, wave, depth): | ||
| 526 | rng = random.Random(f"{seed}:{index}:{wave}") | ||
| 527 | return generate(rng, wave, max_depth=depth, budget=rng.randrange(4, 13)) | ||
| 528 | |||
| 529 | |||
| 530 | def run_suite(programs, seed, waves, structured=True, depth=3, limit=None): | ||
| 531 | counts = {"pass": 0, "mismatch": 0, "skip": {}, "harness-error": 0} | ||
| 532 | failures = [] | ||
| 533 | total = programs if limit is None else min(programs, limit) | ||
| 534 | for i in range(total): | ||
| 535 | for wave in waves: | ||
| 536 | name = f"ps_cf_{i:04d}_w{wave}" | ||
| 537 | body = program_for(seed, i, wave, depth) | ||
| 538 | try: | ||
| 539 | status, detail = run_case(name, body, wave, structured) | ||
| 540 | except Exception as e: # noqa: BLE001 - harness bugs must be loud | ||
| 541 | counts["harness-error"] += 1 | ||
| 542 | failures.append((i, wave, f"harness error {type(e).__name__}: {e}")) | ||
| 543 | continue | ||
| 544 | if status == "match": | ||
| 545 | counts["pass"] += 1 | ||
| 546 | elif status == "mismatch": | ||
| 547 | counts["mismatch"] += 1 | ||
| 548 | failures.append((i, wave, detail)) | ||
| 549 | else: | ||
| 550 | counts["skip"][detail] = counts["skip"].get(detail, 0) + 1 | ||
| 551 | return counts, failures | ||
| 552 | |||
| 553 | |||
| 554 | def self_test(): | ||
| 555 | """Harness canaries: a program must match, a sabotaged reference must be caught, the interpreter must | ||
| 556 | reconverge after a divergent branch.""" | ||
| 557 | ok = True | ||
| 558 | body = [("if", ("gt", "u32", 4, 0), True, [("probe", 5), ("op", "v_add_nc_u32 v9, 1, v9")]), ("probe", 6)] | ||
| 559 | for wave in (32, 64): | ||
| 560 | status, detail = run_case("ps_canary_ok", body, wave) | ||
| 561 | if status != "match": | ||
| 562 | print(f"canary FAILED (wave{wave}): hand-written if did not match ({status}: {detail})") | ||
| 563 | ok = False | ||
| 564 | # The reference must be able to disagree: drop the s_or that restores EXEC and the lanes > 4 never export. | ||
| 565 | e = Emitter(32) | ||
| 566 | e.program(body) | ||
| 567 | e.items = [it for it in e.items if not (it[0] == "ins" and it[1].startswith("s_or_b32 exec_lo"))] | ||
| 568 | with tempfile.TemporaryDirectory(prefix="cf-diff-") as tmp: | ||
| 569 | p = os.path.join(tmp, "c.s") | ||
| 570 | with open(p, "w", encoding="utf-8") as f: | ||
| 571 | f.write(listing_text(e.assemble(), "ps_canary_bad")) | ||
| 572 | if len(cf_ref.run(p, wave=32)["exports"]) != 4: # 4 > lane: lanes 0-3 stay on | ||
| 573 | print("canary FAILED: the reference did not drop lanes whose EXEC was never restored") | ||
| 574 | ok = False | ||
| 575 | # Divergent loop + vote: every lane must leave the loop with its own trip count. | ||
| 576 | body = [("vloop", (0, 3, False), None, [("probe", 9), ("vccz", ("eq", "u32", 0, 1), "s_cbranch_vccz", | ||
| 577 | [("op", "s_add_u32 s10, s10, 1")])])] | ||
| 578 | for wave in (32, 64): | ||
| 579 | status, detail = run_case("ps_canary_loop", body, wave) | ||
| 580 | if status != "match": | ||
| 581 | print(f"canary FAILED (wave{wave}): divergent loop did not match ({status}: {detail})") | ||
| 582 | ok = False | ||
| 583 | if ok: | ||
| 584 | print("canaries: match ok, sabotaged reference detected, divergent loop reconverges") | ||
| 585 | return ok | ||
| 586 | |||
| 587 | |||
| 588 | def main(argv=None): | ||
| 589 | ap = argparse.ArgumentParser(description="FUZZ-8: control-flow/EXEC differential fuzzer.") | ||
| 590 | ap.add_argument("--programs", type=int, default=200) | ||
| 591 | ap.add_argument("--seed", type=int, default=1) | ||
| 592 | ap.add_argument("--wave", choices=("32", "64", "both"), default="both") | ||
| 593 | ap.add_argument("--depth", type=int, default=3, help="maximum nesting depth") | ||
| 594 | ap.add_argument("--dispatch-loop", action="store_true", help="translate in the dispatch-loop form") | ||
| 595 | ap.add_argument("--program", type=int, help="only this program index (with --show / --minimize)") | ||
| 596 | ap.add_argument("--show", action="store_true", help="print the listing of --program") | ||
| 597 | ap.add_argument("--minimize", action="store_true", help="reduce a mismatching program before printing it") | ||
| 598 | ap.add_argument("--spirv-val", action="store_true", | ||
| 599 | help="also run spirv-as and spirv-val on every translation (a failure counts as a mismatch)") | ||
| 600 | ap.add_argument("--self-test", action="store_true") | ||
| 601 | a = ap.parse_args(argv) | ||
| 602 | if a.spirv_val: | ||
| 603 | missing = [t for t in ("spirv-as", "spirv-val") if not shutil.which(t)] | ||
| 604 | if missing: | ||
| 605 | print(f"--spirv-val needs {' and '.join(missing)} on PATH") | ||
| 606 | return 2 | ||
| 607 | global SPIRV_VAL | ||
| 608 | SPIRV_VAL = True | ||
| 609 | if a.self_test: | ||
| 610 | return 0 if self_test() else 1 | ||
| 611 | waves = (32, 64) if a.wave == "both" else (int(a.wave),) | ||
| 612 | structured = not a.dispatch_loop | ||
| 613 | if a.program is not None: | ||
| 614 | rc = 0 | ||
| 615 | for wave in waves: | ||
| 616 | body = program_for(a.seed, a.program, wave, a.depth) | ||
| 617 | status, detail = run_case(f"ps_cf_{a.program:04d}_w{wave}", body, wave, structured) | ||
| 618 | print(f"program {a.program} wave{wave}: {status} {detail}") | ||
| 619 | if status == "mismatch": | ||
| 620 | rc = 1 | ||
| 621 | if a.minimize: | ||
| 622 | body = minimize(body, wave, structured) | ||
| 623 | print("reduced:", run_case("ps_cf_min", body, wave, structured)[1]) | ||
| 624 | if a.show or a.minimize: | ||
| 625 | print(listing_text(build(body, wave), f"ps_cf_{a.program:04d}_w{wave}")) | ||
| 626 | return rc | ||
| 627 | counts, failures = run_suite(a.programs, a.seed, waves, structured, a.depth) | ||
| 628 | skips = sum(counts["skip"].values()) | ||
| 629 | form = "dispatch loop" if a.dispatch_loop else "structured" | ||
| 630 | print(f"{a.programs} programs x wave {'/'.join(map(str, waves))} (seed {a.seed}, {form}): " | ||
| 631 | f"{counts['pass']} pass, {counts['mismatch']} mismatch, {skips} skipped, " | ||
| 632 | f"{counts['harness-error']} harness errors") | ||
| 633 | for reason, n in sorted(counts["skip"].items(), key=lambda kv: -kv[1]): | ||
| 634 | print(f" skip x{n}: {reason}") | ||
| 635 | for i, wave, detail in failures[:10]: | ||
| 636 | print(f" program {i} wave{wave}: {detail}") | ||
| 637 | if len(failures) > 10: | ||
| 638 | print(f" ... {len(failures) - 10} more") | ||
| 639 | if counts["harness-error"]: | ||
| 640 | return 2 | ||
| 641 | return 1 if counts["mismatch"] else 0 | ||
| 642 | |||
| 643 | |||
| 644 | if __name__ == "__main__": | ||
| 645 | sys.exit(main()) | ||