Skip to content
Merged
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
6 changes: 6 additions & 0 deletions .github/workflows/runtime.yml
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,15 @@ on:
- "tools/lane_masks.py"
- "tools/mc_command.py"
- "tools/mesh_compute_vs.py"
- "tools/native_pso_hashes.py"
- "tools/rdna2_decode.py"
- "tools/rdna2_isa_tables.py"
- "tools/rdna2spirv.py"
- "tools/replace_retry.py"
- "tools/report_paths.py"
- "tools/shader_carve.py"
- "tools/shader_carve_accel.py"
- "tools/shader_carve_native/**"
- "tools/shader_disasm.py"
- "tools/shader_ir.py"
- "tools/shader_meta.py"
Expand Down Expand Up @@ -77,12 +80,15 @@ on:
- "tools/lane_masks.py"
- "tools/mc_command.py"
- "tools/mesh_compute_vs.py"
- "tools/native_pso_hashes.py"
- "tools/rdna2_decode.py"
- "tools/rdna2_isa_tables.py"
- "tools/rdna2spirv.py"
- "tools/replace_retry.py"
- "tools/report_paths.py"
- "tools/shader_carve.py"
- "tools/shader_carve_accel.py"
- "tools/shader_carve_native/**"
- "tools/shader_disasm.py"
- "tools/shader_ir.py"
- "tools/shader_meta.py"
Expand Down
9 changes: 9 additions & 0 deletions docs/d3d12_vulkan.md
Original file line number Diff line number Diff line change
Expand Up @@ -2029,6 +2029,15 @@ without recorded inputs. In that case the runtime accepts any input layout when

### 3.6 Shader identity, PSOs and feature selection

The Xbox native graphics pipeline descriptor identifies stages by the digest in a DXBC HASH part (see
`docs/fspx.md`, kind 7). The shaders stage writes `<work>/shaders/spirv/native_hashes.txt` from the user's
carved DXBC containers and translation index. After the version header, each line contains the 16-byte digest
in lowercase hex, the translated stage and a container path relative to the index, separated by tabs.
Containers sharing a digest must agree on stage and FSSM hash. A collision fails the stage and preserves the
previous catalog. Rerunning the shaders stage checks its source fingerprint, including the catalog writer.
To add or refresh just the catalog in an existing translation, run
`python -I tools/native_pso_hashes.py "<work>/shaders/dxbc" "<work>/shaders/spirv"`.

