From 18af7e9fa2673b6d184ad6d3d90b8e4024577719 Mon Sep 17 00:00:00 2001 From: DadaCap <167002618+DadaCap@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:52:51 +0100 Subject: [PATCH 1/2] wave64_emulate_opt: fold a region at most one lane of the wave runs (SHADER-W64-ONE-LANE-FOLD) A forward must-analysis proves EXEC at most one lane after v_cmp(x)_eq_{i,u}32 , v0 (v0 the thread id, not written since entry; the group one row of x or rows of whole waves) and through copies, ANDs and saveexecs of that mask. Such an s_cbranch_execz region folds with several stores and in a cycle, orders no accesses inside, and when it writes no EXEC its v_readfirstlane_b32 is the lane's own value. One 1024-thread library compute program: 639 -> 33 OpSwitch cases, spirv-val valid. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Gt9hwRYcpySx4P4ncQ3wD5 --- docs/design.md | 1 + tests/semantic/test_wave64_one_lane_fold.py | 147 ++++++++++++++++++++ tools/rdna2spirv.py | 16 ++- tools/wave64_emulate_opt.py | 127 +++++++++++++++-- 4 files changed, 278 insertions(+), 13 deletions(-) create mode 100644 tests/semantic/test_wave64_one_lane_fold.py diff --git a/docs/design.md b/docs/design.md index 1b9e513adf..4e848375e4 100644 --- a/docs/design.md +++ b/docs/design.md @@ -419,6 +419,7 @@ How the generated SPIR-V expects the runtime to work: | Wave64 leading-bit scans | With `--wave64-emulate`, `s_flbit_i32_b32` and `s_flbit_i32` of a lane mask use the same wave-wide exchange as `s_bcnt1` and `s_ff1`. These reads prevent lane-local EXEC-zero folding and require synchronized scheduling in wave-divergent blocks. Plain scalar inputs still allow the fold. Hand-written compute shaders in `tests/semantic/test_wave64_emulate_opt.py` check EXECZ at 64 and 128 threads and a branch on SCC taken by just one wave at 128 threads. The strict CPU workgroup interpreter observes the unsigned scan of VCC_LO = 8 returning 28 in the expected invocations. Both scan forms pass `spirv-val --target-env vulkan1.2`. | | Wave64 emulation: scalar exits from a folded EXECZ region | A folded lane-local `s_cbranch_execz`/`execnz` region may leave to its join from inside, for example `s_cmp` + `s_cbranch_scc0/scc1` straight to the label that restores EXEC. The ISA then skips the rest of the region for the whole wave. `find_local_exec_folds` in `tools/wave64_emulate_opt.py` builds the region's sub-CFG with an exit node for every edge to the join, so `cfg_structure.structure` puts each later block of the region behind a `%pc` guard; the exit node itself emits nothing. Before this the edge was dropped and the block after the branch ran whenever the lane was active. Confirmed on the CPU against the native wave64 translation and the ISA: `tests/semantic/test_wave64_emulate_opt.py` `test_folded_region_scalar_branch_to_join_skips_the_rest` (taken and not-taken `scc0`/`scc1`, 64 and 128 threads, the region still folded) fails before the change on the four taken cases. **Not GPU-verified.** | | Barycentric fallback (`--bary-fallback`) | For devices without `VK_KHR_fragment_shader_barycentric` (NVIDIA Pascal, for one), and for Mesa ANV's known BaryCoordKHR.i bug (SHADER-925). The raw pair a PS reads comes from an ordinary vec3 input, `%bary`, at the lowest location none of the shader's attributes uses, instead of `BuiltIn BaryCoordKHR`. The module needs neither the `FragmentBarycentricKHR` capability nor the extension, and the index records the location as `bary_fallback_input`. `tools/bary_fallback_gs.py` writes a pass-through geometry shader that supplies (1,0,0), (0,1,0), (0,0,1) at the triangle vertices. GPU-checked on NVIDIA Pascal and Intel Arc B580/Mesa ANV: ANV native `ps_uniform_branch` and `ps_scc_mask32` fail with i=0.0, while the fallback passes and `ps_bary` passes natively. `make_game.py` and `scripts/run_gpu_tests.py` select the fallback automatically for Mesa ANV. `LEONIDA_BARY_FALLBACK=1` forces fallback and `LEONIDA_BARY_FALLBACK=0` forces native barycentrics consistently in both entry points; explicit `--bary-fallback` also forces the fallback in `make_game.py`. The standalone `build.py`/`check.py` path follows the same variable/probe rule. Checked in `tests/semantic/test_bary_fallback.py` and the builder/runner wiring tests. | +| Wave64 emulation: a folded region at most one lane runs (SHADER-W64-ONE-LANE-FOLD) | A compute shader picks one thread for a tail (clear LDS, then after a barrier sum it up and store) with `v_cmpx_eq_u32 c, v0` or `v_cmp_eq_u32 m, c, v0` + `s_and_saveexec_b64 _, m`. `v0` is LocalInvocationId.x and a wave is 64 consecutive threads, so no two lanes of a wave share it when the group is one row (`size_y * size_z == 1`) or a row is whole waves (`size_x % 64 == 0`); then the compare is true in at most one lane. `_one_lane_in` in `tools/wave64_emulate_opt.py` proves per block, forward over the CFG with intersection at joins, that EXEC is at most one lane: `v0` must not have been written since entry, and the mask goes on through `s_mov_b64`, `s_and_b64` with anything, `s_andn2_b64` of it, a saveexec of it and any later compare (a compare is 0 in inactive lanes). Where `run` of an `s_cbranch_execz` region is proved so, `find_local_exec_folds` drops the one-store-per-domain and acyclic limits and marks the fold `one_lane` (the region's EXEC writes already must keep a skipped lane inactive, so it stays at most one lane): with one lane the lane's own order of its accesses is the wave's, so `x_memory_order` orders nothing inside it. A `v_readfirstlane_b32` is allowed in such a fold when the region writes no EXEC at all: the lane runs the fold only when active, so it is the first lane of EXEC and the result is its own value (also into `vcc_lo`/`vcc_hi`). Confirmed on the CPU against the plain round emulation in both invocation orders: `tests/semantic/test_wave64_one_lane_fold.py` (128 threads; LDS writes, a barrier, first-lane reads and two stores to one address; a lane of wave 0, of wave 1, or none; the negatives `v_cmpx_eq` of a non-id VGPR, `v0` overwritten, `v_cmpx_gt`, and a 32 x 4 group are not marked one-lane). One 1024-thread library compute shader goes from 639 to 33 `OpSwitch` cases and passes `spirv-val`. **Not GPU-verified.** | | Metadata index | `spirv/index.json`: one entry per translated shader with its stage, `wave64` / `subgroup_size`, SPIR-V capabilities and extensions, the Vulkan **features** to enable (barycentrics, interlock, mesh, geometry, Float64, Int64, buffer device address, write-without-format, `shaderFmaFloat32` for `--fma khr`, …), `needs_maintenance8`, the descriptor bindings it uses (set 0), push-constant size, `local_size`, `user_sgprs` (CS), `lds_bytes`, mesh `max_vertices`/`max_primitives`/`params`, geometry inputs/outputs, vertex-input locations and types, full `vertex_input_signature` (ISG1 register/mask/system-value/component-type, for PSO lookup), `wave64_emulated` (true for VS/PS/GS wave64, which the translator emits as per-subgroup code with no cross-half exchange, and for compute/mesh translated with `--wave64-emulate`; the runtime does not use it: it reads `wave64`, `subgroup_size` and `wave64_exchange`), `dynamic_format` (runtime V# FORMAT: codes outside FORMATS decode to 0) / `fixed_format_codes`, `src_sha256` and optional `fssm_sha256` (via `--fssm-dir`), PS system inputs, `bary_fallback_input` (`--bary-fallback`: the location of the barycentric input), `mesh_compute` (`--mesh-compute`: the slot layout and push-constant size), `pc_tail` (`--pc-tail-ubo`: the set, binding and size of the uniform block that holds the push-constant tail), and input/output locations. A shader translated with `--wave64-emulate` carries `wave64_exchange: "workgroup"` and `subgroup_size: null`: any subgroup size is exact, request none. Otherwise `subgroup_size` (64 for wave64, 32) is what the PSO asks for through `VkPipelineShaderStageRequiredSubgroupSizeCreateInfo` where the device lists the stage in `requiredSubgroupSizeStages` (docs/d3d12_vulkan.md section 3.2): that list is the driver's, not "compute/mesh only". The AMD Windows driver reports FRAGMENT, COMPUTE, TASK and MESH (measured on a Radeon 880M, driver 26.11.2, sizes 32..64), and current Mesa RADV on GFX10+ reports COMPUTE, FRAGMENT and task/mesh (`src/amd/vulkan/radv_physical_device.c`, `requiredSubgroupSizeStages`, Mesa main at 152b9cde; older Mesa: compute only), so wave64 pixel shaders can run exact there. NVIDIA lists every stage but only size 32, so there a native wave64 shader cannot get 64 and wave64 PS/VS/GS stay 2x32. A runtime can create every pipeline at load time from it without parsing SPIR-V. | | Full-corpus pipeline build | `vk_pipeline_check pipeline_cache.bin --jobs 4` on an RTX 4060 Ti (NVIDIA 595 driver): **all 26,503 shaders become real pipelines, 0 failures** (cs 2,689, ps 12,101, ms 9,282, vs 2,236, gs 195; graphics stages with generated stub partners). Compile time 40,784 s of CPU (2.84 h wall on 4 threads): cs 23,633 s (mean 8.8 s; the ray-tracing ScreenProbes/RTShadowTrace shaders take 2-19 min each), ps 11,481 s, ms 5,395 s, vs 275 s. The resulting `VkPipelineCache` is 3.81 GB; seeding a run with it makes those pipelines instant, which is what a fast first boot needs. The cache is per driver and GPU, and a shader whose SPIR-V changes compiles again (the checker resumes from the file). Neither register storage (one variable per register) nor smaller SPIR-V cut NVIDIA compile time: the big ray-tracing shaders are expensive as such, so the runtime should compile them in the background rather than block on them. | | `v_cndmask_b32` source modifiers | `v_cndmask_b32` only moves bits, so a VOP3 `abs` on `src0`/`src1` clears bit 31 and `neg` flips it (`abs` first) as plain bit moves (`OpBitwiseAnd 0x7FFFFFFF`, then `OpBitwiseXor 0x80000000`, `Gen.src_u_sign_mods`), never `FAbs`/`OpFNegate`: a signalling NaN stays signalling and a denormal isn't flushed. Until 2026-11-23 the sources went through `Gen.modify`, and the mini interpreter quieted them (`-v1` of `0x7F800001` gave `0xFFC00001`, not `0xFF800001`). **Not measured on hardware for this instruction**: the rule follows the same VOP3 input modifiers measured as sign-bit moves on `v_cmp_class_f32` (gfx1036, all four IEEE/denorm modes, row "Floating-point class compare" above), and LLVM's AMDGPU backend moves `fneg`/`fabs` through a select into `v_cndmask_b32_e64`'s source modifiers (`AMDGPUTargetLowering::foldFreeOpFromSelect`), which is only exact if they are sign-bit moves. Checked on the CPU and with `spirv-val` by `tests/semantic/test_cndmask_sign_mods.py` (15 words including signalling/quiet NaNs, denormals, zeros and infinities x `v`, `-v`, `\|v\|`, `-\|v\|` x both operands). | diff --git a/tests/semantic/test_wave64_one_lane_fold.py b/tests/semantic/test_wave64_one_lane_fold.py new file mode 100644 index 0000000000..046f6df92c --- /dev/null +++ b/tests/semantic/test_wave64_one_lane_fold.py @@ -0,0 +1,147 @@ +"""--wave64-emulate: a region that at most one lane of the wave runs (EXEC narrowed by `v_cmpx_eq_u32 c, v0`, v0 +being the thread id) folds lane-locally with several stores, and its v_readfirstlane_b32 takes the lane's own value. + +Hand-written programs, 128 threads (two waves), on the workgroup interpreter of test_wave64_emulate_opt.py in both +invocation orders, compared with the plain round emulation (no fold); the constant picks a lane of wave 0, of wave 1, +or none. The negatives must not take the one-lane path and must still match. + +Run from the repository root: python -I tests/semantic/test_wave64_one_lane_fold.py +""" +import contextlib +import os +import re +import sys +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +if HERE not in sys.path: + sys.path.insert(0, HERE) + +import test_wave64_emulate_opt as base # noqa: E402 + +opt = base.wave64_emulate_opt +PUSH = base.VSHARP + [0] * 28 +OUT = 0x30000 +BIG = ("buffer_", "ds_") + +# One lane clears LDS (three writes, the last two to one address), every wave meets at a barrier, the same lane +# reads LDS back, takes first-lane copies of what it read (one into vcc_lo) and stores twice to one address. +PROGRAM = f""" + s_mov_b64 exec, -1 + v_lshlrev_b32_e32 v9, 2, v0 + v_mov_b32_e32 v4, 7 + v_add_nc_u32_e32 v4, v0, v4 + s_mov_b64 s[40:41], exec + {{pick}} + s_mov_b64 vcc, exec + s_cbranch_execz @A + v_mov_b32_e32 v2, 0 + v_mov_b32_e32 v5, 11 + ds_write_b32 v2, v5 + v_mov_b32_e32 v5, 12 + ds_write_b32 v2, v5 offset:4 + v_mov_b32_e32 v5, 13 + ds_write_b32 v2, v5 +A: + s_mov_b64 exec, s[40:41] + s_barrier + s_and_b64 exec, vcc, exec + s_cbranch_execz @B + v_mov_b32_e32 v2, 0 + ds_read_b32 v6, v2 + ds_read_b32 v7, v2 offset:4 + s_waitcnt lgkmcnt(0) + v_readfirstlane_b32 s12, v6 + v_readfirstlane_b32 vcc_lo, v7 + v_add_nc_u32_e32 v8, s12, v0 + v_add_nc_u32_e32 v8, vcc_lo, v8 + v_add_nc_u32_e32 v3, {OUT + 512:#x}, v9 + buffer_store_dword v4, v3, s[0:3], 0 offen + buffer_store_dword v8, v3, s[0:3], 0 offen +B: + s_mov_b64 exec, -1 + v_add_nc_u32_e32 v9, {OUT:#x}, v9 + buffer_store_dword v4, v9, s[0:3], 0 offen + s_endpgm +""" + + +def assemble(text): + """`(text, nbytes)` list of a listing with `name:` labels and `s_cbranch_x @name` branches.""" + items, labels, pc = [], {}, 0 + for raw in text.strip().splitlines(): + line = raw.strip() + if line.endswith(":"): + labels[line[:-1]] = pc + continue + n = 8 if line.startswith(BIG) or "0x" in line else 4 + items.append((pc, line, n)) + pc += n + return [(re.sub(r"@(\w+)", lambda m: str((labels[m.group(1)] - p - n) // 4 & 0xFFFF), line), n) + for p, line, n in items] + + +@contextlib.contextmanager +def rounds_only(): + saved = opt.find_local_exec_folds, opt.plan_structured_emulation + opt.find_local_exec_folds = lambda *a, **k: ({}, {}, set()) + opt.plan_structured_emulation = lambda *a, **k: None + try: + yield + finally: + opt.find_local_exec_folds, opt.plan_structured_emulation = saved + + +class OneLaneTests(unittest.TestCase): + def check(self, pick, size=(128, 1, 1)): + """Translate and run the program; compare with the round emulation. Returns (folds, memory).""" + insns = assemble(PROGRAM.replace("{pick}", pick)) + seen = [] + fold = opt.find_local_exec_folds + + def spy(*a, **k): + seen.append(fold(*a, **k)) + return seen[-1] + + opt.find_local_exec_folds = spy + try: + spv, _ = base._translate_encoded("cs_one_lane", insns, size, rsrc2=0x20088) + finally: + opt.find_local_exec_folds = fold + with rounds_only(): + ref, _ = base._translate_encoded("cs_one_lane_ref", insns, size, rsrc2=0x20088) + want, _ = base.run_emulated_workgroup(ref, size, push_constants=PUSH) + want = {k: v for k, v in want.items() if k >= OUT} + for rev in (False, True): + got, _ = base.run_emulated_workgroup(spv, size, push_constants=PUSH, reverse_order=rev) + self.assertEqual({k: v for k, v in got.items() if k >= OUT}, want, f"reverse={rev}") + return seen[-1][0], want + + def test_one_lane_folds_and_matches(self): + for c in (0, 65, 200): # a lane of wave 0, of wave 1, no lane + with self.subTest(c=c): + folds, mem = self.check(f"v_cmpx_eq_u32_e32 {c}, v0") + self.assertEqual(sum(fd["one_lane"] for fd in folds.values()), 2) + self.assertEqual(mem.get(OUT + 512 + 4 * c), 13 + 12 + c if c < 128 else None) + self.assertEqual(mem[OUT + 4 * 127], 7 + 127) + + def test_one_lane_from_a_compare_mask(self): + folds, mem = self.check("v_cmp_eq_u32_e64 s[42:43], 3, v0\ns_and_saveexec_b64 s[44:45], s[42:43]") + self.assertEqual(sum(fd["one_lane"] for fd in folds.values()), 2) + self.assertEqual(mem[OUT + 512 + 12], 13 + 12 + 3) + + def test_not_one_lane_keeps_the_rounds(self): + variants = { + "not the thread id": ("v_cmpx_eq_u32_e32 0, v4", (128, 1, 1)), + "thread id overwritten": ("v_mov_b32_e32 v0, 0\nv_cmpx_eq_u32_e32 0, v0", (128, 1, 1)), + "not an equality": ("v_cmpx_gt_u32_e32 2, v0", (128, 1, 1)), + "rows of 32 threads": ("v_cmpx_eq_u32_e32 0, v0", (32, 4, 1)), + } + for name, (pick, size) in variants.items(): + with self.subTest(name): + folds, _ = self.check(pick, size) + self.assertFalse(any(fd["one_lane"] for fd in folds.values())) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index fa3c1aadf9..f2b24bbabc 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -387,6 +387,7 @@ def __init__(self, stage, hoist_reg_ptrs=False, cache_active=False): self.emulate = False # --wave64-emulate: exact wave64 on any subgroup size (cs/ms; see x_round) self.emulate_inline = False # emulate: current block emits direct inline barriers (no x_split) self.emulate_plan = None # emulate: structured plan from wave64_emulate_opt.plan_structured_emulation + self.x_one_lane = False # emulate: emitting a fold that at most one lane of the wave runs ("one_lane") self.mini_segs = defaultdict(list) # emulate_plan: mini_idx -> continuation segment ids self.tail_segs = [] # emulate_plan: continuation segment ids belonging to tail_scheduler self.x_seg = 0 # emulate: number of the next continuation segment (past the block numbers) @@ -5836,7 +5837,8 @@ def x_memory_order(self, op): store = "store" in op or op.startswith("ds_write") reads = not store writes = store or "atomic" in op or (kind == "lds" and not op.startswith("ds_read")) - if (kind, "w") in self.x_dirty or (writes and (kind, "r") in self.x_dirty): + # In a fold that at most one lane of the wave runs, that lane's own order is the wave's. + if not self.x_one_lane and ((kind, "w") in self.x_dirty or (writes and (kind, "r") in self.x_dirty)): self.x_order_barrier() if reads: self.x_dirty.add((kind, "r")) @@ -7790,6 +7792,10 @@ def _insn(self, ins): # hardware reads the first lane's copy of the whole mask; here the lane's own copy is its bit. self.dst(a[0], self.src_u(a[1])) return + if self.x_one_lane: + # A fold that at most one lane runs and that leaves EXEC alone: this lane is the first in EXEC. + self.dst(a[0], self.src_u(a[1])) + return if self.wave32_fragment: self.uses_subgroup = self.uses_ballot = True v, act = self.src_u(a[1]), self.active_b() @@ -18387,8 +18393,12 @@ def target(ins): folds, fold_chain, absorbed = {}, {}, set() if g.emulate: g.scc_live = wave64_emulate_opt.scc_live_outs(blocks, succ) + # v0 is LocalInvocationId.x (the prologue) and a wave is 64 consecutive threads, so no two lanes of a wave + # share v0 when the group is one row of x or a row is a whole number of waves. + sx, sy, sz = g.cs["size"] if stage == "cs" else (0, 0, 0) + tid = frozenset({0}) if stage == "cs" and (sy * sz == 1 or sx % 64 == 0) else frozenset() folds, fold_chain, absorbed = wave64_emulate_opt.find_local_exec_folds( - blocks, raw_edges, succ, g.lane_masks, g.scc_live, g.mask_writes) + blocks, raw_edges, succ, g.lane_masks, g.scc_live, g.mask_writes, tid) if STRUCTURED: g.emulate_plan = wave64_emulate_opt.plan_structured_emulation( blocks, raw_edges, succ, folds, fold_chain, absorbed, g.lane_masks, g.scc_live, g.x_lanes) @@ -18415,6 +18425,7 @@ def emit_folded_region(fd): g.emit(f"{lbl_do} = OpLabel") marks_before = len(g.x_marks) body_before = len(g.body) + g.x_one_lane = fd["one_lane"] if fd["sub_tree"] is None: for ins in blocks[fd["run"]]: op = base_op(ins["op"]) @@ -18508,6 +18519,7 @@ def emit_folded_region(fd): g.emit(f"{again} = OpIEqual %bool {v} {g.cu(sub_id)}") g.emit(f"OpBranchConditional {again} {head} {end}") g.emit(f"{end} = OpLabel") + g.x_one_lane = False assert len(g.x_marks) == marks_before, "wave64 emulation: x_split inside a folded lane-local region" assert not any("OpControlBarrier" in l for l in g.body[body_before:]), \ "wave64 emulation: OpControlBarrier inside a folded lane-local region" diff --git a/tools/wave64_emulate_opt.py b/tools/wave64_emulate_opt.py index f8a50e0eb8..f98fe7500b 100644 --- a/tools/wave64_emulate_opt.py +++ b/tools/wave64_emulate_opt.py @@ -1135,7 +1135,99 @@ def _region_has_cycle(region, succ): return False -def find_local_exec_folds(blocks, raw_edges, succ, lane_masks, scc_live, mask_writes=frozenset()): +_TID_EQ = frozenset(f"v_cmp{x}_eq_{t}32" for x in ("", "x") for t in ("i", "u")) +_VGPR_READ_ONLY = ("exp", "buffer_store", "tbuffer_store", "image_store", "global_store", "flat_store", "scratch_store", + "ds_write", "ds_store", "v_cmp", "v_readlane", "v_readfirstlane") + + +def _one_key(x, cmp_dest=False): + """The mask an operand names for `_one_lane_in`: "exec", "vcc" or the first SGPR of a pair (else None).""" + t = x.get("t") if x.get("k") == "special" else None + if t == "exec" or t == "vcc" or (cmp_dest and t == "vcc_lo"): + return "vcc" if t.startswith("vcc") else t + return _sgpr_pair(x) + + +def _one_lane_step(ins, st): + """`_one_lane_in` across one instruction: `st` = (VGPRs still the thread id, masks with at most one lane set).""" + tid, one = st + meta = _get_op_meta(ins["op"]) + op, a = meta[0], ins["args"] + if meta[1]: + return st + if op.startswith(("v_movrel", "v_swaprel")): + tid = frozenset() + elif a and a[0].get("k") == "vgpr" and not op.startswith(_VGPR_READ_ONLY): + # A memory result can be one register longer than its operand says (tfe); a swap writes both operands. + vdst = a[:2] if op.startswith("v_swap") else a[:1] + tid = tid - {x["r"] + i for x in vdst if x.get("k") == "vgpr" + for i in range(x.get("n", 1) + (not op.startswith("v_")))} + may_w = _scalar_rw_with_meta(ins, meta)[1] + writes_exec = bool(meta[8] & _FLAG_WRITES_EXEC_OP) or ( + bool(a) and a[0].get("k") == "special" and a[0].get("t", "").startswith("exec")) + if not writes_exec and not may_w & (_ALL_SGPRS | 1 << _BIT_VCC): + return tid, one + + def is_one(x): + k = _one_key(x) + return k is not None and k in one + + dest, val, exec_val = None, False, False + if op.startswith("v_cmp"): + # A compare writes 0 in every inactive lane, so its result is within EXEC; `== c` of the thread id is true + # in at most one lane of the wave. + val = "exec" in one + if op in _TID_EQ and not ins.get("mods") and not ins["op"].endswith("_sdwa") and len(a) >= 2: + x, y = a[-2:] + if x.get("k") == "vgpr": + x, y = y, x + val = val or (x.get("k") == "imm" and isinstance(x.get("v"), int) and y.get("k") == "vgpr" + and y.get("n", 1) == 1 and y["r"] in tid) + exec_val = val + if not op.startswith("v_cmpx"): + dest = "vcc" if len(a) == 2 else _one_key(a[0], cmp_dest=True) + elif op in ("s_and_saveexec_b64", "s_andn2_saveexec_b64") and len(a) == 2: + dest, val = _one_key(a[0]), "exec" in one # the old EXEC + exec_val = is_one(a[1]) or (op == "s_and_saveexec_b64" and "exec" in one) + elif op in ("s_mov_b64", "s_and_b64", "s_andn2_b64") and len(a) >= 2: + # The result is within the first source (and within the second for s_and_b64). + val = is_one(a[1]) or (op == "s_and_b64" and len(a) > 2 and is_one(a[2])) + dest = _one_key(a[0]) + exec_val = val + out = {k for k in one if k != "exec" and not may_w & (1 << _BIT_VCC if k == "vcc" else 3 << k)} + if not writes_exec and "exec" in one: + out.add("exec") + if writes_exec and exec_val: + out.add("exec") + if dest not in (None, "exec") and val: + out.add(dest) + return tid, frozenset(out) + + +def _one_lane_in(active_blocks, succ, tid): + """Per block, whether EXEC is certainly at most one lane of the wave on entry (forward must-analysis, merge = + intersection). `tid`: VGPRs whose entry value no two lanes of a wave share (the thread id); one holds that + value until it is written. `v_cmp(x)_eq_{i,u}32 , ` is true in at most one lane, and a + mask stays at most one lane through a copy, an AND with anything, `s_andn2_b64` of it and a saveexec of it.""" + n = len(active_blocks) + state_in = [None] * n + state_in[0] = (frozenset(tid), frozenset()) + work = collections.deque([0]) + while work: + b = work.popleft() + st = state_in[b] + for ins in active_blocks[b]: + st = _one_lane_step(ins, st) + for v in succ[b]: + old = state_in[v] + new = st if old is None else (old[0] & st[0], old[1] & st[1]) + if new != old: + state_in[v] = new + work.append(v) + return [s is not None and "exec" in s[1] for s in state_in] + + +def find_local_exec_folds(blocks, raw_edges, succ, lane_masks, scc_live, mask_writes=frozenset(), tid=frozenset()): """Find safe lane-local `s_cbranch_execz`/`nz` regions to fold inline under --wave64-emulate. Allows read-only regions (including regions with internal scalar-counted loops) AND acyclic @@ -1145,7 +1237,7 @@ def find_local_exec_folds(blocks, raw_edges, succ, lane_masks, scc_live, mask_wr Returns `(folds, fold_chain, absorbed)`: - `folds`: dict `head_block -> {"run": int, "skip": int, "region": frozenset[int], "order": list[int], "sub_tree": list | None, "mem_reads": frozenset[str], - "mem_writes": frozenset[str], "mem_stats": tuple}` + "mem_writes": frozenset[str], "mem_stats": tuple, "one_lane": bool}` containing only the maximal (outermost) folded regions. - `fold_chain`: dict `head_block -> skip_block` when `skip_block` has no predecessors outside `{head_block} | region` and can be emitted directly after the fold in the same block. @@ -1182,6 +1274,7 @@ def find_local_exec_folds(blocks, raw_edges, succ, lane_masks, scc_live, mask_wr may_w = 0 exec_writes = [] sgpr_write_ops = [] + first_lane = False term = ("fall", None) for ins in insns: @@ -1202,9 +1295,12 @@ def find_local_exec_folds(blocks, raw_edges, succ, lane_masks, scc_live, mask_wr clean = False continue flags = m[8] - if flags & _FLAG_FORBIDDEN_FOLD or _vcc_pair_collects_mask(ins, lane_masks): + # A v_readfirstlane_b32 only in a fold that at most one lane runs and that leaves EXEC alone (below). + rfl = bool(tid) and m[0] == "v_readfirstlane_b32" + if (flags & _FLAG_FORBIDDEN_FOLD and not rfl) or _vcc_pair_collects_mask(ins, lane_masks): clean = False continue + first_lane = first_lane or rfl acc = m[9] if acc is not None: kind, r, w = acc @@ -1268,11 +1364,13 @@ def find_local_exec_folds(blocks, raw_edges, succ, lane_masks, scc_live, mask_wr kill[b] = k_mask terms[b] = term if clean: - blk_info[b] = (True, (mem_ops, mem_r, mem_w, lds_ops, lds_r, lds_w), may_w, exec_writes, sgpr_write_ops) + blk_info[b] = (True, (mem_ops, mem_r, mem_w, lds_ops, lds_r, lds_w), may_w, exec_writes, sgpr_write_ops, + first_lane) else: - blk_info[b] = (False, _EMPTY_MEM_STATS, 0, (), ()) + blk_info[b] = (False, _EMPTY_MEM_STATS, 0, (), (), False) scalar_live_in = _solve_scalar_liveness(use, kill, preds) + one_lane_in = None # Gather candidate s_cbranch_execz / s_cbranch_execnz blocks with single-entry/single-exit post-dominated regions. candidates = [] @@ -1324,10 +1422,16 @@ def find_local_exec_folds(blocks, raw_edges, succ, lane_masks, scc_live, mask_wr lds_ops += lo lds_r = lds_r or lr lds_w = lds_w or lw - if (mem_w and mem_ops > 1) or (lds_w and lds_ops > 1): - continue - if (mem_w or lds_w) and _region_has_cycle(region, succ): - continue + # With at most one lane in EXEC (kept so by the EXEC check below) the lane's own order of its accesses is + # the wave's, and v_readfirstlane_b32 reads the lane's own value as long as the region leaves EXEC alone. + first_lane = any(blk_info[u][5] for u in region) + one = (first_lane or (mem_w and mem_ops > 1) or (lds_w and lds_ops > 1) + or ((mem_w or lds_w) and _region_has_cycle(region, succ))) + if one: + if one_lane_in is None: + one_lane_in = _one_lane_in(active_blocks, succ, tid) + if not one_lane_in[run] or (first_lane and any(blk_info[u][3] for u in region)): + continue # No scalar written in R may be live-in at `skip`. region_may_w = 0 for u in region: @@ -1338,12 +1442,12 @@ def find_local_exec_folds(blocks, raw_edges, succ, lane_masks, scc_live, mask_wr if not _exec_writes_stay_inactive(region, blk_info, scalar_live_in[run]): continue candidates.append((len(region), b, run, skip, frozenset(region), - (mem_ops, mem_r, mem_w, lds_ops, lds_r, lds_w))) + (mem_ops, mem_r, mem_w, lds_ops, lds_r, lds_w), bool(one))) # Validate innermost regions first so nested s_cbranch_execz/nz inside an outer region are already verified. candidates.sort(key=lambda item: (item[0], item[1])) valid = {} - for _, b, run, skip, region, mem_stats in candidates: + for _, b, run, skip, region, mem_stats, one in candidates: ok = True for u in region: tkind, top = terms[u] @@ -1400,6 +1504,7 @@ def find_local_exec_folds(blocks, raw_edges, succ, lane_masks, scc_live, mask_wr "mem_reads": mem_reads, "mem_writes": mem_writes, "mem_stats": mem_stats, + "one_lane": one, # at most one lane runs it: no order between lanes, v_readfirstlane_b32 is a copy } # Select maximal (non-overlapping outermost) folded regions. From a78040bb133cb25433eb92a2536ab87435c32e7d Mon Sep 17 00:00:00 2001 From: DadaCap <167002618+DadaCap@users.noreply.github.com> Date: Fri, 27 Nov 2026 13:39:13 +0100 Subject: [PATCH 2/2] Wave64 one-lane fold: loop a one-block self-loop, half EXEC writes, implicit carry VCC Three soundness gaps the review reproduced against the round emulation: - A region that is one block branching back to itself was emitted straight, so it ran once. It now gets a sub-CFG like a multi-block region and is emitted as a loop through cfg_structure.structure. This also covers the read-only self-loop that was already folded before the one-lane rule. - A write of one half of EXEC (v_cmp_eq_u32_e64 exec_lo, 0, v0) marked EXEC at most one lane, though the emitter keeps the other half's lanes. A half write now keeps the fact only when EXEC already had it and the half written is within it (a compare). - The short form v_add_co_ci_u32 vD, src0, src1 (also sub, subrev) wrote VCC only in the emitter. explicit_carry_vcc now gives it its VCC carry-out and carry-in operands when the listing is read, so every analysis sees the write, and the emitter's special case is removed. tests/semantic/test_wave64_one_lane_fold.py adds each case (8 subtests fail before) and picks in lanes 32-63 of both waves. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Gt9hwNPurxyJ9LAfUbNiYr --- docs/design.md | 2 +- tests/semantic/test_wave64_one_lane_fold.py | 78 ++++++++++++++++++++- tools/rdna2spirv.py | 17 +++-- tools/wave64_emulate_opt.py | 9 ++- 4 files changed, 95 insertions(+), 11 deletions(-) diff --git a/docs/design.md b/docs/design.md index a4d3c628e7..d6f989884a 100644 --- a/docs/design.md +++ b/docs/design.md @@ -437,7 +437,7 @@ How the generated SPIR-V expects the runtime to work: | Wave64 emulation: scalar exits from a folded EXECZ region | A folded lane-local `s_cbranch_execz`/`execnz` region may leave to its join from inside, for example `s_cmp` + `s_cbranch_scc0/scc1` straight to the label that restores EXEC. The ISA then skips the rest of the region for the whole wave. `find_local_exec_folds` in `tools/wave64_emulate_opt.py` builds the region's sub-CFG with an exit node for every edge to the join, so `cfg_structure.structure` puts each later block of the region behind a `%pc` guard; the exit node itself emits nothing. Before this the edge was dropped and the block after the branch ran whenever the lane was active. Confirmed on the CPU against the native wave64 translation and the ISA: `tests/semantic/test_wave64_emulate_opt.py` `test_folded_region_scalar_branch_to_join_skips_the_rest` (taken and not-taken `scc0`/`scc1`, 64 and 128 threads, the region still folded) fails before the change on the four taken cases. **Not GPU-verified.** | | Wave64 emulation: cross-lane reads of missing lanes | With `--wave64-emulate`, a read of another lane's exchange slot (`ds_swizzle_b32`, `ds_bpermute_b32`, `ds_permute_b32`'s targets and data, `v_readlane_b32`, `v_readfirstlane_b32`, DPP and the other reads behind `Gen.x_round`) gives 0 when the source lane doesn't exist in a partial last wave (`Gen.x_lane_word`: `x_wbase + lane < threads`, else 0), as a source lane that isn't running reads 0 on the hardware. The prologue still zeroes those slots, but a read must not depend on it: RADV (Mesa 26.3.1, gfx1036 iGPU and RX 7900 XTX) compiled the store, barrier and load of an exchange behind a branch into `masked_swizzle_amd` with `fetch_inactive` (`RADV_DEBUG=shaders`), so in a 40-thread group lanes 32-39 of `ds_swizzle_b32 offset:swizzle(SWAP,8)` read the missing lanes' registers, garbage that changed between runs. Workgroups whose size is a multiple of 64 emit the same module as before. Confirmed by `runtime/test/shaders/cs_w64x_partial_swizzle.asm` (40 threads: SWAP 8, BROADCAST 16,15 and `ds_bpermute_b32` from lanes 40-47; its 8 words measured natively on gfx1036 through `tools/hw_oracle`): emulated at subgroup 32 (RADV, Mesa 26.3.1), words 2 and 3 wrong before in 20 of 20 runs on the gfx1036 iGPU and 19 of 20 on the RX 7900 XTX, and all 8 words right in 20 of 20 runs on both after; native wave64 and emulated at subgroup 64 right both times. `scripts/run_gpu_tests.py` runs the partial-wave fixtures emulated at subgroup 32, as `check.py` does, since at RADV's default of 64 this fixture passed before the change too; by `crosslane_fuzz.py --wave 64 --ext --dpp --no-maskdata --programs 1000 --seed 48315`, emulated: on the gfx1036 iGPU 993 match and 7 hyp_only (all 40-thread groups, lanes 32-39 reading a swizzle source of 40-47) before, 1000/1000 after, and on the RX 7900 XTX 995 match and 5 hyp_only before, 1000/1000 after; and by `tests/semantic/test_w64x_partial_swizzle.py` (fixture `w64x_partial_swizzle.asm`, 40 and 104 threads, the prologue's zero stores replaced by a poison word in the workgroup interpreter; both cases fail before the change). | | Barycentric fallback (`--bary-fallback`) | For devices without `VK_KHR_fragment_shader_barycentric` (NVIDIA Pascal, for one), and for Mesa ANV's known BaryCoordKHR.i bug (SHADER-925). The raw pair a PS reads comes from an ordinary vec3 input, `%bary`, at the lowest location none of the shader's attributes uses, instead of `BuiltIn BaryCoordKHR`. The module needs neither the `FragmentBarycentricKHR` capability nor the extension, and the index records the location as `bary_fallback_input`. `tools/bary_fallback_gs.py` writes a pass-through geometry shader that supplies (1,0,0), (0,1,0), (0,0,1) at the triangle vertices. GPU-checked on NVIDIA Pascal and Intel Arc B580/Mesa ANV: ANV native `ps_uniform_branch` and `ps_scc_mask32` fail with i=0.0, while the fallback passes and `ps_bary` passes natively. `make_game.py` and `scripts/run_gpu_tests.py` select the fallback automatically for Mesa ANV. `LEONIDA_BARY_FALLBACK=1` forces fallback and `LEONIDA_BARY_FALLBACK=0` forces native barycentrics consistently in both entry points; explicit `--bary-fallback` also forces the fallback in `make_game.py`. The standalone `build.py`/`check.py` path follows the same variable/probe rule. Checked in `tests/semantic/test_bary_fallback.py` and the builder/runner wiring tests. | -| Wave64 emulation: a folded region at most one lane runs (SHADER-W64-ONE-LANE-FOLD) | A compute shader picks one thread for a tail (clear LDS, then after a barrier sum it up and store) with `v_cmpx_eq_u32 c, v0` or `v_cmp_eq_u32 m, c, v0` + `s_and_saveexec_b64 _, m`. `v0` is LocalInvocationId.x and a wave is 64 consecutive threads, so no two lanes of a wave share it when the group is one row (`size_y * size_z == 1`) or a row is whole waves (`size_x % 64 == 0`); then the compare is true in at most one lane. `_one_lane_in` in `tools/wave64_emulate_opt.py` proves per block, forward over the CFG with intersection at joins, that EXEC is at most one lane: `v0` must not have been written since entry, and the mask goes on through `s_mov_b64`, `s_and_b64` with anything, `s_andn2_b64` of it, a saveexec of it and any later compare (a compare is 0 in inactive lanes). Where `run` of an `s_cbranch_execz` region is proved so, `find_local_exec_folds` drops the one-store-per-domain and acyclic limits and marks the fold `one_lane` (the region's EXEC writes already must keep a skipped lane inactive, so it stays at most one lane): with one lane the lane's own order of its accesses is the wave's, so `x_memory_order` orders nothing inside it. A `v_readfirstlane_b32` is allowed in such a fold when the region writes no EXEC at all: the lane runs the fold only when active, so it is the first lane of EXEC and the result is its own value (also into `vcc_lo`/`vcc_hi`). Confirmed on the CPU against the plain round emulation in both invocation orders: `tests/semantic/test_wave64_one_lane_fold.py` (128 threads; LDS writes, a barrier, first-lane reads and two stores to one address; a lane of wave 0, of wave 1, or none; the negatives `v_cmpx_eq` of a non-id VGPR, `v0` overwritten, `v_cmpx_gt`, and a 32 x 4 group are not marked one-lane). One 1024-thread library compute shader goes from 639 to 33 `OpSwitch` cases and passes `spirv-val`. **Not GPU-verified.** | +| Wave64 emulation: a folded region at most one lane runs (SHADER-W64-ONE-LANE-FOLD) | A compute shader picks one thread for a tail (clear LDS, then after a barrier sum it up and store) with `v_cmpx_eq_u32 c, v0` or `v_cmp_eq_u32 m, c, v0` + `s_and_saveexec_b64 _, m`. `v0` is LocalInvocationId.x and a wave is 64 consecutive threads, so no two lanes of a wave share it when the group is one row (`size_y * size_z == 1`) or a row is whole waves (`size_x % 64 == 0`); then the compare is true in at most one lane. `_one_lane_in` in `tools/wave64_emulate_opt.py` proves per block, forward over the CFG with intersection at joins, that EXEC is at most one lane: `v0` must not have been written since entry, and the mask goes on through `s_mov_b64`, `s_and_b64` with anything, `s_andn2_b64` of it, a saveexec of it and any later compare (a compare is 0 in inactive lanes). A write of one half of EXEC (`exec_lo`/`exec_hi`, which the emitter writes as that half only) keeps the fact only when EXEC already had it and the half written is within it (a compare): the other half keeps its lanes, so `v_cmp_eq_u32 exec_lo, 0, v0` from a full EXEC leaves lanes 32-63 on. The assembler's short form `v_add_co_ci_u32 vD, src0, src1` (also `sub`, `subrev`) gets its VCC carry-out and carry-in operands when the listing is read (`explicit_carry_vcc` in `tools/rdna2spirv.py`), so every analysis sees the VCC it writes. Where `run` of an `s_cbranch_execz` region is proved so, `find_local_exec_folds` drops the one-store-per-domain and acyclic limits and marks the fold `one_lane` (the region's EXEC writes already must keep a skipped lane inactive, so it stays at most one lane): with one lane the lane's own order of its accesses is the wave's, so `x_memory_order` orders nothing inside it. A one-block region that branches back to itself is emitted as a loop through `cfg_structure.structure` like a multi-block region; emitted straight it ran once (also for a read-only loop, before this row). A `v_readfirstlane_b32` is allowed in such a fold when the region writes no EXEC at all: the lane runs the fold only when active, so it is the first lane of EXEC and the result is its own value (also into `vcc_lo`/`vcc_hi`). Confirmed on the CPU against the plain round emulation in both invocation orders: `tests/semantic/test_wave64_one_lane_fold.py` (128 threads; LDS writes, a barrier, first-lane reads and two stores to one address; a lane of wave 0, of wave 1, or none; the negatives `v_cmpx_eq` of a non-id VGPR, `v0` overwritten, `v_cmpx_gt`, and a 32 x 4 group are not marked one-lane; picks in lanes 32-63 of either wave; a one-block self-loop with and without a store, which ran once before; `v_cmp_eq_u32_e64 exec_lo, 0, v0` from a full EXEC, which was marked one-lane before; and the short and explicit `v_add_co_ci_u32` carry into VCC after a one-lane compare, whose short form was marked one-lane before). One 1024-thread library compute shader goes from 639 to 33 `OpSwitch` cases and passes `spirv-val`. **Not GPU-verified.** | | Metadata index | `spirv/index.json`: one entry per translated shader with its stage, `wave64` / `subgroup_size`, SPIR-V capabilities and extensions, the Vulkan **features** to enable (barycentrics, interlock, mesh, geometry, Float64, Int64, buffer device address, write-without-format, `shaderFmaFloat32` for `--fma khr`, …), `needs_maintenance8`, the descriptor bindings it uses (set 0), push-constant size, `local_size`, `user_sgprs` (CS), `lds_bytes`, mesh `max_vertices`/`max_primitives`/`params`, geometry inputs/outputs, vertex-input locations and types, full `vertex_input_signature` (ISG1 register/mask/system-value/component-type, for PSO lookup), `wave64_emulated` (true for VS/PS/GS wave64, which the translator emits as per-subgroup code with no cross-half exchange, and for compute/mesh translated with `--wave64-emulate`; the runtime does not use it: it reads `wave64`, `subgroup_size` and `wave64_exchange`), `dynamic_format` (runtime V# FORMAT: codes outside FORMATS decode to 0) / `fixed_format_codes`, `src_sha256` and optional `fssm_sha256` (via `--fssm-dir`), PS system inputs, `bary_fallback_input` (`--bary-fallback`: the location of the barycentric input), `mesh_compute` (`--mesh-compute`: the slot layout and push-constant size), `pc_tail` (`--pc-tail-ubo`: the set, binding and size of the uniform block that holds the push-constant tail), and input/output locations. A shader translated with `--wave64-emulate` carries `wave64_exchange: "workgroup"` and `subgroup_size: null`: any subgroup size is exact, request none. Otherwise `subgroup_size` (64 for wave64, 32) is what the PSO asks for through `VkPipelineShaderStageRequiredSubgroupSizeCreateInfo` where the device lists the stage in `requiredSubgroupSizeStages` (docs/d3d12_vulkan.md section 3.2): that list is the driver's, not "compute/mesh only". The AMD Windows driver reports FRAGMENT, COMPUTE, TASK and MESH (measured on a Radeon 880M, driver 26.11.2, sizes 32..64), and current Mesa RADV on GFX10+ reports COMPUTE, FRAGMENT and task/mesh (`src/amd/vulkan/radv_physical_device.c`, `requiredSubgroupSizeStages`, Mesa main at 152b9cde; older Mesa: compute only), so wave64 pixel shaders can run exact there. NVIDIA lists every stage but only size 32, so there a native wave64 shader cannot get 64 and wave64 PS/VS/GS stay 2x32. A runtime can create every pipeline at load time from it without parsing SPIR-V. | | Full-corpus pipeline build | `vk_pipeline_check pipeline_cache.bin --jobs 4` on an RTX 4060 Ti (NVIDIA 595 driver): **all 26,503 shaders become real pipelines, 0 failures** (cs 2,689, ps 12,101, ms 9,282, vs 2,236, gs 195; graphics stages with generated stub partners). Compile time 40,784 s of CPU (2.84 h wall on 4 threads): cs 23,633 s (mean 8.8 s; the ray-tracing ScreenProbes/RTShadowTrace shaders take 2-19 min each), ps 11,481 s, ms 5,395 s, vs 275 s. The resulting `VkPipelineCache` is 3.81 GB; seeding a run with it makes those pipelines instant, which is what a fast first boot needs. The cache is per driver and GPU, and a shader whose SPIR-V changes compiles again (the checker resumes from the file). Neither register storage (one variable per register) nor smaller SPIR-V cut NVIDIA compile time: the big ray-tracing shaders are expensive as such, so the runtime should compile them in the background rather than block on them. | | `v_cndmask_b32` source modifiers | `v_cndmask_b32` only moves bits, so a VOP3 `abs` on `src0`/`src1` clears bit 31 and `neg` flips it (`abs` first) as plain bit moves (`OpBitwiseAnd 0x7FFFFFFF`, then `OpBitwiseXor 0x80000000`, `Gen.src_u_sign_mods`), never `FAbs`/`OpFNegate`: a signalling NaN stays signalling and a denormal isn't flushed. Until 2026-11-23 the sources went through `Gen.modify`, and the mini interpreter quieted them (`-v1` of `0x7F800001` gave `0xFFC00001`, not `0xFF800001`). **Not measured on hardware for this instruction**: the rule follows the same VOP3 input modifiers measured as sign-bit moves on `v_cmp_class_f32` (gfx1036, all four IEEE/denorm modes, row "Floating-point class compare" above), and LLVM's AMDGPU backend moves `fneg`/`fabs` through a select into `v_cndmask_b32_e64`'s source modifiers (`AMDGPUTargetLowering::foldFreeOpFromSelect`), which is only exact if they are sign-bit moves. Checked on the CPU and with `spirv-val` by `tests/semantic/test_cndmask_sign_mods.py` (15 words including signalling/quiet NaNs, denormals, zeros and infinities x `v`, `-v`, `\|v\|`, `-\|v\|` x both operands). | diff --git a/tests/semantic/test_wave64_one_lane_fold.py b/tests/semantic/test_wave64_one_lane_fold.py index 046f6df92c..c816ae5afc 100644 --- a/tests/semantic/test_wave64_one_lane_fold.py +++ b/tests/semantic/test_wave64_one_lane_fold.py @@ -71,6 +71,8 @@ def assemble(text): items, labels, pc = [], {}, 0 for raw in text.strip().splitlines(): line = raw.strip() + if not line: + continue if line.endswith(":"): labels[line[:-1]] = pc continue @@ -93,9 +95,9 @@ def rounds_only(): class OneLaneTests(unittest.TestCase): - def check(self, pick, size=(128, 1, 1)): + def check(self, pick, size=(128, 1, 1), program=PROGRAM): """Translate and run the program; compare with the round emulation. Returns (folds, memory).""" - insns = assemble(PROGRAM.replace("{pick}", pick)) + insns = assemble(program.replace("{pick}", pick)) seen = [] fold = opt.find_local_exec_folds @@ -118,7 +120,7 @@ def spy(*a, **k): return seen[-1][0], want def test_one_lane_folds_and_matches(self): - for c in (0, 65, 200): # a lane of wave 0, of wave 1, no lane + for c in (0, 40, 65, 100, 200): # lanes 0 and 32-63 of wave 0, 1 and 32-63 of wave 1, no lane with self.subTest(c=c): folds, mem = self.check(f"v_cmpx_eq_u32_e32 {c}, v0") self.assertEqual(sum(fd["one_lane"] for fd in folds.values()), 2) @@ -142,6 +144,76 @@ def test_not_one_lane_keeps_the_rounds(self): folds, _ = self.check(pick, size) self.assertFalse(any(fd["one_lane"] for fd in folds.values())) + def test_self_loop_keeps_its_back_edge(self): + # One block that loops on a scalar count, as the whole region: every iteration must run (v1 = 10 + 2). + for store in (True, False): # cyclic stores (a one-lane fold) and a read-only loop + body = STORE_IN_LOOP if store else "" + for c in (0, 40, 100, 200): + with self.subTest(store=store, c=c): + folds, mem = self.check(f"v_cmpx_eq_u32_e32 {c}, v0", program=SELF_LOOP.replace("{store}", body)) + if c < 128: + self.assertEqual(mem[OUT + 4 * c], 12) + if store: + self.assertEqual(sum(fd["one_lane"] for fd in folds.values()), 1) + + def test_exec_half_write_is_not_one_lane(self): + # exec_lo = (v0 == 0) keeps exec_hi: lanes 32-63 stay on, so the first-lane read is not the lane's own. + folds, mem = self.check("v_cmp_eq_u32_e64 exec_lo, 0, v0", program=FIRST_LANE) + self.assertFalse(any(fd["one_lane"] for fd in folds.values())) + self.assertEqual(mem[OUT + 4 * 40], 0) + # Narrowing EXEC that already is at most one lane keeps it so. + folds, mem = self.check("v_cmpx_eq_u32_e32 40, v0\nv_cmp_eq_u32_e64 exec_lo, 40, v0", program=FIRST_LANE) + self.assertEqual(sum(fd["one_lane"] for fd in folds.values()), 1) + self.assertEqual(mem[OUT + 4 * 40], 40) # lane 40 is in the high half, which exec_lo leaves + + def test_implicit_vcc_carry_kills_the_mask(self): + # The carry out of v_add_co_ci_u32 (all lanes carry) replaces the one-lane compare in VCC. + for add in ("v_add_co_ci_u32 v3, v1, v2", "v_add_co_ci_u32_e32 v3, vcc, v1, v2, vcc"): + with self.subTest(add): + pick = f"v_cmp_eq_u32_e32 vcc, 0, v0\n{add}\ns_and_saveexec_b64 s[44:45], vcc" + folds, mem = self.check(pick, program=FIRST_LANE) + self.assertFalse(any(fd["one_lane"] for fd in folds.values())) + self.assertEqual(mem[OUT + 4 * 1], 0) + + +STORE_IN_LOOP = f"v_add_nc_u32_e32 v3, {OUT + 512:#x}, v9\nbuffer_store_dword v1, v3, s[0:3], 0 offen" +SELF_LOOP = f""" + s_mov_b64 exec, -1 + v_lshlrev_b32_e32 v9, 2, v0 + v_mov_b32_e32 v1, 10 + s_mov_b32 s10, 2 + {{pick}} + s_cbranch_execz @B +L: + v_add_nc_u32_e32 v1, 1, v1 + {{store}} + s_sub_u32 s10, s10, 1 + s_cmp_lg_u32 s10, 0 + s_cbranch_scc1 @L +B: + s_mov_b64 exec, -1 + v_add_nc_u32_e32 v9, {OUT:#x}, v9 + buffer_store_dword v1, v9, s[0:3], 0 offen + s_endpgm +""" +# The lanes that pass the pick store the first-lane copy of v0, the others 0xee. +FIRST_LANE = f""" + s_mov_b64 exec, -1 + v_lshlrev_b32_e32 v9, 2, v0 + v_mov_b32_e32 v5, 0xee + v_mov_b32_e32 v1, -1 + v_mov_b32_e32 v2, 1 + {{pick}} + s_cbranch_execz @B + v_readfirstlane_b32 s14, v0 + v_mov_b32_e32 v5, s14 +B: + s_mov_b64 exec, -1 + v_add_nc_u32_e32 v9, {OUT:#x}, v9 + buffer_store_dword v5, v9, s[0:3], 0 offen + s_endpgm +""" + if __name__ == "__main__": unittest.main() diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 11f1d40896..8d4182353f 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -10373,11 +10373,7 @@ def halves(s, is_full): elif op in ("v_add_co_u32", "v_add_co_ci_u32", "v_sub_co_u32", "v_sub_co_ci_u32", "v_subrev_co_u32", "v_subrev_co_ci_u32"): # Lane masks are all-ones/zero: carry in = (vcc or the named mask) != 0, carry out stored the same way. - if op.endswith("ci_u32") and len(a) == 3: - # the assembler's short form v_add_co_ci_u32 vD, src0, src1: carry out and in are VCC (llvm-mc and the - # disassembler print it as v_add_co_ci_u32_e32 vD, vcc_lo, src0, src1, vcc_lo) - vcc = {"k": "special", "t": "vcc"} - a = [a[0], vcc, a[1], a[2], vcc] + # (The short form v_add_co_ci_u32 vD, src0, src1 has its VCC operands from explicit_carry_vcc.) vd, cd = a[0], a[1] srcs = a[2:] x, y = self.src_u(srcs[0]), self.src_u(srcs[1]) @@ -18084,6 +18080,16 @@ def restore_vcc_tuples(insns, blob, code_start, code_end, wave32=True): return sorted(kept + restored, key=lambda i: i["pc"]) +def explicit_carry_vcc(insns): + """In place: the assembler's short form v_add_co_ci_u32 vD, src0, src1 (also v_sub_co_ci_u32, v_subrev_co_ci_u32) + gets its carry-out and carry-in operands, VCC, as llvm-mc and the disassembler print it + (v_add_co_ci_u32_e32 vD, vcc_lo, src0, src1, vcc_lo). Every analysis then sees the VCC it writes.""" + for ins in insns: + a = ins["args"] + if base_op(ins["op"]) in ("v_add_co_ci_u32", "v_sub_co_ci_u32", "v_subrev_co_ci_u32") and len(a) == 3: + ins["args"] = [a[0], {"k": "special", "t": "vcc"}, a[1], a[2], {"k": "special", "t": "vcc"}] + + def widen_wave64_masks(insns): """In place: the lane-mask SGPR operands of VALU instructions become the pairs they are in wave64. @@ -18549,6 +18555,7 @@ def _translate(path): g.wave64 = fspx_ws == 64 else: g.wave64 = marker_wave64(path, info["name"], stage, insns) + explicit_carry_vcc(insns) if g.wave64: widen_wave64_masks(insns) # A wave32 program using VCC as an SMEM pointer needs both scalar words. Mark its pair producers diff --git a/tools/wave64_emulate_opt.py b/tools/wave64_emulate_opt.py index f98fe7500b..45063bc074 100644 --- a/tools/wave64_emulate_opt.py +++ b/tools/wave64_emulate_opt.py @@ -1194,6 +1194,10 @@ def is_one(x): val = is_one(a[1]) or (op == "s_and_b64" and len(a) > 2 and is_one(a[2])) dest = _one_key(a[0]) exec_val = val + if any(x.get("k") == "special" and x.get("t") in ("exec_lo", "exec_hi") for x in a[:2]): + # One half of EXEC (a compare into exec_lo, s_mov_b32 exec_hi, a carry out): the other half keeps its lanes, + # so EXEC stays at most one lane only if it already was and the half written is within it (a compare). + exec_val = exec_val and "exec" in one out = {k for k in one if k != "exec" and not may_w & (1 << _BIT_VCC if k == "vcc" else 3 << k)} if not writes_exec and "exec" in one: out.add("exec") @@ -1464,8 +1468,9 @@ def find_local_exec_folds(blocks, raw_edges, succ, lane_masks, scc_live, mask_wr break if not ok: continue - # Build local sub-CFG and verify reducibility (multi-block regions use cfg_structure.structure). - if len(region) == 1: + # Build local sub-CFG and verify reducibility (multi-block regions and a one-block loop use + # cfg_structure.structure; emitted straight, a block that branches back to itself would run once). + if len(region) == 1 and run not in succ[run]: order = [run] sub_tree = None else: