"""Build the hand-written test shaders in this folder into SPIR-V. 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 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 can override the default header with leading "; group: X,Y,Z" and "; rsrc2: 0x..." comments. A shader whose header has "; fssm-at: 0xOFFSET" and "; fssm-data: 0xWORD ..." comments also gets a synthetic FSSM program (the magic, zeros up to OFFSET, then the words): it is published as /fssm/.fssm and its SHA-256 goes into the index as fssm_sha256, which is what the layer looks a PSO's shader up by (the translator hashes /fssm/.fssm for the game's programs, and compute shaders here already). A test builds the shader container from that file. The words are also what a shader reads through s_getpc_b64 (the code base) at that offset. The stage comes from the name's prefix. Mesh shaders (ms_) also need a DXBC container with their PSV0, which this doesn't make; geometry shaders (gs_) get gs_tri's signatures (gs_container). The comment at the top of each .asm says which test program to run on the result and what it should print. With LEONIDA_FMA=khr (or glsl, or exact), the fused multiply-adds are translated with --fma khr (OpFmaKHR, which needs VK_KHR_shader_fma; the test programs enable it when the device has it, else they exit 77), --fma glsl, or --fma exact (a single rounding built from plain f32 ops, for a driver that splits GLSL Fma and has no VK_KHR_shader_fma). With LEONIDA_BARY_FALLBACK=1, pixel shaders that read raw barycentrics are translated with --bary-fallback, and each gets a pass-through geometry shader, .bary_gs.spv, that check.py draws it with (tools/bary_fallback_gs.py). With the variable unset, build.py/check.py follow the Mesa ANV probe automatically. With LEONIDA_F16_INTERP_FALLBACK=1, 16-bit interpolants are translated with --f16-interp-fallback (decoded halves from the producer instead of PerVertexKHR inputs); 0 turns that off. With the variable unset, build.py/check.py turn it on where tools/vk_subgroup_info.py reports no PerVertexKHR inputs (MoltenVK), as scripts/run_gpu_tests.py does. Under --bary-fallback, ps_ij_computed isn't built: its computed I/J pair needs PerVertexKHR inputs (or --f16-interp-fallback without --bary-fallback), and check.py reports it as SKIP. With LEONIDA_PC_TAIL_UBO=1, every shader is translated with --pc-tail-ubo (s0..s31 in 128 push-constant bytes, the heap base and code base in a uniform block at set 1), for devices whose maxPushConstantsSize is 128; set it for check.py too, whose test programs then bind that block (runtime/test/vk_pc_tail.h). """ import json import os import re import struct import subprocess import sys import tempfile from pathlib import Path HERE = os.path.dirname(os.path.abspath(__file__)) 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) # Not built under the barycentric fallback, set or picked from the device (see main). NEEDS_PER_VERTEX_INPUTS = ("ps_ij_computed",) sys.path.insert(0, HERE) # this script is also run with python -I from compute_fixture import compute_header, shift_user_data, user_data_shift # noqa: E402 def barycentric_fallback_override(): v = (os.environ.get("LEONIDA_BARY_FALLBACK") or "").strip().lower() if v in ("1", "true", "yes", "on"): return True if v in ("0", "false", "no", "off"): return False return None def probe_gpu(): """Run tools/vk_subgroup_info.py once and return its JSON capability dict (empty on failure).""" try: r = subprocess.run([sys.executable, "-I", os.path.join(TOOLS, "vk_subgroup_info.py")], capture_output=True, text=True, timeout=60) answer = json.loads(r.stdout.strip().splitlines()[-1]) except (OSError, ValueError, IndexError, subprocess.SubprocessError): return {} return answer if isinstance(answer, dict) and "error" not in answer else {} def barycentric_fallback(answer=None): override = barycentric_fallback_override() if override is not None: return override if answer is None: answer = probe_gpu() return answer.get("barycentric_fallback") is True def f16_interp_fallback_override(): v = (os.environ.get("LEONIDA_F16_INTERP_FALLBACK") or "").strip().lower() if v in ("1", "true", "yes", "on"): return True if v in ("0", "false", "no", "off"): return False return None def f16_interp_fallback(answer=None): """LEONIDA_F16_INTERP_FALLBACK=1 (or 0). Unset, it is on where the device can't take PerVertexKHR inputs: tools/vk_subgroup_info.py reports per_vertex_inputs false (MoltenVK), the rule of scripts/run_gpu_tests.py. A device that gives no answer leaves it off.""" override = f16_interp_fallback_override() if override is not None: return override if answer is None: answer = probe_gpu() return answer.get("per_vertex_inputs") is False def gpu_fallback_flags(): """Match the selected device's barycentric, f16-interpolation, and float32 flush-to-zero capabilities.""" answer = probe_gpu() flags = [] if barycentric_fallback(answer): flags.append("--bary-fallback") if f16_interp_fallback(answer): flags.append("--f16-interp-fallback") if answer.get("denorm_flush_to_zero_f32") is False: flags.append("--no-ftz32") return flags def asm_mattr(path): for ln in Path(path).read_text(encoding="utf-8").splitlines(): s = ln.strip() if not s: continue if not s.startswith(";"): break m = re.match(r";\s*mattr:\s*(\S+)", s) if m: return m.group(1) return None CLIP_CASES = {"vs_clip": 1, "vs_clip_param4": 4, "vs_clip_undeclared": 1} def explicit_lod_bias(): """LEONIDA_EXPLICIT_LOD_BIAS=1 (or 0). Unset, it is on where tools/vk_subgroup_info.py --lod-bias measures that the sampler drops mipLodBias (one compute dispatch from Python, no test programs needed), the rule of scripts/run_gpu_tests.py. No answer leaves it off.""" v = (os.environ.get("LEONIDA_EXPLICIT_LOD_BIAS") or "").strip().lower() if v in ("1", "true", "yes", "on"): return True if v in ("0", "false", "no", "off"): return False try: r = subprocess.run([sys.executable, "-I", os.path.join(TOOLS, "vk_subgroup_info.py"), "--lod-bias"], capture_output=True, text=True, timeout=60) return json.loads(r.stdout.strip().splitlines()[-1]).get("explicit_lod_bias") is True except (OSError, ValueError, IndexError, AttributeError, subprocess.SubprocessError): return False def asm_fssm_fields(path): """(offset, words) of the "fssm-at" and "fssm-data" header comments, (None, []) without them.""" at, words = None, [] for ln in Path(path).read_text(encoding="utf-8").splitlines(): s = ln.strip() if s and not s.startswith(";"): break m = re.match(r";\s*fssm-at:\s*(0x[0-9a-fA-F]+|\d+)", s) if m: at = int(m.group(1), 0) m = re.match(r";\s*fssm-data:\s*(.*)", s) if m: words += [int(w, 0) for w in m.group(1).split()] return at, words def asm_fssm(path): """The synthetic FSSM program a vs_/ps_ shader's header asks for, or None.""" at, words = asm_fssm_fields(path) if at is None or not words or at < 4 or at % 4: return None return b"FSSM" + bytes(at - 4) + b"".join(struct.pack(".bary_gs.spv). import bary_fallback_gs bary_fallback_gs.build_for_index(str(spirv)) return 0 if __name__ == "__main__": sys.exit(main())