upleb.uk

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

summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorItsNotRexed <300290919+ItsNotRexed@users.noreply.github.com>2026-11-22 08:38:46 -0500
committerItsNotRexed <300290919+ItsNotRexed@users.noreply.github.com>2026-11-22 08:38:46 -0500
commit724db6df235a2fa82800a1d32f3a707beb5eeb59 (patch)
tree420f5d0449ffcc7a08f489f6015b2dfa6322de08
parent985a0ee4dc7993cb2d177f69f5ffd913f5fd6200 (diff)
parent834b71cf108cd6ff2cd95bfd40c62a96fcfc5589 (diff)
Merge pull request #1720 from Luiz Neves
-rw-r--r--tests/semantic/spirv_mini_interp.py22
-rw-r--r--tests/semantic/spirv_wave_interp.py16
-rw-r--r--tests/semantic/test_interp_merge_check.py78
3 files changed, 116 insertions, 0 deletions
diff --git a/tests/semantic/spirv_mini_interp.py b/tests/semantic/spirv_mini_interp.py
index dbc1c4317..b288e42f7 100644
--- a/tests/semantic/spirv_mini_interp.py
+++ b/tests/semantic/spirv_mini_interp.py
@@ -37,6 +37,27 @@ class UnsupportedConstruct(NotImplementedError):
37 """The module uses something this interpreter deliberately does not model.""" 37 """The module uses something this interpreter deliberately does not model."""
38 38
39 39
40class InvalidModule(AssertionError):
41 """The module breaks a SPIR-V structural rule spirv-val enforces, so no driver would accept it, even though
42 this interpreter could run it. Raised instead of returning results for a shader that never reaches a GPU."""
43
44
45def check_structure(body):
46 """spirv-val's merge rule (SPIR-V 2.16.2): OpSelectionMerge must be the second-to-last instruction of its block,
47 directly before OpBranchConditional or OpSwitch, and OpLoopMerge directly before OpBranch or
48 OpBranchConditional. Until 2026-11-22 the interpreter skipped merges, so a translator change that put an
49 instruction between a merge and its branch (#1633: OpLoad %active) passed every semantic test while every
50 driver rejected the module. `body` is the list of (result, opcode, operands, line) of a function."""
51 follow = {"OpSelectionMerge": ("OpBranchConditional", "OpSwitch"),
52 "OpLoopMerge": ("OpBranch", "OpBranchConditional")}
53 for k, (_, op, _, line) in enumerate(body):
54 if op in follow:
55 nxt = body[k + 1][1] if k + 1 < len(body) else None
56 if nxt not in follow[op]:
57 raise InvalidModule(f"{line!r} is followed by {body[k + 1][3] if nxt else 'the end of the function'!r}"
58 f", not by {' or '.join(follow[op])}")
59
60
40# Instructions that carry no runtime semantics for a single-entry-point, straight-line module. 61# Instructions that carry no runtime semantics for a single-entry-point, straight-line module.
41_IGNORED = frozenset({ 62_IGNORED = frozenset({
42 "OpCapability", "OpExtension", "OpExtInstImport", "OpMemoryModel", "OpEntryPoint", "OpExecutionMode", 63 "OpCapability", "OpExtension", "OpExtInstImport", "OpMemoryModel", "OpEntryPoint", "OpExecutionMode",
@@ -463,6 +484,7 @@ def _invocation(text, inputs, push_constants, memory, step=False):
463 raise UnsupportedConstruct(f"{op} in module header") 484 raise UnsupportedConstruct(f"{op} in module header")
464 if not in_body: 485 if not in_body:
465 raise UnsupportedConstruct("no function body") 486 raise UnsupportedConstruct("no function body")
487 check_structure(body)
466 488
467 def deref(p): 489 def deref(p):
468 box, i = p 490 box, i = p
diff --git a/tests/semantic/spirv_wave_interp.py b/tests/semantic/spirv_wave_interp.py
index db8f1e950..a3adf6544 100644
--- a/tests/semantic/spirv_wave_interp.py
+++ b/tests/semantic/spirv_wave_interp.py
@@ -38,6 +38,15 @@ class UnsupportedConstruct(NotImplementedError):
38 """The module uses something this interpreter deliberately does not model.""" 38 """The module uses something this interpreter deliberately does not model."""
39 39
40 40
41class InvalidModule(AssertionError):
42 """The module breaks spirv-val's merge rule (see spirv_mini_interp.check_structure): a merge instruction must
43 directly precede its block's branch. Raised instead of running a shader no driver would accept."""
44
45
46_MERGE_FOLLOW = {"OpSelectionMerge": ("OpBranchConditional", "OpSwitch"),
47 "OpLoopMerge": ("OpBranch", "OpBranchConditional")}
48
49
41class F: 50class F:
42 """A 32-bit float carried as its bit pattern.""" 51 """A 32-bit float carried as its bit pattern."""
43 __slots__ = ("bits",) 52 __slots__ = ("bits",)
@@ -120,6 +129,7 @@ class _Module:
120 self.id_type = {} 129 self.id_type = {}
121 cur = None 130 cur = None
122 in_body = False 131 in_body = False
132 merge_line = None # (opcode, line) of a merge whose branch has not been seen yet
123 for raw in text.splitlines(): 133 for raw in text.splitlines():
124 line = raw.strip() 134 line = raw.strip()
125 if not line: 135 if not line:
@@ -130,6 +140,11 @@ class _Module:
130 res, op, rest = m.groups() 140 res, op, rest = m.groups()
131 a = rest.split() 141 a = rest.split()
132 if in_body: 142 if in_body:
143 if merge_line is not None:
144 if op not in _MERGE_FOLLOW[merge_line[0]]:
145 raise InvalidModule(f"{merge_line[1]!r} is followed by {line!r}, not by "
146 f"{' or '.join(_MERGE_FOLLOW[merge_line[0]])}")
147 merge_line = None
133 if op == "OpFunctionEnd": 148 if op == "OpFunctionEnd":
134 in_body = False 149 in_body = False
135 continue 150 continue
@@ -149,6 +164,7 @@ class _Module:
149 cur.phis.append((res, a)) 164 cur.phis.append((res, a))
150 elif op in ("OpSelectionMerge", "OpLoopMerge"): 165 elif op in ("OpSelectionMerge", "OpLoopMerge"):
151 cur.merge = (op, a[0], a[1] if op == "OpLoopMerge" else None) 166 cur.merge = (op, a[0], a[1] if op == "OpLoopMerge" else None)
167 merge_line = (op, line)
152 elif op in _TERMINATORS: 168 elif op in _TERMINATORS:
153 cur.term = (op, a) 169 cur.term = (op, a)
154 cur = None 170 cur = None
diff --git a/tests/semantic/test_interp_merge_check.py b/tests/semantic/test_interp_merge_check.py
new file mode 100644
index 000000000..382955f5f
--- /dev/null
+++ b/tests/semantic/test_interp_merge_check.py
@@ -0,0 +1,78 @@
1"""spirv_mini_interp and spirv_wave_interp reject a module that breaks spirv-val's merge rule.
2
3OpSelectionMerge must directly precede OpBranchConditional / OpSwitch, and OpLoopMerge directly precede OpBranch /
4OpBranchConditional (SPIR-V 2.16.2). Both interpreters used to skip merges, so #1633's first version, with an
5`OpLoad %active` between the merge and its branch, passed every semantic test while spirv-val rejected every module
6it produced (found by @mokkymiah, confirmed by @Impre-visible). Each case takes a translated module, which the
7interpreters run, and moves one instruction to sit between a merge and its branch. Standard library only.
8"""
9import os
10import re
11import sys
12import unittest
13
14HERE = os.path.dirname(os.path.abspath(__file__))
15sys.dont_write_bytecode = True
16sys.path.insert(0, HERE)
17
18from test_salu64_bitwise_data import translate_ps # noqa: E402 (also puts tools/ on sys.path)
19import spirv_mini_interp as si # noqa: E402
20import spirv_wave_interp as wi # noqa: E402
21
22LINES = ["v_mbcnt_lo_u32_b32 v4, -1, 0", "v_cmpx_gt_u32_e32 5, v4", "v_mov_b32 v0, 1.0",
23 "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"]
24
25
26def spv():
27 text = translate_ps(LINES)
28 assert text.count("OpSelectionMerge") >= 1
29 return text
30
31
32def break_merge(text):
33 """Put the instruction just before the first OpSelectionMerge between it and its branch."""
34 lines = text.splitlines()
35 k = next(i for i, ln in enumerate(lines) if ln.strip().startswith("OpSelectionMerge"))
36 assert re.match(r"\s*%\S+ = Op", lines[k - 1]), lines[k - 1]
37 lines[k - 1], lines[k] = lines[k], lines[k - 1]
38 return "\n".join(lines) + "\n"
39
40
41def drop_branch(text):
42 """Remove the branch after the first OpSelectionMerge, so the merge is followed by something else."""
43 lines = text.splitlines()
44 k = next(i for i, ln in enumerate(lines) if ln.strip().startswith("OpSelectionMerge"))
45 return "\n".join(lines[:k + 1] + lines[k + 2:]) + "\n"
46
47
48class MergeRule(unittest.TestCase):
49 def test_translated_module_runs(self):
50 text = spv()
51 self.assertEqual(si.run_fragment(text)["%out_mrt0"][0], 0x3F800000)
52 self.assertEqual(len(wi.run_wave(text, wave=32)["outputs"]), 32)
53
54 def test_instruction_between_merge_and_branch(self):
55 bad = break_merge(spv())
56 with self.assertRaisesRegex(si.InvalidModule, "OpSelectionMerge"):
57 si.run_fragment(bad)
58 with self.assertRaisesRegex(wi.InvalidModule, "OpSelectionMerge"):
59 wi.run_wave(bad, wave=32)
60
61 def test_merge_without_its_branch(self):
62 bad = drop_branch(spv())
63 with self.assertRaises(si.InvalidModule):
64 si.run_fragment(bad)
65 with self.assertRaises(wi.InvalidModule):
66 wi.run_wave(bad, wave=32)
67
68 def test_loop_merge_rule(self):
69 ok = [(None, "OpLoopMerge", [], "OpLoopMerge %m %c None"), (None, "OpBranch", [], "OpBranch %h")]
70 si.check_structure(ok)
71 with self.assertRaisesRegex(si.InvalidModule, "OpLoopMerge"):
72 si.check_structure([ok[0], (None, "OpIAdd", [], "%x = OpIAdd %uint %a %b"), ok[1]])
73 with self.assertRaisesRegex(si.InvalidModule, "end of the function"):
74 si.check_structure([ok[0]])
75
76
77if __name__ == "__main__":
78 unittest.main()