From 49dd92d41d9b68845e700fcd750b87e9f276012a Mon Sep 17 00:00:00 2001 From: shelbykb2 <80599220+shelbykb2@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:00:09 -0700 Subject: translator: SMEM loads with soffset and imm add both (the imm was dropped) What was wrong An RDNA2 SMEM load can carry a register offset and an immediate at once. llvm-mc prints that form as "s_buffer_load_dword s12, s[24:27], s40 offset:0x4". shader_ir.parse_line puts "offset:0x4" in mods, and Gen.scalar_load only read the third operand, so the immediate was dropped without a diagnostic: the line translated to the same SPIR-V with and without the modifier, and spirv-val accepted both. Evidence Measured on an AMD Radeon RX 6800 (gfx1030) by running the instructions as a raw compute kernel: for s_buffer_load_dword/x2/x4/x8 the address is base + soffset + imm + 4*i, e.g. soffset 8 + imm 4 reads the dword at +12. s_load_dword* with both offsets was not measured; it shares the SMEM encoding (soffset_en + imm), so giving it the same rule is an inference. Change - scalar_load adds the immediate when the third operand is a register and mods has offset:N. The no-modifier forms emit the same code as before. - Forms llvm-mc does not accept (immediate operand plus offset:, two offset: modifiers, a fourth operand, an unparseable offset) raise Unsupported. - Not changed, and listed in docs/design.md as known differences: the hardware truncates base, soffset and imm each to a multiple of 4 and s_buffer_load returns 0 past NUM_RECORDS; the translator does neither. A negative s_load immediate is still zero-extended from 32 bits, in both forms (not measured). Tests - tests/semantic/test_scalar_mem_smem.py: SmemSoffsetImmTranslatorTests runs the code scalar_load emits against concrete SGPRs and memory and asserts the addresses and values read (9 tests; 7 fail on main, where the loads read +8 instead of +12, and the imm-only / soffset-only regression cases pass). - runtime/test/shaders/cs_smem_soffset_imm.asm, wired into check.py and scripts/run_gpu_tests.py. Not run on a GPU in this change. - unittest discover -s tests/semantic: 335 -> 344, all pass. - pytest tests (--capture=sys, llvm-mc through WSL): 883 -> 893 passed, the same 6 test_rtti_scan failures before and after (pefile not installed). - The 27 hand-written GPU shaders: 27 translated, 27 pass spirv-val before and after, output byte-identical. AI-assisted. Co-Authored-By: Claude Fable 5.2 --- scripts/run_gpu_tests.py | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) (limited to 'scripts/run_gpu_tests.py') diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index 02d4b86ce..34f3981c5 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py @@ -414,9 +414,13 @@ def run_suite(a, work: str) -> int: results.append((name, False, "64-wide subgroup was not confirmed (rebuild vk_compute_test)")) else: results.append((name, rc == 0, msg.splitlines()[-1] if msg else "")) - elif name in ("cs_store", "cs_wave64_ballot", "cs_wm_half_ops", "cs_wm_half_cmp", "cs_wm_bfm64", "cs_wm_scc_rfl"): + elif name in ("cs_store", "cs_smem_soffset_imm", "cs_wave64_ballot", "cs_wm_half_ops", "cs_wm_half_cmp", + "cs_wm_bfm64", "cs_wm_scc_rfl"): cs_dump_wants = { "cs_store": [0x400080FF, 0xE00003FF, 0x3C004000, 0xEEEEEEEE, 0x40003C00, 0xBC003800], + # base + soffset + imm (cs_smem_soffset_imm.asm); out[4..7] are seeds the shader leaves alone + "cs_smem_soffset_imm": [0x5EED0024, 0x5EED0028, 0x5EED002C, 0x5EED0030, + 0x5EED0010, 0x5EED0014, 0x5EED0018, 0x5EED001C], "cs_wave64_ballot": [32, 16, 24, 40, 8, 48], "cs_wm_half_ops": [32, 16, 16, 0, 16], "cs_wm_half_cmp": [1, 0, 1, 1], @@ -424,9 +428,10 @@ def run_suite(a, work: str) -> int: "cs_wm_scc_rfl": [55, 48], } want = cs_dump_wants[name] - # Every dump but cs_store is a whole-wave (wave64) mask test: ask for a 64-wide subgroup and skip, as - # check.py does, where the device has none (vk_compute_test exits 77) instead of reporting a failure. - wave64 = name != "cs_store" + # Every dump but cs_store and cs_smem_soffset_imm is a whole-wave (wave64) mask test: ask for a + # 64-wide subgroup and skip, as check.py does, where the device has none (vk_compute_test exits 77) + # instead of reporting a failure. + wave64 = name not in ("cs_store", "cs_smem_soffset_imm") rc, msg = run_cmd([vk_compute, spv, "1", "dump"] + (["--require-wave64"] if wave64 else []), env=cs_env) dump_line = next((ln for ln in msg.splitlines() if "out[0..7] =" in ln), "") if wave64 and rc == 77: @@ -434,7 +439,7 @@ def run_suite(a, work: str) -> int: elif rc == 0 and dump_line: vals = [int(x) for x in dump_line.split("=")[1].split()[:len(want)]] ok = vals == want - fmt = hex if name == "cs_store" else str + fmt = hex if name in ("cs_store", "cs_smem_soffset_imm") else str results.append((name, ok, " ".join(fmt(x) for x in vals))) else: results.append((name, False, msg)) -- cgit v1.2.3 From 66a410edf0c4d387ef5414efc10e684c5687e45b Mon Sep 17 00:00:00 2001 From: Mokbul Miah <12134052+mokkymiah@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:56:01 +0000 Subject: Accept LLVM_MC as a whole command in the tests and GPU tools LLVM_MC may be one executable or a command line such as the WSL llvm-mc documented for Windows. shader_disasm.py already split it, but the tests, runtime/test/shaders/build.py and scripts/run_gpu_tests.py treated it as a single executable, so the documented setup skipped translator tests, and build.py passed a Windows path to WSL. Share the splitter in tools/mc_command.py and feed assembly on stdin. --- docs/design.md | 4 +++ make_game.py | 2 +- runtime/test/shaders/build.py | 21 ++++++++++----- scripts/run_gpu_tests.py | 11 +++++--- tests/conftest.py | 15 ++++++----- tests/test_mc_command.py | 61 +++++++++++++++++++++++++++++++++++++++++++ tools/mc_command.py | 29 ++++++++++++++++++++ tools/shader_disasm.py | 20 +++----------- 8 files changed, 129 insertions(+), 34 deletions(-) create mode 100644 tests/test_mc_command.py create mode 100644 tools/mc_command.py (limited to 'scripts/run_gpu_tests.py') diff --git a/docs/design.md b/docs/design.md index 9c2c3a389..596978356 100644 --- a/docs/design.md +++ b/docs/design.md @@ -277,6 +277,10 @@ set LLVM_MC=wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc python -I make_game.py --game "D:\path\to\your\package" --stages shaders ``` +The same form works in every tool that reads `LLVM_MC`. `tools/mc_command.py` splits it for `shader_disasm.py`, +the tests, `runtime/test/shaders/build.py` and `scripts/run_gpu_tests.py`; the assembler callers pass the assembly +on stdin, so a WSL command never receives a Windows file path. + `shader_disasm.py` disassembles one `s_endpgm` before starting, so a missing tool or AMDGPU target stops the run with that reason instead of writing empty `.s` files. To disassemble by hand inside WSL: diff --git a/make_game.py b/make_game.py index 3965439e5..a6f72d706 100644 --- a/make_game.py +++ b/make_game.py @@ -302,7 +302,7 @@ def shaders(game: str, work: str, jobs: int) -> None: shutil.rmtree(spirv, ignore_errors=True) if not os.path.isfile(disassembled): need(os.environ.get("LLVM_MC", "llvm-mc"), - "Install LLVM 21 or newer with the AMDGPU target, or set LLVM_MC to llvm-mc's full path.") + "Install LLVM 21 or newer with the AMDGPU target, or set LLVM_MC to llvm-mc's path or whole command.") log("shaders: disassembling (gfx1013)") drop(translated) py("shader_disasm.py", os.path.join(dxbc, "fssm"), "--out", disasm, "--mcpu", "gfx1013", "--jobs", jobs) diff --git a/runtime/test/shaders/build.py b/runtime/test/shaders/build.py index 1cc450310..2ae5cffa6 100644 --- a/runtime/test/shaders/build.py +++ b/runtime/test/shaders/build.py @@ -3,8 +3,9 @@ python3 -I runtime/test/shaders/build.py [name ...] Each .asm is RDNA2 assembly. It is assembled with llvm-mc (LLVM 21+ with the AMDGPU target; set LLVM_MC to its -path, as for the shaders stage). Listings, synthetic FSSM headers and DXBC containers are staged in a temporary -directory. After validation, the build writes /spirv/.spv and the translator metadata. +path or to a whole command, as for the shaders stage). Listings, synthetic FSSM headers and DXBC containers are +staged in a temporary directory. After validation, the build writes /spirv/.spv and the translator +metadata. Compute shaders get the header the tests were written for: RSRC2 0x8088 (4 user SGPRs holding the V#, the workgroup id in s4, 512 bytes of LDS) and a 64x1x1 group (a "; group: X,Y,Z" comment at the top of the .asm @@ -22,8 +23,12 @@ import tempfile from pathlib import Path HERE = os.path.dirname(os.path.abspath(__file__)) -TRANSLATOR = os.path.join(HERE, "..", "..", "..", "tools", "rdna2spirv.py") -LLVM_MC = os.environ.get("LLVM_MC", "llvm-mc") +TOOLS = os.path.join(HERE, "..", "..", "..", "tools") +TRANSLATOR = os.path.join(TOOLS, "rdna2spirv.py") +sys.path.insert(0, TOOLS) +import mc_command # noqa: E402 + +MC = mc_command.mc_command() RSRC2, GROUP = 0x8088, (64, 1, 1) @@ -60,12 +65,14 @@ def translate_tests(work, names): fssm.mkdir() for n in names: asm_path = os.path.join(HERE, n + ".asm") + raw = Path(asm_path).read_text(encoding="utf-8") mattr = asm_mattr(asm_path) - cmd = [LLVM_MC, "-triple=amdgcn--amdpal", "-mcpu=gfx1013"] + cmd = MC + ["-triple=amdgcn--amdpal", "-mcpu=gfx1013"] if mattr: cmd.append(f"-mattr={mattr}") - cmd += ["-show-encoding", asm_path] - r = subprocess.run(cmd, capture_output=True, text=True) + cmd.append("-show-encoding") + # Feed the text on stdin: an LLVM_MC command that runs in WSL cannot open a Windows path argument. + r = subprocess.run(cmd, input=raw, capture_output=True, text=True) if r.returncode or "error:" in r.stderr: sys.exit(f"{n}.asm did not assemble:\n{r.stderr}") # rdna2spirv.py rejects assembler directives such as the "\t.text" llvm-mc prints first. diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index d6afae39b..d73b75e0d 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py @@ -1,7 +1,9 @@ """Assemble, translate, and run the synthetic RDNA2->SPIR-V GPU test suite on Vulkan. Usage: - python -I scripts/run_gpu_tests.py [--llvm-mc PATH] [--build DIR] [--work DIR] [--filter SUBSTR] + python -I scripts/run_gpu_tests.py [--llvm-mc CMD] [--build DIR] [--work DIR] [--filter SUBSTR] + +--llvm-mc (or LLVM_MC) is a path or a whole command, e.g. "wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc". """ import argparse import json @@ -16,6 +18,8 @@ import tempfile ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SHADER_DIR = os.path.join(ROOT, "runtime", "test", "shaders") TRANSLATOR = os.path.join(ROOT, "tools", "rdna2spirv.py") +sys.path.insert(0, os.path.join(ROOT, "tools")) +import mc_command # noqa: E402 def make_dxbc(chunks: list[tuple[bytes, bytes]]) -> bytes: @@ -80,7 +84,7 @@ def asm_group(asm_path: str) -> tuple[int, int, int]: def assemble_to_s(llvm_mc: str, asm_path: str, s_path: str, name: str) -> None: """Assemble raw RDNA2 .asm with llvm-mc -show-encoding into .s format for rdna2spirv.py.""" raw = open(asm_path, encoding="utf-8").read() - cmd = [llvm_mc, "-triple=amdgcn--amdpal", "-mcpu=gfx1013"] + cmd = mc_command.mc_command(llvm_mc) + ["-triple=amdgcn--amdpal", "-mcpu=gfx1013"] for ln in raw.splitlines(): s = ln.strip() if not s: @@ -357,7 +361,8 @@ def check_clip_half(raw_path: str, want_b: float, want_a: float) -> tuple[bool, def main() -> int: ap = argparse.ArgumentParser() - ap.add_argument("--llvm-mc", default=os.environ.get("LLVM_MC", "llvm-mc")) + ap.add_argument("--llvm-mc", default=os.environ.get("LLVM_MC", "llvm-mc"), + help="llvm-mc path, or a whole command such as 'wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc'") ap.add_argument("--build", default=os.path.join(ROOT, "runtime", "build")) ap.add_argument("--work", default=None) ap.add_argument("--filter", default="") diff --git a/tests/conftest.py b/tests/conftest.py index c78e0209a..0e89d3675 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -17,13 +17,14 @@ import pytest ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, os.path.join(ROOT, "tools")) +import mc_command # noqa: E402 import rdna2spirv # noqa: E402 def _has_amdgpu(mc): """True if this llvm-mc was built with the AMDGPU target (the official Windows release archives are not).""" try: - r = subprocess.run([mc, "--version"], capture_output=True, text=True, timeout=60) + r = subprocess.run(mc + ["--version"], capture_output=True, text=True, timeout=60) except (OSError, subprocess.SubprocessError): return False return "amdgcn" in r.stdout @@ -33,12 +34,14 @@ def _find_llvm_mc(): candidates = [] env = os.environ.get("LLVM_MC") if env: - candidates.append(shutil.which(env)) # None when the path doesn't exist - candidates.append(shutil.which("llvm-mc")) + candidates.append(mc_command.split_command(env)) + found = shutil.which("llvm-mc") + if found: + candidates.append([found]) # Debian/Ubuntu install it versioned, out of PATH. - candidates += sorted(glob.glob("/usr/lib/llvm-*/bin/llvm-mc"), reverse=True) + candidates += [[p] for p in sorted(glob.glob("/usr/lib/llvm-*/bin/llvm-mc"), reverse=True)] # Default location of the official Windows installer, which doesn't add LLVM to PATH unless asked to. - candidates += glob.glob(r"C:\Program Files\LLVM\bin\llvm-mc.exe") + candidates += [[p] for p in glob.glob(r"C:\Program Files\LLVM\bin\llvm-mc.exe")] for c in candidates: if c and _has_amdgpu(c): return c @@ -126,7 +129,7 @@ class Shader: rsrc2, (lx, ly, lz) = cs_header (workdir / "fssm").mkdir(exist_ok=True) (workdir / "fssm" / f"{name}.fssm").write_bytes(bytes(0x138) + struct.pack("<4I", rsrc2, lx, ly, lz)) - cmd = [LLVM_MC, "-triple=amdgcn--amdpal", "-mcpu=gfx1013"] + cmd = LLVM_MC + ["-triple=amdgcn--amdpal", "-mcpu=gfx1013"] for ln in asm.splitlines(): s = ln.strip() if not s: diff --git a/tests/test_mc_command.py b/tests/test_mc_command.py new file mode 100644 index 000000000..0e3c84e53 --- /dev/null +++ b/tests/test_mc_command.py @@ -0,0 +1,61 @@ +"""LLVM_MC is one executable path or a whole command line, in every tool that reads it. + +Windows runs llvm-mc through WSL (the official Windows LLVM build has no AMDGPU target): + + set LLVM_MC=wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc + + python -I tests/test_mc_command.py +""" +import os +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(ROOT, "tools")) + +import mc_command # noqa: E402 + + +class SplitCommandTest(unittest.TestCase): + def test_bare_name(self): + self.assertEqual(mc_command.split_command("llvm-mc"), ["llvm-mc"]) + + def test_empty(self): + self.assertEqual(mc_command.split_command(""), []) + self.assertEqual(mc_command.split_command(" "), []) + + def test_command_line(self): + self.assertEqual(mc_command.split_command("wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc"), + ["wsl", "-d", "Ubuntu", "-e", "/usr/lib/llvm-21/bin/llvm-mc"]) + + def test_quoted_arguments(self): + if os.name == "nt": + raw = '"C:\\Program Files\\LLVM\\bin\\llvm-mc.exe" --version' + want = ["C:\\Program Files\\LLVM\\bin\\llvm-mc.exe", "--version"] + else: + raw = '"/opt/llvm 21/bin/llvm-mc" --version' + want = ["/opt/llvm 21/bin/llvm-mc", "--version"] + self.assertEqual(mc_command.split_command(raw), want) + + def test_path_with_spaces_is_kept_whole(self): + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, "llvm mc") + with open(path, "w", encoding="utf-8") as f: + f.write("") + self.assertEqual(mc_command.split_command(path), [path]) + self.assertEqual(mc_command.split_command(f'"{path}"'), [path]) + + def test_mc_command_reads_the_environment(self): + with mock.patch.dict(os.environ, {"LLVM_MC": "wsl -d Ubuntu -e /opt/llvm-21/bin/llvm-mc"}): + self.assertEqual(mc_command.mc_command(), + ["wsl", "-d", "Ubuntu", "-e", "/opt/llvm-21/bin/llvm-mc"]) + + def test_mc_command_falls_back_to_the_path_name(self): + with mock.patch.dict(os.environ, {"LLVM_MC": ""}): + self.assertEqual(mc_command.mc_command(), ["llvm-mc"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/mc_command.py b/tools/mc_command.py new file mode 100644 index 000000000..9f76e03b4 --- /dev/null +++ b/tools/mc_command.py @@ -0,0 +1,29 @@ +"""Resolve LLVM_MC to an argv list. + +LLVM_MC may be one executable (a path, spaces and all) or a whole command line. Windows needs the command-line +form when llvm-mc runs inside WSL, because the official Windows LLVM build has no AMDGPU target: + + set LLVM_MC=wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc +""" +import os +import shlex + + +def split_command(raw: str) -> list: + """Split a command line without eating the backslashes of a Windows path (POSIX shlex would).""" + raw = raw.strip() + if not raw: + return [] + if os.path.isfile(raw): + return [raw] # a plain path, spaces and all + if os.name != "nt": + return shlex.split(raw) + parts = shlex.split(raw, posix=False) + return [p[1:-1] if len(p) > 1 and p[0] == p[-1] == '"' else p for p in parts] + + +def mc_command(raw: str | None = None) -> list: + """LLVM_MC is a path, or a command line: 'wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc'.""" + if raw is None: + raw = os.environ.get("LLVM_MC", "llvm-mc") + return split_command(raw) or ["llvm-mc"] diff --git a/tools/shader_disasm.py b/tools/shader_disasm.py index 942d44dac..4f5fafcd3 100644 --- a/tools/shader_disasm.py +++ b/tools/shader_disasm.py @@ -13,34 +13,20 @@ Set LLVM_MC to llvm-mc's path, or to a whole command such as """ import argparse import os -import shlex import struct import subprocess import sys from concurrent.futures import ThreadPoolExecutor +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from mc_command import mc_command # noqa: E402 + TRIPLE = "amdgcn--amdpal" ENDPGM = b"\x00\x00\x81\xbf" PROBE = "0x00 0x00 0x81 0xbf" # s_endpgm: the one instruction every shader ends with FAILED = [] # (path, first stderr line) for shaders that produced no disassembly -def split_command(raw: str) -> list: - """Split LLVM_MC without eating the backslashes of a Windows path (POSIX shlex would).""" - if os.name != "nt": - return shlex.split(raw) - parts = shlex.split(raw, posix=False) - return [p[1:-1] if len(p) > 1 and p[0] == p[-1] == '"' else p for p in parts] - - -def mc_command() -> list: - """LLVM_MC is a path, or a command line: 'wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc'.""" - raw = os.environ.get("LLVM_MC", "llvm-mc").strip() - if os.path.isfile(raw): - return [raw] # a plain path, spaces and all - return split_command(raw) or ["llvm-mc"] - - MC = mc_command() -- cgit v1.2.3 From 4e390e0871d7265e629b51aca8ff99a15a6a6845 Mon Sep 17 00:00:00 2001 From: ItsNotRexed <300290919+ItsNotRexed@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:19:54 -0500 Subject: run_gpu_tests: --filter ps_flat also builds vs_ids, which ps_flat is drawn with (fixes #192) Co-Authored-By: Claude Opus 5.5 --- scripts/run_gpu_tests.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'scripts/run_gpu_tests.py') diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index cef73011b..edd5cad19 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py @@ -377,9 +377,13 @@ def run_suite(a, work: str) -> int: asm_files = sorted(f for f in os.listdir(SHADER_DIR) if f.endswith(".asm")) if a.filter: asm_files = [f for f in asm_files if a.filter in f] + # Shaders a selected test draws with are built even when the filter leaves them out (#192): ps_flat uses vs_ids. + build_files = list(asm_files) + if any(f.startswith("ps_flat") for f in asm_files) and "vs_ids.asm" not in build_files: + build_files.append("vs_ids.asm") # 1. Create synthetic DXBC / FSSM metadata + assemble .asm -> .s - for fname in asm_files: + for fname in build_files: name = os.path.splitext(fname)[0] if name == "gs_tri": dxbc = make_dxbc([ -- cgit v1.2.3