r"""Run hand-written RDNA2 pixel-shader ISA on an AMD GPU: a hardware oracle for what only a pixel shader can do. tools/hw_oracle launches compute kernels; v_interp_*, the parameter data the SPI writes into LDS, exports and helper lanes need a real draw. This tool gets one through Vulkan's VK_KHR_pipeline_binary (the AMD Windows driver exposes it, with uncompressed data): 1. vk_harness builds a pipeline from a template vertex + pixel shader (SPIR-V) and writes its binary (VKH_BINARY_OUT). On AMD that binary is one PAL ELF: `.text` holds `_amdgpu_gs_main` (the vertex stage) and `_amdgpu_ps_main`, the `.note` holds the PAL metadata (msgpack): register counts and the SPI setup (SPI_PS_INPUT_ENA/ADDR, the parameter layout, the export format), which the driver programs from the metadata. 2. The ISA under test is assembled with AMD clang (gfx1036 or the --mcpu given) and replaces `_amdgpu_ps_main`; `.text` grows when it is longer, and the pixel stage's VGPR/SGPR counts in the metadata are raised to cover the registers it names. 3. vk_harness builds the pipeline from the patched binary (VKH_BINARY_IN), draws one full-screen triangle into an RGBA32F target and reads it back, so every pixel's mrt0 export comes back as four raw dwords. The template decides what the hardware sets up before the code runs: which barycentrics are in VGPRs, which user SGPRs hold what (the PS sets M0 from one of them for v_interp), how many parameters the SPI writes into LDS and in what format, and the export format of mrt0 (32_ABGR for the harness' RGBA32F target). --show-template prints the template's own ISA and that part of its metadata, so the code under test can follow the same conventions. Templates: `const` (no inputs), `interp2` (two smooth vec4 varyings: location 0 = (u, v, 0, 1) and location 1 = (u, v, 0, 0) with u, v = 0..2 across the screen, as scripts/run_gpu_tests.py's vs_tri), or --vs/--ps files (.spv, or .spvasm assembled with spirv-as). --format picks another color target (the driver then picks the export format for it, as for a game pipeline); the readback is that target's texels as stored. The selected format, including the default RGBA32F, takes precedence over a VKH_COLOR_FORMAT inherited from the shell. Checked on an AMD Radeon iGPU (gfx1036, Windows driver 26.10.1): the driver accepts a patched binary and the patched code runs as the pixel shader (no checksum over the code). The pixel stage there is compiled as wave64. On Linux, RADV (Mesa) returns one binary per stage instead (radv_shader_serialize's layout, see the RADV section below); the pixel stage's code, sizes and register counts are found by their values and patched there. RADV takes GFX10 (RDNA1/RDNA2) devices only (GFX11+ is refused: no v_interp), --set is PAL-only, and Mesa may merge a template's varyings (interp2 becomes one parameter, attr0 = (2u, 2v, 0, 1)). Checked on gfx1036 with Mesa 26.3.1. Usage: python -I tools/ps_oracle.py --build --template interp2 --show-template python -I tools/ps_oracle.py --build --template interp2 --asm body.s [--size 8 8] [--json out.json] Select the AMD GPU with LEONIDA_VK_DEVICE (e.g. radeon). Standard library only; needs vk_harness from the runtime build, AMD clang (LEONIDA_AMD_CLANG, as tools/hw_oracle), llvm-objdump (llvm-mc on RADV) next to it for --show-template, and spirv-as on PATH for the templates. Exit codes: 0 ran, 1 the GPU run failed, 2 usage or a bad input, 77 the device or a tool is missing (no VK_KHR_pipeline_binary, neither a PAL nor a RADV binary, a RADV GPU other than GFX10, no clang). """ import argparse import collections import json import os import re import shutil import struct import subprocess import sys import tempfile HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) from report_paths import same_report_path # noqa: E402 PS_SYMBOL = "_amdgpu_ps_main" S_CODE_END = struct.pack("= 0xE0: return t - 0x100, i + 1 if 0x80 <= t <= 0x8F or t in (0xDE, 0xDF): n, i = (t & 0x0F, i + 1) if t <= 0x8F else (struct.unpack_from(">H" if t == 0xDE else ">I", b, i + 1)[0], i + (3 if t == 0xDE else 5)) d = {} for _ in range(n): k, i = mp_load(b, i) v, i = mp_load(b, i) d[k] = v return d, i if 0x90 <= t <= 0x9F or t in (0xDC, 0xDD): n, i = (t & 0x0F, i + 1) if t <= 0x9F else (struct.unpack_from(">H" if t == 0xDC else ">I", b, i + 1)[0], i + (3 if t == 0xDC else 5)) out = [] for _ in range(n): v, i = mp_load(b, i) out.append(v) return out, i if 0xA0 <= t <= 0xBF or t in (0xD9, 0xDA, 0xDB): if t <= 0xBF: n, i = t & 0x1F, i + 1 else: w = {0xD9: 1, 0xDA: 2, 0xDB: 4}[t] n, i = int.from_bytes(b[i + 1:i + 1 + w], "big"), i + 1 + w return b[i:i + n].decode("utf-8"), i + n if t in (0xC4, 0xC5, 0xC6): w = {0xC4: 1, 0xC5: 2, 0xC6: 4}[t] n = int.from_bytes(b[i + 1:i + 1 + w], "big") return bytes(b[i + 1 + w:i + 1 + w + n]), i + 1 + w + n if t == 0xC0: return None, i + 1 if t in (0xC2, 0xC3): return t == 0xC3, i + 1 if t == 0xCA: return F32(struct.unpack_from(">f", b, i + 1)[0]), i + 5 if t == 0xCB: return struct.unpack_from(">d", b, i + 1)[0], i + 9 ints = {0xCC: ">B", 0xCD: ">H", 0xCE: ">I", 0xCF: ">Q", 0xD0: ">b", 0xD1: ">h", 0xD2: ">i", 0xD3: ">q"} if t in ints: return struct.unpack_from(ints[t], b, i + 1)[0], i + 1 + struct.calcsize(ints[t]) raise ValueError(f"msgpack type 0x{t:02x} at {i} is not supported") def _mp_len(n, small, small_max, wide): if n <= small_max: return bytes([small | n]) for code, fmt, top in wide: if n < top: return bytes([code]) + struct.pack(fmt, n) raise ValueError("too long") def mp_dump(v): if v is None: return b"\xc0" if v is True or v is False: return b"\xc3" if v else b"\xc2" if isinstance(v, int): if 0 <= v <= 0x7F: return bytes([v]) if -32 <= v < 0: return bytes([v + 0x100]) for code, fmt, lo, hi in ((0xCC, ">B", 0, 1 << 8), (0xCD, ">H", 0, 1 << 16), (0xCE, ">I", 0, 1 << 32), (0xCF, ">Q", 0, 1 << 64), (0xD0, ">b", -(1 << 7), 0), (0xD1, ">h", -(1 << 15), 0), (0xD2, ">i", -(1 << 31), 0), (0xD3, ">q", -(1 << 63), 0)): if lo <= v < hi: return bytes([code]) + struct.pack(fmt, v) raise ValueError(f"integer {v} out of range") if isinstance(v, F32): return b"\xca" + struct.pack(">f", v) if isinstance(v, float): return b"\xcb" + struct.pack(">d", v) if isinstance(v, str): s = v.encode("utf-8") if len(s) <= 31: return bytes([0xA0 | len(s)]) + s return _mp_len(len(s), 0, -1, ((0xD9, ">B", 1 << 8), (0xDA, ">H", 1 << 16), (0xDB, ">I", 1 << 32))) + s if isinstance(v, (bytes, bytearray)): return _mp_len(len(v), 0, -1, ((0xC4, ">B", 1 << 8), (0xC5, ">H", 1 << 16), (0xC6, ">I", 1 << 32))) + bytes(v) if isinstance(v, list): return _mp_len(len(v), 0x90, 15, ((0xDC, ">H", 1 << 16), (0xDD, ">I", 1 << 32))) + b"".join(map(mp_dump, v)) if isinstance(v, dict): head = _mp_len(len(v), 0x80, 15, ((0xDE, ">H", 1 << 16), (0xDF, ">I", 1 << 32))) return head + b"".join(mp_dump(k) + mp_dump(x) for k, x in v.items()) raise TypeError(f"cannot write {type(v).__name__} as msgpack") # ---- the PAL ELF of a pipeline binary ---- _SH = " [(key size, 32 key bytes, data)].""" with open(path, "rb") as f: d = f.read() n, at, out = struct.unpack_from(" / v[a:b] and s / s[a:b].""" top = {"v": 0, "s": 0} for line in lines: for kind, single, last in _REG.findall(line.split(";", 1)[0]): top[kind] = max(top[kind], int(last or single) + 1) return top["v"], top["s"] def set_meta(pipe, path, value): """Set one value in the pipeline's metadata map: path is '/'-separated keys from amdpal.pipelines[0] (list indices as numbers), e.g. ".graphics_registers/.spi_ps_input_cntl/0/.fp16_interp_mode".""" keys = [int(k) if k.isdigit() else k for k in path.split("/") if k] node = pipe for k in keys[:-1]: node = node[k] if keys[-1] not in node if isinstance(node, dict) else not 0 <= keys[-1] < len(node): raise ValueError(f"no metadata entry {path!r}") old = node[keys[-1]] if isinstance(old, F32): value = F32(value) node[keys[-1]] = value def patch_ps(elf_bytes, code, lines=(), sets=()): """The ELF with `_amdgpu_ps_main` replaced by `code` (raw instruction bytes), padded with s_code_end, the pixel stage's VGPR/SGPR counts raised to cover the registers `lines` name, and each (path, value) of `sets` written into the metadata (set_meta). `_amdgpu_ps_main` must be the last function of .text (it is in the AMD driver's binaries).""" elf = Elf(elf_bytes) syms = {s[0]: s for s in elf.symbols()} if PS_SYMBOL not in syms: raise Unavailable(f"no {PS_SYMBOL} in the pipeline binary") _, start, _, entry = syms[PS_SYMBOL] if any(v > start for n, v, _s, _e in syms.values() if n and n != PS_SYMBOL): raise ValueError(f"{PS_SYMBOL} is not the last function of .text") ti = elf.index(".text") code = bytes(code) + S_CODE_END * ((-len(code) % 64) // 4 + 64) # the hardware prefetches past the end elf.data[ti] = bytearray(elf.data[ti][:start]) + bytearray(code) elf.set_symbol_size(entry, len(code) - 64 * 4) v, s = regs_used(lines) meta = elf.metadata() stage = ps_stage(meta) changed = bool(sets) for path, value in sets: set_meta(meta["amdpal.pipelines"][0], path, value) if v > stage.get(".vgpr_count", 0) or s > stage.get(".sgpr_count", 0): stage[".vgpr_count"] = max(stage.get(".vgpr_count", 0), v) stage[".sgpr_count"] = max(stage.get(".sgpr_count", 0), s) changed = True if changed: elf.set_metadata(meta) return elf.to_bytes() def ps_code(elf_bytes): """(start, bytes) of `_amdgpu_ps_main` in .text (to the end of .text, s_code_end padding included).""" elf = Elf(elf_bytes) syms = {s[0]: s for s in elf.symbols()} start = syms[PS_SYMBOL][1] return start, bytes(elf.data[elf.index(".text")][start:]) def is_wave64(elf_bytes): """The pixel stage's wave size from its first instruction, s_version (UC_VERSION_W64_BIT).""" _, code = ps_code(elf_bytes) word = struct.unpack_from("> 23 != 0x161: # SOPK opcode 1 (s_version) in GFX10: 0xB080xxxx return None return bool(word & W64_BIT) # ---- RADV (Mesa) stage binaries ---- # RADV hands back one binary per stage, as radv_shader_serialize writes it (Mesa 26.3, radv_pipeline_cache.c; the # structs in radv_shader.h): uint32 type (0 = legacy), struct ac_shader_config (ac_binary.h: num_sgprs, num_vgprs # first, rsrc1 later), struct radv_shader_info (its size changes between Mesa versions; wave_size, a byte, stage, # next_stage sit together in it), uint32 total_size (padded to 8), then code_size, exec_size, ir_size, disasm_size, # stats_size, debug_info_size, then the data: stats, code, ir, disasm, debug info. Debug strings may follow # total_size. RADV builds an imported binary with radv_shader_create_uncached (no cache lookup) and programs # SPI_SHADER_PGM_RSRC1_PS from config.rsrc1, whose VGPRS field is (num_vgprs - 1) / (wave32 ? 8 : 4) # (radv_postprocess_binary_config). Only the two leading config fields are read at a fixed place; the rest is found # from values that must agree with each other, so a Mesa with another layout is refused instead of misread. RadvLayout = collections.namedtuple("RadvLayout", "code code_size exec_size sizes_at total_at vgprs sgprs rsrc1_at " "wave is_ps") MESA_FRAGMENT, MESA_NONE = 4, 0xFF # Mesa's chip names (amd_family.c) of GFX10 with their LLVM targets (ac_get_llvm_processor_name) RADV_GFX10 = {"NAVI10": "gfx1010", "NAVI12": "gfx1011", "NAVI14": "gfx1012", "GFX1013": "gfx1013", "NAVI21": "gfx1030", "NAVI22": "gfx1031", "NAVI23": "gfx1032", "VANGOGH": "gfx1033", "NAVI24": "gfx1034", "REMBRANDT": "gfx1035", "RAPHAEL_MENDOCINO": "gfx1036"} def radv_layout(data): """Where the code, its sizes and the register counts are in one RADV stage binary (RadvLayout), or Unavailable.""" u32 = lambda at: struct.unpack_from("> 12 & 0xFF and any(u32(j) == u32(k) >> 12 & 0xFF for j in range(12, k, 4))] if len(rsrc1) != 1: raise Unavailable("the RADV binary's rsrc1 was not found (an unknown Mesa layout)") return RadvLayout(code_at, code_size, exec_size, sizes_at, total_at, vgprs, sgprs, rsrc1[0], wave, True) def radv_ps_index(bins): """Which of RADV's stage binaries is the pixel stage.""" ps = [i for i, (_ks, _key, data) in enumerate(bins) if radv_layout(data).is_ps] if len(ps) != 1: raise Unavailable(f"{len(ps)} of the {len(bins)} RADV binaries are a pixel stage (expected one)") return ps[0] def radv_arch(device): """The LLVM target of a RADV device name ('... (RADV RAPHAEL_MENDOCINO)'), Unavailable when it is not GFX10.""" m = re.search(r"\(RADV ([A-Z0-9_]+)\)", device or "") if not m: raise Unavailable(f"the pipeline came back as several binaries and the device ({device or '?'}) is not RADV") if m.group(1) not in RADV_GFX10: raise Unavailable(f"unsupported architecture: {m.group(1)} ({device}); on RADV this tool runs GFX10 " "(RDNA1/RDNA2) pixel shaders only (GFX11+ interpolates with lds_param_load, not v_interp)") return RADV_GFX10[m.group(1)] def patch_radv_ps(data, code, lines=()): """The RADV pixel-stage binary with its code replaced by `code` (raw instruction bytes, padded with s_code_end), the sizes fixed and num_vgprs/num_sgprs and rsrc1's VGPRS raised to cover the registers `lines` name.""" lay = radv_layout(data) if not lay.is_ps: raise ValueError("not the pixel-stage binary") padded = bytes(code) + S_CODE_END * ((-len(code) % 64) // 4 + 64) # the hardware prefetches past the end out = bytearray(data[:lay.code]) + padded + data[lay.code + lay.code_size:] put = lambda at, v: struct.pack_into("