From af4929c2d754d0908a40ea1acfff92ee07b95c30 Mon Sep 17 00:00:00 2001 From: Luiz Neves Date: Sun, 22 Nov 2026 23:12:08 -0300 Subject: [PATCH] spirv_mini_interp: run_workgroup shares LDS; OpControlBarrier Every invocation of run_workgroup had its own zero-initialised Workgroup variables, so no CPU test could check lanes communicating through LDS or racing on an LDS dword, and OpControlBarrier was refused. The Workgroup boxes are now the workgroup's (created by the first invocation, shared by the rest), and OpControlBarrier is a point every invocation must reach together, as a subgroup operation is. run_fragment still refuses it (test_barrier_control pins that). tests/semantic/test_interp_shared_lds.py: one lane writes and all read after s_barrier (one and two waves), lanes racing with ds_add_u32 and its returned values, the ds_add_f32 CAS loop on shared LDS, separate workgroups, and a barrier only one invocation reaches. --- tests/semantic/spirv_mini_interp.py | 35 +++++-- tests/semantic/test_interp_shared_lds.py | 118 +++++++++++++++++++++++ 2 files changed, 144 insertions(+), 9 deletions(-) create mode 100644 tests/semantic/test_interp_shared_lds.py diff --git a/tests/semantic/spirv_mini_interp.py b/tests/semantic/spirv_mini_interp.py index 044e8cf80..76475118c 100644 --- a/tests/semantic/spirv_mini_interp.py +++ b/tests/semantic/spirv_mini_interp.py @@ -15,9 +15,10 @@ Design rules (see tests/semantic/README.md): boxes; PushConstant reads can be seeded with a word list; physical-storage-buffer loads/stores (and 32-bit atomics, which with one invocation are read-combine-write) use a flat address -> word dictionary, so they must be 32-bit integers at 4-byte-aligned addresses (anything else raises). Workgroup variables (LDS) are - zero-initialised per invocation like Function ones, so they are only meaningful with one invocation - (run_workgroup does not share them between invocations); 32-bit atomics on them (and on Function variables) - are read-combine-write like the physical-storage-buffer ones. Images are rejected. + zero-initialised; run_workgroup shares them between its invocations, as a workgroup does (one invocation + alone has its own). 32-bit atomics on them (and on Function variables) are read-combine-write like the + physical-storage-buffer ones. OpControlBarrier is a point every invocation of run_workgroup must reach + together (run_fragment refuses it). Images are rejected. * A default run sees zero push constants, no inputs and empty memory, so tests that do not care about them keep the old behaviour. @@ -355,7 +356,10 @@ def run_workgroup(text, invocations, subgroup_size, inputs_for=None, push_consta missing lanes are not running. `inputs_for(i)` gives invocation i's Input values (see run_fragment); push constants and the physical-address memory are shared. Every invocation must reach every subgroup operation, in the same order (the translator emits them in uniform control flow and models EXEC with a variable, so a - lane that is off in EXEC still executes them). + lane that is off in EXEC still executes them). Workgroup variables (LDS) are shared by all the invocations, + and OpControlBarrier, like a subgroup operation, must be reached by every invocation at the same point. + Invocations at the same instruction execute it in invocation order, so lanes racing on one LDS dword see a + defined interleaving (see the lockstep note below). Subgroup operations (Subgroup scope), over the running lanes of the caller's subgroup: * OpGroupNonUniformShuffle returns the value of lane Id. An Id at or past `subgroup_size` is undefined in @@ -370,7 +374,9 @@ def run_workgroup(text, invocations, subgroup_size, inputs_for=None, push_consta if out_of_range not in ("raise", "wrap"): raise ValueError(f"out_of_range: {out_of_range!r}") memory = {} if memory is None else memory - gens = [_invocation(text, (inputs_for(i) if inputs_for else None), push_constants, memory, step=True) + workgroup = {} # Workgroup variable id -> its box, one per workgroup + gens = [_invocation(text, (inputs_for(i) if inputs_for else None), push_constants, memory, step=True, + workgroup=workgroup) for i in range(invocations)] pending = [None] * invocations # what each invocation yielded last; None once it has returned @@ -413,6 +419,8 @@ def run_workgroup(text, invocations, subgroup_size, inputs_for=None, push_consta for req in group: acc |= req[2] results.append(acc) + elif kind == "OpControlBarrier": + results.append(None) # everyone is here: the "same point" check above is the barrier elif kind == "OpGroupNonUniformShuffle": if not 0 <= ident < subgroup_size: if out_of_range == "raise": @@ -430,10 +438,11 @@ def run_workgroup(text, invocations, subgroup_size, inputs_for=None, push_consta _TICK = ("tick", None, None, None) -def _invocation(text, inputs, push_constants, memory, step=False): +def _invocation(text, inputs, push_constants, memory, step=False, workgroup=None): """One invocation as a generator. It yields (opcode, instruction index, value, id) at each subgroup operation - and expects that operation's result back; with `step` it also yields _TICK before each instruction. It - returns run_fragment's result.""" + and at each OpControlBarrier, and expects that operation's result back; with `step` it also yields _TICK before + each instruction. `workgroup` (run_workgroup's) maps a Workgroup variable id to the box all invocations + share; without it the invocation has its own. It returns run_fragment's result.""" inputs = inputs or {} push_constants = list(push_constants or []) memory = {} if memory is None else memory @@ -540,6 +549,8 @@ def _invocation(text, inputs, push_constants, memory, step=False): elif cls == "Input": init = inputs.get(res, types.zero(pointee)) var_box[res] = [list(init) if isinstance(init, (list, tuple)) else init] + elif cls == "Workgroup" and workgroup is not None and res in workgroup: + var_box[res] = workgroup[res] # another invocation of the workgroup made it elif cls in ("Function", "Output", "Workgroup", "Private"): if len(a) > 2: init = values[a[2]] @@ -548,6 +559,8 @@ def _invocation(text, inputs, push_constants, memory, step=False): var_box[res] = [types.zero(pointee)] if cls == "Output": outputs.append(res) + if cls == "Workgroup" and workgroup is not None: + workgroup[res] = var_box[res] # the first invocation's box is the workgroup's else: raise UnsupportedConstruct(f"storage class {cls}") pointers[res] = ("pc", 0) if cls == "PushConstant" else (var_box[res], 0) @@ -880,8 +893,12 @@ def _invocation(text, inputs, push_constants, memory, step=False): values[res] = val(a[1]) > val(a[2]) elif op == "OpUGreaterThanEqual": values[res] = val(a[1]) >= val(a[2]) + elif op == "OpControlBarrier": + # : run_workgroup's invocations meet here (each has finished + # every earlier instruction, and with shared Workgroup memory sees the others' writes). run_fragment + # refuses it, as it does a subgroup operation: a barrier belongs to a workgroup. + yield (op, pc - 1, None, None) elif op == "OpGroupNonUniformShuffle": - # OpGroupNonUniformShuffle ; the scope must be Subgroup (3). if types.t[a[0]][0] != "int" or val(a[1]) != 3: raise UnsupportedConstruct("OpGroupNonUniformShuffle other than a Subgroup-scope integer") values[res] = yield (op, pc - 1, val(a[2]), val(a[3])) diff --git a/tests/semantic/test_interp_shared_lds.py b/tests/semantic/test_interp_shared_lds.py new file mode 100644 index 000000000..f97b7f406 --- /dev/null +++ b/tests/semantic/test_interp_shared_lds.py @@ -0,0 +1,118 @@ +"""spirv_mini_interp.run_workgroup shares Workgroup (LDS) memory between its invocations, and OpControlBarrier. + +Until this change every invocation of run_workgroup had its own zero-initialised Workgroup variables, so no CPU test +could check lanes communicating through LDS or racing on an LDS dword (each saw only its own writes), and +OpControlBarrier (s_barrier) was refused. Now the Workgroup boxes are the workgroup's, and a barrier is a point every +invocation must reach together, as a subgroup operation is; run_fragment still refuses it. The programs below are +translated compute shaders (one or two wave32 waves, 512 bytes of LDS) writing their results through the +vk_compute_test V#. Standard library only; no GPU, no game files. +""" +import os +import struct +import sys +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +if HERE not in sys.path: + sys.path.insert(0, HERE) # python -I leaves the script's folder off sys.path + +import support # noqa: E402 (support puts tools/ on sys.path, honouring LEONIDA_TOOLS_DIR) +import spirv_mini_interp as si # noqa: E402 + +VSHARP = [0, 0, 0xFFFFFFFF, 0x31016FAC] # base 0, num_records max, raw + + +def fssm(invocations): + b = bytearray(0x148) + struct.pack_into("<4I", b, 0x138, 0x8088, invocations, 1, 1) # 4 user SGPRs, wg id in s4, 512 B LDS + return bytes(b) + + +def run(name, lines, invocations=32): + spv = support.translate_lines(name, lines + ["s_endpgm"], fssm=fssm(invocations)) + mem = {} + si.run_workgroup(spv, invocations, 32, inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), + "%sg_lane": i % 32}, + push_constants=VSHARP + [0] * 28, memory=mem) + return [mem.get(4 * i) for i in range(invocations)] + + +STORE_V3 = ["v_lshlrev_b32_e32 v4, 2, v0", "buffer_store_dword v3, v4, s[0:3], 0 offen"] # out[lane] = v3 + + +class SharedLds(unittest.TestCase): + def test_one_lane_writes_every_lane_reads_after_the_barrier(self): + lines = ["v_mov_b32_e32 v1, 0x40", "v_cmpx_eq_u32_e32 0, v0", "v_mov_b32_e32 v2, 0x1234", + "ds_write_b32 v1, v2", "s_mov_b32 exec_lo, -1", "s_waitcnt lgkmcnt(0)", "s_barrier", + "ds_read_b32 v3, v1", "s_waitcnt lgkmcnt(0)"] + STORE_V3 + for n in (32, 64): # one wave, and two waves of one workgroup + with self.subTest(invocations=n): + self.assertEqual(run("cs_lds_bcast", lines, n), [0x1234] * n) + + def test_lanes_racing_on_one_dword(self): + # every lane adds 1 to one LDS dword (zero-initialised); after the barrier each reads the total + lines = ["v_mov_b32_e32 v1, 0x80", "v_mov_b32_e32 v2, 1", "ds_add_u32 v1, v2", "s_waitcnt lgkmcnt(0)", + "s_barrier", "ds_read_b32 v3, v1", "s_waitcnt lgkmcnt(0)"] + STORE_V3 + for n in (32, 64): + with self.subTest(invocations=n): + self.assertEqual(run("cs_lds_count", lines, n), [n] * n) + + def test_returned_values_are_each_old_value_once(self): + lines = ["v_mov_b32_e32 v1, 0x80", "v_mov_b32_e32 v2, 1", "ds_add_rtn_u32 v3, v1, v2", + "s_waitcnt lgkmcnt(0)"] + STORE_V3 + self.assertEqual(sorted(run("cs_lds_ticket", lines)), list(range(32))) + + def test_a_cas_loop_on_shared_lds(self): + # ds_add_f32 is an OpAtomicCompareExchange loop: 32 lanes each add 1.0 to one dword + lines = ["v_mov_b32_e32 v1, 0x80", "v_mov_b32_e32 v2, 1.0", "ds_add_f32 v1, v2", "s_waitcnt lgkmcnt(0)", + "s_barrier", "ds_read_b32 v3, v1", "s_waitcnt lgkmcnt(0)"] + STORE_V3 + self.assertEqual(run("cs_lds_fadd", lines), [struct.unpack("