A D3D12 PSO carries DXBC containers, not SPIR-V. The layer identifies a shader by hashing the **FSSM payload** (the
native RDNA2 program inside the container) and looking it up in a build-time table keyed by `(stage, hash)`. The
build emits that hash for every translation; the runtime extracts the FSSM chunk from the DXBC container the same
Expand Down
30 changes: 28 additions & 2 deletions make_game.py
Original file line number Diff line number Diff line change
Expand Up @@ -1341,12 +1341,37 @@ def shaders(game: str, work: str, jobs: int, emulate: bool = False, keep_emulate
f.write(sources + "\n")
translate(disasm, spirv, jobs, emulate=emulate, fallbacks=fallbacks)
verify_translation_completeness(dxbc, spirv)
native_pso_hashes(dxbc, spirv)
fspx_shaders(game, work, signature, emulate=emulate, fallbacks=fallbacks)
bvh_shaders(game, work, signature, jobs, emulate=emulate, fallbacks=fallbacks)
library_shaders(game, work, signature, jobs, emulate=emulate, fallbacks=fallbacks)
log("shaders: done")


def native_pso_hashes(dxbc: str, spirv: str) -> None:
"""Index the carved containers named by native graphics PSOs, including on a resumed translation."""
import native_pso_hashes as tool

index = os.path.join(spirv, "index.json")
if not os.path.isfile(index) or not os.path.isdir(dxbc):
return
output = os.path.join(spirv, tool.OUT_NAME)
if os.path.isfile(output):
stamp = os.stat(output).st_mtime_ns
inputs = (index, dxbc, os.path.join(dxbc, "index.json"), tool.__file__,
os.path.join(os.path.dirname(tool.__file__), "shader_carve.py"))
if all(not os.path.exists(p) or os.stat(p).st_mtime_ns <= stamp for p in inputs):
with os.scandir(dxbc) as files:
if all(not f.name.endswith(".dxbc") or f.stat().st_mtime_ns <= stamp for f in files):
return
try:
table = tool.build(dxbc, spirv)
tool.write(spirv, table)
except (OSError, ValueError) as error:
fail(f"shaders: could not index native graphics pipelines: {error}")
log(f"shaders: indexed {len(table)} native shader digests")


FSPX_DLL = "amd_fidelityfx_upscaler_xbox.dll"
FSPX_TOOLS = ("fspx_unpack.py", "shader_disasm.py") # with TRANSLATION_SOURCES, what the FSPX outputs come from

Expand Down Expand Up @@ -1805,11 +1830,12 @@ def runtime_gpu_max_push_constants():
return int(v) if isinstance(v, int) and not isinstance(v, bool) and v > 0 else None


# Source and data files that produce the translated modules, metadata and partner stubs.
# Source and data files that produce the translated modules, metadata, partner stubs and native PSO catalog.
TRANSLATION_SOURCES = ("rdna2spirv.py", "shader_ir.py", "cfg_structure.py", "file_mode.py", "fssm_header.py", "lane_masks.py", "wave64_halves.py",
"wave64_emulate_opt.py", "shader_meta.py", "spirv_stubs.py", "spirv_asm.py", "spirv_asm_tables.py",
"spirv_opt.py", "report_paths.py", "replace_retry.py", "fssm_unpack.py", "shader_stage_manifest.py",
"rdna2_decode.py", "rdna2_isa_tables.py", "gfx10_formats.json")
"rdna2_decode.py", "rdna2_isa_tables.py", "gfx10_formats.json",
"native_pso_hashes.py", "shader_carve.py", "shader_carve_accel.py")


def sources_digest(folder: str, names, lead: str = "") -> str:
Expand Down
9 changes: 6 additions & 3 deletions runtime/cmake/translator_deps.cmake
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# What the SPIR-V that test/shaders/build.py writes comes from, besides the .asm files: build.py and the modules it
# imports, the scripts it runs (tools/rdna2spirv.py, and tools/vk_subgroup_info.py, whose answer picks
# --bary-fallback), and every module rdna2spirv.py imports or file it reads (make_game.py's TRANSLATION_SOURCES).
# The shader fixtures use test/shaders/build.py, its local imports and the scripts it runs (tools/rdna2spirv.py
# and tools/vk_subgroup_info.py, whose answer picks --bary-fallback). Track the shader-stage dependencies in
# make_game.py's TRANSLATION_SOURCES here too, including the native PSO catalog writer.
# Every add_custom_command that runs build.py DEPENDS on this list, so an edit to a helper such as tools/spirv_asm.py
# rebuilds the test shaders instead of leaving the last build's SPIR-V in place (BUILD-1064).
# tests/test_cmake_translator_deps.py fails when an import is missing here or a build.py rule doesn't use the list.
Expand All @@ -16,11 +16,14 @@ set(LEONIDA_TRANSLATOR_DEPS
${_leonida_repo}/tools/gfx10_formats.json
${_leonida_repo}/tools/lane_masks.py
${_leonida_repo}/tools/mc_command.py
${_leonida_repo}/tools/native_pso_hashes.py
${_leonida_repo}/tools/rdna2_decode.py
${_leonida_repo}/tools/rdna2_isa_tables.py
${_leonida_repo}/tools/rdna2spirv.py
${_leonida_repo}/tools/replace_retry.py
${_leonida_repo}/tools/report_paths.py
${_leonida_repo}/tools/shader_carve.py
${_leonida_repo}/tools/shader_carve_accel.py
${_leonida_repo}/tools/shader_ir.py
${_leonida_repo}/tools/shader_meta.py
${_leonida_repo}/tools/shader_stage_manifest.py
Expand Down
2 changes: 1 addition & 1 deletion tests/test_bvh_shaders_stage.py
Original file line number Diff line number Diff line change
Expand Up @@ -386,7 +386,7 @@ def fake_py(tool_name, *args):

def fake_translate(disasm, spirv, jobs, emulate=False, fallbacks=()):
ran.append("translate")
write("", spirv, "index.json")
write('{"shader": {"stage": "vs"}}', spirv, "index.json")

def stage():
ran.clear()
Expand Down
14 changes: 8 additions & 6 deletions tests/test_cmake_translator_deps.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
They used to list only build.py, compute_fixture.py, rdna2spirv.py and their .asm files, so an edit to a module the
translator imports (tools/spirv_asm.py, spirv_asm_tables.py, shader_ir.py, ...) left the last build's SPIR-V in place
(old #3752, BUILD-1064). The rules now depend on LEONIDA_TRANSLATOR_DEPS (runtime/cmake/translator_deps.cmake); this
checks that list against what build.py reaches. No compiler needed; the cmake -P case is skipped without cmake.
checks the imports of build.py and the native catalog writer. No compiler is needed. The cmake -P check runs when
cmake is on PATH.
"""
import ast
import os
Expand Down Expand Up @@ -33,11 +34,12 @@ def listed():


def reached():
"""build.py, the tools scripts it runs (named by a string literal) and every local module they import."""
"""build.py, the scripts it runs, the native shader catalog and their transitive local imports."""
tree = ast.parse(BUILD_PY.read_text(encoding="utf-8"))
todo = [BUILD_PY] + [TOOLS / n.value for n in ast.walk(tree)
if isinstance(n, ast.Constant) and isinstance(n.value, str)
and n.value.endswith(".py") and (TOOLS / n.value).is_file()]
todo = [BUILD_PY, TOOLS / "native_pso_hashes.py"]
todo.extend(TOOLS / n.value for n in ast.walk(tree)
if isinstance(n, ast.Constant) and isinstance(n.value, str)
and n.value.endswith(".py") and (TOOLS / n.value).is_file())
seen = set()
while todo:
path = todo.pop()
Expand All @@ -60,7 +62,7 @@ def reached():


class TranslatorDepsTest(unittest.TestCase):
def test_the_list_covers_every_local_module_build_py_reaches(self):
def test_the_list_covers_build_py_and_native_catalog_imports(self):
self.assertEqual({p for p in listed() if p.endswith(".py")}, reached())

def test_the_list_has_the_data_files_the_translator_reads(self):
Expand Down
4 changes: 3 additions & 1 deletion tests/test_fspx_shaders_stage.py
Original file line number Diff line number Diff line change
Expand Up @@ -382,7 +382,9 @@ def fake_py(tool, *args):

def fake_translate(disasm, spirv, jobs, emulate=False, fallbacks=()):
ran.append("translate")
touch(spirv, "index.json")
os.makedirs(spirv, exist_ok=True)
with open(os.path.join(spirv, "index.json"), "w", encoding="utf-8") as f:
json.dump({"shader": {"stage": "vs"}}, f)

def stage():
ran.clear()
Expand Down
2 changes: 2 additions & 0 deletions tests/test_make_game_translator_flags.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,8 @@ def touch(self, *parts):
json.dump([{"file": "shader.dxbc"}], f)
elif p == os.path.join(self.dxbc, "fssm_index.json"):
json.dump([{"name": "shader"}], f)
elif p == os.path.join(self.spirv, "index.json"):
json.dump({"shader": {"stage": "vs"}}, f)
elif p.endswith(".s"):
f.write("synthetic listing\n")

Expand Down
140 changes: 140 additions & 0 deletions tests/test_native_pso_hashes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
"""tools/native_pso_hashes.py on hand-built DXBC containers and indexes: no game data."""
import json
import os
import struct
import sys
import tempfile
import unittest
from unittest import mock

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "tools"))
import native_pso_hashes as tool # noqa: E402
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import make_game # noqa: E402


def container(digest: bytes, other=b"") -> bytes:
"""A DXBC container with a HASH part (flags 0, then the digest) and an optional second part."""
parts = [b"HASH" + struct.pack("<I", 20) + struct.pack("<I", 0) + digest]
if other:
parts.insert(0, b"PRIV" + struct.pack("<I", len(other)) + other)
head = 32 + 4 * len(parts)
offsets, at = [], head
for p in parts:
offsets.append(at)
at += len(p)
body = b"DXBC" + bytes(16) + struct.pack("<II", 1, at) + struct.pack("<I", len(parts))
return body + b"".join(struct.pack("<I", o) for o in offsets) + b"".join(parts)


class NativePsoHashesTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.dxbc = os.path.join(self.tmp.name, "shaders", "dxbc")
self.spirv = os.path.join(self.tmp.name, "shaders", "spirv")
os.makedirs(self.dxbc)
os.makedirs(self.spirv)

def tearDown(self):
self.tmp.cleanup()

def put(self, name, data):
with open(os.path.join(self.dxbc, name + ".dxbc"), "wb") as f:
f.write(data)

def index(self, entries):
with open(os.path.join(self.spirv, "index.json"), "w", encoding="utf-8", newline="\n") as f:
json.dump(entries, f)

def read(self):
with open(os.path.join(self.spirv, tool.OUT_NAME), encoding="utf-8") as f:
return f.read().splitlines()

def test_stage_builds_missing_catalog_and_refreshes_changed_translation(self):
d = bytes(range(16))
self.put("one", container(d))
self.index({"one": {"stage": "vs", "fssm_sha256": "a" * 64}})
with mock.patch.object(tool, "build", wraps=tool.build) as build:
make_game.native_pso_hashes(self.dxbc, self.spirv)
self.assertEqual(build.call_count, 1)
self.assertIn(d.hex() + "\tvs\t../dxbc/one.dxbc", self.read())
make_game.native_pso_hashes(self.dxbc, self.spirv)
self.assertEqual(build.call_count, 1)
self.index({})
old = os.path.join(self.spirv, tool.OUT_NAME)
os.utime(old, (1, 1))
make_game.native_pso_hashes(self.dxbc, self.spirv)
self.assertEqual(build.call_count, 2)
self.assertEqual(self.read(), [tool.HEADER])

def test_replacing_one_container_refreshes_the_digest(self):
self.index({"one": {"stage": "ps", "fssm_sha256": "a" * 64}})
self.put("one", container(bytes(16)))
make_game.native_pso_hashes(self.dxbc, self.spirv)
stamp = os.stat(os.path.join(self.spirv, tool.OUT_NAME)).st_mtime_ns
changed = bytes([5]) * 16
self.put("one", container(changed))
os.utime(os.path.join(self.dxbc, "one.dxbc"), ns=(stamp, stamp + 1000000000))
make_game.native_pso_hashes(self.dxbc, self.spirv)
self.assertEqual(self.read()[1], changed.hex() + "\tps\t../dxbc/one.dxbc")

def test_malformed_translator_identity(self):
self.put("one", container(bytes(16)))
for stage, fssm in (("ps\tvs", "a" * 64), ("vs", "short")):
with self.subTest(stage=stage, fssm=fssm):
self.index({"one": {"stage": stage, "fssm_sha256": fssm}})
with self.assertRaisesRegex(ValueError, "invalid translated stage or FSSM hash"):
tool.build(self.dxbc, self.spirv)

def test_digest_of_a_container(self):
d = bytes(range(16))
self.assertEqual(tool.hash_digest(container(d)), d)
self.assertEqual(tool.hash_digest(container(d, b"x" * 9)), d)
self.assertIsNone(tool.hash_digest(b"DXBC" + bytes(28)))
self.assertIsNone(tool.hash_digest(container(d)[:-1]))
self.assertIsNone(tool.hash_digest(b"FSSM" + bytes(60)))

def test_map_lines(self):
a, b, c = bytes([1] * 16), bytes([2] * 16), bytes([3] * 16)
self.put("vs one", container(a))
self.put(".ms_dot", container(b))
self.put("same_a", container(a, b"other")) # another container with digest a and the same program
self.put("untranslated", container(c))
self.put("not_dxbc", b"nothing")
self.index({"vs one": {"stage": "vs", "fssm_sha256": "1" * 64}, ".ms_dot": {"stage": "ms", "fssm_sha256": "2" * 64},
"same_a": {"stage": "vs", "fssm_sha256": "1" * 64}, "not_dxbc": {"stage": "ps", "fssm_sha256": "3" * 64}})
self.assertEqual(tool.main(["x", self.dxbc, self.spirv]), 0)
lines = self.read()
self.assertEqual(lines[0], tool.HEADER)
self.assertEqual(lines[1:], [f"{a.hex()}\tvs\t../dxbc/same_a.dxbc", f"{b.hex()}\tms\t../dxbc/.ms_dot.dxbc"])
with open(os.path.join(self.spirv, tool.OUT_NAME), "rb") as f:
self.assertNotIn(b"\r", f.read())

def test_a_digest_with_two_programs_does_not_publish_a_partial_map(self):
a = bytes([7] * 16)
self.put("one", container(a))
self.put("two", container(a, b"x"))
self.index({"one": {"stage": "ps", "fssm_sha256": "1" * 64}, "two": {"stage": "ps", "fssm_sha256": "2" * 64}})
with open(os.path.join(self.spirv, tool.OUT_NAME), "w", encoding="utf-8", newline="\n") as f:
f.write("stale\n")
with self.assertRaises(tool.DigestClash):
tool.build(self.dxbc, self.spirv)
self.assertEqual(tool.main(["x", self.dxbc, self.spirv]), 1)
self.assertEqual(self.read(), ["stale"])

def test_no_index(self):
self.assertEqual(tool.main(["x", self.dxbc, self.spirv]), 1)
self.assertEqual(tool.main(["x"]), 2)

def test_a_shared_digest_requires_the_same_stage(self):
shared = container(bytes([9]) * 16)
self.put("one", shared)
self.put("two", shared)
self.index({name: {"stage": stage, "fssm_sha256": "1" * 64}
for name, stage in (("one", "vs"), ("two", "ps"))})
with self.assertRaises(tool.DigestClash):
tool.build(self.dxbc, self.spirv)


if __name__ == "__main__":
unittest.main()
8 changes: 6 additions & 2 deletions tests/test_shader_stage_resume.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,10 @@ def touch(self, *parts):
json.dump([{"file": "s0.dxbc"}], f)
elif p == os.path.join(self.dxbc, "fssm_index.json"):
json.dump([{"name": "s0"}], f)
elif p == os.path.join(self.spirv, "index.json"):
with open(os.path.join(self.dxbc, "index.json"), encoding="utf-8") as source:
carved = json.load(source)
json.dump({os.path.splitext(entry["file"])[0]: {"stage": "vs"} for entry in carved}, f)
elif p.endswith(".s"):
f.write("synthetic listing\n")

Expand Down Expand Up @@ -528,8 +532,8 @@ def test_a_kill_right_after_a_merge_for_new_sources_keeps_the_translation(self):


class TranslationSourcesTest(unittest.TestCase):
def test_the_list_covers_every_local_module_the_translator_imports(self):
seen, todo = set(), ["rdna2spirv"]
def test_the_list_covers_the_translator_and_native_catalog_imports(self):
seen, todo = set(), ["rdna2spirv", "native_pso_hashes"]
while todo:
name = todo.pop()
if name in seen:
Expand Down
Loading