Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions docs/fspx.md
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,15 @@ program whose kind 0 is too short for word 4 keeps the code heuristic.
`op_sel` 2 and `op_sel_hi` 5 the result is the dot product with the two 16-bit halves of the second source
exchanged, in all 5 operand sets (4 of them give another word under the plain rule). So `op_sel` selects halves
here as it does for the packed 16-bit ops. The words are in `tests/semantic/test_alu_dot4_i8.py`.
- `tools/shader_disasm.py` (so `fspx_unpack.py --disasm` and `make_game.py`) prints such a word as
`v_dot4_i32_i8 vD, a, b, c op_sel:[0,1,0] op_sel_hi:[1,0,1]` with its real encoding. A dword pair that llvm-mc
rejected, with exactly opcode 0x16, `op_sel` 2, `op_sel_hi` 5, no `clamp` and no `neg`, is decoded with the two
fields at their defaults and then given the fields and the encoding back, so the translator reads it and its
encoding check against the blob passes. Any other `op_sel`/`op_sel_hi` value, `clamp` or `neg` is still
undecodable (only this one was measured). A pair llvm-mc accepted, such as a literal followed by an instruction,
is never touched. `tests/semantic/test_fspx_dot4_op_sel_disasm.py` checks it with llvm-mc (the 5 measured
operand sets, and the forms that stay refused); the 89 words of the real programs are not re-run here, because
that needs the package's DLL.

## Kind 7: records

