From 8ee2b9a76b4c62c8a007a415c1882a827237f744 Mon Sep 17 00:00:00 2001 From: quartz-heron-58 <245169279+quartz-heron-58@users.noreply.github.com> Date: Fri, 27 Nov 2026 10:58:00 +0800 Subject: [PATCH 1/6] rdna2spirv: --mesh-serial-waves, a mesh program's waves one after the other in 64 invocations (work in progress) Under --wave64-emulate a mesh program of more than 64 threads (a multiple of 64, no LDS instruction, not --mesh-compute) declares 64 invocations and runs one pass per wave: the invocation's index is the built-in plus 64 x pass, every initialised Function variable is set again per pass, the exports of a pass are copied to per-pass twins, and the epilogue sets the counts once and writes each pass's outputs. Each pass is one wave, so the plan is the single-wave one and the exchange buffer is one wave's. Off by default; with the flag off the output is unchanged. Work in progress for SHADER-W64-MESH-SERIAL-WAVES: no test or docs row yet. Co-Authored-By: Claude Fable 5.2 --- tools/rdna2spirv.py | 107 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 105 insertions(+), 2 deletions(-) diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index b10de728ec..2abe3e5ba9 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -98,6 +98,10 @@ # in push-constant dwords 36..37 (the block grows from 144 to 152 bytes). The slot layout is mesh_compute_layout(); # the index records it as "mesh_compute". tools/mesh_compute_vs.py writes the vertex shader that draws the slots. MESH_COMPUTE = False +# --mesh-serial-waves (with --wave64-emulate): a mesh shader of more than 64 threads whose waves do not share LDS +# runs its waves one after the other in 64 invocations, one pass per wave, so each pass is a single wave (the +# inline_all structured form) instead of several waves side by side under mini-schedulers. See assemble(). +MESH_SERIAL_WAVES = False # --pc-tail-ubo: for devices with 128 bytes of push constants, Vulkan's minimum (AMD's Windows driver on RDNA2 iGPUs, # some Intel Arc drivers; D3D-14's push_constants_need_fallback). The push-constant block keeps s0..s31 (128 bytes). # The tail that follows them by default (dwords 32..35: heap base, code base; 36..37: the --mesh-compute output @@ -546,6 +550,7 @@ def __init__(self, stage, hoist_reg_ptrs=False, cache_active=False): self.lane_either = {} # id(instruction) -> SGPRs holding constant 0/-1 (EITHER) there self.cur_either = () self.x_lanes = 64 # emulate: workgroup invocations rounded up to whole waves + self.ms_serial = 0 # --mesh-serial-waves: number of passes (waves run one after the other), or 0 self.scc_live = None # emulate: set of id(ins) whose SCC write is live-out (wave64_emulate_opt) self.cur_scc_live = True # emulate: whether the current instruction's SCC result is live-out self.bar_rounds = False # native wave32 cs with an s_barrier outside uniform control flow (bar_scheduler) @@ -16091,6 +16096,76 @@ def insert_late_constants(gen, out, written): out[at:at] = [f"{gen.consts[v]} = OpConstant %uint {v}" for v in late] +def ms_serial_passes(gen, fn, lists): + """--mesh-serial-waves: the function's variables, then a loop over the passes around the prologue (and, appended + by the caller, the body). Returns the new `fn`, the lines that close the loop after the body, and the export + variables with their per-pass twins. + + Pass w runs the invocations as lanes 64 * w .. 64 * w + 63 of the workgroup: `%local_index` is a Function variable + here, the built-in (now `%real_local_index`) plus 64 * w, so the launch state (v5, the wave id in s3), the lane + and everything else that reads it see wave w. Every initialised Function variable gets its initial value again at + the start of a pass. What a pass exported sits in Function variables (`%ms_pos`, `%ms_prim`, ...): they are copied + to the pass's twins before the next pass overwrites them, and the epilogue writes each pass's outputs from its + twins after the loop, once the counts are known.""" + w_count = gen.ms_serial + for lines in lists: + for i, l in enumerate(lines): + if "%local_index" in l: + lines[i] = re.sub(r"%local_index\b", "%real_local_index", l) + last_var = max(i for i, l in enumerate(fn) if " = OpVariable " in l) + head, rest = fn[:last_var + 1], fn[last_var + 1:] + var = re.compile(r"^(%\w+) = OpVariable (\S+) Function(?: (\S+))?$") + reinit, exports, twins = [], [], [] + for l in head: + m = var.match(l) + if not m: + continue + name, ptr, init = m.groups() + if init: + reinit.append(f"OpStore {name} {init}") + if name.startswith("%ms_"): + exports.append(name) + twins += [f"{name}__w{w} = OpVariable {ptr} Function" + (f" {init}" if init else "") for w in range(w_count)] + c = gen.cu + head = head + ["%local_index = OpVariable %_ptr_Function_uint Function " + c(0), + "%msw_pass = OpVariable %_ptr_Function_uint Function " + c(0)] + twins + open_loop = ["OpBranch %msw_head", "%msw_head = OpLabel", "OpLoopMerge %msw_exit %msw_cont None", + "OpBranch %msw_body", "%msw_body = OpLabel"] + reinit + [ + "%msw_w = OpLoad %uint %msw_pass", "%msw_rl = OpLoad %uint %real_local_index", + f"%msw_off = OpIMul %uint %msw_w {c(64)}", "%msw_li = OpIAdd %uint %msw_rl %msw_off", + "OpStore %local_index %msw_li"] + close = [] + for w in range(w_count): + close += [f"%msw_is{w} = OpIEqual %bool %msw_w {c(w)}", + f"OpSelectionMerge %msw_sv_end{w} None", f"OpBranchConditional %msw_is{w} %msw_sv{w} %msw_sv_end{w}", + f"%msw_sv{w} = OpLabel"] + close += [f"OpCopyMemory {name}__w{w} {name}" for name in exports] + close += [f"OpBranch %msw_sv_end{w}", f"%msw_sv_end{w} = OpLabel"] + close += ["OpBranch %msw_cont", "%msw_cont = OpLabel", f"%msw_n = OpIAdd %uint %msw_w {c(1)}", + "OpStore %msw_pass %msw_n", f"%msw_more = OpULessThan %bool %msw_n {c(w_count)}", + "OpBranchConditional %msw_more %msw_head %msw_exit", "%msw_exit = OpLabel"] + return head + open_loop + rest, close, exports + + +def ms_serial_epilogue(gen, lines, exports): + """--mesh-serial-waves: the mesh epilogue for passes. `lines` is the epilogue of one invocation: the barrier, + the counts and OpSetMeshOutputsEXT, then (from the load of `%local_index` on) the writes of what the invocation + exported. The first part stays as it is, once; the writes are repeated per pass w with the pass's twins of the + export variables and the output index real index + 64 * w, every id of the block renamed per pass.""" + cut = lines.index("%mli = OpLoad %uint %local_index") + once, writes = lines[:cut], lines[cut + 1:] + defined = set(re.findall(r"^(%\w+) = ", "\n".join(writes), re.M)) + out = list(once) + ["%msw_erl = OpLoad %uint %real_local_index"] + for w in range(gen.ms_serial): + names = {d: f"{d}_w{w}" for d in defined} + names.update({e: f"{e}__w{w}" for e in exports}) + names["%mli"] = f"%mli_w{w}" + out.append(f"%mli_w{w} = OpIAdd %uint %msw_erl {gen.cu(64 * w)}") + for l in writes: + out.append(re.sub(r"%\w+", lambda m: names.get(m.group(0), m.group(0)), l)) + return out + + def assemble(gen): store_dims = gen.uses_store_views | gen.uses_store_reads vs = gen.stage == "vs" @@ -16122,6 +16197,8 @@ def assemble(gen): x_zero = x_sink - x_mask # mask and schedule words: zeroed before the first round x_threads = (gen.cs or gen.ms)["size"] x_threads = x_threads[0] * x_threads[1] * x_threads[2] + if gen.ms_serial: + x_threads = 64 # the invocations of one pass sx, sy, _ = (gen.cs or gen.ms)["size"] for v in (0, 1, 2, 3, 6, 31, 63, 0x948, x_mask, x_sched, x_sink, x_sink + 1, x_zero - 1, x_threads, x_waves, sx, sx * sy, 0xFFFFFFC0): @@ -16281,7 +16358,7 @@ def assemble(gen): if msc: hdr.append("OpExecutionMode %main LocalSize {} {} {}".format(*gen.ms["size"])) elif ms: - hdr += ["OpExecutionMode %main LocalSize {} {} {}".format(*gen.ms["size"]), + hdr += ["OpExecutionMode %main LocalSize {} {} {}".format(*((64, 1, 1) if gen.ms_serial else gen.ms["size"])), f"OpExecutionMode %main OutputVertices {gen.ms['maxv']}", f"OpExecutionMode %main OutputPrimitivesEXT {gen.ms['maxp']}", "OpExecutionMode %main OutputTrianglesEXT"] @@ -17065,6 +17142,9 @@ def label(prefix): gen.body =[" " + l if not (l.startswith("%") and " = OpLabel" in l) else l for l in flow + body] if pops: fn.append("OpBeginInvocationInterlockEXT") # end of the entry block: uniform, executed once + serial_close, serial_exports = [], [] + if ms and not msc and gen.ms_serial: + fn, serial_close, serial_exports = ms_serial_passes(gen, fn, (hdr, dec, gvars)) out = hdr + dec + types + gvars + helpers + fn end_lock = " OpEndInvocationInterlockEXT\n" if pops else "" if msc: @@ -17145,6 +17225,8 @@ def label(prefix): f"%m{tag}p = OpAccessChain %_ptr_Out_int_ms %ms_cull %mli {c(member)}", f"OpStore %m{tag}p %m{tag}v"] L += ["OpBranch %ms_pend", "%ms_pend = OpLabel"] + if gen.ms_serial: + L = ms_serial_epilogue(gen, L, serial_exports) end_lock = "".join((" " + l if " = OpLabel" not in l else l) + "\n" for l in L) + end_lock if gen.uses_active and gen.stage == "ps": # A pixel is written when its lane was on in EXEC at the last `vm` export the path ran (if it ran one) and @@ -17177,6 +17259,8 @@ def label(prefix): "%live = OpLabel\n OpReturn\n OpFunctionEnd\n") else: tail = end_lock + " OpReturn\n OpFunctionEnd\n" + if serial_close: + gen.body = list(gen.body) + [(" " + l if " = OpLabel" not in l else l) for l in serial_close] insert_late_constants(gen, out, written) return split_big_switch(no_contraction(dedupe_types( "\n".join(" " + l if not l.startswith("%") or " = " not in l else l for l in out) + @@ -18758,6 +18842,14 @@ def _translate(path): g.emulate = True size = (g.cs or g.ms)["size"] g.x_lanes = -(-size[0] * size[1] * size[2] // 64) * 64 + threads = size[0] * size[1] * size[2] + if (MESH_SERIAL_WAVES and stage == "ms" and not MESH_COMPUTE and threads > 64 and threads % 64 == 0 + and not any(i["op"].startswith("ds_") for i in insns)): + g.ms_serial = threads // 64 # passes; every pass is one whole wave + g.x_lanes = 64 + for k in range(g.ms_serial + 1): + g.cu(k) + g.cu(64 * k) insns = fold_far_branches(insns) branchy = any(base_op(i["op"]) in BRANCHES for i in insns) if stage == "ps": @@ -19309,7 +19401,9 @@ def x_prologue(gen, threads): "%done = OpVariable %_ptr_Function_bool Function %false"] # This invocation's place: index in the workgroup, lane and wave (the same split as Gen.wave_lane). if gen.stage == "ms": - L += ["%x_li = OpLoad %uint %local_index"] + # --mesh-serial-waves: the exchange is one wave's, so its place in %x_buf comes from the invocation's own index + # (0-63), not from the workgroup index of the lane it runs in this pass (ms_serial_passes). + L += ["%x_li = OpLoad %uint " + ("%real_local_index" if gen.ms_serial else "%local_index")] else: L += ["%x_lid = OpLoad %v3uint %local_id", "%x_lx = OpCompositeExtract %uint %x_lid 0", "%x_ly = OpCompositeExtract %uint %x_lid 1", "%x_lz = OpCompositeExtract %uint %x_lid 2", @@ -19726,6 +19820,8 @@ def shader_meta(g, asm, src_path=None, fssm_path=None): "bytes": 24 if getattr(g, "msc_layout", None) else 16} if g.ms: m["local_size"] = list(g.ms["size"]) + if g.ms_serial: # the program's thread count stays in local_size; the module declares 64 invocations + m["mesh_serial_waves"] = g.ms_serial m["max_vertices"], m["max_primitives"] = g.ms["maxv"], g.ms["maxp"] m["params"] = sorted(g.ms_params) if g.gs: @@ -20114,6 +20210,11 @@ def main(): help="mesh shaders become compute shaders that write their vertices and primitives to a buffer " "(metadata: mesh_compute), drawn by tools/mesh_compute_vs.py, for devices without " "VK_EXT_mesh_shader (e.g. NVIDIA Pascal)") + ap.add_argument("--mesh-serial-waves", action="store_true", + default=os.environ.get("LEONIDA_MESH_SERIAL_WAVES") == "1", + help="with --wave64-emulate: a mesh shader of more than 64 threads whose waves share no LDS runs " + "its waves one after the other in 64 invocations (one single-wave pass per wave) instead of " + "side by side; also on with LEONIDA_MESH_SERIAL_WAVES=1") ap.add_argument("--shader-clock", choices=("off", "khr"), default="off", help="s_memtime / s_memrealtime: off = Unsupported (default), khr = OpReadClockKHR (needs " "VK_KHR_shader_clock; feature shaderSubgroupClock / shaderDeviceClock in the metadata)") @@ -20180,6 +20281,7 @@ def main(): LOOP_LIMIT = a.loop_limit MAX_STRUCTURED_DEPTH = a.max_structured_depth global STRUCTURED, WAVE64_EMULATE, WAVE64_GRAPHICS, BARY_FALLBACK, TEXEL_OFFSET_FALLBACK, MESH_COMPUTE, FMA_KHR, SHADER_CLOCK, F16_HALVES, OPT_SPIRV + global MESH_SERIAL_WAVES global PC_TAIL_UBO, ADDRESS_GUARD PC_TAIL_UBO = a.pc_tail_ubo ADDRESS_GUARD = a.address_guard @@ -20195,6 +20297,7 @@ def main(): BARY_FALLBACK = a.bary_fallback TEXEL_OFFSET_FALLBACK = a.texel_offset_fallback MESH_COMPUTE = a.mesh_compute + MESH_SERIAL_WAVES = a.mesh_serial_waves F16_HALVES = a.f16_interp_fallback OPT_SPIRV = a.opt if a.merge: From e954dc8c160849b643f3b74aff9115b94336cd9a Mon Sep 17 00:00:00 2001 From: quartz-heron-58 <245169279+quartz-heron-58@users.noreply.github.com> Date: Fri, 27 Nov 2026 11:13:58 +0800 Subject: [PATCH 2/6] mesh-serial-waves: a GPU fixture whose waves vote differently; no memory writes in a serial program (work in progress) ms_w64x_wave_votes: two waves take different branches, each with its own ballot count (and a v_readfirstlane in the second), and the triangle's vertices come from threads 0 and 1 of the first wave and thread 64 of the second, so ms_tri's picture needs both waves to have run their own branch with their own votes. It passes in the side-by-side form and with --mesh-serial-waves on an RTX 4080 (NVIDIA 621.24). A program with a store or an atomic to memory keeps the side-by-side form, as one with LDS does: its waves could pass each other something. Co-Authored-By: Claude Fable 5.2 --- runtime/test/shaders/ms_w64x_wave_votes.asm | 57 +++++++++++++++++++++ scripts/run_gpu_tests.py | 6 ++- tools/rdna2spirv.py | 6 ++- 3 files changed, 66 insertions(+), 3 deletions(-) create mode 100644 runtime/test/shaders/ms_w64x_wave_votes.asm diff --git a/runtime/test/shaders/ms_w64x_wave_votes.asm b/runtime/test/shaders/ms_w64x_wave_votes.asm new file mode 100644 index 0000000000..9613e1e1fb --- /dev/null +++ b/runtime/test/shaders/ms_w64x_wave_votes.asm @@ -0,0 +1,57 @@ +; Mesh shader (NGG, wave64, 128 threads = 2 waves): the two waves take different branches, each with its own +; wave-wide reads, and each wave contributes vertices to the one triangle. +; wave 0: ballot of (lane & 7) == 5, s_bcnt1 must be 8. +; wave 1: ballot of lane < 3, s_bcnt1 must be 3, plus v_readfirstlane of the lane number, which must be 0. +; A wave whose count is right sets the blue channel of param0 to 0.5 in the vertices it exports, else 0. +; The triangle is ms_tri's, but its vertices come from threads 0 and 1 (wave 0) and thread 64 (wave 1), so the +; picture is ms_tri's only when both waves ran their own branch with their own votes: a wave that saw the other +; wave's ballot, or ran the other branch, gets a different count. Only wave 0 sends the mesh allocation +; (1 primitive, 65 vertices: indices 0, 1 and 64 are used). +; Needs a DXBC with PSV0 (128 threads, 128/64 outputs, triangles; see scripts/run_gpu_tests.py): +; VKH_MESH=1 vk_harness ms_w64x_wave_votes.spv fs_passthru.spv out.raw +; -> every pixel = ((x+0.5)/64, (y+0.5)/64, 0.5, 1), identical to ms_tri. +; mattr: +wavefrontsize64,-wavefrontsize32 +v_mbcnt_lo_u32_b32 v0, -1, 0 +v_mbcnt_hi_u32_b32 v0, -1, v0 +v_mov_b32_e32 v11, v0 +s_bfe_u32 s4, s3, 0x40018 +v_lshl_add_u32 v0, s4, 6, v0 +s_cmp_eq_u32 s4, 0 +s_cbranch_scc0 6 +v_and_b32_e32 v12, 7, v11 +v_cmp_eq_u32_e64 s[6:7], 5, v12 +s_bcnt1_i32_b64 s10, s[6:7] +s_mov_b32 s14, 8 +s_branch 6 +v_cmp_gt_u32_e64 s[6:7], 3, v11 +s_bcnt1_i32_b64 s10, s[6:7] +v_readfirstlane_b32 s15, v11 +s_add_u32 s10, s10, s15 +s_mov_b32 s14, 3 +s_cmp_eq_u32 s10, s14 +s_cselect_b32 s13, 1, 0 +v_cvt_f32_u32_e32 v15, s13 +v_mul_f32_e32 v15, 0.5, v15 +v_cmp_eq_u32_e32 vcc, 1, v0 +v_cndmask_b32_e64 v1, -1.0, 0x40400000, vcc +v_cndmask_b32_e64 v3, 0, 2.0, vcc +v_cmp_eq_u32_e32 vcc, 64, v0 +v_cndmask_b32_e64 v2, -1.0, 0x40400000, vcc +v_cndmask_b32_e64 v4, 0, 2.0, vcc +v_mov_b32_e32 v6, 0 +v_mov_b32_e32 v7, 1.0 +v_mov_b32_e32 v8, v15 +s_mov_b32 m0, 0x1041 +s_cmp_lg_u32 s4, 0 +s_cbranch_scc1 1 +s_sendmsg sendmsg(MSG_GS_ALLOC_REQ) +v_cmp_gt_u32_e64 s[16:17], 2, v0 +v_cmp_eq_u32_e64 s[18:19], 64, v0 +s_or_b64 exec, s[16:17], s[18:19] +exp pos0 v1, v2, v6, v7 done +exp param0 v3, v4, v8, v7 +s_mov_b64 exec, -1 +v_cmpx_eq_u32_e32 0, v0 +v_mov_b32_e32 v9, 0x4000400 +exp prim v9, off, off, off done +s_endpgm diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index 60e9687830..1ac19c96e4 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py @@ -895,6 +895,8 @@ def run_suite(a, work: str) -> int: ]) elif name in ("ms_tri", "ms_w64x_ballot", "ms_wave_info_s3", "ms_f16_pack"): dxbc = make_dxbc([(b"PSV0", make_ms_psv0(128, 64, 64, 2))]) + elif name == "ms_w64x_wave_votes": # vertex 64 comes from the second wave: 128 output vertices + dxbc = make_dxbc([(b"PSV0", make_ms_psv0(128, 128, 64, 2))]) elif name == "ms_v5_workgroup": dxbc = make_dxbc([(b"PSV0", make_ms_psv0(32, 3, 1, group_shared=128))]) elif name == "ms_clip": @@ -1632,13 +1634,13 @@ def run_suite(a, work: str) -> int: problem = mesh_v5_test(a.build, spirv_dir, Path(raw_dir) / f"{name}.raw") results.append((name, None if isinstance(problem, Skip) else not problem, problem or "24/24 workgroup coordinates exact (2 x 3 x 4)")) - elif name in ("ms_tri", "ms_w64x_ballot", "ms_wave_info_s3"): + elif name in ("ms_tri", "ms_w64x_ballot", "ms_wave_info_s3", "ms_w64x_wave_votes"): raw = os.path.join(raw_dir, f"{name}.raw") env = mesh_env(spirv_dir, name, gfx_env) rc, msg = run_readback(raw, run_cmd, [vk_harness, spv, fs_passthru, raw], env=env) # ms_w64x_ballot needs exact wave64 (a 64-wide subgroup, or --wave64-emulate): skip it elsewhere, as # the wave64 compute dumps are. - no64 = (name == "ms_w64x_ballot" and not w64_emulated() and + no64 = (name in ("ms_w64x_ballot", "ms_w64x_wave_votes") and not w64_emulated() and not any(int(x) >= 64 for x in re.findall(r"subgroup \d+\.\.(\d+)", msg))) if rc == UNSUPPORTED: results.append((name, None, unsupported_skip(msg))) diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 2abe3e5ba9..760f6b7b0d 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -18844,7 +18844,11 @@ def _translate(path): g.x_lanes = -(-size[0] * size[1] * size[2] // 64) * 64 threads = size[0] * size[1] * size[2] if (MESH_SERIAL_WAVES and stage == "ms" and not MESH_COMPUTE and threads > 64 and threads % 64 == 0 - and not any(i["op"].startswith("ds_") for i in insns)): + and not any(i["op"].startswith("ds_") or "store" in i["op"] or "atomic" in i["op"] for i in insns)): + # The waves of such a program cannot pass each other anything: no LDS, and no store or atomic to + # memory another wave could read (ms_wave_info_s3 counts lanes in LDS across an s_barrier and keeps + # the side-by-side form). What is left between them is the allocation request and the exports, which + # assemble() orders itself. The order of the waves is then not observable. g.ms_serial = threads // 64 # passes; every pass is one whole wave g.x_lanes = 64 for k in range(g.ms_serial + 1): From fbceecf04241aaea01c386f09cb86b1dccb279c6 Mon Sep 17 00:00:00 2001 From: quartz-heron-58 <245169279+quartz-heron-58@users.noreply.github.com> Date: Fri, 27 Nov 2026 11:29:22 +0800 Subject: [PATCH 3/6] mesh-serial-waves: unit tests, the design row, the GPU runner's switch tests/test_mesh_serial_waves.py: the module shape of a program that qualifies (64 invocations, the pass loop, the index from the built-in, the exchange's own place, per-pass copies of the exports, one OpSetMeshOutputsEXT), that every initialised Function variable is set again per pass, and that ms_wave_info_s3 (LDS), a 32-thread program, native wave64 and --mesh-compute are unchanged by the flag. LEONIDA_MESH_SERIAL_WAVES=1 is read by scripts/run_gpu_tests.py, like the other translation switches, and no longer by rdna2spirv.py itself. docs/design.md and docs/testing.md say what the flag does and how it is tested; conftest gives ms_w64x_wave_votes its 128-vertex PSV0. Co-Authored-By: Claude Fable 5.2 --- docs/design.md | 1 + docs/testing.md | 7 ++ scripts/run_gpu_tests.py | 2 + tests/conftest.py | 2 + tests/test_mesh_serial_waves.py | 109 ++++++++++++++++++++++++++++++++ tools/rdna2spirv.py | 7 +- 6 files changed, 124 insertions(+), 4 deletions(-) create mode 100644 tests/test_mesh_serial_waves.py diff --git a/docs/design.md b/docs/design.md index 7bff52e7f9..9ec47172a8 100644 --- a/docs/design.md +++ b/docs/design.md @@ -367,6 +367,7 @@ How the generated SPIR-V expects the runtime to work: | Wave size | **Most of the game's shaders are wave64: 23,841 of 26,503** (`fssm_header.wave_size()`: FSSM header flags word `u32[0xD4]` bit 5, `0x20` = wave32, `0` = wave64; 0 contradictions against GFX10 code-proven wave32/wave64 instructions across all 26,503 blobs): 10,974 of 12,101 PS, 9,282 of 9,282 mesh shaders, 2,236 of 2,236 VS, 1,154 of 2,689 CS and 195 of 195 GS, against 2,662 wave32 (1,535 CS and 1,127 PS). A full-corpus translation at `ec8ec4c9` marks exactly these 23,841 `wave64` (`subgroup_size` 64) in the index. Before the FSSM flag (#1900) the wave size came from code markers (64-bit EXEC/mask writes, `exec_hi`, `*_saveexec_b64`): at `6a6704df` they made 21,538 of the 26,487 shaders translated then wave64 (the figure quoted here was 21,545). 10,031 PS, 9,282 mesh shaders, 1,179 VS, 851 CS and 195 GS (the 16 shaders refused then are all wave64 CS by the flag; the figure quoted here was 21,545). Against the flag they call 2,287 wave64 shaders wave32 (943 PS, 1,057 VS, 287 CS), whose code has no 64-bit EXEC/mask marker, and none the other way. An older marker scan (`s_mov_b64 exec, -1`, `exec_hi`, `s_and/or_saveexec_b64` and 64-bit masks) counted 9,930 PS, 8,666 mesh shaders, 1,115 VS and 923 CS, but it left out the 769 listings whose names start with `.` (616 of them mesh shaders; Python's `glob` skips such names). Over all 26,503, the translator's own marker test (`WAVE64_RE`, or a 64-bit op on EXEC/VCC) on the code `translate()` keeps finds 21,554 wave64: 10,031 PS, 9,282 mesh shaders, 1,179 VS, 867 CS and 195 GS. With the 2,287 above that is exactly the flag's 23,841, and none contradicts it; read raw, 104 more wave32 listings (80 CS, 24 PS) seem to carry a marker, all from embedded data words decoded as instructions. The first marker scan (`s_mov_b64 exec, -1`, `exec_hi`, `s_and/or_saveexec_b64` and 64-bit masks, written into this row at `0082ad53`) counted 9,930 PS, 8,666 mesh shaders, 1,115 VS and 923 CS: 20,634 without the GS, so not the 21,545 total either. The translator maps a wave to a subgroup, and NVIDIA subgroups are 32 wide. What that means: (1) lane-independent code, which is most pixel-shader math, is exact; (2) wave-wide branch decisions and reductions are made per 32-lane half, which is exact unless scalar state computed for one half is later consumed by the other; (3) lane indices from `v_mbcnt_lo/hi` and wave IDs from the merged-wave SGPR must be 64-lane values. Mesh and compute shaders build thread IDs as wave_id·64 + mbcnt, so those need a mapping from `LocalInvocationIndex` (lane = index & 63, wave = index >> 6). Full fidelity needs either 64-wide subgroups (AMD GPUs, via `VK_EXT_subgroup_size_control` requiredSubgroupSize = 64) or emulating cross-half ops (ballot, readlane, shuffles across halves) through workgroup memory. | | Mesh shaders | NGG wave64 programs → `VK_EXT_mesh_shader` (`MeshEXT`). **PSV0** (DXBC) gives NumThreads (128×1×1 in the corpus), MaxOutputVertices/Primitives (128/128) and the topology (triangles). System inputs, from Mesa's RADV setup for mesh as NGG on GFX10.3: v5 = first launch vertex ID of the lane (the "vertex_id" slot), `linearGroupIndex * NumThreads + LocalInvocationIndex` with the linear index from WorkgroupId/NumWorkgroups; all 9,282/9,282 corpus mesh shaders read `v5` once with `v_readfirstlane_b32 sX, v5` and use `sX` only via `s_lshr_b32 D, sX, 7` to recover the group index (NumThreads is 128 in the corpus), matching TomBox's mesh ABI (`gid.x * numThreads + gi`) on 1D launches. GPU-checked with `runtime/test/shaders/ms_v5_workgroup.asm` (24/24 groups exact on RTX 4060 Ti and RTX 3080, and on an RTX 4050 Laptop and an AMD Radeon 740M (RADV)); still unverified on Xbox hardware: the low 7 bits of `v5` on lanes 1..127 and whether 3D `DispatchMesh` flattens XYZ or uses X only. The merged-wave-info SGPR (s3 in this ABI) = wave ID << 24, from LocalInvocationIndex >> 6; `v_mbcnt` lanes = LocalInvocationIndex & 63; user data in s16.. as usual. All 9,282 mesh-shader listings of 1.0.2.1 (names starting with `.` included) read exactly v5 before writing anything (`rdna2spirv.read_before_write_vgprs` over the code `translate()` keeps). An earlier sample of 1,500 put 27 aside as adding loop-carried registers; over the corpus no extra read is loop-carried. Read raw, 266 of the 309 listings with embedded data words seem to read more VGPRs, each after a branch (in 101 the register is written after the read); they come from data words decoded as instructions and are gone once the listing is re-anchored to the FSSM code and cut to reachable code, as `translate()` does. 1,473 of 1,500 sampled mesh shaders read exactly v5, and the rest only add loop-carried registers. Exports: on NGG, thread t exports vertex t (`pos0`, `paramN`) and primitive t (`prim`). They're staged per invocation; an all-`off` export is the dummy a wave with no vertices must issue, and writes nothing. `s_sendmsg GS_ALLOC_REQ` (m0 = prims << 12 \| verts, sent by thread 0) stores the counts in a workgroup variable. At shader end, in uniform control flow: workgroup barrier, `OpSetMeshOutputsEXT(min(verts, max), min(prims, max))`, then each thread writes its staged vertex (Position + Location N) and primitive (`PrimitiveTriangleIndicesEXT` = bits [8:0], [18:10], [28:20]; `CullPrimitiveEXT` = bit 31). `pos1..pos3` clip/cull distances are staged per invocation and emitted in a per-vertex `Block` output struct (`Position` + `ClipDistance`/`CullDistance` arrays, `VK_EXT_mesh_shader`) when used, keeping the standalone `%ms_out_pos` layout unchanged for shaders without `pos1+`. The distances are copied to that struct one float at a time, not as a whole array: SPIRV-Cross 1.4.363.0 turns a whole-array store into a mesh output into a C array assignment that Metal rejects (SHADER-155; `ms_clip` then compiles and draws its 2048/4096 pixels in a native Metal mesh draw on an Apple A18 Pro). `%ms_cull` (the `PerPrimitiveEXT` `CullPrimitiveEXT` `Block`) is listed before `%ms_out_vtx` in `OpEntryPoint MeshEXT`'s interface list: AMD's proprietary Windows Vulkan driver `24.10.24` (LLPC) was reported, on one Ryzen 5 7600 iGPU, to segfault (`0xC0000005`) during `vkCreateGraphicsPipelines` when the per-vertex clip/cull `Block` precedes the per-primitive `Block` (even on `glslangValidator` output), while driver `32.0.32029.2010` on an RX 9070 XT and an RX 7900 XT accepts either order; the order has no meaning in SPIR-V, so this one costs nothing on other drivers; reordering the interface list fixes `ms_clip` on AMD Ryzen 5 7600 RDNA2 iGPU (`2048/2048` clipped, `2048/2048` drawn, `4096/4096` culled when `CullPrimitiveEXT = true`, 0 validation errors) while keeping `CullPrimitiveEXT` in its `Block+bool` form for SPIRV-Tools ≤2025.1 (`SHADER-MS-CLIP-IFACE`). GPU-checked with `runtime/test/shaders/ms_tri.asm` (`VKH_MESH=1 vk_harness`), built from the game's own idioms (thread ID from s3 and mbcnt across two waves, thread-0 ALLOC_REQ, per-thread exports): 0 error on every pixel. `Layer` and `ViewportIndex` from the `pos1` misc vector (`z[10:0]`, `z[19:16]`) are per-primitive members of `%ms_cull` (`Gen.export_misc_pos1`): each lane stages the value it exports and writes it to the primitive with its own index. That is exact when the value is the same for all vertices of a primitive; whether the hardware takes it from the primitive's provoking vertex instead is not measured. Confirmed by the translator tests (`tests/test_translate.py`); none of the 1,906 mesh shaders of the corpus that export `pos1` writes either, so the game's mesh shaders only gain unused declarations. Compressed exports (`exp pos1` / `exp param` with `compr`) unpack their two f16 pairs the way the pixel-shader compressed export does (`Gen.export_comps`): LLVM lists each register twice (`v4, v4, v5, v5`), so the pair is operands 1 and 3, each unpacked with `UnpackHalf2x16` into (x, y) and (z, w), and an `off` register leaves its two components unwritten. Before, such an export was refused. Confirmed by the translator tests (`tests/test_translate.py`); none of the 9,282 mesh shaders of the corpus uses one, so the game's translation does not change. | | Mesh shaders as compute (`--mesh-compute`) | For devices without `VK_EXT_mesh_shader` (NVIDIA Pascal, for one), and on by itself in `make_game.py` on Intel's Windows Vulkan driver (`VK_DRIVER_ID_INTEL_PROPRIETARY_WINDOWS` with mesh shaders, `runtime_gpu_mesh_draws_crash`): there `vkCmdDrawMeshTasksEXT` crashes (0xC0000409 in `igvk64.dll`) for a mesh shader with a live push-constant load at byte 32 or later, which every corpus mesh shader has, while `--mesh-compute` is exact (BUILD-2202, Arc A770, driver 32.0.101.9175; no fixed version known; `--native-mesh` keeps native mesh shaders). Each mesh shader becomes a `GLCompute` module with the same workgroup size and code; only the epilogue changes. Instead of `OpSetMeshOutputsEXT` and the mesh outputs, after the same barrier lane 0 writes the vertex and primitive counts, lane i < vertex count writes its vertex and lane i < primitive count its primitive into this workgroup's **slot** of an output buffer: slot = linear workgroup index (x + y·nx + z·nx·ny) × `slot_bytes`, computed in 64 bits. The buffer's device address is in push-constant dwords 36–37, so these modules declare 152 bytes. Slot layout (`rdna2spirv.mesh_compute_layout`, recorded per shader as `mesh_compute` in the index), all 16-byte aligned: a header (vertex count, primitive count), then `max_vertices` vertices, each holding the position, the clip and then cull distances padded to whole vec4s, and one vec4 per param location; then `max_primitives` primitives of three vertex indices plus 1 if culled. The modules need no mesh capability, extension or `shaderClipDistance`. `tools/mesh_compute_vs.py` writes the vertex shader that draws the slots with a non-indexed `vkCmdDraw(groups × max_primitives × 3)`: vertex v is workgroup v / (3·max_primitives), primitive (v / 3) mod max_primitives, corner v mod 3. A primitive past the count, or one culled, gets one position outside the clip volume at all three corners and is clipped. Otherwise the corner's index, clamped to `max_vertices` − 1, selects the vertex, and its position, distances and params go out at the mesh shader's locations, so the pixel shader is unchanged. One draw rasterizes in vertex order, which is workgroup then primitive order, as with mesh workgroups. Corpus: all 9,282 mesh shaders are 128×1×1 with 128/128 outputs, wave64, 0–18 params, clip distances in 1,906, cull distances and per-primitive attributes in none, no task shaders. On a 32-wide device combine it with `--wave64-emulate`. GPU-checked on an NVIDIA GeForce GTX 1060 6GB (Pascal: no mesh shaders; driver 560.94, Windows 10) with `LEONIDA_MESH_COMPUTE=1 LEONIDA_W64_EMULATE=1`: `ms_tri`, `ms_w64x_ballot` and `ms_wave_info_s3` 4096/4096 pixels exact, `ms_clip` 2048/4096 covered as expected, `ms_v5_workgroup` 24/24 workgroup coordinates, zero Khronos validation messages. Checked in `tests/test_mesh_compute.py`. The runtime side, turning a `DispatchMesh` into that dispatch, a barrier and the draw, is the follow-up (it needs the graphics pipelines of #291). Unused primitives still run the vertex shader; compaction with an indirect draw would avoid that. | +| Mesh shaders with their waves in series (`--mesh-serial-waves`) | With `--wave64-emulate`, a mesh shader of more than 64 threads is several waves side by side in one workgroup, and what its waves do not do alike (a region one wave enters and the other skips, with votes or memory accesses inside) goes to mini-schedulers: a round loop over a `%pc` switch. With this flag a mesh shader whose thread count is a multiple of 64 and whose waves cannot pass each other anything (no `ds_` instruction, no store or atomic to memory, not `--mesh-compute`) declares `LocalSize 64` and runs one pass per wave instead (`ms_serial_passes`, `ms_serial_epilogue`). `%local_index` becomes a Function variable, the built-in (`%real_local_index`) plus 64 x pass, so the launch state (v5, the wave id in s3) and every lane computation see the wave of the pass; every initialised Function variable is stored again at the start of a pass; what a pass exported is copied to per-pass twins of the export variables; after the loop the epilogue does its barrier, reads the counts and calls `OpSetMeshOutputsEXT` once, then writes each pass's vertices and primitives at index built-in + 64 x pass. Each pass is one wave, so the plan is the single-wave one (`inline_all` when the program has branches) and the exchange buffer is one wave's, addressed by the invocation's own index. Why the order of the waves is not observable: the waves of such a program share nothing but the allocation request and the exports, which the epilogue orders itself (the request may come from any wave: the counts are read after all passes). A program that shares LDS (`ms_wave_info_s3`) or writes memory keeps the side-by-side form, as does everything without the flag: off by default, and with it off the output is unchanged. Measured on an RTX 4080 (NVIDIA 621.24, 32-wide subgroups): the `ms_*` GPU tests pass in both forms, among them `ms_w64x_wave_votes`, whose two waves take different branches with their own ballots and whose triangle takes vertices from both; module shape by `tests/test_mesh_serial_waves.py`. Not measured: other vendors, llvmpipe, a thread count that is not a multiple of 64 (kept side by side). | | Mesh primitive export and allocation (`exp prim`, `MSG_GS_ALLOC_REQ`) | The GFX10 NGG formats, from Mesa 22.3 `src/amd/llvm/ac_llvm_build.c`: `ac_build_sendmsg_gs_alloc_req` (lines 4475–4477) puts `prim_cnt << 12 \| vtx_cnt` in m0, and `ac_pack_prim_export` (lines 4518–4539) packs index 0, 1 and 2 in bits 0–8, 10–18 and 20–28, the edge flags in bits 9, 19 and 29 and "null primitive (skip)" in bit 31. Thread t exports vertex t and primitive t, only below the vertex and primitive counts (`src/amd/common/ac_nir_lower_ngg.c`, `emit_ms_finale`, lines 4056–4067). Translated: the counts from m0 (each clamped to PSV0's maximum) go to `OpSetMeshOutputsEXT` or the `--mesh-compute` header; `PrimitiveTriangleIndicesEXT` takes the three 9-bit fields without the edge flags, and `CullPrimitiveEXT` (or the slot's culled word) is bit 31; invocations at or past a count write nothing. Executed for both paths in `tests/semantic/test_ms_prim_export.py` (72 threads in two wave64 waves: odd threads set the edge flags, threads with t & 2 the null bit). Open: the index fields are not clamped to the vertex count as Mesa's mesh lowering clamps them (`ac_nir_lower_ngg.c` line 4112), so a null primitive whose fields point past the count (skipped on hardware) would be undefined in SPIR-V; no corpus count of such exports exists. | | Geometry shaders | On output stream zero, `GS_OP_EMIT_CUT` emits the staged vertex and ends its strip under the same EXEC guard. The synthetic `gs_emit_cut.asm` checks that six vertices form two separate triangles. [RDNA 2 ISA, S_SENDMSG](https://docs.amd.com/api/khub/documents/Et~wpu9g~Ffl7d9q0QZ~Og/content). All 195 are `$GS_VoxelizeGeneric` permutations: legacy (merged ES/GS) wave32 programs on LDS rings, with no `exp`. All 195 are `$GS_VoxelizeGeneric` permutations: legacy (merged ES/GS) programs on LDS rings, with no `exp`, written for wave64 (the FSSM header's wave-size flag says wave64 in 195 of 195, see *Wave size*, and the translator's index marks all 195 `wave64` with `subgroup_size` 64 at `f847748c`; the code agrees: the EXEC prologue that `gs_tri.asm` mirrors compares the thread count with 64 and writes a 64-bit EXEC, the count in #94 finds `v_mbcnt_hi_u32_b32` in all 195, and the translator marks all 195 `wave64`; an earlier version of this row said wave32, TEST-251). Inputs: vertex i sits at the dword offset in v0 lo / v0 hi / v1 lo; an LDS read at vertex base + 4·(4·reg + comp) is input-signature register reg, component comp (checked: SV_Position xyz in dwords 0–2 and TEXCOORD0.xy in 4–5, as ISG1 declares). Outputs: emitted vertex k is dwords [k·4·nreg, (k+1)·4·nreg) of the lane's GSVS area, dword = 4·reg + comp of the output signature (20 dwords = 5 OSG1 registers; every write matches a declared mask). Translation: synthetic offsets (vertex i at dword 64·i), LDS reads → `gl_in[i]` inputs, LDS writes → staged slots, `MSG_GS EMIT` → copy slot (emit count) to the outputs + `OpEmitVertex`, `CUT` → `OpEndPrimitive`, `GS_DONE` → nothing. The prologue's `s_bfm_b64`/`s_cselect` EXEC setup is fed s3 = 64 << 8. GPU-checked with `runtime/test/shaders/gs_tri.asm` (`VKH_GS=… vk_harness`): 0 error. Without a geometry stage (Apple GPUs: Metal, MoltenVK), `tools/spirv_gs_to_compute.py` lowers the translated module to a compute capture pass, one invocation per input primitive: inputs come from a buffer, each `OpEmitVertex` guards its record/meta stores and `%gsc_n` increment on `n < OutputVertices` (dropping excess vertices rather than overflowing into the next primitive's slots, and updating `OpPhi` predecessors across split blocks, and rejecting (`Unsupported`) an `OpEmitVertex` in a loop header before its `OpLoopMerge`, which the split would move; SHADER-617, checked on the CPU by `tests/test_spirv_gs_to_compute_bounds.py`), and a meta buffer holds each primitive's vertex count (`<= OutputVertices`) and strip ends, for an ordinary draw afterwards (SHADER-159). Metal, MoltenVK), `tools/spirv_gs_to_compute.py` lowers the translated module to a compute capture pass, one invocation per input primitive: inputs come from a buffer, each `OpEmitVertex` writes the outputs to a record buffer, and a meta buffer holds each primitive's vertex count and strip ends, for an ordinary draw afterwards (SHADER-159). `gs_tri` lowered this way, converted with SPIRV-Cross and run natively on an Apple A18 Pro: 195/195 records exact for 65 random triangles, and the captured fullscreen triangle drawn from the records matches all 4096 gradient pixels. Not done: wiring it into a draw path, and GS that use cross-lane operations or more than one invocation. | | Integer clamp | The VOP3 `clamp` bit on `v_add_nc_u32`, `v_sub_nc_u32`, `v_subrev_nc_u32` saturates the result to [0, 0xFFFFFFFF], and on `v_add_nc_i32`/`v_sub_nc_i32` to [0x80000000, 0x7FFFFFFF]; without it they wrap. GFX9+ semantics: LLVM selects `uaddsat`/`usubsat` and `saddsat`/`ssubsat` to exactly these ops with clamp set. **Until this change clamp was silently ignored on the unsigned ops** (and the signed ones were `Unsupported`). Checked on the CPU by `tests/semantic/test_alu_add_nc_clamp.py`. The carry-out unsigned ops (`v_add_co_u32`, `v_sub_co_u32`, `v_subrev_co_u32`, `v_add_co_ci_u32`, `v_sub_co_ci_u32`, `v_subrev_co_ci_u32`) with VOP3 `clamp` likewise saturate D to `0xFFFFFFFF` on add carry or `0` on sub borrow while still reporting the real carry/borrow bit in `sdst` (**until 2026-11-22 the translator ignored `clamp` on all six**); confirmed natively on RDNA2 (AMD Radeon 680M `gfx1035` wave32 & wave64 via `tools/hw_oracle`, and independently on `gfx1036` in #1746) and CPU-checked by `tests/semantic/test_alu_add_co_clamp.py`. The 16-bit unsigned add/sub (`v_add_nc_u16`, `v_sub_nc_u16`, and the `v_add_u16`/`v_sub_u16`/`v_subrev_u16` `_e64` names) saturate to [0, 0xFFFF] with `clamp` (llvm-mc 21 gfx1030 encodes the bit on them, and LLVM selects i16 `uaddsat`/`usubsat` to them); **until 2026-11-22 the translator wrapped instead**. `clamp` on any other 16-bit integer op raises `Unsupported`. CPU-checked by `tests/semantic/test_alu_u16_clamp.py` (the high half of the destination is kept), **not GPU-verified**. CPU-checked by `tests/semantic/test_alu_u16_clamp.py` (the high half of the destination is kept), and **Hardware-verified on RDNA2** (AMD Radeon 680M, `gfx1035`, Windows 11, driver `26.5.1`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137): all 32-bit and 16-bit `*_nc_*` `clamp` cases (including `op_sel` and kept destination half on u16) match hardware bit-for-bit. **Open divergence measured on the same hardware:** `v_add_co_u32`, `v_sub_co_u32`, `v_subrev_co_u32`, `v_add_co_ci_u32`, `v_sub_co_ci_u32` and `v_subrev_co_ci_u32` with `clamp` saturate D (`0xFFFFFFFF` / `0`) while still reporting the real carry/borrow in `sdst`, whereas the translator currently ignores `clamp` on these carry-out ops. | diff --git a/docs/testing.md b/docs/testing.md index 671c5548c9..4d4e450a4e 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -574,6 +574,13 @@ only for `check.py`, the shaders read the tail from push constants the programs (`LEONIDA_MESH_COMPUTE=1`) isn't combined with it yet: its vertex shader still reads the output address from push constants, so those tests skip. +## Mesh shaders with their waves in series + +`LEONIDA_MESH_SERIAL_WAVES=1` for `run_gpu_tests.py`, together with `LEONIDA_W64_EMULATE=1`, translates the mesh +shaders with `--mesh-serial-waves` (`docs/design.md`, "Mesh shaders with their waves in series"): the ones that +qualify run one pass per wave in 64 invocations. The `ms_*` tests must pass with and without it; +`ms_w64x_wave_votes` is the one whose two waves take different branches and both give the triangle a vertex. + ## GPUs without mesh shaders (NVIDIA Pascal and older) Without `VK_EXT_mesh_shader`, the `ms_*` tests are skipped; that's expected, not a failure. To test the path that diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index 1ac19c96e4..455700a40f 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py @@ -947,6 +947,8 @@ def run_suite(a, work: str) -> int: cmd.append("--texel-offset-fallback") if MESH_COMPUTE: # mesh shaders as compute writing to a buffer, drawn by tools/mesh_compute_vs.py cmd.append("--mesh-compute") + if os.environ.get("LEONIDA_MESH_SERIAL_WAVES") == "1": # with --wave64-emulate: one pass per wave + cmd.append("--mesh-serial-waves") if pc_tail_ubo(): # 128 push-constant bytes; heap base and code base from a uniform block at set 1 cmd.append("--pc-tail-ubo") if os.environ.get("LEONIDA_FMA") in ("glsl", "khr", "exact"): # GLSL Fma, OpFmaKHR or emulated (docs/design.md) diff --git a/tests/conftest.py b/tests/conftest.py index 308590f678..c23a3ecb22 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -142,6 +142,8 @@ def mesh_psv0_chunk(threads=(128, 1, 1), max_vertices=64, max_primitives=64, top SAMPLE_DXBC = {"gs_tri": GS_TRI_DXBC, "ms_tri": MS_TRI_DXBC, "ms_clip": MS_CLIP_DXBC, "ms_wave_info_s3": MS_TRI_DXBC, "ms_w64x_ballot": MS_TRI_DXBC, "ms_f16_pack": MS_TRI_DXBC, # scripts/run_gpu_tests.py, ms_tri's PSV0 "gs_w64_a_ring": GS_TRI_DXBC, "gs_w64_c_lane_id": GS_TRI_DXBC, # build.py gives every gs_* gs_tri's + # vertex 64 comes from the second wave: 128 output vertices (scripts/run_gpu_tests.py) + "ms_w64x_wave_votes": make_dxbc([mesh_psv0_chunk(max_vertices=128)]), "ms_v5_workgroup": make_dxbc([mesh_psv0_chunk(threads=(32, 1, 1), max_vertices=3, max_primitives=1, group_shared=128)])} diff --git a/tests/test_mesh_serial_waves.py b/tests/test_mesh_serial_waves.py new file mode 100644 index 0000000000..043e9284a2 --- /dev/null +++ b/tests/test_mesh_serial_waves.py @@ -0,0 +1,109 @@ +"""rdna2spirv.py --mesh-serial-waves: a mesh shader's waves one after the other in 64 invocations. + +Under --wave64-emulate a 128-thread mesh shader is two waves side by side in one workgroup, and what the waves do +not do alike goes through mini-schedulers. With --mesh-serial-waves a program whose waves cannot pass each other +anything (no LDS, no store or atomic to memory) declares 64 invocations and runs one pass per wave, each pass a +single wave. The inputs are the hand-written GPU tests runtime/test/shaders/ms_*.asm with conftest's synthetic +PSV0 containers (no game data); on the GPU, scripts/run_gpu_tests.py with LEONIDA_W64_EMULATE=1 and +LEONIDA_MESH_SERIAL_WAVES=1 draws them. Here: +* a program that qualifies declares LocalSize 64, loops over the passes (and, when it has branches, has no + OpSwitch left: one wave gets the inline plan), takes the invocation's index from the built-in plus 64 * pass, keeps one copy of the export variables per pass and sets + the mesh outputs once; it passes spirv-val; the metadata records the number of passes and keeps the program's + thread count; +* the exchange takes its place in %x_buf from the invocation's own index, not from the lane it runs; +* ms_wave_info_s3, whose waves count lanes in LDS, keeps the side-by-side form, and so does every program + without --wave64-emulate, under --mesh-compute or of at most 64 threads; +* without the flag the module is unchanged. +""" +import os +import re +import sys + +import pytest + +from conftest import ROOT, SAMPLE_DXBC, requires_tools + +sys.path.insert(0, os.path.join(ROOT, "tools")) +import rdna2spirv # noqa: E402 + +SERIAL = ("ms_tri", "ms_clip", "ms_f16_pack", "ms_w64x_ballot", "ms_w64x_wave_votes") +SIDE_BY_SIDE = ("ms_wave_info_s3", # LDS shared by the waves + "ms_v5_workgroup") # 32 threads: one partial wave + + +def _translate(make_shader, name, serial, emulate=True, compute=False): + with open(os.path.join(ROOT, "runtime", "test", "shaders", name + ".asm"), encoding="utf-8") as f: + shader = make_shader(f.read(), name, dxbc=SAMPLE_DXBC[name]) + old = rdna2spirv.MESH_SERIAL_WAVES, rdna2spirv.WAVE64_EMULATE, rdna2spirv.MESH_COMPUTE + rdna2spirv.MESH_SERIAL_WAVES, rdna2spirv.WAVE64_EMULATE, rdna2spirv.MESH_COMPUTE = serial, emulate, compute + try: + spvasm = shader.translate() + meta = rdna2spirv.shader_meta(rdna2spirv.translate.last_gen, spvasm) + finally: + rdna2spirv.MESH_SERIAL_WAVES, rdna2spirv.WAVE64_EMULATE, rdna2spirv.MESH_COMPUTE = old + return shader, spvasm, meta + + +@requires_tools +@pytest.mark.parametrize("name", SERIAL) +def test_serial_module(make_shader, name): + shader, spvasm, meta = _translate(make_shader, name, True) + shader.validate(spvasm) + assert "OpExecutionMode %main LocalSize 64 1 1" in spvasm + assert meta["mesh_serial_waves"] == 2 and meta["local_size"] == [128, 1, 1] + if name == "ms_w64x_wave_votes": # a program with branches: one wave gets the inline plan, no scheduler + assert "OpSwitch" not in spvasm # (a straight-line program keeps the round loop over its segments) + assert spvasm.count("OpLoopMerge %msw_exit %msw_cont None") == 1 + # The built-in is only read to make the pass's index and the exchange's own place. + assert "OpDecorate %real_local_index BuiltIn LocalInvocationIndex" in spvasm + assert "%local_index = OpVariable %_ptr_Function_uint Function" in spvasm + assert re.search(r"%msw_li = OpIAdd %uint %msw_rl %msw_off\s+OpStore %local_index %msw_li", spvasm) + assert "%x_li = OpLoad %uint %real_local_index" in spvasm + assert "%x_li = OpLoad %uint %local_index" not in spvasm + # One copy of what a pass exported per pass, one OpSetMeshOutputsEXT, one write block per pass. + for w in (0, 1): + assert f"OpCopyMemory %ms_pos__w{w} %ms_pos" in spvasm + assert f"OpLoad %v4float %ms_pos__w{w}" in spvasm + assert f"%mli_w{w} = OpIAdd %uint %msw_erl" in spvasm + assert spvasm.count("OpSetMeshOutputsEXT") == 1 + assert spvasm.index("%msw_exit = OpLabel") < spvasm.index("OpSetMeshOutputsEXT") + + +@requires_tools +@pytest.mark.parametrize("name", SERIAL) +def test_initialised_variables_are_set_again_each_pass(make_shader, name): + _, spvasm, _ = _translate(make_shader, name, True) + body = spvasm[spvasm.index("%msw_body = OpLabel"):] + variables = re.findall(r"^\s*(%\w+) = OpVariable \S+ Function (\S+)$", spvasm, re.M) + assert variables + for var, init in variables: + if var in ("%local_index", "%msw_pass") or "__w" in var: + continue # the pass counter, the index it sets, and the per-pass copies + assert re.search(rf"OpStore {re.escape(var)} {re.escape(init)}\n", body), var + + +@requires_tools +@pytest.mark.parametrize("name", SIDE_BY_SIDE) +def test_program_that_does_not_qualify_is_unchanged(make_shader, name): + _, plain, plain_meta = _translate(make_shader, name, False) + _, flagged, meta = _translate(make_shader, name, True) + assert flagged == plain and meta == plain_meta + assert "mesh_serial_waves" not in meta and "%msw_" not in flagged + + +@requires_tools +@pytest.mark.parametrize("emulate,compute", [(False, False), (True, True)], ids=["native", "mesh-compute"]) +def test_flag_needs_emulation_and_the_mesh_path(make_shader, emulate, compute): + _, plain, _ = _translate(make_shader, "ms_tri", False, emulate, compute) + _, flagged, meta = _translate(make_shader, "ms_tri", True, emulate, compute) + assert flagged == plain and "mesh_serial_waves" not in meta + + +@requires_tools +@pytest.mark.parametrize("name", SERIAL) +def test_without_the_flag_the_waves_are_side_by_side(make_shader, name): + shader, spvasm, meta = _translate(make_shader, name, False) + shader.validate(spvasm) + assert "OpExecutionMode %main LocalSize 128 1 1" in spvasm + assert "%msw_" not in spvasm and "mesh_serial_waves" not in meta + assert "OpDecorate %local_index BuiltIn LocalInvocationIndex" in spvasm diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 760f6b7b0d..1b9e9c5506 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -20215,10 +20215,9 @@ def main(): "(metadata: mesh_compute), drawn by tools/mesh_compute_vs.py, for devices without " "VK_EXT_mesh_shader (e.g. NVIDIA Pascal)") ap.add_argument("--mesh-serial-waves", action="store_true", - default=os.environ.get("LEONIDA_MESH_SERIAL_WAVES") == "1", - help="with --wave64-emulate: a mesh shader of more than 64 threads whose waves share no LDS runs " - "its waves one after the other in 64 invocations (one single-wave pass per wave) instead of " - "side by side; also on with LEONIDA_MESH_SERIAL_WAVES=1") + help="with --wave64-emulate: a mesh shader of more than 64 threads whose waves cannot pass each " + "other anything (no LDS, no store or atomic) runs its waves one after the other in 64 " + "invocations, one single-wave pass per wave, instead of side by side (docs/design.md)") ap.add_argument("--shader-clock", choices=("off", "khr"), default="off", help="s_memtime / s_memrealtime: off = Unsupported (default), khr = OpReadClockKHR (needs " "VK_KHR_shader_clock; feature shaderSubgroupClock / shaderDeviceClock in the metadata)") From cd25a5c95a1a7c94f2167647fc2ef9b138512845 Mon Sep 17 00:00:00 2001 From: quartz-heron-58 <245169279+quartz-heron-58@users.noreply.github.com> Date: Fri, 27 Nov 2026 13:27:43 +0800 Subject: [PATCH 4/6] mesh-serial-waves: a unit test for a wave whose program ends early A variant of ms_w64x_wave_votes with an s_endpgm behind a branch in the middle of the program: the module still qualifies, validates, and main keeps one return, after the loop over the passes and the output writes. Suggested in review by tiguan26. Co-Authored-By: Claude Fable 5.2 --- tests/test_mesh_serial_waves.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/tests/test_mesh_serial_waves.py b/tests/test_mesh_serial_waves.py index 043e9284a2..95afb4b277 100644 --- a/tests/test_mesh_serial_waves.py +++ b/tests/test_mesh_serial_waves.py @@ -107,3 +107,32 @@ def test_without_the_flag_the_waves_are_side_by_side(make_shader, name): assert "OpExecutionMode %main LocalSize 128 1 1" in spvasm assert "%msw_" not in spvasm and "mesh_serial_waves" not in meta assert "OpDecorate %local_index BuiltIn LocalInvocationIndex" in spvasm + + +@requires_tools +def test_a_wave_that_ends_early_does_not_skip_the_later_passes(make_shader): + # ms_w64x_wave_votes with an s_endpgm in the middle of the program, behind a branch on the wave's number (7, + # so never taken here): the end of one wave's program must end its pass, not the invocation. + name = "ms_w64x_wave_votes" + with open(os.path.join(ROOT, "runtime", "test", "shaders", name + ".asm"), encoding="utf-8") as f: + text = f.read() + at = "s_bfe_u32 s4, s3, 0x40018\n" + assert text.count(at) == 1 + text = text.replace(at, at + "s_cmp_eq_u32 s4, 7\ns_cbranch_scc0 1\ns_endpgm\n") + shader = make_shader(text, name, dxbc=SAMPLE_DXBC[name]) + old = rdna2spirv.MESH_SERIAL_WAVES, rdna2spirv.WAVE64_EMULATE + rdna2spirv.MESH_SERIAL_WAVES, rdna2spirv.WAVE64_EMULATE = True, True + try: + spvasm = shader.translate() + meta = rdna2spirv.shader_meta(rdna2spirv.translate.last_gen, spvasm) + finally: + rdna2spirv.MESH_SERIAL_WAVES, rdna2spirv.WAVE64_EMULATE = old + shader.validate(spvasm) + assert meta["mesh_serial_waves"] == 2 + assert spvasm != _translate(make_shader, name, True)[1] # the early end is in the module + assert "OpExecutionMode %main LocalSize 64 1 1" in spvasm + main = spvasm[spvasm.index("%main = OpFunction"):] + main = main[:main.index("OpFunctionEnd")] + # One return, after the loop over the passes and after the outputs are written. + assert main.count("OpReturn") == 1 and "OpKill" not in main and "OpTerminateInvocation" not in main + assert main.index("%msw_exit = OpLabel") < main.index("OpSetMeshOutputsEXT") < main.index("OpReturn") From dbdef2efd7c8c6bd2ec11d4456d28e4c34ece113 Mon Sep 17 00:00:00 2001 From: quartz-heron-58 <245169279+quartz-heron-58@users.noreply.github.com> Date: Fri, 27 Nov 2026 17:29:50 +0800 Subject: [PATCH 5/6] mesh-serial-waves: a GPU fixture whose two waves run loops of different length ms_w64x_wave_loops: each wave loops while a wave-wide count is not 0, 5 iterations in wave 0 and 9 in wave 1, so under --wave64-emulate the waves reach different numbers of workgroup barriers. Written after stalls were reported with the serial form on an RTX 2070 SUPER (issue 1608). On an RTX 4080 (NVIDIA 621.24) it draws 4096/4096 pixels exact side by side and in series; that does not explain the stalls. Co-Authored-By: Claude Fable 5.2 --- docs/testing.md | 2 +- runtime/test/shaders/ms_w64x_wave_loops.asm | 63 +++++++++++++++++++++ scripts/run_gpu_tests.py | 6 +- tests/conftest.py | 1 + tests/test_mesh_serial_waves.py | 2 +- 5 files changed, 69 insertions(+), 5 deletions(-) create mode 100644 runtime/test/shaders/ms_w64x_wave_loops.asm diff --git a/docs/testing.md b/docs/testing.md index 4d4e450a4e..62f5ced44a 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -579,7 +579,7 @@ constants, so those tests skip. `LEONIDA_MESH_SERIAL_WAVES=1` for `run_gpu_tests.py`, together with `LEONIDA_W64_EMULATE=1`, translates the mesh shaders with `--mesh-serial-waves` (`docs/design.md`, "Mesh shaders with their waves in series"): the ones that qualify run one pass per wave in 64 invocations. The `ms_*` tests must pass with and without it; -`ms_w64x_wave_votes` is the one whose two waves take different branches and both give the triangle a vertex. +`ms_w64x_wave_votes` is the one whose two waves take different branches and both give the triangle a vertex. `ms_w64x_wave_loops` is the one whose two waves run a loop of different length (5 and 9 iterations), each iteration reading a wave-wide count, so under emulation the waves reach different numbers of barriers. ## GPUs without mesh shaders (NVIDIA Pascal and older) diff --git a/runtime/test/shaders/ms_w64x_wave_loops.asm b/runtime/test/shaders/ms_w64x_wave_loops.asm new file mode 100644 index 0000000000..45fc924c68 --- /dev/null +++ b/runtime/test/shaders/ms_w64x_wave_loops.asm @@ -0,0 +1,63 @@ +; Mesh shader (NGG, wave64, 128 threads = 2 waves): each wave runs a loop whose every iteration reads a wave-wide +; count, and the two waves leave it after a different number of iterations. +; limit of a lane = (lane & 3) + 1 in wave 0, (lane & 7) + 1 in wave 1. +; each iteration counts the lanes whose limit is above the iteration number (s_bcnt1 of a 64-lane compare), adds +; the count to a sum and goes round again while the count is not 0. +; wave 0: counts 64, 48, 32, 16, 0: 5 iterations, sum 160. wave 1: 64, 56, ..., 8, 0: 9 iterations, sum 288. +; A wave whose sum is right sets the blue channel of param0 to 0.5 in the vertices it exports, else 0. +; The triangle is ms_tri's, with its vertices from threads 0 and 1 (wave 0) and thread 64 (wave 1), as in +; ms_w64x_wave_votes: the picture is ms_tri's only when both waves ran their own number of iterations with their +; own lanes. Under --wave64-emulate every count is an exchange with a workgroup barrier inside the loop, so the +; waves reach different numbers of barriers; with --mesh-serial-waves the two loops run one after the other. +; Only wave 0 sends the mesh allocation (1 primitive, 65 vertices: indices 0, 1 and 64 are used). +; Needs a DXBC with PSV0 (128 threads, 128/64 outputs, triangles; see scripts/run_gpu_tests.py): +; VKH_MESH=1 vk_harness ms_w64x_wave_loops.spv fs_passthru.spv out.raw +; -> every pixel = ((x+0.5)/64, (y+0.5)/64, 0.5, 1), identical to ms_tri. +; mattr: +wavefrontsize64,-wavefrontsize32 +v_mbcnt_lo_u32_b32 v0, -1, 0 +v_mbcnt_hi_u32_b32 v0, -1, v0 +v_mov_b32_e32 v11, v0 +s_bfe_u32 s4, s3, 0x40018 +v_lshl_add_u32 v0, s4, 6, v0 +s_mov_b32 s14, 288 +s_cmp_eq_u32 s4, 0 +s_cselect_b32 s5, 3, 7 +s_cselect_b32 s14, 160, s14 +v_and_b32_e32 v13, s5, v11 +v_add_nc_u32_e32 v13, 1, v13 +s_mov_b32 s20, 0 +s_mov_b32 s22, 0 +v_mov_b32_e32 v20, s20 +v_cmp_lt_u32_e64 s[6:7], v20, v13 +s_bcnt1_i32_b64 s10, s[6:7] +s_add_u32 s22, s22, s10 +s_add_u32 s20, s20, 1 +s_cmp_lg_u32 s10, 0 +s_cbranch_scc1 65528 +s_cmp_eq_u32 s22, s14 +s_cselect_b32 s13, 1, 0 +v_cvt_f32_u32_e32 v15, s13 +v_mul_f32_e32 v15, 0.5, v15 +v_cmp_eq_u32_e32 vcc, 1, v0 +v_cndmask_b32_e64 v1, -1.0, 0x40400000, vcc +v_cndmask_b32_e64 v3, 0, 2.0, vcc +v_cmp_eq_u32_e32 vcc, 64, v0 +v_cndmask_b32_e64 v2, -1.0, 0x40400000, vcc +v_cndmask_b32_e64 v4, 0, 2.0, vcc +v_mov_b32_e32 v6, 0 +v_mov_b32_e32 v7, 1.0 +v_mov_b32_e32 v8, v15 +s_mov_b32 m0, 0x1041 +s_cmp_lg_u32 s4, 0 +s_cbranch_scc1 1 +s_sendmsg sendmsg(MSG_GS_ALLOC_REQ) +v_cmp_gt_u32_e64 s[16:17], 2, v0 +v_cmp_eq_u32_e64 s[18:19], 64, v0 +s_or_b64 exec, s[16:17], s[18:19] +exp pos0 v1, v2, v6, v7 done +exp param0 v3, v4, v8, v7 +s_mov_b64 exec, -1 +v_cmpx_eq_u32_e32 0, v0 +v_mov_b32_e32 v9, 0x4000400 +exp prim v9, off, off, off done +s_endpgm diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index 455700a40f..ccfc488b0f 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py @@ -895,7 +895,7 @@ def run_suite(a, work: str) -> int: ]) elif name in ("ms_tri", "ms_w64x_ballot", "ms_wave_info_s3", "ms_f16_pack"): dxbc = make_dxbc([(b"PSV0", make_ms_psv0(128, 64, 64, 2))]) - elif name == "ms_w64x_wave_votes": # vertex 64 comes from the second wave: 128 output vertices + elif name in ("ms_w64x_wave_votes", "ms_w64x_wave_loops"): # vertex 64 comes from the second wave: 128 output vertices dxbc = make_dxbc([(b"PSV0", make_ms_psv0(128, 128, 64, 2))]) elif name == "ms_v5_workgroup": dxbc = make_dxbc([(b"PSV0", make_ms_psv0(32, 3, 1, group_shared=128))]) @@ -1636,13 +1636,13 @@ def run_suite(a, work: str) -> int: problem = mesh_v5_test(a.build, spirv_dir, Path(raw_dir) / f"{name}.raw") results.append((name, None if isinstance(problem, Skip) else not problem, problem or "24/24 workgroup coordinates exact (2 x 3 x 4)")) - elif name in ("ms_tri", "ms_w64x_ballot", "ms_wave_info_s3", "ms_w64x_wave_votes"): + elif name in ("ms_tri", "ms_w64x_ballot", "ms_wave_info_s3", "ms_w64x_wave_votes", "ms_w64x_wave_loops"): raw = os.path.join(raw_dir, f"{name}.raw") env = mesh_env(spirv_dir, name, gfx_env) rc, msg = run_readback(raw, run_cmd, [vk_harness, spv, fs_passthru, raw], env=env) # ms_w64x_ballot needs exact wave64 (a 64-wide subgroup, or --wave64-emulate): skip it elsewhere, as # the wave64 compute dumps are. - no64 = (name in ("ms_w64x_ballot", "ms_w64x_wave_votes") and not w64_emulated() and + no64 = (name in ("ms_w64x_ballot", "ms_w64x_wave_votes", "ms_w64x_wave_loops") and not w64_emulated() and not any(int(x) >= 64 for x in re.findall(r"subgroup \d+\.\.(\d+)", msg))) if rc == UNSUPPORTED: results.append((name, None, unsupported_skip(msg))) diff --git a/tests/conftest.py b/tests/conftest.py index c23a3ecb22..d5fde526e1 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -144,6 +144,7 @@ def mesh_psv0_chunk(threads=(128, 1, 1), max_vertices=64, max_primitives=64, top "gs_w64_a_ring": GS_TRI_DXBC, "gs_w64_c_lane_id": GS_TRI_DXBC, # build.py gives every gs_* gs_tri's # vertex 64 comes from the second wave: 128 output vertices (scripts/run_gpu_tests.py) "ms_w64x_wave_votes": make_dxbc([mesh_psv0_chunk(max_vertices=128)]), + "ms_w64x_wave_loops": make_dxbc([mesh_psv0_chunk(max_vertices=128)]), "ms_v5_workgroup": make_dxbc([mesh_psv0_chunk(threads=(32, 1, 1), max_vertices=3, max_primitives=1, group_shared=128)])} diff --git a/tests/test_mesh_serial_waves.py b/tests/test_mesh_serial_waves.py index 95afb4b277..071599d23b 100644 --- a/tests/test_mesh_serial_waves.py +++ b/tests/test_mesh_serial_waves.py @@ -26,7 +26,7 @@ sys.path.insert(0, os.path.join(ROOT, "tools")) import rdna2spirv # noqa: E402 -SERIAL = ("ms_tri", "ms_clip", "ms_f16_pack", "ms_w64x_ballot", "ms_w64x_wave_votes") +SERIAL = ("ms_tri", "ms_clip", "ms_f16_pack", "ms_w64x_ballot", "ms_w64x_wave_votes", "ms_w64x_wave_loops") SIDE_BY_SIDE = ("ms_wave_info_s3", # LDS shared by the waves "ms_v5_workgroup") # 32 threads: one partial wave From 29361079f69b9e38449dcc1e8896f5f172e5627a Mon Sep 17 00:00:00 2001 From: qhukz13 Date: Fri, 27 Nov 2026 22:26:50 +0200 Subject: [PATCH 6/6] rdna2spirv: --mesh-serial-waves under --mesh-compute too (SHADER-W64-MESH-SERIAL-COMPUTE) GPUs without VK_EXT_mesh_shader (NVIDIA Pascal) translate mesh programs with --mesh-compute and are the ones that need wave64 emulation most, but the switch was off there. The compute program now runs the same passes, and mesh_compute_epilogue's slot writes go through ms_serial_epilogue: the header from index 0, which only pass 0's lane 0 has, and each pass's vertices and primitives at the built-in index + 64 * pass, from that pass's copies. Co-Authored-By: Claude Opus 5.5 --- docs/design.md | 2 +- docs/testing.md | 1 + tests/test_mesh_serial_waves.py | 56 ++++++++++++++++++++++++++++++--- tools/rdna2spirv.py | 21 ++++++++----- 4 files changed, 66 insertions(+), 14 deletions(-) diff --git a/docs/design.md b/docs/design.md index cc022cedc1..a474f82992 100644 --- a/docs/design.md +++ b/docs/design.md @@ -367,7 +367,7 @@ How the generated SPIR-V expects the runtime to work: | Wave size | **Most of the game's shaders are wave64: 23,841 of 26,503** (`fssm_header.wave_size()`: FSSM header flags word `u32[0xD4]` bit 5, `0x20` = wave32, `0` = wave64; 0 contradictions against GFX10 code-proven wave32/wave64 instructions across all 26,503 blobs): 10,974 of 12,101 PS, 9,282 of 9,282 mesh shaders, 2,236 of 2,236 VS, 1,154 of 2,689 CS and 195 of 195 GS, against 2,662 wave32 (1,535 CS and 1,127 PS). A full-corpus translation at `ec8ec4c9` marks exactly these 23,841 `wave64` (`subgroup_size` 64) in the index. Before the FSSM flag (#1900) the wave size came from code markers (64-bit EXEC/mask writes, `exec_hi`, `*_saveexec_b64`): at `6a6704df` they made 21,538 of the 26,487 shaders translated then wave64 (the figure quoted here was 21,545). 10,031 PS, 9,282 mesh shaders, 1,179 VS, 851 CS and 195 GS (the 16 shaders refused then are all wave64 CS by the flag; the figure quoted here was 21,545). Against the flag they call 2,287 wave64 shaders wave32 (943 PS, 1,057 VS, 287 CS), whose code has no 64-bit EXEC/mask marker, and none the other way. An older marker scan (`s_mov_b64 exec, -1`, `exec_hi`, `s_and/or_saveexec_b64` and 64-bit masks) counted 9,930 PS, 8,666 mesh shaders, 1,115 VS and 923 CS, but it left out the 769 listings whose names start with `.` (616 of them mesh shaders; Python's `glob` skips such names). Over all 26,503, the translator's own marker test (`WAVE64_RE`, or a 64-bit op on EXEC/VCC) on the code `translate()` keeps finds 21,554 wave64: 10,031 PS, 9,282 mesh shaders, 1,179 VS, 867 CS and 195 GS. With the 2,287 above that is exactly the flag's 23,841, and none contradicts it; read raw, 104 more wave32 listings (80 CS, 24 PS) seem to carry a marker, all from embedded data words decoded as instructions. The first marker scan (`s_mov_b64 exec, -1`, `exec_hi`, `s_and/or_saveexec_b64` and 64-bit masks, written into this row at `0082ad53`) counted 9,930 PS, 8,666 mesh shaders, 1,115 VS and 923 CS: 20,634 without the GS, so not the 21,545 total either. The translator maps a wave to a subgroup, and NVIDIA subgroups are 32 wide. What that means: (1) lane-independent code, which is most pixel-shader math, is exact; (2) wave-wide branch decisions and reductions are made per 32-lane half, which is exact unless scalar state computed for one half is later consumed by the other; (3) lane indices from `v_mbcnt_lo/hi` and wave IDs from the merged-wave SGPR must be 64-lane values. Mesh and compute shaders build thread IDs as wave_id·64 + mbcnt, so those need a mapping from `LocalInvocationIndex` (lane = index & 63, wave = index >> 6). Full fidelity needs either 64-wide subgroups (AMD GPUs, via `VK_EXT_subgroup_size_control` requiredSubgroupSize = 64) or emulating cross-half ops (ballot, readlane, shuffles across halves) through workgroup memory. | | Mesh shaders | NGG wave64 programs → `VK_EXT_mesh_shader` (`MeshEXT`). **PSV0** (DXBC) gives NumThreads (128×1×1 in the corpus), MaxOutputVertices/Primitives (128/128) and the topology (triangles). System inputs, from Mesa's RADV setup for mesh as NGG on GFX10.3: v5 = first launch vertex ID of the lane (the "vertex_id" slot), `linearGroupIndex * NumThreads + LocalInvocationIndex` with the linear index from WorkgroupId/NumWorkgroups; all 9,282/9,282 corpus mesh shaders read `v5` once with `v_readfirstlane_b32 sX, v5` and use `sX` only via `s_lshr_b32 D, sX, 7` to recover the group index (NumThreads is 128 in the corpus), matching TomBox's mesh ABI (`gid.x * numThreads + gi`) on 1D launches. GPU-checked with `runtime/test/shaders/ms_v5_workgroup.asm` (24/24 groups exact on RTX 4060 Ti and RTX 3080, and on an RTX 4050 Laptop and an AMD Radeon 740M (RADV)); still unverified on Xbox hardware: the low 7 bits of `v5` on lanes 1..127 and whether 3D `DispatchMesh` flattens XYZ or uses X only. The merged-wave-info SGPR (s3 in this ABI) = wave ID << 24, from LocalInvocationIndex >> 6; `v_mbcnt` lanes = LocalInvocationIndex & 63; user data in s16.. as usual. All 9,282 mesh-shader listings of 1.0.2.1 (names starting with `.` included) read exactly v5 before writing anything (`rdna2spirv.read_before_write_vgprs` over the code `translate()` keeps). An earlier sample of 1,500 put 27 aside as adding loop-carried registers; over the corpus no extra read is loop-carried. Read raw, 266 of the 309 listings with embedded data words seem to read more VGPRs, each after a branch (in 101 the register is written after the read); they come from data words decoded as instructions and are gone once the listing is re-anchored to the FSSM code and cut to reachable code, as `translate()` does. 1,473 of 1,500 sampled mesh shaders read exactly v5, and the rest only add loop-carried registers. Exports: on NGG, thread t exports vertex t (`pos0`, `paramN`) and primitive t (`prim`). They're staged per invocation; an all-`off` export is the dummy a wave with no vertices must issue, and writes nothing. `s_sendmsg GS_ALLOC_REQ` (m0 = prims << 12 \| verts, sent by thread 0) stores the counts in a workgroup variable. At shader end, in uniform control flow: workgroup barrier, `OpSetMeshOutputsEXT(min(verts, max), min(prims, max))`, then each thread writes its staged vertex (Position + Location N) and primitive (`PrimitiveTriangleIndicesEXT` = bits [8:0], [18:10], [28:20]; `CullPrimitiveEXT` = bit 31). `pos1..pos3` clip/cull distances are staged per invocation and emitted in a per-vertex `Block` output struct (`Position` + `ClipDistance`/`CullDistance` arrays, `VK_EXT_mesh_shader`) when used, keeping the standalone `%ms_out_pos` layout unchanged for shaders without `pos1+`. The distances are copied to that struct one float at a time, not as a whole array: SPIRV-Cross 1.4.363.0 turns a whole-array store into a mesh output into a C array assignment that Metal rejects (SHADER-155; `ms_clip` then compiles and draws its 2048/4096 pixels in a native Metal mesh draw on an Apple A18 Pro). `%ms_cull` (the `PerPrimitiveEXT` `CullPrimitiveEXT` `Block`) is listed before `%ms_out_vtx` in `OpEntryPoint MeshEXT`'s interface list: AMD's proprietary Windows Vulkan driver `24.10.24` (LLPC) was reported, on one Ryzen 5 7600 iGPU, to segfault (`0xC0000005`) during `vkCreateGraphicsPipelines` when the per-vertex clip/cull `Block` precedes the per-primitive `Block` (even on `glslangValidator` output), while driver `32.0.32029.2010` on an RX 9070 XT and an RX 7900 XT accepts either order; the order has no meaning in SPIR-V, so this one costs nothing on other drivers; reordering the interface list fixes `ms_clip` on AMD Ryzen 5 7600 RDNA2 iGPU (`2048/2048` clipped, `2048/2048` drawn, `4096/4096` culled when `CullPrimitiveEXT = true`, 0 validation errors) while keeping `CullPrimitiveEXT` in its `Block+bool` form for SPIRV-Tools ≤2025.1 (`SHADER-MS-CLIP-IFACE`). GPU-checked with `runtime/test/shaders/ms_tri.asm` (`VKH_MESH=1 vk_harness`), built from the game's own idioms (thread ID from s3 and mbcnt across two waves, thread-0 ALLOC_REQ, per-thread exports): 0 error on every pixel. `Layer` and `ViewportIndex` from the `pos1` misc vector (`z[10:0]`, `z[19:16]`) are per-primitive members of `%ms_cull` (`Gen.export_misc_pos1`): each lane stages the value it exports and writes it to the primitive with its own index. That is exact when the value is the same for all vertices of a primitive; whether the hardware takes it from the primitive's provoking vertex instead is not measured. Confirmed by the translator tests (`tests/test_translate.py`); none of the 1,906 mesh shaders of the corpus that export `pos1` writes either, so the game's mesh shaders only gain unused declarations. Compressed exports (`exp pos1` / `exp param` with `compr`) unpack their two f16 pairs the way the pixel-shader compressed export does (`Gen.export_comps`): LLVM lists each register twice (`v4, v4, v5, v5`), so the pair is operands 1 and 3, each unpacked with `UnpackHalf2x16` into (x, y) and (z, w), and an `off` register leaves its two components unwritten. Before, such an export was refused. Confirmed by the translator tests (`tests/test_translate.py`); none of the 9,282 mesh shaders of the corpus uses one, so the game's translation does not change. | | Mesh shaders as compute (`--mesh-compute`) | For devices without `VK_EXT_mesh_shader` (NVIDIA Pascal, for one), and on by itself in `make_game.py` on Intel's Windows Vulkan driver (`VK_DRIVER_ID_INTEL_PROPRIETARY_WINDOWS` with mesh shaders, `runtime_gpu_mesh_draws_crash`): there `vkCmdDrawMeshTasksEXT` crashes (0xC0000409 in `igvk64.dll`) for a mesh shader with a live push-constant load at byte 32 or later, which every corpus mesh shader has, while `--mesh-compute` is exact (BUILD-2202, Arc A770, driver 32.0.101.9175; no fixed version known; `--native-mesh` keeps native mesh shaders). Each mesh shader becomes a `GLCompute` module with the same workgroup size and code; only the epilogue changes. Instead of `OpSetMeshOutputsEXT` and the mesh outputs, after the same barrier lane 0 writes the vertex and primitive counts, lane i < vertex count writes its vertex and lane i < primitive count its primitive into this workgroup's **slot** of an output buffer: slot = linear workgroup index (x + y·nx + z·nx·ny) × `slot_bytes`, computed in 64 bits. The buffer's device address is in push-constant dwords 36–37, so these modules declare 152 bytes. Slot layout (`rdna2spirv.mesh_compute_layout`, recorded per shader as `mesh_compute` in the index), all 16-byte aligned: a header (vertex count, primitive count), then `max_vertices` vertices, each holding the position, the clip and then cull distances padded to whole vec4s, and one vec4 per param location; then `max_primitives` primitives of three vertex indices plus 1 if culled. The modules need no mesh capability, extension or `shaderClipDistance`. `tools/mesh_compute_vs.py` writes the vertex shader that draws the slots with a non-indexed `vkCmdDraw(groups × max_primitives × 3)`: vertex v is workgroup v / (3·max_primitives), primitive (v / 3) mod max_primitives, corner v mod 3. A primitive past the count, or one culled, gets one position outside the clip volume at all three corners and is clipped. Otherwise the corner's index, clamped to `max_vertices` − 1, selects the vertex, and its position, distances and params go out at the mesh shader's locations, so the pixel shader is unchanged. One draw rasterizes in vertex order, which is workgroup then primitive order, as with mesh workgroups. Corpus: all 9,282 mesh shaders are 128×1×1 with 128/128 outputs, wave64, 0–18 params, clip distances in 1,906, cull distances and per-primitive attributes in none, no task shaders. On a 32-wide device combine it with `--wave64-emulate`. GPU-checked on an NVIDIA GeForce GTX 1060 6GB (Pascal: no mesh shaders; driver 560.94, Windows 10) with `LEONIDA_MESH_COMPUTE=1 LEONIDA_W64_EMULATE=1`: `ms_tri`, `ms_w64x_ballot` and `ms_wave_info_s3` 4096/4096 pixels exact, `ms_clip` 2048/4096 covered as expected, `ms_v5_workgroup` 24/24 workgroup coordinates, zero Khronos validation messages. Checked in `tests/test_mesh_compute.py`. The runtime side, turning a `DispatchMesh` into that dispatch, a barrier and the draw, is the follow-up (it needs the graphics pipelines of #291). Unused primitives still run the vertex shader; compaction with an indirect draw would avoid that. | -| Mesh shaders with their waves in series (`--mesh-serial-waves`) | With `--wave64-emulate`, a mesh shader of more than 64 threads is several waves side by side in one workgroup, and what its waves do not do alike (a region one wave enters and the other skips, with votes or memory accesses inside) goes to mini-schedulers: a round loop over a `%pc` switch. With this flag a mesh shader whose thread count is a multiple of 64 and whose waves cannot pass each other anything (no `ds_` instruction, no store or atomic to memory, not `--mesh-compute`) declares `LocalSize 64` and runs one pass per wave instead (`ms_serial_passes`, `ms_serial_epilogue`). `%local_index` becomes a Function variable, the built-in (`%real_local_index`) plus 64 x pass, so the launch state (v5, the wave id in s3) and every lane computation see the wave of the pass; every initialised Function variable is stored again at the start of a pass; what a pass exported is copied to per-pass twins of the export variables; after the loop the epilogue does its barrier, reads the counts and calls `OpSetMeshOutputsEXT` once, then writes each pass's vertices and primitives at index built-in + 64 x pass. Each pass is one wave, so the plan is the single-wave one (`inline_all` when the program has branches) and the exchange buffer is one wave's, addressed by the invocation's own index. Why the order of the waves is not observable: the waves of such a program share nothing but the allocation request and the exports, which the epilogue orders itself (the request may come from any wave: the counts are read after all passes). A program that shares LDS (`ms_wave_info_s3`) or writes memory keeps the side-by-side form, as does everything without the flag: off by default, and with it off the output is unchanged. Measured on an RTX 4080 (NVIDIA 621.24, 32-wide subgroups): the `ms_*` GPU tests pass in both forms, among them `ms_w64x_wave_votes`, whose two waves take different branches with their own ballots and whose triangle takes vertices from both; module shape by `tests/test_mesh_serial_waves.py`. Not measured: other vendors, llvmpipe, a thread count that is not a multiple of 64 (kept side by side). | +| Mesh shaders with their waves in series (`--mesh-serial-waves`) | With `--wave64-emulate`, a mesh shader of more than 64 threads is several waves side by side in one workgroup, and what its waves do not do alike (a region one wave enters and the other skips, with votes or memory accesses inside) goes to mini-schedulers: a round loop over a `%pc` switch. With this flag a mesh shader whose thread count is a multiple of 64 and whose waves cannot pass each other anything (no `ds_` instruction, no store or atomic to memory) declares `LocalSize 64` and runs one pass per wave instead (`ms_serial_passes`, `ms_serial_epilogue`). `%local_index` becomes a Function variable, the built-in (`%real_local_index`) plus 64 x pass, so the launch state (v5, the wave id in s3) and every lane computation see the wave of the pass; every initialised Function variable is stored again at the start of a pass; what a pass exported is copied to per-pass twins of the export variables; after the loop the epilogue does its barrier, reads the counts and calls `OpSetMeshOutputsEXT` once, then writes each pass's vertices and primitives at index built-in + 64 x pass. Under `--mesh-compute` (devices without `VK_EXT_mesh_shader`, such as NVIDIA Pascal) the compute program does the same, and its slot writes (`mesh_compute_epilogue`) are repeated per pass the same way: the header from index 0, which only pass 0's lane 0 has, each pass's vertices and primitives at built-in + 64 x pass; the metadata keeps the program's thread count in `local_size` (the runtime only checks it for whole subgroups and the invocation limit, which 64 passes as well). Each pass is one wave, so the plan is the single-wave one (`inline_all` when the program has branches) and the exchange buffer is one wave's, addressed by the invocation's own index. Why the order of the waves is not observable: the waves of such a program share nothing but the allocation request and the exports, which the epilogue orders itself (the request may come from any wave: the counts are read after all passes). A program that shares LDS (`ms_wave_info_s3`) or writes memory keeps the side-by-side form, as does everything without the flag: off by default, and with it off the output is unchanged. Measured on an RTX 4080 (NVIDIA 621.24, 32-wide subgroups): the `ms_*` GPU tests pass in both forms, among them `ms_w64x_wave_votes`, whose two waves take different branches with their own ballots and whose triangle takes vertices from both; module shape by `tests/test_mesh_serial_waves.py`. Not measured: other vendors, llvmpipe, a thread count that is not a multiple of 64 (kept side by side). | | Mesh primitive export and allocation (`exp prim`, `MSG_GS_ALLOC_REQ`) | The GFX10 NGG formats, from Mesa 22.3 `src/amd/llvm/ac_llvm_build.c`: `ac_build_sendmsg_gs_alloc_req` (lines 4475–4477) puts `prim_cnt << 12 \| vtx_cnt` in m0, and `ac_pack_prim_export` (lines 4518–4539) packs index 0, 1 and 2 in bits 0–8, 10–18 and 20–28, the edge flags in bits 9, 19 and 29 and "null primitive (skip)" in bit 31. Thread t exports vertex t and primitive t, only below the vertex and primitive counts (`src/amd/common/ac_nir_lower_ngg.c`, `emit_ms_finale`, lines 4056–4067). Translated: the counts from m0 (each clamped to PSV0's maximum) go to `OpSetMeshOutputsEXT` or the `--mesh-compute` header; `PrimitiveTriangleIndicesEXT` takes the three 9-bit fields without the edge flags, and `CullPrimitiveEXT` (or the slot's culled word) is bit 31; invocations at or past a count write nothing. **Indices stay below the vertex count**: every `exp prim` in the corpus comes from an epilogue that compares each 10-bit field with the vertex count and, when one is at or past it, sets bit 31 and keeps the fields (count over the 1.0.2.1 corpus: all 8,666 listings with `exp prim`), so a null primitive can carry indices up to 511. The hardware skips it, but `VK_EXT_mesh_shader` leaves an index at or past the vertex count undefined even on a culled primitive. The translator writes index k as `null ? 0 : umin(field_k, vertex count - 1)`, as Mesa's mesh lowering clamps them (`ac_nir_lower_ngg.c` line 4112), and a primitive count of 0 when the vertex count is 0 (so `vertex count - 1` never wraps); `CullPrimitiveEXT` is unchanged. Until 2026-11-26 the raw fields were written, a suspected cause of device losses in mesh draws on NVIDIA (not confirmed). Executed for both paths in `tests/semantic/test_ms_prim_export.py` (72 threads in two wave64 waves: odd threads set the edge flags, threads with t & 2 the null bit; and `fixtures/ms_prim_null_clamp.asm`, 128 threads at vertex counts 0, 10, 100 and 128, whose null primitives carry fields 300, 511, 0x3FF and the vertex count itself: its assertions fail on the old translator); `spirv-val` accepts both modules, plain and `--wave64-emulate`. **Not GPU-checked.** | | Geometry shaders | On output stream zero, `GS_OP_EMIT_CUT` emits the staged vertex and ends its strip under the same EXEC guard. The synthetic `gs_emit_cut.asm` checks that six vertices form two separate triangles. [RDNA 2 ISA, S_SENDMSG](https://docs.amd.com/api/khub/documents/Et~wpu9g~Ffl7d9q0QZ~Og/content). All 195 are `$GS_VoxelizeGeneric` permutations: legacy (merged ES/GS) wave32 programs on LDS rings, with no `exp`. All 195 are `$GS_VoxelizeGeneric` permutations: legacy (merged ES/GS) programs on LDS rings, with no `exp`, written for wave64 (the FSSM header's wave-size flag says wave64 in 195 of 195, see *Wave size*, and the translator's index marks all 195 `wave64` with `subgroup_size` 64 at `f847748c`; the code agrees: the EXEC prologue that `gs_tri.asm` mirrors compares the thread count with 64 and writes a 64-bit EXEC, the count in #94 finds `v_mbcnt_hi_u32_b32` in all 195, and the translator marks all 195 `wave64`; an earlier version of this row said wave32, TEST-251). Inputs: vertex i sits at the dword offset in v0 lo / v0 hi / v1 lo; an LDS read at vertex base + 4·(4·reg + comp) is input-signature register reg, component comp (checked: SV_Position xyz in dwords 0–2 and TEXCOORD0.xy in 4–5, as ISG1 declares). Outputs: emitted vertex k is dwords [k·4·nreg, (k+1)·4·nreg) of the lane's GSVS area, dword = 4·reg + comp of the output signature (20 dwords = 5 OSG1 registers; every write matches a declared mask). Translation: synthetic offsets (vertex i at dword 64·i), LDS reads → `gl_in[i]` inputs, LDS writes → staged slots, `MSG_GS EMIT` → copy slot (emit count) to the outputs + `OpEmitVertex`, `CUT` → `OpEndPrimitive`, `GS_DONE` → nothing. The prologue's `s_bfm_b64`/`s_cselect` EXEC setup is fed s3 = 64 << 8. GPU-checked with `runtime/test/shaders/gs_tri.asm` (`VKH_GS=… vk_harness`): 0 error. Without a geometry stage (Apple GPUs: Metal, MoltenVK), `tools/spirv_gs_to_compute.py` lowers the translated module to a compute capture pass, one invocation per input primitive: inputs come from a buffer, each `OpEmitVertex` guards its record/meta stores and `%gsc_n` increment on `n < OutputVertices` (dropping excess vertices rather than overflowing into the next primitive's slots, and updating `OpPhi` predecessors across split blocks, and rejecting (`Unsupported`) an `OpEmitVertex` in a loop header before its `OpLoopMerge`, which the split would move; SHADER-617, checked on the CPU by `tests/test_spirv_gs_to_compute_bounds.py`), and a meta buffer holds each primitive's vertex count (`<= OutputVertices`) and strip ends, for an ordinary draw afterwards (SHADER-159). Metal, MoltenVK), `tools/spirv_gs_to_compute.py` lowers the translated module to a compute capture pass, one invocation per input primitive: inputs come from a buffer, each `OpEmitVertex` writes the outputs to a record buffer, and a meta buffer holds each primitive's vertex count and strip ends, for an ordinary draw afterwards (SHADER-159). `gs_tri` lowered this way, converted with SPIRV-Cross and run natively on an Apple A18 Pro: 195/195 records exact for 65 random triangles, and the captured fullscreen triangle drawn from the records matches all 4096 gradient pixels. Not done: wiring it into a draw path, and GS that use cross-lane operations or more than one invocation. | | Integer clamp | The VOP3 `clamp` bit on `v_add_nc_u32`, `v_sub_nc_u32`, `v_subrev_nc_u32` saturates the result to [0, 0xFFFFFFFF], and on `v_add_nc_i32`/`v_sub_nc_i32` to [0x80000000, 0x7FFFFFFF]; without it they wrap. GFX9+ semantics: LLVM selects `uaddsat`/`usubsat` and `saddsat`/`ssubsat` to exactly these ops with clamp set. **Until this change clamp was silently ignored on the unsigned ops** (and the signed ones were `Unsupported`). Checked on the CPU by `tests/semantic/test_alu_add_nc_clamp.py`. The carry-out unsigned ops (`v_add_co_u32`, `v_sub_co_u32`, `v_subrev_co_u32`, `v_add_co_ci_u32`, `v_sub_co_ci_u32`, `v_subrev_co_ci_u32`) with VOP3 `clamp` likewise saturate D to `0xFFFFFFFF` on add carry or `0` on sub borrow while still reporting the real carry/borrow bit in `sdst` (**until 2026-11-22 the translator ignored `clamp` on all six**); confirmed natively on RDNA2 (AMD Radeon 680M `gfx1035` wave32 & wave64 via `tools/hw_oracle`, and independently on `gfx1036` in #1746) and CPU-checked by `tests/semantic/test_alu_add_co_clamp.py`. The 16-bit unsigned add/sub (`v_add_nc_u16`, `v_sub_nc_u16`, and the `v_add_u16`/`v_sub_u16`/`v_subrev_u16` `_e64` names) saturate to [0, 0xFFFF] with `clamp` (llvm-mc 21 gfx1030 encodes the bit on them, and LLVM selects i16 `uaddsat`/`usubsat` to them); **until 2026-11-22 the translator wrapped instead**. `clamp` on any other 16-bit integer op raises `Unsupported`. CPU-checked by `tests/semantic/test_alu_u16_clamp.py` (the high half of the destination is kept), **not GPU-verified**. CPU-checked by `tests/semantic/test_alu_u16_clamp.py` (the high half of the destination is kept), and **Hardware-verified on RDNA2** (AMD Radeon 680M, `gfx1035`, Windows 11, driver `26.5.1`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137): all 32-bit and 16-bit `*_nc_*` `clamp` cases (including `op_sel` and kept destination half on u16) match hardware bit-for-bit. **Open divergence measured on the same hardware:** `v_add_co_u32`, `v_sub_co_u32`, `v_subrev_co_u32`, `v_add_co_ci_u32`, `v_sub_co_ci_u32` and `v_subrev_co_ci_u32` with `clamp` saturate D (`0xFFFFFFFF` / `0`) while still reporting the real carry/borrow in `sdst`, whereas the translator currently ignores `clamp` on these carry-out ops. | diff --git a/docs/testing.md b/docs/testing.md index 62f5ced44a..2bdeb3acd8 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -580,6 +580,7 @@ constants, so those tests skip. shaders with `--mesh-serial-waves` (`docs/design.md`, "Mesh shaders with their waves in series"): the ones that qualify run one pass per wave in 64 invocations. The `ms_*` tests must pass with and without it; `ms_w64x_wave_votes` is the one whose two waves take different branches and both give the triangle a vertex. `ms_w64x_wave_loops` is the one whose two waves run a loop of different length (5 and 9 iterations), each iteration reading a wave-wide count, so under emulation the waves reach different numbers of barriers. +With `LEONIDA_MESH_COMPUTE=1` as well (below), the same tests run the passes in the `--mesh-compute` form. ## GPUs without mesh shaders (NVIDIA Pascal and older) diff --git a/tests/test_mesh_serial_waves.py b/tests/test_mesh_serial_waves.py index 071599d23b..f4d7d73fc3 100644 --- a/tests/test_mesh_serial_waves.py +++ b/tests/test_mesh_serial_waves.py @@ -11,8 +11,11 @@ the mesh outputs once; it passes spirv-val; the metadata records the number of passes and keeps the program's thread count; * the exchange takes its place in %x_buf from the invocation's own index, not from the lane it runs; +* under --mesh-compute (devices without VK_EXT_mesh_shader, such as NVIDIA Pascal) the compute program does the + same, and writes its slot once per pass: the header from lane 0 of pass 0 only, each pass's vertices and + primitives at the real index + 64 * pass; * ms_wave_info_s3, whose waves count lanes in LDS, keeps the side-by-side form, and so does every program - without --wave64-emulate, under --mesh-compute or of at most 64 threads; + without --wave64-emulate or of at most 64 threads; * without the flag the module is unchanged. """ import os @@ -92,13 +95,56 @@ def test_program_that_does_not_qualify_is_unchanged(make_shader, name): @requires_tools -@pytest.mark.parametrize("emulate,compute", [(False, False), (True, True)], ids=["native", "mesh-compute"]) -def test_flag_needs_emulation_and_the_mesh_path(make_shader, emulate, compute): - _, plain, _ = _translate(make_shader, "ms_tri", False, emulate, compute) - _, flagged, meta = _translate(make_shader, "ms_tri", True, emulate, compute) +@pytest.mark.parametrize("compute", [False, True], ids=["mesh", "mesh-compute"]) +def test_flag_needs_emulation(make_shader, compute): + _, plain, _ = _translate(make_shader, "ms_tri", False, False, compute) + _, flagged, meta = _translate(make_shader, "ms_tri", True, False, compute) assert flagged == plain and "mesh_serial_waves" not in meta +@requires_tools +@pytest.mark.parametrize("name", SERIAL) +def test_serial_mesh_compute_module(make_shader, name): + shader, spvasm, meta = _translate(make_shader, name, True, compute=True) + shader.validate(spvasm) + assert "OpEntryPoint GLCompute %main" in spvasm and "OpSetMeshOutputsEXT" not in spvasm + assert "OpExecutionMode %main LocalSize 64 1 1" in spvasm + assert meta["mesh_serial_waves"] == 2 and meta["local_size"] == [128, 1, 1] and "mesh_compute" in meta + if name == "ms_w64x_wave_votes": # one wave per pass: the inline plan, no scheduler + assert "OpSwitch" not in spvasm + assert spvasm.count("OpLoopMerge %msw_exit %msw_cont None") == 1 + assert "OpDecorate %real_local_index BuiltIn LocalInvocationIndex" in spvasm + assert "%x_li = OpLoad %uint %real_local_index" in spvasm + main = spvasm[spvasm.index("%main = OpFunction"):] + loop_end = main.index("%msw_exit = OpLabel") + # One barrier and one read of the counts, after the passes; then the slot writes of each pass from its copies. + assert main.count("%msc = OpLoad %uint %ms_counts") == 1 and loop_end < main.index("%msc = OpLoad") + for w in (0, 1): + assert f"OpCopyMemory %ms_pos__w{w} %ms_pos" in main + assert re.search(rf"%mli_w{w} = OpIAdd %uint %msw_erl %\w+", main) + assert f"OpLoad %v4float %ms_pos__w{w}" in main[loop_end:] + # The header goes to lane 0 of the slot: pass w's lane 0 is index 64 * w, so only pass 0 writes it. + assert re.search(rf"%mh0_w{w} = OpIEqual %bool %mli_w{w} %c0\b", main) + assert "OpLoad %v4float %ms_pos\n" not in main[loop_end:] # no write from the last pass's own variables + offset = re.search(r"%mli_w1 = OpIAdd %uint %msw_erl (%\w+)", main).group(1) + assert re.search(rf"^\s*{re.escape(offset)} = OpConstant %uint 64$", spvasm, re.M) + # As many slot stores per pass as the module without passes has in all. + _, plain, _ = _translate(make_shader, name, False, compute=True) + plain_main = plain[plain.index("%main = OpFunction"):] + stores = len(re.findall(r"%mp\d+ = OpConvertUToPtr %_ptr_PSB_uint", plain_main)) # the slot's + assert stores + for w in (0, 1): + assert len(re.findall(rf"%mp\d+_w{w} = OpConvertUToPtr %_ptr_PSB_uint", main)) == stores + + +@requires_tools +@pytest.mark.parametrize("name", SIDE_BY_SIDE) +def test_mesh_compute_program_that_does_not_qualify_is_unchanged(make_shader, name): + _, plain, plain_meta = _translate(make_shader, name, False, compute=True) + _, flagged, meta = _translate(make_shader, name, True, compute=True) + assert flagged == plain and meta == plain_meta and "%msw_" not in flagged + + @requires_tools @pytest.mark.parametrize("name", SERIAL) def test_without_the_flag_the_waves_are_side_by_side(make_shader, name): diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index d8e6a00bf6..1f431cc8c5 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -16056,7 +16056,8 @@ def ms_prim_count(c, maxp): def mesh_compute_epilogue(gen): - """--mesh-compute: the mesh epilogue as buffer stores. Same barrier and counts as the mesh path; then lane 0 + """--mesh-compute: the mesh epilogue as buffer stores, as lines (assemble indents them; ms_serial_epilogue + repeats the writes per pass). Same barrier and counts as the mesh path; then lane 0 writes the header, lane i < vertex count its vertex and lane i < primitive count its primitive, at the offsets of gen.msc_layout in this workgroup's slot (linear workgroup index x + y*nx + z*nx*ny).""" c, lay = gen.cu, gen.msc_layout @@ -16150,7 +16151,7 @@ def store_floats(base, values): for i, w in enumerate(("%mi0", "%mi1", "%mi2", "%mnb")): store(at("%mpb", 4 * i), w) L += ["OpBranch %msc_pend", "%msc_pend = OpLabel"] - return "".join((" " + l if " = OpLabel" not in l else l) + "\n" for l in L) + return L def float_literal(bits): @@ -16232,8 +16233,8 @@ def ms_serial_passes(gen, fn, lists): def ms_serial_epilogue(gen, lines, exports): """--mesh-serial-waves: the mesh epilogue for passes. `lines` is the epilogue of one invocation: the barrier, - the counts and OpSetMeshOutputsEXT, then (from the load of `%local_index` on) the writes of what the invocation - exported. The first part stays as it is, once; the writes are repeated per pass w with the pass's twins of the + the counts and OpSetMeshOutputsEXT (or, with --mesh-compute, mesh_compute_epilogue's barrier and counts), then + (from the load of `%local_index` on) the writes of what the invocation exported. The first part stays as it is, once; the writes are repeated per pass w with the pass's twins of the export variables and the output index real index + 64 * w, every id of the block renamed per pass.""" cut = lines.index("%mli = OpLoad %uint %local_index") once, writes = lines[:cut], lines[cut + 1:] @@ -16266,6 +16267,7 @@ def assemble(gen): gen.msc_layout = mesh_compute_layout(gen.ms["maxv"], gen.ms["maxp"], gen.clip_count if gen.uses_clip else 0, gen.cull_count if gen.uses_cull else 0, gen.ms_params) # Built here, before any constant is emitted, so every constant it asks for gets declared. + # --mesh-serial-waves: the constants of each pass's output index too (_translate asked for them). gen.msc_epilogue = mesh_compute_epilogue(gen) # --pc-tail-ubo: the uniform block exists only when the shader reads the tail (after the epilogue, which reads it). gen.uses_pc_tail = PC_TAIL_UBO and (gen.uses_heap or gen.uses_codebase or msc) @@ -16439,7 +16441,7 @@ def assemble(gen): hdr += ["OpExecutionMode %main Triangles", "OpExecutionMode %main Invocations 1", "OpExecutionMode %main OutputTriangleStrip", f"OpExecutionMode %main OutputVertices {gen.gs['maxv']}"] if msc: - hdr.append("OpExecutionMode %main LocalSize {} {} {}".format(*gen.ms["size"])) + hdr.append("OpExecutionMode %main LocalSize {} {} {}".format(*((64, 1, 1) if gen.ms_serial else gen.ms["size"]))) elif ms: hdr += ["OpExecutionMode %main LocalSize {} {} {}".format(*((64, 1, 1) if gen.ms_serial else gen.ms["size"])), f"OpExecutionMode %main OutputVertices {gen.ms['maxv']}", @@ -17230,12 +17232,15 @@ def label(prefix): if pops: fn.append("OpBeginInvocationInterlockEXT") # end of the entry block: uniform, executed once serial_close, serial_exports = [], [] - if ms and not msc and gen.ms_serial: + if ms and gen.ms_serial: fn, serial_close, serial_exports = ms_serial_passes(gen, fn, (hdr, dec, gvars)) out = hdr + dec + types + gvars + helpers + fn end_lock = " OpEndInvocationInterlockEXT\n" if pops else "" if msc: - end_lock = gen.msc_epilogue + end_lock + # The slot writes of one invocation; with passes, once per pass from its twins (ms_serial_epilogue). Lane 0 + # of pass 0 is then the only one that writes the header: a later pass's index starts at 64. + L = ms_serial_epilogue(gen, gen.msc_epilogue, serial_exports) if gen.ms_serial else gen.msc_epilogue + end_lock = "".join((" " + l if " = OpLabel" not in l else l) + "\n" for l in L) + end_lock elif ms: # All invocations reach the end: wait for the ALLOC_REQ write, declare the counts once (uniform), then each # thread writes the vertex and primitive it exported (index = LocalInvocationIndex). @@ -18926,7 +18931,7 @@ def _translate(path): size = (g.cs or g.ms)["size"] g.x_lanes = -(-size[0] * size[1] * size[2] // 64) * 64 threads = size[0] * size[1] * size[2] - if (MESH_SERIAL_WAVES and stage == "ms" and not MESH_COMPUTE and threads > 64 and threads % 64 == 0 + if (MESH_SERIAL_WAVES and stage == "ms" and threads > 64 and threads % 64 == 0 and not any(i["op"].startswith("ds_") or "store" in i["op"] or "atomic" in i["op"] for i in insns)): # The waves of such a program cannot pass each other anything: no LDS, and no store or atomic to # memory another wave could read (ms_wave_info_s3 counts lanes in LDS across an s_barrier and keeps