Expand Down
15 changes: 13 additions & 2 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,10 @@ def mesh_psv0_chunk(threads=(128, 1, 1), max_vertices=64, max_primitives=64, top
# 0x8088 = 4 user SGPRs, TGID_X, 512 B of LDS; group 64x1x1 (the header the cs_* samples in runtime/test/shaders use).
DEFAULT_CS_HEADER = (0x8088, (64, 1, 1))

# The comment line a sample carries when llvm-mc cannot assemble it (cs_dpp_cmp.asm: a VOPC compare in DPP form).
# scripts/run_gpu_tests.py has the same line; tests/test_translate.py checks that the two agree.
TEXT_ONLY_MARK = "; run_gpu_tests: text only, llvm-mc has no gfx1013 encoding for an instruction here"


class Shader:
def __init__(self, workdir, name, asm, cs_header=DEFAULT_CS_HEADER, dxbc=EMPTY_DXBC):
Expand All @@ -167,6 +171,15 @@ def __init__(self, workdir, name, asm, cs_header=DEFAULT_CS_HEADER, dxbc=EMPTY_D
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))
self.path = disasm / f"{name}.s"
self.workdir = workdir
if any(ln.strip() == TEXT_ONLY_MARK for ln in asm.splitlines()):
# llvm-mc has no gfx1013 encoding for an instruction of this sample, so its text is the listing, as in
# assemble_to_s of scripts/run_gpu_tests.py: the translator reads straight-line code from the text alone.
lines = [f"; {name} code 0x0..0x0 (synthetic), gfx1013, 0 invalid words"]
lines += ["\t" + ln.strip() for ln in asm.splitlines() if ln.strip() and not ln.lstrip().startswith(";")]
self.path.write_text("\n".join(lines) + "\n", encoding="utf-8", newline="\n")
return
cmd = LLVM_MC + ["-triple=amdgcn--amdpal", "-mcpu=gfx1013"]
for ln in asm.splitlines():
s = ln.strip()
Expand All @@ -181,9 +194,7 @@ def __init__(self, workdir, name, asm, cs_header=DEFAULT_CS_HEADER, dxbc=EMPTY_D
cmd.append("-show-encoding")
r = subprocess.run(cmd, input=asm, capture_output=True, text=True)
assert r.returncode == 0, r.stderr
self.path = disasm / f"{name}.s"
self.path.write_text(f"; {name} synthetic\n{r.stdout}")
self.workdir = workdir

def translate(self):
return rdna2spirv.translate(str(self.path))
Expand Down
4 changes: 2 additions & 2 deletions tests/semantic/test_alu_dot4_i8.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@
op_sel 2 and op_sel_hi 5, which llvm-mc does not decode (docs/fspx.md). Run on the same hardware as two raw words
(0xCC165008 0x0C0E0501: v8 = v1 . v2 + v3 with those fields), that form gave the words of MEASURED_OP_SEL: the dot
product with the two 16-bit halves of the second source exchanged, as op_sel selects halves for the packed 16-bit
ops. `ref_op_sel` reproduces them; the translator refuses any op_sel on these two instructions until a listing can
carry it.
ops. `ref_op_sel` reproduces them. A listing carries the form since tools/shader_disasm.py prints it
(tests/semantic/test_fspx_dot4_op_sel_disasm.py).

neg_lo and neg_hi. llvm-mc accepts them on v_dot4_i32_i8 for gfx1036 (not on v_dot4c_i32_i8), and the hardware does
not ignore them: on the same GPU, 5 operand sets with 8 forms each gave the words of `ref_neg`, 9 of which are in
Expand Down
157 changes: 157 additions & 0 deletions tests/semantic/test_fspx_dot4_op_sel_disasm.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
"""The FidelityFX upscaler's programs (docs/fspx.md) hold 89 v_dot4_i32_i8 words with op_sel 2 and op_sel_hi 5, which
llvm-mc does not decode: it rejects the first dword, reads the second as another instruction, and the translator then
refuses the program ("fall-through into undecodable words"), so 9 of the 29 programs had no pipeline and the DLL's
next pipeline call faulted. tools/shader_disasm.py now prints such a word as the instruction it is, with its
op_sel/op_sel_hi fields and its real encoding, so the translator reads it and checks it against the blob.

Each case assembles a small program with llvm-mc, turns one v_dot4_i32_i8 into the op_sel 2 / op_sel_hi 5 form by
setting those fields in its two dwords, disassembles the bytes with shader_disasm, and translates the listing in the
FSPX layout (disasm/, fspx/<name>.code and .json). The expected words are the ones measured on gfx1036
(MEASURED_OP_SEL in test_alu_dot4_i8.py). They need llvm-mc with the AMDGPU target (LLVM_MC, or llvm-mc on PATH) and
skip without it. No GPU and no game files.

python -I tests/semantic/test_fspx_dot4_op_sel_disasm.py
"""
import json
import os
import struct
import subprocess
import sys
import tempfile
import unittest
import warnings

HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(os.path.dirname(HERE))
sys.dont_write_bytecode = True
sys.path.insert(0, os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools"))
sys.path.insert(0, HERE)

import rdna2spirv # noqa: E402
import shader_disasm # noqa: E402
import spirv_mini_interp as si # noqa: E402
from test_alu_dot4_i8 import MEASURED_OP_SEL, ref # noqa: E402

MCPU = "gfx1030" # fspx_unpack.py's default: LLVM decodes v_dot4_i32_i8 for it and not for gfx1013
STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4)


def assemble(line):
"""The bytes llvm-mc assembles one instruction line to."""
p = subprocess.run(shader_disasm.MC + ["--assemble", "-triple=amdgcn--amdpal", f"-mcpu={MCPU}", "-show-encoding"],
input="\t" + line + "\n", capture_output=True, text=True, errors="replace")
match = shader_disasm.ENCODING.search(p.stdout)
if p.returncode or not match:
raise AssertionError(f"llvm-mc cannot assemble {line!r}: {p.stderr.strip()}")
return bytes(int(b, 16) for b in match.group(1).split(","))


def llvm_decodes_v_dot4():
try:
return shader_disasm.run_mc(assemble("v_dot4_i32_i8 v8, v1, v2, v3"), MCPU)[1] == 0
except (OSError, AssertionError):
return False


def with_op_sel(word_pair, op_sel, op_sel_hi):
"""The two dwords of a plain v_dot4_i32_i8 (op_sel 0, op_sel_hi 7) with these fields: op_sel in bits 13:11 and
op_sel_hi[2] in bit 14 of the first dword, op_sel_hi[1:0] in bits 28:27 of the second."""
w0, w1 = struct.unpack("<2I", word_pair)
w0 = w0 & ~(7 << 11) & ~(1 << 14) | op_sel << 11 | (op_sel_hi >> 2) << 14
w1 = w1 & ~(3 << 27) | (op_sel_hi & 3) << 27
return struct.pack("<2I", w0, w1)


def program(a, b, addend, middle):
"""Code bytes of: v8 = the v_dot4_i32_i8 given by `middle` (its two dwords), v9 = the plain v_dot4_i32_i8 on the
same registers, both written to mrt0. Returns (code, byte offset of the first dot4)."""
head = b"".join(assemble(line) for line in (
f"v_mov_b32_e32 v1, 0x{a:08x}", f"v_mov_b32_e32 v2, 0x{b:08x}", f"v_mov_b32_e32 v3, 0x{addend:08x}"))
tail = b"".join(assemble(line) for line in (
"v_dot4_i32_i8 v9, v1, v2, v3", "exp mrt0 v8, v9, v8, v9 done vm", "s_endpgm"))
return head + middle + tail, len(head)


def translate_fspx(name, listing, code):
"""SPIR-V assembly for a listing in the FSPX layout, with the code bytes it was disassembled from beside it."""
with tempfile.TemporaryDirectory() as tmp:
for d in ("disasm", "fspx"):
os.mkdir(os.path.join(tmp, d))
with open(os.path.join(tmp, name + ".dxbc"), "wb") as f:
f.write(STUB_DXBC)
with open(os.path.join(tmp, "fspx", name + ".code"), "wb") as f:
f.write(code)
with open(os.path.join(tmp, "fspx", name + ".json"), "w", encoding="utf-8") as f:
json.dump({}, f)
src = os.path.join(tmp, "disasm", name + ".s")
with open(src, "w", encoding="utf-8", newline="\n") as f:
f.write(listing)
with warnings.catch_warnings():
warnings.simplefilter("ignore", ResourceWarning)
return rdna2spirv.translate(src)


def listing_of(name, code):
asm, bad, err = shader_disasm.disasm(code, MCPU)
return f"; {name} code 0x0..0x{len(code):x} (fspx), {MCPU}, {bad} invalid words\n" + asm, bad


@unittest.skipUnless(llvm_decodes_v_dot4(), "needs llvm-mc with the AMDGPU target that decodes v_dot4_i32_i8")
class Dot4OpSelListing(unittest.TestCase):
def plain_pair(self):
return assemble("v_dot4_i32_i8 v8, v1, v2, v3")

def test_the_listing_carries_the_op_sel_word_and_the_program_runs(self):
for a, b, addend, measured in MEASURED_OP_SEL:
with self.subTest(a=f"{a:#010x}", b=f"{b:#010x}", addend=f"{addend:#010x}"):
middle = with_op_sel(self.plain_pair(), 2, 5)
code, at = program(a, b, addend, middle)
listing, bad = listing_of("ps_fspx_dot4_op_sel", code)
self.assertEqual(bad, 0, listing)
lines = [ln for ln in listing.splitlines() if "v_dot4_i32_i8" in ln]
self.assertEqual(len(lines), 2, listing)
self.assertIn("v_dot4_i32_i8 v8, v1, v2, v3 op_sel:[0,1,0] op_sel_hi:[1,0,1]", lines[0])
self.assertIn("encoding: [" + ",".join(f"0x{x:02x}" for x in middle) + "]", lines[0])
self.assertNotIn("op_sel", lines[1]) # the plain instruction next to it stays plain
words = support_words(translate_fspx("ps_fspx_dot4_op_sel", listing, code))
self.assertEqual(words, [measured, ref(a, b, addend), measured, ref(a, b, addend)])

def test_other_op_sel_values_stay_undecodable(self):
# Only op_sel 2 / op_sel_hi 5 was measured on hardware; anything else is still rejected, never guessed.
for op_sel, op_sel_hi in ((1, 5), (4, 5), (2, 7), (0, 5), (2, 4)):
with self.subTest(op_sel=op_sel, op_sel_hi=op_sel_hi):
code, _ = program(1, 1, 0, with_op_sel(self.plain_pair(), op_sel, op_sel_hi))
listing, bad = listing_of("ps_fspx_dot4_other", code)
self.assertNotIn("op_sel:[0,1,0] op_sel_hi:[1,0,1]", listing)
with self.assertRaises(rdna2spirv.Unsupported): # undecodable, or printed without a dropped field
translate_fspx("ps_fspx_dot4_other", listing, code)

def test_a_clamp_or_neg_bit_on_the_word_stays_undecodable(self):
for name, shift, dword in (("clamp", 15, 0), ("neg_hi", 8, 0), ("neg_lo", 29, 1)):
with self.subTest(field=name):
middle = list(struct.unpack("<2I", with_op_sel(self.plain_pair(), 2, 5)))
middle[dword] |= 1 << shift
code, _ = program(1, 1, 0, struct.pack("<2I", *middle))
listing, bad = listing_of("ps_fspx_dot4_mods", code)
self.assertGreaterEqual(bad, 1)
self.assertNotIn("op_sel:[0,1,0]", listing)

def test_data_that_looks_like_the_word_is_left_alone(self):
# The same two dwords as a 32-bit literal and the instruction after it decode with no invalid word, so they
# are not touched: only a word llvm-mc rejected is read as v_dot4_i32_i8.
pair = struct.unpack("<2I", with_op_sel(self.plain_pair(), 2, 5))
code = (assemble("v_mov_b32_e32 v4, 0x%08x" % pair[0]) + assemble("v_fmac_legacy_f32 v7, v1, v2") +
assemble("s_endpgm"))
self.assertEqual(struct.unpack_from("<2I", code, 4), pair)
listing, bad = listing_of("ps_fspx_dot4_literal", code)
self.assertEqual(bad, 0, listing)
self.assertNotIn("op_sel", listing)


def support_words(spv):
out = si.run_fragment(spv)
return list(out["%out_mrt0"])


if __name__ == "__main__":
unittest.main()
22 changes: 20 additions & 2 deletions tests/test_translate.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@
import pytest

import rdna2spirv
from conftest import (EMPTY_DXBC, KNOWN_VAL_ISSUES, ROOT, SAMPLE_DXBC, Shader, make_dxbc, mesh_psv0_chunk,
requires_tools, signature_chunk)
from conftest import (EMPTY_DXBC, KNOWN_VAL_ISSUES, ROOT, SAMPLE_DXBC, TEXT_ONLY_MARK, Shader, make_dxbc,
mesh_psv0_chunk, requires_tools, signature_chunk)

pytestmark = requires_tools

Expand Down Expand Up @@ -64,6 +64,24 @@ def test_gpu_samples_translate_and_validate(path, make_shader):
shader.validate(shader.translate(), KNOWN_VAL_ISSUES.get(stem))


def test_text_only_mark_is_spelled_as_in_the_gpu_runner():
"""conftest.Shader and scripts/run_gpu_tests.py have to agree on the comment line that marks a sample llvm-mc
cannot assemble: with two spellings, a marked sample is handed to llvm-mc here and fails."""
runner = Path(ROOT, "scripts", "run_gpu_tests.py").read_text(encoding="utf-8")
assert f'\nTEXT_ONLY_MARK = "{TEXT_ONLY_MARK}"\n' in runner


def test_only_a_marked_sample_skips_llvm_mc(make_shader):
"""A sample with the text-only line becomes its own listing, comment lines dropped, whatever llvm-mc makes of
its instructions; the same lines without it still go to llvm-mc and fail there."""
body = "v_mov_b32 v1, 1.0\n v_no_such_instruction v0, v1\n\ns_endpgm\n"
shader = make_shader(f"; a sample llvm-mc cannot assemble\n{TEXT_ONLY_MARK}\n{body}", "cs_text_only")
assert shader.path.read_text(encoding="utf-8").splitlines()[1:] == [
"\tv_mov_b32 v1, 1.0", "\tv_no_such_instruction v0, v1", "\ts_endpgm"]
with pytest.raises(AssertionError, match="v_no_such_instruction"):
make_shader(body, "cs_not_marked")


@pytest.mark.parametrize("case", sorted(SUPPORTED))
def test_supported_instruction(case, make_shader):
shader = make_shader(program(SUPPORTED[case]))
Expand Down
56 changes: 56 additions & 0 deletions tools/shader_disasm.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@

TRIPLE = "amdgcn--amdpal"
ENDPGM = b"\x00\x00\x81\xbf"
DOT4_I8_OPCODE = 0x16 # VOP3P v_dot4_i32_i8
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

Expand Down Expand Up @@ -97,6 +98,9 @@ def disasm(code: bytes, mcpu: str, backend: str = "llvm-mc", wave32: bool = True
fixed = with_vopc_dpp(code, mcpu, err)
if fixed:
return fixed
fixed = with_dot4_op_sel(code, mcpu, bad, err)
if fixed:
return fixed
return asm, bad, err


Expand Down Expand Up @@ -184,6 +188,58 @@ def with_vopc_dpp(code: bytes, mcpu: str, err: str):
return None


def dot4_op_sel_words(code: bytes, offsets) -> dict:
"""{offset: (word0, word1)} of the dword pairs at `offsets` that are v_dot4_i32_i8 with op_sel 2 and op_sel_hi 5,
no clamp and no neg: the form 89 words of the FidelityFX upscaler's programs take (docs/fspx.md). llvm-mc has no
decoding for it, and a plain v_dot4_i32_i8 has op_sel 0 and op_sel_hi 7. Only this combination is recognised:
its result was measured on hardware (tests/semantic/test_alu_dot4_i8.py), the other op_sel values were not."""
found = {}
for at in sorted(offsets):
if at % 4 or at + 8 > len(code):
continue
w0, w1 = struct.unpack_from("<2I", code, at)
if (w0 >> 23 == 0x198 and (w0 >> 16) & 0x7F == DOT4_I8_OPCODE and (w0 >> 8) & 7 == 0 # VOP3P, neg_hi
and (w0 >> 11) & 7 == 2 and (w0 >> 14) & 1 == 1 and (w0 >> 15) & 1 == 0 # op_sel, hi[2], clamp
and (w1 >> 27) & 3 == 1 and (w1 >> 29) & 7 == 0): # op_sel_hi[1:0], neg_lo
found[at] = (w0, w1)
return found


def with_dot4_op_sel(code: bytes, mcpu: str, bad: int, err: str):
"""The listing of `code` with each rejected v_dot4_i32_i8 op_sel 2 / op_sel_hi 5 word printed as the instruction
it is, or None when there is none. llvm-mc rejects the pair, so it is decoded with the two fields at their
defaults (op_sel 0, op_sel_hi 7), and each such line gets the real fields and the real encoding back: the
translator then reads the instruction and checks its encoding against the blob. A word that is not printed as
v_dot4_i32_i8 at an instruction boundary was not an instruction (it sits in a literal or in data), so it is
left as it was and the pass runs again without it."""
words = dot4_op_sel_words(code, invalid_offsets(err))
while words and bad:
patched = bytearray(code)
for at, (w0, w1) in words.items():
struct.pack_into("<2I", patched, at, w0 & ~(7 << 11), w1 | (2 << 27))
asm, bad2, err2 = run_mc(bytes(patched), mcpu)
if not asm.strip():
return None
invalid, pos, hit, lines = invalid_offsets(err2), 0, set(), []
for line in asm.split("\n"):
enc = ENCODING.search(line)
if not enc:
lines.append(line)
continue
while pos in invalid:
pos += 4
if pos in words and line.lstrip("\t").startswith("v_dot4_i32_i8 "):
hit.add(pos)
w0, w1 = words[pos]
original = ",".join(f"0x{b:02x}" for b in struct.pack("<2I", w0, w1))
line = line[:enc.start()].rstrip() + " op_sel:[0,1,0] op_sel_hi:[1,0,1]"
line = f"{line:<40}; encoding: [{original}]"
lines.append(line)
pos += len(enc.group(1).split(","))
if hit == set(words):
return "\n".join(lines), bad2, err2
words = {at: w for at, w in words.items() if at in hit}
return None
MAX_DATA_DWORDS = 1 << 16


Expand Down
Loading