From 51fc8e0b13acad07cd05032d9d0cf2abe75f4e1f Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Thu, 26 Nov 2026 01:28:44 +0200 Subject: [PATCH 001/240] shader: add offset, short-read, and regular-file guards in sgd5_effects with CLI suite (#2608) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 3 + tests/sgd5_effects_cli_check.py | 447 ++++++++++++++++++++++++++++++++ tools/sgd5_effects.py | 16 +- 3 files changed, 463 insertions(+), 3 deletions(-) create mode 100644 tests/sgd5_effects_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 5a367699d..f04ee8e85 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8891,6 +8891,9 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/awc_metadata_cli_check.py") add_test(NAME sgd5_effect_candidates COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/sgd5_effects_check.py") + add_test(NAME shader_sgd5_effects_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/sgd5_effects_cli_check.py") + set_tests_properties(shader_sgd5_effects_cli_check PROPERTIES TIMEOUT 60) add_test(NAME rdna2_tools_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/rdna2_tools_check.py") add_test(NAME rdna2_cli_checks COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/sgd5_effects_cli_check.py b/tests/sgd5_effects_cli_check.py new file mode 100644 index 000000000..297c69e9c --- /dev/null +++ b/tests/sgd5_effects_cli_check.py @@ -0,0 +1,447 @@ +"""CLI, path-guard, short-read, error-handling, and mutation suite for tools/sgd5_effects.py.""" + +import argparse +from contextlib import redirect_stderr, redirect_stdout +import hashlib +import io +import json +from pathlib import Path +import runpy +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory +import unittest +from unittest import mock +import zlib + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "sgd5_effects.py" +sys.path.insert(0, str(ROOT / "tools")) + +import sgd5_effects # noqa: E402 + + +def _word(value: int) -> bytes: + return struct.pack(" bytes: + encoded = text.encode("ascii") + b"\0" + return bytes([len(encoded)]) + encoded + + +def _deflate_raw(blob: bytes, mode: int = zlib.Z_FINISH) -> bytes: + compressor = zlib.compressobj(wbits=-15) + return compressor.compress(blob) + compressor.flush(mode) + + +def _program_record(label: str, kind: int, identity: int, *, pack=_deflate_raw) -> tuple[bytes, str]: + dxil = struct.pack(" bytes: + lists = b"".join(_word(len(group)) + b"".join(map(_word, group)) for group in (vs, ps, [], [], [], [])) + strings = b"\0entry\0" + return _len_name(label) + _word(0) + lists + b"\xff\xff" + _word(len(strings)) + strings + + +def _build_archive(prefix_len: int = 0) -> tuple[bytes, int, int, int, int, int, str, str]: + vs0, vs_digest = _program_record("vs_main", 1, 101) + ps0, ps_digest = _program_record("ps_main", 0, 202) + arrays = _word(1) + vs0 + _word(1) + ps0 + _word(0) * 4 + first = _effect_record("idle", [], []) + second = _effect_record("draw", [0], [0]) + header = bytes(prefix_len) + b"SGD5" + bytes(28) + arrays_start = len(header) + first_start = arrays_start + len(arrays) + 4 + second_start = first_start + len(first) + archive = header + arrays + _word(2) + first + second + return archive, prefix_len, len(archive), arrays_start, second_start, len(archive), vs_digest, ps_digest + + +def _run_main(argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = sgd5_effects.main(argv) + except SystemExit as exc: + raw = exc.code + code = 0 if raw is None else (int(raw) if isinstance(raw, int) else 2) + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class Sgd5EffectsCliPositiveTests(unittest.TestCase): + def test_cli_zero_and_hex_offsets_exact_json_schema(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + for label, prefix_len, fmt_offset in ( + ("zero_group_start", 0, str), + ("hex_offsets", 16, hex), + ): + with self.subTest(label=label): + data, grp_start, grp_end, arrays, rec_start, rec_end, vs_digest, ps_digest = _build_archive( + prefix_len + ) + archive = root / f"{label}.bin" + archive.write_bytes(data) + argv = [ + str(archive), + "draw", + "--group", + fmt_offset(grp_start), + fmt_offset(grp_end), + "--arrays", + fmt_offset(arrays), + "--record", + fmt_offset(rec_start), + fmt_offset(rec_end), + ] + expected = { + "effect": "draw", + "candidates": [ + { + "group": "VS", + "index": 0, + "name": "vs_main", + "dxil_kind": 1, + "container_sha256": vs_digest, + }, + { + "group": "PS", + "index": 0, + "name": "ps_main", + "dxil_kind": 0, + "container_sha256": ps_digest, + }, + ], + } + + code, out, err = _run_main(argv) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + doc = json.loads(out) + self.assertEqual(set(doc), {"effect", "candidates"}) + self.assertEqual(doc, expected) + for item in doc["candidates"]: + self.assertEqual(set(item), {"group", "index", "name", "dxil_kind", "container_sha256"}) + + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stderr, "") + self.assertEqual(json.loads(proc.stdout), expected) + + self.assertEqual(sorted(p.name for p in root.iterdir()), ["hex_offsets.bin", "zero_group_start.bin"]) + + def test_main_sys_argv_and_script_entrypoint(self) -> None: + with TemporaryDirectory() as tmp: + data, grp_start, grp_end, arrays, rec_start, rec_end, _, _ = _build_archive(0) + archive = Path(tmp) / "entry.bin" + archive.write_bytes(data) + cli_argv = [ + str(TOOL), + str(archive), + "draw", + "--group", + str(grp_start), + str(grp_end), + "--arrays", + str(arrays), + "--record", + str(rec_start), + str(rec_end), + ] + + with mock.patch.object(sys, "argv", cli_argv): + code, out, err = _run_main(None) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertEqual(len(json.loads(out)["candidates"]), 2) + + stdout, stderr = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", cli_argv), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertIs(type(exited.exception.code), int) + self.assertEqual(exited.exception.code, 0) + self.assertEqual(stderr.getvalue(), "") + self.assertEqual(len(json.loads(stdout.getvalue())["candidates"]), 2) + + +class Sgd5EffectsCliNegativeAndMutationTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_code: int = 1, + expected_fragment: str, + check_subprocess: bool = True, + ) -> None: + code, out, err = _run_main(argv) + self.assertEqual(code, expected_code, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertIn(expected_fragment.lower(), err.lower()) + + if check_subprocess: + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertIn(expected_fragment.lower(), proc.stderr.lower()) + + def test_py314_safe_argparse_errors_exit_nonzero_without_traceback(self) -> None: + with TemporaryDirectory() as tmp: + data, grp_start, grp_end, arrays, rec_start, rec_end, _, _ = _build_archive(0) + archive = Path(tmp) / "valid.bin" + archive.write_bytes(data) + base_argv = [ + str(archive), + "draw", + "--group", + str(grp_start), + str(grp_end), + "--arrays", + str(arrays), + "--record", + str(rec_start), + str(rec_end), + ] + for label, argv, frag in ( + ("missing_all_args", [], "usage:"), + ("missing_required_flags", [str(archive), "draw"], "required"), + ("non_integer_arrays", [str(archive), "draw", "--group", "0", "1", "--arrays", "bad", "--record", "0", "1"], "invalid"), + ("unknown_flag", [*base_argv, "--unknown-flag"], "unrecognized"), + ): + with self.subTest(case=label): + with self.assertRaises(SystemExit) as exited: + with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()): + sgd5_effects.main(argv) + self.assertNotEqual(exited.exception.code, 0) + self._assert_clean_failure(argv, expected_code=2, expected_fragment=frag) + + def test_negative_offsets_rejected_by_offset_parser_before_opening_archive(self) -> None: + self.assertEqual(sgd5_effects.offset("0"), 0) + self.assertEqual(sgd5_effects.offset("0x20"), 32) + for raw in ("-1", "-0x1", "-16"): + with self.subTest(raw=raw): + with self.assertRaises(argparse.ArgumentTypeError): + sgd5_effects.offset(raw) + + with TemporaryDirectory() as tmp: + data, grp_start, grp_end, arrays, rec_start, rec_end, _, _ = _build_archive(0) + existing = Path(tmp) / "existing.bin" + existing.write_bytes(data) + missing = Path(tmp) / "missing.bin" + + for archive in (existing, missing): + for label, bad_argv in ( + ("neg_group_start", [str(archive), "draw", "--group", "-1", str(grp_end), "--arrays", str(arrays), "--record", str(rec_start), str(rec_end)]), + ("neg_group_end", [str(archive), "draw", "--group", str(grp_start), "-1", "--arrays", str(arrays), "--record", str(rec_start), str(rec_end)]), + ("neg_arrays", [str(archive), "draw", "--group", str(grp_start), str(grp_end), "--arrays=-0x1", "--record", str(rec_start), str(rec_end)]), + ("neg_record_start", [str(archive), "draw", "--group", str(grp_start), str(grp_end), "--arrays", str(arrays), "--record", "-1", str(rec_end)]), + ("neg_record_end", [str(archive), "draw", "--group", str(grp_start), str(grp_end), "--arrays", str(arrays), "--record", str(rec_start), "-0x10"]), + ): + with self.subTest(archive=archive.name, case=label): + with mock.patch.object( + sgd5_effects, + "candidates", + side_effect=AssertionError("candidates called for negative offset"), + ): + self._assert_clean_failure( + bad_argv, + expected_code=2, + expected_fragment="non-negative", + ) + + def test_non_file_and_missing_archive_rejected_upfront_before_candidates(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + dir_path = root / "archive_dir" + dir_path.mkdir() + missing_path = root / "missing.bin" + + for label, bad_archive in ( + ("directory", str(dir_path)), + ("empty_cwd_dir", ""), + ("missing_file", str(missing_path)), + ): + with self.subTest(case=label): + argv = [ + bad_archive, + "draw", + "--group", + "0", + "64", + "--arrays", + "32", + "--record", + "48", + "64", + ] + with mock.patch.object( + sgd5_effects, + "candidates", + side_effect=AssertionError(f"candidates called for invalid archive {label}"), + ): + self._assert_clean_failure( + argv, + expected_code=1, + expected_fragment="regular file", + check_subprocess=bool(bad_archive), + ) + + def test_cursor_short_and_overlong_reads_and_negative_skip_rejected(self) -> None: + class _FakeView: + def __init__(self, payload: bytes) -> None: + self._payload = payload + + def read(self, offset: int, length: int) -> bytes: + return self._payload + + for label, payload, request in ( + ("empty_short_read", b"", 4), + ("partial_short_read", b"abc", 4), + ("overlong_read", b"abcde", 4), + ): + with self.subTest(case=label): + cursor = sgd5_effects.Cursor(_FakeView(payload), 0, 16) + with self.assertRaisesRegex(ValueError, "Truncated"): + cursor.read(request) + + neg_cursor = sgd5_effects.Cursor(_FakeView(b"abcd"), 4, 16) + with self.assertRaisesRegex(ValueError, "Negative"): + neg_cursor.skip(-1) + self.assertEqual(neg_cursor.pos, 4) + + with TemporaryDirectory() as tmp: + data, grp_start, grp_end, arrays, rec_start, rec_end, _, _ = _build_archive(0) + archive = Path(tmp) / "short_read.bin" + archive.write_bytes(data) + argv = [ + str(archive), + "draw", + "--group", + str(grp_start), + str(grp_end), + "--arrays", + str(arrays), + "--record", + str(rec_start), + str(rec_end), + ] + with mock.patch.object(sgd5_effects.PagedResource, "read", side_effect=[b"SGD5", b"SG"]): + self._assert_clean_failure( + argv, + expected_code=1, + expected_fragment="Truncated", + check_subprocess=False, + ) + + def test_os_value_struct_and_zlib_errors_caught_without_traceback(self) -> None: + with TemporaryDirectory() as tmp: + data, grp_start, grp_end, arrays, rec_start, rec_end, _, _ = _build_archive(0) + archive = Path(tmp) / "probe.bin" + archive.write_bytes(data) + argv = [ + str(archive), + "draw", + "--group", + str(grp_start), + str(grp_end), + "--arrays", + str(arrays), + "--record", + str(rec_start), + str(rec_end), + ] + + # Real corrupt archive checks via both in-process main() and subprocess. + bad_magic = bytearray(data) + bad_magic[0:4] = b"BAD!" + bad_magic_path = Path(tmp) / "bad_magic.bin" + bad_magic_path.write_bytes(bad_magic) + self._assert_clean_failure( + [str(bad_magic_path), *argv[1:]], + expected_code=1, + expected_fragment="Missing SGD5 group header", + ) + + vs_bad, _ = _program_record("vs_main", 1, 101, pack=lambda blob: b"\xff" * len(_deflate_raw(blob))) + ps0, _ = _program_record("ps_main", 0, 202) + bad_arrays = _word(1) + vs_bad + _word(1) + ps0 + _word(0) * 4 + draw_effect = _effect_record("draw", [0], [0]) + bad_zlib_bytes = ( + b"SGD5" + + bytes(28) + + bad_arrays + + _word(2) + + _effect_record("idle", [], []) + + draw_effect + ) + bad_zlib_path = Path(tmp) / "bad_zlib.bin" + bad_zlib_path.write_bytes(bad_zlib_bytes) + self._assert_clean_failure( + [ + str(bad_zlib_path), + "draw", + "--group", + "0", + str(len(bad_zlib_bytes)), + "--arrays", + "32", + "--record", + str(len(bad_zlib_bytes) - len(draw_effect)), + str(len(bad_zlib_bytes)), + ], + expected_code=1, + expected_fragment="Invalid compressed SGD5 candidate", + ) + + # Direct error-tuple mutation controls for (OSError, ValueError, struct.error, zlib.error). + for exc in ( + OSError("simulated read error"), + ValueError("simulated validation error"), + struct.error("unpack requires a buffer of 12 bytes"), + zlib.error("Error -3 while decompressing data"), + ): + with self.subTest(exc=type(exc).__name__): + with mock.patch.object(sgd5_effects, "candidates", side_effect=exc): + self._assert_clean_failure( + argv, + expected_code=1, + expected_fragment=str(exc), + check_subprocess=False, + ) + + self.assertEqual( + sorted(p.name for p in Path(tmp).iterdir()), + ["bad_magic.bin", "bad_zlib.bin", "probe.bin"], + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/sgd5_effects.py b/tools/sgd5_effects.py index c485ec52f..f0c851ec1 100644 --- a/tools/sgd5_effects.py +++ b/tools/sgd5_effects.py @@ -23,6 +23,8 @@ def __init__(self, view: PagedResource, start: int, end: int): self.end = end def skip(self, size: int) -> int: + if size < 0: + raise ValueError("Negative SGD5 field size") start = self.pos if size > self.end - start: raise ValueError("SGD5 field exceeds supplied range") @@ -30,7 +32,10 @@ def skip(self, size: int) -> int: return start def read(self, size: int) -> bytes: - return self.view.read(self.skip(size), size) + data = self.view.read(self.skip(size), size) + if len(data) != size: + raise ValueError("Truncated SGD5 field") + return data def word(self) -> int: return int.from_bytes(self.read(4), "little") @@ -158,7 +163,10 @@ def candidates(stream: BinaryIO, name: str, group_start: int, group_end: int, ar def offset(value: str) -> int: - return int(value, 0) + parsed = int(value, 0) + if parsed < 0: + raise argparse.ArgumentTypeError(f"Expected non-negative offset, got {value}") + return parsed def main(argv: Sequence[str] | None = None) -> int: @@ -172,10 +180,12 @@ def main(argv: Sequence[str] | None = None) -> int: help="Physical bounds of the selected effect, including its final name block") args = parser.parse_args(argv) try: + if not args.archive.is_file(): + raise ValueError(f"Expected an existing regular file: {args.archive}") with args.archive.open("rb") as stream: found = candidates(stream, args.effect, *args.group, args.arrays, *args.record) print(json.dumps({"effect": args.effect, "candidates": [asdict(item) for item in found]}, indent=2)) - except (OSError, ValueError) as exc: + except (OSError, ValueError, struct.error, zlib.error) as exc: sys.stderr.write(f"{args.archive}: {exc}\n") return 1 return 0 From 0858991042594da908c6f039c8be866855d0eaad Mon Sep 17 00:00:00 2001 From: JVProg <100954822+JVProg@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:29:12 +0100 Subject: [PATCH 002/240] startup: count new view records by slot behind an opt-in census (#2613) X2W_D3D12_VIEW_CENSUS=1 counts new distinct view records by device slot and logs the record vector capacity and hash bucket count before an insertion that is expected to grow either. Record identity, ids and descriptor binding do not change. Refs #1199 Co-authored-by: Claude Sonnet 5.5 --- CMakeLists.txt | 28 +++ docs/startup-runtime.md | 43 ++++ src/startup_stubs/d3d12_capture.inl | 54 +++++ src/startup_stubs/d3d12_xs_device.cpp | 22 ++ tests/startup_view_census.cpp | 288 ++++++++++++++++++++++++++ 5 files changed, 435 insertions(+) create mode 100644 tests/startup_view_census.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index f04ee8e85..23e414ed9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1371,6 +1371,34 @@ foreach(backend IN ITEMS warp hardware) endforeach() +# X2W_D3D12_VIEW_CENSUS=1 counts new distinct view records by slot and logs capacity and buckets before they grow. +# `off` runs without the switch (nothing reported); `vary` is the negative control: the repeated stream is made distinct, +# and the fixture must say so. +add_executable(startup_view_census tests/startup_view_census.cpp) +target_compile_features(startup_view_census PRIVATE cxx_std_17) +target_link_libraries(startup_view_census PRIVATE d3d12_xs_shim d3d12 dxgi psapi) +foreach(backend IN ITEMS warp hardware) + foreach(mode IN ITEMS on off vary) + set(census_env "X2W_D3D12_BUDGET=1;X2W_D3D12_PERMISSIVE=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=0") + list(APPEND census_env "X2W_TRAP_LOG=${CMAKE_CURRENT_BINARY_DIR}/startup_view_census_${mode}_${backend}.log") + if(NOT mode STREQUAL "off") + list(APPEND census_env "X2W_D3D12_VIEW_CENSUS=1") + endif() + if(mode STREQUAL "on") + set(census_test startup_view_census_${backend}) + add_test(NAME ${census_test} COMMAND startup_view_census ${backend}) + else() + set(census_test startup_view_census_${mode}_${backend}) + add_test(NAME ${census_test} COMMAND startup_view_census ${backend} ${mode}) + endif() + set_tests_properties(${census_test} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77 ENVIRONMENT "${census_env}") + if(mode STREQUAL "vary") + set_tests_properties(${census_test} PROPERTIES + PASS_REGULAR_EXPRESSION "FAIL: the repeated stream added records") + endif() + endforeach() +endforeach() + add_executable(startup_resource_retire_title tests/startup_resource_retire_title.cpp) target_include_directories(startup_resource_retire_title PRIVATE src) target_compile_features(startup_resource_retire_title PRIVATE cxx_std_17) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 1353b96e3..e38af186e 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1349,6 +1349,7 @@ ctest --preset dev --no-tests=error -R '^startup_trap_header(_prefix_control|_pr | `X2W_D3D12_RELEASE_RETIRED=1` | opt-in, effective with `X2W_D3D12_RENDER=1` only (the list handlers that record holds exist only there): frees the desktop object of a released committed 2D texture of one narrow class once no recorded list, submission or release-time fence refers to it ([details](#d3d12-resource-budget)). Unset, nothing changes | | `X2W_D3D12_RELEASE_RETIRED_VIEWS=1` | opt-in, effective only together with `X2W_D3D12_RELEASE_RETIRED=1`: a released class texture that only tracked slot-18 descriptor slots keep alive (the title never overwrites them) is freed once those slots are replaced by null descriptors ([details](#d3d12-resource-budget)). Unset, nothing changes | | `X2W_D3D12_RETIRE_REASONS=1` | diagnostic only, effective with `X2W_D3D12_RELEASE_RETIRED=1` and `X2W_D3D12_BUDGET=1`: adds one `x2w-retire held:` line to the heartbeat that counts final-released resources whose desktop object is still alive, by reason ([details](#d3d12-resource-budget)). Unset, nothing is recorded | +| `X2W_D3D12_VIEW_CENSUS=1` | diagnostic only: counts new distinct view records by device slot (a heartbeat line), and logs the record vector capacity and hash bucket count before either grows ([details](#d3d12-view-census)). Unset, nothing is counted or logged | | `X2W_DRAW_NULL_IDENTITY=1` | null descriptors read as identity values instead of zero | | `X2W_DEPTH_STATE=1` | translated draws of slot 57 pipelines take their depth-stencil state and stencil reference from state block A instead of the desktop default (depth and stencil off); a refused block keeps the default. Off by default, then nothing changes: see [Shortcuts that are known to be wrong](#shortcuts-that-are-known-to-be-wrong) | | `X2W_PRESENT_SIGNATURE_EVERY=` | in render mode, samples a coarse signature of the presented picture every `n` presents from the start, without a script request (`0` off). Unset, sampling starts, every 4 presents, only once a script with a `wait` asks for it: see [Waiting for the presented picture](#waiting-for-the-presented-picture) | @@ -1534,6 +1535,48 @@ FALSE without the switch, like `x2w_d3d12_budget_snapshot`. `startup_resource_re runs the same steps without the switch. The hardware cases report 77 without a physical adapter, and the debug-layer cases report 77 where the debug layer is not installed. +## D3D12 view census + +The stand-in keeps one record per distinct view: slot, resource, counter, +description bytes and whether the desktop view was created. Records are not +removed. `X2W_D3D12_VIEW_CENSUS=1` shows which slot adds them. It changes no +record, id or descriptor binding. + +The heartbeat adds a line: + +`x2w-view-census distinct by slot: cbv= srv= uav= rtv= dsv= sampler= records= capacity= ids= buckets= grows-records= grows-ids= missed=` + +- `cbv` to `sampler`: new records from device slots 17 to 22. +- `records`, `capacity`: size and capacity of the record vector. +- `ids`, `buckets`: size and bucket count of the hash map from content to id. + +Before an insertion that is expected to grow either container, the same fields +are logged as `x2w-view-census before growth of `, +with the slot of the new record. The values are those before the growth. The line +is written before the allocation, so it is in the log when that allocation fails, +also when no further heartbeat follows. The growth is predicted: from the +vector's capacity, and for the map from the MSVC rehash rule (the new size over +the bucket count exceeds the maximum load factor). `missed` counts capacity or +bucket changes that no line announced. + +The census counts distinct byte contents, not distinct views. It does not say +why two records differ (for example a changing address, or description bytes +that the view type does not use), and it does not measure the size of the +containers in bytes or reduce it. + +`startup_view_census_` calls slots 17, 18 and 22 of the device. +A repeated descriptor must add no record and grow nothing. A stream of 200,000 +distinct constant buffer views, 3,000 buffer SRVs and 100 samplers must be +counted by slot, with one log line per announced growth. Both streams run under +a job commit limit 256 MiB above the commit held after setup. `off` checks that +nothing is reported without the switch; in `vary` the repeated stream changes +every call, and the fixture must fail. Slots 19 to 21 are not exercised. + +```powershell +cmake --build --preset dev --target startup_view_census +ctest --preset dev --no-tests=error -R "^startup_view_census" -V +``` + ## Input script `X2W_INPUT_SCRIPT` (`run.ps1 -InputScript`) drives the virtual gamepad of the `GameInput.dll` diff --git a/src/startup_stubs/d3d12_capture.inl b/src/startup_stubs/d3d12_capture.inl index 6f92733f0..2b51942e8 100644 --- a/src/startup_stubs/d3d12_capture.inl +++ b/src/startup_stubs/d3d12_capture.inl @@ -61,6 +61,33 @@ std::vector& view_materialized() { static std::vector& view_ids() { static std::unordered_map m; return m; } // content hash -> view id LONG64 views_noted, views_distinct, descriptors_copied; +// X2W_D3D12_VIEW_CENSUS=1 (diagnostic only, docs/startup-runtime.md): new distinct view records by slot, and one line +// before an insertion that is expected to grow view_records or the view_ids buckets. All fields: note_lock held. +bool view_census_enabled() +{ + static const bool on = x2w_local::env_on("X2W_D3D12_VIEW_CENSUS"); + return on; +} +struct ViewCensus { + u64 distinct[6]; // slots 17..22 + u64 grows_records, grows_ids; // growths announced + u64 missed; // capacity or bucket count changed without an announcement +}; +ViewCensus view_census{}; + +std::size_t view_census_format(char* out, std::size_t capacity, const char* what) +{ + const ViewCensus& c = view_census; + const int n = std::snprintf(out, capacity, + "x2w-view-census %s: cbv=%llu srv=%llu uav=%llu rtv=%llu dsv=%llu sampler=%llu records=%llu capacity=%llu " + "ids=%llu buckets=%llu grows-records=%llu grows-ids=%llu missed=%llu", + what, c.distinct[0], c.distinct[1], c.distinct[2], c.distinct[3], c.distinct[4], c.distinct[5], + static_cast(view_records().size()), static_cast(view_records().capacity()), + static_cast(view_ids().size()), static_cast(view_ids().bucket_count()), + c.grows_records, c.grows_ids, c.missed); + return n < 0 ? 0 : (std::min)(static_cast(n), capacity - 1); +} + // The shadow entry for a desktop CPU descriptor handle (note_lock held), or null. std::uint32_t* shadow_slot(u64 desktop_handle, std::uint32_t* room = nullptr) { @@ -306,10 +333,37 @@ void note_view(int slot, u64 resource, u64 counter, const void* desc, std::size_ record.id = found->second; } else { record.id = static_cast(view_records().size()); + const bool census = view_census_enabled(); + std::size_t capacity_before = 0, buckets_before = 0; + bool records_full = false, ids_full = false; + if (census) { + capacity_before = view_records().capacity(); + buckets_before = view_ids().bucket_count(); + records_full = view_records().size() == capacity_before; + // MSVC's rule: unordered_map rehashes when the new size would exceed the maximum load factor. + ids_full = static_cast(view_ids().size() + 1) / static_cast(buckets_before) > + view_ids().max_load_factor(); + // Logged before the allocation, so the last line survives an allocation that fails. + if (records_full || ids_full) { + view_census.grows_records += records_full; + view_census.grows_ids += ids_full; + char line[640]; + view_census_format(line, sizeof(line), + records_full && ids_full ? "before growth of records and ids" + : records_full ? "before growth of records" + : "before growth of ids"); + log("%s (new slot %u)", line, record.slot); + } + } view_records().push_back(record); view_materialized().push_back(created); view_ids()[hash] = record.id; ++views_distinct; + if (census) { + if (record.slot >= 17 && record.slot <= 22) ++view_census.distinct[record.slot - 17]; + view_census.missed += !records_full && view_records().capacity() != capacity_before; + view_census.missed += !ids_full && view_ids().bucket_count() != buckets_before; + } } if (std::uint32_t* slot_ptr = shadow_slot(dest_desktop)) { const std::uint32_t prev = *slot_ptr; diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index f92272d09..50a37c5aa 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -5288,6 +5288,24 @@ extern "C" __declspec(dllexport) std::size_t x2w_d3d12_retire_reasons_line(char* return retire_reasons_line(out, capacity); } +// The census heartbeat line, or an empty string when X2W_D3D12_VIEW_CENSUS is not set. +std::size_t view_census_line(char* out, std::size_t capacity) +{ + if (!out || !capacity) return 0; + out[0] = 0; + if (!view_census_enabled()) return 0; + AcquireSRWLockShared(¬e_lock); + const std::size_t used = view_census_format(out, capacity, "distinct by slot"); + ReleaseSRWLockShared(¬e_lock); + return used; +} + +// Fixture export (startup_view_census): the line the heartbeat logs, now. +extern "C" __declspec(dllexport) std::size_t x2w_d3d12_view_census_line(char* out, std::size_t capacity) +{ + return view_census_line(out, capacity); +} + // Fixture probe (startup_resource_retire): what still names a resource of the class by its raw desktop pointer, how many // resources the open recording of a list moved out of COMMON, and how many it holds. Counts entries only. struct RetireProbe { @@ -6070,6 +6088,10 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa "(region-information proofs %lld, region queries %lld)", views_noted, views_distinct, descriptors_copied, static_cast(heap_infos().size()), static_cast(placed_buffer_calls), static_cast(placed_buffer_region_info), static_cast(placed_buffer_queries)); + { + char line[640]; + if (view_census_line(line, sizeof(line))) log("%s", line); + } { LARGE_INTEGER frequency; QueryPerformanceFrequency(&frequency); diff --git a/tests/startup_view_census.cpp b/tests/startup_view_census.cpp new file mode 100644 index 000000000..d11b99cfd --- /dev/null +++ b/tests/startup_view_census.cpp @@ -0,0 +1,288 @@ +// X2W_D3D12_VIEW_CENSUS=1 (docs/startup-runtime.md#d3d12-view-census): the stand-in counts new distinct view records +// by slot and logs the vector capacity and hash bucket count before an insertion that grows either. The fixture compares +// a stream of one repeated descriptor with a stream of distinct descriptors, both through the real device view slots +// and both under a job commit limit set above what the process holds after setup. +// +// startup_view_census [off|vary] +// (X2W_D3D12_BUDGET=1 X2W_D3D12_PERMISSIVE=1 X2W_D3D12_RENDER=1 X2W_D3D12_VIEW_CENSUS=1 X2W_TRAP_LOG=) +// "off" runs without X2W_D3D12_VIEW_CENSUS: nothing may be reported or logged. "vary" is the negative control: +// the stream meant to repeat one descriptor changes it every call, which the fixture must report as a failure. +#include + +#include +#include +#include +#include + +#include +#include +#include +#include + +using Microsoft::WRL::ComPtr; + +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); +extern "C" __declspec(dllimport) std::size_t x2w_d3d12_view_census_line(char*, std::size_t); + +namespace { + +constexpr unsigned long long headroom = 256ull << 20; // job commit limit above the commit held after setup +constexpr UINT repeated_calls = 200000; +constexpr UINT distinct_buffers = 200000; // slot 17 +constexpr UINT distinct_views = 3000; // slot 18 +constexpr UINT distinct_samplers = 100; // slot 22 + +template +Result invoke(IUnknown* object, unsigned slot, Args... args) +{ + using Call = Result (WINAPI*)(IUnknown*, Args...); + return reinterpret_cast((*reinterpret_cast(object))[slot])(object, args...); +} + +bool require(HRESULT hr, const char* stage) +{ + if (FAILED(hr)) std::printf("FAIL: %s hr=0x%08lx\n", stage, static_cast(hr)); + return SUCCEEDED(hr); +} + +ComPtr pick_adapter(IDXGIFactory4* factory, bool warp) +{ + ComPtr adapter; + if (warp) { + factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)); + return adapter; + } + wchar_t name[128]{}; + GetEnvironmentVariableW(L"XBOX2WINDOWS_ADAPTER", name, static_cast(std::size(name))); + for (UINT i = 0; factory->EnumAdapters1(i, &adapter) == S_OK; ++i, adapter.Reset()) { + DXGI_ADAPTER_DESC1 desc{}; + if (SUCCEEDED(adapter->GetDesc1(&desc)) && !(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && + (!name[0] || std::wcsstr(desc.Description, name)) && + SUCCEEDED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) + return adapter; + } + return nullptr; +} + +unsigned long long process_commit() +{ + PROCESS_MEMORY_COUNTERS_EX counters{}; + if (!GetProcessMemoryInfo(GetCurrentProcess(), reinterpret_cast(&counters), sizeof(counters))) + return 0; + return counters.PrivateUsage; +} + +// Puts this process in its own job with a commit limit. The job lives until the process ends. +bool limit_commit(unsigned long long limit) +{ + const HANDLE job = CreateJobObjectW(nullptr, nullptr); + JOBOBJECT_EXTENDED_LIMIT_INFORMATION info{}; + info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_JOB_MEMORY; + info.JobMemoryLimit = static_cast(limit); + return job && SetInformationJobObject(job, JobObjectExtendedLimitInformation, &info, sizeof(info)) && + AssignProcessToJobObject(job, GetCurrentProcess()); +} + +struct Census { + unsigned long long cbv, srv, uav, rtv, dsv, sampler, records, capacity, ids, buckets, grows_records, grows_ids, missed; +}; + +bool read_census(Census& c, const char* stage) +{ + char line[1024]{}; + if (!x2w_d3d12_view_census_line(line, sizeof(line))) { + std::printf("FAIL: %s: the census line is empty although the switch is on\n", stage); + return false; + } + const int fields = std::sscanf(line, + "x2w-view-census distinct by slot: cbv=%llu srv=%llu uav=%llu rtv=%llu dsv=%llu sampler=%llu records=%llu " + "capacity=%llu ids=%llu buckets=%llu grows-records=%llu grows-ids=%llu missed=%llu", + &c.cbv, &c.srv, &c.uav, &c.rtv, &c.dsv, &c.sampler, &c.records, &c.capacity, &c.ids, &c.buckets, + &c.grows_records, &c.grows_ids, &c.missed); + std::printf("%s: %s\n", stage, line); + if (fields != 13) std::printf("FAIL: %s: unreadable census line (%d fields)\n", stage, fields); + return fields == 13; +} + +bool check(bool ok, const char* what) +{ + if (!ok) std::printf("FAIL: %s\n", what); + return ok; +} + +std::string read_log() +{ + wchar_t path[MAX_PATH]; + const DWORD length = GetEnvironmentVariableW(L"X2W_TRAP_LOG", path, MAX_PATH); + std::string text; + if (!length || length >= MAX_PATH) return text; + const HANDLE file = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + if (file == INVALID_HANDLE_VALUE) return text; + char chunk[4096]; + DWORD got = 0; + while (ReadFile(file, chunk, sizeof(chunk), &got, nullptr) && got) text.append(chunk, got); + CloseHandle(file); + return text; +} + +unsigned long long occurrences(const std::string& text, const char* needle) +{ + unsigned long long count = 0; + for (std::size_t at = text.find(needle); at != std::string::npos; at = text.find(needle, at + 1)) ++count; + return count; +} + +struct Streams { + IUnknown* guest; + UINT64 view_handle, sampler_handle; + + void constant_buffer(UINT index) const + { + const D3D12_CONSTANT_BUFFER_VIEW_DESC desc{0x100000ull + 256ull * index, 256}; + invoke(guest, 17, &desc, view_handle); + } + void buffer_view(UINT index) const + { + D3D12_SHADER_RESOURCE_VIEW_DESC desc; + std::memset(&desc, 0, sizeof(desc)); // padding is part of the record's content + desc.Format = DXGI_FORMAT_R32_FLOAT; + desc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + desc.Buffer.FirstElement = index; + desc.Buffer.NumElements = 1; + invoke(guest, 18, static_cast(nullptr), &desc, view_handle); + } + void sampler(UINT index) const + { + D3D12_SAMPLER_DESC desc{}; + desc.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR; + desc.AddressU = desc.AddressV = desc.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; + desc.MipLODBias = static_cast(index) / 16.0f; + desc.MaxAnisotropy = 1; + desc.ComparisonFunc = D3D12_COMPARISON_FUNC_ALWAYS; + desc.MaxLOD = D3D12_FLOAT32_MAX; + invoke(guest, 22, &desc, sampler_handle); + } +}; + +bool scenario(const Streams& s, bool vary) +{ + // One of each first, so the repeated stream starts from records that already exist. + s.constant_buffer(0); + s.buffer_view(0); + s.sampler(0); + Census start{}, repeated{}, distinct{}; + if (!read_census(start, "start")) return false; + + const unsigned long long before_repeated = process_commit(); + for (UINT i = 0; i < repeated_calls; ++i) s.constant_buffer(vary ? i : 0); + for (UINT i = 0; i < distinct_views; ++i) s.buffer_view(0); + const unsigned long long after_repeated = process_commit(); + if (!read_census(repeated, "repeated")) return false; + if (!check(repeated.records == start.records && repeated.cbv == start.cbv && repeated.srv == start.srv && + repeated.sampler == start.sampler, + "the repeated stream added records")) + return false; + if (!check(repeated.capacity == start.capacity && repeated.buckets == start.buckets && + repeated.grows_records == start.grows_records && repeated.grows_ids == start.grows_ids, + "the repeated stream grew a container")) + return false; + + for (UINT i = 1; i <= distinct_buffers; ++i) s.constant_buffer(i); + for (UINT i = 1; i <= distinct_views; ++i) s.buffer_view(i); + for (UINT i = 1; i <= distinct_samplers; ++i) s.sampler(i); + const unsigned long long after_distinct = process_commit(); + if (!read_census(distinct, "distinct")) return false; + std::printf("commit bytes: repeated stream %+lld, distinct stream %+lld\n", + static_cast(after_repeated - before_repeated), + static_cast(after_distinct - after_repeated)); + if (!check(distinct.cbv - repeated.cbv == distinct_buffers, "slot 17 count") || + !check(distinct.srv - repeated.srv == distinct_views, "slot 18 count") || + !check(distinct.sampler - repeated.sampler == distinct_samplers, "slot 22 count") || + !check(!distinct.uav && !distinct.rtv && !distinct.dsv, "a slot without calls has records") || + !check(distinct.records - repeated.records == distinct_buffers + distinct_views + distinct_samplers, + "record total") || + !check(distinct.ids == distinct.records, "ids and records differ") || + !check(distinct.capacity >= distinct.records, "capacity below size") || + !check(distinct.grows_records > repeated.grows_records, "no vector growth announced") || + !check(distinct.grows_ids > repeated.grows_ids, "no bucket growth announced") || + !check(!distinct.missed, "a container grew without an announcement")) + return false; + + // Every announced growth has its log line. + const std::string log = read_log(); + const unsigned long long both = occurrences(log, "x2w-view-census before growth of records and ids:"); + const unsigned long long records = occurrences(log, "x2w-view-census before growth of records:") + both; + const unsigned long long ids = occurrences(log, "x2w-view-census before growth of ids:") + both; + std::printf("growth lines in the log: records %llu, ids %llu\n", records, ids); + return check(records == distinct.grows_records && ids == distinct.grows_ids, "growth lines and counters differ"); +} + +// With the switch off the same calls report nothing. +bool nothing_reported(const Streams& s) +{ + for (UINT i = 0; i < 1000; ++i) s.constant_buffer(i); + char line[256]; + std::memset(line, 'x', sizeof(line)); + const std::size_t length = x2w_d3d12_view_census_line(line, sizeof(line)); + return check(!length && !line[0], "the census reported without its switch") && + check(!occurrences(read_log(), "x2w-view-census"), "the census logged without its switch"); +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc < 2 || argc > 3 || (std::strcmp(argv[1], "warp") && std::strcmp(argv[1], "hardware")) || + (argc == 3 && std::strcmp(argv[2], "off") && std::strcmp(argv[2], "vary"))) + return 2; + const bool off = argc == 3 && !std::strcmp(argv[2], "off"); + const bool vary = argc == 3 && !std::strcmp(argv[2], "vary"); + char value[2]{}; + const bool census_on = GetEnvironmentVariableA("X2W_D3D12_VIEW_CENSUS", value, sizeof(value)) == 1 && value[0] == '1'; + wchar_t log_path[MAX_PATH]; + const DWORD log_length = GetEnvironmentVariableW(L"X2W_TRAP_LOG", log_path, MAX_PATH); + if (census_on == off || !log_length || log_length >= MAX_PATH) { + std::puts("FAIL: the environment does not match the requested mode"); + return 2; + } + DeleteFileW(log_path); // before the stand-in writes its first line + + ComPtr factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 3; + const auto adapter = pick_adapter(factory.Get(), std::strcmp(argv[1], "warp") == 0); + if (!adapter) return 77; + ComPtr guest, views, samplers; + std::array parameters{}; + if (!require(D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), + reinterpret_cast(guest.GetAddressOf())), "Xbox device")) + return 3; + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 backing, bytes; + } view_heap{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1}, 0, 0}, sampler_heap{{D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 1}, 0, 0}; + if (!require(invoke(guest.Get(), 14, &view_heap, &__uuidof(ID3D12DescriptorHeap), views.GetAddressOf()), "view heap") || + !require(invoke(guest.Get(), 14, &sampler_heap, &__uuidof(ID3D12DescriptorHeap), samplers.GetAddressOf()), "sampler heap")) + return 3; + const Streams streams{guest.Get(), invoke(views.Get(), 9), invoke(samplers.Get(), 9)}; + + const unsigned long long held = process_commit(); + if (!held || !limit_commit(held + headroom)) { + std::printf("FAIL: could not set the job commit limit (error %lu)\n", GetLastError()); + return 4; + } + // The limit is real: a commit larger than the room under it is refused. + if (void* too_much = VirtualAlloc(nullptr, static_cast(headroom + held), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)) { + VirtualFree(too_much, 0, MEM_RELEASE); + std::puts("FAIL: the job commit limit did not refuse an allocation above it"); + return 4; + } + DXGI_ADAPTER_DESC1 adapter_desc{}; + if (SUCCEEDED(adapter->GetDesc1(&adapter_desc))) std::printf("adapter=%ls\n", adapter_desc.Description); + std::printf("mode=%s, commit after setup %llu bytes, job limit %llu bytes\n", off ? "off" : vary ? "vary" : "on", held, + held + headroom); + if (!(off ? nothing_reported(streams) : scenario(streams, vary))) return 5; + std::puts(off ? "view-census off checks passed" : "view-census checks passed"); + return 0; +} From 99ed51fd998a3e7a5546288fed414beabd1d4815 Mon Sep 17 00:00:00 2001 From: dnn <55638248+denn0x@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:30:04 +0000 Subject: [PATCH 003/240] startup: lower v_pack_b32_f16 with op_sel and neg/abs in gfx2hlsl (#2475) * startup: lower v_pack_b32_f16 with op_sel and neg/abs in gfx2hlsl D[15:0] = S0.f16, D[31:16] = S1.f16 (AMD RDNA 2 ISA, VOP3 V_PACK_B32_F16). op_sel[i] selects the high half of source i (LLVM 15: VOP3_OPSEL); neg and abs act on bit 15 of the selected half, abs first. The halves are copied as bits, as pixel_aot lowers the same instruction; no binary16 denormal flush or NaN quieting is modelled (assumed). Register sources only: an inline float constant on a binary16 operand is a binary16 value. A destination op_sel bit and clamp are refused. Test: tests/startup_gfx2hlsl_pack_b32_f16_check.py evaluates the emitted expression for every op_sel x abs x neg combination over sample register pairs against a bit reference (2304 cases), plus an SGPR source. Negative controls: swapped halves and neg-before-abs are caught by the reference; without the handler the instruction is refused, as on main. * gfx2hlsl: explain the low/high half reads and the strict op_sel spelling in v_pack_b32_f16 (comments only) * tests: verify packed binary16 output words on D3D12 --------- Co-authored-by: Royoo <3230853833@qq.com> Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- .github/workflows/windows.yml | 1 + AGENTS.md | 1 + CMakeLists.txt | 9 ++ tests/startup_gfx2hlsl_pack_b32_f16_check.py | 141 +++++++++++++++++++ tools/startup/gfx2hlsl.py | 38 +++++ 5 files changed, 190 insertions(+) create mode 100644 tests/startup_gfx2hlsl_pack_b32_f16_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 71eb71905..ef7f3e5e6 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -308,6 +308,7 @@ jobs: tests/startup_gfx2hlsl_mul_hi_check.py \ tests/startup_gfx2hlsl_sad_check.py \ tests/startup_gfx2hlsl_scalar_brev_fold_check.py \ + tests/startup_gfx2hlsl_pack_b32_f16_check.py \ tests/startup_inline_sampler_check.py \ tests/startup_buffer_address_check.py \ tests/startup_buffer_format_word3_table_check.py \ diff --git a/AGENTS.md b/AGENTS.md index 89516ec2a..f9a68ef8d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -249,6 +249,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_f32_nan_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_sopk_signext_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_scalar_brev_fold_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_pack_b32_f16_check.py ./out/pe-env/bin/python -B tests/run_checks_parallel_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_handler_arity_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_getpc_refusal_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 23e414ed9..522a02a4a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3250,6 +3250,9 @@ if(EXISTS "${INTAKE_PYTHON}") # s_brev_b32 of a known constant folds to a known word (a sampler built from it is a constant descriptor). add_test(NAME startup_gfx2hlsl_scalar_brev_fold COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_scalar_brev_fold_check.py") + # v_pack_b32_f16 with op_sel and the neg/abs source modifiers, evaluated against a bit reference. + add_test(NAME startup_gfx2hlsl_pack_b32_f16 COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_pack_b32_f16_check.py") # Scalar sign-extends and conditional moves (batch 3 #2). add_test(NAME startup_gfx2hlsl_s_sext_cmov COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_sext_cmov_check.py") @@ -3420,6 +3423,12 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_gfx2hlsl_cvt_pk_u8_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) endforeach() + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_pack_b32_f16_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_pack_b32_f16_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_pack_b32_f16_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl v_cvt_pk_u16_u32 and v_cvt_pk_i16_i32 (#1723): VOP3A saturating 16-bit integer packs, encoding/refusal # controls, and WARP/hardware draws (FXC 5_1 and DXC 6_0) with four mutations per opcode. add_test(NAME startup_gfx2hlsl_cvt_pk_int16_controls COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/startup_gfx2hlsl_pack_b32_f16_check.py b/tests/startup_gfx2hlsl_pack_b32_f16_check.py new file mode 100644 index 000000000..071eddee7 --- /dev/null +++ b/tests/startup_gfx2hlsl_pack_b32_f16_check.py @@ -0,0 +1,141 @@ +"""v_pack_b32_f16 (VOP3) in tools/startup/gfx2hlsl.py: D[15:0] = S0.f16, D[31:16] = S1.f16 (AMD RDNA 2 ISA). + +Synthetic VOP3 words (gfx10 opcode 0x311; op_sel in word 0 bits 14:11, abs in bits 10:8, clamp in bit 15, neg in +word 1 bits 31:29). The decoder reads each word back, and the test asserts the printed op_sel and modifier forms. +The emitted expression is evaluated in Python for every op_sel[0..1] x abs x neg combination over sample register +pairs. The reference written here selects the half (op_sel[i] = high half of source i), then applies abs (clear +bit 15) and then neg (flip bit 15). An SGPR source is accepted. +Controls (refused): a destination op_sel bit, clamp, an inline float constant and an inline integer source. +Negative controls: an expression with the halves swapped, or with neg applied before abs, is caught by the +reference; without op_v_pack_b32_f16 the instruction is refused, as on main. +The draw mode checks raw integer readback under DXC and FXC and rejects a lowering that omits negation. +""" +import re +import struct +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools' / 'startup')) +import gfx2hlsl as G # noqa: E402 + + +class Pipe: + root = {'params': [], 'flags': 0} + + def ud(self, source): + return 0 + + +def vop3(vdst, s0, s1, opsel=0, absm=0, neg=0, clamp=0): + """s0 and s1 are 9-bit source fields: 256 + n is vN, n < 106 is sN, 128..208 and 240..248 inline constants.""" + return [0xd4000000 | 0x311 << 16 | clamp << 15 | opsel << 11 | absm << 8 | vdst, s0 | s1 << 9 | neg << 29] + + +def one(words): + s = G.Stage(Pipe(), 'vs', b'') + s.lines, s.pc = [], 0 + _, _, name, text = G.decode(struct.pack('<2I', *words))[0] + s.one(name, text) + return text, s.lines + + +def ev(expr, env): + py = re.sub(r'(0x[0-9a-f]+|\d+)u\b', r'\1', expr) + return eval(py, {}, env) & 0xffffffff + + +def ref(a, b, sel, absm, neg, neg_first=False): + out = [] + for i, x in enumerate((a, b)): + h = (x >> 16) & 0xffff if sel >> i & 1 else x & 0xffff + if neg_first and neg >> i & 1: + h ^= 0x8000 + if absm >> i & 1: + h &= 0x7fff + if not neg_first and neg >> i & 1: + h ^= 0x8000 + out.append(h) + return out[0] | out[1] << 16 + + +VALUES = [0x00000000, 0x3c00bc00, 0x80017fff, 0xfc007e00, 0x12345678, 0xffff0001] + + +def refused(words, why): + try: + one(words) + except G.Unsupported as error: + assert why in str(error), str(error) + else: + raise AssertionError('accepted: %s' % why) + + +def main(): + cases = 0 + for sel in range(4): + for absm in range(4): + for neg in range(4): + text, lines = one(vop3(3, 257, 258, sel, absm, neg)) + assert text.startswith('v_pack_b32_f16 v3, '), text + assert ('op_sel:[%d,%d,0]' % (sel & 1, sel >> 1) in text) == bool(sel), text + m = re.fullmatch(r'v3 = (.*);', lines[0]) + assert m and len(lines) == 1, lines + for a in VALUES: + for b in VALUES: + got = ev(m.group(1), {'v1': a, 'v2': b}) + assert got == ref(a, b, sel, absm, neg), (text, hex(a), hex(b), hex(got)) + cases += 1 + if absm and neg & absm: + # The modifier order matters only where both act: the wrong order must be caught. + assert any(ev(m.group(1), {'v1': a, 'v2': b}) != ref(a, b, sel, absm, neg, neg_first=True) + for a in VALUES for b in VALUES), text + text, lines = one(vop3(3, 5, 258, 1)) # SGPR source, high half + assert text == 'v_pack_b32_f16 v3, s5, v2 op_sel:[1,0,0]', text + assert all(ev(lines[0][len('v3 = '):-1], {'s5': a, 'v2': b}) == ref(a, b, 1, 0, 0) + for a in VALUES for b in VALUES), lines + _, lines = one(vop3(3, 257, 258, 1)) + swapped = re.fullmatch(r'v3 = (.*) \| \((.*) << 16\);', lines[0]) + wrong = '%s | (%s << 16)' % (swapped.group(2), swapped.group(1)) + assert any(ev(wrong, {'v1': a, 'v2': b}) != ref(a, b, 1, 0, 0) for a in VALUES for b in VALUES) + refused(vop3(3, 257, 258, 4), 'v_pack_b32_f16 form') + refused(vop3(3, 257, 258, clamp=1), 'v_pack_b32_f16 modifier clamp') + refused(vop3(3, 242, 258), 'v_pack_b32_f16 source 1.0') + refused(vop3(3, 129, 258), 'v_pack_b32_f16 source 1') + saved = G.Stage.op_v_pack_b32_f16 + del G.Stage.op_v_pack_b32_f16 + try: + refused(vop3(3, 257, 258), 'v_pack_b32_f16') + finally: + G.Stage.op_v_pack_b32_f16 = saved + print('pack_b32_f16: %d (op_sel, abs, neg, value) cases match the reference; SGPR source accepted; swapped ' + 'halves and neg-before-abs caught; destination op_sel, clamp and constants refused; refused without the ' + 'handler' % cases) + + +def draw_cases(dxc, renderer, adapter, fxc=None): + from startup_gfx2hlsl_lane_alu import check_draw + + op = 'v_pack_b32_f16' + # The selected halves cover zeros, subnormals, infinities and NaN payloads as integer bits. + values = [ + (0x0000bc00, 0xa5a58000, 0), (0x80017e00, 0xf0f00001, 0), + (0xfc008001, 0xabcd7d55, 0), (0x7d337c00, 0xdcba7c00, 0), + ] + body = b''.join(struct.pack('<2I', *vop3(12 + lane, 256 + lane, 260 + lane, 1, 1, 1)) + for lane in range(4)) + family = { + 'ops': {op: (2, lambda a, b: ref(a, b, 1, 1, 1), False)}, + 'draw': {op: values}, + 'body': {op: body}, + 'mutations': {op: (r' \^ 0x8000u', '', lambda a, b: ref(a, b, 1, 1, 0))}, + 'accepted': [], + 'refused': [], + } + check_draw(family, dxc, renderer, adapter, fxc) + + +if __name__ == '__main__': + if len(sys.argv) > 1 and sys.argv[1] == 'draw': + draw_cases(*sys.argv[2:]) + else: + main() diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index a19e68b69..11a1552af 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -5289,6 +5289,44 @@ def op_v_cvt_i32_f32(self, ops, mods): dst = reg_range(ops[0])[1] self.set_v(dst, 'uint(int(F(%s)))' % self.u(ops[1])) + def op_v_pack_b32_f16(self, ops, mods): + """D[15:0] = S0.f16, D[31:16] = S1.f16 (AMD RDNA 2 ISA, VOP3 V_PACK_B32_F16). + + op_sel[i] selects the high half of source i (LLVM 15 VOP3Instructions.td: V_PACK_B32_F16 is VOP3_OPSEL). + The neg and abs source modifiers act on the sign bit (bit 15) of the selected half, abs first. The halves + are copied as bits, like pixel_aot's lowering of the same instruction: no binary16 denormal flush and no + NaN quieting is modelled (an assumption, not measured). Register sources only: an inline float constant + on a binary16 operand is a binary16 value, not the binary32 word u() would give. A destination op_sel bit + and clamp are refused, and so is any modifier other than the one op_sel:[a,b,c] spelling the decoder + prints.""" + sel = [0, 0, 0] + for m in mods: + match = re.fullmatch(r'op_sel:\[([01]),([01]),([01])\]', m) + if not match: + raise Unsupported('v_pack_b32_f16 modifier %s' % m) + sel = [int(x) for x in match.groups()] + dst = reg_range(ops[0]) if ops else None + if sel[2] or len(ops) != 3 or not dst or dst[0] != 'v' or dst[1] != dst[2]: + raise Unsupported('v_pack_b32_f16 form %s %s' % (', '.join(ops), ' '.join(mods))) + halves = [] + for i, tok in enumerate(ops[1:3]): + neg = tok.startswith('-') and not re.match(r'-[\d.]', tok) + tok = tok[1:] if neg else tok + absolute = tok.startswith('|') and tok.endswith('|') + tok = tok[1:-1] if absolute else tok + reg = reg_range(tok) + if not reg or reg[1] != reg[2] or reg[0] not in ('v', 's'): + raise Unsupported('v_pack_b32_f16 source %s' % ops[1 + i]) + # The high half needs the whole word; the low half reads only bits 15:0, so a register whose high half + # is undefined (after an odd-count d16 load) stays readable here. + half = '(%s >> 16)' % self.u(tok) if sel[i] else '(%s & 0xffffu)' % self.u(tok, low16_only=True) + if absolute: + half = '(%s & 0x7fffu)' % half + if neg: + half = '(%s ^ 0x8000u)' % half + halves.append(half) + self.set_v(dst[1], '%s | (%s << 16)' % (halves[0], halves[1])) + def op_v_cvt_pk_u8_f32(self, ops, mods): # VOP3A opcode 350 of the RDNA 1.0 and RDNA 2 ISA guides: # D = (S2 & ~(0xff << 8 * S1[1:0])) | ((flt32_to_uint8(S0) & 0xff) << 8 * S1[1:0]) From d371ce46c57bf972f225616d462f99486f323f77 Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Thu, 26 Nov 2026 01:31:05 +0200 Subject: [PATCH 004/240] cpu: lower 16 VEX.256 AVX2 cross-lane extend and dword/qword unpack forms (#2614) --- CMakeLists.txt | 23 ++ tests/cpu/avx_int_regs_check.py | 15 +- tests/cpu/avx_int_ymm_abs_sign_shuf_check.py | 4 +- tests/cpu/avx_int_ymm_widen_unpack.asm | 301 +++++++++++++++ tests/cpu/avx_int_ymm_widen_unpack.def | 25 ++ tests/cpu/avx_int_ymm_widen_unpack_check.py | 383 +++++++++++++++++++ tools/cpu_avx_int_aot.py | 136 +++++-- 7 files changed, 838 insertions(+), 49 deletions(-) create mode 100644 tests/cpu/avx_int_ymm_widen_unpack.asm create mode 100644 tests/cpu/avx_int_ymm_widen_unpack.def create mode 100644 tests/cpu/avx_int_ymm_widen_unpack_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 522a02a4a..a0ad7738b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -5329,6 +5329,29 @@ if(EXISTS "${INTAKE_PYTHON}") set_tests_properties(cpu_aot_avx_int_ymm_pack PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/cpu_aot_avx_int_ymm_pack.txt") + # cpu_avx_int_ymm_widen_unpack_checks + set(cpu_avx_int_ymm_widen_unpack_exports + "op_vpmovsxbw_ymm,op_vpmovsxbd_ymm,op_vpmovsxbq_ymm,op_vpmovsxwd_ymm,op_vpmovsxwq_ymm,op_vpmovsxdq_ymm," + "op_vpmovzxbw_ymm,op_vpmovzxbd_ymm,op_vpmovzxbq_ymm,op_vpmovzxwd_ymm,op_vpmovzxwq_ymm,op_vpmovzxdq_ymm," + "op_vpunpckldq_ymm,op_vpunpckhdq_ymm,op_vpunpcklqdq_ymm,op_vpunpckhqdq_ymm," + "op_vpmovsxbd_ymm_stale_dst,op_vpmovsxbw_ymm_alias,op_vpmovzxdq_ymm_alias," + "op_vpunpckldq_ymm_dst_src1,op_vpunpckhqdq_ymm_dst_src2,op_vpunpckhdq_ymm_all," + "op_vpmovsxwd_ymm_then_xmm_vpunpcklqdq,op_chain_ymm_widen_unpack") + string(CONCAT cpu_avx_int_ymm_widen_unpack_exports ${cpu_avx_int_ymm_widen_unpack_exports}) + foreach(variant IN ITEMS original altered) + cpu_asm_fixture(cpu_avx_int_ymm_widen_unpack_${variant} avx_int_ymm_widen_unpack) + cpu_translation(cpu_avx_int_ymm_widen_unpack_${variant} cpu_avx_int_aot "${cpu_avx_int_ymm_widen_unpack_exports}") + endforeach() + target_compile_definitions(cpu_avx_int_ymm_widen_unpack_altered PRIVATE ALTER_YMM) + add_test(NAME cpu_aot_avx_int_ymm_widen_unpack COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/cpu/avx_int_ymm_widen_unpack_check.py" + "$" + "$" + "$" + "$") + set_tests_properties(cpu_aot_avx_int_ymm_widen_unpack PROPERTIES + SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/cpu_aot_avx_int_ymm_widen_unpack.txt") set(cpu_avx_move_exports "op_andpd_xmm,op_andpd_ymm,op_andps_xmm,op_andps_ymm,op_andnpd_xmm,op_andnpd_ymm," "op_andnps_xmm,op_andnps_ymm,op_orpd_xmm,op_orpd_ymm,op_orps_xmm,op_orps_ymm," diff --git a/tests/cpu/avx_int_regs_check.py b/tests/cpu/avx_int_regs_check.py index c683c53ab..3a0d0d098 100644 --- a/tests/cpu/avx_int_regs_check.py +++ b/tests/cpu/avx_int_regs_check.py @@ -707,21 +707,22 @@ def check_rejections(original_path): # 1) VEX.L=1 (256-bit) packed-integer encodings of surviving forms must be rejected explicitly (AVX2, not AVX1). # The 256-bit add, subtract, saturating add and subtract, compare, minimum, maximum, absolute value, - # sign, word shuffle, horizontal, and pack forms are lowered and are covered by avx_int_ymm_addsub_check.py, - # avx_int_ymm_sat_check.py, avx_int_ymm_minmax_check.py, avx_int_ymm_abs_sign_shuf_check.py, - # avx_int_ymm_horizontal_check.py, and avx_int_ymm_pack_check.py. + # sign, word shuffle, horizontal, pack, cross-lane extend, and dword/qword unpack forms are lowered and + # covered by avx_int_ymm_addsub_check.py, avx_int_ymm_sat_check.py, avx_int_ymm_minmax_check.py, + # avx_int_ymm_abs_sign_shuf_check.py, avx_int_ymm_horizontal_check.py, avx_int_ymm_pack_check.py, + # and avx_int_ymm_widen_unpack_check.py. vex256_int_cases = [ ("vpmulhuw_ymm", Instruction.create_reg_reg_reg(Code.VEX_VPMULHUW_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2)), - ("vpunpckhdq_ymm", Instruction.create_reg_reg_reg(Code.VEX_VPUNPCKHDQ_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2)), + ("vpsrld_ymm_imm", Instruction.create_reg_reg_u32(Code.VEX_VPSRLD_YMM_YMM_IMM8, R.YMM0, R.YMM1, 4)), ("vpalignr_ymm", Instruction.create_reg_reg_reg_u32(Code.VEX_VPALIGNR_YMM_YMM_YMMM256_IMM8, R.YMM0, R.YMM1, R.YMM2, 4)), ("vpblendvb_ymm", Instruction.create_reg_reg_reg_reg(Code.VEX_VPBLENDVB_YMM_YMM_YMMM256_YMM, R.YMM0, R.YMM1, R.YMM2, R.YMM3)), ("vpblendw_ymm", Instruction.create_reg_reg_reg_u32(Code.VEX_VPBLENDW_YMM_YMM_YMMM256_IMM8, R.YMM0, R.YMM1, R.YMM2, 0xAA)), ("vpmaddwd_ymm", Instruction.create_reg_reg_reg(Code.VEX_VPMADDWD_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2)), ("vpmulld_ymm", Instruction.create_reg_reg_reg(Code.VEX_VPMULLD_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2)), ("vmpsadbw_ymm", Instruction.create_reg_reg_reg_u32(Code.VEX_VMPSADBW_YMM_YMM_YMMM256_IMM8, R.YMM0, R.YMM1, R.YMM2, 0)), - ("vpmovsxbw_ymm", Instruction.create_reg_reg(Code.VEX_VPMOVSXBW_YMM_XMMM128, R.YMM0, R.XMM1)), - ("vpmovzxdq_ymm", Instruction.create_reg_reg(Code.VEX_VPMOVZXDQ_YMM_XMMM128, R.YMM0, R.XMM1)), - ("vpunpckldq_ymm", Instruction.create_reg_reg_reg(Code.VEX_VPUNPCKLDQ_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2)), + ("vpsrld_ymm_xmm", Instruction.create_reg_reg_reg(Code.VEX_VPSRLD_YMM_YMM_XMMM128, R.YMM0, R.YMM1, R.XMM2)), + ("vpsllq_ymm_imm", Instruction.create_reg_reg_u32(Code.VEX_VPSLLQ_YMM_YMM_IMM8, R.YMM0, R.YMM1, 4)), + ("vpsrlq_ymm_xmm", Instruction.create_reg_reg_reg(Code.VEX_VPSRLQ_YMM_YMM_XMMM128, R.YMM0, R.YMM1, R.XMM2)), ("vpslld_ymm_imm", Instruction.create_reg_reg_u32(Code.VEX_VPSLLD_YMM_YMM_IMM8, R.YMM0, R.YMM1, 4)), ("vpslld_ymm_xmm", Instruction.create_reg_reg_reg(Code.VEX_VPSLLD_YMM_YMM_XMMM128, R.YMM0, R.YMM1, R.XMM2)), ("vpsrlq_ymm_imm", Instruction.create_reg_reg_u32(Code.VEX_VPSRLQ_YMM_YMM_IMM8, R.YMM0, R.YMM1, 4)), diff --git a/tests/cpu/avx_int_ymm_abs_sign_shuf_check.py b/tests/cpu/avx_int_ymm_abs_sign_shuf_check.py index 07ae0dc61..f69a5589e 100644 --- a/tests/cpu/avx_int_ymm_abs_sign_shuf_check.py +++ b/tests/cpu/avx_int_ymm_abs_sign_shuf_check.py @@ -243,8 +243,8 @@ def check_translator(): "unsupported EVEX instruction"), ("vpshufhw_evex", (loads[0], Instruction.create_reg_reg_u32( Code.EVEX_VPSHUFHW_YMM_K1Z_YMMM256_IMM8, R.YMM0, R.YMM1, 0x1B), ret), "unsupported EVEX instruction"), - ("vpmovsxbw_ymm_xmm_source", (loads[0], Instruction.create_reg_reg( - Code.VEX_VPMOVSXBW_YMM_XMMM128, R.YMM0, R.XMM1), ret), "unsupported VEX.256 (L=1) packed-integer encoding"), + ("vpsrld_ymm_xmm_source", (*loads, Instruction.create_reg_reg_reg( + Code.VEX_VPSRLD_YMM_YMM_XMMM128, R.YMM0, R.YMM1, R.XMM2), ret), "unsupported VEX.256 (L=1) packed-integer encoding"), ("vpshufb_ymm_other_form", (*loads, Instruction.create_reg_reg_reg( Code.VEX_VPSHUFB_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2), ret), "unsupported instruction"), ("vpalignr_ymm_other_form", (*loads, Instruction.create_reg_reg_reg_u32( diff --git a/tests/cpu/avx_int_ymm_widen_unpack.asm b/tests/cpu/avx_int_ymm_widen_unpack.asm new file mode 100644 index 000000000..6a4404912 --- /dev/null +++ b/tests/cpu/avx_int_ymm_widen_unpack.asm @@ -0,0 +1,301 @@ +; coverage: source cpu_aot_avx_int_ymm_widen_unpack +; Source-owned differential fixture for 256-bit (VEX.L=1, AVX2) packed-integer +; cross-lane extend moves (VPMOVSX*/VPMOVZX*) and in-lane unpacks (VPUNPCK{L,H}{DQ,QDQ}). +; RCX = const void* input_a (32 bytes) +; RDX = const void* input_b (32 bytes) +; R8 = void* output (32 bytes) +.code + +op_vpmovsxbw_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] +IFDEF ALTER_YMM + vpmovzxbw ymm0, xmm1 +ELSE + vpmovsxbw ymm0, xmm1 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpmovsxbw_ymm ENDP + +op_vpmovsxbd_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] +IFDEF ALTER_YMM + vpmovzxbd ymm0, xmm1 +ELSE + vpmovsxbd ymm0, xmm1 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpmovsxbd_ymm ENDP + +op_vpmovsxbq_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] +IFDEF ALTER_YMM + vpmovzxbq ymm0, xmm1 +ELSE + vpmovsxbq ymm0, xmm1 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpmovsxbq_ymm ENDP + +op_vpmovsxwd_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] +IFDEF ALTER_YMM + vpmovzxwd ymm0, xmm1 +ELSE + vpmovsxwd ymm0, xmm1 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpmovsxwd_ymm ENDP + +op_vpmovsxwq_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] +IFDEF ALTER_YMM + vpmovzxwq ymm0, xmm1 +ELSE + vpmovsxwq ymm0, xmm1 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpmovsxwq_ymm ENDP + +op_vpmovsxdq_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] +IFDEF ALTER_YMM + vpmovzxdq ymm0, xmm1 +ELSE + vpmovsxdq ymm0, xmm1 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpmovsxdq_ymm ENDP + +op_vpmovzxbw_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] +IFDEF ALTER_YMM + vpmovsxbw ymm0, xmm1 +ELSE + vpmovzxbw ymm0, xmm1 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpmovzxbw_ymm ENDP + +op_vpmovzxbd_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] +IFDEF ALTER_YMM + vpmovsxbd ymm0, xmm1 +ELSE + vpmovzxbd ymm0, xmm1 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpmovzxbd_ymm ENDP + +op_vpmovzxbq_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] +IFDEF ALTER_YMM + vpmovsxbq ymm0, xmm1 +ELSE + vpmovzxbq ymm0, xmm1 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpmovzxbq_ymm ENDP + +op_vpmovzxwd_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] +IFDEF ALTER_YMM + vpmovsxwd ymm0, xmm1 +ELSE + vpmovzxwd ymm0, xmm1 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpmovzxwd_ymm ENDP + +op_vpmovzxwq_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] +IFDEF ALTER_YMM + vpmovsxwq ymm0, xmm1 +ELSE + vpmovzxwq ymm0, xmm1 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpmovzxwq_ymm ENDP + +op_vpmovzxdq_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] +IFDEF ALTER_YMM + vpmovsxdq ymm0, xmm1 +ELSE + vpmovzxdq ymm0, xmm1 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpmovzxdq_ymm ENDP + +op_vpunpckldq_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] + vmovdqu ymm2, YMMWORD PTR [rdx] +IFDEF ALTER_YMM + vpunpckhdq ymm0, ymm1, ymm2 +ELSE + vpunpckldq ymm0, ymm1, ymm2 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpunpckldq_ymm ENDP + +op_vpunpckhdq_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] + vmovdqu ymm2, YMMWORD PTR [rdx] +IFDEF ALTER_YMM + vpunpckldq ymm0, ymm1, ymm2 +ELSE + vpunpckhdq ymm0, ymm1, ymm2 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpunpckhdq_ymm ENDP + +op_vpunpcklqdq_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] + vmovdqu ymm2, YMMWORD PTR [rdx] +IFDEF ALTER_YMM + vpunpckhqdq ymm0, ymm1, ymm2 +ELSE + vpunpcklqdq ymm0, ymm1, ymm2 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpunpcklqdq_ymm ENDP + +op_vpunpckhqdq_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] + vmovdqu ymm2, YMMWORD PTR [rdx] +IFDEF ALTER_YMM + vpunpcklqdq ymm0, ymm1, ymm2 +ELSE + vpunpckhqdq ymm0, ymm1, ymm2 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpunpckhqdq_ymm ENDP + +op_vpmovsxbd_ymm_stale_dst PROC FRAME + .endprolog + vmovdqu ymm0, YMMWORD PTR [rdx] + vmovdqu ymm1, YMMWORD PTR [rcx] + vpmovsxbd ymm0, xmm1 + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpmovsxbd_ymm_stale_dst ENDP + +op_vpmovsxbw_ymm_alias PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] + vpmovsxbw ymm1, xmm1 + vmovdqu YMMWORD PTR [r8], ymm1 + vzeroupper + ret +op_vpmovsxbw_ymm_alias ENDP + +op_vpmovzxdq_ymm_alias PROC FRAME + .endprolog + vmovdqu ymm2, YMMWORD PTR [rcx] + vpmovzxdq ymm2, xmm2 + vmovdqu YMMWORD PTR [r8], ymm2 + vzeroupper + ret +op_vpmovzxdq_ymm_alias ENDP + +op_vpunpckldq_ymm_dst_src1 PROC FRAME + .endprolog + vmovdqu ymm3, YMMWORD PTR [rcx] + vmovdqu ymm4, YMMWORD PTR [rdx] + vpunpckldq ymm3, ymm3, ymm4 + vmovdqu YMMWORD PTR [r8], ymm3 + vzeroupper + ret +op_vpunpckldq_ymm_dst_src1 ENDP + +op_vpunpckhqdq_ymm_dst_src2 PROC FRAME + .endprolog + vmovdqu ymm4, YMMWORD PTR [rcx] + vmovdqu ymm5, YMMWORD PTR [rdx] + vpunpckhqdq ymm5, ymm4, ymm5 + vmovdqu YMMWORD PTR [r8], ymm5 + vzeroupper + ret +op_vpunpckhqdq_ymm_dst_src2 ENDP + +op_vpunpckhdq_ymm_all PROC FRAME + .endprolog + vmovdqu ymm2, YMMWORD PTR [rcx] + vpunpckhdq ymm2, ymm2, ymm2 + vmovdqu YMMWORD PTR [r8], ymm2 + vzeroupper + ret +op_vpunpckhdq_ymm_all ENDP + +op_vpmovsxwd_ymm_then_xmm_vpunpcklqdq PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] + vmovdqu ymm2, YMMWORD PTR [rdx] + vpmovsxwd ymm0, xmm1 + vpunpcklqdq xmm0, xmm0, xmm2 + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpmovsxwd_ymm_then_xmm_vpunpcklqdq ENDP + +op_chain_ymm_widen_unpack PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] + vmovdqu ymm2, YMMWORD PTR [rdx] + vpmovsxwd ymm3, xmm1 + vpmovzxbd ymm4, xmm2 + vpunpckldq ymm0, ymm3, ymm4 + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_chain_ymm_widen_unpack ENDP + +END diff --git a/tests/cpu/avx_int_ymm_widen_unpack.def b/tests/cpu/avx_int_ymm_widen_unpack.def new file mode 100644 index 000000000..3935ba5a4 --- /dev/null +++ b/tests/cpu/avx_int_ymm_widen_unpack.def @@ -0,0 +1,25 @@ +EXPORTS + op_vpmovsxbw_ymm + op_vpmovsxbd_ymm + op_vpmovsxbq_ymm + op_vpmovsxwd_ymm + op_vpmovsxwq_ymm + op_vpmovsxdq_ymm + op_vpmovzxbw_ymm + op_vpmovzxbd_ymm + op_vpmovzxbq_ymm + op_vpmovzxwd_ymm + op_vpmovzxwq_ymm + op_vpmovzxdq_ymm + op_vpunpckldq_ymm + op_vpunpckhdq_ymm + op_vpunpcklqdq_ymm + op_vpunpckhqdq_ymm + op_vpmovsxbd_ymm_stale_dst + op_vpmovsxbw_ymm_alias + op_vpmovzxdq_ymm_alias + op_vpunpckldq_ymm_dst_src1 + op_vpunpckhqdq_ymm_dst_src2 + op_vpunpckhdq_ymm_all + op_vpmovsxwd_ymm_then_xmm_vpunpcklqdq + op_chain_ymm_widen_unpack diff --git a/tests/cpu/avx_int_ymm_widen_unpack_check.py b/tests/cpu/avx_int_ymm_widen_unpack_check.py new file mode 100644 index 000000000..e1d10328a --- /dev/null +++ b/tests/cpu/avx_int_ymm_widen_unpack_check.py @@ -0,0 +1,383 @@ +"""Differential, boundary, mutation, and rejection checks for 256-bit AVX2 extend and unpack ops.""" + +import ctypes +import os +from pathlib import Path +import random +import struct +import sys + +from iced_x86 import Code, Decoder, Formatter, FormatterSyntax, Instruction, MemoryOperand, Register as R +import pefile + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "tools")) +from avx_int_ymm_minmax_check import encode_seq, first_bad_word, invoke, load # noqa: E402 +from avx_int_ymm_pack_check import host_has_avx2 # noqa: E402 +from cpu_avx_int_aot import lift_code # noqa: E402 +from cpu_leaf_aot import bounded_code, export_rva # noqa: E402 + +EXTEND_SPECS = { + # export: (signed, src_width_bytes, dst_width_bytes) + "op_vpmovsxbw_ymm": (True, 1, 2), + "op_vpmovsxbd_ymm": (True, 1, 4), + "op_vpmovsxbq_ymm": (True, 1, 8), + "op_vpmovsxwd_ymm": (True, 2, 4), + "op_vpmovsxwq_ymm": (True, 2, 8), + "op_vpmovsxdq_ymm": (True, 4, 8), + "op_vpmovzxbw_ymm": (False, 1, 2), + "op_vpmovzxbd_ymm": (False, 1, 4), + "op_vpmovzxbq_ymm": (False, 1, 8), + "op_vpmovzxwd_ymm": (False, 2, 4), + "op_vpmovzxwq_ymm": (False, 2, 8), + "op_vpmovzxdq_ymm": (False, 4, 8), +} +UNPACK_EXPORTS = ( + "op_vpunpckldq_ymm", + "op_vpunpckhdq_ymm", + "op_vpunpcklqdq_ymm", + "op_vpunpckhqdq_ymm", +) +BASE_EXPORTS = tuple(EXTEND_SPECS) + UNPACK_EXPORTS +SPECIAL_EXPORTS = ( + "op_vpmovsxbd_ymm_stale_dst", + "op_vpmovsxbw_ymm_alias", + "op_vpmovzxdq_ymm_alias", + "op_vpunpckldq_ymm_dst_src1", + "op_vpunpckhqdq_ymm_dst_src2", + "op_vpunpckhdq_ymm_all", + "op_vpmovsxwd_ymm_then_xmm_vpunpcklqdq", + "op_chain_ymm_widen_unpack", +) +EXPORTS = BASE_EXPORTS + SPECIAL_EXPORTS + +_FMT_SIGNED = {1: "b", 2: "h", 4: "i", 8: "q"} +_FMT_UNSIGNED = {1: "B", 2: "H", 4: "I", 8: "Q"} + + +# --- Independent Python reference: cross-lane XMM->YMM extend & per-128-bit-lane unpack --- + +def _ref_extend(is_signed, src_w, dst_w, a): + count = 32 // dst_w + in_fmt = (_FMT_SIGNED if is_signed else _FMT_UNSIGNED)[src_w] + out_fmt = (_FMT_SIGNED if is_signed else _FMT_UNSIGNED)[dst_w] + vals = struct.unpack(f"<{count}{in_fmt}", a[:count * src_w]) + return struct.pack(f"<{count}{out_fmt}", *vals) + + +def _unpack_half(kind, a16, b16): + if kind in ("ldq", "hdq"): + xs = struct.unpack("<4I", a16) + ys = struct.unpack("<4I", b16) + off = 0 if kind == "ldq" else 2 + return struct.pack("<4I", xs[off], ys[off], xs[off + 1], ys[off + 1]) + if kind in ("lqdq", "hqdq"): + xs = struct.unpack("<2Q", a16) + ys = struct.unpack("<2Q", b16) + idx = 0 if kind == "lqdq" else 1 + return struct.pack("<2Q", xs[idx], ys[idx]) + raise ValueError(kind) + + +def _ref_unpack(kind, a, b): + return _unpack_half(kind, a[:16], b[:16]) + _unpack_half(kind, a[16:32], b[16:32]) + + +def reference(name, a, b): + if name in EXTEND_SPECS: + return _ref_extend(*EXTEND_SPECS[name], a) + if name == "op_vpmovsxbd_ymm_stale_dst": + return _ref_extend(True, 1, 4, a) + if name == "op_vpmovsxbw_ymm_alias": + return _ref_extend(True, 1, 2, a) + if name == "op_vpmovzxdq_ymm_alias": + return _ref_extend(False, 4, 8, a) + if name in ("op_vpunpckldq_ymm", "op_vpunpckldq_ymm_dst_src1"): + return _ref_unpack("ldq", a, b) + if name == "op_vpunpckhdq_ymm": + return _ref_unpack("hdq", a, b) + if name == "op_vpunpckhdq_ymm_all": + return _ref_unpack("hdq", a, a) + if name == "op_vpunpcklqdq_ymm": + return _ref_unpack("lqdq", a, b) + if name in ("op_vpunpckhqdq_ymm", "op_vpunpckhqdq_ymm_dst_src2"): + return _ref_unpack("hqdq", a, b) + if name == "op_vpmovsxwd_ymm_then_xmm_vpunpcklqdq": + t = _ref_extend(True, 2, 4, a) + return _unpack_half("lqdq", t[:16], b[:16]) + b"\x00" * 16 + if name == "op_chain_ymm_widen_unpack": + t3 = _ref_extend(True, 2, 4, a) + t4 = _ref_extend(False, 1, 4, b) + return _ref_unpack("ldq", t3, t4) + raise KeyError(name) + + +def all_pairs(): + """Construct sign-boundary vectors with non-zero ignored XMM/YMM upper bytes plus random.""" + pairs = [] + b_edges = (0x00, 0x01, 0x7F, 0x80, 0x81, 0xFE, 0xFF) + w_edges = (0x0000, 0x0001, 0x7FFF, 0x8000, 0x8001, 0xFFFE, 0xFFFF) + d_edges = (0x00000000, 0x00000001, 0x7FFFFFFF, 0x80000000, 0x80000001, 0xFFFFFFFE, 0xFFFFFFFF) + + for shift in range(len(b_edges)): + a = bytes(b_edges[(i + shift) % len(b_edges)] for i in range(32)) + b = bytes(b_edges[(3 * i + shift + 1) % len(b_edges)] for i in range(32)) + pairs.append((a, b)) + for shift in range(len(w_edges)): + a = struct.pack("<16H", *(w_edges[(i + shift) % len(w_edges)] for i in range(16))) + b = struct.pack("<16H", *(w_edges[(3 * i + shift + 2) % len(w_edges)] for i in range(16))) + pairs.append((a, b)) + for shift in range(len(d_edges)): + a = struct.pack("<8I", *(d_edges[(i + shift) % len(d_edges)] for i in range(8))) + b = struct.pack("<8I", *(d_edges[(3 * i + shift + 2) % len(d_edges)] for i in range(8))) + pairs.append((a, b)) + + # Distinct non-zero high bytes in xmm (bytes 4..15) and upper ymm lane (bytes 16..31). + pairs.append((bytes(range(0x10, 0x30)), bytes(range(0xA0, 0xC0)))) + pairs.append((bytes(0x80 + i for i in range(32)), bytes(0x7F - i for i in range(32)))) + pairs.append((bytes(32), bytes(32))) + pairs.append((b"\xff" * 32, b"\xff" * 32)) + pairs.append((b"\x80" * 16 + b"\x55" * 16, b"\x7f" * 16 + b"\xaa" * 16)) + + rng = random.Random(0x57DE9) + pairs += [(rng.randbytes(32), rng.randbytes(32)) for _ in range(160)] + return pairs + + +def bind(path, prefix): + lib = ctypes.CDLL(str(Path(path).resolve())) + funcs = {} + for name in EXPORTS: + fn = getattr(lib, prefix + name) + fn.argtypes = [ctypes.c_uint64] * 3 + fn.restype = None + funcs[name] = fn + return lib, funcs + + +def check_translator(): + ret = Instruction.create(Code.RETNQ) + ymm_loads = (load(R.YMM1, R.RCX), load(R.YMM2, R.RDX)) + xmm_loads = ( + Instruction.create_reg_mem(Code.VEX_VMOVDQU_XMM_XMMM128, R.XMM1, MemoryOperand(R.RCX)), + Instruction.create_reg_mem(Code.VEX_VMOVDQU_XMM_XMMM128, R.XMM2, MemoryOperand(R.RDX)), + ) + + extend_codes = { + "VPMOVSXBW": Code.VEX_VPMOVSXBW_YMM_XMMM128, + "VPMOVSXBD": Code.VEX_VPMOVSXBD_YMM_XMMM64, + "VPMOVSXBQ": Code.VEX_VPMOVSXBQ_YMM_XMMM32, + "VPMOVSXWD": Code.VEX_VPMOVSXWD_YMM_XMMM128, + "VPMOVSXWQ": Code.VEX_VPMOVSXWQ_YMM_XMMM64, + "VPMOVSXDQ": Code.VEX_VPMOVSXDQ_YMM_XMMM128, + "VPMOVZXBW": Code.VEX_VPMOVZXBW_YMM_XMMM128, + "VPMOVZXBD": Code.VEX_VPMOVZXBD_YMM_XMMM64, + "VPMOVZXBQ": Code.VEX_VPMOVZXBQ_YMM_XMMM32, + "VPMOVZXWD": Code.VEX_VPMOVZXWD_YMM_XMMM128, + "VPMOVZXWQ": Code.VEX_VPMOVZXWQ_YMM_XMMM64, + "VPMOVZXDQ": Code.VEX_VPMOVZXDQ_YMM_XMMM128, + } + accepted = 0 + for name, code in extend_codes.items(): + source, _ = lift_code( + name, 0x1000, encode_seq(xmm_loads[0], Instruction.create_reg_reg(code, R.YMM0, R.XMM1), ret)) + assert f"ymm0 = op_{name.lower()}_ymm(ymm1);" in source, name + # Aliased dst == src with YMM source loaded must also lift cleanly. + alias_src, _ = lift_code( + f"{name}_alias", 0x1000, encode_seq(ymm_loads[0], Instruction.create_reg_reg(code, R.YMM1, R.XMM1), ret)) + assert f"ymm1 = op_{name.lower()}_ymm(ymm1);" in alias_src, name + accepted += 1 + + for name in ("VPUNPCKLDQ", "VPUNPCKHDQ", "VPUNPCKLQDQ", "VPUNPCKHQDQ"): + code = getattr(Code, f"VEX_{name}_YMM_YMM_YMMM256") + source, _ = lift_code( + name, 0x1000, encode_seq(*ymm_loads, Instruction.create_reg_reg_reg(code, R.YMM0, R.YMM1, R.YMM2), ret)) + assert f"wide128(op_{name.lower()}, ymm1, ymm2)" in source, name + accepted += 1 + + # 128-bit forms keep their 128-bit single-helper path. + src_ext128, _ = lift_code( + "xmm_vpmovsxbw", 0x1000, + encode_seq(xmm_loads[0], Instruction.create_reg_reg(Code.VEX_VPMOVSXBW_XMM_XMMM64, R.XMM0, R.XMM1), ret)) + assert "ymm0 = op_vpmovsxbw(ymm1);" in src_ext128 and "_ymm" not in src_ext128 + src_unpck128, _ = lift_code( + "xmm_vpunpckldq", 0x1000, + encode_seq(*xmm_loads, Instruction.create_reg_reg_reg(Code.VEX_VPUNPCKLDQ_XMM_XMM_XMMM128, R.XMM0, R.XMM1, R.XMM2), ret)) + assert "ymm0 = op_vpunpckldq(ymm1, ymm2);" in src_unpck128 and "wide128" not in src_unpck128 + + mem_err = "unsupported memory operand for register-domain AVX integer instruction" + mem = MemoryOperand(R.RDX) + cases = [] + for name, code in extend_codes.items(): + cases.append((f"{name.lower()}_mem", (Instruction.create_reg_mem(code, R.YMM0, mem), ret), mem_err)) + for name in ("VPUNPCKLDQ", "VPUNPCKHDQ", "VPUNPCKLQDQ", "VPUNPCKHQDQ"): + code = getattr(Code, f"VEX_{name}_YMM_YMM_YMMM256") + cases.append((f"{name.lower()}_mem", (ymm_loads[0], Instruction.create_reg_reg_mem(code, R.YMM0, R.YMM1, mem), ret), mem_err)) + + cases += [ + # EVEX variants + ("vpmovsxbw_evex", (xmm_loads[0], Instruction.create_reg_reg(Code.EVEX_VPMOVSXBW_YMM_K1Z_XMMM128, R.YMM0, R.XMM1), ret), + "unsupported EVEX instruction"), + ("vpmovzxdq_evex", (xmm_loads[0], Instruction.create_reg_reg(Code.EVEX_VPMOVZXDQ_YMM_K1Z_XMMM128, R.YMM0, R.XMM1), ret), + "unsupported EVEX instruction"), + ("vpunpckldq_evex", (*ymm_loads, Instruction.create_reg_reg_reg(Code.EVEX_VPUNPCKLDQ_YMM_K1Z_YMM_YMMM256B32, R.YMM0, R.YMM1, R.YMM2), ret), + "unsupported EVEX instruction"), + ("vpunpckhqdq_evex", (*ymm_loads, Instruction.create_reg_reg_reg(Code.EVEX_VPUNPCKHQDQ_YMM_K1Z_YMM_YMMM256B64, R.YMM0, R.YMM1, R.YMM2), ret), + "unsupported EVEX instruction"), + # Nonvolatile YMM6..15 / XMM6..15 + ("vpmovsxbd_nonvol_dst", (xmm_loads[0], Instruction.create_reg_reg(Code.VEX_VPMOVSXBD_YMM_XMMM64, R.YMM6, R.XMM1), ret), + "nonvolatile vector register"), + ("vpmovzxwq_nonvol_src", (xmm_loads[0], Instruction.create_reg_reg(Code.VEX_VPMOVZXWQ_YMM_XMMM64, R.YMM0, R.XMM7), ret), + "nonvolatile vector register"), + ("vpunpckldq_nonvol_dst", (*ymm_loads, Instruction.create_reg_reg_reg(Code.VEX_VPUNPCKLDQ_YMM_YMM_YMMM256, R.YMM8, R.YMM1, R.YMM2), ret), + "nonvolatile vector register"), + ("vpunpcklqdq_nonvol_src2", (*ymm_loads, Instruction.create_reg_reg_reg(Code.VEX_VPUNPCKLQDQ_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM15), ret), + "nonvolatile vector register"), + # Unlowered YMM unpack forms whose 128-bit encodings are carved out to cpu_vex_aot.py + ("vpunpcklbw_ymm", (*ymm_loads, Instruction.create_reg_reg_reg(Code.VEX_VPUNPCKLBW_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2), ret), + "unsupported instruction"), + ("vpunpckhbw_ymm", (*ymm_loads, Instruction.create_reg_reg_reg(Code.VEX_VPUNPCKHBW_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2), ret), + "unsupported instruction"), + ("vpunpcklwd_ymm", (*ymm_loads, Instruction.create_reg_reg_reg(Code.VEX_VPUNPCKLWD_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2), ret), + "unsupported instruction"), + ("vpunpckhwd_ymm", (*ymm_loads, Instruction.create_reg_reg_reg(Code.VEX_VPUNPCKHWD_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2), ret), + "unsupported instruction"), + # Undefined sources + ("vpmovsxbw_undef_src", (Instruction.create_reg_reg(Code.VEX_VPMOVSXBW_YMM_XMMM128, R.YMM0, R.XMM3), ret), + "undefined vector register ymm3"), + ("vpunpckhdq_undef_src2", (ymm_loads[0], Instruction.create_reg_reg_reg(Code.VEX_VPUNPCKHDQ_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM3), ret), + "undefined vector register ymm3"), + # Missing terminal ret + ("vpmovzxdq_missing_ret", (xmm_loads[0], Instruction.create_reg_reg(Code.VEX_VPMOVZXDQ_YMM_XMMM128, R.YMM0, R.XMM1)), + "missing terminal ret"), + ] + for label, seq, reason in cases: + try: + lift_code(label, 0x1000, encode_seq(*seq)) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: translator accepted a rejected control") + return accepted, len(cases) + + +def check_differential(native, lifted, altered, altered_lifted): + pairs = all_pairs() + total = 0 + for name in EXPORTS: + for index, (a, b) in enumerate(pairs): + want = reference(name, a, b) + for label, funcs in (("native", native), ("lifted", lifted)): + got = invoke(funcs[name], a, b) + if got != want: + raise AssertionError( + f"{label} {name} case {index} word {first_bad_word(got, want)}: " + f"got {got.hex()} expected {want.hex()}") + total += 1 + + # Unaligned input and output buffers; guard bytes must remain intact. + a, b = pairs[len(pairs) // 2] + for name in EXPORTS: + for a_offset, out_offset in ((1, 0), (0, 3), (7, 5)): + want = reference(name, a, b) + for label, funcs in (("native", native), ("lifted", lifted)): + got = invoke(funcs[name], a, b, a_offset, out_offset) + if got != want: + raise AssertionError(f"{label} {name} offsets {a_offset}/{out_offset}") + total += 1 + + # Altered build checks: swapped ops match altered native and diverge from original. + for name in BASE_EXPORTS: + changed = 0 + for a, b in pairs: + alt_nat = invoke(altered[name], a, b) + alt_lif = invoke(altered_lifted[name], a, b) + if alt_lif != alt_nat: + raise AssertionError(f"altered {name}: lifted differs from native") + changed += alt_nat != invoke(native[name], a, b) + if not changed: + raise AssertionError(f"altered build did not diverge on {name}") + + # Mutant Python models: must fail against lifted in the expected 64-bit words. + zero16 = b"\x00" * 16 + mutants = [ + # Upper 128-bit half dropped on extend and unpack + ("op_vpmovsxbw_ymm", lambda x, _y: reference("op_vpmovsxbw_ymm", x, _y)[:16] + zero16, {2, 3}), + ("op_vpunpckldq_ymm", lambda x, y: reference("op_vpunpckldq_ymm", x, y)[:16] + zero16, {2, 3}), + # Lower 128-bit extend duplicated into upper 128-bit lane instead of cross-lane slicing + ("op_vpmovsxbw_ymm", lambda x, _y: reference("op_vpmovsxbw_ymm", x, _y)[:16] * 2, {2, 3}), + ("op_vpmovzxbd_ymm", lambda x, _y: reference("op_vpmovzxbd_ymm", x, _y)[:16] * 2, {2, 3}), + ("op_vpmovsxdq_ymm", lambda x, _y: reference("op_vpmovsxdq_ymm", x, _y)[:16] * 2, {2, 3}), + # Stale upper YMM bits (bytes 16..31) erroneously read for upper half + ("op_vpmovsxbw_ymm", lambda x, _y: _ref_extend(True, 1, 2, x)[:16] + _ref_extend(True, 1, 2, x[16:])[:16], {2, 3}), + # Wrong sign/zero extension + ("op_vpmovsxbd_ymm", lambda x, y: reference("op_vpmovzxbd_ymm", x, y), {0, 1, 2, 3}), + ("op_vpmovzxwq_ymm", lambda x, y: reference("op_vpmovsxwq_ymm", x, y), {0, 1, 2, 3}), + # Ignored upper XMM bytes (bytes 8..15) erroneously read for *BD + ("op_vpmovsxbd_ymm", lambda x, _y: _ref_extend(True, 1, 4, x[8:]), {0, 1, 2, 3}), + # Cross-lane or swapped unpacks + ("op_vpunpckldq_ymm", lambda x, y: reference("op_vpunpckhdq_ymm", x, y), {0, 1, 2, 3}), + ("op_vpunpcklqdq_ymm", lambda x, y: reference("op_vpunpckhqdq_ymm", x, y), {0, 1, 2, 3}), + ("op_vpunpckldq_ymm", + lambda x, y: _unpack_half("ldq", x[:16], y[:16]) + _unpack_half("ldq", x[:16], y[:16]), {2, 3}), + # Missing VEX.128 upper-half zeroing after YMM extend + ("op_vpmovsxwd_ymm_then_xmm_vpunpcklqdq", + lambda x, y: reference("op_vpmovsxwd_ymm_then_xmm_vpunpcklqdq", x, y)[:16] + _ref_extend(True, 2, 4, x)[16:], + {2, 3}), + ] + for name, wrong, allowed_words in mutants: + bad_words = set() + for x, y in pairs: + w = first_bad_word(invoke(lifted[name], x, y), wrong(x, y)) + if w is not None: + bad_words.add(w) + if not bad_words or not bad_words <= allowed_words: + raise AssertionError( + f"mutant on {name}: bad words {sorted(bad_words)}, expected subset of {sorted(allowed_words)}") + + return total, len(mutants), len(BASE_EXPORTS) + + +def record_covered_forms(original_path): + record = os.environ.get("FORM_COVERAGE_RECORD") + if not record: + return + formatter = Formatter(FormatterSyntax.INTEL) + forms = set() + with pefile.PE(str(original_path), fast_load=True) as pe: + for name in EXPORTS: + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + for ins in Decoder(64, raw, ip=entry): + forms.add(formatter.format_mnemonic(ins).lower()) + out_path = Path(record) + out_path.parent.mkdir(parents=True, exist_ok=True) + out_path.write_text("".join(word + "\n" for word in sorted(forms)), encoding="utf-8") + + +def main(): + if os.environ.get("FORM_COVERAGE_RECORD"): + Path(os.environ["FORM_COVERAGE_RECORD"]).unlink(missing_ok=True) + + original_path, lifted_path, altered_path, altered_lifted_path = (Path(p) for p in sys.argv[1:5]) + + accepted, rejected = check_translator() + print(f"{accepted} 256-bit extend/unpack forms accepted; {rejected} rejection controls passed") + + lifted_lib, lifted = bind(lifted_path, "lifted_") + if not host_has_avx2(lifted_lib): + print("Host lacks CPUID.01H:ECX[28] + XGETBV + CPUID.07H:EBX[5] AVX2; skipping native differential check") + sys.exit(77) + + _, native = bind(original_path, "") + _, altered = bind(altered_path, "") + _, altered_lifted = bind(altered_lifted_path, "lifted_") + total, caught, altered_count = check_differential(native, lifted, altered, altered_lifted) + print(f"{total} native/lifted/reference cases across {len(EXPORTS)} exports matched bit for bit; " + f"{caught} mutant controls + {altered_count} altered-build controls caught") + + record_covered_forms(original_path) + + +if __name__ == "__main__": + main() diff --git a/tools/cpu_avx_int_aot.py b/tools/cpu_avx_int_aot.py index 0e67cda33..7f1d4b03b 100644 --- a/tools/cpu_avx_int_aot.py +++ b/tools/cpu_avx_int_aot.py @@ -40,6 +40,9 @@ - 256-bit (VEX.L=1, AVX2, register operands only) pack with saturation: vpacksswb, vpackssdw, vpackusdw. Each 128-bit lane is computed independently (128-bit vpackuswb stays with cpu_vex_aot.py). + - 256-bit (VEX.L=1, AVX2, register operands only) cross-lane extend: vpmovsxbw/bd/bq/wd/wq/dq, + vpmovzxbw/bd/bq/wd/wq/dq (XMM low 128 bits -> YMM 256 bits; upper source bits ignored). + - 256-bit (VEX.L=1, AVX2, register operands only) in-lane unpack: vpunpckldq/hdq/lqdq/hqdq. Transport/ABI glue: vmovdqu (128/256-bit flat load, store and register copy), flat 32/64-bit GPR load/store mov for scratch GPRs, and terminal ret. @@ -95,6 +98,7 @@ "vphaddw", "vphaddd", "vphaddsw", "vphsubw", "vphsubd", "vphsubsw", "vpmuldq", "vpmuludq", "vpmulhrsw", "vpsadbw", "vpacksswb", "vpackssdw", "vpackusdw", + "vpunpckldq", "vpunpckhdq", "vpunpcklqdq", "vpunpckhqdq", ) } WIDE_BINARY_CODES = { @@ -112,6 +116,7 @@ "VPHADDW", "VPHADDD", "VPHADDSW", "VPHSUBW", "VPHSUBD", "VPHSUBSW", "VPMULDQ", "VPMULUDQ", "VPMULHRSW", "VPSADBW", "VPACKSSWB", "VPACKSSDW", "VPACKUSDW", + "VPUNPCKLDQ", "VPUNPCKHDQ", "VPUNPCKLQDQ", "VPUNPCKHQDQ", ) } # 256-bit one-source forms: the 128-bit helper runs on each half. vpshufhw/vpshuflw use the @@ -128,6 +133,28 @@ WIDE_UNARY_IMM_CODES = { getattr(Code, f"VEX_{name}_YMM_YMMM256_IMM8") for name in ("VPSHUFHW", "VPSHUFLW") } +# 256-bit cross-lane sign/zero-extend moves (XMM low 128 bits -> YMM 256 bits). +WIDE_EXTEND_HELPERS = { + getattr(M, name.upper()): f"op_{name}_ymm" + for name in ( + "vpmovsxbw", "vpmovsxbd", "vpmovsxbq", "vpmovsxwd", "vpmovsxwq", "vpmovsxdq", + "vpmovzxbw", "vpmovzxbd", "vpmovzxbq", "vpmovzxwd", "vpmovzxwq", "vpmovzxdq", + ) +} +WIDE_EXTEND_CODES = { + Code.VEX_VPMOVSXBW_YMM_XMMM128, + Code.VEX_VPMOVSXBD_YMM_XMMM64, + Code.VEX_VPMOVSXBQ_YMM_XMMM32, + Code.VEX_VPMOVSXWD_YMM_XMMM128, + Code.VEX_VPMOVSXWQ_YMM_XMMM64, + Code.VEX_VPMOVSXDQ_YMM_XMMM128, + Code.VEX_VPMOVZXBW_YMM_XMMM128, + Code.VEX_VPMOVZXBD_YMM_XMMM64, + Code.VEX_VPMOVZXBQ_YMM_XMMM32, + Code.VEX_VPMOVZXWD_YMM_XMMM128, + Code.VEX_VPMOVZXWQ_YMM_XMMM64, + Code.VEX_VPMOVZXDQ_YMM_XMMM128, +} # Unary: dst = helper(src) UNARY_HELPERS = { @@ -379,7 +406,7 @@ } -ALLOWED_CODES |= WIDE_BINARY_CODES | WIDE_UNARY_CODES | WIDE_UNARY_IMM_CODES +ALLOWED_CODES |= WIDE_BINARY_CODES | WIDE_UNARY_CODES | WIDE_UNARY_IMM_CODES | WIDE_EXTEND_CODES PRELUDE = """#include @@ -1092,68 +1119,91 @@ // --- Sign-extend and zero-extend moves --- -static Vec256 op_vpmovsxbw(const Vec256& a) { +static Vec256 extend_bw(const Vec256& a, unsigned count, bool sign_ext) { Vec256 out{}; - for (unsigned i = 0; i < 8u; ++i) set_lane16(out, i, static_cast(static_cast(s8(lane8(a, i))))); + for (unsigned i = 0; i < count; ++i) { + const std::uint8_t u = lane8(a, i); + set_lane16(out, i, sign_ext ? static_cast(static_cast(s8(u))) + : static_cast(u)); + } return out; } -static Vec256 op_vpmovsxbd(const Vec256& a) { +static Vec256 extend_bd(const Vec256& a, unsigned count, bool sign_ext) { Vec256 out{}; - for (unsigned i = 0; i < 4u; ++i) set_lane32(out, i, static_cast(static_cast(s8(lane8(a, i))))); + for (unsigned i = 0; i < count; ++i) { + const std::uint8_t u = lane8(a, i); + set_lane32(out, i, sign_ext ? static_cast(static_cast(s8(u))) + : static_cast(u)); + } return out; } -static Vec256 op_vpmovsxbq(const Vec256& a) { - return {{static_cast(static_cast(s8(lane8(a, 0u)))), - static_cast(static_cast(s8(lane8(a, 1u)))), 0ull, 0ull}}; -} - -static Vec256 op_vpmovsxwd(const Vec256& a) { +static Vec256 extend_bq(const Vec256& a, unsigned count, bool sign_ext) { Vec256 out{}; - for (unsigned i = 0; i < 4u; ++i) set_lane32(out, i, static_cast(static_cast(s16(lane16(a, i))))); + for (unsigned i = 0; i < count; ++i) { + const std::uint8_t u = lane8(a, i); + out.q[i] = sign_ext ? static_cast(static_cast(s8(u))) + : static_cast(u); + } return out; } -static Vec256 op_vpmovsxwq(const Vec256& a) { - return {{static_cast(static_cast(s16(lane16(a, 0u)))), - static_cast(static_cast(s16(lane16(a, 1u)))), 0ull, 0ull}}; -} - -static Vec256 op_vpmovsxdq(const Vec256& a) { - return {{static_cast(static_cast(s32(lane32(a, 0u)))), - static_cast(static_cast(s32(lane32(a, 1u)))), 0ull, 0ull}}; -} - -static Vec256 op_vpmovzxbw(const Vec256& a) { +static Vec256 extend_wd(const Vec256& a, unsigned count, bool sign_ext) { Vec256 out{}; - for (unsigned i = 0; i < 8u; ++i) set_lane16(out, i, lane8(a, i)); + for (unsigned i = 0; i < count; ++i) { + const std::uint16_t u = lane16(a, i); + set_lane32(out, i, sign_ext ? static_cast(static_cast(s16(u))) + : static_cast(u)); + } return out; } -static Vec256 op_vpmovzxbd(const Vec256& a) { +static Vec256 extend_wq(const Vec256& a, unsigned count, bool sign_ext) { Vec256 out{}; - for (unsigned i = 0; i < 4u; ++i) set_lane32(out, i, lane8(a, i)); + for (unsigned i = 0; i < count; ++i) { + const std::uint16_t u = lane16(a, i); + out.q[i] = sign_ext ? static_cast(static_cast(s16(u))) + : static_cast(u); + } return out; } -static Vec256 op_vpmovzxbq(const Vec256& a) { - return {{lane8(a, 0u), lane8(a, 1u), 0ull, 0ull}}; -} - -static Vec256 op_vpmovzxwd(const Vec256& a) { +static Vec256 extend_dq(const Vec256& a, unsigned count, bool sign_ext) { Vec256 out{}; - for (unsigned i = 0; i < 4u; ++i) set_lane32(out, i, lane16(a, i)); + for (unsigned i = 0; i < count; ++i) { + const std::uint32_t u = lane32(a, i); + out.q[i] = sign_ext ? static_cast(static_cast(s32(u))) + : static_cast(u); + } return out; } -static Vec256 op_vpmovzxwq(const Vec256& a) { - return {{lane16(a, 0u), lane16(a, 1u), 0ull, 0ull}}; -} - -static Vec256 op_vpmovzxdq(const Vec256& a) { - return {{lane32(a, 0u), lane32(a, 1u), 0ull, 0ull}}; -} +static Vec256 op_vpmovsxbw(const Vec256& a) { return extend_bw(a, 8u, true); } +static Vec256 op_vpmovsxbd(const Vec256& a) { return extend_bd(a, 4u, true); } +static Vec256 op_vpmovsxbq(const Vec256& a) { return extend_bq(a, 2u, true); } +static Vec256 op_vpmovsxwd(const Vec256& a) { return extend_wd(a, 4u, true); } +static Vec256 op_vpmovsxwq(const Vec256& a) { return extend_wq(a, 2u, true); } +static Vec256 op_vpmovsxdq(const Vec256& a) { return extend_dq(a, 2u, true); } +static Vec256 op_vpmovzxbw(const Vec256& a) { return extend_bw(a, 8u, false); } +static Vec256 op_vpmovzxbd(const Vec256& a) { return extend_bd(a, 4u, false); } +static Vec256 op_vpmovzxbq(const Vec256& a) { return extend_bq(a, 2u, false); } +static Vec256 op_vpmovzxwd(const Vec256& a) { return extend_wd(a, 4u, false); } +static Vec256 op_vpmovzxwq(const Vec256& a) { return extend_wq(a, 2u, false); } +static Vec256 op_vpmovzxdq(const Vec256& a) { return extend_dq(a, 2u, false); } + +static Vec256 op_vpmovsxbw_ymm(const Vec256& a) { return extend_bw(a, 16u, true); } +static Vec256 op_vpmovsxbd_ymm(const Vec256& a) { return extend_bd(a, 8u, true); } +static Vec256 op_vpmovsxbq_ymm(const Vec256& a) { return extend_bq(a, 4u, true); } +static Vec256 op_vpmovsxwd_ymm(const Vec256& a) { return extend_wd(a, 8u, true); } +static Vec256 op_vpmovsxwq_ymm(const Vec256& a) { return extend_wq(a, 4u, true); } +static Vec256 op_vpmovsxdq_ymm(const Vec256& a) { return extend_dq(a, 4u, true); } +static Vec256 op_vpmovzxbw_ymm(const Vec256& a) { return extend_bw(a, 16u, false); } +static Vec256 op_vpmovzxbd_ymm(const Vec256& a) { return extend_bd(a, 8u, false); } +static Vec256 op_vpmovzxbq_ymm(const Vec256& a) { return extend_bq(a, 4u, false); } +static Vec256 op_vpmovzxwd_ymm(const Vec256& a) { return extend_wd(a, 8u, false); } +static Vec256 op_vpmovzxwq_ymm(const Vec256& a) { return extend_wq(a, 4u, false); } +static Vec256 op_vpmovzxdq_ymm(const Vec256& a) { return extend_dq(a, 4u, false); } // --- Unpack / interleave --- @@ -1379,7 +1429,8 @@ def write_gpr(op_index, ins): wide_unary = ins.code in WIDE_UNARY_CODES wide_unary_imm = ins.code in WIDE_UNARY_IMM_CODES wide_binary = ins.code in WIDE_BINARY_CODES - wide_any = wide_unary or wide_unary_imm or wide_binary + wide_extend = ins.code in WIDE_EXTEND_CODES + wide_any = wide_unary or wide_unary_imm or wide_binary or wide_extend if (mnemonic in AVX_INT_128_ONLY_MNEMONICS and not wide_any and op_code.encoding == EncodingKind.VEX and op_code.l == 1): raise ValueError(f"unsupported VEX.256 (L=1) packed-integer encoding at RVA {ins.ip:#x}: {ins}") @@ -1445,6 +1496,11 @@ def write_gpr(op_index, ins): statements.append( f"{dst} = wide128_unary_imm({WIDE_UNARY_IMM_HELPERS[mnemonic]}, {src}, {imm:#x}u);") defined_vec.add(dst_idx) + elif wide_extend: + src, _ = read_vec(1, ins) + dst_idx, dst, _ = write_vec(0, ins, allow_ymm=True) + statements.append(f"{dst} = {WIDE_EXTEND_HELPERS[mnemonic]}({src});") + defined_vec.add(dst_idx) elif mnemonic in UNARY_HELPERS: src, _ = read_vec(1, ins) dst_idx, dst, _ = write_vec(0, ins) From 780c0bc492b21a9853af7fdde6e200ee0437ad7e Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Thu, 26 Nov 2026 01:33:06 +0200 Subject: [PATCH 005/240] cpu: lower 32/64-bit BMI2 BZHI, MULX, PDEP, and PEXT in cpu_bmi2_bit_aot (#2621) --- CMakeLists.txt | 26 + tests/cpu/bmi2_bit_aot.asm | 303 +++++++++++ tests/cpu/bmi2_bit_aot.def | 27 + tests/cpu/bmi2_bit_aot_check.py | 854 ++++++++++++++++++++++++++++++++ tools/cpu_bmi2_bit_aot.py | 688 +++++++++++++++++++++++++ 5 files changed, 1898 insertions(+) create mode 100644 tests/cpu/bmi2_bit_aot.asm create mode 100644 tests/cpu/bmi2_bit_aot.def create mode 100644 tests/cpu/bmi2_bit_aot_check.py create mode 100644 tools/cpu_bmi2_bit_aot.py diff --git a/CMakeLists.txt b/CMakeLists.txt index a0ad7738b..fb058175c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -6542,6 +6542,32 @@ if(EXISTS "${INTAKE_PYTHON}") SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/cpu_aot_bmi2_shift.txt") + # cpu_aot_bmi2_bit + set(cpu_bmi2_bit_exports + "op_bzhi32,op_bzhi64,op_mulx32,op_mulx64,op_mulx32_alias,op_mulx64_alias," + "op_pdep32,op_pdep64,op_pext32,op_pext64," + "op_bzhi32_mem,op_bzhi64_mem,op_mulx32_mem,op_mulx64_mem," + "op_pdep32_mem,op_pdep64_mem,op_pext32_mem,op_pext64_mem," + "op_mem_r8_source,op_bzhi32_flags,op_bzhi64_flags," + "op_flags_preserve32,op_flags_preserve64,op_flags_preserve_pf," + "op_flags_preserve_mem,op_bmi2_bit_discarded_read") + string(CONCAT cpu_bmi2_bit_exports ${cpu_bmi2_bit_exports}) + foreach(variant IN ITEMS original altered) + cpu_asm_fixture(cpu_bmi2_bit_${variant} bmi2_bit_aot) + cpu_translation(cpu_bmi2_bit_${variant} cpu_bmi2_bit_aot "${cpu_bmi2_bit_exports}") + endforeach() + target_compile_definitions(cpu_bmi2_bit_altered PRIVATE ALTER_BMI2_BIT) + add_test(NAME cpu_aot_bmi2_bit COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/cpu/bmi2_bit_aot_check.py" + "$" + "$" + "$" + "$" + "${CMAKE_CXX_COMPILER}") + set_tests_properties(cpu_aot_bmi2_bit PROPERTIES + SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/cpu_aot_bmi2_bit.txt") + # cpu_aot_bmi1_bit set(cpu_bmi1_aot_exports "op_blsi32,op_blsi64,op_blsmsk32,op_blsmsk64,op_blsr32,op_blsr64," diff --git a/tests/cpu/bmi2_bit_aot.asm b/tests/cpu/bmi2_bit_aot.asm new file mode 100644 index 000000000..6c6ab04a4 --- /dev/null +++ b/tests/cpu/bmi2_bit_aot.asm @@ -0,0 +1,303 @@ +; coverage: record cpu_aot_bmi2_bit +; Source-built MASM fixture for the four BMI2 bit-manipulation forms from +; docs/coverage/x64_zen2.tsv group BMI/ADX: BZHI, MULX, PDEP, and PEXT in 32-bit +; and 64-bit register and flat zero-displacement [rcx|rdx|r8] memory forms, plus +; BZHI CF/ZF/SF/OF flag checks, CMP -> PDEP/PEXT/MULX -> SETcc flag preservation +; (CF, ZF, SF, OF, PF), MULX op0==op1 aliasing, 32-bit zero-extension, [r8] +; source-then-store, and discarded faulting m64 read. +.code + +PACK_CF_ZF_SF_OF MACRO + setb r9b + sete r10b + sets r11b + seto byte ptr [r8] + movzx r9d, r9b + movzx r10d, r10b + mov eax, 2 + pdep r10d, r10d, eax + or r9d, r10d + movzx r11d, r11b + mov eax, 4 + pdep r11d, r11d, eax + or r9d, r11d + movzx r10d, byte ptr [r8] + mov eax, 8 + pdep r10d, r10d, eax + or r9d, r10d + mov eax, r9d + mov dword ptr [r8], eax +ENDM + +; --- Register forms (mov rax,-1 / r9,-1 / r10,-1 before 32-bit ops checks [63:32] zero-ext) --- + +op_bzhi32 PROC FRAME + .endprolog + mov rax, -1 +IFDEF ALTER_BMI2_BIT + pext eax, ecx, edx +ELSE + bzhi eax, ecx, edx +ENDIF + ret +op_bzhi32 ENDP + +op_bzhi64 PROC FRAME + .endprolog +IFDEF ALTER_BMI2_BIT + pext rax, rcx, rdx +ELSE + bzhi rax, rcx, rdx +ENDIF + ret +op_bzhi64 ENDP + +op_mulx32 PROC FRAME + .endprolog + mov r9, -1 + mov r10, -1 +IFDEF ALTER_BMI2_BIT + mulx r10d, r9d, ecx +ELSE + mulx r9d, r10d, ecx +ENDIF + mov qword ptr [r8], r10 + mov rax, r9 + ret +op_mulx32 ENDP + +op_mulx64 PROC FRAME + .endprolog +IFDEF ALTER_BMI2_BIT + mulx r10, r9, rcx +ELSE + mulx r9, r10, rcx +ENDIF + mov qword ptr [r8], r10 + mov rax, r9 + ret +op_mulx64 ENDP + +op_mulx32_alias PROC FRAME + .endprolog + mov rax, -1 +IFDEF ALTER_BMI2_BIT + mulx r9d, eax, ecx +ELSE + mulx eax, eax, ecx +ENDIF + ret +op_mulx32_alias ENDP + +op_mulx64_alias PROC FRAME + .endprolog +IFDEF ALTER_BMI2_BIT + mulx r9, rax, rcx +ELSE + mulx rax, rax, rcx +ENDIF + ret +op_mulx64_alias ENDP + +op_pdep32 PROC FRAME + .endprolog + mov rax, -1 +IFDEF ALTER_BMI2_BIT + pext eax, ecx, edx +ELSE + pdep eax, ecx, edx +ENDIF + ret +op_pdep32 ENDP + +op_pdep64 PROC FRAME + .endprolog +IFDEF ALTER_BMI2_BIT + pext rax, rcx, rdx +ELSE + pdep rax, rcx, rdx +ENDIF + ret +op_pdep64 ENDP + +op_pext32 PROC FRAME + .endprolog + mov rax, -1 +IFDEF ALTER_BMI2_BIT + pdep eax, ecx, edx +ELSE + pext eax, ecx, edx +ENDIF + ret +op_pext32 ENDP + +op_pext64 PROC FRAME + .endprolog +IFDEF ALTER_BMI2_BIT + pdep rax, rcx, rdx +ELSE + pext rax, rcx, rdx +ENDIF + ret +op_pext64 ENDP + +; --- Flat zero-displacement [rcx|rdx] m32 / m64 source forms --- + +op_bzhi32_mem PROC FRAME + .endprolog + mov rax, -1 + mov r9d, dword ptr [rdx] + bzhi eax, dword ptr [rcx], r9d + ret +op_bzhi32_mem ENDP + +op_bzhi64_mem PROC FRAME + .endprolog + mov r9, qword ptr [rdx] + bzhi rax, qword ptr [rcx], r9 + ret +op_bzhi64_mem ENDP + +op_mulx32_mem PROC FRAME + .endprolog + mov r9, -1 + mov r10, -1 + mulx r9d, r10d, dword ptr [rcx] + mov qword ptr [r8], r10 + mov rax, r9 + ret +op_mulx32_mem ENDP + +op_mulx64_mem PROC FRAME + .endprolog + mulx r9, r10, qword ptr [rcx] + mov qword ptr [r8], r10 + mov rax, r9 + ret +op_mulx64_mem ENDP + +op_pdep32_mem PROC FRAME + .endprolog + mov rax, -1 + pdep eax, ecx, dword ptr [rdx] + ret +op_pdep32_mem ENDP + +op_pdep64_mem PROC FRAME + .endprolog + pdep rax, rcx, qword ptr [rdx] + ret +op_pdep64_mem ENDP + +op_pext32_mem PROC FRAME + .endprolog + mov rax, -1 + pext eax, ecx, dword ptr [rdx] + ret +op_pext32_mem ENDP + +op_pext64_mem PROC FRAME + .endprolog + pext rax, rcx, qword ptr [rdx] + ret +op_pext64_mem ENDP + +; --- [r8] source-then-store and program order --- + +op_mem_r8_source PROC FRAME + .endprolog + mov r9, qword ptr [rcx] + pdep r10, r9, qword ptr [r8] + pext r11, r10, qword ptr [rdx] + mulx r9, rax, qword ptr [r8] + xor rax, r11 + mov qword ptr [r8], r10 + ret +op_mem_r8_source ENDP + +; --- BZHI flags: (CF << 0) | (ZF << 1) | (SF << 2) | (OF << 3) --- + +op_bzhi32_flags PROC FRAME + .endprolog + xor r9d, r9d + xor r10d, r10d + xor r11d, r11d + mov rax, -1 + bzhi eax, ecx, edx + PACK_CF_ZF_SF_OF + ret +op_bzhi32_flags ENDP + +op_bzhi64_flags PROC FRAME + .endprolog + xor r9d, r9d + xor r10d, r10d + xor r11d, r11d + bzhi rax, rcx, rdx + PACK_CF_ZF_SF_OF + ret +op_bzhi64_flags ENDP + +; --- Flag preservation across CMP -> PDEP/PEXT/MULX -> SETcc (CF/ZF/SF/OF and PF) --- + +op_flags_preserve32 PROC FRAME + .endprolog + xor r9d, r9d + xor r10d, r10d + xor r11d, r11d + cmp ecx, edx + pdep r9d, ecx, edx + pext r10d, r9d, edx + mulx r11d, eax, ecx + PACK_CF_ZF_SF_OF + ret +op_flags_preserve32 ENDP + +op_flags_preserve64 PROC FRAME + .endprolog + xor r9d, r9d + xor r10d, r10d + xor r11d, r11d + cmp rcx, rdx + pdep r9, rcx, rdx + pext r10, r9, rdx + mulx r11, rax, rcx + PACK_CF_ZF_SF_OF + ret +op_flags_preserve64 ENDP + +op_flags_preserve_pf PROC FRAME + .endprolog + cmp rcx, rdx + pdep r9, rcx, rdx + pext r10, r9, rdx + mulx r11, rax, rcx + setp byte ptr [r8] + ret +op_flags_preserve_pf ENDP + +op_flags_preserve_mem PROC FRAME + .endprolog + xor r9d, r9d + xor r10d, r10d + xor r11d, r11d + mov r9, qword ptr [rcx] + mov r10, qword ptr [rdx] + cmp r9, r10 + pdep r11, r9, qword ptr [rdx] + pext r9, r11, qword ptr [rcx] + mulx r10, rax, qword ptr [rcx] + PACK_CF_ZF_SF_OF + ret +op_flags_preserve_mem ENDP + +; --- Discarded memory read must still fault on NULL rdx even under /O2 --- + +op_bmi2_bit_discarded_read PROC FRAME + .endprolog + pext r9, rcx, qword ptr [rdx] + mov rax, rcx + ret +op_bmi2_bit_discarded_read ENDP + +END diff --git a/tests/cpu/bmi2_bit_aot.def b/tests/cpu/bmi2_bit_aot.def new file mode 100644 index 000000000..a8e7c1060 --- /dev/null +++ b/tests/cpu/bmi2_bit_aot.def @@ -0,0 +1,27 @@ +EXPORTS + op_bzhi32 + op_bzhi64 + op_mulx32 + op_mulx64 + op_mulx32_alias + op_mulx64_alias + op_pdep32 + op_pdep64 + op_pext32 + op_pext64 + op_bzhi32_mem + op_bzhi64_mem + op_mulx32_mem + op_mulx64_mem + op_pdep32_mem + op_pdep64_mem + op_pext32_mem + op_pext64_mem + op_mem_r8_source + op_bzhi32_flags + op_bzhi64_flags + op_flags_preserve32 + op_flags_preserve64 + op_flags_preserve_pf + op_flags_preserve_mem + op_bmi2_bit_discarded_read diff --git a/tests/cpu/bmi2_bit_aot_check.py b/tests/cpu/bmi2_bit_aot_check.py new file mode 100644 index 000000000..cf2f0ae67 --- /dev/null +++ b/tests/cpu/bmi2_bit_aot_check.py @@ -0,0 +1,854 @@ +"""Differential, /O2, flag-preservation, mutant, and rejection checks for cpu_bmi2_bit_aot.""" + +import ctypes +import os +from pathlib import Path +import random +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory + +from iced_x86 import Code, Decoder, Encoder, Formatter, FormatterSyntax, Instruction, MemoryOperand, Register as R +import pefile + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "tools")) +from cpu_bmi2_bit_aot import lift_code, translate # noqa: E402 +from cpu_leaf_aot import bounded_code, export_rva # noqa: E402 + +EXPORTS = ( + "op_bzhi32", + "op_bzhi64", + "op_mulx32", + "op_mulx64", + "op_mulx32_alias", + "op_mulx64_alias", + "op_pdep32", + "op_pdep64", + "op_pext32", + "op_pext64", + "op_bzhi32_mem", + "op_bzhi64_mem", + "op_mulx32_mem", + "op_mulx64_mem", + "op_pdep32_mem", + "op_pdep64_mem", + "op_pext32_mem", + "op_pext64_mem", + "op_mem_r8_source", + "op_bzhi32_flags", + "op_bzhi64_flags", + "op_flags_preserve32", + "op_flags_preserve64", + "op_flags_preserve_pf", + "op_flags_preserve_mem", + "op_bmi2_bit_discarded_read", +) + +ALTERED_EXPORTS = ( + "op_bzhi32", + "op_bzhi64", + "op_mulx32", + "op_mulx64", + "op_mulx32_alias", + "op_mulx64_alias", + "op_pdep32", + "op_pdep64", + "op_pext32", + "op_pext64", +) + +MASK32 = 0xFFFFFFFF +MASK64 = 0xFFFFFFFFFFFFFFFF +GUARD_PRE = bytes(range(0xA0, 0xB0)) +GUARD_POST = bytes(range(0xC0, 0xD0)) +OUT_FILL = b"\x5A" * 16 + + +# --- Independent Python reference model --- + +def ref_bzhi(val, idx, bits, *, bad_mask=False): + mask = (1 << bits) - 1 + s = val & mask + n = (idx & (bits - 1)) if bad_mask else (idx & 0xFF) + if n >= bits: + d = s + cf = 1 + else: + d = s & ((1 << n) - 1) + cf = 0 + zf = 1 if d == 0 else 0 + sf = 1 if (d & (1 << (bits - 1))) else 0 + of = 0 + packed = (cf << 0) | (zf << 1) | (sf << 2) | (of << 3) + return d, packed + + +def ref_mulx(src1, src2, bits): + mask = (1 << bits) - 1 + prod = (src1 & mask) * (src2 & mask) + lo = prod & mask + hi = (prod >> bits) & mask + return hi, lo + + +def ref_pdep(src, msk, bits): + mask = (1 << bits) - 1 + s = src & mask + m = msk & mask + d = 0 + k = 0 + for i in range(bits): + if (m >> i) & 1: + if (s >> k) & 1: + d |= 1 << i + k += 1 + return d + + +def ref_pext(src, msk, bits): + mask = (1 << bits) - 1 + s = src & mask + m = msk & mask + d = 0 + k = 0 + for i in range(bits): + if (m >> i) & 1: + if (s >> i) & 1: + d |= 1 << k + k += 1 + return d + + +def ref_cmp_flags(a, b, bits): + mask = (1 << bits) - 1 + sign = 1 << (bits - 1) + ua, ub = a & mask, b & mask + r = (ua - ub) & mask + cf = 1 if ua < ub else 0 + zf = 1 if r == 0 else 0 + sf = 1 if (r & sign) else 0 + of = 1 if (((ua ^ ub) & (ua ^ r)) & sign) else 0 + pf = 1 if (bin(r & 0xFF).count("1") % 2 == 0) else 0 + packed4 = (cf << 0) | (zf << 1) | (sf << 2) | (of << 3) + return (cf, zf, sf, of, pf), packed4 + + +VALUES = ( + 0x0000000000000000, + 0x0000000000000001, + 0x0000000000000003, + 0x0000000055AA55AA, + 0x000000007FFFFFFF, + 0x0000000080000000, + 0x0000000080000001, + 0x00000000FFFFFFFF, + 0xDEADBEEF00000000, + 0xDEADBEEF80000001, + 0x7FFFFFFFFFFFFFFF, + 0x8000000000000000, + 0x8000000000000001, + 0xFFFFFFFFFFFFFFFE, + 0xFFFFFFFFFFFFFFFF, + 0x0123456789ABCDEF, + 0xFEDCBA9876543210, +) +BZHI_INDICES = ( + 0, 1, 7, 15, 31, 32, 33, 63, 64, 65, 255, + 0x100, 0x101, 0x120, 0x13F, 0x140, 0xFFFFFFFF, 0x8000000000000000, +) +BIT_MASKS = ( + 0x0000000000000000, + 0x0000000000000001, + 0x0000000080000000, + 0x0000000055555555, + 0x00000000AAAAAAAA, + 0x00000000FFFFFFFF, + 0x8000000000000001, + 0x0F0F0F0F0F0F0F0F, + 0x5555555555555555, + 0xAAAAAAAAAAAAAAAA, + 0xFFFFFFFFFFFFFFFF, +) + + +def encode_seq(*instructions): + enc = Encoder(64) + ip = 0x1000 + for ins in instructions: + ip += enc.encode(ins, ip) + return enc.take_buffer() + + +def check_rejections(original_path): + """Verify shifts, BMI1, EVEX/XOP, ABI, addressing, PF/AF, prefix, and state rejections.""" + ret = Instruction.create(Code.RETNQ) + mov_rax_rcx = Instruction.create_reg_reg(Code.MOV_R64_RM64, R.RAX, R.RCX) + mov_r9_rcx = Instruction.create_reg_reg(Code.MOV_R64_RM64, R.R9, R.RCX) + cmp_rcx_rdx = Instruction.create_reg_reg(Code.CMP_R64_RM64, R.RCX, R.RDX) + bzhi_rax = Instruction.create_reg_reg_reg(Code.VEX_BZHI_R64_RM64_R64, R.RAX, R.RCX, R.RDX) + + alt_accept = [ + ("bzhi64_r11_r8_rcx", ( + Instruction.create_reg_mem_reg(Code.VEX_BZHI_R64_RM64_R64, R.R11, MemoryOperand(R.R8), R.RCX), + Instruction.create_reg_reg(Code.MOV_R64_RM64, R.RAX, R.R11), + ret, + ), "r11 = op_bzhi64(ld_1000_1, rcx, flags);"), + ("bzhi32_self_alias", ( + mov_r9_rcx, + Instruction.create_reg_reg_reg(Code.VEX_BZHI_R32_RM32_R32, R.R9D, R.R9D, R.EDX), + Instruction.create_reg_reg(Code.MOV_R32_RM32, R.EAX, R.R9D), + ret, + ), "r9 = op_bzhi32((r9 & 0xFFFFFFFFull), (rdx & 0xFFFFFFFFull), flags);"), + ("mulx64_alias_mem", ( + Instruction.create_reg_reg_mem(Code.VEX_MULX_R64_R64_RM64, R.R9, R.R9, MemoryOperand(R.RCX)), + Instruction.create_reg_reg(Code.MOV_R64_RM64, R.RAX, R.R9), + ret, + ), "r9 = mulx_hi_1000;"), + ("pdep64_r9_r10_rcx", ( + Instruction.create_reg_reg(Code.MOV_R64_RM64, R.R10, R.RDX), + Instruction.create_reg_reg_mem(Code.VEX_PDEP_R64_R64_RM64, R.R9, R.R10, MemoryOperand(R.RCX)), + Instruction.create_reg_reg(Code.MOV_R64_RM64, R.RAX, R.R9), + ret, + ), "r9 = op_pdep64(r10, ld_1003_2);"), + ("pext32_r11_r9_r8", ( + Instruction.create_reg_reg(Code.MOV_R32_RM32, R.R9D, R.ECX), + Instruction.create_reg_reg_mem(Code.VEX_PEXT_R32_R32_RM32, R.R11D, R.R9D, MemoryOperand(R.R8)), + Instruction.create_reg_reg(Code.MOV_R32_RM32, R.EAX, R.R11D), + ret, + ), "r11 = op_pext32((r9 & 0xFFFFFFFFull), ld_1003_2);"), + ] + for label, seq, expected in alt_accept: + src, count = lift_code(label, 0x1000, encode_seq(*seq)) + assert f"lifted_{label}" in src and count == len(seq), (label, count) + if expected not in src: + raise AssertionError(f"alt {label}: expected {expected!r} in:\n{src}") + + seg_pext = Instruction.create_reg_reg_mem(Code.VEX_PEXT_R64_R64_RM64, R.RAX, R.RCX, MemoryOperand(R.RDX)) + seg_pext.segment_prefix = R.GS + evex_ins = Instruction.create_reg_reg_reg(Code.EVEX_VPADDD_XMM_K1Z_XMM_XMMM128B32, R.XMM0, R.XMM1, R.XMM2) + evex_ins.op_mask = R.K1 + + unit_cases = [ + # EVEX / XOP + ("evex_vpaddd", (evex_ins, mov_rax_rcx, ret), "unsupported EVEX instruction"), + ("xop_bextr", (Instruction.create_reg_reg_u32(Code.XOP_BEXTR_R32_RM32_IMM32, R.EAX, R.ECX, 0x0804), ret), + "unsupported XOP instruction"), + # BMI2 shifts & legacy shifts (ALL shifts refused) + ("bmi2_rorx", (Instruction.create_reg_reg_u32(Code.VEX_RORX_R64_RM64_IMM8, R.RAX, R.RCX, 5), ret), + "unsupported VEX instruction"), + ("bmi2_shlx", (Instruction.create_reg_reg_reg(Code.VEX_SHLX_R64_RM64_R64, R.RAX, R.RCX, R.RDX), ret), + "unsupported VEX instruction"), + ("bmi2_shrx", (Instruction.create_reg_reg_reg(Code.VEX_SHRX_R32_RM32_R32, R.EAX, R.ECX, R.EDX), ret), + "unsupported VEX instruction"), + ("bmi2_sarx", (Instruction.create_reg_reg_reg(Code.VEX_SARX_R64_RM64_R64, R.RAX, R.RCX, R.RDX), ret), + "unsupported VEX instruction"), + ("legacy_shl_imm", (mov_rax_rcx, Instruction.create_reg_u32(Code.SHL_RM32_IMM8, R.EAX, 1), ret), + "unsupported instruction"), + ("legacy_shl_1", (mov_rax_rcx, Instruction.create_reg_u32(Code.SHL_RM64_1, R.RAX, 1), ret), + "unsupported instruction"), + ("legacy_shr_imm", (mov_rax_rcx, Instruction.create_reg_u32(Code.SHR_RM32_IMM8, R.EAX, 3), ret), + "unsupported instruction"), + ("legacy_sar_cl", (mov_rax_rcx, Instruction.create_reg_reg(Code.SAR_RM32_CL, R.EAX, R.CL), ret), + "unsupported instruction"), + ("legacy_ror_imm", (mov_rax_rcx, Instruction.create_reg_u32(Code.ROR_RM32_IMM8, R.EAX, 2), ret), + "unsupported instruction"), + # BMI1 instructions + ("bmi1_andn", (Instruction.create_reg_reg_reg(Code.VEX_ANDN_R32_R32_RM32, R.EAX, R.ECX, R.EDX), ret), + "unsupported VEX instruction"), + ("bmi1_bextr", (Instruction.create_reg_reg_reg(Code.VEX_BEXTR_R32_RM32_R32, R.EAX, R.ECX, R.EDX), ret), + "unsupported VEX instruction"), + ("bmi1_blsi", (Instruction.create_reg_reg(Code.VEX_BLSI_R32_RM32, R.EAX, R.ECX), ret), + "unsupported VEX instruction"), + ("bmi1_blsmsk", (Instruction.create_reg_reg(Code.VEX_BLSMSK_R64_RM64, R.RAX, R.RCX), ret), + "unsupported VEX instruction"), + ("bmi1_blsr", (Instruction.create_reg_reg(Code.VEX_BLSR_R64_RM64, R.RAX, R.RCX), ret), + "unsupported VEX instruction"), + ("bmi1_tzcnt", (Instruction.create_reg_reg(Code.TZCNT_R64_RM64, R.RAX, R.RCX), ret), + "unsupported instruction"), + # Nonvolatile GPRs + ("nonvol_rbx_dst", (Instruction.create_reg_reg_reg(Code.VEX_BZHI_R64_RM64_R64, R.RBX, R.RCX, R.RDX), mov_rax_rcx, ret), + "nonvolatile GPR"), + ("nonvol_rsi_src", (Instruction.create_reg_reg_reg(Code.VEX_PDEP_R64_R64_RM64, R.RAX, R.RSI, R.RDX), ret), + "nonvolatile GPR"), + ("nonvol_r12_idx", (Instruction.create_reg_reg_reg(Code.VEX_BZHI_R64_RM64_R64, R.RAX, R.RCX, R.R12), ret), + "nonvolatile GPR"), + ("nonvol_rsp_lo", (Instruction.create_reg_reg_reg(Code.VEX_MULX_R64_R64_RM64, R.RAX, R.RSP, R.RCX), ret), + "nonvolatile GPR"), + # Writes to argument GPRs (rcx/rdx/r8) including MULX op0 & op1 + ("write_arg_rcx", (Instruction.create_reg_reg_reg(Code.VEX_BZHI_R64_RM64_R64, R.RCX, R.RDX, R.R8), mov_rax_rcx, ret), + "cannot write argument GPR rcx"), + ("write_arg_mulx_hi_edx", (Instruction.create_reg_reg_reg(Code.VEX_MULX_R32_R32_RM32, R.EDX, R.EAX, R.ECX), ret), + "cannot write argument GPR rdx"), + ("write_arg_mulx_lo_r8", (Instruction.create_reg_reg_reg(Code.VEX_MULX_R64_R64_RM64, R.RAX, R.R8, R.RCX), ret), + "cannot write argument GPR r8"), + ("write_arg_pext_r8", (Instruction.create_reg_reg_reg(Code.VEX_PEXT_R64_R64_RM64, R.R8, R.RCX, R.RDX), mov_rax_rcx, ret), + "cannot write argument GPR r8"), + # High-byte GPRs + ("high_byte_ah", (mov_rax_rcx, Instruction.create_reg_reg(Code.MOV_R8_RM8, R.AL, R.AH), ret), + "unsupported high-byte GPR"), + ("high_byte_ch_dst", (Instruction.create_reg_reg(Code.MOV_R8_RM8, R.CH, R.DL), mov_rax_rcx, ret), + "unsupported high-byte GPR"), + # Displaced memory operands (must be refused!) + ("disp_mem_bzhi", (Instruction.create_reg_mem_reg( + Code.VEX_BZHI_R64_RM64_R64, R.RAX, MemoryOperand(R.RCX, displ=8, displ_size=1), R.RDX), ret), + "displaced memory operand"), + ("disp_mem_mulx", (Instruction.create_reg_reg_mem( + Code.VEX_MULX_R32_R32_RM32, R.R9D, R.EAX, MemoryOperand(R.RDX, displ=4, displ_size=1)), ret), + "displaced memory operand"), + ("disp_mem_pdep", (Instruction.create_reg_reg_mem( + Code.VEX_PDEP_R64_R64_RM64, R.RAX, R.RCX, MemoryOperand(R.R8, displ=8, displ_size=1)), ret), + "displaced memory operand"), + ("disp_mem_pext", (Instruction.create_reg_reg_mem( + Code.VEX_PEXT_R32_R32_RM32, R.EAX, R.ECX, MemoryOperand(R.RCX, displ=-4, displ_size=1)), ret), + "displaced memory operand"), + ("disp_mem_store_mov", (mov_rax_rcx, Instruction.create_mem_reg( + Code.MOV_RM64_R64, MemoryOperand(R.R8, displ=8, displ_size=1), R.RAX), ret), + "displaced memory operand"), + ("disp_mem_store_setcc", (cmp_rcx_rdx, mov_rax_rcx, Instruction.create_mem( + Code.SETB_RM8, MemoryOperand(R.R8, displ=1, displ_size=1)), ret), + "displaced memory operand"), + # RIP-relative, SIB-indexed, bad base, non-[r8] stores + ("rip_rel_pdep", (Instruction.create_reg_reg_mem( + Code.VEX_PDEP_R64_R64_RM64, R.RAX, R.RCX, MemoryOperand(R.RIP, displ=0x1020, displ_size=4)), ret), + "RIP-relative memory operand"), + ("sib_idx_pext", (Instruction.create_reg_reg_mem( + Code.VEX_PEXT_R64_R64_RM64, R.RAX, R.RCX, MemoryOperand(R.RCX, R.RDX, 8)), ret), + "SIB index memory operand"), + ("bad_base_rbx", (Instruction.create_reg_reg_mem( + Code.VEX_MULX_R64_R64_RM64, R.R9, R.RAX, MemoryOperand(R.RBX)), ret), + "bad base register in memory operand"), + ("bad_base_rsp", (Instruction.create_reg_mem_reg( + Code.VEX_BZHI_R32_RM32_R32, R.EAX, MemoryOperand(R.RSP), R.EDX), ret), + "bad base register in memory operand"), + ("non_r8_store_mov", (mov_rax_rcx, Instruction.create_mem_reg(Code.MOV_RM64_R64, MemoryOperand(R.RCX), R.RAX), ret), + "non-r8 store memory operand"), + ("non_r8_store_setcc", (cmp_rcx_rdx, mov_rax_rcx, Instruction.create_mem(Code.SETE_RM8, MemoryOperand(R.RDX)), ret), + "non-r8 store memory operand"), + # Undefined GPR / undefined flag / PF & AF readers after BZHI + ("undef_gpr_src", (Instruction.create_reg_reg_reg(Code.VEX_PDEP_R64_R64_RM64, R.RAX, R.R9, R.RDX), ret), + "undefined GPR r9"), + ("undef_gpr_idx", (Instruction.create_reg_reg_reg(Code.VEX_BZHI_R64_RM64_R64, R.RAX, R.RCX, R.R10), ret), + "undefined GPR r10"), + ("undef_rax_ret", (Instruction.create_reg_reg_reg(Code.VEX_PEXT_R64_R64_RM64, R.R9, R.RCX, R.RDX), ret), + "return with undefined RAX"), + ("undef_flags_setb", (mov_rax_rcx, Instruction.create_mem(Code.SETB_RM8, MemoryOperand(R.R8)), ret), + "undefined flags read"), + ("undef_flags_after_pdep", (Instruction.create_reg_reg_reg(Code.VEX_PDEP_R64_R64_RM64, R.RAX, R.RCX, R.RDX), + Instruction.create_mem(Code.SETE_RM8, MemoryOperand(R.R8)), ret), "undefined flags read"), + ("undef_pf_setp_after_bzhi", (cmp_rcx_rdx, bzhi_rax, Instruction.create_mem(Code.SETP_RM8, MemoryOperand(R.R8)), ret), + "undefined flags read"), + ("undef_pf_setnp_after_bzhi", (cmp_rcx_rdx, bzhi_rax, Instruction.create_mem(Code.SETNP_RM8, MemoryOperand(R.R8)), ret), + "undefined flags read"), + ("af_reader_lahf_after_bzhi", (bzhi_rax, Instruction.create(Code.LAHF), ret), + "unsupported instruction"), + ("af_reader_pushfq_after_bzhi", (bzhi_rax, Instruction.create(Code.PUSHFQ), ret), + "unsupported instruction"), + # Prefixes, branches, missing/trailing ret + ("seg_prefix_pext", (seg_pext, ret), "unsupported instruction prefix"), + ("branch_jmp", (mov_rax_rcx, Instruction.create_branch(Code.JMP_REL8_64, 0x1010), ret), + "non-leaf branch or call"), + ("missing_ret", (mov_rax_rcx,), "missing terminal ret"), + ("after_ret", (mov_rax_rcx, ret, mov_r9_rcx), "unreachable instruction after ret"), + ] + + raw_cases = [ + ("lock_prefix", bytes.fromhex("f00fb109") + encode_seq(mov_rax_rcx, ret), "unsupported instruction prefix"), + ("rep_prefix", bytes.fromhex("f3a4") + encode_seq(mov_rax_rcx, ret), "unsupported instruction prefix"), + ("empty_stream", b"", "truncated instruction stream"), + ] + + for label, seq, reason in unit_cases: + try: + lift_code(label, 0x1000, encode_seq(*seq)) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: translator accepted rejected control") + + for label, raw, reason in raw_cases: + try: + lift_code(label, 0x1000, raw) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: translator accepted raw rejected control") + + # End-to-end PE patching and CLI non-traceback rejection controls. + pe_bytes = Path(original_path).read_bytes() + with pefile.PE(data=pe_bytes, fast_load=True) as pe: + entry = export_rva(pe, "op_flags_preserve64") + file_off = pe.get_offset_from_rva(entry) + pdata = pe.OPTIONAL_HEADER.DATA_DIRECTORY[3] + records = pe.get_data(pdata.VirtualAddress, pdata.Size) + rec_idx = next(i for i in range(0, len(records), 12) if struct.unpack_from(" max_len: + raise AssertionError(f"{label}: patch ({len(patch)} bytes) exceeds max_len ({max_len})") + damaged = bytearray(pe_bytes) + damaged[file_off : file_off + len(patch)] = patch + struct.pack_into("> bit_idx) & 1 for p in seen_bzhi} != {0, 1}: + raise AssertionError(f"{name} did not exercise both 0 and 1 for {fname}") + if {(p >> 3) & 1 for p in seen_bzhi} != {0}: + raise AssertionError(f"{name} observed non-zero OF") + + # 4) Flag preservation across CMP -> PDEP/PEXT/MULX -> SETcc (CF, ZF, SF, OF, PF) + flag_pairs = [ + (0x0000000000000000, 0x0000000000000000), + (0x0000000000000000, 0x0000000000000001), + (0x0000000000000003, 0x0000000000000002), + (0x0000000080000000, 0x0000000000000001), + (0x000000007FFFFFFF, 0x00000000FFFFFFFF), + (0x8000000000000000, 0x0000000000000001), + (0x7FFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF), + ] + [(rng.getrandbits(64), rng.getrandbits(64)) for _ in range(24)] + + for bits, name in ((32, "op_flags_preserve32"), (64, "op_flags_preserve64")): + seen = set() + for a, b in flag_pairs: + f_tuple, packed4 = ref_cmp_flags(a, b, bits) + seen.add(f_tuple[:4]) + exp_buf = struct.pack("(word rcx, word rdx, word r8) +where rcx, rdx, and r8 enter as 64-bit integer arguments or flat pointers to caller-owned +buffers and RAX carries the 64-bit return value. + +Supported BMI2 bit-manipulation instructions (docs/coverage/x64_zen2.tsv group BMI/ADX): + - BZHI r32, r/m32, r32 | BZHI r64, r/m64, r64 (index = src2[7:0]; CF=1 if index>=width) + - MULX r32, r32, r/m32 | MULX r64, r64, r/m64 (implicit EDX/RDX src1; op0==op1 -> hi) + - PDEP r32, r32, r/m32 | PDEP r64, r64, r/m64 (parallel bit deposit, flagless) + - PEXT r32, r32, r/m32 | PEXT r64, r64, r/m64 (parallel bit extract, flagless) + +Exact SDM semantics: + - 32-bit destinations zero-extend into bits [63:32]. + - BZHI masks index to low 8 bits (index >= width preserves src and sets CF=1; index == 0 + yields 0 with CF=0; updates CF, ZF, SF, clears OF, and leaves PF/AF undefined). + - MULX reads implicit EDX/RDX and src2 before writing dst_lo then dst_hi (so op0==op1 + writes the high half) and leaves all flags unmodified. + - PDEP and PEXT leave all flags unmodified. + - Memory operands are flat zero-displacement [rcx|rdx|r8] loads read unconditionally via + load_always() so /O2 cannot eliminate faulting reads. + +Transport / flag-packing glue: + - Volatile scratch GPR (rax/r9/r10/r11) mov, movzx, cmp, xor, or, setcc (reg or [r8]), + flat zero-displacement [r8] stores, and terminal ret. + +EVEX/XOP encodings, shifts/rotates (legacy SHL/SHR/SAR/ROR/ROL and BMI2 RORX/SARX/SHLX/SHRX), +BMI1 (ANDN/BEXTR/BLSI/BLSMSK/BLSR/TZCNT), nonvolatile GPRs, writes to argument GPRs +(rcx/rdx/r8), high-byte GPRs, undefined GPR or flag reads (including PF/AF after BZHI), +RIP-relative/SIB-indexed/displaced/non-argument memory operands, stores outside [r8], +instruction prefixes, branches/calls, and missing or trailing instructions after ret are +rejected. +""" + +import argparse +from pathlib import Path + +import pefile +from iced_x86 import ( + Code, + Decoder, + EncodingKind, + FlowControl, + MemorySizeExt, + OpKind, + Register as R, + RegisterExt, +) + +from cpu_leaf_aot import bounded_code, export_rva + + +ARGUMENTS = {R.RCX: "rcx", R.RDX: "rdx", R.R8: "r8"} +ARGUMENT_NAMES = {"rcx", "rdx", "r8"} + +VOLATILE_GPR64 = { + R.RAX: "rax", + R.RCX: "rcx", + R.RDX: "rdx", + R.R8: "r8", + R.R9: "r9", + R.R10: "r10", + R.R11: "r11", +} +VOLATILE_GPR32 = { + R.EAX: "rax", + R.ECX: "rcx", + R.EDX: "rdx", + R.R8D: "r8", + R.R9D: "r9", + R.R10D: "r10", + R.R11D: "r11", +} +VOLATILE_GPR16 = { + R.AX: "rax", + R.CX: "rcx", + R.DX: "rdx", + R.R8W: "r8", + R.R9W: "r9", + R.R10W: "r10", + R.R11W: "r11", +} +VOLATILE_GPR8 = { + R.AL: "rax", + R.CL: "rcx", + R.DL: "rdx", + R.R8L: "r8", + R.R9L: "r9", + R.R10L: "r10", + R.R11L: "r11", +} +HIGH_BYTE_GPRS = {R.AH, R.CH, R.DH, R.BH} +NONVOLATILE_GPR = { + R.RBX, R.EBX, R.BX, R.BL, + R.RBP, R.EBP, R.BP, R.BPL, + R.RSI, R.ESI, R.SI, R.SIL, + R.RDI, R.EDI, R.DI, R.DIL, + R.RSP, R.ESP, R.SP, R.SPL, + R.R12, R.R12D, R.R12W, R.R12L, + R.R13, R.R13D, R.R13W, R.R13L, + R.R14, R.R14D, R.R14W, R.R14L, + R.R15, R.R15D, R.R15W, R.R15L, +} + +BMI2_BIT_SPECS = { + Code.VEX_BZHI_R32_RM32_R32: ("bzhi", 32), + Code.VEX_BZHI_R64_RM64_R64: ("bzhi", 64), + Code.VEX_MULX_R32_R32_RM32: ("mulx", 32), + Code.VEX_MULX_R64_R64_RM64: ("mulx", 64), + Code.VEX_PDEP_R32_R32_RM32: ("pdep", 32), + Code.VEX_PDEP_R64_R64_RM64: ("pdep", 64), + Code.VEX_PEXT_R32_R32_RM32: ("pext", 32), + Code.VEX_PEXT_R64_R64_RM64: ("pext", 64), +} + +MOV_WIDTHS = { + Code.MOV_R64_RM64: 64, + Code.MOV_RM64_R64: 64, + Code.MOV_RM64_IMM32: 64, + Code.MOV_R64_IMM64: 64, + Code.MOV_R32_RM32: 32, + Code.MOV_RM32_R32: 32, + Code.MOV_RM32_IMM32: 32, + Code.MOV_R32_IMM32: 32, + Code.MOV_R8_RM8: 8, + Code.MOV_RM8_R8: 8, + Code.MOV_RM8_IMM8: 8, + Code.MOV_R8_IMM8: 8, +} +MOVZX_SPECS = { + Code.MOVZX_R32_RM8: (32, 8), + Code.MOVZX_R64_RM8: (64, 8), +} +CMP_WIDTHS = { + Code.CMP_R32_RM32: 32, + Code.CMP_RM32_R32: 32, + Code.CMP_RM32_IMM8: 32, + Code.CMP_RM32_IMM32: 32, + Code.CMP_EAX_IMM32: 32, + Code.CMP_R64_RM64: 64, + Code.CMP_RM64_R64: 64, + Code.CMP_RM64_IMM8: 64, + Code.CMP_RM64_IMM32: 64, + Code.CMP_RAX_IMM32: 64, +} +XOR_WIDTHS = { + Code.XOR_R32_RM32: 32, + Code.XOR_RM32_R32: 32, + Code.XOR_RM32_IMM8: 32, + Code.XOR_R64_RM64: 64, + Code.XOR_RM64_R64: 64, + Code.XOR_RM64_IMM8: 64, +} +OR_WIDTHS = { + Code.OR_R32_RM32: 32, + Code.OR_RM32_R32: 32, + Code.OR_RM32_IMM8: 32, + Code.OR_R64_RM64: 64, + Code.OR_RM64_R64: 64, + Code.OR_RM64_IMM8: 64, +} +SETCC_SPECS = { + Code.SETB_RM8: ("cf", "flags.cf"), + Code.SETAE_RM8: ("cf", "!flags.cf"), + Code.SETE_RM8: ("zf", "flags.zf"), + Code.SETNE_RM8: ("zf", "!flags.zf"), + Code.SETS_RM8: ("sf", "flags.sf"), + Code.SETNS_RM8: ("sf", "!flags.sf"), + Code.SETO_RM8: ("of", "flags.of"), + Code.SETNO_RM8: ("of", "!flags.of"), + # PF is tracked solely to validate flag preservation and reject reads after BZHI. + Code.SETP_RM8: ("pf", "flags.pf"), + Code.SETNP_RM8: ("pf", "!flags.pf"), +} + +PRELUDE = """#include +#include +#include +#if defined(_MSC_VER) +#include +#endif + +using word = std::uint64_t; + +struct Flags { + bool cf = false; + bool zf = false; + bool sf = false; + bool of = false; + bool pf = false; +}; + +template +static inline T load_always(word address) { + std::atomic_signal_fence(std::memory_order_seq_cst); + T v{}; + std::memcpy(&v, reinterpret_cast(address), sizeof(T)); + const volatile T observed = v; + std::atomic_signal_fence(std::memory_order_seq_cst); + return observed; +} + +template +static inline void store_always(word address, T value) { + std::atomic_signal_fence(std::memory_order_seq_cst); + std::memcpy(reinterpret_cast(address), &value, sizeof(T)); + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +static inline bool parity_even(std::uint8_t byte) { + byte ^= static_cast(byte >> 4); + byte &= 0x0Fu; + return ((0x9669u >> byte) & 1u) != 0u; +} + +static inline word update_gpr_width(word cur, std::uint64_t val, unsigned width) { + if (width == 8u) { + return (cur & ~0xFFull) | (val & 0xFFull); + } + if (width == 32u) { + return val & 0xFFFFFFFFull; + } + return val; +} + +static inline void compute_cmp32(word lhs_w, word rhs_w, Flags& flags) { + const std::uint32_t a = static_cast(lhs_w); + const std::uint32_t b = static_cast(rhs_w); + const std::uint32_t r = a - b; + flags.cf = a < b; + flags.zf = r == 0u; + flags.sf = (r & 0x80000000u) != 0u; + flags.of = (((a ^ b) & (a ^ r)) & 0x80000000u) != 0u; + flags.pf = parity_even(static_cast(r)); +} + +static inline void compute_cmp64(word a, word b, Flags& flags) { + const word r = a - b; + flags.cf = a < b; + flags.zf = r == 0ull; + flags.sf = (r >> 63) != 0ull; + flags.of = (((a ^ b) & (a ^ r)) >> 63) != 0ull; + flags.pf = parity_even(static_cast(r)); +} + +static inline void compute_logic_flags(word result, unsigned width, Flags& flags) { + const std::uint64_t masked = (width == 32u) ? (result & 0xFFFFFFFFull) : result; + flags.cf = false; + flags.of = false; + flags.zf = masked == 0ull; + flags.sf = ((masked >> (width - 1u)) & 1ull) != 0ull; + flags.pf = parity_even(static_cast(masked)); +} + +// --- BMI2 BZHI / MULX / PDEP / PEXT helpers --- + +static inline word op_bzhi32(word src_w, word idx_w, Flags& flags) { + const std::uint32_t s = static_cast(src_w); + const unsigned idx = static_cast(idx_w & 0xFFull); + std::uint32_t d = 0u; + if (idx >= 32u) { + d = s; + flags.cf = true; + } else { + d = (idx == 0u) ? 0u : (s & ((1u << idx) - 1u)); + flags.cf = false; + } + flags.zf = (d == 0u); + flags.sf = (d & 0x80000000u) != 0u; + flags.of = false; + return static_cast(d); +} + +static inline word op_bzhi64(word s, word idx_w, Flags& flags) { + const unsigned idx = static_cast(idx_w & 0xFFull); + word d = 0ull; + if (idx >= 64u) { + d = s; + flags.cf = true; + } else { + d = (idx == 0u) ? 0ull : (s & ((1ull << idx) - 1ull)); + flags.cf = false; + } + flags.zf = (d == 0ull); + flags.sf = (d >> 63) != 0ull; + flags.of = false; + return d; +} + +static inline void op_mulx32(word src1_w, word src2_w, word& hi, word& lo) { + const std::uint64_t prod = static_cast(static_cast(src1_w)) + * static_cast(static_cast(src2_w)); + lo = prod & 0xFFFFFFFFull; + hi = prod >> 32; +} + +static inline void op_mulx64(word src1, word src2, word& hi, word& lo) { +#if defined(_MSC_VER) + word high = 0ull; + lo = _umul128(src1, src2, &high); + hi = high; +#else + const unsigned __int128 prod = static_cast(src1) * static_cast(src2); + lo = static_cast(prod); + hi = static_cast(prod >> 64); +#endif +} + +static inline word op_pdep32(word src_w, word mask_w) { + std::uint32_t s = static_cast(src_w); + std::uint32_t m = static_cast(mask_w); + std::uint32_t d = 0u; + while (m != 0u) { + const std::uint32_t lowest = m & (~m + 1u); + if ((s & 1u) != 0u) { + d |= lowest; + } + s >>= 1; + m &= ~lowest; + } + return static_cast(d); +} + +static inline word op_pdep64(word s, word m) { + word d = 0ull; + while (m != 0ull) { + const word lowest = m & (~m + 1ull); + if ((s & 1ull) != 0ull) { + d |= lowest; + } + s >>= 1; + m &= ~lowest; + } + return d; +} + +static inline word op_pext32(word src_w, word mask_w) { + const std::uint32_t s = static_cast(src_w); + std::uint32_t m = static_cast(mask_w); + std::uint32_t d = 0u; + std::uint32_t out_bit = 1u; + while (m != 0u) { + const std::uint32_t lowest = m & (~m + 1u); + if ((s & lowest) != 0u) { + d |= out_bit; + } + out_bit <<= 1; + m &= ~lowest; + } + return static_cast(d); +} + +static inline word op_pext64(word s, word m) { + word d = 0ull; + word out_bit = 1ull; + while (m != 0ull) { + const word lowest = m & (~m + 1ull); + if ((s & lowest) != 0ull) { + d |= out_bit; + } + out_bit <<= 1; + m &= ~lowest; + } + return d; +} + +#if defined(_MSC_VER) +extern "C" __declspec(dllexport) std::uint32_t host_has_bmi2() { + int info[4]{}; + __cpuid(info, 0); + if (info[0] < 7) return 0u; + __cpuidex(info, 7, 0); + return (static_cast(info[1]) & (1u << 8)) != 0u ? 1u : 0u; +} +#endif +""" + + +def gpr_info(register, ins): + """Map volatile GPR (64/32/16/8-bit low) to (name, width_bits), rejecting nonvolatile/high-byte.""" + if register in VOLATILE_GPR64: + return VOLATILE_GPR64[register], 64 + if register in VOLATILE_GPR32: + return VOLATILE_GPR32[register], 32 + if register in VOLATILE_GPR16: + return VOLATILE_GPR16[register], 16 + if register in VOLATILE_GPR8: + return VOLATILE_GPR8[register], 8 + if register in HIGH_BYTE_GPRS: + raise ValueError(f"unsupported high-byte GPR {register} at RVA {ins.ip:#x}: {ins}") + if register in NONVOLATILE_GPR: + raise ValueError(f"nonvolatile GPR {register} at RVA {ins.ip:#x}: {ins}") + raise ValueError(f"unsupported GPR {register} at RVA {ins.ip:#x}: {ins}") + + +def flat_address(ins, expected_bytes, *, write=False): + """Lower a flat zero-displacement [rcx|rdx|r8] memory operand (stores only to [r8]).""" + if ins.is_ip_rel_memory_operand or ins.memory_base in (R.RIP, R.EIP): + raise ValueError(f"RIP-relative memory operand at RVA {ins.ip:#x}: {ins}") + if ins.memory_index != R.NONE: + raise ValueError(f"SIB index memory operand at RVA {ins.ip:#x}: {ins}") + base = ins.memory_base + if base == R.NONE or not RegisterExt.is_gpr64(base) or base not in ARGUMENTS: + raise ValueError(f"bad base register in memory operand at RVA {ins.ip:#x}: {ins}") + if ins.memory_displacement != 0: + raise ValueError(f"displaced memory operand at RVA {ins.ip:#x}: {ins}") + if write and base != R.R8: + raise ValueError(f"non-r8 store memory operand at RVA {ins.ip:#x}: {ins}") + actual_bytes = MemorySizeExt.size(ins.memory_size) + if actual_bytes != expected_bytes: + raise ValueError( + f"unexpected {actual_bytes}-byte memory operand (expected {expected_bytes}) at RVA {ins.ip:#x}: {ins}" + ) + return ARGUMENTS[base] + + +def _immediate_value(ins, op_index, width): + kind = ins.op_kind(op_index) + if kind == OpKind.IMMEDIATE8: + return ins.immediate8 & 0xFF + if kind == OpKind.IMMEDIATE32: + return ins.immediate32 & 0xFFFFFFFF + if kind == OpKind.IMMEDIATE64: + return ins.immediate64 & 0xFFFFFFFFFFFFFFFF + if kind == OpKind.IMMEDIATE8TO32: + return ins.immediate8to32 & 0xFFFFFFFF + if kind == OpKind.IMMEDIATE8TO64: + return ins.immediate8to64 & 0xFFFFFFFFFFFFFFFF + if kind == OpKind.IMMEDIATE32TO64: + return ins.immediate32to64 & 0xFFFFFFFFFFFFFFFF + raise ValueError(f"unsupported immediate kind {kind} for {width}-bit op at RVA {ins.ip:#x}: {ins}") + + +def lift_code(name, start, raw): + """Decode and lift one bounded straight-line BMI2 BZHI/MULX/PDEP/PEXT leaf function.""" + instructions = list(Decoder(64, raw, ip=start)) + if not instructions or instructions[-1].next_ip != start + len(raw): + raise ValueError(f"truncated instruction stream in {name} at RVA {start:#x}") + if any(ins.is_invalid for ins in instructions): + bad = next(ins for ins in instructions if ins.is_invalid) + raise ValueError(f"invalid instruction at RVA {bad.ip:#x}") + + defined_gpr = {"rcx", "rdx", "r8"} + used_scratch = set() + defined_flags = set() + statements = [] + returned = False + + def note_scratch(reg_name): + if reg_name in ("r9", "r10", "r11"): + used_scratch.add(reg_name) + + def read_reg(op_index, ins, expected_width): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register operand {op_index} at RVA {ins.ip:#x}: {ins}") + reg_name, width = gpr_info(ins.op_register(op_index), ins) + if width != expected_width: + raise ValueError(f"unexpected GPR width {width} at RVA {ins.ip:#x}: {ins}") + if reg_name not in defined_gpr: + raise ValueError(f"undefined GPR {reg_name} at RVA {ins.ip:#x}: {ins}") + note_scratch(reg_name) + mask = {8: "0xFFull", 32: "0xFFFFFFFFull"}.get(width) + return f"({reg_name} & {mask})" if mask else reg_name + + def check_dst_reg(op_index, ins, expected_width, *, require_defined=False): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register destination at RVA {ins.ip:#x}: {ins}") + reg_name, width = gpr_info(ins.op_register(op_index), ins) + if width != expected_width: + raise ValueError(f"unexpected GPR destination width {width} at RVA {ins.ip:#x}: {ins}") + if reg_name in ARGUMENT_NAMES: + raise ValueError(f"cannot write argument GPR {reg_name} at RVA {ins.ip:#x}: {ins}") + if require_defined and reg_name not in defined_gpr: + raise ValueError(f"undefined GPR {reg_name} at RVA {ins.ip:#x}: {ins}") + note_scratch(reg_name) + return reg_name + + def read_rm(op_index, ins, width): + kind = ins.op_kind(op_index) + if kind == OpKind.REGISTER: + return read_reg(op_index, ins, width) + if kind == OpKind.MEMORY: + addr = flat_address(ins, width // 8, write=False) + ctype = {8: "std::uint8_t", 32: "std::uint32_t", 64: "std::uint64_t"}[width] + load_var = f"ld_{ins.ip:x}_{op_index}" + statements.append(f"const word {load_var} = static_cast(load_always<{ctype}>({addr}));") + return load_var + raise ValueError(f"unsupported operand at RVA {ins.ip:#x}: {ins}") + + for ins in instructions: + if returned: + raise ValueError(f"unreachable instruction after ret at RVA {ins.ip:#x}: {ins}") + if ins.has_lock_prefix or ins.has_rep_prefix or ins.has_repne_prefix or ins.has_segment_prefix: + raise ValueError(f"unsupported instruction prefix at RVA {ins.ip:#x}: {ins}") + + op_code = ins.op_code() + encoding = op_code.encoding + if encoding == EncodingKind.EVEX or ins.op_mask != R.NONE or ins.zeroing_masking or ins.is_broadcast: + raise ValueError(f"unsupported EVEX instruction at RVA {ins.ip:#x}: {ins}") + if encoding == EncodingKind.XOP: + raise ValueError(f"unsupported XOP instruction at RVA {ins.ip:#x}: {ins}") + if ins.code != Code.RETNQ and ins.flow_control != FlowControl.NEXT: + raise ValueError(f"non-leaf branch or call at RVA {ins.ip:#x}: {ins}") + + code = ins.code + if code in BMI2_BIT_SPECS: + if encoding != EncodingKind.VEX: + raise ValueError(f"expected VEX encoding for BMI2 op at RVA {ins.ip:#x}: {ins}") + mnemonic, width = BMI2_BIT_SPECS[code] + if mnemonic == "bzhi": + src_expr = read_rm(1, ins, width) + idx_expr = read_reg(2, ins, width) + dst = check_dst_reg(0, ins, width, require_defined=False) + statements.append(f"{dst} = op_bzhi{width}({src_expr}, {idx_expr}, flags);") + defined_gpr.add(dst) + # BZHI defines CF, ZF, SF, OF and leaves PF/AF undefined. + defined_flags = {"cf", "zf", "sf", "of"} + elif mnemonic == "mulx": + src1_expr = "(rdx & 0xFFFFFFFFull)" if width == 32 else "rdx" + src2_expr = read_rm(2, ins, width) + dst_hi = check_dst_reg(0, ins, width, require_defined=False) + dst_lo = check_dst_reg(1, ins, width, require_defined=False) + hi_var = f"mulx_hi_{ins.ip:x}" + lo_var = f"mulx_lo_{ins.ip:x}" + statements.append(f"word {hi_var} = 0ull;") + statements.append(f"word {lo_var} = 0ull;") + statements.append(f"op_mulx{width}({src1_expr}, {src2_expr}, {hi_var}, {lo_var});") + # Write dst_lo first, then dst_hi so op0 == op1 receives the high half per Intel SDM. + statements.append(f"{dst_lo} = {lo_var};") + statements.append(f"{dst_hi} = {hi_var};") + defined_gpr.add(dst_lo) + defined_gpr.add(dst_hi) + else: + src_expr = read_reg(1, ins, width) + mask_expr = read_rm(2, ins, width) + dst = check_dst_reg(0, ins, width, require_defined=False) + statements.append(f"{dst} = op_{mnemonic}{width}({src_expr}, {mask_expr});") + defined_gpr.add(dst) + elif encoding == EncodingKind.VEX: + raise ValueError(f"unsupported VEX instruction at RVA {ins.ip:#x}: {ins}") + elif code == Code.RETNQ: + if "rax" not in defined_gpr: + raise ValueError(f"return with undefined RAX at RVA {ins.ip:#x}") + statements.append("return rax;") + returned = True + elif code in MOV_WIDTHS: + width = MOV_WIDTHS[code] + if ins.op0_kind == OpKind.REGISTER and ins.op1_kind in (OpKind.REGISTER, OpKind.MEMORY): + src_expr = read_rm(1, ins, width) + dst = check_dst_reg(0, ins, width, require_defined=(width < 32)) + statements.append(f"{dst} = update_gpr_width({dst}, {src_expr}, {width}u);") + if width >= 32: + defined_gpr.add(dst) + elif ins.op0_kind == OpKind.MEMORY and ins.op1_kind == OpKind.REGISTER: + src_expr = read_rm(1, ins, width) + addr = flat_address(ins, width // 8, write=True) + ctype = {8: "std::uint8_t", 32: "std::uint32_t", 64: "std::uint64_t"}[width] + statements.append(f"store_always<{ctype}>({addr}, static_cast<{ctype}>({src_expr}));") + elif ins.op0_kind == OpKind.REGISTER: + imm = _immediate_value(ins, 1, width) + dst = check_dst_reg(0, ins, width, require_defined=(width < 32)) + statements.append(f"{dst} = update_gpr_width({dst}, {imm:#x}ull, {width}u);") + if width >= 32: + defined_gpr.add(dst) + elif ins.op0_kind == OpKind.MEMORY: + imm = _immediate_value(ins, 1, width) + addr = flat_address(ins, width // 8, write=True) + ctype = {8: "std::uint8_t", 32: "std::uint32_t", 64: "std::uint64_t"}[width] + statements.append(f"store_always<{ctype}>({addr}, static_cast<{ctype}>({imm:#x}ull));") + else: + raise ValueError(f"unsupported mov operands at RVA {ins.ip:#x}: {ins}") + elif code in MOVZX_SPECS: + dst_width, src_width = MOVZX_SPECS[code] + src_expr = read_rm(1, ins, src_width) + dst = check_dst_reg(0, ins, dst_width, require_defined=False) + statements.append(f"{dst} = {src_expr};") + defined_gpr.add(dst) + elif code in CMP_WIDTHS: + width = CMP_WIDTHS[code] + lhs_expr = read_rm(0, ins, width) + if ins.op1_kind in (OpKind.REGISTER, OpKind.MEMORY): + rhs_expr = read_rm(1, ins, width) + else: + rhs_expr = f"{_immediate_value(ins, 1, width):#x}ull" + statements.append(f"compute_cmp{width}({lhs_expr}, {rhs_expr}, flags);") + defined_flags = {"cf", "zf", "sf", "of", "pf"} + elif code in XOR_WIDTHS: + width = XOR_WIDTHS[code] + if ( + ins.op0_kind == OpKind.REGISTER + and ins.op1_kind == OpKind.REGISTER + and ins.op0_register == ins.op1_register + ): + dst = check_dst_reg(0, ins, width, require_defined=False) + statements.append(f"{dst} = 0ull;") + defined_gpr.add(dst) + else: + dst = check_dst_reg(0, ins, width, require_defined=True) + lhs_expr = read_reg(0, ins, width) + if ins.op1_kind in (OpKind.REGISTER, OpKind.MEMORY): + rhs_expr = read_rm(1, ins, width) + else: + rhs_expr = f"{_immediate_value(ins, 1, width):#x}ull" + statements.append(f"{dst} = update_gpr_width({dst}, {lhs_expr} ^ {rhs_expr}, {width}u);") + statements.append(f"compute_logic_flags({dst}, {width}u, flags);") + defined_flags = {"cf", "zf", "sf", "of", "pf"} + elif code in OR_WIDTHS: + width = OR_WIDTHS[code] + dst = check_dst_reg(0, ins, width, require_defined=True) + lhs_expr = read_reg(0, ins, width) + if ins.op1_kind in (OpKind.REGISTER, OpKind.MEMORY): + rhs_expr = read_rm(1, ins, width) + else: + rhs_expr = f"{_immediate_value(ins, 1, width):#x}ull" + statements.append(f"{dst} = update_gpr_width({dst}, {lhs_expr} | {rhs_expr}, {width}u);") + statements.append(f"compute_logic_flags({dst}, {width}u, flags);") + defined_flags = {"cf", "zf", "sf", "of", "pf"} + elif code in SETCC_SPECS: + flag_name, cond_expr = SETCC_SPECS[code] + if flag_name not in defined_flags: + raise ValueError(f"undefined flags read by {ins} at RVA {ins.ip:#x}") + if ins.op0_kind == OpKind.REGISTER: + dst = check_dst_reg(0, ins, 8, require_defined=True) + statements.append(f"{dst} = update_gpr_width({dst}, ({cond_expr}) ? 1ull : 0ull, 8u);") + elif ins.op0_kind == OpKind.MEMORY: + addr = flat_address(ins, 1, write=True) + statements.append( + f"store_always({addr}, static_cast(({cond_expr}) ? 1u : 0u));" + ) + else: + raise ValueError(f"unsupported setcc operand at RVA {ins.ip:#x}: {ins}") + else: + raise ValueError(f"unsupported instruction at RVA {ins.ip:#x}: {ins}") + + if not returned: + raise ValueError(f"missing terminal ret in {name} at RVA {start + len(raw):#x}") + + decls = [" word rax = 0ull;"] + for gpr in ("r9", "r10", "r11"): + if gpr in used_scratch: + decls.append(f" word {gpr} = 0ull;") + decls.append(" Flags flags{};") + body = [f" {stmt}" for stmt in statements] + lines = [ + f'extern "C" __declspec(dllexport) std::uint64_t lifted_{name}(word rcx, word rdx, word r8) {{', + " (void)rcx; (void)rdx; (void)r8;", + *decls, + *body, + "}", + ] + return "\n".join(lines), len(instructions) + + +def lift(pe, name): + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + source, count = lift_code(name, entry, raw) + return source, entry, count + + +def translate_pe(pe, names): + if pe.FILE_HEADER.Machine != 0x8664 or pe.OPTIONAL_HEADER.Magic != 0x20B: + raise ValueError("expected AMD64 PE32+") + lifted = [lift(pe, name) for name in names] + source = PRELUDE + "\n".join(f"\n{text}" for text, _, _ in lifted) + "\n" + meta = [(name, entry, count) for name, (_, entry, count) in zip(names, lifted)] + return source, meta + + +def translate(image, names): + with pefile.PE(str(image), fast_load=True) as pe: + return translate_pe(pe, names) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("image", type=Path) + parser.add_argument("exports", help="comma-separated export names") + parser.add_argument("output", type=Path) + args = parser.parse_args() + try: + source, meta = translate(args.image, [n for n in args.exports.split(",") if n]) + args.output.write_text(source, encoding="utf-8") + for name, entry, count in meta: + print(f"{name} at RVA {entry:#x}: {count} instructions") + except (ValueError, OSError, pefile.PEFormatError) as error: + parser.exit(1, f"{error}\n") From cf22fa995c86bd55d75a64c341a7710270ae5862 Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Thu, 26 Nov 2026 01:33:56 +0200 Subject: [PATCH 006/240] pe: sort package scan and harden CLI path guards in pe_package_preflight with CLI suite (#2609) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 3 + tests/pe_package_preflight_cli_check.py | 582 ++++++++++++++++++++++++ tools/pe_package_preflight.py | 32 +- 3 files changed, 612 insertions(+), 5 deletions(-) create mode 100644 tests/pe_package_preflight_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index fb058175c..88aad3b10 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -10273,6 +10273,9 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/dependency_paths_cli_check.py") add_test(NAME pe_package_import_closure COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/pe_package_preflight_check.py") + add_test(NAME pe_package_preflight_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/pe_package_preflight_cli_check.py") + set_tests_properties(pe_package_preflight_cli_check PROPERTIES TIMEOUT 60) add_test(NAME pe_inventory_cli_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/pe_inventory_cli_check.py") add_test(NAME call_evidence_check COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/pe_package_preflight_cli_check.py b/tests/pe_package_preflight_cli_check.py new file mode 100644 index 000000000..18f488a2c --- /dev/null +++ b/tests/pe_package_preflight_cli_check.py @@ -0,0 +1,582 @@ +#!/usr/bin/env python3 +"""Synthetic PE32+ CLI, deterministic scan, and error-handling suite for tools/pe_package_preflight.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +import json +from pathlib import Path +import runpy +import struct +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOLS_DIR = ROOT / "tools" +TOOL = TOOLS_DIR / "pe_package_preflight.py" +sys.path.insert(0, str(TOOLS_DIR)) +import pe_package_preflight # noqa: E402 + + +IMAGE_BASE = 0x180000000 +RAW_OFFSET = 0x200 +SECTION_RVA = 0x1000 +SECTION_SIZE = 0x1000 + + +def _build_pe32_plus( + *, + imports: tuple[tuple[str, str, str | int], ...] = (), + exports: tuple[tuple[str | None, str | None], ...] = (), + machine: int = 0x8664, +) -> bytes: + """Build a minimal synthetic PE32+ image with optional exports and normal/delay imports.""" + rdata = bytearray(SECTION_SIZE) + cursor = 0 + + def alloc(size: int, align: int = 4) -> int: + nonlocal cursor + cursor = (cursor + align - 1) & ~(align - 1) + rva = SECTION_RVA + cursor + if cursor + size > len(rdata): + raise AssertionError("synthetic .rdata overflow") + cursor += size + return rva + + def put(rva: int, blob: bytes) -> None: + offset = rva - SECTION_RVA + rdata[offset:offset + len(blob)] = blob + + export_rva = export_size = 0 + if exports: + code_rva = alloc(4, 4) + put(code_rva, b"\xC3\x90\x90\x90") + functions = [] + named_entries = [] + for idx, (symbol, forwarder) in enumerate(exports): + if forwarder is not None: + fwd_blob = forwarder.encode("ascii") + b"\0" + fwd_rva = alloc(len(fwd_blob), 2) + put(fwd_rva, fwd_blob) + functions.append(fwd_rva) + else: + functions.append(code_rva) + if symbol is not None: + name_blob = symbol.encode("ascii") + b"\0" + name_rva = alloc(len(name_blob), 2) + put(name_rva, name_blob) + named_entries.append((symbol, idx, name_rva)) + named_entries.sort(key=lambda item: item[0]) + + eat_rva = alloc(4 * len(functions), 4) + put(eat_rva, b"".join(struct.pack(" tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = pe_package_preflight.main(argv) + except SystemExit as exc: + code = exc.code + if not isinstance(code, int): + if code is not None: + stderr.write(f"{code}\n") + code = 0 if code is None else 1 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +def _make_synthetic_package(pkg: Path) -> None: + sub = pkg / "sub" + sub.mkdir() + (pkg / "app.exe").write_bytes( + _build_pe32_plus( + imports=( + ("normal", "helper.dll", "HelperInit"), + ("delay", "helper.dll", 2), + ("normal", "kernel32.dll", "ExitProcess"), + ) + ) + ) + (sub / "helper.dll").write_bytes( + _build_pe32_plus( + imports=(("normal", "core.dll", "CoreTick"),), + exports=(("HelperInit", None), (None, None)), + ) + ) + (sub / "core.dll").write_bytes( + _build_pe32_plus(exports=(("CoreTick", None),)) + ) + + +class PePackagePreflightCliPositiveTests(unittest.TestCase): + def test_stdout_and_atomic_output_with_zero_leftover_temps(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + pkg = base / "package" + pkg.mkdir() + _make_synthetic_package(pkg) + + # 1) Stdout mode (in-process + subprocess). + code, out, err = _run_main([str(pkg), "app.exe"]) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + report = json.loads(out) + self.assertEqual(report["schema"], 1) + self.assertEqual(report["entry"], "app.exe") + self.assertEqual(report["summary"]["images_scanned"], 3) + self.assertEqual(report["summary"]["images_reachable"], 3) + self.assertEqual(report["summary"]["static_imports"], 4) + self.assertEqual(report["summary"]["bundled_failures"], 0) + self.assertEqual(report["summary"]["external_unverified"], 1) + self.assertEqual(report["ignored_images"], []) + self.assertFalse(report["reachable"]["sub/helper.dll"]["conditional"]) + self.assertEqual( + report["reachable"]["sub/core.dll"]["path"], + ["app.exe", "sub/helper.dll", "sub/core.dll"], + ) + + proc = _run_subprocess(str(pkg), "app.exe") + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stderr, "") + self.assertEqual(json.loads(proc.stdout), report) + + # 2) Atomic --output creation into nested non-existent directory, 0 leftover temps. + nested_out = base / "reports" / "nested" / "preflight.json" + proc_out = _run_subprocess(str(pkg), "app.exe", "--output", str(nested_out)) + self.assertEqual(proc_out.returncode, 0, proc_out.stderr) + self.assertEqual(proc_out.stdout, "") + self.assertEqual(proc_out.stderr, "") + self.assertEqual(json.loads(nested_out.read_text(encoding="utf-8")), report) + self.assertEqual( + sorted(p.name for p in nested_out.parent.iterdir()), + ["preflight.json"], + ) + + # 3) Atomic replacement of pre-existing output file, 0 leftover temps. + nested_out.write_text("stale content", encoding="utf-8") + code_rep, out_rep, err_rep = _run_main([str(pkg), "app.exe", "--output", str(nested_out)]) + self.assertEqual(code_rep, 0, err_rep) + self.assertEqual(out_rep, "") + self.assertEqual(err_rep, "") + self.assertEqual(json.loads(nested_out.read_text(encoding="utf-8")), report) + self.assertEqual( + sorted(p.name for p in nested_out.parent.iterdir()), + ["preflight.json"], + ) + + # 4) sys.argv forwarding when argv=None and __main__ entrypoint. + cli_argv = [str(TOOL), str(pkg), "app.exe"] + with mock.patch.object(sys, "argv", cli_argv): + code_none, out_none, err_none = _run_main(None) + self.assertEqual(code_none, 0, err_none) + self.assertEqual(json.loads(out_none), report) + + stdout, stderr = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", cli_argv), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 0) + self.assertEqual(stderr.getvalue(), "") + self.assertEqual(json.loads(stdout.getvalue()), report) + + def test_unsorted_rglob_deterministic_order_and_cutoff(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + a_dir = root / "a_dir" + b_dir = root / "B_dir" + a_dir.mkdir() + b_dir.mkdir() + + entry = a_dir / "first.exe" + second = a_dir / "second.dll" + huge = b_dir / "huge.dll" + entry.write_bytes(b"a" * 100) + second.write_bytes(b"b" * 100) + huge.write_bytes(b"z" * 500) + + # Unsorted rglob puts B_dir/huge.dll first (and ASCII sort puts 'B' < 'a'); + # deterministic casefold sort visits a_dir/first.exe, a_dir/second.dll before B_dir/huge.dll. + unsorted_paths = [huge, second, entry] + with ( + mock.patch.object(Path, "rglob", return_value=iter(unsorted_paths)), + mock.patch.object(pe_package_preflight, "MAX_IMAGE_BYTES", 300), + mock.patch.object(pe_package_preflight, "MAX_IMAGES", 1), + ): + with self.assertRaisesRegex(ValueError, "1024 PE image inspection limit"): + pe_package_preflight._paths(root.resolve()) + + with ( + mock.patch.object(Path, "rglob", return_value=iter(unsorted_paths)), + mock.patch.object(pe_package_preflight, "MAX_IMAGE_BYTES", 300), + mock.patch.object(pe_package_preflight, "MAX_TOTAL_BYTES", 150), + ): + with self.assertRaisesRegex(ValueError, "2 GiB PE inspection limit"): + pe_package_preflight._paths(root.resolve()) + + with tempfile.TemporaryDirectory() as tmp: + pkg = Path(tmp) + _make_synthetic_package(pkg) + forward = [pkg / "app.exe", pkg / "sub" / "core.dll", pkg / "sub" / "helper.dll"] + reversed_order = list(reversed(forward)) + with mock.patch.object(Path, "rglob", return_value=iter(forward)): + code_a, out_a, err_a = _run_main([str(pkg), "app.exe"]) + with mock.patch.object(Path, "rglob", return_value=iter(reversed_order)): + code_b, out_b, err_b = _run_main([str(pkg), "app.exe"]) + self.assertEqual(code_a, 0, err_a) + self.assertEqual(code_b, 0, err_b) + self.assertEqual(out_a, out_b) + + +class PePackagePreflightCliNegativeTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_code: int | None, + fragments: tuple[str, ...] = (), + check_subprocess: bool = True, + ) -> str: + code, out, err = _run_main(argv) + if expected_code is None: + self.assertNotEqual(code, 0) + else: + self.assertEqual(code, expected_code, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertTrue(err.strip()) + for fragment in fragments: + self.assertIn(fragment.lower(), err.lower()) + + if check_subprocess: + proc = _run_subprocess(*argv) + if expected_code is None: + self.assertNotEqual(proc.returncode, 0) + else: + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + for fragment in fragments: + self.assertIn(fragment.lower(), proc.stderr.lower()) + return err + + def test_root_is_dir_and_non_empty_entry_validated_before_inspect(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + pkg = base / "package" + pkg.mkdir() + _make_synthetic_package(pkg) + + not_a_dir = base / "regular.txt" + not_a_dir.write_text("not a directory", encoding="utf-8") + + with mock.patch.object( + pe_package_preflight, + "inspect", + side_effect=AssertionError("inspect called for invalid package/entry"), + ): + self._assert_clean_failure( + [str(base / "missing_pkg"), "app.exe"], + expected_code=1, + fragments=("pe_package_preflight:",), + ) + self._assert_clean_failure( + [str(not_a_dir), "app.exe"], + expected_code=1, + fragments=("pe_package_preflight:", "Package root must be a directory"), + ) + for blank_entry in ("", " "): + with self.subTest(entry=blank_entry): + self._assert_clean_failure( + [str(pkg), blank_entry], + expected_code=1, + fragments=("pe_package_preflight:", "Entry must be"), + ) + + for blank_entry in ("", " "): + with self.subTest(direct_entry=blank_entry): + with self.assertRaisesRegex(ValueError, "Entry must be"): + pe_package_preflight.inspect(pkg, blank_entry) + + def test_output_collision_dir_inside_pkg_rejected_before_temp_staging(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + pkg = base / "package" + pkg.mkdir() + _make_synthetic_package(pkg) + + file_parent = base / "collision.txt" + file_parent.write_text("keep-me", encoding="utf-8") + out_dir = base / "existing_dir" + out_dir.mkdir() + + cases = ( + ("parent_regular_file", file_parent / "report.json", ("not a directory",)), + ("ancestor_regular_file", file_parent / "nested" / "report.json", ("not a directory",)), + ("output_is_dir", out_dir, ("directory",)), + ("output_empty_string", Path(""), ("directory",)), + ("output_inside_pkg_root", pkg, ("outside the inspected package",)), + ("output_inside_pkg_file", pkg / "report.json", ("outside the inspected package",)), + ("output_inside_pkg_nested", pkg / "new_sub" / "report.json", ("outside the inspected package",)), + ) + for label, target, frags in cases: + with self.subTest(case=label): + with ( + mock.patch.object( + pe_package_preflight, + "inspect", + side_effect=AssertionError(f"inspect called for {label}"), + ), + mock.patch.object( + pe_package_preflight.tempfile, + "TemporaryDirectory", + side_effect=AssertionError(f"temp staging called for {label}"), + ), + ): + argv = [str(pkg), "app.exe", "--output", "" if label == "output_empty_string" else str(target)] + self._assert_clean_failure( + argv, + expected_code=1, + fragments=("pe_package_preflight:", *frags), + ) + + self.assertEqual(file_parent.read_text(encoding="utf-8"), "keep-me") + self.assertEqual(list(out_dir.iterdir()), []) + self.assertFalse((pkg / "report.json").exists()) + self.assertFalse((pkg / "new_sub").exists()) + + def test_output_symlink_rejected_before_temp_staging(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + pkg = base / "package" + pkg.mkdir() + _make_synthetic_package(pkg) + + out_dir = base / "out_dir" + out_dir.mkdir() + real_target = out_dir / "real.json" + real_target.write_text("untouched", encoding="utf-8") + live_link = out_dir / "live_link.json" + dangling_link = out_dir / "dangling_link.json" + try: + live_link.symlink_to(real_target) + dangling_link.symlink_to(out_dir / "nonexistent.json") + except OSError as exc: + if getattr(exc, "winerror", None) != 1314: + raise + self.skipTest("this Windows account cannot create symlinks (WinError 1314)") + + for label, target in (("live_symlink", live_link), ("dangling_symlink", dangling_link)): + with self.subTest(case=label): + with ( + mock.patch.object( + pe_package_preflight, + "inspect", + side_effect=AssertionError(f"inspect called for {label}"), + ), + mock.patch.object( + pe_package_preflight.tempfile, + "TemporaryDirectory", + side_effect=AssertionError(f"temp staging called for {label}"), + ), + ): + self._assert_clean_failure( + [str(pkg), "app.exe", "--output", str(target)], + expected_code=1, + fragments=("pe_package_preflight:", "symlink"), + ) + + self.assertEqual(real_target.read_text(encoding="utf-8"), "untouched") + self.assertEqual( + sorted(p.name for p in out_dir.iterdir()), + ["dangling_link.json", "live_link.json", "real.json"], + ) + + def test_temp_staging_replace_failure_leaves_zero_leftover_temps(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + pkg = base / "package" + pkg.mkdir() + _make_synthetic_package(pkg) + + out_dir = base / "out_dir" + out_dir.mkdir() + out_file = out_dir / "report.json" + out_file.write_text("original", encoding="utf-8") + + with mock.patch.object(Path, "replace", side_effect=OSError("simulated replace failure")): + self._assert_clean_failure( + [str(pkg), "app.exe", "--output", str(out_file)], + expected_code=1, + fragments=("pe_package_preflight:", "simulated replace failure"), + check_subprocess=False, + ) + + self.assertEqual(out_file.read_text(encoding="utf-8"), "original") + self.assertEqual(sorted(p.name for p in out_dir.iterdir()), ["report.json"]) + + def test_invalid_pe_and_missing_entry_do_not_create_output_dir_or_temps(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + pkg = base / "package" + pkg.mkdir() + (pkg / "bad.exe").write_bytes(b"not a valid PE") + absent_out = base / "should_not_exist" / "report.json" + + self._assert_clean_failure( + [str(pkg), "bad.exe", "--output", str(absent_out)], + expected_code=1, + fragments=("pe_package_preflight:",), + ) + self.assertFalse(absent_out.parent.exists()) + + _make_synthetic_package(pkg) + self._assert_clean_failure( + [str(pkg), "missing.exe", "--output", str(absent_out)], + expected_code=1, + fragments=("pe_package_preflight:",), + ) + self.assertFalse(absent_out.parent.exists()) + + def test_argparse_errors_py314_safe(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + pkg = Path(tmp) + _make_synthetic_package(pkg) + cases = ( + ([], ("required",)), + ([str(pkg)], ("required",)), + ([str(pkg), "app.exe", "--bogus-flag"], ("unrecognized",)), + ([str(pkg), "app.exe", "--output"], ("expected one argument",)), + ) + for argv, frags in cases: + with self.subTest(argv=argv): + self._assert_clean_failure( + argv, + expected_code=None, + fragments=frags, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/pe_package_preflight.py b/tools/pe_package_preflight.py index 4af2e57a5..89c3dd462 100644 --- a/tools/pe_package_preflight.py +++ b/tools/pe_package_preflight.py @@ -9,6 +9,7 @@ import heapq import json from pathlib import Path +import struct import sys import tempfile @@ -35,7 +36,7 @@ def _relative(root, path): def _paths(root): result = {} total_bytes = 0 - for path in root.rglob("*"): + for path in sorted(root.rglob("*"), key=lambda p: (p.as_posix().casefold(), p.as_posix())): if path.suffix.casefold() not in (".dll", ".exe"): continue if path.is_symlink(): @@ -160,7 +161,25 @@ def packaged(module): ignored_images=sorted(set(images) - set(reached))) +def _validate_entry(entry): + if not isinstance(entry, str) or not entry.strip(): + raise ValueError("Entry must be a non-empty relative path to an .exe inside the package") + + +def _validate_output(output, root): + if output.is_symlink(): + raise ValueError(f"Output path must not be a symlink: {output}") + for parent in output.parents: + if parent.is_file() or ((parent.exists() or parent.is_symlink()) and not parent.is_dir()): + raise NotADirectoryError(f"Output parent is not a directory: {parent}") + if output.resolve().is_relative_to(root): + raise ValueError("Write reports outside the inspected package") + if output.is_dir(): + raise IsADirectoryError(f"Output path is a directory: {output}") + + def inspect(root, entry): + _validate_entry(entry) root = Path(root).resolve(strict=True) if not root.is_dir(): raise ValueError("Package root must be a directory") @@ -183,11 +202,14 @@ def main(argv=None): args = parser.parse_args(argv) try: root = args.package.resolve(strict=True) - if args.output and args.output.resolve().is_relative_to(root): - raise ValueError("Write reports outside the inspected package") + if not root.is_dir(): + raise ValueError("Package root must be a directory") + _validate_entry(args.entry) + if args.output is not None: + _validate_output(args.output, root) report = inspect(root, args.entry) output = json.dumps(report, indent=2, sort_keys=True, ensure_ascii=True) + "\n" - if args.output: + if args.output is not None: args.output.parent.mkdir(parents=True, exist_ok=True) # Replace the directory entry instead of writing through a possible hard link. with tempfile.TemporaryDirectory(dir=args.output.parent) as directory: @@ -196,7 +218,7 @@ def main(argv=None): report_path.replace(args.output) else: print(output, end="") - except (OSError, ValueError, KeyError, pefile.PEFormatError) as exc: + except (OSError, ValueError, KeyError, struct.error, pefile.PEFormatError) as exc: parser.exit(1, f"pe_package_preflight: {exc}\n") return 0 From b97bb64d250f5d5ce04290860de1fe4c7b4c918a Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Thu, 26 Nov 2026 01:34:49 +0200 Subject: [PATCH 007/240] shader: harden rdna_cvt_pk_u8 CLI validation and atomic writes with CLI suite (#2619) --- CMakeLists.txt | 3 + tests/rdna_cvt_pk_u8_cli_check.py | 505 ++++++++++++++++++++++++++++++ tools/rdna_cvt_pk_u8.py | 230 ++++++++++---- 3 files changed, 680 insertions(+), 58 deletions(-) create mode 100644 tests/rdna_cvt_pk_u8_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 88aad3b10..d9cd0bdbc 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -10202,6 +10202,9 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_CURRENT_BINARY_DIR}/triangle_vs.cso" "${DXC_BIN_DIR}/dxil.dll") set_tests_properties(shader_metadata_probe PROPERTIES SKIP_RETURN_CODE 77) add_test(NAME shader_metadata_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/shader_probe_check.py") + add_test(NAME shader_rdna_cvt_pk_u8_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/rdna_cvt_pk_u8_cli_check.py") + set_tests_properties(shader_rdna_cvt_pk_u8_cli_check PROPERTIES TIMEOUT 60) add_test(NAME shader_metadata_census COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/shader_census_check.py") add_test(NAME shader_profile_audit_check COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/rdna_cvt_pk_u8_cli_check.py b/tests/rdna_cvt_pk_u8_cli_check.py new file mode 100644 index 000000000..8194c9f35 --- /dev/null +++ b/tests/rdna_cvt_pk_u8_cli_check.py @@ -0,0 +1,505 @@ +"""Pure-Python CLI, atomic-write, path-collision, error-guard, and mutation suite for tools/rdna_cvt_pk_u8.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +import json +import os +from pathlib import Path +import runpy +import subprocess +import sys +from tempfile import TemporaryDirectory +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "rdna_cvt_pk_u8.py" +MEASURED_TSV = ROOT / "tests" / "data" / "rdna_cvt_pk_u8_measured.tsv" +sys.path.insert(0, str(ROOT / "tools")) + +import rdna_cvt_pk_u8 # noqa: E402 + + +def _run_main(argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = rdna_cvt_pk_u8.main(argv) + except SystemExit as exc: + return exc.code, stdout.getvalue(), stderr.getvalue() + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str, cwd: Path | None = None) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + cwd=str(cwd) if cwd is not None else None, + timeout=30, + ) + + +class _FakeHip: + device = 0 + + def __init__(self) -> None: + self.calls: list[tuple[str, int]] = [] + + def count(self) -> int: + return 2 + + def arch(self, device: int | None = None) -> str: + idx = self.device if device is None else device + return "gfx1030:sramecc-:xnack-" if idx == 0 else "gfx1036" + + def run_kernel(self, hsaco: bytes, kname: str, words: list[tuple[int, int]]) -> list[int]: + self.calls.append((kname, len(words))) + model = "trunc_sat_nan0" if kname.endswith("_rtz") else "rne_sat_nan0" + return [rdna_cvt_pk_u8.model_word(model, b, s) for b, s in words] + + +def _fake_build(arch: str, variant: str, workdir: str, args) -> tuple[bytes, str]: + out = Path(workdir) / f"{variant}_{arch}.hsaco" + out.write_bytes(b"HSACO_" + variant.encode("ascii")) + return out.read_bytes(), str(out) + + +class RdnaCvtPkU8CliPositiveTests(unittest.TestCase): + def test_self_test_direct_argv_and_subprocess(self) -> None: + code, out, err = _run_main(["--self-test"]) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertIn("self-test OK", out) + + with mock.patch.object(sys, "argv", [str(TOOL), "--self-test"]): + code_default, out_default, err_default = _run_main(None) + self.assertIs(type(code_default), int) + self.assertEqual(code_default, 0, err_default) + self.assertIn("self-test OK", out_default) + + stdout = io.StringIO() + stderr = io.StringIO() + with ( + mock.patch.object(sys, "argv", [str(TOOL), "--self-test"]), + redirect_stdout(stdout), + redirect_stderr(stderr), + self.assertRaises(SystemExit) as exited, + ): + runpy.run_path(str(TOOL), run_name="__main__") + self.assertIs(type(exited.exception.code), int) + self.assertEqual(exited.exception.code, 0) + self.assertIn("self-test OK", stdout.getvalue()) + self.assertEqual(stderr.getvalue(), "") + + proc = _run_subprocess("--self-test") + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stderr, "") + self.assertIn("self-test OK", proc.stdout) + + def test_mocked_hip_writes_tsv_and_json_atomically_and_matches_measured(self) -> None: + expected_rows = [ + line.rstrip("\n") + for line in MEASURED_TSV.read_text(encoding="utf-8").splitlines() + if not line.startswith("#") + ] + self.assertEqual(len(expected_rows), 5432) + + with TemporaryDirectory() as tmp: + root = Path(tmp) + out_tsv = root / "tsv_dir" / "rdna_cvt_pk_u8.tsv" + out_json = root / "json_dir" / "rdna_cvt_pk_u8.json" + seen_replaces: list[tuple[Path, Path]] = [] + real_replace = os.replace + created_workdirs: list[Path] = [] + real_mkdtemp = rdna_cvt_pk_u8.tempfile.mkdtemp + + def tracking_replace(src, dst): + src_p, dst_p = Path(src), Path(dst) + seen_replaces.append((src_p, dst_p)) + self.assertEqual(src_p.parent.resolve(), dst_p.parent.resolve()) + return real_replace(src, dst) + + def tracking_mkdtemp(**kwargs): + d = Path(real_mkdtemp(**kwargs)) + created_workdirs.append(d) + return str(d) + + with ( + mock.patch.object(rdna_cvt_pk_u8, "Hip", _FakeHip), + mock.patch.object(rdna_cvt_pk_u8, "build", side_effect=_fake_build), + mock.patch.object(rdna_cvt_pk_u8.os, "replace", side_effect=tracking_replace), + mock.patch.object(rdna_cvt_pk_u8.tempfile, "mkdtemp", side_effect=tracking_mkdtemp), + ): + code, out, err = _run_main([ + "--out", str(out_tsv), + "--json", str(out_json), + "--show", "0", + ]) + + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertIn("HIP device 0: gfx1030:sramecc-:xnack- <- used", out) + self.assertIn("HIP device 1: gfx1036", out) + self.assertIn("rows identical to", out) + self.assertIn("results written to", out) + self.assertIn("verbose JSON written to", out) + + self.assertEqual(len(created_workdirs), 1) + self.assertFalse(created_workdirs[0].exists()) + + self.assertEqual(len(seen_replaces), 2) + self.assertEqual( + {dst.resolve() for _, dst in seen_replaces}, + {out_tsv.resolve(), out_json.resolve()}, + ) + self.assertEqual([p.name for p in out_tsv.parent.iterdir()], [out_tsv.name]) + self.assertEqual([p.name for p in out_json.parent.iterdir()], [out_json.name]) + + tsv_lines = out_tsv.read_text(encoding="utf-8").splitlines() + self.assertIn("# device gfx1030", tsv_lines) + tsv_rows = [line for line in tsv_lines if not line.startswith("#")] + self.assertEqual(tsv_rows, expected_rows) + + doc = json.loads(out_json.read_text(encoding="utf-8")) + self.assertEqual(doc["arch"], "gfx1030") + self.assertEqual(doc["sentinel"], rdna_cvt_pk_u8.SENTINEL) + self.assertEqual(len(doc["rows"]), 5432) + self.assertEqual(doc["summary"]["default"]["matching_models"], ["rne_sat_nan0"]) + self.assertEqual(doc["summary"]["rtz"]["matching_models"], ["trunc_sat_nan0"]) + self.assertEqual(doc["summary"]["flush"]["matching_models"], ["rne_sat_nan0"]) + + def test_asm_only_with_keep_and_compare_diff_report(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + keep_dir = root / "keep_artifacts" + with mock.patch.object(rdna_cvt_pk_u8, "build", side_effect=_fake_build): + code, out, err = _run_main(["--asm-only", "--arch", "gfx1030", "--keep", str(keep_dir)]) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertIn("built default", out) + self.assertTrue((keep_dir / "default_gfx1030.hsaco").is_file()) + + # Compare with a modified TSV triggers the DIFFER summary line without failing. + ref_lines = MEASURED_TSV.read_text(encoding="utf-8").splitlines() + for idx, line in enumerate(ref_lines): + if not line.startswith("#"): + parts = line.split("\t") + parts[3] = "00000000" + ref_lines[idx] = "\t".join(parts) + break + diff_ref = root / "diff_ref.tsv" + diff_ref.write_text("\n".join(ref_lines) + "\n", encoding="utf-8") + out_tsv = root / "out.tsv" + + with ( + mock.patch.object(rdna_cvt_pk_u8, "Hip", _FakeHip), + mock.patch.object(rdna_cvt_pk_u8, "build", side_effect=_fake_build), + ): + code2, out2, err2 = _run_main([ + "--out", str(out_tsv), + "--compare", str(diff_ref), + ]) + self.assertEqual(code2, 0, err2) + self.assertEqual(err2, "") + self.assertIn("rows DIFFER from", out2) + self.assertIn("(1 of 5432 rows)", out2) + + +class RdnaCvtPkU8CliNegativeAndMutationTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_code: int = 1, + expected_fragments: tuple[str, ...] = (), + check_subprocess: bool = True, + allow_stdout: bool = False, + cwd: Path | None = None, + ) -> str: + code, out, err = _run_main(argv) + self.assertIs(type(code), int) + self.assertEqual(code, expected_code, err) + if not allow_stdout: + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertTrue(err.strip(), f"expected stderr output for {argv!r}") + for fragment in expected_fragments: + self.assertIn(fragment, err) + + if check_subprocess: + proc = _run_subprocess(*argv, cwd=cwd) + self.assertEqual(proc.returncode, expected_code, proc.stderr) + if not allow_stdout: + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertTrue(proc.stderr.strip(), f"expected subprocess stderr output for {argv!r}") + for fragment in expected_fragments: + self.assertIn(fragment, proc.stderr) + return err + + def test_asm_only_needs_arch_and_hip_runtime_errors(self) -> None: + # --asm-only without --arch -> stderr + return 2 (not SystemExit). + with mock.patch.object(rdna_cvt_pk_u8, "Hip", side_effect=AssertionError("Hip() must not run")): + self._assert_clean_failure( + ["--asm-only"], + expected_code=2, + expected_fragments=("error: --asm-only needs --arch",), + ) + + with TemporaryDirectory() as tmp: + out_tsv = Path(tmp) / "out.tsv" + with mock.patch.object(rdna_cvt_pk_u8, "Hip", side_effect=RuntimeError("no HIP dll")): + self._assert_clean_failure( + ["--out", str(out_tsv)], + expected_code=2, + expected_fragments=("error: no HIP dll",), + check_subprocess=False, + ) + + class _FailingKernelHip(_FakeHip): + def run_kernel(self, hsaco, kname, words): + raise RuntimeError("kernel launch failed") + + with ( + mock.patch.object(rdna_cvt_pk_u8, "Hip", _FailingKernelHip), + mock.patch.object(rdna_cvt_pk_u8, "build", side_effect=_fake_build), + ): + self._assert_clean_failure( + ["--out", str(out_tsv)], + expected_code=3, + expected_fragments=("error: kernel launch failed",), + check_subprocess=False, + allow_stdout=True, + ) + self.assertFalse(out_tsv.exists()) + + def test_flag_and_path_type_validation_guards(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + reg_file = root / "regular.txt" + reg_file.write_text("keep-me", encoding="utf-8") + existing_dir = root / "existing_dir" + existing_dir.mkdir() + valid_out = root / "ok.tsv" + + cases = [ + (["--show", "-1", "--out", str(valid_out)], "--show must be >= 0", True), + (["--keep", "", "--out", str(valid_out)], "--keep path must not be empty", True), + (["--keep", str(reg_file), "--out", str(valid_out)], "--keep path is not a directory", True), + (["--keep", str(reg_file / "sub"), "--out", str(valid_out)], "--keep parent path is not a directory", True), + (["--compare", str(existing_dir), "--out", str(valid_out)], "--compare path is a directory", True), + (["--out", ""], "--out path must not be empty", True), + (["--out", str(existing_dir) + os.sep], "--out path is a directory path", True), + (["--out", str(existing_dir)], "--out path is a directory", True), + (["--out", str(reg_file / "child.tsv")], "--out parent path is not a directory", True), + (["--out", str(reg_file / "sub" / "child.tsv")], "--out parent path is not a directory", True), + (["--out", str(valid_out), "--json", ""], "--json path must not be empty", True), + (["--out", str(valid_out), "--json", str(existing_dir) + "/"], "--json path is a directory path", True), + (["--out", str(valid_out), "--json", str(existing_dir)], "--json path is a directory", True), + (["--out", str(valid_out), "--json", str(reg_file / "child.json")], "--json parent path is not a directory", True), + ] + for argv, fragment, subproc in cases: + with self.subTest(argv=argv): + with ( + mock.patch.object(rdna_cvt_pk_u8, "Hip", side_effect=AssertionError("Hip() must not run")), + mock.patch.object(rdna_cvt_pk_u8, "build", side_effect=AssertionError("build() must not run")), + ): + self._assert_clean_failure( + argv, + expected_code=1, + expected_fragments=("error:", fragment), + check_subprocess=subproc, + ) + self.assertEqual(reg_file.read_text(encoding="utf-8"), "keep-me") + self.assertEqual(list(existing_dir.iterdir()), []) + + def test_symlink_output_guards_kill_mutations(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + target = root / "target.txt" + target.write_text("do-not-clobber", encoding="utf-8") + valid_out = root / "valid.tsv" + + for flag, name in (("--out", "out_link.tsv"), ("--json", "json_link.json")): + link = root / name + try: + link.symlink_to(target) + created_real = True + except OSError as exc: + if getattr(exc, "winerror", None) != 1314: + raise + created_real = False + + argv = [flag, str(link)] if flag == "--out" else ["--out", str(valid_out), flag, str(link)] + if created_real: + self._assert_clean_failure( + argv, + expected_code=1, + expected_fragments=("error:", f"{flag} path must not be a symlink"), + ) + link.unlink() + else: + with ( + mock.patch.object( + Path, + "is_symlink", + autospec=True, + side_effect=lambda p, expected=link: os.path.normcase(str(p.resolve())) + == os.path.normcase(str(expected.resolve())), + ), + mock.patch.object(rdna_cvt_pk_u8, "Hip", side_effect=AssertionError("Hip() must not run")), + ): + self._assert_clean_failure( + argv, + expected_code=1, + expected_fragments=("error:", f"{flag} path must not be a symlink"), + check_subprocess=False, + ) + self.assertEqual(target.read_text(encoding="utf-8"), "do-not-clobber") + + def test_collision_guards_alias_nonexistent_and_hardlink(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + sub = root / "sub" + sub.mkdir() + ref = root / "ref.tsv" + ref.write_text("# ref\n", encoding="utf-8") + ref_hardlink = root / "ref_hardlink.tsv" + os.link(ref, ref_hardlink) + self.assertNotEqual(ref.resolve(), ref_hardlink.resolve()) + self.assertTrue(ref.samefile(ref_hardlink)) + + ghost_a = root / "ghost.txt" + ghost_b = sub / ".." / "ghost.txt" + other_out = root / "other_out.tsv" + + collision_cases = [ + (["--out", str(ref), "--compare", str(ref)], "--out path collides with --compare"), + (["--out", str(sub / ".." / "ref.tsv"), "--compare", str(ref)], "--out path collides with --compare"), + (["--out", str(ref_hardlink), "--compare", str(ref)], "--out path collides with --compare"), + (["--out", str(ghost_a), "--compare", str(ghost_b)], "--out path collides with --compare"), + (["--out", str(other_out), "--json", str(ref), "--compare", str(ref)], "--json path collides with --compare"), + (["--out", str(other_out), "--json", str(ref_hardlink), "--compare", str(ref)], "--json path collides with --compare"), + (["--out", str(ghost_a), "--json", str(ghost_b)], "--out and --json paths must not collide"), + (["--out", str(ref), "--json", str(ref_hardlink)], "--out and --json paths must not collide"), + (["--keep", str(ghost_a), "--out", str(ghost_b)], "--keep and --out paths must not collide"), + ] + for argv, fragment in collision_cases: + with self.subTest(argv=argv): + with mock.patch.object(rdna_cvt_pk_u8, "Hip", side_effect=AssertionError("Hip() must not run")): + self._assert_clean_failure( + argv, + expected_code=1, + expected_fragments=("error:", fragment), + ) + self.assertEqual(ref.read_text(encoding="utf-8"), "# ref\n") + + def test_atomic_write_and_compare_failures_leave_zero_temps(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + out_tsv = root / "out_dir" / "res.tsv" + out_json = root / "json_dir" / "res.json" + out_tsv.parent.mkdir() + out_json.parent.mkdir() + out_tsv.write_text("PRIOR_TSV", encoding="utf-8") + out_json.write_text("PRIOR_JSON", encoding="utf-8") + + # 1) os.replace fails on --out: prior files preserved, zero sibling .tmp leftovers. + with ( + mock.patch.object(rdna_cvt_pk_u8, "Hip", _FakeHip), + mock.patch.object(rdna_cvt_pk_u8, "build", side_effect=_fake_build), + mock.patch.object(rdna_cvt_pk_u8.os, "replace", side_effect=OSError("simulated tsv replace fail")), + ): + self._assert_clean_failure( + ["--out", str(out_tsv), "--json", str(out_json)], + expected_code=1, + expected_fragments=("error: simulated tsv replace fail",), + check_subprocess=False, + allow_stdout=True, + ) + self.assertEqual(out_tsv.read_text(encoding="utf-8"), "PRIOR_TSV") + self.assertEqual(out_json.read_text(encoding="utf-8"), "PRIOR_JSON") + self.assertEqual([p.name for p in out_tsv.parent.iterdir()], ["res.tsv"]) + self.assertEqual([p.name for p in out_json.parent.iterdir()], ["res.json"]) + + # 2) os.replace fails on --json after --out: prior --json preserved, zero sibling .tmp leftovers. + real_replace = os.replace + calls = [] + + def fail_second_replace(src, dst): + calls.append(Path(dst)) + if len(calls) == 2: + raise OSError("simulated json replace fail") + return real_replace(src, dst) + + with ( + mock.patch.object(rdna_cvt_pk_u8, "Hip", _FakeHip), + mock.patch.object(rdna_cvt_pk_u8, "build", side_effect=_fake_build), + mock.patch.object(rdna_cvt_pk_u8.os, "replace", side_effect=fail_second_replace), + ): + self._assert_clean_failure( + ["--out", str(out_tsv), "--json", str(out_json)], + expected_code=1, + expected_fragments=("error: simulated json replace fail",), + check_subprocess=False, + allow_stdout=True, + ) + self.assertEqual(out_json.read_text(encoding="utf-8"), "PRIOR_JSON") + self.assertEqual([p.name for p in out_tsv.parent.iterdir()], ["res.tsv"]) + self.assertEqual([p.name for p in out_json.parent.iterdir()], ["res.json"]) + + # 3) Corrupt UTF-8 --compare file -> ValueError/UnicodeDecodeError caught -> clean exit 1. + bad_cmp = root / "bad_utf8.tsv" + bad_cmp.write_bytes(b"\xff\xfe\xfd") + with ( + mock.patch.object(rdna_cvt_pk_u8, "Hip", _FakeHip), + mock.patch.object(rdna_cvt_pk_u8, "build", side_effect=_fake_build), + ): + self._assert_clean_failure( + ["--out", str(out_tsv), "--compare", str(bad_cmp)], + expected_code=1, + expected_fragments=("error:",), + check_subprocess=False, + allow_stdout=True, + ) + + # 4) json.JSONDecodeError caught cleanly if raised during main flow. + with ( + mock.patch.object(rdna_cvt_pk_u8, "Hip", _FakeHip), + mock.patch.object(rdna_cvt_pk_u8, "build", side_effect=_fake_build), + mock.patch.object( + rdna_cvt_pk_u8.json, + "dumps", + side_effect=json.JSONDecodeError("bad json", "x", 0), + ), + ): + self._assert_clean_failure( + ["--out", str(out_tsv), "--json", str(out_json)], + expected_code=1, + expected_fragments=("error:", "bad json"), + check_subprocess=False, + allow_stdout=True, + ) + + def test_argparse_usage_errors_compatible_with_py314(self) -> None: + for bad_argv, fragment in ( + (["--unknown-flag"], "--unknown-flag"), + (["--arch"], "--arch"), + (["--show", "not-an-int"], "--show"), + (["--cov", "9"], "--cov"), + (["--build", "bogus"], "--build"), + ): + with self.subTest(argv=bad_argv): + self._assert_clean_failure( + bad_argv, + expected_code=2, + expected_fragments=("usage:", fragment), + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/rdna_cvt_pk_u8.py b/tools/rdna_cvt_pk_u8.py index d7dccdc75..09a533e23 100644 --- a/tools/rdna_cvt_pk_u8.py +++ b/tools/rdna_cvt_pk_u8.py @@ -28,6 +28,7 @@ import json import math import os +from pathlib import Path import re import shutil import struct @@ -526,7 +527,103 @@ def check(name, got, want): # ---------------------------------------------------------------- main -def main(): +def _same_path(left, right): + left_p = Path(left) + right_p = Path(right) + if os.path.normcase(str(left_p.resolve())) == os.path.normcase(str(right_p.resolve())): + return True + return left_p.exists() and right_p.exists() and left_p.samefile(right_p) + + +def _validate_output_path(flag, raw_path): + if not raw_path or not raw_path.strip(): + raise ValueError('%s path must not be empty' % flag) + if raw_path.endswith(('/', '\\')): + raise ValueError('%s path is a directory path: %s' % (flag, raw_path)) + p = Path(raw_path) + if p.is_symlink(): + raise ValueError('%s path must not be a symlink: %s' % (flag, raw_path)) + if p.is_dir(): + raise ValueError('%s path is a directory: %s' % (flag, raw_path)) + if p.exists() and not p.is_file(): + raise ValueError('%s path is not a regular file: %s' % (flag, raw_path)) + for parent in p.parents: + if parent.is_symlink() and not parent.is_dir(): + raise ValueError('%s parent path is a symlink to non-directory: %s' % (flag, parent)) + if parent.exists() and not parent.is_dir(): + raise ValueError('%s parent path is not a directory: %s' % (flag, parent)) + return p + + +def _validate_args(args): + if args.show < 0: + raise ValueError('--show must be >= 0, got %d' % args.show) + + keep_path = None + if args.keep is not None: + if not args.keep.strip(): + raise ValueError('--keep path must not be empty') + keep_path = Path(args.keep) + if keep_path.exists() and not keep_path.is_dir(): + raise ValueError('--keep path is not a directory: %s' % args.keep) + if keep_path.is_symlink() and not keep_path.is_dir(): + raise ValueError('--keep path is a broken symlink: %s' % args.keep) + for parent in keep_path.parents: + if parent.exists() and not parent.is_dir(): + raise ValueError('--keep parent path is not a directory: %s' % parent) + + cmp_path = None + if args.compare: + cmp_path = Path(args.compare) + if cmp_path.is_dir(): + raise ValueError('--compare path is a directory: %s' % args.compare) + + out_path = _validate_output_path('--out', args.out) + json_path = _validate_output_path('--json', args.json) if args.json is not None else None + + if cmp_path is not None and _same_path(out_path, cmp_path): + raise ValueError('--out path collides with --compare: %s' % args.out) + if json_path is not None and cmp_path is not None and _same_path(json_path, cmp_path): + raise ValueError('--json path collides with --compare: %s' % args.json) + if json_path is not None and _same_path(out_path, json_path): + raise ValueError('--out and --json paths must not collide: %s' % args.out) + if keep_path is not None: + if _same_path(keep_path, out_path): + raise ValueError('--keep and --out paths must not collide: %s' % args.out) + if json_path is not None and _same_path(keep_path, json_path): + raise ValueError('--keep and --json paths must not collide: %s' % args.json) + if cmp_path is not None and _same_path(keep_path, cmp_path): + raise ValueError('--keep and --compare paths must not collide: %s' % args.compare) + + +def _write_atomic(path, content): + """Write content to a sibling temp file and atomically replace path, cleaning up on failure.""" + target = Path(path) + target.parent.mkdir(parents=True, exist_ok=True) + tmp_path = None + try: + with tempfile.NamedTemporaryFile( + mode='w', + encoding='utf-8', + newline='\n', + dir=target.parent, + prefix='.%s.' % target.name, + suffix='.tmp', + delete=False, + ) as handle: + tmp_path = Path(handle.name) + handle.write(content) + os.replace(tmp_path, target) + except BaseException: + if tmp_path is not None: + try: + tmp_path.unlink(missing_ok=True) + except OSError: + pass + raise + + +def main(argv=None) -> int: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument('--device', type=int, default=0, help='HIP device index (default 0; every device is listed)') ap.add_argument('--arch', help='target, e.g. gfx1030, gfx1032, gfx1100 (default: from the HIP device)') @@ -543,72 +640,89 @@ def main(): ap.add_argument('--clang', help='clang executable (--build hip)') ap.add_argument('--llvm-mc', help='llvm-mc executable (--build asm)') ap.add_argument('--lld', help='ld.lld executable (--build asm)') - args = ap.parse_args() + args = ap.parse_args(argv) if args.self_test: return self_test() - hip, arch = None, args.arch - if not args.asm_only: + temp_workdir = None + try: + _validate_args(args) + + hip, arch = None, args.arch + if not args.asm_only: + try: + hip = Hip() + hip.device = args.device + for i in range(hip.count()): + print('HIP device %d: %s%s' % (i, hip.arch(i), ' <- used' if i == args.device else '')) + if not arch: + arch = hip.arch() + except RuntimeError as e: + print('error: %s' % e, file=sys.stderr) + return 2 + if not arch: + print('error: --asm-only needs --arch', file=sys.stderr) + return 2 + arch = arch.split(':')[0] + + if args.keep: + workdir = args.keep + os.makedirs(workdir, exist_ok=True) + else: + temp_workdir = tempfile.mkdtemp(prefix='cvt_pk_u8_') + workdir = temp_workdir + + images = {} + for var in VARIANTS: + images[var] = build(arch, var, workdir, args) + print('built %s (%d bytes): %s' % (var, len(images[var][0]), images[var][1])) + if args.asm_only: + return 0 + + rows = build_rows() + words = [(r[1], r[2]) for r in rows] + results = {} try: - hip = Hip() - hip.device = args.device - for i in range(hip.count()): - print('HIP device %d: %s%s' % (i, hip.arch(i), ' <- used' if i == args.device else '')) - if not arch: - arch = hip.arch() + for var in VARIANTS: + results[var] = hip.run_kernel(images[var][0], 'cvt_pk_u8_' + var, words) except RuntimeError as e: print('error: %s' % e, file=sys.stderr) - return 2 - if not arch: - sys.exit('error: --asm-only needs --arch') - arch = arch.split(':')[0] - - workdir = args.keep or tempfile.mkdtemp(prefix='cvt_pk_u8_') - os.makedirs(workdir, exist_ok=True) - images = {} - for var in VARIANTS: - images[var] = build(arch, var, workdir, args) - print('built %s (%d bytes): %s' % (var, len(images[var][0]), images[var][1])) - if args.asm_only: + return 3 + summary = analyse(rows, results, args.show) + print_report(rows, results, summary, arch, args.show) + header = ['# rdna_cvt_pk_u8 v1: v_cvt_pk_u8_f32 vD, vIn, vSel, vS2 measured by tools/rdna_cvt_pk_u8.py', + '# sentinel (S2) %08x' % SENTINEL, '# device %s' % arch, + '# columns (tab separated, words in hex): label in sel default rtz flush', + '# default = MODE at launch default, rtz = s_round_mode 0xf, flush = s_denorm_mode 0'] + lines = ['\t'.join([r[0], '%08x' % r[1], '%08x' % r[2]] + ['%08x' % results[v][i] for v in VARIANTS]) + for i, r in enumerate(rows)] + _write_atomic(args.out, '\n'.join(header + lines) + '\n') + print('\nresults written to %s' % os.path.abspath(args.out)) + if args.json: + payload = json.dumps( + {'arch': arch, 'sentinel': SENTINEL, + 'rows': [{'label': r[0], 'in': '%08x' % r[1], 'sel': '%08x' % r[2], + **{v: '%08x' % results[v][i] for v in results}} for i, r in enumerate(rows)], + 'summary': summary}, + indent=1, + ) + _write_atomic(args.json, payload) + print('verbose JSON written to %s' % os.path.abspath(args.json)) + if args.compare and os.path.exists(args.compare): + with open(args.compare, encoding='utf-8') as f: + stored = [l.rstrip('\n') for l in f if not l.startswith('#')] + if stored == lines: + print('rows identical to %s' % args.compare) + else: + print('rows DIFFER from %s (%d of %d rows)' % (args.compare, sum(a != b for a, b in zip(stored, lines)), len(lines))) return 0 - - rows = build_rows() - words = [(r[1], r[2]) for r in rows] - results = {} - try: - for var in VARIANTS: - results[var] = hip.run_kernel(images[var][0], 'cvt_pk_u8_' + var, words) - except RuntimeError as e: + except (OSError, ValueError, json.JSONDecodeError) as e: print('error: %s' % e, file=sys.stderr) - return 3 - summary = analyse(rows, results, args.show) - print_report(rows, results, summary, arch, args.show) - header = ['# rdna_cvt_pk_u8 v1: v_cvt_pk_u8_f32 vD, vIn, vSel, vS2 measured by tools/rdna_cvt_pk_u8.py', - '# sentinel (S2) %08x' % SENTINEL, '# device %s' % arch, - '# columns (tab separated, words in hex): label in sel default rtz flush', - '# default = MODE at launch default, rtz = s_round_mode 0xf, flush = s_denorm_mode 0'] - lines = ['\t'.join([r[0], '%08x' % r[1], '%08x' % r[2]] + ['%08x' % results[v][i] for v in VARIANTS]) - for i, r in enumerate(rows)] - os.makedirs(os.path.dirname(os.path.abspath(args.out)), exist_ok=True) - with open(args.out, 'w', newline='\n') as f: - f.write('\n'.join(header + lines) + '\n') - print('\nresults written to %s' % os.path.abspath(args.out)) - if args.json: - with open(args.json, 'w') as f: - json.dump({'arch': arch, 'sentinel': SENTINEL, - 'rows': [{'label': r[0], 'in': '%08x' % r[1], 'sel': '%08x' % r[2], - **{v: '%08x' % results[v][i] for v in results}} for i, r in enumerate(rows)], - 'summary': summary}, f, indent=1) - print('verbose JSON written to %s' % os.path.abspath(args.json)) - if args.compare and os.path.exists(args.compare): - with open(args.compare) as f: - stored = [l.rstrip('\n') for l in f if not l.startswith('#')] - if stored == lines: - print('rows identical to %s' % args.compare) - else: - print('rows DIFFER from %s (%d of %d rows)' % (args.compare, sum(a != b for a, b in zip(stored, lines)), len(lines))) - return 0 + return 1 + finally: + if temp_workdir is not None: + shutil.rmtree(temp_workdir, ignore_errors=True) if __name__ == '__main__': From 51fdbbce9099ef1b185ca4305790e00da2edf736 Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Thu, 26 Nov 2026 01:35:09 +0200 Subject: [PATCH 008/240] ffx: add upfront path guards and atomic writes to ffx_working_set_delta with CLI suite (#2616) --- CMakeLists.txt | 3 + tests/ffx_working_set_delta_cli_check.py | 322 +++++++++++++++++++++++ tools/ffx_working_set_delta.py | 50 +++- 3 files changed, 371 insertions(+), 4 deletions(-) create mode 100644 tests/ffx_working_set_delta_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index d9cd0bdbc..b701049bc 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -10335,6 +10335,9 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/probe_root_devices_check.py") add_test(NAME ffx_working_set_delta_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/ffx_working_set_delta_check.py") + add_test(NAME ffx_working_set_delta_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/ffx_working_set_delta_cli_check.py") + set_tests_properties(ffx_working_set_delta_cli_check PROPERTIES TIMEOUT 60) add_test(NAME bink_descriptors_aot_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/bink_descriptors_aot_check.py") add_test(NAME range_manifest_check COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/ffx_working_set_delta_cli_check.py b/tests/ffx_working_set_delta_cli_check.py new file mode 100644 index 000000000..d076e34ea --- /dev/null +++ b/tests/ffx_working_set_delta_cli_check.py @@ -0,0 +1,322 @@ +#!/usr/bin/env python3 +"""Pure-Python CLI, atomic-write, path-guard, and error-handling suite for tools/ffx_working_set_delta.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +from pathlib import Path +import runpy +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOLS_DIR = ROOT / "tools" +TOOL = TOOLS_DIR / "ffx_working_set_delta.py" +sys.path.insert(0, str(TOOLS_DIR)) +import ffx_working_set_delta # noqa: E402 + + +SYNTHETIC_CPP = ( + '#include \n' + 'using word = uint64_t;\n' + 'extern "C" __declspec(dllexport) word create_delta(word input, word counters) { return input + counters; }\n' +) + + +def _run_main(argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = ffx_working_set_delta.main(argv) + except SystemExit as exc: + code = exc.code + if not isinstance(code, int): + if code is not None: + stderr.write(f"{code}\n") + code = 0 if code is None else 1 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class FfxWorkingSetDeltaCliPositiveTests(unittest.TestCase): + def test_atomic_cpp_output_in_nested_new_dir_and_overwrite(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "synthetic.dll" + image.write_bytes(b"synthetic-image-placeholder") + nested_out = base / "nested" / "sub" / "delta.cpp" + + # 1) Create missing parent directories and write atomically with 0 .tmp files. + with mock.patch.object(ffx_working_set_delta, "generate", return_value=SYNTHETIC_CPP) as gen: + code, out, err = _run_main([str(image), str(nested_out)]) + gen.assert_called_once_with(image, False) + self.assertEqual(code, 0, err) + self.assertEqual(out, "") + self.assertEqual(err, "") + self.assertEqual(nested_out.read_text(encoding="ascii"), SYNTHETIC_CPP) + self.assertEqual(sorted(p.name for p in nested_out.parent.iterdir()), ["delta.cpp"]) + + # 2) Forward --package flag and atomically replace pre-existing file with 0 .tmp files. + nested_out.write_text("stale content", encoding="ascii") + pkg_cpp = SYNTHETIC_CPP + "// package-mode\n" + with mock.patch.object(ffx_working_set_delta, "generate", return_value=pkg_cpp) as gen_pkg: + code_pkg, out_pkg, err_pkg = _run_main([str(image), str(nested_out), "--package"]) + gen_pkg.assert_called_once_with(image, True) + self.assertEqual(code_pkg, 0, err_pkg) + self.assertEqual(out_pkg, "") + self.assertEqual(err_pkg, "") + self.assertEqual(nested_out.read_text(encoding="ascii"), pkg_cpp) + self.assertEqual(sorted(p.name for p in nested_out.parent.iterdir()), ["delta.cpp"]) + + # 3) Verify sys.argv forwarding when argv=None. + cli_argv = [str(TOOL), str(image), str(nested_out)] + with ( + mock.patch.object(sys, "argv", cli_argv), + mock.patch.object(ffx_working_set_delta, "generate", return_value=SYNTHETIC_CPP), + ): + code_none, out_none, err_none = _run_main(None) + self.assertEqual(code_none, 0, err_none) + self.assertEqual(out_none, "") + self.assertEqual(err_none, "") + self.assertEqual(nested_out.read_text(encoding="ascii"), SYNTHETIC_CPP) + + # 4) Verify __main__ entrypoint propagates SystemExit cleanly. + bad_pe = base / "bad_main.dll" + bad_pe.write_bytes(b"not a PE") + stdout, stderr = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", [str(TOOL), str(bad_pe), str(base / "unused.cpp")]), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 1) + self.assertEqual(stdout.getvalue(), "") + self.assertNotIn("Traceback", stderr.getvalue()) + self.assertTrue(stderr.getvalue().strip()) + + +class FfxWorkingSetDeltaCliNegativeTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_code: int | None, + fragments: tuple[str, ...] = (), + check_subprocess: bool = True, + ) -> str: + code, out, err = _run_main(argv) + if expected_code is None: + self.assertNotEqual(code, 0) + else: + self.assertEqual(code, expected_code, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertTrue(err.strip()) + for fragment in fragments: + self.assertIn(fragment.lower(), err.lower()) + + if check_subprocess: + proc = _run_subprocess(*argv) + if expected_code is None: + self.assertNotEqual(proc.returncode, 0) + else: + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + for fragment in fragments: + self.assertIn(fragment.lower(), proc.stderr.lower()) + return err + + def test_missing_and_directory_image_rejected_before_generate(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + dir_image = base / "dir_image" + dir_image.mkdir() + absent_out = base / "should_not_exist" / "delta.cpp" + + with ( + mock.patch.object( + ffx_working_set_delta, + "generate", + side_effect=AssertionError("generate called for invalid image path"), + ), + mock.patch.object( + ffx_working_set_delta, + "_write_atomic", + side_effect=AssertionError("_write_atomic called for invalid image path"), + ), + ): + self._assert_clean_failure( + [str(base / "missing.dll"), str(absent_out)], + expected_code=1, + fragments=("image file not found",), + ) + self._assert_clean_failure( + [str(dir_image), str(absent_out)], + expected_code=1, + fragments=("image path is a directory",), + ) + + self.assertFalse(absent_out.parent.exists()) + + def test_invalid_pe_bytes_exit_1_without_creating_output_or_temps(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + bad_pe = base / "bad.dll" + bad_pe.write_bytes(b"not a valid PE32+ image") + absent_out = base / "absent_dir" / "delta.cpp" + + self._assert_clean_failure( + [str(bad_pe), str(absent_out)], + expected_code=1, + ) + self.assertFalse(absent_out.parent.exists()) + + def test_output_guards_reject_before_generate_and_write(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(b"synthetic-image-bytes") + same_cpp = base / "same.cpp" + same_cpp.write_bytes(b"synthetic-cpp-bytes") + hardlink_cpp = base / "hardlink.cpp" + hardlink_cpp.hardlink_to(image) + out_dir = base / "existing_dir.cpp" + out_dir.mkdir() + file_parent = base / "regular_parent.txt" + file_parent.write_text("keep-me", encoding="ascii") + + with ( + mock.patch.object( + ffx_working_set_delta, + "generate", + side_effect=AssertionError("generate called for invalid output path"), + ), + mock.patch.object( + ffx_working_set_delta, + "_write_atomic", + side_effect=AssertionError("_write_atomic called for invalid output path"), + ), + ): + for label, argv, code, frags in ( + ("non_cpp_suffix", [str(image), str(base / "out.txt")], 2, ("distinct .cpp output",)), + ("empty_output", [str(image), ""], 2, ("distinct .cpp output",)), + ("same_path", [str(same_cpp), str(same_cpp)], 2, ("distinct .cpp output",)), + ("hardlink_samefile", [str(image), str(hardlink_cpp)], 2, ("distinct .cpp output",)), + ("output_is_dir", [str(image), str(out_dir)], 1, ("directory",)), + ("parent_is_file", [str(image), str(file_parent / "delta.cpp")], 1, ("not a directory",)), + ("ancestor_is_file", [str(image), str(file_parent / "sub" / "delta.cpp")], 1, ("not a directory",)), + ): + with self.subTest(case=label): + self._assert_clean_failure(argv, expected_code=code, fragments=frags) + + self.assertEqual(same_cpp.read_bytes(), b"synthetic-cpp-bytes") + self.assertEqual(image.read_bytes(), b"synthetic-image-bytes") + self.assertEqual(list(out_dir.iterdir()), []) + self.assertEqual(file_parent.read_text(encoding="ascii"), "keep-me") + self.assertFalse((base / "out.txt").exists()) + + def test_output_symlink_rejected_before_generate_and_write(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(b"synthetic-image-bytes") + out_dir = base / "out_dir" + out_dir.mkdir() + real_target = out_dir / "real.cpp" + real_target.write_text("untouched", encoding="ascii") + live_link = out_dir / "live_link.cpp" + dangling_link = out_dir / "dangling_link.cpp" + try: + live_link.symlink_to(real_target) + dangling_link.symlink_to(out_dir / "missing.cpp") + except OSError as exc: + if getattr(exc, "winerror", None) != 1314: + raise + self.skipTest("this Windows account cannot create symlinks (WinError 1314)") + + with ( + mock.patch.object( + ffx_working_set_delta, + "generate", + side_effect=AssertionError("generate called for symlink output"), + ), + mock.patch.object( + ffx_working_set_delta, + "_write_atomic", + side_effect=AssertionError("_write_atomic called for symlink output"), + ), + ): + for label, link in (("live_symlink", live_link), ("dangling_symlink", dangling_link)): + with self.subTest(case=label): + self._assert_clean_failure( + [str(image), str(link)], + expected_code=1, + fragments=("symlink",), + ) + + self.assertEqual(real_target.read_text(encoding="ascii"), "untouched") + self.assertEqual( + sorted(p.name for p in out_dir.iterdir()), + ["dangling_link.cpp", "live_link.cpp", "real.cpp"], + ) + + def test_atomic_write_failure_leaves_zero_tmp_files(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(b"synthetic-image-bytes") + out_dir = base / "out_dir" + out_dir.mkdir() + out_cpp = out_dir / "delta.cpp" + out_cpp.write_text("original", encoding="ascii") + + with ( + mock.patch.object(ffx_working_set_delta, "generate", return_value=SYNTHETIC_CPP), + mock.patch.object(Path, "replace", side_effect=OSError("simulated replace failure")), + ): + self._assert_clean_failure( + [str(image), str(out_cpp)], + expected_code=1, + fragments=("simulated replace failure",), + check_subprocess=False, + ) + + self.assertEqual(out_cpp.read_text(encoding="ascii"), "original") + self.assertEqual(sorted(p.name for p in out_dir.iterdir()), ["delta.cpp"]) + + def test_argparse_errors_py314_safe(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(b"synthetic") + out_cpp = base / "delta.cpp" + + for argv, frags in ( + ([], ("required",)), + ([str(image)], ("required",)), + ([str(image), str(out_cpp), "--bogus-flag"], ("unrecognized",)), + ): + with self.subTest(argv=argv): + self._assert_clean_failure( + argv, + expected_code=None, + fragments=frags, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/ffx_working_set_delta.py b/tools/ffx_working_set_delta.py index 6ed27189a..cf9184fc4 100644 --- a/tools/ffx_working_set_delta.py +++ b/tools/ffx_working_set_delta.py @@ -1,6 +1,8 @@ """Translate the counter updates following two upscaler working-set queries.""" import argparse from pathlib import Path +import struct +import tempfile import pefile @@ -31,6 +33,47 @@ def generate(image: Path, package: bool) -> str: return "\n".join(source) +def _validate_paths(image: Path, output: Path, parser: argparse.ArgumentParser) -> None: + if image.is_dir(): + raise IsADirectoryError(f"image path is a directory: {image}") + if not image.is_file(): + raise FileNotFoundError(f"image file not found: {image}") + if output.suffix.lower() != ".cpp": + parser.error("choose a distinct .cpp output") + if output.is_symlink(): + raise ValueError(f"output path must not be a symlink: {output}") + if output.is_dir(): + raise IsADirectoryError(f"output path is a directory: {output}") + for parent in output.parents: + if parent.is_file() or ((parent.exists() or parent.is_symlink()) and not parent.is_dir()): + raise NotADirectoryError(f"output parent is not a directory: {parent}") + if output.resolve() == image.resolve() or (output.exists() and image.samefile(output)): + parser.error("choose a distinct .cpp output") + + +def _write_atomic(path: Path, content: str) -> None: + """Write ASCII content to a sibling temp file and atomically replace path, leaving 0 temp files on failure.""" + path.parent.mkdir(parents=True, exist_ok=True) + tmp_path = None + try: + with tempfile.NamedTemporaryFile( + mode="w", + encoding="ascii", + newline="\n", + dir=path.parent, + prefix=f".{path.stem}.", + suffix=".tmp", + delete=False, + ) as handle: + tmp_path = Path(handle.name) + handle.write(content) + tmp_path.replace(path) + except BaseException: + if tmp_path is not None: + tmp_path.unlink(missing_ok=True) + raise + + def main(argv=None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("image", type=Path) @@ -38,10 +81,9 @@ def main(argv=None) -> int: parser.add_argument("--package", action="store_true") args = parser.parse_args(argv) try: - if args.output.suffix.lower() != ".cpp" or args.output.resolve() == args.image.resolve(): - parser.error("choose a distinct .cpp output") - args.output.write_text(generate(args.image, args.package), encoding="ascii") - except (OSError, ValueError, pefile.PEFormatError) as error: + _validate_paths(args.image, args.output, parser) + _write_atomic(args.output, generate(args.image, args.package)) + except (OSError, ValueError, struct.error, pefile.PEFormatError) as error: parser.exit(1, f"{error}\n") return 0 From e5d8251b736c097c9c967296d11568501e1e3dd4 Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:36:22 +0100 Subject: [PATCH 009/240] startup: refuse a lane mask read as data by v_mov_b32 and v_cndmask_b32 (#2623) A lane-mask register (a compare result, vcc_lo, exec_lo, a saved EXEC copy) holds only the current lane's bit in the one-lane model, while RDNA 2 reads the whole mask word when the register is a data operand. v_cndmask_b32 (both data operands) and v_mov_b32 (plain, e64 and SDWA DWORD) took such a register through u()/u_src and emitted the lane bit. They now refuse it, after stripping the source modifiers; the lane select of v_cndmask is unchanged. Tests that moved a mask with v_mov_b32 first now expect the new refusal, or read the mask as a lane select instead so they still reach the refusal they test. The SDWA check that accepted a whole-mask move now expects a refusal. AI-assisted. --- .github/workflows/windows.yml | 1 + AGENTS.md | 1 + CMakeLists.txt | 3 + docs/experiments.md | 11 +++- tests/startup_gfx2hlsl_add_sub_co_check.py | 12 ++-- tests/startup_gfx2hlsl_compute_check.py | 27 ++++---- tests/startup_gfx2hlsl_join_symbols_check.py | 20 ++++-- tests/startup_gfx2hlsl_mask_data_check.py | 65 +++++++++++++++++++ ...up_gfx2hlsl_readfirstlane_uniform_check.py | 12 +++- tests/startup_gfx2hlsl_sdwa_check.py | 5 +- tools/startup/gfx2hlsl.py | 23 ++++++- 11 files changed, 148 insertions(+), 32 deletions(-) create mode 100644 tests/startup_gfx2hlsl_mask_data_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index ef7f3e5e6..6ac6935fd 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -249,6 +249,7 @@ jobs: tests/startup_gfx2hlsl_int_med3_check.py \ tests/startup_gfx2hlsl_cselect_mask_check.py \ tests/startup_gfx2hlsl_mask_overwrite_check.py \ + tests/startup_gfx2hlsl_mask_data_check.py \ tests/startup_gfx2hlsl_image_get_lod_check.py \ tests/startup_gfx2hlsl_add_sub_co_check.py \ tests/startup_gfx2hlsl_add_sub_co_ci_check.py \ diff --git a/AGENTS.md b/AGENTS.md index f9a68ef8d..92208393f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -202,6 +202,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_int_med3_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_cselect_mask_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_mask_overwrite_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_mask_data_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_image_get_lod_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_add_sub_co_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_add_sub_co_ci_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index b701049bc..ed89ff2ac 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3386,6 +3386,9 @@ if(EXISTS "${INTAKE_PYTHON}") # Startup shader translator: a scalar load or select into a former lane-mask SGPR clears its mask mark. add_test(NAME startup_gfx2hlsl_mask_overwrite_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_mask_overwrite_check.py") + # Startup shader translator: lane masks cannot be used as vector data words. + add_test(NAME startup_gfx2hlsl_mask_data_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_mask_data_check.py") # Startup shader translator: image_get_lod on a 2D texture (CalculateLevelOfDetail / Unclamped). add_test(NAME startup_gfx2hlsl_image_get_lod_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_image_get_lod_check.py") diff --git a/docs/experiments.md b/docs/experiments.md index c84ebab6c..2a1cfa310 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14153,11 +14153,20 @@ ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_cselect_mask_controls$ ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_mask_overwrite_controls$' -V ``` +## Startup translator: lane masks used as vector data + +The one-lane model stores a mask as the current lane's bit. RDNA 2 reads the whole mask word when the register is +a data source. For example, after `v_cmp_eq_u32_e64 s[30:31], 0, v0`, reading s30 as data gives +`0xffffffff` if all 32 lanes pass. The translator refuses lane masks in either data operand of +`v_cndmask_b32` and in the source of `v_mov_b32`, including SDWA DWORD. Source modifiers still identify the +underlying mask register. Lane masks remain valid as selectors, and ordinary scalar words remain valid as data. +The synthetic controls run under `startup_gfx2hlsl_mask_data_controls`. + ## Startup translator: 32-bit add and subtract with a carry out `tools/startup/gfx2hlsl.py` refused the VOP3b forms `v_add_co_u32`, `v_sub_co_u32` and `v_subrev_co_u32` as unknown instructions. It now lowers them from the AMD RDNA 2 ISA description: `D = S0 + S1` with the carry out of bit 31, `D = S0 - S1` with a borrow when `S1 > S0`, and `SUBREV` with the sources swapped. These forms take no carry-in. The carry goes to the lane's bit of VCC or of the SGPR destination, which becomes a lane mask and is never a uniform source. The result and the carry are computed into the scratch registers `a` and `w` before either destination is written, so a destination may overlap a source. When `exec` is not known, an inactive lane keeps D and writes a 0 carry, as the compare lowering does. `clamp`, other modifiers, an EXEC carry-out and a wrong operand count are refused. -`tests/startup_gfx2hlsl_add_sub_co_check.py` decodes synthetic VOP3b words for the three forms with an SGPR and a VCC carry-out, evaluates the emitted lines with the restricted evaluator of `startup_gfx2hlsl_bit_alu_check.py` on a grid of edge values, and compares them with Python references written from the ISA description. It also checks that the carry-out SGPR is a lane mask, that a readfirstlane of a copy of it is refused, the exec-masked form, an overlapping destination and the refusals. Negative control: a borrow with the comparison reversed disagrees with the reference on the grid. On the translator before this change every form is refused. Test: `startup_gfx2hlsl_add_sub_co_controls`. Not covered: DXC compilation and a draw through a translated pipeline; the check evaluates the emitted HLSL text only. +`tests/startup_gfx2hlsl_add_sub_co_check.py` decodes synthetic VOP3b words for the three forms with an SGPR and a VCC carry-out, evaluates the emitted lines with the restricted evaluator of `startup_gfx2hlsl_bit_alu_check.py` on a grid of edge values, and compares them with Python references written from the ISA description. It also checks that the carry-out SGPR is a lane mask, that moving it as vector data is refused, the exec-masked form, an overlapping destination and the refusals. Negative control: a borrow with the comparison reversed disagrees with the reference on the grid. On the translator before this change every form is refused. Test: `startup_gfx2hlsl_add_sub_co_controls`. Not covered: DXC compilation and a draw through a translated pipeline; the check evaluates the emitted HLSL text only. ```powershell ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_add_sub_co_controls$' -V diff --git a/tests/startup_gfx2hlsl_add_sub_co_check.py b/tests/startup_gfx2hlsl_add_sub_co_check.py index 7fa75429f..0a80e6ea1 100644 --- a/tests/startup_gfx2hlsl_add_sub_co_check.py +++ b/tests/startup_gfx2hlsl_add_sub_co_check.py @@ -8,8 +8,8 @@ The emitted lines are evaluated with the restricted evaluator of startup_gfx2hlsl_bit_alu_check on a grid of edge values and compared with Python references written from the ISA description, for an SGPR and a VCC carry-out. Also -checked: the carry-out SGPR becomes a lane mask that is not a uniform source, a readfirstlane of a copy of it is -refused, inactive lanes keep D and get a 0 carry when exec is not known, a destination that overlaps a source reads +checked: the carry-out SGPR becomes a lane mask that is refused as vector move data, inactive lanes keep D +and get a 0 carry when exec is not known, a destination that overlaps a source reads the source first, and clamp, a wrong operand count and an EXEC carry-out are refused. Negative control: a borrow written as S0 > S1 differs from the reference on the grid. """ @@ -117,15 +117,15 @@ def main(): count += 1 check('%s matches the ISA reference on the grid' % text, bad is None, bad) - # The carry-out is per lane: a readfirstlane of a VGPR copied from it must not be proven uniform. + # The carry-out holds only this lane's bit and cannot be moved as a data word. s, text, _ = translate(vop3b(0x30f, 2, 18, V4, V3)) try: s.one('v_mov_b32', 'v_mov_b32 v5, s18') - s.one('v_readfirstlane_b32', 'v_readfirstlane_b32 s20, v5') except G.Unsupported as error: - check('%s: readfirstlane of a copy of the carry-out is refused' % text, 'uniform' in str(error), str(error)) + check('%s: moving the carry-out as data is refused' % text, + str(error) == 'v_mov_b32 data operand s18 is a lane mask', str(error)) else: - check('%s: readfirstlane of a copy of the carry-out is refused' % text, False, s.lines) + check('%s: moving the carry-out as data is refused' % text, False, s.lines) # D of varying sources is not proven uniform either. s, text, _ = translate(vop3b(0x30f, 2, 18, V4, V3)) try: diff --git a/tests/startup_gfx2hlsl_compute_check.py b/tests/startup_gfx2hlsl_compute_check.py index 5cc703fd8..fd4c3bd58 100644 --- a/tests/startup_gfx2hlsl_compute_check.py +++ b/tests/startup_gfx2hlsl_compute_check.py @@ -412,6 +412,7 @@ def saveexec_fixture(): # Single instructions the controls splice into case A before its store, recorded from llvm-mc 15. STORE_A = WORDS_A.index(bytes.fromhex('001070e004050480')) +SCC_LANE_SELECT = 'v_cndmask_b32_e64 v5, 0, 1, s20' SPLICE = { 's_cmp_lt_u32 s7, 4': '07840abf', 's_and_b32 s13, s13, 0xc000ffff': '0dff0d87ffff00c0', @@ -422,7 +423,7 @@ def saveexec_fixture(): 's_cmov_b32 s20, 1': '810594be', 's_cmov_b64 s[20:21], s[4:5]': '040694be', 's_cmovk_i32 s20, 3': '030014b1', - 's_cbranch_scc0 1': '010084bf', + 's_cbranch_scc0 2': '020084bf', 's_cbranch_scc1 1': '010085bf', 's_cbranch_vccz 1': '010086bf', 'v_mov_b32 v3, 0': '8002067e', @@ -441,6 +442,7 @@ def saveexec_fixture(): 's_add_u32 s20, s7, 1': '07811480', 's_or_b32 exec_lo, exec_lo, s0': '7e007e88', 'v_mov_b32 v5, s20': '14020a7e', + SCC_LANE_SELECT: '050001d580025100', 's_mov_b32 s21, exec_lo': '7e0395be', 's_mov_b32 exec_lo, vcc_lo': '6a03febe', 's_mov_b32 exec_lo, s21': '1503febe', @@ -694,11 +696,10 @@ def check_mbcnt(): def check_descriptor_scc(): # Case A loads the input descriptor into s[12:15] and stores through s[16:19]. - # Put the condition into the stored value, or let the branch skip the move. + # Read s20's lane bit into the stored value. The SCC branches skip both dwords of the lane select. compare = 's_cmp_lt_u32 s7, 4' mask = 's_and_b32 s13, s13, 0xc000ffff' select = 's_cselect_b32 s20, 1, 0' - move = 'v_mov_b32 v5, s20' def pipeline(*lines): return translate('A', code=splice(*lines)) @@ -707,20 +708,20 @@ def rejected(*lines): refused('scc from descriptor data', lambda: pipeline(*lines)) for reader in (select, 's_cselect_b64 s[20:21], 1, 0', 's_cmov_b32 s20, 1', 's_cmov_b64 s[20:21], s[4:5]', - 's_cmovk_i32 s20, 3', 's_cbranch_scc0 1', 's_cbranch_scc1 1'): - rejected(compare, mask, reader, move) - assert 'uav 0 table 1 16' in pipeline(mask, compare, reader, move).manifest() - rejected(compare, 's_add_u32 s13, s13, 1', select, move) - assert 's20 = scc ?' in pipeline(compare, 's_mov_b32 s13, s13', select, move).hlsl_cs() - assert 's20 = scc ?' in pipeline(mask, 's_and_b32 s22, s7, 1', select, move).hlsl_cs() - assert 's20 = scc ?' in pipeline(mask, 's_and_saveexec_b32 s0, vcc_lo', select, move).hlsl_cs() + 's_cmovk_i32 s20, 3', 's_cbranch_scc0 2', 's_cbranch_scc1 2'): + rejected(compare, mask, reader, SCC_LANE_SELECT) + assert 'uav 0 table 1 16' in pipeline(mask, compare, reader, SCC_LANE_SELECT).manifest() + rejected(compare, 's_add_u32 s13, s13, 1', select, SCC_LANE_SELECT) + assert 's20 = scc ?' in pipeline(compare, 's_mov_b32 s13, s13', select, SCC_LANE_SELECT).hlsl_cs() + assert 's20 = scc ?' in pipeline(mask, 's_and_b32 s22, s7, 1', select, SCC_LANE_SELECT).hlsl_cs() + assert 's20 = scc ?' in pipeline(mask, 's_and_saveexec_b32 s0, vcc_lo', select, SCC_LANE_SELECT).hlsl_cs() # A conditional edge can bypass the fresh comparison. A back edge can carry # the descriptor-derived flag to a read that comes first in program order. - rejected(mask, 's_cbranch_vccz 1', compare, select, move) + rejected(mask, 's_cbranch_vccz 1', compare, select, SCC_LANE_SELECT) rejected(compare, 'v_mov_b32 v3, 0', select, mask, 'v_add_nc_u32 v3, 1, v3', - 'v_cmp_gt_u32 vcc_lo, 2, v3', 's_cbranch_vccnz 65530', move) - assert 's20 = scc ?' in pipeline(compare, 's_branch 2', mask, select, move).hlsl_cs() + 'v_cmp_gt_u32 vcc_lo, 2, v3', 's_cbranch_vccnz 65530', SCC_LANE_SELECT) + assert 's20 = scc ?' in pipeline(compare, 's_branch 2', mask, select, SCC_LANE_SELECT).hlsl_cs() def check_lds(): diff --git a/tests/startup_gfx2hlsl_join_symbols_check.py b/tests/startup_gfx2hlsl_join_symbols_check.py index 8d72a634d..cda6bc966 100644 --- a/tests/startup_gfx2hlsl_join_symbols_check.py +++ b/tests/startup_gfx2hlsl_join_symbols_check.py @@ -274,13 +274,18 @@ def cmp_ne(sdst, v): # v_cmp_ne_i32_e64 sdst, 0, v return struct.pack('> 0u) & 0xffu);') check('v_mov UNUSED_SEXT with a DWORD destination has no unused bits', mov('v2', 'DWORD', 'UNUSED_SEXT', 'WORD_0') == 'v1 = ((v2 >> 0u) & 0xffffu);') -check('v_mov whole lane mask is the plain move', mov('exec_lo', 'DWORD', 'UNUSED_PAD', 'DWORD') == 'v1 = exec;') +check('v_mov whole lane mask refused', + mov('exec_lo', 'DWORD', 'UNUSED_PAD', 'DWORD') == 'refused: v_mov_b32 data operand exec_lo is a lane mask') check('v_mov UNUSED_SEXT with a sub-dword destination refused', refused_as('v_mov_b32_sdwa v1, v2 dst_sel:WORD_0 dst_unused:UNUSED_SEXT src0_sel:DWORD', 'SDWA UNUSED_SEXT')) check('v_mov clamp refused', refused_as('v_mov_b32_sdwa v1, v2 clamp dst_sel:DWORD dst_unused:UNUSED_PAD ' @@ -172,4 +173,4 @@ def mov(source, dst_sel, unused, src_sel): for text in failures: print(' ' + text) sys.exit(1) -print('PASS') \ No newline at end of file +print('PASS') diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 11a1552af..3b4af0c56 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -1871,6 +1871,22 @@ def split_neg(tok): return True, tok[1:] return False, tok + def reject_lane_mask_data(self, op, tok): + """The lane bit cannot represent a mask's word when it is read as data.""" + source = tok + while True: + neg, operand = self.split_neg(source) + if neg: + source = operand + elif source.startswith('|') and source.endswith('|') and len(source) >= 2: + source = source[1:-1] + elif source.startswith(('abs(', 'sext(')) and source.endswith(')'): + source = source[source.index('(') + 1:-1] + else: + break + if self.is_lane_mask(source): + raise Unsupported('%s data operand %s is a lane mask' % (op, tok)) + def u_src(self, tok): """uint expression for an integer-context source that the disassembler may print negated.""" # In an integer instruction the `-` modifier is the source's sign bit flipped: the same bit @@ -3341,7 +3357,9 @@ def sdwa(self, base, ops, mods): elif base == 'v_mov_b32': arity, text = 1, '{0}' # A lane mask is one bit per lane here, so a byte or word of it is not the hardware's field. - if fields.get('src0_sel') != 'DWORD' and self.is_lane_mask(ops[1].removeprefix('sext(').removesuffix(')')): + if fields.get('src0_sel') == 'DWORD': + self.reject_lane_mask_data(base, ops[1]) + elif self.is_lane_mask(ops[1].removeprefix('sext(').removesuffix(')')): raise Unsupported('v_mov_b32 SDWA %s of lane mask %s' % (fields.get('src0_sel'), ops[1])) else: raise Unsupported('SDWA form of %s' % base) @@ -5545,6 +5563,7 @@ def op_v_readlane_b32(self, ops, mods): def op_v_mov_b32(self, ops, mods): if len(ops) != 2: raise Unsupported('v_mov_b32 with %d operands, expected 2' % len(ops)) + self.reject_lane_mask_data('v_mov_b32', ops[1]) self.set_v(reg_range(ops[0])[1], self.u(ops[1])) def op_v_swap_b32(self, ops, mods): @@ -5579,6 +5598,8 @@ def op_v_cndmask_b32(self, ops, mods): raise Unsupported('v_cndmask_b32 with %s' % mods) if len(ops) not in (3, 4): raise Unsupported('v_cndmask_b32 with %d operands, expected 3 or 4' % len(ops)) + for source in ops[1:3]: + self.reject_lane_mask_data('v_cndmask_b32', source) mask = self.u(ops[3]) if len(ops) > 3 else 'vcc' self.set_v(reg_range(ops[0])[1], '(%s & 1) ? %s : %s' % (mask, self.u_src(ops[2]), self.u_src(ops[1]))) From 0a3a2653e2cf3bb3e41ddf4aa1fc64be88194b89 Mon Sep 17 00:00:00 2001 From: RavenCurseBurg Date: Thu, 26 Nov 2026 07:37:16 +0800 Subject: [PATCH 010/240] tests: reuse the compute pipeline across descriptor-format references (#2615) * tests: run compute store references on a shared renderer device * tests: compare the descriptor fixture using one device for its reference cases * tests: use one root signature and compute pipeline for the reference batch * tests: retain case labels and 320-word diagnostics in the shared compute run --------- Co-authored-by: RavenCurseBurg <360931527+RavenCurseBurg@users.noreply.github.com> Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- docs/experiments.md | 6 ++ tests/compute_check.cpp | 164 ++++++++++++++++------------- tests/compute_load_format_check.py | 104 ++++++++++-------- tests/desktop_gpu.h | 13 ++- tests/offscreen_check.cpp | 35 +++--- 5 files changed, 194 insertions(+), 128 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 2a1cfa310..f593934ce 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -6199,6 +6199,12 @@ On the invalid runs, these mutated sources must fail: Dropping only the -1 clamp is not observable: long division of 32768 by 32767 also gives 1.0. With the lowering removed, or with its channel count changed, the translation controls fail. LLVM 15 assembles the fixture, and `lower` of the disassembly and the CLI output both match `lower` of the source. +The seven matching and fourteen intentionally wrong references use the same shader. The fixture passes +them to `offscreen_check --compute-store-batch ...` in order. They share +one D3D12 device, root signature and pipeline. Each case gets fresh buffers, submits its own dispatch and +compares all 320 words after the fence. The renderer reports `pass`, `mismatch` or `error` for each case +and exits with status 1 if any case fails. The eleven shader mutations still compile and dispatch separately. + ```powershell cmake --build --preset dev --target offscreen_check ctest --preset dev --no-tests=error -R '^compute_(store_aot_descriptor_load_format_|load_format_controls$)' -V diff --git a/tests/compute_check.cpp b/tests/compute_check.cpp index 4b6ada2a5..ee4fb50d1 100644 --- a/tests/compute_check.cpp +++ b/tests/compute_check.cpp @@ -250,8 +250,21 @@ struct StoreCase { } }; -static void run_compute(ID3D12Device* device, bool tables, D3D12_SHADER_BYTECODE shader, - D3D12_SHADER_BYTECODE rootBytes, bool conversion_pair = false, +static ComputeReadbackProgram create_compute_program(ID3D12Device* device, D3D12_SHADER_BYTECODE shader, + D3D12_SHADER_BYTECODE rootBytes) +{ + ComputeReadbackProgram program; + check(device->CreateRootSignature(0, rootBytes.pShaderBytecode, rootBytes.BytecodeLength, IID_PPV_ARGS(&program.signature)), + "Create compute root signature"); + D3D12_COMPUTE_PIPELINE_STATE_DESC pso{}; + pso.pRootSignature = program.signature.Get(); + pso.CS = shader; + check(device->CreateComputePipelineState(&pso, IID_PPV_ARGS(&program.pipeline)), "Create compute pipeline"); + return program; +} + +static void run_compute(ID3D12Device* device, bool tables, const ComputeReadbackProgram& program, + bool conversion_pair = false, const StoreCase* store = nullptr, const std::vector* texels = nullptr, DXGI_FORMAT texture_format = DXGI_FORMAT_UNKNOWN, ID3D12Resource* rendered_texture = nullptr, bool dpp_case = false, bool sized_views = false, UINT texture_first_mip = 0, @@ -259,14 +272,6 @@ static void run_compute(ID3D12Device* device, bool tables, D3D12_SHADER_BYTECODE { if ((texels || rendered_texture) && !tables) throw std::runtime_error("An image load needs the descriptor-table signature"); if (uav_words == 0 || uav_words > capacity) throw std::runtime_error("Invalid compute UAV word count"); - ComPtr signature; - check(device->CreateRootSignature(0, rootBytes.pShaderBytecode, rootBytes.BytecodeLength, IID_PPV_ARGS(&signature)), - "Create compute root signature"); - D3D12_COMPUTE_PIPELINE_STATE_DESC pso{}; - pso.pRootSignature = signature.Get(); - pso.CS = shader; - ComPtr pipeline; - check(device->CreateComputePipelineState(&pso, IID_PPV_ARGS(&pipeline)), "Create compute pipeline"); auto input = make_buffer(device, constants_offset + 4 * alignment, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); auto output = make_buffer(device, bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, @@ -275,14 +280,14 @@ static void run_compute(ID3D12Device* device, bool tables, D3D12_SHADER_BYTECODE fill_upload(input.Get(), store && store->has_source ? &store->source : nullptr, store && store->has_initial ? &store->initial : nullptr, store ? &store->root_constants : nullptr); - ComputeCommands commands(device, pipeline.Get()); + ComputeCommands commands(device, program.pipeline.Get()); auto& list = commands.list; ComPtr texture_upload, texture; if (texels) texture = upload_texture(device, list.Get(), *texels, texture_format, texture_upload); transition(list.Get(), output.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST); list->CopyBufferRegion(output.Get(), 0, input.Get(), bytes, bytes); transition(list.Get(), output.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); - list->SetComputeRootSignature(signature.Get()); + list->SetComputeRootSignature(program.signature.Get()); ComPtr heap; if (tables) { // An image-load case binds its output at u0 and the source texture at t0; the table @@ -346,21 +351,18 @@ static void run_compute(ID3D12Device* device, bool tables, D3D12_SHADER_BYTECODE store->axis(2), capacity, mismatches); else std::printf("layout=%s output_words=%u guard_words=%u mismatches=%u\n", tables ? "tables" : "root", active, capacity - active, mismatches); - if (mismatches) throw std::runtime_error("Compute readback differs from CPU reference"); + if (mismatches) throw ReadbackMismatch("Compute readback differs from CPU reference"); } void check_compute(ID3D12Device* device, bool tables) { const D3D12_SHADER_BYTECODE shader = tables ? D3D12_SHADER_BYTECODE{compute_tables, sizeof(compute_tables)} : D3D12_SHADER_BYTECODE{compute_root, sizeof(compute_root)}; - run_compute(device, tables, shader, shader); + run_compute(device, tables, create_compute_program(device, shader, shader)); } -void check_compute_file(ID3D12Device* device, const char* path, bool conversion_pair, const char* reference, - bool dpp_case, bool sized_views, UINT uav_words) +static std::vector read_compute_shader(const char* path) { - if (sized_views && uav_words > capacity) - throw std::runtime_error("Invalid compute UAV word count"); std::ifstream file(path, std::ios::binary | std::ios::ate); if (!file) throw std::runtime_error(std::string("Could not open compute shader: ") + path); const auto size = file.tellg(); @@ -369,70 +371,86 @@ void check_compute_file(ID3D12Device* device, const char* path, bool conversion_ file.seekg(0); if (!file.read(bytes.data(), static_cast(bytes.size()))) throw std::runtime_error(std::string("Could not read compute shader: ") + path); - const D3D12_SHADER_BYTECODE shader{bytes.data(), bytes.size()}; - if (reference) { - StoreCase store{}; - std::ifstream file(reference, std::ios::binary); - file.read(reinterpret_cast(&store.groups), sizeof(store.groups)); - file.read(reinterpret_cast(store.expected.data()), sizeof(store.expected)); - // Bit 31 declares the trailing initial output segment; no other bit above the - // group counts is known, so an unflagged case keeps its historic bounds check. - constexpr UINT initial_data_flag = 1u << 31; - store.has_initial = (store.groups & initial_data_flag) != 0; - store.groups &= ~initial_data_flag; - if (!file || store.groups >> 24 || !store.axis(0) || store.axis(0) > 5 || store.axis(1) > 5 || - store.axis(2) > 5) - throw std::runtime_error("Invalid compute store reference"); - if (dpp_case && store.groups != 1) - throw std::runtime_error("Invalid compute DPP reference dispatch"); - if (store.has_initial) { - file.read(reinterpret_cast(store.initial.data()), sizeof(store.initial)); - if (!file) - throw std::runtime_error("Invalid compute store initial words"); - } + return bytes; +} + +static StoreCase read_store_reference(const char* reference, bool dpp_case) +{ + StoreCase store{}; + std::ifstream file(reference, std::ios::binary); + file.read(reinterpret_cast(&store.groups), sizeof(store.groups)); + file.read(reinterpret_cast(store.expected.data()), sizeof(store.expected)); + // Bit 31 declares the trailing initial output segment; no other bit above the + // group counts is known, so an unflagged case keeps its historic bounds check. + constexpr UINT initial_data_flag = 1u << 31; + store.has_initial = (store.groups & initial_data_flag) != 0; + store.groups &= ~initial_data_flag; + if (!file || store.groups >> 24 || !store.axis(0) || store.axis(0) > 5 || store.axis(1) > 5 || + store.axis(2) > 5) + throw std::runtime_error("Invalid compute store reference"); + if (dpp_case && store.groups != 1) + throw std::runtime_error("Invalid compute DPP reference dispatch"); + if (store.has_initial) { + file.read(reinterpret_cast(store.initial.data()), sizeof(store.initial)); + if (!file) + throw std::runtime_error("Invalid compute store initial words"); + } + if (file.peek() != std::char_traits::eof()) { + file.read(reinterpret_cast(store.root_constants.data()), sizeof(store.root_constants)); + if (!file) + throw std::runtime_error("Invalid compute store constants"); if (file.peek() != std::char_traits::eof()) { - file.read(reinterpret_cast(store.root_constants.data()), sizeof(store.root_constants)); - if (!file) - throw std::runtime_error("Invalid compute store constants"); - if (file.peek() != std::char_traits::eof()) { - file.read(reinterpret_cast(store.source.data()), sizeof(store.source)); - if (!file || file.peek() != std::char_traits::eof()) - throw std::runtime_error("Invalid compute store source words"); - store.has_source = true; - } + file.read(reinterpret_cast(store.source.data()), sizeof(store.source)); + if (!file || file.peek() != std::char_traits::eof()) + throw std::runtime_error("Invalid compute store source words"); + store.has_source = true; } + } + return store; +} + +ComputeReadbackProgram load_compute_store_program(ID3D12Device* device, const char* shader) +{ + const auto code = read_compute_shader(shader); + return create_compute_program(device, {code.data(), code.size()}, {compute_root, sizeof(compute_root)}); +} + +void check_compute_store_reference(ID3D12Device* device, const ComputeReadbackProgram& program, const char* reference) +{ + const StoreCase store = read_store_reference(reference, false); + run_compute(device, false, program, false, &store); +} + +void check_compute_file(ID3D12Device* device, const char* path, bool conversion_pair, const char* reference, + bool dpp_case, bool sized_views, UINT uav_words) +{ + if (sized_views && uav_words > capacity) + throw std::runtime_error("Invalid compute UAV word count"); + const auto bytes = read_compute_shader(path); + const D3D12_SHADER_BYTECODE shader{bytes.data(), bytes.size()}; + if (reference) { + const StoreCase store = read_store_reference(reference, dpp_case); if (sized_views) { const UINT effective_uav_words = uav_words ? uav_words : capacity; if (effective_uav_words > capacity) throw std::runtime_error("Invalid compute UAV word count"); - run_compute(device, true, shader, {compute_tables, sizeof(compute_tables)}, false, &store, nullptr, + const auto program = create_compute_program(device, shader, {compute_tables, sizeof(compute_tables)}); + run_compute(device, true, program, false, &store, nullptr, DXGI_FORMAT_UNKNOWN, nullptr, dpp_case, true, 0, effective_uav_words); } else { - run_compute(device, false, shader, {compute_root, sizeof(compute_root)}, false, &store, nullptr, + const auto program = create_compute_program(device, shader, {compute_root, sizeof(compute_root)}); + run_compute(device, false, program, false, &store, nullptr, DXGI_FORMAT_UNKNOWN, nullptr, dpp_case); } } else { - run_compute(device, false, shader, shader, conversion_pair); + run_compute(device, false, create_compute_program(device, shader, shader), conversion_pair); } } -static std::vector read_texture_shader(const char* path) -{ - std::ifstream file(path, std::ios::binary | std::ios::ate); - if (!file) throw std::runtime_error(std::string("Could not open compute shader: ") + path); - const auto size = file.tellg(); - if (size <= 0) throw std::runtime_error(std::string("Empty compute shader: ") + path); - std::vector bytes(static_cast(size)); - file.seekg(0); - if (!file.read(bytes.data(), static_cast(bytes.size()))) - throw std::runtime_error(std::string("Could not read compute shader: ") + path); - return bytes; -} - // The image load uses a descriptor-table signature. Its case file appends the source texels. void check_compute_texture_file(ID3D12Device* device, const char* path, const char* reference) { - const auto code = read_texture_shader(path); + const auto code = read_compute_shader(path); const D3D12_SHADER_BYTECODE shader{code.data(), code.size()}; StoreCase store{}; std::ifstream source(reference, std::ios::binary); @@ -458,7 +476,8 @@ void check_compute_texture_file(ID3D12Device* device, const char* path, const ch throw std::runtime_error("Invalid compute image load reference"); const auto format = rgba8 ? DXGI_FORMAT_R8G8B8A8_UINT : rgba32_float ? DXGI_FORMAT_R32G32B32A32_FLOAT : DXGI_FORMAT_R32G32B32A32_UINT; - run_compute(device, true, shader, {compute_tables, sizeof(compute_tables)}, false, &store, &texels, format, + const auto program = create_compute_program(device, shader, {compute_tables, sizeof(compute_tables)}); + run_compute(device, true, program, false, &store, &texels, format, nullptr, false, false, view_mip1 ? 1 : 0); } @@ -540,12 +559,12 @@ bool check_compute_texture_msaa_file(ID3D12Device* device, const char* path, con source.read(reinterpret_cast(store.expected.data()), sizeof(store.expected)); if (!source || source.peek() != std::char_traits::eof() || store.groups != 1) throw std::runtime_error("Invalid compute MSAA load reference"); - const auto code = read_texture_shader(path); - const auto vs = read_texture_shader(vs_path), ps = read_texture_shader(ps_path); + const auto code = read_compute_shader(path); + const auto vs = read_compute_shader(vs_path), ps = read_compute_shader(ps_path); auto texture = render_msaa_texture(device, {vs.data(), vs.size()}, {ps.data(), ps.size()}); if (!texture) return false; - run_compute(device, true, {code.data(), code.size()}, {compute_tables, sizeof(compute_tables)}, - false, &store, nullptr, DXGI_FORMAT_UNKNOWN, texture.Get()); + const auto program = create_compute_program(device, {code.data(), code.size()}, {compute_tables, sizeof(compute_tables)}); + run_compute(device, true, program, false, &store, nullptr, DXGI_FORMAT_UNKNOWN, texture.Get()); return true; } @@ -650,7 +669,7 @@ bool check_compute_texture_store_file(ID3D12Device* device, const char* path, co return false; } - const auto code = read_texture_shader(path); + const auto code = read_compute_shader(path); ComPtr signature; check(device->CreateRootSignature(0, compute_tables, sizeof(compute_tables), IID_PPV_ARGS(&signature)), "Create image store root signature"); @@ -761,6 +780,7 @@ void check_bvh_root_roundtrip(ID3D12Device* device) if (roundtrip->GetBufferSize() != control->GetBufferSize() || std::memcmp(roundtrip->GetBufferPointer(), control->GetBufferPointer(), control->GetBufferSize()) != 0) throw std::runtime_error("Normalized signature differs from independent control serialization"); - run_compute(device, false, shader, {roundtrip->GetBufferPointer(), roundtrip->GetBufferSize()}); + const auto program = create_compute_program(device, shader, {roundtrip->GetBufferPointer(), roundtrip->GetBufferSize()}); + run_compute(device, false, program); std::puts("normalized_signature=matched_control root_creation=passed pipeline_creation=passed dispatch=passed"); } diff --git a/tests/compute_load_format_check.py b/tests/compute_load_format_check.py index bdaa9eca3..bc98b779b 100644 --- a/tests/compute_load_format_check.py +++ b/tests/compute_load_format_check.py @@ -7,6 +7,7 @@ from fractions import Fraction import os from pathlib import Path +import re import struct import subprocess import sys @@ -311,38 +312,70 @@ def binary(directory, assembler, objcopy, library): return 0 +def check_references(renderer, backend, shader, cases): + paths = [path for path, _label, _diagnostic in cases] + result = subprocess.run([renderer, backend, "--compute-store-batch", shader, *paths], + capture_output=True, text=True) + statuses = [line for line in result.stdout.splitlines() if line.startswith("case=")] + messages = re.split(r"(?=^case=\d+ path=)", result.stderr, flags=re.MULTILINE)[1:] + summaries = [line for line in result.stdout.splitlines() if line.startswith("groups=")] + for i, (path, label, diagnostic) in enumerate(cases): + status = "mismatch" if diagnostic else "pass" + if (i >= len(statuses) or statuses[i] != f"case={i} status={status}" + or i >= len(messages) or not messages[i].startswith(f"case={i} path={path}\n") + or (diagnostic and diagnostic not in messages[i])): + raise AssertionError(f"{NAME}: {label} expected {status}\n{result.stdout}{result.stderr}") + summary = summaries[i] if i < len(summaries) else "" + counts = re.fullmatch(r"groups=\d+ compared_words=320 mismatches=(\d+)", summary) + if not counts or (int(counts[1]) > 0) != bool(diagnostic): + raise AssertionError(f"{NAME}: {label} unexpected readback\n{result.stdout}{result.stderr}") + expected_exit = int(any(diagnostic for _, _, diagnostic in cases)) + if not (len(cases) == len(statuses) == len(messages) == len(summaries)) or result.returncode != expected_exit: + raise AssertionError(f"{NAME}: unexpected batch result ({result.returncode})\n{result.stdout}{result.stderr}") + labels = iter(label for _path, label, _diagnostic in cases) + for line in result.stdout.splitlines(): + if line.startswith("groups="): + print(f"{NAME}: {next(labels)}") + print(line) + + def draw(directory, compiler, renderer, backend): """Dispatch with chosen t0 words; wrong references and mutated sources must fail. - Every case owns its case and cso files, so the launches run on a small thread pool. Results are - checked afterwards in the original order with the original messages. + The reference cases share one device and compute pipeline. Each independently compiled mutation keeps its own + renderer process so compilation and readback can overlap with the reference checks. """ src, cso = directory / "load.hlsl", directory / "load.cso" source = lower() src.write_text(source, encoding="ascii") subprocess.run([compiler, "-T", "cs_6_0", "-E", "main", "-Fo", cso, src], check=True) words = source_words() - jobs = [] # (check, label, extra, case bytes, shader, mutated source or None) + references = [] + mutations = [] - def add(check, label, groups, reference, formats=None, extra=None, mutated=None): + def write_case(number, groups, reference, formats): + case = directory / f"case{number}.bin" data = (struct.pack("<321I", groups, *reference) + struct.pack("<16I", *(formats or constants())) + struct.pack("<320I", *words)) - jobs.append((check, label, extra, data, mutated)) - - def run(number, job): - _check, _label, _extra, data, mutated = job - case, shader = directory / f"case{number}.bin", cso case.write_bytes(data) - if mutated is not None: - shader = directory / f"mutated{number}.cso" - bad_src = directory / f"mutated{number}.hlsl" - bad_src.write_text(mutated, encoding="ascii") - subprocess.run([compiler, "-T", "cs_6_0", "-E", "main", "-Fo", shader, bad_src], check=True) - return subprocess.run([renderer, backend, "--compute-store-case", shader, case], - capture_output=True, text=True) + return case + + def add_reference(label, groups, reference, formats=None, diagnostic=None): + case = write_case(len(references), groups, reference, formats) + references.append((case, label, diagnostic)) + + def run_mutation(number, label, case, mutated): + shader = directory / f"mutated{number}.cso" + bad_src = directory / f"mutated{number}.hlsl" + bad_src.write_text(mutated, encoding="ascii") + subprocess.run([compiler, "-T", "cs_6_0", "-E", "main", "-Fo", shader, bad_src], check=True) + result = subprocess.run([renderer, backend, "--compute-store-case", shader, case], + capture_output=True, text=True) + if result.returncode != 1 or "Compute readback differs" not in result.stderr: + raise AssertionError(f"{NAME}: mutation '{label}' escaped detection\n{result.stderr}") for groups in (1, 2): - add("pass", "dispatch", groups, expected_words(groups)) + add_reference("dispatch", groups, expected_words(groups)) def invalid_formats(number): formats = constants() @@ -354,48 +387,37 @@ def invalid_formats(number): unwritten = [base.SENTINEL] * 320 zeros = (lambda channels: (lambda words: [0] * channels)) for number, (label, index, _word) in enumerate(INVALID): - add("pass", f"refused {label}", 2, unwritten, invalid_formats(number)) + add_reference(f"refused {label}", 2, unwritten, invalid_formats(number)) channels = len(LOADS[index][0]) placeholders = [("published as zeros", zeros(channels))] if number == 2: placeholders.append(("published with the (0, 0, 0, 1) fill", lambda words: [words[0], 0])) for what, values in placeholders: published = expected_words(2, placeholder=(index, values)) - add("placeholder", f"{label} {what}", 2, published, invalid_formats(number), - extra=f"word=0 expected={published[0]:08x} actual=c5c5c5c5") + add_reference(f"{label} {what}", 2, published, invalid_formats(number), + diagnostic=f"word=0 expected={published[0]:08x} actual=c5c5c5c5") expected = expected_words(2) for label, wrong in WRONG: reference = expected_words(2, wrong=wrong) word = next((i for i, (a, b) in enumerate(zip(expected, reference)) if a != b), None) if word is None: raise AssertionError(f"{NAME}: reference '{label}' matches the expected words") - add("wrong", label, 2, reference, extra=f"word={word} expected=") + add_reference(f"reference '{label}'", 2, reference, diagnostic=f"word={word} expected=") for label, old, new, run_index in MUTATIONS: mutated = source.replace(old, new, 1) if mutated == source: raise AssertionError(f"{NAME}: mutation '{label}' did not change the source") - if run_index is None: - add("mutation", label, 2, expected, mutated=mutated) - else: - add("mutation", label, 2, unwritten, invalid_formats(run_index), mutated=mutated) + number = len(references) + len(mutations) + reference, formats = (expected, None) if run_index is None else (unwritten, invalid_formats(run_index)) + case = write_case(number, 2, reference, formats) + mutations.append((number, label, case, mutated)) with ThreadPoolExecutor(max_workers=min(LAUNCH_THREADS, os.cpu_count() or 1)) as pool: - results = list(pool.map(lambda item: run(*item), enumerate(jobs))) - for (check, label, extra, _data, _mutated), result in zip(jobs, results): - if check == "pass": - print(f"{NAME}: {label}", flush=True) - sys.stdout.write(result.stdout) - if result.returncode: - sys.stderr.write(result.stderr) - return 1 - elif check == "placeholder": - if result.returncode != 1 or extra not in result.stderr: - raise AssertionError(f"{NAME}: {label} escaped detection\n{result.stderr}") - elif check == "wrong": - if result.returncode != 1 or extra not in result.stderr: - raise AssertionError(f"{NAME}: reference '{label}' escaped detection\n{result.stderr}") - elif result.returncode != 1 or "Compute readback differs" not in result.stderr: - raise AssertionError(f"{NAME}: mutation '{label}' escaped detection\n{result.stderr}") + batch = pool.submit(check_references, renderer, backend, cso, references) + mutants = [pool.submit(run_mutation, *mutation) for mutation in mutations] + batch.result() + for future in mutants: + future.result() print(f"{NAME}: {2 + len(INVALID)} dispatches, {len(WRONG) + len(INVALID) + 1} wrong references and " f"{len(MUTATIONS)} mutated sources checked") return 0 diff --git a/tests/desktop_gpu.h b/tests/desktop_gpu.h index 84ff8c3f5..b09835fa1 100644 --- a/tests/desktop_gpu.h +++ b/tests/desktop_gpu.h @@ -46,6 +46,12 @@ void check_spirv_compare_sampler(ID3D12Device* device, const char* shader_path, const char* reference_path, const char* descriptors = nullptr); void check_compute_file(ID3D12Device* device, const char* path, bool conversion_pair, const char* reference = nullptr, bool dpp_case = false, bool sized_views = false, UINT uav_words = 0); +struct ComputeReadbackProgram { + Microsoft::WRL::ComPtr signature; + Microsoft::WRL::ComPtr pipeline; +}; +ComputeReadbackProgram load_compute_store_program(ID3D12Device* device, const char* shader); +void check_compute_store_reference(ID3D12Device* device, const ComputeReadbackProgram& program, const char* reference); void check_compute_texture_file(ID3D12Device* device, const char* path, const char* reference); bool check_compute_texture_msaa_file(ID3D12Device* device, const char* path, const char* reference, const char* vs_path, const char* ps_path); @@ -80,8 +86,11 @@ void check_texture_mips(ID3D12Device* device); void check_depth_mask_draw(ID3D12Device*, const char*, const char*, const char*, bool); void check_sampled_coverage(ID3D12Device*, const char*, const char*); void check_dual_pixel(ID3D12Device*, const char*, const char*, bool); -struct PixelMismatch : std::runtime_error { - PixelMismatch() : std::runtime_error("AOT color export differs from CPU reference") {} +struct ReadbackMismatch : std::runtime_error { + using std::runtime_error::runtime_error; +}; +struct PixelMismatch : ReadbackMismatch { + PixelMismatch() : ReadbackMismatch("AOT color export differs from CPU reference") {} }; void check_translated_pixel(ID3D12Device* device, const char* path, bool swapRB, const char* reference = nullptr, diff --git a/tests/offscreen_check.cpp b/tests/offscreen_check.cpp index d3973cdd1..963f442ca 100644 --- a/tests/offscreen_check.cpp +++ b/tests/offscreen_check.cpp @@ -459,11 +459,14 @@ bool validate_compute_mesh_texture_fallback_args(int argc, char** argv) (argc != 10 || std::string_view(argv[9]) == "--stale"); } -template -OperationResult run_pixel_batch(const OperationContext& ctx, AfterDraw after_draw) +template +OperationResult run_readback_batch(const OperationContext& ctx, AfterCase after_case) { - const bool pairs = std::string_view(ctx.argv[2]) == "--check-pixel-pairs"; + const std::string_view operation(ctx.argv[2]); + const bool pairs = operation == "--check-pixel-pairs"; + const bool compute = operation == "--compute-store-batch"; const int stride = pairs ? 2 : 1; + ComputeReadbackProgram program; bool failed = false; for (int i = 4, index = 0; i < ctx.argc; i += stride, ++index) { const char* shader = ctx.argv[pairs ? i - 1 : 3]; @@ -471,10 +474,15 @@ OperationResult run_pixel_batch(const OperationContext& ctx, AfterDraw after_dra std::fprintf(stderr, "case=%d path=%s\n", index, ctx.argv[i]); if (pairs) std::fprintf(stderr, "shader=%s\n", shader); try { - check(ctx.device->GetDeviceRemovedReason(), "Pixel batch device"); - check_translated_pixel(ctx.device, shader, false, ctx.argv[i]); - after_draw(index); - } catch (const PixelMismatch& e) { + check(ctx.device->GetDeviceRemovedReason(), compute ? "Compute batch device" : "Pixel batch device"); + if (compute) { + if (!program.pipeline) program = load_compute_store_program(ctx.device, shader); + check_compute_store_reference(ctx.device, program, ctx.argv[i]); + } else { + check_translated_pixel(ctx.device, shader, false, ctx.argv[i]); + } + after_case(index); + } catch (const ReadbackMismatch& e) { std::fprintf(stderr, "%s\n", e.what()); status = "mismatch"; } catch (const std::exception& e) { @@ -490,15 +498,15 @@ OperationResult run_pixel_batch(const OperationContext& ctx, AfterDraw after_dra return failed ? OperationResult{OutcomeKind::fail, nullptr} : OperationResult{OutcomeKind::pass, nullptr}; } -OperationResult run_check_pixel_batch(const OperationContext& ctx) +OperationResult run_check_batch(const OperationContext& ctx) { - return run_pixel_batch(ctx, [](int) {}); + return run_readback_batch(ctx, [](int) {}); } OperationResult run_pixel_batch_debug_control(const OperationContext& ctx) { if (!ctx.messages) return {OutcomeKind::skip, "skip: pixel batch control requires the D3D12 debug layer"}; - return run_pixel_batch(ctx, [&](int index) { + return run_readback_batch(ctx, [&](int index) { if (index == 1) check(ctx.messages->AddApplicationMessage(D3D12_MESSAGE_SEVERITY_ERROR, "pixel batch control error"), "Add pixel batch control message"); @@ -511,7 +519,7 @@ OperationResult run_pixel_batch_removal_control(const OperationContext& ctx) const HRESULT hr = ctx.device->QueryInterface(IID_PPV_ARGS(&device)); if (hr == E_NOINTERFACE) return {OutcomeKind::skip, "skip: pixel batch control requires ID3D12Device5"}; check(hr, "Query pixel batch control device"); - return run_pixel_batch(ctx, [&](int index) { + return run_readback_batch(ctx, [&](int index) { if (index == 1) device->RemoveDevice(); }); } @@ -1620,8 +1628,8 @@ constexpr CapabilityGate kGateSm66MinLod{ // Scenario-dependent capability checks (such as DXR tier, mesh tier, or existing-heap support) // remain inside the handlers and report OutcomeKind::skip. const OperationSpec kOperations[] = { - {"--check-pixel-batch", 5, kUnboundedArgc, nullptr, kNoGate, run_check_pixel_batch}, - {"--check-pixel-pairs", 5, kUnboundedArgc, validate_pixel_pairs_args, kNoGate, run_check_pixel_batch}, + {"--check-pixel-batch", 5, kUnboundedArgc, nullptr, kNoGate, run_check_batch}, + {"--check-pixel-pairs", 5, kUnboundedArgc, validate_pixel_pairs_args, kNoGate, run_check_batch}, {"--pixel-batch-debug-control", 7, 7, nullptr, kNoGate, run_pixel_batch_debug_control}, {"--pixel-batch-removal-control", 7, 7, nullptr, kNoGate, run_pixel_batch_removal_control}, {"--compute-root", 3, 3, nullptr, kNoGate, run_compute_root}, @@ -1629,6 +1637,7 @@ const OperationSpec kOperations[] = { {"--compute-root-file", 4, 4, nullptr, kNoGate, run_compute_root_file}, {"--ffx-immediate-conversion", 4, 4, nullptr, kNoGate, run_ffx_immediate_conversion}, {"--compute-store-case", 5, 5, nullptr, kNoGate, run_compute_store_case}, + {"--compute-store-batch", 5, kUnboundedArgc, nullptr, kNoGate, run_check_batch}, {"--compute-store-sized-case", 5, 6, nullptr, kNoGate, run_compute_store_sized_case}, {"--compute-store-dpp-case", 5, 5, nullptr, kGateShaderWave, run_compute_store_dpp_case}, {"--compute-store-case-atomic64", 5, 5, nullptr, kGateComputeAtomic64, run_compute_store_case}, From 35e0a5d92dbe08ee541f17da23eb4a968463d455 Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Thu, 26 Nov 2026 01:38:17 +0200 Subject: [PATCH 011/240] runtime: add upfront CLI guards and atomic writes to bink_heap_aot with CLI suite (#2627) --- CMakeLists.txt | 3 + tests/bink_heap_aot_cli_check.py | 363 +++++++++++++++++++++++++++++++ tools/bink_heap_aot.py | 59 ++++- 3 files changed, 419 insertions(+), 6 deletions(-) create mode 100644 tests/bink_heap_aot_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index ed89ff2ac..08f0f7f5a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -10308,6 +10308,9 @@ if(EXISTS "${INTAKE_PYTHON}") set_tests_properties(pe_run_package_trap_missing PROPERTIES TIMEOUT 60) add_test(NAME bink_heap_aot_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/bink_heap_aot_check.py") + add_test(NAME runtime_bink_heap_aot_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/bink_heap_aot_cli_check.py") + set_tests_properties(runtime_bink_heap_aot_cli_check PROPERTIES TIMEOUT 60) add_test(NAME bink_frame_aot_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/bink_frame_aot_check.py") add_test(NAME cpu_stdio_exe_aot_check COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/bink_heap_aot_cli_check.py b/tests/bink_heap_aot_cli_check.py new file mode 100644 index 000000000..49bc5af44 --- /dev/null +++ b/tests/bink_heap_aot_cli_check.py @@ -0,0 +1,363 @@ +#!/usr/bin/env python3 +"""Pure-Python CLI, atomic-write, path-guard, and error-handling suite for tools/bink_heap_aot.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +from pathlib import Path +import runpy +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOLS_DIR = ROOT / "tools" +TOOL = TOOLS_DIR / "bink_heap_aot.py" +sys.path.insert(0, str(TOOLS_DIR)) +import bink_heap_aot # noqa: E402 + + +SYNTHETIC_CPP = ( + '#include \n' + 'using word = uint64_t;\n' + 'extern "C" __declspec(dllexport) void* heap_request(word bytes) { return nullptr; }\n' +) + + +def _run_main(argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = bink_heap_aot.main(argv) + except SystemExit as exc: + code = exc.code + if not isinstance(code, int): + if code is not None: + stderr.write(f"{code}\n") + code = 0 if code is None else 1 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class BinkHeapAotCliPositiveTests(unittest.TestCase): + def test_atomic_cpp_output_in_nested_new_dir_and_overwrite(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "synthetic.dll" + image.write_bytes(b"synthetic-image-placeholder") + nested_out = base / "nested" / "sub" / "heap_aot.cpp" + + # 1) Create missing parent directories and write atomically with 0 .tmp files. + with mock.patch.object(bink_heap_aot, "generate", return_value=SYNTHETIC_CPP) as gen: + code, out, err = _run_main([str(image), str(nested_out)]) + gen.assert_called_once_with(image, None, None) + self.assertEqual(code, 0, err) + self.assertEqual(out, "") + self.assertEqual(err, "") + self.assertEqual(nested_out.read_text(encoding="ascii"), SYNTHETIC_CPP) + self.assertEqual(sorted(p.name for p in nested_out.parent.iterdir()), ["heap_aot.cpp"]) + + # 2) Forward --entries and --group-entry, and atomically overwrite existing file with 0 .tmp files. + nested_out.write_text("stale content", encoding="ascii") + entries_cpp = SYNTHETIC_CPP + "// entries-mode\n" + with mock.patch.object(bink_heap_aot, "generate", return_value=entries_cpp) as gen_entries: + code_ent, out_ent, err_ent = _run_main([ + str(image), + str(nested_out), + "--entries", + "0x1000", + "0x2000", + "--group-entry", + "heap_group", + ]) + gen_entries.assert_called_once_with(image, [0x1000, 0x2000], "heap_group") + self.assertEqual(code_ent, 0, err_ent) + self.assertEqual(out_ent, "") + self.assertEqual(err_ent, "") + self.assertEqual(nested_out.read_text(encoding="ascii"), entries_cpp) + self.assertEqual(sorted(p.name for p in nested_out.parent.iterdir()), ["heap_aot.cpp"]) + + # 3) Verify sys.argv forwarding when argv=None. + cli_argv = [str(TOOL), str(image), str(nested_out)] + with ( + mock.patch.object(sys, "argv", cli_argv), + mock.patch.object(bink_heap_aot, "generate", return_value=SYNTHETIC_CPP), + ): + code_none, out_none, err_none = _run_main(None) + self.assertEqual(code_none, 0, err_none) + self.assertEqual(out_none, "") + self.assertEqual(err_none, "") + self.assertEqual(nested_out.read_text(encoding="ascii"), SYNTHETIC_CPP) + + # 4) Verify __main__ entrypoint propagates SystemExit cleanly on invalid PE. + bad_pe = base / "bad_main.dll" + bad_pe.write_bytes(b"not a PE") + stdout, stderr = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", [str(TOOL), str(bad_pe), str(base / "unused.cpp")]), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 1) + self.assertEqual(stdout.getvalue(), "") + self.assertNotIn("Traceback", stderr.getvalue()) + self.assertTrue(stderr.getvalue().strip()) + + +class BinkHeapAotCliNegativeTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_code: int | None, + fragments: tuple[str, ...] = (), + check_subprocess: bool = True, + ) -> str: + code, out, err = _run_main(argv) + if expected_code is None: + self.assertNotEqual(code, 0) + else: + self.assertEqual(code, expected_code, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertTrue(err.strip()) + for fragment in fragments: + self.assertIn(fragment.lower(), err.lower()) + + if check_subprocess: + proc = _run_subprocess(*argv) + if expected_code is None: + self.assertNotEqual(proc.returncode, 0) + else: + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + for fragment in fragments: + self.assertIn(fragment.lower(), proc.stderr.lower()) + return err + + def test_missing_and_directory_image_rejected_before_generate(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + dir_image = base / "dir_image" + dir_image.mkdir() + absent_out = base / "should_not_exist" / "heap_aot.cpp" + + with ( + mock.patch.object( + bink_heap_aot, + "generate", + side_effect=AssertionError("generate called for invalid image path"), + ), + mock.patch.object( + bink_heap_aot, + "_write_atomic", + side_effect=AssertionError("_write_atomic called for invalid image path"), + ), + ): + self._assert_clean_failure( + [str(base / "missing.dll"), str(absent_out)], + expected_code=1, + fragments=("image file not found",), + ) + self._assert_clean_failure( + [str(dir_image), str(absent_out)], + expected_code=1, + fragments=("image path is a directory",), + ) + + self.assertFalse(absent_out.parent.exists()) + + def test_invalid_pe_bytes_exit_1_without_creating_output_or_temps(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + bad_pe = base / "bad.dll" + bad_pe.write_bytes(b"not a valid PE32+ image") + absent_out = base / "absent_dir" / "heap_aot.cpp" + + self._assert_clean_failure( + [str(bad_pe), str(absent_out)], + expected_code=1, + ) + self.assertFalse(absent_out.parent.exists()) + + def test_negative_entries_and_empty_group_entry_rejected_before_generate(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(b"synthetic-image-bytes") + out_cpp = base / "absent_dir" / "heap_aot.cpp" + + with ( + mock.patch.object( + bink_heap_aot, + "generate", + side_effect=AssertionError("generate called for invalid entries/group-entry"), + ), + mock.patch.object( + bink_heap_aot, + "_write_atomic", + side_effect=AssertionError("_write_atomic called for invalid entries/group-entry"), + ), + ): + for label, argv, frags in ( + ("neg_alloc_rva", [str(image), str(out_cpp), "--entries", "-1", "0x2000"], ("non-negative",)), + ("neg_free_rva", [str(image), str(out_cpp), "--entries", "0x1000", "-4"], ("non-negative",)), + ("both_neg_rva", [str(image), str(out_cpp), "--entries", "-1", "-4"], ("non-negative",)), + ("empty_group_entry", [str(image), str(out_cpp), "--group-entry", ""], ("--group-entry",)), + ("blank_group_entry", [str(image), str(out_cpp), "--group-entry", " "], ("--group-entry",)), + ): + with self.subTest(case=label): + self._assert_clean_failure(argv, expected_code=1, fragments=frags) + + self.assertFalse(out_cpp.parent.exists()) + + def test_output_guards_reject_before_generate_and_write(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(b"synthetic-image-bytes") + same_cpp = base / "same.cpp" + same_cpp.write_bytes(b"synthetic-cpp-bytes") + hardlink_cpp = base / "hardlink.cpp" + hardlink_cpp.hardlink_to(image) + out_dir = base / "existing_dir.cpp" + out_dir.mkdir() + file_parent = base / "regular_parent.txt" + file_parent.write_text("keep-me", encoding="ascii") + + with ( + mock.patch.object( + bink_heap_aot, + "generate", + side_effect=AssertionError("generate called for invalid output path"), + ), + mock.patch.object( + bink_heap_aot, + "_write_atomic", + side_effect=AssertionError("_write_atomic called for invalid output path"), + ), + ): + for label, argv, code, frags in ( + ("non_cpp_suffix", [str(image), str(base / "out.txt")], 2, ("distinct .cpp output",)), + ("empty_output", [str(image), ""], 2, ("distinct .cpp output",)), + ("same_path", [str(same_cpp), str(same_cpp)], 2, ("distinct .cpp output",)), + ("hardlink_samefile", [str(image), str(hardlink_cpp)], 2, ("distinct .cpp output",)), + ("output_is_dir", [str(image), str(out_dir)], 1, ("directory",)), + ("parent_is_file", [str(image), str(file_parent / "heap_aot.cpp")], 1, ("not a directory",)), + ("ancestor_is_file", [str(image), str(file_parent / "sub" / "heap_aot.cpp")], 1, ("not a directory",)), + ): + with self.subTest(case=label): + self._assert_clean_failure(argv, expected_code=code, fragments=frags) + + self.assertEqual(same_cpp.read_bytes(), b"synthetic-cpp-bytes") + self.assertEqual(image.read_bytes(), b"synthetic-image-bytes") + self.assertEqual(list(out_dir.iterdir()), []) + self.assertEqual(file_parent.read_text(encoding="ascii"), "keep-me") + self.assertFalse((base / "out.txt").exists()) + + def test_output_symlink_rejected_before_generate_and_write(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(b"synthetic-image-bytes") + out_dir = base / "out_dir" + out_dir.mkdir() + real_target = out_dir / "real.cpp" + real_target.write_text("untouched", encoding="ascii") + live_link = out_dir / "live_link.cpp" + dangling_link = out_dir / "dangling_link.cpp" + try: + live_link.symlink_to(real_target) + dangling_link.symlink_to(out_dir / "missing.cpp") + except OSError as exc: + if getattr(exc, "winerror", None) != 1314: + raise + self.skipTest("this Windows account cannot create symlinks (WinError 1314)") + + with ( + mock.patch.object( + bink_heap_aot, + "generate", + side_effect=AssertionError("generate called for symlink output"), + ), + mock.patch.object( + bink_heap_aot, + "_write_atomic", + side_effect=AssertionError("_write_atomic called for symlink output"), + ), + ): + for label, link in (("live_symlink", live_link), ("dangling_symlink", dangling_link)): + with self.subTest(case=label): + self._assert_clean_failure( + [str(image), str(link)], + expected_code=1, + fragments=("symlink",), + ) + + self.assertEqual(real_target.read_text(encoding="ascii"), "untouched") + self.assertEqual( + sorted(p.name for p in out_dir.iterdir()), + ["dangling_link.cpp", "live_link.cpp", "real.cpp"], + ) + + def test_atomic_write_failure_leaves_zero_tmp_files(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(b"synthetic-image-bytes") + out_dir = base / "out_dir" + out_dir.mkdir() + out_cpp = out_dir / "heap_aot.cpp" + out_cpp.write_text("original", encoding="ascii") + + with ( + mock.patch.object(bink_heap_aot, "generate", return_value=SYNTHETIC_CPP), + mock.patch.object(Path, "replace", side_effect=OSError("simulated replace failure")), + ): + self._assert_clean_failure( + [str(image), str(out_cpp)], + expected_code=1, + fragments=("simulated replace failure",), + check_subprocess=False, + ) + + self.assertEqual(out_cpp.read_text(encoding="ascii"), "original") + self.assertEqual(sorted(p.name for p in out_dir.iterdir()), ["heap_aot.cpp"]) + + def test_argparse_errors_py314_safe(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(b"synthetic") + out_cpp = base / "heap_aot.cpp" + + for argv, frags in ( + ([], ("required",)), + ([str(image)], ("required",)), + ([str(image), str(out_cpp), "--entries", "0x1000"], ("expected 2 arguments",)), + ([str(image), str(out_cpp), "--entries", "bad", "0x2000"], ("invalid",)), + ([str(image), str(out_cpp), "--bogus-flag"], ("unrecognized",)), + ): + with self.subTest(argv=argv): + self._assert_clean_failure( + argv, + expected_code=None, + fragments=frags, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/bink_heap_aot.py b/tools/bink_heap_aot.py index 430f39223..49455a304 100644 --- a/tools/bink_heap_aot.py +++ b/tools/bink_heap_aot.py @@ -1,6 +1,8 @@ """Lower the Bink callback setter and heap callers to a Windows DLL.""" import argparse from pathlib import Path +import struct +import tempfile import pefile from iced_x86 import Decoder, MemorySizeExt, Mnemonic as M, OpKind as K, Register as R @@ -208,7 +210,52 @@ def generate(image, entries, group_entry=None): """ + group -def main(argv=None): +def _validate_args(args: argparse.Namespace, parser: argparse.ArgumentParser) -> None: + if args.image.is_dir(): + raise IsADirectoryError(f"image path is a directory: {args.image}") + if not args.image.is_file(): + raise FileNotFoundError(f"image file not found: {args.image}") + if args.entries is not None and any(rva < 0 for rva in args.entries): + raise ValueError("--entries RVAs must be non-negative") + if args.group_entry is not None and not args.group_entry.strip(): + raise ValueError("--group-entry must be non-empty") + if args.output.suffix.lower() != ".cpp": + parser.error("choose a distinct .cpp output") + if args.output.is_symlink(): + raise ValueError(f"output path must not be a symlink: {args.output}") + if args.output.is_dir(): + raise IsADirectoryError(f"output path is a directory: {args.output}") + for parent in args.output.parents: + if parent.is_file() or ((parent.exists() or parent.is_symlink()) and not parent.is_dir()): + raise NotADirectoryError(f"output parent is not a directory: {parent}") + if args.output.resolve() == args.image.resolve() or (args.output.exists() and args.image.samefile(args.output)): + parser.error("choose a distinct .cpp output") + + +def _write_atomic(path: Path, content: str) -> None: + """Write ASCII content to a sibling temp file and atomically replace path, leaving 0 temp files on failure.""" + path.parent.mkdir(parents=True, exist_ok=True) + tmp_path = None + try: + with tempfile.NamedTemporaryFile( + mode="w", + encoding="ascii", + newline="\n", + dir=path.parent, + prefix=f".{path.stem}.", + suffix=".tmp", + delete=False, + ) as handle: + tmp_path = Path(handle.name) + handle.write(content) + tmp_path.replace(path) + except BaseException: + if tmp_path is not None: + tmp_path.unlink(missing_ok=True) + raise + + +def main(argv=None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("image", type=Path) parser.add_argument("output", type=Path) @@ -216,13 +263,13 @@ def main(argv=None): metavar=("ALLOC_RVA", "FREE_RVA")) parser.add_argument("--group-entry", help="Grouped allocation caller RVA or the fixture export heap_group") args = parser.parse_args(argv) - if args.output.suffix.lower() != ".cpp" or args.output.resolve() == args.image.resolve(): - parser.error("choose a distinct .cpp output") try: - args.output.write_text(generate(args.image, args.entries, args.group_entry), encoding="ascii") - except (ValueError, OSError, pefile.PEFormatError) as error: + _validate_args(args, parser) + _write_atomic(args.output, generate(args.image, args.entries, args.group_entry)) + except (ValueError, OSError, struct.error, pefile.PEFormatError) as error: parser.exit(1, f"{error}\n") + return 0 if __name__ == "__main__": - main() + raise SystemExit(main()) From 0236873794ac49a0154a623fdbaa3c0b46fc7035 Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Thu, 26 Nov 2026 01:39:12 +0200 Subject: [PATCH 012/240] ci: harden coverage_svg validation and atomic writes with CLI suite (#2617) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 3 + tests/coverage_svg_cli_check.py | 448 ++++++++++++++++++++++++++++++++ tools/coverage_svg.py | 56 +++- 3 files changed, 501 insertions(+), 6 deletions(-) create mode 100644 tests/coverage_svg_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 08f0f7f5a..ad93d3a12 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4280,6 +4280,9 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/emit_variants_cli_check.py") add_test(NAME coverage_svg COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/coverage_svg_check.py") + add_test(NAME ci_coverage_svg_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/coverage_svg_cli_check.py") + set_tests_properties(ci_coverage_svg_cli_check PROPERTIES TIMEOUT 60) # Compile-only: outcome classification and GVN pass shares, no wall-time threshold (#775). add_test(NAME dxc_compile_time_gvn COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/dxc_compile_time_check.py" "${DXC_EXECUTABLE}") diff --git a/tests/coverage_svg_cli_check.py b/tests/coverage_svg_cli_check.py new file mode 100644 index 000000000..149ad4628 --- /dev/null +++ b/tests/coverage_svg_cli_check.py @@ -0,0 +1,448 @@ +#!/usr/bin/env python3 +"""CLI, validation, collision, atomic-write, and mutation suite for tools/coverage_svg.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +import json +import os +from pathlib import Path +import runpy +import subprocess +import sys +from tempfile import TemporaryDirectory +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "coverage_svg.py" +sys.path.insert(0, str(ROOT / "tools")) + +import coverage_svg as cs # noqa: E402 + + +def _sample_coverage(): + return { + "x64_zen2": { + "covered": 4, + "total": 1007, + "blocked_by_skip": ["SSE movss"], + "groups": { + "Integer": {"covered": 3, "total": 1000}, + "SSE": {"covered": 1, "total": 6}, + "Tiny": {"covered": 0, "total": 1}, + "Zero": {"covered": 0, "total": 0}, + }, + }, + "gfx1013": { + "covered": 0, + "total": 0, + "blocked_by_skip": [], + "groups": { + "ZeroOnly": {"covered": 0, "total": 0}, + }, + }, + "gfx1030": { + "covered": 2, + "total": 5, + "blocked_by_skip": ["VOP3 v_add3_u32"], + "groups": { + "SOP1": {"covered": 2, "total": 3}, + "VOP3": {"covered": 0, "total": 2}, + }, + }, + } + + +def _run_main(argv): + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = cs.main(argv) + except SystemExit as exc: + code = exc.code if isinstance(exc.code, int) else 2 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args): + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class CoverageSvgCliPositiveTests(unittest.TestCase): + def test_direct_main_writes_svg_creates_parents_and_leaves_zero_tmp(self): + data = _sample_coverage() + with TemporaryDirectory() as tmp: + root = Path(tmp) + cov = root / "coverage.json" + cov.write_text(json.dumps(data), encoding="utf-8") + out_svg = root / "nested" / "sub" / "dashboard.svg" + self.assertFalse(out_svg.parent.exists()) + + code, out, err = _run_main([str(cov), str(out_svg), "--source", "test-commit, test-os, warp"]) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(out, "") + self.assertEqual(err, "") + self.assertTrue(out_svg.is_file()) + self.assertEqual( + out_svg.read_text(encoding="utf-8"), + cs.render(data, "test-commit, test-os, warp"), + ) + self.assertEqual([p.name for p in out_svg.parent.iterdir()], ["dashboard.svg"]) + + def test_sys_argv_and_script_entrypoint(self): + data = _sample_coverage() + with TemporaryDirectory() as tmp: + root = Path(tmp) + cov = root / "coverage.json" + cov.write_text(json.dumps(data), encoding="utf-8") + out_svg = root / "out" / "entry.svg" + cli_argv = [str(TOOL), str(cov), str(out_svg), "--source", "entry-banner"] + + with mock.patch.object(sys, "argv", cli_argv): + code, out, err = _run_main(None) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(out, "") + self.assertEqual(err, "") + self.assertIn("Measured on entry-banner.", out_svg.read_text(encoding="utf-8")) + + out_svg.unlink() + stdout, stderr = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", cli_argv), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 0) + self.assertEqual(stdout.getvalue(), "") + self.assertEqual(stderr.getvalue(), "") + self.assertTrue(out_svg.is_file()) + + def test_subprocess_end_to_end_positive(self): + data = _sample_coverage() + with TemporaryDirectory() as tmp: + root = Path(tmp) + cov = root / "coverage.json" + cov.write_text(json.dumps(data), encoding="utf-8") + out_svg = root / "sub.svg" + + proc = _run_subprocess(str(cov), str(out_svg), "--source", "sub-banner") + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertEqual(proc.stderr, "") + self.assertEqual(out_svg.read_text(encoding="utf-8"), cs.render(data, "sub-banner")) + self.assertFalse(any(p.name.endswith(".tmp") for p in root.iterdir())) + + +class CoverageSvgCliNegativeAndMutationTests(unittest.TestCase): + def _assert_clean_failure(self, argv, *, expected_fragment, expected_code=1, check_subprocess=True): + code, out, err = _run_main(argv) + self.assertEqual(code, expected_code, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + if expected_code == 1: + self.assertIn("coverage_svg:", err) + else: + self.assertIn("usage:", err.lower()) + if expected_fragment: + self.assertIn(expected_fragment, err) + + if check_subprocess: + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + if expected_code == 1: + self.assertIn("coverage_svg:", proc.stderr) + else: + self.assertIn("usage:", proc.stderr.lower()) + if expected_fragment: + self.assertIn(expected_fragment, proc.stderr) + + def test_empty_and_whitespace_source_rejected_upfront_and_in_render(self): + data = _sample_coverage() + for bad_source in ("", " ", "\t\n", None): + with self.subTest(bad_source=bad_source): + with self.assertRaisesRegex(ValueError, "source"): + cs.render(data, bad_source) + + with TemporaryDirectory() as tmp: + root = Path(tmp) + cov = root / "coverage.json" + cov.write_text(json.dumps(data), encoding="utf-8") + out_svg = root / "never_created" / "out.svg" + + for bad_source in ("", " ", "\t\n"): + with self.subTest(cli_source=bad_source): + with ( + mock.patch.object(cs, "render") as render_mock, + mock.patch.object(cs, "_write_atomic") as write_mock, + ): + self._assert_clean_failure( + [str(cov), str(out_svg), "--source", bad_source], + expected_fragment="--source must not be empty", + ) + render_mock.assert_not_called() + write_mock.assert_not_called() + self.assertFalse(out_svg.parent.exists()) + + def test_render_rejects_bool_negative_and_covered_gt_total_counts(self): + def _mutated(mutator): + sample = _sample_coverage() + mutator(sample) + return sample + + cases = ( + ("area_bool_covered", lambda d: d["x64_zen2"].__setitem__("covered", True), TypeError, "integers"), + ("area_bool_total", lambda d: d["x64_zen2"].__setitem__("total", False), TypeError, "integers"), + ("area_float_covered", lambda d: d["x64_zen2"].__setitem__("covered", 1.5), TypeError, "integers"), + ("area_neg_covered", lambda d: d["x64_zen2"].__setitem__("covered", -1), ValueError, "non-negative"), + ("area_neg_total", lambda d: d["x64_zen2"].__setitem__("total", -1), ValueError, "non-negative"), + ( + "area_covered_gt_total", + lambda d: d["x64_zen2"].__setitem__("covered", d["x64_zen2"]["total"] + 1), + ValueError, + "exceed total", + ), + ("group_bool_covered", lambda d: d["x64_zen2"]["groups"]["Integer"].__setitem__("covered", True), TypeError, "integers"), + ("group_bool_total", lambda d: d["x64_zen2"]["groups"]["Integer"].__setitem__("total", True), TypeError, "integers"), + ("group_float_total", lambda d: d["x64_zen2"]["groups"]["Integer"].__setitem__("total", 2.5), TypeError, "integers"), + ("group_neg_covered", lambda d: d["x64_zen2"]["groups"]["Integer"].__setitem__("covered", -1), ValueError, "non-negative"), + ("group_neg_total", lambda d: d["x64_zen2"]["groups"]["Integer"].__setitem__("total", -1), ValueError, "non-negative"), + ( + "group_covered_gt_total", + lambda d: d["x64_zen2"]["groups"]["SSE"].__setitem__("covered", 7), + ValueError, + "exceed total", + ), + ) + for name, mutator, exc_type, fragment in cases: + with self.subTest(case=name): + with self.assertRaisesRegex(exc_type, fragment): + cs.render(_mutated(mutator), "banner") + + with TemporaryDirectory() as tmp: + root = Path(tmp) + out_svg = root / "never" / "out.svg" + for name, mutator, _, fragment in cases: + with self.subTest(cli_case=name): + cov = root / f"{name}.json" + cov.write_text(json.dumps(_mutated(mutator)), encoding="utf-8") + self._assert_clean_failure( + [str(cov), str(out_svg), "--source", "banner"], + expected_fragment=fragment, + ) + self.assertFalse(out_svg.parent.exists()) + self.assertFalse(any(p.name.endswith(".tmp") for p in root.iterdir())) + + def test_coverage_input_missing_dir_and_non_regular_rejected_upfront(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + missing = root / "missing.json" + dir_in = root / "dir_in" + dir_in.mkdir() + reg_in = root / "coverage.json" + reg_in.write_text(json.dumps(_sample_coverage()), encoding="utf-8") + out_svg = root / "never" / "out.svg" + + for path, frag in ( + (missing, "coverage file not found"), + (dir_in, "coverage path is a directory"), + ): + with self.subTest(path=path): + with ( + mock.patch.object(cs, "render") as render_mock, + mock.patch.object(cs, "_write_atomic") as write_mock, + ): + self._assert_clean_failure( + [str(path), str(out_svg), "--source", "banner"], + expected_fragment=frag, + ) + render_mock.assert_not_called() + write_mock.assert_not_called() + self.assertFalse(out_svg.parent.exists()) + + with ( + mock.patch.object(Path, "is_file", return_value=False), + mock.patch.object(cs, "render") as render_mock, + mock.patch.object(cs, "_write_atomic") as write_mock, + ): + self._assert_clean_failure( + [str(reg_in), str(out_svg), "--source", "banner"], + expected_fragment="regular file", + check_subprocess=False, + ) + render_mock.assert_not_called() + write_mock.assert_not_called() + self.assertFalse(out_svg.parent.exists()) + + def test_output_dir_symlink_file_parent_and_samefile_rejected_upfront(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + sub = root / "sub" + sub.mkdir() + cov = root / "coverage.json" + cov.write_text(json.dumps(_sample_coverage()), encoding="utf-8") + cov_bytes = cov.read_bytes() + + # 1) Existing directory output rejected upfront. + out_dir = root / "existing_dir" + out_dir.mkdir() + with ( + mock.patch.object(cs, "render") as render_mock, + mock.patch.object(cs, "_write_atomic") as write_mock, + ): + self._assert_clean_failure( + [str(cov), str(out_dir), "--source", "banner"], + expected_fragment="existing directory", + ) + render_mock.assert_not_called() + write_mock.assert_not_called() + self.assertEqual(list(out_dir.iterdir()), []) + + # 2) Output symlink rejected upfront (real symlink if permitted, else mocked). + target = root / "keep_target.svg" + target.write_text("keep-target", encoding="utf-8") + sym_out = root / "link.svg" + try: + sym_out.symlink_to(target) + created_real = True + except OSError as exc: + if getattr(exc, "winerror", None) != 1314: + raise + created_real = False + + if created_real: + with ( + mock.patch.object(cs, "render") as render_mock, + mock.patch.object(cs, "_write_atomic") as write_mock, + ): + self._assert_clean_failure( + [str(cov), str(sym_out), "--source", "banner"], + expected_fragment="symbolic link", + ) + render_mock.assert_not_called() + write_mock.assert_not_called() + sym_out.unlink() + else: + with ( + mock.patch.object( + Path, + "is_symlink", + autospec=True, + side_effect=lambda p, expected=sym_out: p.resolve() == expected.resolve(), + ), + mock.patch.object(cs, "render") as render_mock, + mock.patch.object(cs, "_write_atomic") as write_mock, + ): + self._assert_clean_failure( + [str(cov), str(sym_out), "--source", "banner"], + expected_fragment="symbolic link", + check_subprocess=False, + ) + render_mock.assert_not_called() + write_mock.assert_not_called() + self.assertEqual(target.read_text(encoding="utf-8"), "keep-target") + + # 3) File-parent output (direct and nested under regular file) rejected upfront. + file_parent = root / "regular_parent" + file_parent.write_text("keep-parent", encoding="utf-8") + for bad_out in (file_parent / "out.svg", file_parent / "nested" / "out.svg"): + with self.subTest(file_parent_out=bad_out): + with ( + mock.patch.object(cs, "render") as render_mock, + mock.patch.object(cs, "_write_atomic") as write_mock, + ): + self._assert_clean_failure( + [str(cov), str(bad_out), "--source", "banner"], + expected_fragment="parent path is not a directory", + ) + render_mock.assert_not_called() + write_mock.assert_not_called() + self.assertEqual(file_parent.read_text(encoding="utf-8"), "keep-parent") + + # 4) Output colliding with input via exact path, resolve() alias, and hardlink samefile(). + alias_out = sub / ".." / "coverage.json" + hardlink_out = sub / "hardlink.svg" + os.link(cov, hardlink_out) + self.assertNotEqual(cov.resolve(), hardlink_out.resolve()) + self.assertTrue(cov.samefile(hardlink_out)) + + for label, bad_out in (("exact", cov), ("alias", alias_out), ("samefile", hardlink_out)): + with self.subTest(collision=label): + with ( + mock.patch.object(cs, "render") as render_mock, + mock.patch.object(cs, "_write_atomic") as write_mock, + ): + self._assert_clean_failure( + [str(cov), str(bad_out), "--source", "banner"], + expected_fragment="must not match input", + ) + render_mock.assert_not_called() + write_mock.assert_not_called() + self.assertEqual(cov.read_bytes(), cov_bytes) + self.assertFalse(any(p.name.endswith(".tmp") for p in root.iterdir())) + self.assertFalse(any(p.name.endswith(".tmp") for p in sub.iterdir())) + + def test_bad_json_and_atomic_write_failure_leave_zero_tmp_files(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + bad_json = root / "bad.json" + bad_json.write_text("{not json", encoding="utf-8") + never_out = root / "never" / "out.svg" + self._assert_clean_failure( + [str(bad_json), str(never_out), "--source", "banner"], + expected_fragment="Expecting", + ) + self.assertFalse(never_out.parent.exists()) + self.assertFalse(any(p.name.endswith(".tmp") for p in root.iterdir())) + + cov = root / "coverage.json" + cov.write_text(json.dumps(_sample_coverage()), encoding="utf-8") + sentinel_dir = root / "sentinel_dir" + sentinel_dir.mkdir() + sentinel = sentinel_dir / "keep.svg" + sentinel.write_text("prior-svg", encoding="utf-8") + + with mock.patch.object(Path, "replace", side_effect=OSError("simulated replace failure")): + self._assert_clean_failure( + [str(cov), str(sentinel), "--source", "banner"], + expected_fragment="simulated replace failure", + check_subprocess=False, + ) + self.assertEqual(sentinel.read_text(encoding="utf-8"), "prior-svg") + self.assertEqual([p.name for p in sentinel_dir.iterdir()], ["keep.svg"]) + + def test_argparse_errors_py314_compatible_exit_2_without_traceback(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + cov = root / "coverage.json" + cov.write_text(json.dumps(_sample_coverage()), encoding="utf-8") + out_svg = root / "out.svg" + + for bad_argv in ( + [], + [str(cov)], + [str(cov), str(out_svg)], + [str(cov), str(out_svg), "--source"], + [str(cov), str(out_svg), "--source", "ok", "--unknown-flag"], + ): + with self.subTest(argv=bad_argv): + self._assert_clean_failure( + bad_argv, + expected_fragment="", + expected_code=2, + ) + self.assertFalse(out_svg.exists()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/coverage_svg.py b/tools/coverage_svg.py index cf3dbeb55..e90a51e0f 100644 --- a/tools/coverage_svg.py +++ b/tools/coverage_svg.py @@ -104,7 +104,23 @@ def group(name, counts, x, y, w, h): return "".join(parts) + "", labelled +def _validate_counts(covered, total, scope: str) -> None: + if ( + isinstance(covered, bool) + or not isinstance(covered, int) + or isinstance(total, bool) + or not isinstance(total, int) + ): + raise TypeError(f"{scope} counts must be integers") + if total < 0 or covered < 0: + raise ValueError(f"{scope} counts must be non-negative") + if covered > total: + raise ValueError(f"{scope} covered count ({covered}) must not exceed total ({total})") + + def render(m, source): + if not isinstance(source, str) or not source.strip(): + raise ValueError("--source must not be empty") if not isinstance(m, dict): raise TypeError("coverage root must be a JSON object") rows = [text(20, 34, "Instruction-form coverage", 20, bold=True), text(20, 56, NOTE, 12, MUTED), @@ -119,6 +135,7 @@ def render(m, source): groups = r["groups"] if not isinstance(blocked, list) or not isinstance(groups, dict): raise TypeError(f"{key} entry has invalid blocked_by_skip or groups") + _validate_counts(r["covered"], r["total"], key) held = {} for form in blocked: if not isinstance(form, str): @@ -137,8 +154,7 @@ def render(m, source): raise TypeError(f"{key}.{g} must be a JSON object") total = v["total"] covered = v["covered"] - if total < 0 or covered < 0: - raise ValueError(f"{key}.{g} counts must be non-negative") + _validate_counts(covered, total, f"{key}.{g}") if total > 0: items.append((g, total)) items.sort(key=lambda kv: -kv[1]) @@ -180,6 +196,35 @@ def _write_atomic(path: Path, content: str) -> None: raise +def _same_path(left: Path, right: Path) -> bool: + if left == right: + return True + if left.exists() and right.exists() and left.samefile(right): + return True + try: + return left.resolve() == right.resolve() + except OSError: + return False + + +def _validate_paths(coverage: Path, output: Path) -> None: + if not coverage.exists(): + raise FileNotFoundError(f"coverage file not found: {coverage}") + if coverage.is_dir(): + raise IsADirectoryError(f"coverage path is a directory: {coverage}") + if not coverage.is_file(): + raise ValueError(f"coverage path must be a regular file: {coverage}") + if output.is_symlink(): + raise ValueError(f"output path must not be a symbolic link: {output}") + if output.exists() and output.is_dir(): + raise IsADirectoryError(f"output path is an existing directory: {output}") + for parent in output.parents: + if (parent.exists() or parent.is_symlink()) and not parent.is_dir(): + raise ValueError(f"output parent path is not a directory: {parent}") + if _same_path(output, coverage): + raise ValueError(f"output path must not match input path: {output}") + + def main(argv=None) -> int: parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("coverage", type=Path, help="JSON written by form_coverage.py --json") @@ -187,10 +232,9 @@ def main(argv=None) -> int: parser.add_argument("--source", required=True, help="commit, OS build and adapter of the measured run") args = parser.parse_args(argv) try: - coverage_path = args.coverage.resolve() - output_path = args.output.resolve() - if output_path == coverage_path: - raise ValueError(f"output path must not match input path: {args.output}") + if not args.source.strip(): + raise ValueError("--source must not be empty") + _validate_paths(args.coverage, args.output) svg = render(json.loads(args.coverage.read_text(encoding="utf-8")), args.source) _write_atomic(args.output, svg) except (OSError, ValueError, KeyError, TypeError) as exc: From 0f09473fa6f42e0049b47f28f6364aafafd826eb Mon Sep 17 00:00:00 2001 From: Chad Hyatt Date: Wed, 25 Nov 2026 17:41:04 -0600 Subject: [PATCH 013/240] shader: classify RDNA2 permlane operations as cross-lane (#2628) - Preserve ordinary vector ALU classification and translator refusal. - Exercise the authored encodings and dashboard categories. Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- docs/experiments.md | 10 +++++++ tests/rdna2_tools_check.py | 48 +++++++++++++++++++++++++++++++ tools/scan_unsupported_shaders.py | 10 ++++++- 3 files changed, 67 insertions(+), 1 deletion(-) diff --git a/docs/experiments.md b/docs/experiments.md index f593934ce..27e29d30e 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -13994,6 +13994,16 @@ python3 -B tests/rdna2_tools_check.py Scope: recognition only. No translator lowers these forms through this change, and no hardware or Windows run backs them. +## RDNA2 lane permutations in the unsupported-shader report + +`tools/scan_unsupported_shaders.py` reports `v_permlane16_b32` and +`v_permlanex16_b32` as `VALU (Cross-lane)` in `unsupported_details`. +The former can gather a value from another lane in the same 16-lane row. +The latter selects from the paired row. Both remain unsupported by the +pixel translator with either a declared wave32 or wave64 layout. The +lane-local byte-selection instruction `v_perm_b32` retains its ordinary +VALU classification. [AMD RDNA 2 ISA, §12.12](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) + ## gfx1013 VOP1 rounding, frexp and operand-free opcodes `tools/disasm_rdna2.py` named only part of the VOP1 table; eleven opcodes in two contiguous gaps printed as `v_vop1_NN` diff --git a/tests/rdna2_tools_check.py b/tests/rdna2_tools_check.py index 1b197796d..2aaaf9789 100644 --- a/tests/rdna2_tools_check.py +++ b/tests/rdna2_tools_check.py @@ -4309,6 +4309,54 @@ def test_decoded_scalar_control_forms_are_recognized(self): ) self.assertEqual(missing, []) + def test_permlane_cross_lane_census_preserves_lowering_refusal(self): + # gfx1013 VOP3 bytes use the same valid VGPR/SGPR operands in all three forms. + encodings = ( + ("000077d701050c00", "v_permlane16_b32", "VALU (Cross-lane)"), + ("000078d701050c00", "v_permlanex16_b32", "VALU (Cross-lane)"), + ("000044d701050c00", "v_perm_b32", "VALU (Vector ALU)"), + ) + results = [] + for wave_size in (32, 64): + for encoding, opcode, category in encodings: + with self.subTest(wave_size=wave_size, opcode=opcode): + instruction = disasm_rdna2(bytes.fromhex(encoding))[0]["assembly"] + self.assertEqual(instruction, f"{opcode} v0, v1, s2, s3") + shader = [ + "v_mov_b32_e32 v1, 1", + "s_mov_b32 s2, 0", + "s_mov_b32 s3, 0", + instruction, + "v_cvt_pkrtz_f16_f32_e32 v16, v0, v0", + "exp mrt0 v16, v16, v16, v16 done compr vm", + "s_endpgm", + ] + record = analyze_shader_instructions( + f"ps_{opcode}_wave{wave_size}", shader, wave_size=wave_size + ) + self.assertTrue(record["opcodes_recognized"]) + self.assertFalse(record["translator_accepted"]) + self.assertEqual(record["compatibility_category"], "opcode_recognized_translator_rejected") + self.assertEqual(record["lower_error_kind"], "translator_rejection") + self.assertEqual(record["lower_error"], f"Unsupported instruction 3: {instruction}") + self.assertEqual(record["unsupported_details"], [ + {"line_number": 4, "raw": instruction, "opcode": opcode, "category": category}, + ]) + results.append(record) + + with tempfile.TemporaryDirectory() as tmp: + json_file, _ = generate_progress_dashboard(results, Path(tmp)) + report = json.loads(json_file.read_text(encoding="utf-8")) + cross_lane = report["subsystems"]["VALU (Cross-lane)"] + self.assertEqual(cross_lane["total_instructions"], 4) + self.assertEqual(cross_lane["distinct_opcodes"], 2) + self.assertCountEqual(cross_lane["top_opcodes"], ["v_permlane16_b32", "v_permlanex16_b32"]) + missing = {row["opcode"]: row for row in report["missing_opcodes_ranked"]} + for _, opcode, category in encodings: + self.assertEqual(missing[opcode]["category"], category) + self.assertEqual(missing[opcode]["occurrences"], 2) + + def test_accepted_full_shader(self): """Canonical straight-line pixel shader accepted by pixel_aot translator.""" canonical_shader = [ diff --git a/tools/scan_unsupported_shaders.py b/tools/scan_unsupported_shaders.py index 6e32ee9f6..b81d26544 100644 --- a/tools/scan_unsupported_shaders.py +++ b/tools/scan_unsupported_shaders.py @@ -482,11 +482,15 @@ def lower_rejection_causes(results: list[dict]) -> dict: } ) +OPCODE_ENCODING_SUFFIX = re.compile(r"_(?:e32|e64|sdwa|dpp.*)$") +CROSS_LANE_VALU_OPCODES = {"v_permlane16_b32", "v_permlanex16_b32"} +CROSS_LANE_VALU_CATEGORY = "VALU (Cross-lane)" + def is_opcode_recognized(opcode: str) -> bool: """Check if opcode belongs to recognized AMD RDNA 2 ISA instructions.""" clean = opcode.strip().lower() - base = re.sub(r"_(?:e32|e64|sdwa|dpp.*)$", "", clean) + base = OPCODE_ENCODING_SUFFIX.sub("", clean) if base in KNOWN_RDNA2_BASE_OPCODES or clean in KNOWN_RDNA2_BASE_OPCODES: return True if base.startswith(("v_cmp_", "v_cmpx_")) or clean.startswith(("v_cmp_", "v_cmpx_")): @@ -501,6 +505,8 @@ def is_opcode_recognized(opcode: str) -> bool: def classify_isa_category(opcode: str) -> str: """Classify instruction into RDNA 2 ISA category according to the AMD manual.""" op = opcode.lower() + if OPCODE_ENCODING_SUFFIX.sub("", op.strip()) in CROSS_LANE_VALU_OPCODES: + return CROSS_LANE_VALU_CATEGORY if op.startswith("v_interp"): return "VINTRP (Parameter Interpolation)" if op.startswith("v_"): @@ -899,6 +905,8 @@ def make_progress_bar(percentage: float, width: int = 24, unicode_blocks: bool = def get_implementation_target(opcode: str, category: str) -> str: """Identify target file and subsystem in Xbox2Windows for an opcode.""" op = opcode.lower() + if category == CROSS_LANE_VALU_CATEGORY: + return "`tools/pixel_aot.py` (Wave lane layout, active lanes and bound control)" if "VALU" in category or "Vector ALU" in category: if any(x in op for x in ["_f32", "_f16", "_i32", "_u32"]): return "`tools/pixel_aot.py` (ALU dictionary / table)" From aa1b512cdb2330226e6d40f20c69d50fcac5d8e0 Mon Sep 17 00:00:00 2001 From: lukaslw-lab Date: Thu, 26 Nov 2026 00:42:28 +0100 Subject: [PATCH 014/240] d3d12: do not wrap large allocations for unplaced memory SRVs (#2611) An unplaced buffer memory SRV (device slot 70, #2395) wrapped the whole allocation holding the view with OpenExistingHeapFromAddress. A 6 KiB view in a ~2.15 GiB title startup block wrapped the block; afterwards each VirtualQuery over it took seconds and DirectStorage requests stalled for ~120 s. Wrap only allocations up to the existing 256 MiB span limit (size from one region-information call); larger ones take the upload copy. Co-authored-by: lukaslw-lab <291379150+lukaslw-lab@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- CMakeLists.txt | 2 +- src/startup_stubs/d3d12_memory_srv.inl | 5 +++-- src/startup_stubs/memory_srv_buffer.h | 13 ++++++++++++- src/startup_stubs/placed_buffer_range.h | 12 ++++++++++++ tests/startup_address_buffer_srv_check.py | 4 ++-- tests/startup_address_srv.cpp | 10 ++++++++++ tests/startup_memory_srv_buffer_check.cpp | 15 +++++++++++++-- tests/startup_placed_buffer_range_check.cpp | 19 +++++++++++++++++++ 8 files changed, 72 insertions(+), 8 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index ad93d3a12..6a8cf15c5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1982,7 +1982,7 @@ add_executable(startup_memory_srv_buffer_check tests/startup_memory_srv_buffer_c target_include_directories(startup_memory_srv_buffer_check PRIVATE src) target_compile_features(startup_memory_srv_buffer_check PRIVATE cxx_std_17) add_test(NAME startup_memory_srv_buffer COMMAND startup_memory_srv_buffer_check) -foreach(mutation IN ITEMS height exact-fit first-32 unplaced-extent unplaced-covers) +foreach(mutation IN ITEMS height exact-fit first-32 unplaced-extent unplaced-covers unplaced-heap-limit) add_test(NAME startup_memory_srv_buffer_${mutation}_control COMMAND startup_memory_srv_buffer_check --mutate ${mutation}) set_tests_properties(startup_memory_srv_buffer_${mutation}_control PROPERTIES WILL_FAIL TRUE) endforeach() diff --git a/src/startup_stubs/d3d12_memory_srv.inl b/src/startup_stubs/d3d12_memory_srv.inl index 673084c38..f57e607db 100644 --- a/src/startup_stubs/d3d12_memory_srv.inl +++ b/src/startup_stubs/d3d12_memory_srv.inl @@ -258,7 +258,8 @@ Wrapper* existing_memory_buffer(Wrapper* device, u64 address, u64 bytes) } // Backing for unplaced buffer memory SRVs: 64 KiB page-aligned placed resource on an existing heap -// (OpenExistingHeapFromAddress zero-copy aliasing on hardware) or committed UPLOAD buffer (fallback). +// (OpenExistingHeapFromAddress zero-copy aliasing on hardware, allocations up to 256 MiB) or committed UPLOAD +// buffer (fallback). struct UnplacedBufferEntry { Wrapper* device = nullptr; void* allocation_base = nullptr; @@ -350,7 +351,7 @@ Wrapper* unplaced_memory_buffer(Wrapper* device, u64 address, u64 span_bytes, co break; } } - if (!heap) { + if (!heap && x2w_startup::unplaced_existing_heap_allowed(x2w_startup::allocation_bytes(memory.base))) { ID3D12Device3* device3 = nullptr; if (SUCCEEDED(desktop->QueryInterface(IID_PPV_ARGS(&device3)))) { if (SUCCEEDED(device3->OpenExistingHeapFromAddress(memory.base, IID_PPV_ARGS(&heap)))) { diff --git a/src/startup_stubs/memory_srv_buffer.h b/src/startup_stubs/memory_srv_buffer.h index 4031efe12..b24be40d5 100644 --- a/src/startup_stubs/memory_srv_buffer.h +++ b/src/startup_stubs/memory_srv_buffer.h @@ -127,6 +127,17 @@ inline bool resolve_buffer_srv_desc(std::uint64_t buffer_title_base, std::uint64 return true; } +// Largest unplaced buffer span, and largest allocation an unplaced buffer may wrap as an existing heap. +constexpr std::uint64_t unplaced_max_span = 256ull << 20; + +// OpenExistingHeapFromAddress wraps the whole allocation holding the view, not just the view's pages. A few KiB +// view in a multi-GiB title block must not wrap the block (afterwards each VirtualQuery over the block took +// seconds), so allocations of unknown size (0) or above the span limit take the upload copy instead. +inline bool unplaced_existing_heap_allowed(std::uint64_t allocation_bytes) +{ + return allocation_bytes && allocation_bytes <= unplaced_max_span; +} + // Calculates 64 KiB page-aligned extent and byte span for unplaced buffer memory SRVs. // Returns false on zero address/bytes, arithmetic overflow, or when the span exceeds the maximum allowable limit (256 MiB). inline bool unplaced_buffer_extent(std::uint64_t address, std::uint64_t span_bytes, @@ -134,7 +145,7 @@ inline bool unplaced_buffer_extent(std::uint64_t address, std::uint64_t span_byt { constexpr std::uint64_t alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; constexpr std::uint64_t mask = alignment - 1; - constexpr std::uint64_t max_span = 256ull << 20; + constexpr std::uint64_t max_span = unplaced_max_span; if (!address || !span_bytes || span_bytes > ~std::uint64_t{0} - address) return false; page_start = address & ~mask; const std::uint64_t end = address + span_bytes; diff --git a/src/startup_stubs/placed_buffer_range.h b/src/startup_stubs/placed_buffer_range.h index 456cdfe6b..6e8bc3c4c 100644 --- a/src/startup_stubs/placed_buffer_range.h +++ b/src/startup_stubs/placed_buffer_range.h @@ -58,6 +58,18 @@ inline QueryRegion query_region() } } // namespace placed_detail +// Size of the whole allocation holding address, from one region-information call (no page-table scan); +// 0 when the call is missing or fails. +inline std::uint64_t allocation_bytes(const void* address) +{ + placed_detail::RegionInformation info{}; + SIZE_T returned = 0; + const placed_detail::QueryRegion query = placed_detail::query_region(); + if (!address || !query || !query(GetCurrentProcess(), address, 0 /* MemoryRegionInfo */, &info, sizeof(info), &returned)) + return 0; + return info.RegionSize; +} + // False when the address is not committed (slot 133 returns E_INVALIDARG). Otherwise covered is // exactly "offset <= committed bytes from base && width <= committed bytes - offset" for the run the // full walk measures. diff --git a/tests/startup_address_buffer_srv_check.py b/tests/startup_address_buffer_srv_check.py index 44c6304f0..c8ebc7c8f 100644 --- a/tests/startup_address_buffer_srv_check.py +++ b/tests/startup_address_buffer_srv_check.py @@ -50,13 +50,13 @@ def check(directory, consumer, backend): ) if actual is None: return 77 - values = (17, 63, 141, 141, 99, 17, 17, 17) + values = (17, 63, 141, 141, 99, 17, 17, 77) row = b"".join(bytes((v, 0, 0, 255)) for v in values) expected = row * 4 if actual != expected: raise AssertionError(f"actual {actual.hex()} expected {expected.hex()}") check_refusal_lines(trap_log.read_text(errors="replace")) - print(f"{backend}: buffer memory SRV (raw base, raw interior, unplaced buffer, structured, refused unaligned, refused acceleration structure view) exact") + print(f"{backend}: buffer memory SRV (raw base, raw interior, unplaced buffer, structured, refused unaligned, refused acceleration structure view, unplaced buffer in a large allocation copied) exact") return 0 diff --git a/tests/startup_address_srv.cpp b/tests/startup_address_srv.cpp index d2a72fc2d..1dab72a30 100644 --- a/tests/startup_address_srv.cpp +++ b/tests/startup_address_srv.cpp @@ -533,6 +533,16 @@ int draw_address_buffer_srvs(ID3D12Device* desktop, void* guest, void* list) invoke(guest, 70, ptr(&desc), ptr(&raw), cpu); draw(5); draw(6); + + // An unplaced buffer in an allocation above the 256 MiB limit is not wrapped as an existing heap; its + // upload copy must still publish the bytes at the address. + static auto* const large = static_cast( + VirtualAlloc(nullptr, (256ull << 20) + 65536, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + if (!large) return 53; + large[4] = 77; + raw.address = ptr(large); + raw.view.Buffer.FirstElement = 4; + invoke(guest, 70, ptr(&desc), ptr(&raw), cpu); draw(7); return 0; } diff --git a/tests/startup_memory_srv_buffer_check.cpp b/tests/startup_memory_srv_buffer_check.cpp index abc4c7005..cced3c949 100644 --- a/tests/startup_memory_srv_buffer_check.cpp +++ b/tests/startup_memory_srv_buffer_check.cpp @@ -5,6 +5,7 @@ // --mutate first-32: expect a resolved FirstElement above 4 Gi elements to be cut to 32 bits. // --mutate unplaced-extent: expect page span calculation crossing a 64 KiB boundary to return a single page. // --mutate unplaced-covers: expect a buffer range past the end of the cached page to be accepted as covered. +// --mutate unplaced-heap-limit: expect a 2 GiB allocation to be wrapped as an existing heap for an unplaced buffer. // Each mutated run is a negative control and must fail. #include "startup_stubs/memory_srv_buffer.h" @@ -84,10 +85,11 @@ int main(int argc, char** argv) if (argc == 3 && std::strcmp(argv[1], "--mutate") == 0 && (std::strcmp(argv[2], "height") == 0 || std::strcmp(argv[2], "exact-fit") == 0 || std::strcmp(argv[2], "first-32") == 0 || - std::strcmp(argv[2], "unplaced-extent") == 0 || std::strcmp(argv[2], "unplaced-covers") == 0)) { + std::strcmp(argv[2], "unplaced-extent") == 0 || std::strcmp(argv[2], "unplaced-covers") == 0 || + std::strcmp(argv[2], "unplaced-heap-limit") == 0)) { mutation = argv[2]; } else if (argc != 1) { - std::printf("usage: startup_memory_srv_buffer_check [--mutate height|exact-fit|first-32|unplaced-extent|unplaced-covers]\n"); + std::printf("usage: startup_memory_srv_buffer_check [--mutate height|exact-fit|first-32|unplaced-extent|unplaced-covers|unplaced-heap-limit]\n"); return 2; } const auto buf = buffer_desc(1024); @@ -301,6 +303,15 @@ int main(int argc, char** argv) check("unplaced covers zero cached span", !x2w_startup::unplaced_buffer_covers(0x10000, 0, 0x10000, 48)); check("unplaced covers zero requested span", !x2w_startup::unplaced_buffer_covers(0x10000, 65536, 0x10000, 0)); + // Existing-heap wrap of the allocation holding an unplaced buffer: up to the 256 MiB span limit only. + check("unplaced heap 64 KiB allocation", x2w_startup::unplaced_existing_heap_allowed(65536)); + check("unplaced heap 256 MiB allocation", x2w_startup::unplaced_existing_heap_allowed(256ull << 20)); + check("unplaced heap 256 MiB + 64 KiB allocation", + !x2w_startup::unplaced_existing_heap_allowed((256ull << 20) + 65536)); + check("unplaced heap 2 GiB allocation", + x2w_startup::unplaced_existing_heap_allowed(2ull << 30) == mutated("unplaced-heap-limit")); + check("unplaced heap unknown allocation size", !x2w_startup::unplaced_existing_heap_allowed(0)); + if (failures) return 1; std::printf("slot 70 buffer memory SRV validation: all checks passed\n"); return 0; diff --git a/tests/startup_placed_buffer_range_check.cpp b/tests/startup_placed_buffer_range_check.cpp index 2b395c945..b5806b6cf 100644 --- a/tests/startup_placed_buffer_range_check.cpp +++ b/tests/startup_placed_buffer_range_check.cpp @@ -27,6 +27,8 @@ // it. Decisions as above; in addition every placement must be proven without VirtualQuery (a call // count, not a time). The time per placement of the full walk, the bounded walk and the exact // proof is printed. +// 10. allocation_bytes (the unplaced slot 70 path's existing-heap limit): 64 KiB and 256 MiB + 64 KiB +// reservations with only their first page committed, asked at the base and at the last byte. // // --mutate region-only trusts the allocation size without checking that every page is committed: it // passes (exits 0) only if decisions differ in the partly committed cases and nowhere else. @@ -411,6 +413,23 @@ int main(int argc, char** argv) } } + // Case 10: allocation_bytes reports the whole allocation from any address in it, committed or not. + { + const SIZE_T sizes[] = {page, (SIZE_T{256} << 20) + page}; + for (const SIZE_T bytes : sizes) { + auto* block = static_cast(VirtualAlloc(nullptr, bytes, MEM_RESERVE, PAGE_NOACCESS)); + if (!block || !VirtualAlloc(block, page, MEM_COMMIT, PAGE_READWRITE)) { + setup_fail("cannot reserve the allocation-size block", block); + if (block) VirtualFree(block, 0, MEM_RELEASE); + continue; + } + if (x2w_startup::allocation_bytes(block) != bytes) fail("allocation_bytes at the base", block); + if (x2w_startup::allocation_bytes(block + bytes - 1) != bytes) fail("allocation_bytes at the last byte", block); + VirtualFree(block, 0, MEM_RELEASE); + } + if (x2w_startup::allocation_bytes(nullptr) != 0) fail("allocation_bytes of a null address", nullptr); + } + std::printf("all %llu placements: VirtualQuery calls full walk %llu, measured %llu\n", placements, full_queries, exact_queries); const int total = failures[other] + failures[partial] + failures[cost]; From bb1addf295f5c42b8ca5f4748ea4266fcc8ce72b Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Thu, 26 Nov 2026 01:43:35 +0200 Subject: [PATCH 015/240] cpu: lower VEX.128/256 AVX horizontal and addsub FP ops in cpu_avx_horiz_fp_aot (#2629) --- CMakeLists.txt | 29 ++ tests/cpu/avx_horiz_fp_aot.asm | 329 ++++++++++++++++++++++ tests/cpu/avx_horiz_fp_aot.def | 32 +++ tests/cpu/avx_horiz_fp_aot_check.py | 419 ++++++++++++++++++++++++++++ tools/cpu_avx_horiz_fp_aot.py | 403 ++++++++++++++++++++++++++ 5 files changed, 1212 insertions(+) create mode 100644 tests/cpu/avx_horiz_fp_aot.asm create mode 100644 tests/cpu/avx_horiz_fp_aot.def create mode 100644 tests/cpu/avx_horiz_fp_aot_check.py create mode 100644 tools/cpu_avx_horiz_fp_aot.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 6a8cf15c5..fb6084cec 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -6976,6 +6976,35 @@ if(EXISTS "${INTAKE_PYTHON}") check "$" "$") set_tests_properties(cpu_aot_avx_horiz_fp PROPERTIES SKIP_RETURN_CODE 77) + # cpu_aot_avx_horiz_fp_dedicated + set(cpu_avx_horiz_fp_aot_exports + "op_vhaddps_xmm_reg,op_vhaddpd_xmm_reg,op_vhsubps_xmm_reg,op_vhsubpd_xmm_reg," + "op_vaddsubps_xmm_reg,op_vaddsubpd_xmm_reg," + "op_vhaddps_xmm_mem,op_vhaddpd_xmm_mem,op_vhsubps_xmm_mem,op_vhsubpd_xmm_mem," + "op_vaddsubps_xmm_mem,op_vaddsubpd_xmm_mem," + "op_vhaddps_ymm_reg,op_vhaddpd_ymm_reg,op_vhsubps_ymm_reg,op_vhsubpd_ymm_reg," + "op_vaddsubps_ymm_reg,op_vaddsubpd_ymm_reg," + "op_vhaddps_ymm_mem,op_vhaddpd_ymm_mem,op_vhsubps_ymm_mem,op_vhsubpd_ymm_mem," + "op_vaddsubps_ymm_mem,op_vaddsubpd_ymm_mem," + "op_vhaddps_ymm_mem_rcx,op_vaddsubpd_ymm_mem_r8," + "op_vhaddps_ymm_alias_dst_src1,op_vhaddpd_ymm_alias_dst_src2," + "op_vhsubps_ymm_alias_src1_src2,op_vaddsubps_ymm_alias_all,op_vaddsubpd_xmm_alias_dst_src2") + string(CONCAT cpu_avx_horiz_fp_aot_exports ${cpu_avx_horiz_fp_aot_exports}) + foreach(variant IN ITEMS original altered) + cpu_asm_fixture(cpu_avx_horiz_fp_aot_${variant} avx_horiz_fp_aot) + cpu_translation(cpu_avx_horiz_fp_aot_${variant} cpu_avx_horiz_fp_aot "${cpu_avx_horiz_fp_aot_exports}") + endforeach() + target_compile_definitions(cpu_avx_horiz_fp_aot_altered PRIVATE ALTER_AVX_HORIZ_FP) + add_test(NAME cpu_aot_avx_horiz_fp_dedicated COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/cpu/avx_horiz_fp_aot_check.py" + "$" + "$" + "$" + "$") + set_tests_properties(cpu_aot_avx_horiz_fp_dedicated PROPERTIES + SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/cpu_aot_avx_horiz_fp_dedicated.txt") + cpu_asm_fixture(cpu_avx_addsub_fp avx_addsub_fp) set(avx_addsub_fp_fixture "${CMAKE_CURRENT_BINARY_DIR}/cpu_avx_addsub_fp_lifted.cpp") add_custom_command(OUTPUT "${avx_addsub_fp_fixture}" diff --git a/tests/cpu/avx_horiz_fp_aot.asm b/tests/cpu/avx_horiz_fp_aot.asm new file mode 100644 index 000000000..7678a4a82 --- /dev/null +++ b/tests/cpu/avx_horiz_fp_aot.asm @@ -0,0 +1,329 @@ +; coverage: record cpu_aot_avx_horiz_fp_dedicated +; Source-owned MASM fixture for VEX.128 and VEX.256 AVX horizontal and alternating +; floating-point add/sub ops (vhaddps, vhaddpd, vhsubps, vhsubpd, vaddsubps, vaddsubpd). +; ABI: void fn(const void* rcx, const void* rdx, void* r8). +.code + +op_vhaddps_xmm_reg PROC FRAME + .endprolog + vmovups ymm0, YMMWORD PTR [r8] + vmovups ymm1, YMMWORD PTR [rcx] + vmovups ymm2, YMMWORD PTR [rdx] + vhaddps xmm0, xmm1, xmm2 + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhaddps_xmm_reg ENDP + +op_vhaddpd_xmm_reg PROC FRAME + .endprolog + vmovupd ymm0, YMMWORD PTR [r8] + vmovupd ymm1, YMMWORD PTR [rcx] + vmovupd ymm2, YMMWORD PTR [rdx] +IFDEF ALTER_AVX_HORIZ_FP + vhaddpd ymm0, ymm1, ymm2 +ELSE + vhaddpd xmm0, xmm1, xmm2 +ENDIF + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhaddpd_xmm_reg ENDP + +op_vhsubps_xmm_reg PROC FRAME + .endprolog + vmovaps ymm0, YMMWORD PTR [r8] + vmovaps ymm1, YMMWORD PTR [rcx] + vmovaps ymm2, YMMWORD PTR [rdx] + vhsubps xmm0, xmm1, xmm2 + vmovaps YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhsubps_xmm_reg ENDP + +op_vhsubpd_xmm_reg PROC FRAME + .endprolog + vmovapd ymm0, YMMWORD PTR [r8] + vmovapd ymm1, YMMWORD PTR [rcx] + vmovapd ymm2, YMMWORD PTR [rdx] + vhsubpd xmm0, xmm1, xmm2 + vmovapd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhsubpd_xmm_reg ENDP + +op_vaddsubps_xmm_reg PROC FRAME + .endprolog + vmovups ymm0, YMMWORD PTR [r8] + vmovups ymm1, YMMWORD PTR [rcx] + vmovups ymm2, YMMWORD PTR [rdx] + vaddsubps xmm0, xmm1, xmm2 + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vaddsubps_xmm_reg ENDP + +op_vaddsubpd_xmm_reg PROC FRAME + .endprolog + vmovupd ymm0, YMMWORD PTR [r8] + vmovupd ymm1, YMMWORD PTR [rcx] + vmovupd ymm2, YMMWORD PTR [rdx] + vaddsubpd xmm0, xmm1, xmm2 + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vaddsubpd_xmm_reg ENDP + +op_vhaddps_xmm_mem PROC FRAME + .endprolog + vmovups ymm0, YMMWORD PTR [r8] + vmovups ymm1, YMMWORD PTR [rcx] + vhaddps xmm0, xmm1, XMMWORD PTR [rdx] + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhaddps_xmm_mem ENDP + +op_vhaddpd_xmm_mem PROC FRAME + .endprolog + vmovupd ymm0, YMMWORD PTR [r8] + vmovupd ymm1, YMMWORD PTR [rcx] + vhaddpd xmm0, xmm1, XMMWORD PTR [rdx] + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhaddpd_xmm_mem ENDP + +op_vhsubps_xmm_mem PROC FRAME + .endprolog + vmovups ymm0, YMMWORD PTR [r8] + vmovups ymm1, YMMWORD PTR [rcx] + vhsubps xmm0, xmm1, XMMWORD PTR [rdx] + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhsubps_xmm_mem ENDP + +op_vhsubpd_xmm_mem PROC FRAME + .endprolog + vmovupd ymm0, YMMWORD PTR [r8] + vmovupd ymm1, YMMWORD PTR [rcx] + vhsubpd xmm0, xmm1, XMMWORD PTR [rdx] + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhsubpd_xmm_mem ENDP + +op_vaddsubps_xmm_mem PROC FRAME + .endprolog + vmovups ymm0, YMMWORD PTR [r8] + vmovups ymm1, YMMWORD PTR [rcx] + vaddsubps xmm0, xmm1, XMMWORD PTR [rdx] + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vaddsubps_xmm_mem ENDP + +op_vaddsubpd_xmm_mem PROC FRAME + .endprolog + vmovupd ymm0, YMMWORD PTR [r8] + vmovupd ymm1, YMMWORD PTR [rcx] + vaddsubpd xmm0, xmm1, XMMWORD PTR [rdx] + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vaddsubpd_xmm_mem ENDP + +op_vhaddps_ymm_reg PROC FRAME + .endprolog + vmovaps ymm1, YMMWORD PTR [rcx] + vmovaps ymm2, YMMWORD PTR [rdx] +IFDEF ALTER_AVX_HORIZ_FP + vhsubps ymm0, ymm1, ymm2 +ELSE + vhaddps ymm0, ymm1, ymm2 +ENDIF + vmovaps YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhaddps_ymm_reg ENDP + +op_vhaddpd_ymm_reg PROC FRAME + .endprolog + vmovapd ymm1, YMMWORD PTR [rcx] + vmovapd ymm2, YMMWORD PTR [rdx] + vhaddpd ymm0, ymm1, ymm2 + vmovapd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhaddpd_ymm_reg ENDP + +op_vhsubps_ymm_reg PROC FRAME + .endprolog + vmovups ymm1, YMMWORD PTR [rcx] + vmovups ymm2, YMMWORD PTR [rdx] + vhsubps ymm0, ymm1, ymm2 + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhsubps_ymm_reg ENDP + +op_vhsubpd_ymm_reg PROC FRAME + .endprolog + vmovupd ymm1, YMMWORD PTR [rcx] + vmovupd ymm2, YMMWORD PTR [rdx] + vhsubpd ymm0, ymm1, ymm2 + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhsubpd_ymm_reg ENDP + +op_vaddsubps_ymm_reg PROC FRAME + .endprolog + vmovups ymm1, YMMWORD PTR [rcx] + vmovups ymm2, YMMWORD PTR [rdx] +IFDEF ALTER_AVX_HORIZ_FP + vhaddps ymm0, ymm1, ymm2 +ELSE + vaddsubps ymm0, ymm1, ymm2 +ENDIF + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vaddsubps_ymm_reg ENDP + +op_vaddsubpd_ymm_reg PROC FRAME + .endprolog + vmovupd ymm1, YMMWORD PTR [rcx] + vmovupd ymm2, YMMWORD PTR [rdx] + vaddsubpd ymm0, ymm1, ymm2 + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vaddsubpd_ymm_reg ENDP + +op_vhaddps_ymm_mem PROC FRAME + .endprolog + vmovups ymm1, YMMWORD PTR [rcx] + vhaddps ymm0, ymm1, YMMWORD PTR [rdx] + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhaddps_ymm_mem ENDP + +op_vhaddpd_ymm_mem PROC FRAME + .endprolog + vmovupd ymm1, YMMWORD PTR [rcx] + vhaddpd ymm0, ymm1, YMMWORD PTR [rdx] + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhaddpd_ymm_mem ENDP + +op_vhsubps_ymm_mem PROC FRAME + .endprolog + vmovups ymm1, YMMWORD PTR [rcx] + vhsubps ymm0, ymm1, YMMWORD PTR [rdx] + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhsubps_ymm_mem ENDP + +op_vhsubpd_ymm_mem PROC FRAME + .endprolog + vmovupd ymm1, YMMWORD PTR [rcx] + vhsubpd ymm0, ymm1, YMMWORD PTR [rdx] + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhsubpd_ymm_mem ENDP + +op_vaddsubps_ymm_mem PROC FRAME + .endprolog + vmovups ymm1, YMMWORD PTR [rcx] + vaddsubps ymm0, ymm1, YMMWORD PTR [rdx] + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vaddsubps_ymm_mem ENDP + +op_vaddsubpd_ymm_mem PROC FRAME + .endprolog + vmovupd ymm1, YMMWORD PTR [rcx] +IFDEF ALTER_AVX_HORIZ_FP + vhsubpd ymm0, ymm1, YMMWORD PTR [rdx] +ELSE + vaddsubpd ymm0, ymm1, YMMWORD PTR [rdx] +ENDIF + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vaddsubpd_ymm_mem ENDP + +op_vhaddps_ymm_mem_rcx PROC FRAME + .endprolog + vmovups ymm1, YMMWORD PTR [rdx] + vhaddps ymm0, ymm1, YMMWORD PTR [rcx] + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhaddps_ymm_mem_rcx ENDP + +op_vaddsubpd_ymm_mem_r8 PROC FRAME + .endprolog + vmovupd ymm1, YMMWORD PTR [rcx] + vaddsubpd ymm0, ymm1, YMMWORD PTR [r8] + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vaddsubpd_ymm_mem_r8 ENDP + +op_vhaddps_ymm_alias_dst_src1 PROC FRAME + .endprolog + vmovups ymm0, YMMWORD PTR [rcx] + vmovups ymm1, YMMWORD PTR [rdx] + vhaddps ymm0, ymm0, ymm1 + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhaddps_ymm_alias_dst_src1 ENDP + +op_vhaddpd_ymm_alias_dst_src2 PROC FRAME + .endprolog + vmovupd ymm1, YMMWORD PTR [rcx] + vmovupd ymm0, YMMWORD PTR [rdx] + vhaddpd ymm0, ymm1, ymm0 + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhaddpd_ymm_alias_dst_src2 ENDP + +op_vhsubps_ymm_alias_src1_src2 PROC FRAME + .endprolog + vmovups ymm1, YMMWORD PTR [rcx] + vhsubps ymm0, ymm1, ymm1 + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhsubps_ymm_alias_src1_src2 ENDP + +op_vaddsubps_ymm_alias_all PROC FRAME + .endprolog + vmovups ymm0, YMMWORD PTR [rcx] + vaddsubps ymm0, ymm0, ymm0 + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vaddsubps_ymm_alias_all ENDP + +op_vaddsubpd_xmm_alias_dst_src2 PROC FRAME + .endprolog + vmovupd ymm1, YMMWORD PTR [rcx] + vmovupd ymm0, YMMWORD PTR [rdx] + vaddsubpd xmm0, xmm1, xmm0 + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vaddsubpd_xmm_alias_dst_src2 ENDP + +END diff --git a/tests/cpu/avx_horiz_fp_aot.def b/tests/cpu/avx_horiz_fp_aot.def new file mode 100644 index 000000000..b0a2748a6 --- /dev/null +++ b/tests/cpu/avx_horiz_fp_aot.def @@ -0,0 +1,32 @@ +EXPORTS + op_vhaddps_xmm_reg + op_vhaddpd_xmm_reg + op_vhsubps_xmm_reg + op_vhsubpd_xmm_reg + op_vaddsubps_xmm_reg + op_vaddsubpd_xmm_reg + op_vhaddps_xmm_mem + op_vhaddpd_xmm_mem + op_vhsubps_xmm_mem + op_vhsubpd_xmm_mem + op_vaddsubps_xmm_mem + op_vaddsubpd_xmm_mem + op_vhaddps_ymm_reg + op_vhaddpd_ymm_reg + op_vhsubps_ymm_reg + op_vhsubpd_ymm_reg + op_vaddsubps_ymm_reg + op_vaddsubpd_ymm_reg + op_vhaddps_ymm_mem + op_vhaddpd_ymm_mem + op_vhsubps_ymm_mem + op_vhsubpd_ymm_mem + op_vaddsubps_ymm_mem + op_vaddsubpd_ymm_mem + op_vhaddps_ymm_mem_rcx + op_vaddsubpd_ymm_mem_r8 + op_vhaddps_ymm_alias_dst_src1 + op_vhaddpd_ymm_alias_dst_src2 + op_vhsubps_ymm_alias_src1_src2 + op_vaddsubps_ymm_alias_all + op_vaddsubpd_xmm_alias_dst_src2 diff --git a/tests/cpu/avx_horiz_fp_aot_check.py b/tests/cpu/avx_horiz_fp_aot_check.py new file mode 100644 index 000000000..bbfa86d5d --- /dev/null +++ b/tests/cpu/avx_horiz_fp_aot_check.py @@ -0,0 +1,419 @@ +"""Differential, boundary, mutation, refusal, and coverage-record checks for dedicated AVX horizontal/addsub FP AOT.""" + +import ctypes +import os +from pathlib import Path +import struct +import sys +from tempfile import TemporaryDirectory + +from iced_x86 import ( + Code, + Decoder, + Encoder, + Formatter, + FormatterSyntax, + Instruction, + MemoryOperand, + Register as R, +) +import pefile + +THIS_DIR = Path(__file__).resolve().parent +TOOLS_DIR = THIS_DIR.parents[1] / "tools" +sys.path.insert(0, str(THIS_DIR)) +sys.path.insert(0, str(TOOLS_DIR)) + +from avx_horiz_fp import F32, F64, _guarded_buf # noqa: E402 +from cpu_avx_horiz_fp_aot import lift_code, main as tool_main, translate # noqa: E402 +from cpu_leaf_aot import bounded_code, export_rva # noqa: E402 + + +EXPORTS = ( + "op_vhaddps_xmm_reg", + "op_vhaddpd_xmm_reg", + "op_vhsubps_xmm_reg", + "op_vhsubpd_xmm_reg", + "op_vaddsubps_xmm_reg", + "op_vaddsubpd_xmm_reg", + "op_vhaddps_xmm_mem", + "op_vhaddpd_xmm_mem", + "op_vhsubps_xmm_mem", + "op_vhsubpd_xmm_mem", + "op_vaddsubps_xmm_mem", + "op_vaddsubpd_xmm_mem", + "op_vhaddps_ymm_reg", + "op_vhaddpd_ymm_reg", + "op_vhsubps_ymm_reg", + "op_vhsubpd_ymm_reg", + "op_vaddsubps_ymm_reg", + "op_vaddsubpd_ymm_reg", + "op_vhaddps_ymm_mem", + "op_vhaddpd_ymm_mem", + "op_vhsubps_ymm_mem", + "op_vhsubpd_ymm_mem", + "op_vaddsubps_ymm_mem", + "op_vaddsubpd_ymm_mem", + "op_vhaddps_ymm_mem_rcx", + "op_vaddsubpd_ymm_mem_r8", + "op_vhaddps_ymm_alias_dst_src1", + "op_vhaddpd_ymm_alias_dst_src2", + "op_vhsubps_ymm_alias_src1_src2", + "op_vaddsubps_ymm_alias_all", + "op_vaddsubpd_xmm_alias_dst_src2", +) + +ALTERED_CASES = ( + ("op_vhaddps_ymm_reg", "op_vhsubps_ymm_reg"), + ("op_vaddsubps_ymm_reg", "op_vhaddps_ymm_reg"), + ("op_vaddsubpd_ymm_mem", "op_vhsubpd_ymm_mem"), +) + + +def encode_seq(*instructions): + encoder = Encoder(64) + rip = 0x1000 + for ins in instructions: + rip += encoder.encode(ins, rip) + return encoder.take_buffer() + + +def _lane_ps(kind: str, lane_a: bytes, lane_b: bytes, mxcsr: int) -> bytes: + xa = struct.unpack("<4I", lane_a) + xb = struct.unpack("<4I", lane_b) + if kind == "vhadd": + vals = ( + F32.add(xa[0], xa[1], mxcsr), + F32.add(xa[2], xa[3], mxcsr), + F32.add(xb[0], xb[1], mxcsr), + F32.add(xb[2], xb[3], mxcsr), + ) + elif kind == "vhsub": + vals = ( + F32.sub(xa[0], xa[1], mxcsr), + F32.sub(xa[2], xa[3], mxcsr), + F32.sub(xb[0], xb[1], mxcsr), + F32.sub(xb[2], xb[3], mxcsr), + ) + elif kind == "vaddsub": + vals = ( + F32.sub(xa[0], xb[0], mxcsr), + F32.add(xa[1], xb[1], mxcsr), + F32.sub(xa[2], xb[2], mxcsr), + F32.add(xa[3], xb[3], mxcsr), + ) + else: + raise ValueError(kind) + return struct.pack("<4I", *vals) + + +def _lane_pd(kind: str, lane_a: bytes, lane_b: bytes, mxcsr: int) -> bytes: + xa = struct.unpack("<2Q", lane_a) + xb = struct.unpack("<2Q", lane_b) + if kind == "vhadd": + vals = (F64.add(xa[0], xa[1], mxcsr), F64.add(xb[0], xb[1], mxcsr)) + elif kind == "vhsub": + vals = (F64.sub(xa[0], xa[1], mxcsr), F64.sub(xb[0], xb[1], mxcsr)) + elif kind == "vaddsub": + vals = (F64.sub(xa[0], xb[0], mxcsr), F64.add(xa[1], xb[1], mxcsr)) + else: + raise ValueError(kind) + return struct.pack("<2Q", *vals) + + +def ref_op(name: str, a: bytes, b: bytes, mxcsr: int) -> bytes: + if name == "op_vhaddps_ymm_mem_rcx": + a, b = b, a + elif name in ("op_vhsubps_ymm_alias_src1_src2", "op_vaddsubps_ymm_alias_all"): + b = a + is_xmm = "_xmm_" in name + is_pd = "pd_" in name + if "vhadd" in name: + kind = "vhadd" + elif "vhsub" in name: + kind = "vhsub" + elif "vaddsub" in name: + kind = "vaddsub" + else: + raise KeyError(name) + lane_fn = _lane_pd if is_pd else _lane_ps + lo = lane_fn(kind, a[0:16], b[0:16], mxcsr) + if is_xmm: + return lo + b"\x00" * 16 + return lo + lane_fn(kind, a[16:32], b[16:32], mxcsr) + + +def check_translator(original_path: Path): + source_cpp, meta = translate(original_path, EXPORTS) + assert len(meta) == len(EXPORTS) and "host_has_avx" in source_cpp, meta + + ld_ymm0 = Instruction.create_reg_mem(Code.VEX_VMOVUPS_YMM_YMMM256, R.YMM0, MemoryOperand(R.RCX)) + ld_ymm1 = Instruction.create_reg_mem(Code.VEX_VMOVAPS_YMM_YMMM256, R.YMM1, MemoryOperand(R.RCX)) + ld_ymm2 = Instruction.create_reg_mem(Code.VEX_VMOVUPD_YMM_YMMM256, R.YMM2, MemoryOperand(R.RDX)) + ld_xmm1 = Instruction.create_reg_mem(Code.VEX_VMOVAPD_XMM_XMMM128, R.XMM1, MemoryOperand(R.RCX)) + ld_xmm2 = Instruction.create_reg_mem(Code.VEX_VMOVUPS_XMM_XMMM128, R.XMM2, MemoryOperand(R.RDX)) + ret_ins = Instruction.create(Code.RETNQ) + vzero = Instruction.create(Code.VEX_VZEROUPPER) + + # All 12 horizontal/addsub codes (6 mnemonics x XMM/YMM) in reg & flat [rcx|rdx|r8] mem-src forms. + accepted = 0 + for code, is_ymm, helper in ( + (Code.VEX_VHADDPS_XMM_XMM_XMMM128, False, "op_vhaddps"), + (Code.VEX_VHADDPS_YMM_YMM_YMMM256, True, "op_vhaddps"), + (Code.VEX_VHADDPD_XMM_XMM_XMMM128, False, "op_vhaddpd"), + (Code.VEX_VHADDPD_YMM_YMM_YMMM256, True, "op_vhaddpd"), + (Code.VEX_VHSUBPS_XMM_XMM_XMMM128, False, "op_vhsubps"), + (Code.VEX_VHSUBPS_YMM_YMM_YMMM256, True, "op_vhsubps"), + (Code.VEX_VHSUBPD_XMM_XMM_XMMM128, False, "op_vhsubpd"), + (Code.VEX_VHSUBPD_YMM_YMM_YMMM256, True, "op_vhsubpd"), + (Code.VEX_VADDSUBPS_XMM_XMM_XMMM128, False, "op_vaddsubps"), + (Code.VEX_VADDSUBPS_YMM_YMM_YMMM256, True, "op_vaddsubps"), + (Code.VEX_VADDSUBPD_XMM_XMM_XMMM128, False, "op_vaddsubpd"), + (Code.VEX_VADDSUBPD_YMM_YMM_YMMM256, True, "op_vaddsubpd"), + ): + dst, s1, s2 = (R.YMM0, R.YMM1, R.YMM2) if is_ymm else (R.XMM0, R.XMM1, R.XMM2) + loads = (ld_ymm1, ld_ymm2) if is_ymm else (ld_xmm1, ld_xmm2) + st_code = Code.VEX_VMOVUPS_YMMM256_YMM if is_ymm else Code.VEX_VMOVUPS_XMMM128_XMM + reg_src, _ = lift_code( + f"{helper}_reg", + 0x1000, + encode_seq( + *loads, + Instruction.create_reg_reg_reg(code, dst, s1, s2), + Instruction.create_mem_reg(st_code, MemoryOperand(R.R8), dst), + vzero, + ret_ins, + ), + ) + assert f"{helper}(ymm1, ymm2, {'true' if is_ymm else 'false'})" in reg_src, reg_src + accepted += 1 + + for base in (R.RCX, R.RDX, R.R8): + mem_src, _ = lift_code( + f"{helper}_mem_{base}", + 0x1000, + encode_seq( + loads[0], + Instruction.create_reg_reg_mem(code, dst, s1, MemoryOperand(base)), + Instruction.create_mem_reg(st_code, MemoryOperand(R.R8), dst), + ret_ins, + ), + ) + loader = "load256" if is_ymm else "load128" + assert f"{helper}(ymm1, {loader}(" in mem_src, mem_src + accepted += 1 + + evex_ins = Instruction.create_reg_reg_reg(Code.EVEX_VADDPS_YMM_K1Z_YMM_YMMM256B32, R.YMM0, R.YMM1, R.YMM2) + evex_ins.op_mask = R.K1 + seg_mem = MemoryOperand(R.RDX) + seg_prefix_ins = Instruction.create_reg_reg_mem(Code.VEX_VHADDPS_YMM_YMM_YMMM256, R.YMM0, R.YMM1, seg_mem) + seg_prefix_ins.segment_prefix = R.FS + + rejects = [ + ("evex", (ld_ymm1, ld_ymm2, evex_ins, ret_ins), "unsupported EVEX instruction"), + ("legacy_sse", (ld_xmm1, ld_xmm2, Instruction.create_reg_mem(Code.HADDPS_XMM_XMMM128, R.XMM0, MemoryOperand(R.RDX)), ret_ins), "unsupported instruction"), + ("nonvol_ymm6_dst", (ld_ymm1, ld_ymm2, Instruction.create_reg_reg_reg(Code.VEX_VHADDPS_YMM_YMM_YMMM256, R.YMM6, R.YMM1, R.YMM2), ret_ins), "nonvolatile vector register"), + ("nonvol_xmm15_src", (ld_xmm1, Instruction.create_reg_reg_reg(Code.VEX_VHSUBPD_XMM_XMM_XMMM128, R.XMM0, R.XMM1, R.XMM15), ret_ins), "nonvolatile vector register"), + ("nonvol_ymm7_move", (Instruction.create_reg_mem(Code.VEX_VMOVAPS_YMM_YMMM256, R.YMM7, MemoryOperand(R.RCX)), ret_ins), "nonvolatile vector register"), + ("undef_ymm3", (ld_ymm1, Instruction.create_reg_reg_reg(Code.VEX_VHADDPD_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM3), ret_ins), "undefined vector register ymm3"), + ("undef_alias_dst", (ld_ymm1, Instruction.create_reg_reg_reg(Code.VEX_VHADDPS_YMM_YMM_YMMM256, R.YMM0, R.YMM0, R.YMM1), ret_ins), "undefined vector register ymm0"), + ("disp_mem_rcx", (ld_ymm1, Instruction.create_reg_reg_mem(Code.VEX_VHADDPS_YMM_YMM_YMMM256, R.YMM0, R.YMM1, MemoryOperand(R.RCX, displ=32, displ_size=1)), ret_ins), "unsupported memory operand"), + ("disp_mem_rdx", (ld_xmm1, Instruction.create_reg_reg_mem(Code.VEX_VADDSUBPS_XMM_XMM_XMMM128, R.XMM0, R.XMM1, MemoryOperand(R.RDX, displ=16, displ_size=1)), ret_ins), "unsupported memory operand"), + ("disp_store_r8", (ld_ymm0, Instruction.create_mem_reg(Code.VEX_VMOVUPS_YMMM256_YMM, MemoryOperand(R.R8, displ=32, displ_size=1), R.YMM0), ret_ins), "unsupported memory operand"), + ("non_r8_store_rcx", (ld_ymm0, Instruction.create_mem_reg(Code.VEX_VMOVUPS_YMMM256_YMM, MemoryOperand(R.RCX), R.YMM0), ret_ins), "unsupported memory operand"), + ("non_r8_store_rdx", (ld_xmm1, Instruction.create_mem_reg(Code.VEX_VMOVAPD_XMMM128_XMM, MemoryOperand(R.RDX), R.XMM1), ret_ins), "unsupported memory operand"), + ("indexed_mem", (ld_ymm1, Instruction.create_reg_reg_mem(Code.VEX_VHSUBPS_YMM_YMM_YMMM256, R.YMM0, R.YMM1, MemoryOperand(R.RDX, R.RCX, 1)), ret_ins), "unsupported memory operand"), + ("rip_rel_mem", (ld_ymm1, Instruction.create_reg_reg_mem(Code.VEX_VADDSUBPD_YMM_YMM_YMMM256, R.YMM0, R.YMM1, MemoryOperand(R.RIP, displ=0x1040, displ_size=4)), ret_ins), "unsupported memory operand"), + ("non_arg_base_rax", (ld_ymm1, Instruction.create_reg_reg_mem(Code.VEX_VHADDPS_YMM_YMM_YMMM256, R.YMM0, R.YMM1, MemoryOperand(R.RAX)), ret_ins), "unsupported memory operand"), + ("addr32_ecx", (ld_xmm1, Instruction.create_reg_reg_mem(Code.VEX_VHADDPS_XMM_XMM_XMMM128, R.XMM0, R.XMM1, MemoryOperand(R.ECX)), ret_ins), "unsupported memory operand"), + ("seg_prefix", (ld_ymm1, seg_prefix_ins, ret_ins), "unsupported instruction prefix"), + ("missing_ret", (ld_ymm1, ld_ymm2, Instruction.create_reg_reg_reg(Code.VEX_VHADDPS_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2)), "missing terminal ret"), + ("after_ret", (ld_ymm1, ret_ins, ld_ymm2), "unreachable instruction after ret"), + ] + for label, seq, reason in rejects: + try: + lift_code(label, 0x1000, encode_seq(*seq)) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: translator accepted invalid sequence") + + # Verify CLI failure exit code 1 without traceback and zero temp files. + with TemporaryDirectory() as tmp: + root = Path(tmp) + out_cpp = root / "out.cpp" + try: + tool_main([str(root / "missing.dll"), "op_vhaddps_ymm_reg", str(out_cpp)]) + except SystemExit as exc: + assert exc.code == 1, exc.code + else: + raise AssertionError("missing DLL did not exit") + assert not out_cpp.exists() and list(root.iterdir()) == [] + + print(f"translator validated: {accepted} forms accepted, {len(rejects)} refusal controls passed") + + +def host_has_avx(lifted_lib) -> bool: + if hasattr(lifted_lib, "host_has_avx"): + lifted_lib.host_has_avx.argtypes = [] + lifted_lib.host_has_avx.restype = ctypes.c_uint32 + return bool(lifted_lib.host_has_avx()) + return False + + +def check_differential(native_path: Path, lifted_path: Path, altered_path: Path, altered_lifted_path: Path) -> None: + native = ctypes.CDLL(str(native_path.resolve())) + lifted = ctypes.CDLL(str(lifted_path.resolve())) + altered_native = ctypes.CDLL(str(altered_path.resolve())) + altered_lifted = ctypes.CDLL(str(altered_lifted_path.resolve())) + + exchange = lifted.host_exchange_mxcsr + exchange.argtypes, exchange.restype = [ctypes.c_uint32], ctypes.c_uint32 + + def _f32(*vals): + words = [v if isinstance(v, int) else struct.unpack(" bytes: + _ra, pa = _guarded_buf(a_bytes, align if name == "op_vhaddps_ymm_mem_rcx" else 0) + _rb, pb = _guarded_buf(b_bytes, 0 if name in ("op_vhaddps_ymm_mem_rcx", "op_vaddsubpd_ymm_mem_r8") else align) + seed = b_bytes if name == "op_vaddsubpd_ymm_mem_r8" else b"\xCC" * 32 + _rc, pc = _guarded_buf(seed, align if name == "op_vaddsubpd_ymm_mem_r8" else 0) + fn = getattr(dll, prefix + name) + fn.argtypes = [ctypes.c_uint64, ctypes.c_uint64, ctypes.c_uint64] + fn.restype = None + previous = exchange(mxcsr) + try: + fn(pa, pb, pc) + finally: + exchange(previous) + return ctypes.string_at(pc, 32) + + for name in EXPORTS: + pairs = f64_pairs if "pd_" in name else f32_pairs + for mxcsr in mxcsr_modes: + for a_bytes, b_bytes in pairs: + want = ref_op(name, a_bytes, b_bytes, mxcsr) + got_n = invoke(native, "", name, a_bytes, b_bytes, mxcsr, 0) + got_l = invoke(lifted, "lifted_", name, a_bytes, b_bytes, mxcsr, 0) + if got_n != want or got_l != want: + raise AssertionError( + f"{name} mxcsr={mxcsr:#x}: want={want.hex()} native={got_n.hex()} lifted={got_l.hex()}" + ) + cases += 1 + if "_mem" in name: + a_bytes, b_bytes = pairs[0] + for off in (1, 3, 7): + want = ref_op(name, a_bytes, b_bytes, 0x1F80) + got_n = invoke(native, "", name, a_bytes, b_bytes, 0x1F80, off) + got_l = invoke(lifted, "lifted_", name, a_bytes, b_bytes, 0x1F80, off) + if got_n != want or got_l != want: + raise AssertionError( + f"{name} align={off}: want={want.hex()} native={got_n.hex()} lifted={got_l.hex()}" + ) + cases += 1 + + # Altered controls must diverge from original and match altered native DLL. + for name, alt_ref_name in ALTERED_CASES: + pairs = f64_pairs if "pd_" in name else f32_pairs + a_bytes, b_bytes = pairs[0] + want_orig = ref_op(name, a_bytes, b_bytes, 0x1F80) + want_alt = ref_op(alt_ref_name, a_bytes, b_bytes, 0x1F80) + got_alt_n = invoke(altered_native, "", name, a_bytes, b_bytes, 0x1F80, 0) + got_alt_l = invoke(altered_lifted, "lifted_", name, a_bytes, b_bytes, 0x1F80, 0) + assert got_alt_n == want_alt and got_alt_l == want_alt, (name, got_alt_n.hex(), got_alt_l.hex(), want_alt.hex()) + assert got_alt_l != want_orig, f"altered {name} failed to diverge from original" + + # Altered XMM zeroing control: vhaddpd ymm0 instead of xmm0 leaves bits [255:128] non-zero. + a64, b64 = f64_pairs[0] + want_xmm_orig = ref_op("op_vhaddpd_xmm_reg", a64, b64, 0x1F80) + got_xmm_alt_n = invoke(altered_native, "", "op_vhaddpd_xmm_reg", a64, b64, 0x1F80, 0) + got_xmm_alt_l = invoke(altered_lifted, "lifted_", "op_vhaddpd_xmm_reg", a64, b64, 0x1F80, 0) + assert got_xmm_alt_n == got_xmm_alt_l, (got_xmm_alt_n.hex(), got_xmm_alt_l.hex()) + assert got_xmm_alt_l[:16] == want_xmm_orig[:16] and got_xmm_alt_l[16:] != b"\x00" * 16, got_xmm_alt_l.hex() + + print( + f"{cases} AVX horizontal/addsub FP cases across {len(EXPORTS)} exports and {len(mxcsr_modes)} MXCSR modes " + f"matched native DLL and IEEE-754 reference; {len(ALTERED_CASES) + 1} altered controls diverged" + ) + + +def record_covered_forms(original_path: Path) -> None: + record = os.environ.get("FORM_COVERAGE_RECORD") + if not record: + return + formatter = Formatter(FormatterSyntax.INTEL) + forms = set() + with pefile.PE(str(original_path), fast_load=True) as pe: + for name in EXPORTS: + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + for ins in Decoder(64, raw, ip=entry): + forms.add(formatter.format_mnemonic(ins).lower()) + out_path = Path(record) + out_path.parent.mkdir(parents=True, exist_ok=True) + out_path.write_text("".join(word + "\n" for word in sorted(forms)), encoding="utf-8") + + +def main() -> None: + if os.environ.get("FORM_COVERAGE_RECORD"): + Path(os.environ["FORM_COVERAGE_RECORD"]).unlink(missing_ok=True) + + original_path, lifted_path, altered_path, altered_lifted_path = (Path(p) for p in sys.argv[1:5]) + check_translator(original_path) + + lifted_lib = ctypes.CDLL(str(lifted_path.resolve())) + if not host_has_avx(lifted_lib): + print("Host lacks CPUID.01H:ECX[27:28] + XGETBV[2:1]; skipping native differential check") + sys.exit(77) + + check_differential(original_path, lifted_path, altered_path, altered_lifted_path) + record_covered_forms(original_path) + + +if __name__ == "__main__": + main() diff --git a/tools/cpu_avx_horiz_fp_aot.py b/tools/cpu_avx_horiz_fp_aot.py new file mode 100644 index 000000000..e84bfbbcc --- /dev/null +++ b/tools/cpu_avx_horiz_fp_aot.py @@ -0,0 +1,403 @@ +"""Lift bounded Windows x64 leaf functions with AVX horizontal and add/sub FP ops to C++. + +Each export uses the straight-line leaf ABI: + void lifted_(word rcx, word rdx, word r8) +where rcx, rdx, and r8 carry flat host pointers to caller-owned buffers. YMM0..YMM5 +are modeled as portable 256-bit value structs (four 64-bit lanes); every VEX.128 +write to an XMM destination zeroes bits [255:128] of the corresponding YMM register. + +Supported AVX horizontal / alternating FP forms (docs/coverage/x64_zen2.tsv group AVX): + - VHADDPS, VHADDPD, VHSUBPS, VHSUBPD, VADDSUBPS, VADDSUBPD + in VEX.128 (xmm, xmm, xmm/m128) and VEX.256 (ymm, ymm, ymm/m256) forms. + +Transport / ABI glue: + - VMOVAPS, VMOVAPD, VMOVUPS, VMOVUPD (reg-reg, flat [rcx|rdx|r8] loads, flat [r8] stores) + - VZEROUPPER and terminal RET. + +EVEX encodings, legacy SSE forms, nonvolatile vector registers (XMM6..15/YMM6..15), +undefined vector reads, displaced or non-flat memory operands, non-[r8] stores, +instruction prefixes, branches, and trailing or missing ret are rejected. +""" + +import argparse +from pathlib import Path +import tempfile + +import pefile +from iced_x86 import ( + Code, + Decoder, + EncodingKind, + MemorySizeExt, + OpKind, + Register as R, + RegisterExt, +) + +from cpu_leaf_aot import bounded_code, export_rva + + +ARGUMENTS = {R.RCX: "rcx", R.RDX: "rdx", R.R8: "r8"} +VOLATILE_XMM = {getattr(R, f"XMM{i}"): i for i in range(6)} +VOLATILE_YMM = {getattr(R, f"YMM{i}"): i for i in range(6)} +NONVOLATILE_VEC = ( + {getattr(R, f"XMM{i}") for i in range(6, 32)} + | {getattr(R, f"YMM{i}") for i in range(6, 32)} + | {getattr(R, f"ZMM{i}") for i in range(32)} +) + +# (helper_name, is_ymm) +HORIZ_FP_CODES = { + Code.VEX_VHADDPS_XMM_XMM_XMMM128: ("op_vhaddps", False), + Code.VEX_VHADDPS_YMM_YMM_YMMM256: ("op_vhaddps", True), + Code.VEX_VHADDPD_XMM_XMM_XMMM128: ("op_vhaddpd", False), + Code.VEX_VHADDPD_YMM_YMM_YMMM256: ("op_vhaddpd", True), + Code.VEX_VHSUBPS_XMM_XMM_XMMM128: ("op_vhsubps", False), + Code.VEX_VHSUBPS_YMM_YMM_YMMM256: ("op_vhsubps", True), + Code.VEX_VHSUBPD_XMM_XMM_XMMM128: ("op_vhsubpd", False), + Code.VEX_VHSUBPD_YMM_YMM_YMMM256: ("op_vhsubpd", True), + Code.VEX_VADDSUBPS_XMM_XMM_XMMM128: ("op_vaddsubps", False), + Code.VEX_VADDSUBPS_YMM_YMM_YMMM256: ("op_vaddsubps", True), + Code.VEX_VADDSUBPD_XMM_XMM_XMMM128: ("op_vaddsubpd", False), + Code.VEX_VADDSUBPD_YMM_YMM_YMMM256: ("op_vaddsubpd", True), +} + +# is_ymm for full-width VEX FP moves +VEC_MOVE_CODES = { + Code.VEX_VMOVAPS_XMM_XMMM128: False, + Code.VEX_VMOVAPS_XMMM128_XMM: False, + Code.VEX_VMOVAPS_YMM_YMMM256: True, + Code.VEX_VMOVAPS_YMMM256_YMM: True, + Code.VEX_VMOVAPD_XMM_XMMM128: False, + Code.VEX_VMOVAPD_XMMM128_XMM: False, + Code.VEX_VMOVAPD_YMM_YMMM256: True, + Code.VEX_VMOVAPD_YMMM256_YMM: True, + Code.VEX_VMOVUPS_XMM_XMMM128: False, + Code.VEX_VMOVUPS_XMMM128_XMM: False, + Code.VEX_VMOVUPS_YMM_YMMM256: True, + Code.VEX_VMOVUPS_YMMM256_YMM: True, + Code.VEX_VMOVUPD_XMM_XMMM128: False, + Code.VEX_VMOVUPD_XMMM128_XMM: False, + Code.VEX_VMOVUPD_YMM_YMMM256: True, + Code.VEX_VMOVUPD_YMMM256_YMM: True, +} + +ALLOWED_CODES = { + Code.RETNQ, + Code.VEX_VZEROUPPER, + *HORIZ_FP_CODES, + *VEC_MOVE_CODES, +} + +PRELUDE = """#include +#include +#include +#include +#if defined(_MSC_VER) +#include +#define X2W_UNALIGNED __unaligned +#else +#define X2W_UNALIGNED +#endif + +using word = std::uint64_t; + +struct Vec256 { + std::uint64_t q[4]; +}; + +static inline Vec256 load128(word address) { + std::atomic_signal_fence(std::memory_order_seq_cst); + const auto* p = reinterpret_cast(address); + const std::uint64_t q0 = p[0]; + const std::uint64_t q1 = p[1]; + std::atomic_signal_fence(std::memory_order_seq_cst); + return {{q0, q1, 0ull, 0ull}}; +} + +static inline Vec256 load256(word address) { + std::atomic_signal_fence(std::memory_order_seq_cst); + const auto* p = reinterpret_cast(address); + const std::uint64_t q0 = p[0]; + const std::uint64_t q1 = p[1]; + const std::uint64_t q2 = p[2]; + const std::uint64_t q3 = p[3]; + std::atomic_signal_fence(std::memory_order_seq_cst); + return {{q0, q1, q2, q3}}; +} + +static inline void store128(word address, const Vec256& v) { + std::atomic_signal_fence(std::memory_order_seq_cst); + std::memcpy(reinterpret_cast(address), v.q, 16); + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +static inline void store256(word address, const Vec256& v) { + std::atomic_signal_fence(std::memory_order_seq_cst); + std::memcpy(reinterpret_cast(address), v.q, 32); + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +static inline Vec256 copy128(const Vec256& v) { + return {{v.q[0], v.q[1], 0ull, 0ull}}; +} + +template +static inline Vec256 apply_sse3_lanes(const Vec256& a, const Vec256& b, bool wide, Fn fn) { + Vec256 out{}; + const unsigned lanes = wide ? 2u : 1u; + for (unsigned lane = 0; lane < lanes; ++lane) { + LaneVec va; + LaneVec vb; + std::memcpy(&va, &a.q[lane * 2u], 16); + std::memcpy(&vb, &b.q[lane * 2u], 16); + const LaneVec vr = fn(va, vb); + std::memcpy(&out.q[lane * 2u], &vr, 16); + } + return out; +} + +static inline Vec256 op_vhaddps(const Vec256& a, const Vec256& b, bool wide) { + return apply_sse3_lanes<__m128>(a, b, wide, [](__m128 x, __m128 y) { return _mm_hadd_ps(x, y); }); +} + +static inline Vec256 op_vhaddpd(const Vec256& a, const Vec256& b, bool wide) { + return apply_sse3_lanes<__m128d>(a, b, wide, [](__m128d x, __m128d y) { return _mm_hadd_pd(x, y); }); +} + +static inline Vec256 op_vhsubps(const Vec256& a, const Vec256& b, bool wide) { + return apply_sse3_lanes<__m128>(a, b, wide, [](__m128 x, __m128 y) { return _mm_hsub_ps(x, y); }); +} + +static inline Vec256 op_vhsubpd(const Vec256& a, const Vec256& b, bool wide) { + return apply_sse3_lanes<__m128d>(a, b, wide, [](__m128d x, __m128d y) { return _mm_hsub_pd(x, y); }); +} + +static inline Vec256 op_vaddsubps(const Vec256& a, const Vec256& b, bool wide) { + return apply_sse3_lanes<__m128>(a, b, wide, [](__m128 x, __m128 y) { return _mm_addsub_ps(x, y); }); +} + +static inline Vec256 op_vaddsubpd(const Vec256& a, const Vec256& b, bool wide) { + return apply_sse3_lanes<__m128d>(a, b, wide, [](__m128d x, __m128d y) { return _mm_addsub_pd(x, y); }); +} + +#if defined(_MSC_VER) +extern "C" __declspec(dllexport) std::uint32_t host_has_avx() { + int info[4]{}; + __cpuid(info, 1); + const int need = (1 << 27) | (1 << 28); + if ((info[2] & need) != need) return 0u; + return (_xgetbv(0) & 6u) == 6u ? 1u : 0u; +} + +extern "C" __declspec(dllexport) std::uint32_t host_exchange_mxcsr(std::uint32_t next) { + const std::uint32_t current = _mm_getcsr(); + _mm_setcsr(next); + return current; +} +#endif +""" + + +def vec_index(register, ins, *, expected_wide): + """Map XMM0..XMM5 or YMM0..YMM5 to register index, enforcing width and rejecting nonvolatile/other.""" + if register in VOLATILE_XMM: + if expected_wide: + raise ValueError(f"unsupported vector width for {register} at RVA {ins.ip:#x}: {ins}") + return VOLATILE_XMM[register] + if register in VOLATILE_YMM: + if not expected_wide: + raise ValueError(f"unsupported vector width for {register} at RVA {ins.ip:#x}: {ins}") + return VOLATILE_YMM[register] + if register in NONVOLATILE_VEC: + raise ValueError(f"nonvolatile vector register {register} at RVA {ins.ip:#x}: {ins}") + raise ValueError(f"unsupported vector register {register} at RVA {ins.ip:#x}: {ins}") + + +def flat_address(ins, *, store=False, expected_size=None): + """Lower a flat zero-displacement [rcx|rdx|r8] pointer operand (stores restricted to [r8]).""" + base = ins.memory_base + allowed = {R.R8} if store else ARGUMENTS + if ( + ins.is_ip_rel_memory_operand + or base in (R.NONE, R.RIP, R.EIP, R.RSP, R.ESP) + or ins.memory_index != R.NONE + or ins.memory_displacement != 0 + or not RegisterExt.is_gpr64(base) + or base not in allowed + ): + raise ValueError(f"unsupported memory operand at RVA {ins.ip:#x}: {ins}") + if expected_size is not None and MemorySizeExt.size(ins.memory_size) != expected_size: + raise ValueError(f"unsupported memory size at RVA {ins.ip:#x}: {ins}") + return ARGUMENTS[base] + + +def lift_code(name, start, raw): + """Decode and lift one bounded straight-line AVX horizontal/addsub FP leaf function.""" + instructions = list(Decoder(64, raw, ip=start)) + if not instructions or instructions[-1].next_ip != start + len(raw): + raise ValueError(f"truncated instruction stream in {name} at RVA {start:#x}") + if any(ins.is_invalid for ins in instructions): + bad = next(ins for ins in instructions if ins.is_invalid) + raise ValueError(f"invalid instruction at RVA {bad.ip:#x}") + + used = set() + defined = set() + statements = [] + returned = False + + def read_vec(op_index, ins, *, expected_wide): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register operand {op_index} at RVA {ins.ip:#x}: {ins}") + idx = vec_index(ins.op_register(op_index), ins, expected_wide=expected_wide) + if idx not in defined: + raise ValueError(f"undefined vector register ymm{idx} at RVA {ins.ip:#x}: {ins}") + used.add(idx) + return f"ymm{idx}" + + def write_vec(op_index, ins, *, expected_wide): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register destination at RVA {ins.ip:#x}: {ins}") + idx = vec_index(ins.op_register(op_index), ins, expected_wide=expected_wide) + used.add(idx) + return idx, f"ymm{idx}" + + for ins in instructions: + if returned: + raise ValueError(f"unreachable instruction after ret at RVA {ins.ip:#x}: {ins}") + if ins.has_lock_prefix or ins.has_rep_prefix or ins.has_repne_prefix or ins.has_segment_prefix: + raise ValueError(f"unsupported instruction prefix at RVA {ins.ip:#x}: {ins}") + if ( + ins.op_code().encoding == EncodingKind.EVEX + or ins.op_mask != R.NONE + or ins.zeroing_masking + or ins.is_broadcast + ): + raise ValueError(f"unsupported EVEX instruction at RVA {ins.ip:#x}: {ins}") + if ins.code not in ALLOWED_CODES: + raise ValueError(f"unsupported instruction at RVA {ins.ip:#x}: {ins}") + + if ins.code == Code.RETNQ: + statements.append("return;") + returned = True + elif ins.code == Code.VEX_VZEROUPPER: + for idx in sorted(defined): + statements.append(f"ymm{idx}.q[2] = 0ull; ymm{idx}.q[3] = 0ull;") + elif ins.code in HORIZ_FP_CODES: + helper, wide = HORIZ_FP_CODES[ins.code] + if ins.op_count != 3 or ins.op0_kind != OpKind.REGISTER or ins.op1_kind != OpKind.REGISTER: + raise ValueError(f"unsupported AVX horizontal FP operands at RVA {ins.ip:#x}: {ins}") + src1 = read_vec(1, ins, expected_wide=wide) + if ins.op2_kind == OpKind.MEMORY: + addr = flat_address(ins, expected_size=32 if wide else 16) + src2 = f"{'load256' if wide else 'load128'}({addr})" + elif ins.op2_kind == OpKind.REGISTER: + src2 = read_vec(2, ins, expected_wide=wide) + else: + raise ValueError(f"unsupported AVX horizontal FP operands at RVA {ins.ip:#x}: {ins}") + dst_idx, dst = write_vec(0, ins, expected_wide=wide) + statements.append(f"{dst} = {helper}({src1}, {src2}, {'true' if wide else 'false'});") + defined.add(dst_idx) + elif ins.code in VEC_MOVE_CODES: + wide = VEC_MOVE_CODES[ins.code] + expected_size = 32 if wide else 16 + if ins.op0_kind == OpKind.REGISTER and ins.op1_kind == OpKind.MEMORY: + addr = flat_address(ins, expected_size=expected_size) + dst_idx, dst = write_vec(0, ins, expected_wide=wide) + statements.append(f"{dst} = {'load256' if wide else 'load128'}({addr});") + defined.add(dst_idx) + elif ins.op0_kind == OpKind.MEMORY and ins.op1_kind == OpKind.REGISTER: + src = read_vec(1, ins, expected_wide=wide) + addr = flat_address(ins, store=True, expected_size=expected_size) + statements.append(f"{'store256' if wide else 'store128'}({addr}, {src});") + elif ins.op0_kind == OpKind.REGISTER and ins.op1_kind == OpKind.REGISTER: + src = read_vec(1, ins, expected_wide=wide) + dst_idx, dst = write_vec(0, ins, expected_wide=wide) + statements.append(f"{dst} = {src};" if wide else f"{dst} = copy128({src});") + defined.add(dst_idx) + else: + raise ValueError(f"unsupported vector move operands at RVA {ins.ip:#x}: {ins}") + else: + raise ValueError(f"unsupported instruction at RVA {ins.ip:#x}: {ins}") + + if not returned: + raise ValueError(f"missing terminal ret in {name} at RVA {start + len(raw):#x}") + + decls = [f" Vec256 ymm{idx}{{}};" for idx in sorted(used)] + body = [f" {stmt}" for stmt in statements] + lines = [ + f'extern "C" __declspec(dllexport) void lifted_{name}(word rcx, word rdx, word r8) {{', + " (void)rcx; (void)rdx; (void)r8;", + *decls, + *body, + "}", + ] + return "\n".join(lines), len(instructions) + + +def lift(pe, name): + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + source, count = lift_code(name, entry, raw) + return source, entry, count + + +def translate_pe(pe, names): + if pe.FILE_HEADER.Machine != 0x8664 or pe.OPTIONAL_HEADER.Magic != 0x20B: + raise ValueError("expected AMD64 PE32+") + lifted = [lift(pe, name) for name in names] + source = PRELUDE + "\n".join(f"\n{text}" for text, _, _ in lifted) + "\n" + meta = [(name, entry, count) for name, (_, entry, count) in zip(names, lifted)] + return source, meta + + +def translate(image, names): + with pefile.PE(str(image), fast_load=True) as pe: + return translate_pe(pe, names) + + +def _write_atomic(path: Path, content: str) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + tmp_path = None + try: + with tempfile.NamedTemporaryFile( + mode="w", + encoding="utf-8", + newline="\n", + dir=path.parent, + prefix=f".{path.stem}.", + suffix=".tmp", + delete=False, + ) as handle: + tmp_path = Path(handle.name) + handle.write(content) + tmp_path.replace(path) + except BaseException: + if tmp_path is not None: + tmp_path.unlink(missing_ok=True) + raise + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("image", type=Path) + parser.add_argument("exports", help="comma-separated export names") + parser.add_argument("output", type=Path) + args = parser.parse_args(argv) + try: + if not args.image.is_file(): + raise ValueError(f"input image must be a regular file: {args.image}") + exports = [name for name in args.exports.split(",") if name] + if not exports: + raise ValueError("exports list must not be empty") + source, meta = translate(args.image, exports) + _write_atomic(args.output, source) + for name, entry, count in meta: + print(f"{name} at RVA {entry:#x}: {count} instructions") + except (ValueError, OSError, pefile.PEFormatError) as error: + parser.exit(1, f"cpu_avx_horiz_fp_aot: {error}\n") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) From 815ac65fb5719dc3e955bfbfec3ff9a0a3a8d4ec Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Thu, 26 Nov 2026 01:46:07 +0200 Subject: [PATCH 016/240] script: add archive file and ASCII state guards to script_state_probe with CLI suite (#2620) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 3 + tests/script_state_probe_cli_check.py | 377 ++++++++++++++++++++++++++ tools/script_state_probe.py | 34 ++- 3 files changed, 411 insertions(+), 3 deletions(-) create mode 100644 tests/script_state_probe_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index fb6084cec..f62ff89dd 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8973,6 +8973,9 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/script_dispatch_check.py" "$") add_test(NAME script_state_probe_checks COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/script_state_probe_check.py") + add_test(NAME script_state_probe_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/script_state_probe_cli_check.py") + set_tests_properties(script_state_probe_cli_check PROPERTIES TIMEOUT 60) add_test(NAME script_typed_path_dispatch COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/script_dispatch_check.py" "$" TypedScriptPathTests) add_test(NAME bcpack_prefix_and_mip_tail COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/script_state_probe_cli_check.py b/tests/script_state_probe_cli_check.py new file mode 100644 index 000000000..b0e3a75bf --- /dev/null +++ b/tests/script_state_probe_cli_check.py @@ -0,0 +1,377 @@ +"""Pure-Python CLI and synthetic RPF9 validation suite for tools/script_state_probe.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +import json +import mmap +import os +from pathlib import Path +import runpy +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory +import unittest +from unittest import mock +import zlib + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "script_state_probe.py" +sys.path.insert(0, str(ROOT / "tools")) + +import script_state_probe as probe # noqa: E402 + + +def _attr(name: str, spelling: str, raw: int, kind: int) -> bytes: + return struct.pack(" list[bytes]: + return [ + _attr("priority", str(priority), priority, 3), + _attr("blendduration", "25", 25, 3), + _attr("orbitdistance", "2.500000", 0x40200000, 2), + _attr("pitchlimits", "-0.500000,0.500000,0.000000", 0, 1), + _attr("headinglimits", "-1.500000,1.500000,0.000000", 1, 1), + ] + + +def _synth_record( + *, + priorities: tuple[int, ...] = (7,), + state_label: str = "cli_synthetic_state", + truncate_schema_by: int = 0, + corrupt_zlib: bool = False, + truncate_zlib: bool = False, +) -> bytes: + """Build one zlib-compressed PSIN/LSCH/LENM/LSNS/LGID/LRSC/CHKS record payload.""" + attrs = bytearray() + nodes = bytearray() + + def add_node(name: str, parent: int, row_list: list[bytes]) -> int: + idx = len(nodes) // 16 + nodes.extend( + struct.pack( + " 1: + root_parent = add_node("root", root_parent, []) + for prio in priorities: + state_idx = add_node("state", root_parent, [_attr("id", state_label, 0, 5)]) + add_node("camera", state_idx, _camera_rows(prio)) + + vecs = struct.pack("<6f", -0.5, 0.5, 0.0, -1.5, 1.5, 0.0) + arrays = ((len(attrs) // 16, 2), (0, 0), (2, 4), (0, 0), (len(nodes) // 16, 3)) + root_blob = b"".join(struct.pack("4sI", tag, len(part) + 8)) + body.extend(part) + + chks_size = 20 + total_len = len(body) + chks_size + body.extend(struct.pack(">4sIIQ", b"CHKS", chks_size, total_len, 0)) + + compressed = zlib.compress(bytes(body)) + if corrupt_zlib: + return compressed[:4] + b"\xff\x00\xff\x00" + compressed[8:] + if truncate_zlib: + return compressed[:6] + return compressed + + +def _build_rpf9(*payloads: bytes) -> bytes: + archive = bytearray(b"9FPR") + for payload in payloads: + archive.extend(bytes(-len(archive) % 16)) + archive.extend(payload) + return bytes(archive) + + +def _run_main(argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + rc = probe.main(argv) + except SystemExit as exc: + rc = exc.code if isinstance(exc.code, int) else 2 + return rc, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + env = dict(os.environ, PYTHONUTF8="1") + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + encoding="utf-8", + env=env, + timeout=30, + ) + + +class ScriptStateProbeCliPositiveTests(unittest.TestCase): + def test_direct_main_default_and_state_schema(self): + single_bytes = _build_rpf9(_synth_record(priorities=(7,), state_label="orbit_one")) + ambig_bytes = _build_rpf9(_synth_record(priorities=(7, 11), state_label="orbit_dup")) + with TemporaryDirectory() as tmp: + root = Path(tmp) + single = root / "single.rpf" + single.write_bytes(single_bytes) + ambig = root / "ambig.rpf" + ambig.write_bytes(ambig_bytes) + + # Default mode without --state. + rc, out, err = _run_main([str(single)]) + self.assertEqual(rc, 0, err) + self.assertEqual(err, "") + default_json = json.loads(out) + self.assertEqual( + set(default_json), + {"counts", "requested_state", "first_verified_example"}, + ) + self.assertIsNone(default_json["requested_state"]) + self.assertIsNone(default_json["first_verified_example"]) + self.assertEqual( + default_json["counts"], + { + "section_records": 1, + "node_trees": 1, + "state_nodes": 1, + "camera_parameter_sets": 1, + "all_five_literals_verified": 1, + }, + ) + self.assertEqual(single.read_bytes(), single_bytes) + + # Matching --state mode. + rc, out, err = _run_main([str(single), "--state", "orbit_one"]) + self.assertEqual(rc, 0, err) + self.assertEqual(err, "") + matched_json = json.loads(out) + self.assertEqual(matched_json["requested_state"], "orbit_one") + self.assertEqual( + matched_json["first_verified_example"], + { + "priority": "7", + "blendduration": "25", + "orbitdistance": "2.500000", + "pitchlimits": "-0.500000,0.500000,0.000000", + "headinglimits": "-1.500000,1.500000,0.000000", + }, + ) + self.assertNotIn("ambiguous_state_candidates", matched_json) + + # Unmatched --state mode. + rc, out, err = _run_main([str(single), "--state", "absent_state"]) + self.assertEqual(rc, 0, err) + self.assertEqual(err, "") + missed_json = json.loads(out) + self.assertEqual(missed_json["requested_state"], "absent_state") + self.assertIsNone(missed_json["first_verified_example"]) + + # Ambiguous --state mode. + rc, out, err = _run_main([str(ambig), "--state", "orbit_dup"]) + self.assertEqual(rc, 0, err) + self.assertEqual(err, "") + ambig_json = json.loads(out) + self.assertIsNone(ambig_json["first_verified_example"]) + self.assertEqual( + [c["node_path"] for c in ambig_json["ambiguous_state_candidates"]], + [[0, 1], [0, 3]], + ) + + # Subprocess parity and sys.argv/runpy entrypoint. + proc = _run_subprocess(str(single), "--state", "orbit_one") + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stderr, "") + self.assertEqual(json.loads(proc.stdout), matched_json) + + with mock.patch.object(sys, "argv", [str(TOOL), str(single), "--state", "orbit_one"]): + rc_none, out_none, err_none = _run_main(None) + self.assertEqual(rc_none, 0, err_none) + self.assertEqual(json.loads(out_none), matched_json) + + out_runpy, err_runpy = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", [str(TOOL), str(single)]), + redirect_stdout(out_runpy), + redirect_stderr(err_runpy), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 0) + self.assertEqual(err_runpy.getvalue(), "") + self.assertEqual(json.loads(out_runpy.getvalue()), default_json) + + def test_corrupt_or_truncated_zlib_yields_zero_node_trees_without_crash(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + for label, kw in ( + ("corrupt_zlib", {"corrupt_zlib": True}), + ("truncated_zlib", {"truncate_zlib": True}), + ): + with self.subTest(case=label): + archive = root / f"{label}.rpf" + archive.write_bytes(_build_rpf9(_synth_record(**kw))) + rc, out, err = _run_main([str(archive)]) + self.assertEqual(rc, 0, err) + self.assertEqual(err, "") + payload = json.loads(out) + self.assertEqual(payload["counts"].get("node_trees", 0), 0) + self.assertEqual(payload["counts"], {}) + + +class ScriptStateProbeCliNegativeTests(unittest.TestCase): + def _assert_cli_failure( + self, + argv: list[str], + *, + expected_code: int, + fragment: str, + check_subprocess: bool = True, + ) -> None: + rc, out, err = _run_main(argv) + self.assertEqual(rc, expected_code, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertIn(fragment, err) + + if check_subprocess: + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertIn(fragment, proc.stderr) + + def test_upfront_is_file_and_archive_validation_controls(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + missing = root / "missing.rpf" + folder = root / "dir_archive" + folder.mkdir() + empty = root / "empty.rpf" + empty.write_bytes(b"") + short_header = root / "short.rpf" + short_header.write_bytes(b"9FP") + bad_magic = root / "bad_magic.rpf" + bad_magic.write_bytes(b"NOPE" + b"\x00" * 16) + truncated_schema = root / "truncated_schema.rpf" + truncated_schema.write_bytes(_build_rpf9(_synth_record(truncate_schema_by=8))) + + # Missing and directory must reject upfront before open/mmap. + with ( + mock.patch.object(Path, "open", side_effect=AssertionError("open must not run")), + mock.patch.object(mmap, "mmap", side_effect=AssertionError("mmap must not run")), + ): + with self.assertRaises(FileNotFoundError): + probe.inspect(missing) + with self.assertRaisesRegex(ValueError, "directory"): + probe.inspect(folder) + + self._assert_cli_failure([str(missing)], expected_code=1, fragment="not found") + self._assert_cli_failure([str(folder)], expected_code=1, fragment="directory") + + # 0-byte archive must fail cleanly before mmap.mmap. + with mock.patch.object(mmap, "mmap", side_effect=AssertionError("mmap must not run")): + with self.assertRaisesRegex(ValueError, "Empty archive"): + probe.inspect(empty) + self._assert_cli_failure([str(empty)], expected_code=1, fragment="Empty archive") + + # Truncated header, bad magic, and truncated inner schema. + self._assert_cli_failure([str(short_header)], expected_code=1, fragment="Expected an RPF9 archive") + self._assert_cli_failure([str(bad_magic)], expected_code=1, fragment="Expected an RPF9 archive") + self._assert_cli_failure([str(truncated_schema)], expected_code=1, fragment="Truncated schema members") + + def test_empty_and_non_ascii_state_validation(self): + with TemporaryDirectory() as tmp: + archive = Path(tmp) / "valid.rpf" + archive.write_bytes(_build_rpf9(_synth_record())) + + # Upfront state validation rejects before open/mmap. + with ( + mock.patch.object(Path, "open", side_effect=AssertionError("open must not run")), + mock.patch.object(mmap, "mmap", side_effect=AssertionError("mmap must not run")), + ): + with self.assertRaisesRegex(ValueError, "non-empty ASCII"): + probe.inspect(archive, "") + with self.assertRaisesRegex(ValueError, "ASCII"): + probe.inspect(archive, "café") + with self.assertRaisesRegex(ValueError, "non-empty ASCII"): + probe.joaat("", allow_empty=False) + + # Empty and non-ASCII --state via main(argv) and subprocess. + self._assert_cli_failure([str(archive), "--state", ""], expected_code=1, fragment="non-empty ASCII") + self._assert_cli_failure([str(archive), "--state", "café"], expected_code=1, fragment="ASCII") + + def test_argparse_errors_and_help_py314_compatible(self): + with TemporaryDirectory() as tmp: + archive = Path(tmp) / "valid.rpf" + archive.write_bytes(_build_rpf9(_synth_record())) + + for argv, fragment in ( + ([], "usage:"), + ([str(archive), "--unknown-flag"], "unrecognized"), + ([str(archive), "--state"], "--state"), + ): + with self.subTest(argv=argv): + self._assert_cli_failure(argv, expected_code=2, fragment=fragment) + + rc, out, err = _run_main(["--help"]) + self.assertEqual(rc, 0) + self.assertIn("usage:", out) + self.assertEqual(err, "") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/script_state_probe.py b/tools/script_state_probe.py index cf741652b..8b13d6d5b 100644 --- a/tools/script_state_probe.py +++ b/tools/script_state_probe.py @@ -13,7 +13,11 @@ from section_probe import sections -def joaat(text): +def joaat(text, *, allow_empty=True): + if not isinstance(text, str): + raise ValueError("State label must be an ASCII string") + if not allow_empty and not text: + raise ValueError("State label must be non-empty ASCII") value = 0 for byte in text.encode("ascii"): value = (value + byte) & 0xffffffff @@ -24,6 +28,26 @@ def joaat(text): return (value + (value << 15)) & 0xffffffff +def _validate_state(state): + if not isinstance(state, str) or not state: + raise ValueError("State label must be non-empty ASCII") + try: + return joaat(state, allow_empty=False) + except UnicodeEncodeError as exc: + raise ValueError(f"State label must be ASCII: {state!r}") from exc + + +def _require_archive_file(path): + path = Path(path) + if not path.is_file(): + if path.is_dir(): + raise ValueError(f"archive path is a directory, not a file: {path}") + if not path.exists(): + raise FileNotFoundError(f"archive file not found: {path}") + raise ValueError(f"archive path is not a regular file: {path}") + return path + + CAMERA = {joaat(s): s for s in ("blendduration", "orbitdistance", "priority", "pitchlimits", "headinglimits")} NODE = struct.Struct(" int: parser.add_argument("--state", help="Report at most one hash-verified example for this state label") args = parser.parse_args(argv) try: - result = inspect(args.archive, args.state) + if args.state is not None: + _validate_state(args.state) + archive = _require_archive_file(args.archive) + result = inspect(archive, args.state) except (OSError, ValueError, struct.error, zlib.error) as exc: parser.exit(1, f"{args.archive}: {exc}\n") print(json.dumps(result, indent=2)) From 5b368706e6161181d55c24140ae00aa99dc29b42 Mon Sep 17 00:00:00 2001 From: Royoo <3230853833@qq.com> Date: Thu, 26 Nov 2026 07:48:22 +0800 Subject: [PATCH 017/240] tests: use a portable negative record offset in the SGD5 CLI fixture (#2632) --- tests/sgd5_effects_cli_check.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/sgd5_effects_cli_check.py b/tests/sgd5_effects_cli_check.py index 297c69e9c..903bbb7cb 100644 --- a/tests/sgd5_effects_cli_check.py +++ b/tests/sgd5_effects_cli_check.py @@ -263,7 +263,8 @@ def test_negative_offsets_rejected_by_offset_parser_before_opening_archive(self) ("neg_group_end", [str(archive), "draw", "--group", str(grp_start), "-1", "--arrays", str(arrays), "--record", str(rec_start), str(rec_end)]), ("neg_arrays", [str(archive), "draw", "--group", str(grp_start), str(grp_end), "--arrays=-0x1", "--record", str(rec_start), str(rec_end)]), ("neg_record_start", [str(archive), "draw", "--group", str(grp_start), str(grp_end), "--arrays", str(arrays), "--record", "-1", str(rec_end)]), - ("neg_record_end", [str(archive), "draw", "--group", str(grp_start), str(grp_end), "--arrays", str(arrays), "--record", str(rec_start), "-0x10"]), + # Older argparse versions treat a separate negative hex token as an option, not as an offset. + ("neg_record_end", [str(archive), "draw", "--group", str(grp_start), str(grp_end), "--arrays", str(arrays), "--record", str(rec_start), "-16"]), ): with self.subTest(archive=archive.name, case=label): with mock.patch.object( From 52bccd9012e029ab766c485ce3c2ca4006cf4c18 Mon Sep 17 00:00:00 2001 From: tedin7 <110300616+tedin7@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:49:33 +0100 Subject: [PATCH 018/240] shader: lower image_sample_d and document image_sample_c_d refusal in gfx2hlsl (Part of #1723) (#2082) * feat: lower image_sample_d to SampleGrad in gfx2hlsl Part of #1723. 2D, 2D array and 3D gradient samples; image_sample_c_d is refused by name (needs SM 6.8). * test: register startup_image_sample_d in CMake Part of #1723. * startup: keep the guest LOD cap for image_sample_d and document the form in gfx2hlsl * test: WARP and hardware readback for image_sample_d against a CPU reference * tests: build the implicit Sample negative control with two arguments --------- Co-authored-by: Royoo <3230853833@qq.com> --- CMakeLists.txt | 11 ++ docs/experiments.md | 17 ++ tests/startup_image_sample_d_check.py | 133 ++++++++++++++ tests/startup_image_sample_d_draw_check.py | 203 +++++++++++++++++++++ tools/startup/gfx2hlsl.py | 37 +++- 5 files changed, 398 insertions(+), 3 deletions(-) create mode 100644 tests/startup_image_sample_d_check.py create mode 100644 tests/startup_image_sample_d_draw_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index f62ff89dd..c6788297b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3134,6 +3134,17 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_ngg_slice_check.py") add_test(NAME startup_image_sample_l COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_image_sample_l_check.py") + add_test(NAME startup_image_sample_d COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_image_sample_d_check.py") + # image_sample_d drawn on D3D12 (FXC 5_1 and DXC 6_0): GPU readback of the mip chosen by explicit gradients. + add_test(NAME startup_image_sample_d_draw_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_image_sample_d_draw_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_image_sample_d_draw_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_image_sample_d_draw_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_image_sample_d_draw_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + endforeach() add_test(NAME startup_image_gather_lz COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_image_gather_lz_check.py") add_test(NAME startup_compute_gather_lz COMMAND "${INTAKE_PYTHON}" -B diff --git a/docs/experiments.md b/docs/experiments.md index 27e29d30e..8a03f32b7 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15712,6 +15712,23 @@ The [MASM fixture](../tests/cpu/switch_sal.asm) emits explicit `/6` byte sequenc Not covered by this experiment: `SAL` outside leaf/switch-lifted functions, and title CPU code execution. +## Startup translator: explicit-gradient image_sample_d + +`tools/startup/gfx2hlsl.py` lowers the gfx1013 `image_sample_d` form in a pixel stage to `tex.SampleGrad(smp, uv, ddx, ddy)`. The address dwords are ddx, then ddy (one register per coordinate axis each), then the coordinates: six registers for 2D, seven for a 2D array (slice last), nine for a volume (a contiguous nine-dword volume address encoded as a sixteen-register range is trimmed to nine). Only `dim:`, `dmask:` and the cache-policy bits `dlc`, `glc`, `slc` are accepted. + +Refused with a named reason: `image_sample_c_d` (it would need `SampleCmpGrad`, shader model 6.8; only `image_sample_c` and `_c_lz` are lowered), `image_sample_d_o` and every other offset, bias, clamp, `a16`, `tfe` or `lwe` form, an empty `dmask`, a 1D image, and an address count that does not match the dimension. + +The guest sampler LOD range is kept: a constant sampler carries MIN_LOD and MAX_LOD to the static sampler through the same `smpl` line as `image_sample`, `_l` and `_lz` (sampler words `(0, 0, 0x04000000, 0)` stay capped at mip 0), with the same refusals for a LOD bias and for MIN_LOD above MAX_LOD. A mip filter of 0 keeps the ordinary sampler, and a heap sampler is not validated and is logged once per module. + +Verified: the Python translation checks (address order, refusals, the LOD cap, fixture words against `llvm-mc`) and a D3D12 draw on WARP and hardware (`tests/startup_image_sample_d_draw_check.py`): four `SampleGrad` probes on a three-mip, two-slice fixture read back against a CPU reference, with a MAX_LOD 0 sampler and an implicit `Sample` as negative controls. + +```bash +./out/pe-env/bin/python -B tests/startup_image_sample_d_check.py +./out/pe-env/bin/python -B tests/startup_image_sample_d_check.py binary +ctest --preset dev --no-tests=error -R "^startup_image_sample_d" -V +ctest --preset dev --no-tests=error -R "^startup_image_sample_d_draw_(warp|hardware)$" -V +``` + ### Startup 24-bit multiplies, v_xnor_b32 and the funnel shifts `tools/startup/gfx2hlsl.py` translates `v_mul_i32_i24`, `v_mad_i32_i24`, `v_mul_hi_i32_i24`, `v_xnor_b32`, `v_alignbit_b32` and `v_alignbyte_b32` (VOP2 and VOP3 spellings) in 32-bit integer arithmetic, with no 64-bit type. The signed forms sign-extend the low 24 bits of each source with a left shift of 8 and an arithmetic right shift; the high product is assembled from 12-bit halves so that it stays inside 32 bits. diff --git a/tests/startup_image_sample_d_check.py b/tests/startup_image_sample_d_check.py new file mode 100644 index 000000000..5e7ac7d48 --- /dev/null +++ b/tests/startup_image_sample_d_check.py @@ -0,0 +1,133 @@ +"""Explicit-gradient image_sample_d in tools/startup/gfx2hlsl.py. + + (no arguments) translation controls, pure Python + binary reassemble every fixture source and compare it with the recorded words + +The address dwords of image_sample_d are ddx, then ddy (one register per coordinate axis each), then the coordinates. +The lowering must pass those registers to SampleGrad in that order: a 2D sample has six, a 2D array seven (the slice +last) and a volume nine. image_sample_c_d would need SampleCmpGrad (shader model 6.8) and is refused by name instead +of being sampled without its gradients. +""" +import re +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_image_sample_l_check import POST, PRE # noqa: E402 +from startup_sampler_heap_check import VS_WORDS, assemble, root_blob # noqa: E402 + +TAIL = 's[16:23], s[24:27] dmask:0xf dim:' +IMAGE = { + 'd2': 'image_sample_d v[4:7], v[0:5], ' + TAIL + 'SQ_RSRC_IMG_2D', + 'd2nsa': 'image_sample_d v[4:7], [v0, v1, v2, v3, v1, v0], ' + TAIL + 'SQ_RSRC_IMG_2D', + 'd3': 'image_sample_d v[4:7], v[0:8], ' + TAIL + 'SQ_RSRC_IMG_3D', + 'd2a': 'image_sample_d v[4:7], v[0:6], ' + TAIL + 'SQ_RSRC_IMG_2D_ARRAY', + 'd1': 'image_sample_d v[4:7], [v0, v1, v2], ' + TAIL + 'SQ_RSRC_IMG_1D', + 'cd': 'image_sample_c_d v[4:7], v[0:6], ' + TAIL + 'SQ_RSRC_IMG_2D', + 'do': 'image_sample_d_o v[4:7], v[0:6], ' + TAIL + 'SQ_RSRC_IMG_2D', + 'dtfe': 'image_sample_d v[4:5], v[0:5], s[16:23], s[24:27] dmask:0x1 dim:SQ_RSRC_IMG_2D tfe', + 'dglc': 'image_sample_d v[4:7], v[0:5], ' + TAIL + 'SQ_RSRC_IMG_2D glc', +} +WORDS = { + 'd2': bytes.fromhex('04040cf4000000fa800398be800399be80039abe80039bbef002007eff02027e0000803ef202047ef402067e7fc08cbf080f88f00004c400703f8cbf0f1800f804050607000081bf'), + 'd2nsa': bytes.fromhex('04040cf4000000fa800398be800399be80039abe80039bbef002007eff02027e0000803ef202047ef402067e7fc08cbf0c0f88f00004c4000102030100000000703f8cbf0f1800f804050607000081bf'), + 'd3': bytes.fromhex('04040cf4000000fa800398be800399be80039abe80039bbef002007eff02027e0000803ef202047ef402067e7fc08cbf100f88f00004c400703f8cbf0f1800f804050607000081bf'), + 'd2a': bytes.fromhex('04040cf4000000fa800398be800399be80039abe80039bbef002007eff02027e0000803ef202047ef402067e7fc08cbf280f88f00004c400703f8cbf0f1800f804050607000081bf'), + 'd1': bytes.fromhex('04040cf4000000fa800398be800399be80039abe80039bbef002007eff02027e0000803ef202047ef402067e7fc08cbf020f88f00004c40001020000703f8cbf0f1800f804050607000081bf'), + 'cd': bytes.fromhex('04040cf4000000fa800398be800399be80039abe80039bbef002007eff02027e0000803ef202047ef402067e7fc08cbf080fa8f00004c400703f8cbf0f1800f804050607000081bf'), + 'do': bytes.fromhex('04040cf4000000fa800398be800399be80039abe80039bbef002007eff02027e0000803ef202047ef402067e7fc08cbf080fc8f00004c400703f8cbf0f1800f804050607000081bf'), + 'dtfe': bytes.fromhex('04040cf4000000fa800398be800399be80039abe80039bbef002007eff02027e0000803ef202047ef402067e7fc08cbf080189f00004c400703f8cbf0f1800f804050607000081bf'), + 'dglc': bytes.fromhex('04040cf4000000fa800398be800399be80039abe80039bbef002007eff02027e0000803ef202047ef402067e7fc08cbf082f88f00004c400703f8cbf0f1800f804050607000081bf'), +} + + +def stage(name): + return G.Pipeline(VS_WORDS, WORDS[name], root_blob(flags=0)).hlsl_ps() + + +def grad_call(name): + """(location, ddx, ddy) register lists of the SampleGrad call.""" + call = re.search(r'SampleGrad\(([^;]*)\);', stage(name)) + assert call, name + parts = call.group(1).split('float')[1:] + assert len(parts) == 3, call.group(1) + return [re.findall(r'F\((v\d+)\)', part) for part in parts] + + +def refused(name, text): + try: + stage(name) + except G.Unsupported as error: + assert text in str(error), (name, str(error)) + else: + raise AssertionError('%s was accepted' % name) + + +def check_address_count(): + """A count that does not match the dimension is refused before any register is read.""" + for coords, count in (('[v0, v1, v2, v3, v1]', 5), ('[v0, v1, v2, v3, v1, v0, v2]', 7)): + bare = G.Stage.__new__(G.Stage) + try: + bare.image(['v5', coords, 's0'], ['dim:SQ_RSRC_IMG_2D', 'dmask:0x1'], 'd') + except G.Unsupported as error: + assert str(error) == 'image_sample_d with %d address registers' % count, (coords, error) + else: + raise AssertionError('image_sample_d accepted %d address registers' % count) + + +def check_lod_cap(): + """A guest sampler capped to MAX_LOD 0 keeps its cap: the static sampler carries it, so SampleGrad cannot reach mip 2. + + The cap fixture is the 2D program with `s_mov_b32 s26, 0` (80039abe) widened to the literal 0x04000000, mip filter + point (word 2 bits 27:26 = 1), words (0, 0, 0x04000000, 0). A mip filter of 0 keeps the ordinary sampler.""" + words = WORDS['d2'] + assert words.count(bytes.fromhex('80039abe')) == 1 + capped = words.replace(bytes.fromhex('80039abe'), bytes.fromhex('ff039abe') + (0x04000000).to_bytes(4, 'little')) + pipe = G.Pipeline(VS_WORDS, capped, root_blob(flags=0)) + assert 'SampleGrad(' in pipe.hlsl_ps() + lines = pipe.manifest().splitlines() + assert 'smpl 0 0x0 0x0 0x4000000 0x0' in lines and 'smp ' not in pipe.manifest(), pipe.manifest() + plain = G.Pipeline(VS_WORDS, words, root_blob(flags=0)) + plain.hlsl_ps() + assert 'smp 0 0x0 0x0 0x0 0x0' in plain.manifest().splitlines() and 'smpl' not in plain.manifest(), plain.manifest() + print('a capped constant sampler is carried to the static sampler; mip filter 0 keeps the ordinary one') + + +def controls(): + check_address_count() + check_lod_cap() + assert grad_call('d2') == [['v4', 'v5'], ['v0', 'v1'], ['v2', 'v3']], grad_call('d2') + assert grad_call('d2nsa') == [['v1', 'v0'], ['v0', 'v1'], ['v2', 'v3']], grad_call('d2nsa') + assert grad_call('d3') == [['v6', 'v7', 'v8'], ['v0', 'v1', 'v2'], ['v3', 'v4', 'v5']], grad_call('d3') + assert grad_call('d2a') == [['v4', 'v5', 'v6'], ['v0', 'v1'], ['v2', 'v3']], grad_call('d2a') + assert 'Texture2DArray' in stage('d2a') and 'Texture3D' in stage('d3') + print('2D, NSA 2D, 3D and 2D array pass ddx, ddy and the coordinates to SampleGrad in address order') + + refused('cd', 'image_sample_c_d') + refused('do', 'image_sample_d_o') + refused('d1', 'unverified 1D image sample address or modifiers') + refused('dtfe', 'image_sample_d modifier tfe') + print('refused: compare, offset, 1D, tfe') + + assert grad_call('dglc') == grad_call('d2') # cache-policy bits do not change the sampled value + print('glc is accepted') + + +def check_binary(llvm_mc): + for name, line in IMAGE.items(): + built = assemble(llvm_mc, PRE + line + '\n' + POST) + if built != WORDS[name]: + raise AssertionError('%s fixture: assembled %s, recorded %s' % (name, built.hex(), WORDS[name].hex())) + print('fixture words match llvm-mc') + + +if __name__ == '__main__': + if len(sys.argv) == 1: + controls() + elif sys.argv[1] == 'binary' and len(sys.argv) == 3: + check_binary(sys.argv[2]) + else: + sys.exit(__doc__) diff --git a/tests/startup_image_sample_d_draw_check.py b/tests/startup_image_sample_d_draw_check.py new file mode 100644 index 000000000..409aeca02 --- /dev/null +++ b/tests/startup_image_sample_d_draw_check.py @@ -0,0 +1,203 @@ +"""image_sample_d drawn on D3D12 (WARP and hardware), GPU readback against a CPU reference (Part of #1723). + + (no arguments) build the programs, translate them, check the CPU reference + draw [fxc] + compile (DXC ps_6_0, and FXC ps_5_1 when given) and draw against the + 4x4 two-slice, three-mip R32G32B32A32_FLOAT fixture of startup_image_3d.cpp + +One pixel stage samples four times with explicit gradients. The gradients, not the coordinates, pick the mip level: +rho = largest gradient component * 4 texels, so 0.25 -> mip 0, 0.5 -> mip 1, 1.0 -> mip 2 (exact powers of two, no +rounding ambiguity). Probes use ddx only, ddy only, a gradient on the second axis and the second array slice. +The expected colours come from the fixture formula red = (1 + x + 4y + 16s + 32m) / 128 evaluated here with +exact fractions. Mutants: a sampler capped to MAX_LOD 0 and SampleGrad replaced by an implicit Sample must both +return mip 0 on every probe, which the same draw must report as different from the expected colours. +""" +import re +import struct +import subprocess +import sys +import tempfile +from fractions import Fraction +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import disasm_rdna2 as D # noqa: E402 +import gfx2hlsl as G # noqa: E402 +from startup_image_3d_check import ( # noqa: E402 + FULLSCREEN_VS, + VS_WORDS, + CompileQueue, + compile_hlsl, + root_blob, +) +from startup_image_sample_c_border_check import ( # noqa: E402 + DIM_2D_ARRAY, + EXP_MRT0_V4_V7, + INLINE_FLOATS, + S_ENDPGM, + S_LOAD_DWORDX8, + S_WAIT_LGKM, + S_WAIT_VM, + f32_hex, + manifest_sampler, + mimg_seq, + s_mov_b32, + v_mov_inline, + v_mov_lit, +) + +IMG_SAMPLE_D = 0x22 +SIZE = 4 +LEVELS = 3 +# Point filters, mip filter point (word 2 bits 27:26 = 1), MIN_LOD 0 and MAX_LOD 2.0 (u4.8, word 1 bits 23:12). +SAMPLER_WORDS = (0, 2 * 256 << 12, 0x04000000, 0) +CAPPED_WORDS = (0, 0, 0x04000000, 0) +ADDR = 10 # v10..v16: ddx, ddy, coordinates, slice; v4..v7 receive the four probes + +# (u, v, slice, ddx, ddy) +PROBES = ( + (Fraction(5, 8), Fraction(3, 8), 0, (Fraction(1, 4), 0), (0, Fraction(1, 4))), + (Fraction(5, 8), Fraction(3, 8), 0, (Fraction(1, 2), 0), (0, 0)), + (Fraction(1, 8), Fraction(7, 8), 0, (0, 0), (0, 1)), + (Fraction(7, 8), Fraction(5, 8), 1, (0, Fraction(1, 2)), (0, 0)), +) + + +def bits(value): + return struct.unpack('> m + out.append(texel_red(int(u * dim), int(v * dim), s, m)) + return out + + +def pipeline(code): + return G.Pipeline(VS_WORDS, code, root_blob()) + + +def check_disassembly(code): + off, decoded = 0, [] + while off < len(code): + size, mnemonic, asm, _ = D.decode_instruction(code, off) + assert size > 0 and 'unknown' not in mnemonic, (off, mnemonic, asm) + decoded.append(asm) + off += size + assert off == len(code) and decoded[-1] == 's_endpgm' + assert sum(a.startswith('image_sample_d') for a in decoded) == len(PROBES), decoded + + +def controls(): + _src, code = build_program(SAMPLER_WORDS) + check_disassembly(code) + hlsl = pipeline(code).hlsl_ps() + assert hlsl.count('SampleGrad(') == len(PROBES), hlsl + expected = reference() + # Mip 1 and 2 are reached, and every probe differs from its mip 0 value: the draw can tell the levels apart. + assert expected == [Fraction(7, 128), Fraction(34, 128), Fraction(65, 128), Fraction(54, 128)], expected + assert all(a != b for a, b in list(zip(expected, reference(0)))[1:]) and expected[0] == reference(0)[0] + assert 'smpl ' in pipeline(code).manifest() + print('four SampleGrad probes translate; reference reaches mips 0, 1, 2 and slice 1') + + +def run_draw(renderer, adapter, vs, ps, expected, sampler): + cmd = [renderer, adapter, '--startup-image-2d-array-mips', str(vs), str(ps), '0', expected, sampler] + return subprocess.run(cmd, capture_output=True, text=True) + + +def check_draw(dxc, renderer, adapter, fxc=None): + _src, code = build_program(SAMPLER_WORDS) + pipe = pipeline(code) + sampler = manifest_sampler(pipe) + capped = manifest_sampler(pipeline(build_program(CAPPED_WORDS)[1])) + hlsl = pipe.hlsl_ps() + # Sample takes (sampler, uv) only: drop the two gradient arguments of each call. + gradient = r'float2\(F\(v\d+\), F\(v\d+\)\)' + implicit, changed = re.subn(rf', {gradient}, {gradient}(?=\);)', '', hlsl) + assert changed == hlsl.count('.SampleGrad(') == 4 + implicit = implicit.replace('.SampleGrad(', '.Sample(') + want = ','.join(f32_hex(float(r)) for r in reference()) + mip0 = ','.join(f32_hex(float(r)) for r in reference(0)) + compilers = [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + with tempfile.TemporaryDirectory() as tmp, CompileQueue() as queue: + directory = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + vs = queue.call(compile_hlsl, compiler, kind, FULLSCREEN_VS, 'vs_%s' % kind, vs_profile, directory) + grad = queue.call(compile_hlsl, compiler, kind, hlsl, 'grad_%s' % kind, ps_profile, directory) + run = run_draw(renderer, adapter, vs, grad, want, sampler) + if run.returncode == 77: + print(run.stdout + run.stderr) + sys.exit(77) + if run.returncode != 0: + raise AssertionError('%s image_sample_d draw failed:\n%s\n%s' % (kind, run.stdout, run.stderr)) + print('%s image_sample_d: %s' % (kind, want), flush=True) + + capped_run = run_draw(renderer, adapter, vs, grad, want, capped) + if capped_run.returncode == 0 or ('actual=' + mip0) not in capped_run.stderr: + raise AssertionError('%s capped-sampler mutant did not produce mip 0:\n%s\n%s' + % (kind, capped_run.stdout, capped_run.stderr)) + print('%s mutant MAX_LOD 0 caught' % kind, flush=True) + + flat = queue.call(compile_hlsl, compiler, kind, implicit, 'flat_%s' % kind, ps_profile, directory) + flat_run = run_draw(renderer, adapter, vs, flat, want, sampler) + if flat_run.returncode == 0 or ('actual=' + mip0) not in flat_run.stderr: + raise AssertionError('%s implicit-Sample mutant did not produce mip 0:\n%s\n%s' + % (kind, flat_run.stdout, flat_run.stderr)) + print('%s mutant implicit Sample caught' % kind, flush=True) + + +def main(): + if len(sys.argv) == 1: + controls() + elif len(sys.argv) in (5, 6) and sys.argv[1] == 'draw': + controls() + check_draw(*sys.argv[2:]) + else: + raise SystemExit(__doc__) + + +if __name__ == '__main__': + main() diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 3b4af0c56..9e3cde9cb 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -4833,6 +4833,27 @@ def image(self, ops, mods, how): if one and (how != 'sample' or len(cs) != 1 or not dmask or any(not m.startswith(('dim:', 'dmask:')) for m in mods)): raise Unsupported('unverified 1D image sample address or modifiers') lod = bias = None + grads = None + if how == 'd': + # Address dwords are ddx then ddy (one per coordinate axis each) and then the coordinates, so a 2D + # sample is six registers, a 2D array seven and a volume nine. Offsets, bias, clamp, a16 and the + # other layout-changing modifiers are refused; only cache-policy bits are accepted. + for m in mods: + if not (m.startswith(('dim:', 'dmask:')) or m in ('dlc', 'glc', 'slc')): + raise Unsupported('image_sample_d modifier %s' % m) + if dmask == 0: + raise Unsupported('image_sample_d with an empty dmask') + if one: + raise Unsupported('image_sample_d on a 1D image') + axes = 3 if dim == 'SQ_RSRC_IMG_3D' else 2 + want = 3 * axes + (1 if dim == 'SQ_RSRC_IMG_2D_ARRAY' else 0) + if want == 9 and len(cs) == 16 and not ops[1].startswith('['): + # A contiguous nine-dword volume address is encoded as a sixteen-register range; the rest is padding. + cs = cs[:9] + if len(cs) != want: + raise Unsupported('image_sample_d with %d address registers' % len(cs)) + grads = (cs[:axes], cs[axes:2 * axes]) + cs = cs[2 * axes:] if how in ('l', 'b'): # image_sample_l: the address dwords are the coordinates and then the explicit level. image_sample_b: # the RDNA 2 ISA (section 8.2.5, "{ offset } { bias } { z-compare } { derivative } { body }") puts one @@ -4934,12 +4955,12 @@ def image(self, ops, mods, how): if heap or not words or self.default_sampler_words(words): raise Unsupported('image_get_lod with a sampler that is not constant (LOD limits and bias unknown)') smp = self.pipe.sampler(tuple(self.lod_sampler_words('image_get_lod', words)), lod_limits=True) - elif how in ('sample', 'l', 'lz') and (heap or (words and self.default_sampler_words(words))): + elif how in ('sample', 'l', 'lz', 'd') and (heap or (words and self.default_sampler_words(words))): # A heap sampler, or the fixed default that stands in for one, keeps its unbounded static LOD range: the # descriptor is read at run time, so its MIN_LOD, MAX_LOD and bias are not validated here (#2221). self.pipe.lod_unvalidated.add(name) smp = heap or self.pipe.sampler(tuple(words)) - elif how in ('sample', 'l', 'lz') and words: + elif how in ('sample', 'l', 'lz', 'd') and words: # A constant descriptor carries its LOD limits like image_sample_b, under the same bias and range # validation. A mip filter of 0 (base level only) keeps the ordinary sampler, as before: refusing it # would drop every pipeline with an all-zero inline sampler, and only the bias form needs it refused. @@ -4959,7 +4980,11 @@ def image(self, ops, mods, how): if how == 'sample' and self.kind == 'cs': # A compute lane has no pixel quad to supply derivatives; level 0 would be a guess. raise Unsupported('image_sample with implicit LOD in a compute program') - if how == 'l': + if how == 'd': + axes = len(grads[0]) + dx, dy = ['float%d(%s)' % (axes, ', '.join(self.f(r) for r in g)) for g in grads] + call = '%s.SampleGrad(%s, %s, %s, %s)' % (tex, smp, uv, dx, dy) + elif how == 'l': call = '%s.SampleLevel(%s, %s, %s)' % (tex, smp, uv, self.f(lod)) elif how == 'b': # SampleBias adds the bias to the implicit LOD, like the ISA's _B suffix ("Add this BIAS to the LOD @@ -5111,6 +5136,12 @@ def lod_sampler_words(self, name, words, mip_filter_none_ok=False): def op_image_sample_b(self, ops, mods): self.image(ops, mods, 'b') + def op_image_sample_d(self, ops, mods): + self.image(ops, mods, 'd') + + def op_image_sample_c_d(self, ops, mods): + raise Unsupported('image_sample_c_d: SampleCmpGrad needs shader model 6.8; only c and c_lz are lowered') + def op_image_get_lod(self, ops, mods): self.image(ops, mods, 'get_lod') From c461c847539e74244a59bd517cf9863a568ea0d4 Mon Sep 17 00:00:00 2001 From: SimSalabimse <83839581+SimSalabimse@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:50:18 +0100 Subject: [PATCH 019/240] tests: add source-built mesh57 loop refusal fixture (#2413 T6) (#2622) Prove tip translate_mesh57 refuses a back-edge outside the accepted group-memory exchanges by the named loop reason, with a mutant that drops the back-edge and an exact-string oracle. Co-authored-by: Cursor Agent Co-authored-by: SimSalabimse Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- .github/workflows/windows.yml | 2 + AGENTS.md | 1 + CMakeLists.txt | 3 + docs/experiments.md | 10 ++ tests/startup_mesh57_loop_refusal.s | 74 ++++++++++++ tests/startup_mesh57_loop_refusal_check.py | 128 +++++++++++++++++++++ 6 files changed, 218 insertions(+) create mode 100644 tests/startup_mesh57_loop_refusal.s create mode 100644 tests/startup_mesh57_loop_refusal_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 6ac6935fd..09345a2f4 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -86,6 +86,7 @@ jobs: (["tests/startup_gfx2hlsl_scalar_m0_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_waitcnt_depctr_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_mesh57_skeleton_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_mesh57_loop_refusal_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_cvt_alu_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_cvt_pk_u8_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_cvt_pk_int16_check.py", "binary", "llvm-mc-15"], {}), @@ -268,6 +269,7 @@ jobs: tests/startup_gfx2hlsl_scalar_m0_check.py \ tests/startup_gfx2hlsl_waitcnt_depctr_check.py \ tests/startup_mesh57_skeleton_check.py \ + tests/startup_mesh57_loop_refusal_check.py \ tests/startup_gfx2hlsl_scalar_shift64_bfe_check.py \ tests/startup_gfx2hlsl_readfirstlane_uniform_check.py \ tests/startup_gfx2hlsl_loop_constants_check.py \ diff --git a/AGENTS.md b/AGENTS.md index 92208393f..cd477f204 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -191,6 +191,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_scalar_m0_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_waitcnt_depctr_check.py ./out/pe-env/bin/python -B tests/startup_mesh57_skeleton_check.py +./out/pe-env/bin/python -B tests/startup_mesh57_loop_refusal_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_readfirstlane_uniform_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_loop_constants_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_join_symbols_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index c6788297b..bae96dbe6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3334,6 +3334,9 @@ if(EXISTS "${INTAKE_PYTHON}") # Slot 57 mesh requests (#2413): the one accepted group-memory shape translates; each mutation is refused. add_test(NAME startup_mesh57_skeleton COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_mesh57_skeleton_check.py") + # Slot 57 mesh loop refusal outside the accepted exchanges (#2413 T6); mutant drops the back-edge. + add_test(NAME startup_mesh57_loop_refusal COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_mesh57_loop_refusal_check.py") # Scalar SOPK accumulate: s_addk_i32 signed-overflow SCC and s_mulk_i32 against an integer reference. add_test(NAME startup_gfx2hlsl_sopk_accum COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_sopk_accum_check.py") diff --git a/docs/experiments.md b/docs/experiments.md index 8a03f32b7..c5e36d0f3 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9514,6 +9514,16 @@ and unproven wave masks remain unsupported. Use Append `draw ` for CPU-reference readback of the SCC paths and lane-masked if/else. +The `startup_mesh57_loop_refusal` check is a source-built program with the same +exchanges plus one deliberate back-edge after the count exchange +(`tests/startup_mesh57_loop_refusal.s`). Tip refuses it with +`slot 57 mesh: a loop outside the group-memory exchanges is not covered`. The +mutant replaces that back-edge with a second `s_nop` and must not stop on that +loop message. The oracle is an exact string match; a stub that only checks for +any `unsupported:` result would accept a wrong reason and is rejected by the +check. Host-only (no WARP/hardware draw). Run +`python -B tests/startup_mesh57_loop_refusal_check.py`, or the matching CTest. + A forward `s_cbranch_vccz` or `s_cbranch_vccnz` can also branch on the lane's VCC bit when EXEC is full and every incoming path last wrote VCC with a full-EXEC `v_cmp_*` from wave-uniform SGPRs or constants. A compare with a diff --git a/tests/startup_mesh57_loop_refusal.s b/tests/startup_mesh57_loop_refusal.s new file mode 100644 index 000000000..4303b7941 --- /dev/null +++ b/tests/startup_mesh57_loop_refusal.s @@ -0,0 +1,74 @@ +// Source-built slot 57 mesh fixture for #2413 item T6: the accepted group-memory exchanges plus one +// deliberate back-edge outside them. Tip translate_mesh57 must refuse that loop by name. +// Entry and buffer layout match tests/startup_mesh57_skeleton.s. +s_inst_prefetch 0x3 +s_mov_b64 exec, 1 +s_mov_b64 s[4:5], exec +s_and_b32 s6, s3, 0xf000000 +s_cbranch_scc1 7 // to the reading waves +v_lshrrev_b32 v5, 7, v5 +v_mov_b32 v6, 0 +ds_write_b32 v6, v5 offset:8 +s_waitcnt_depctr 0xffe3 +s_barrier +s_branch 4 // past the reading waves +s_barrier +v_mov_b32 v6, 0 +ds_read_b32 v5, v6 offset:8 +s_mov_b64 exec, -1 +s_bfe_u32 s6, s3, 0x40018 +s_lshl_b32 s7, s6, 6 +v_mbcnt_lo_u32_b32 v0, -1, s7 +v_mbcnt_hi_u32_b32 v0, -1, v0 +s_waitcnt lgkmcnt(0) +v_readfirstlane_b32 s12, v5 +s_load_dwordx4 s[16:19], s[10:11], 0 +s_mov_b32 s13, s8 +s_mov_b32 s14, s9 +s_barrier +s_cmp_eq_i32 s6, 0 +s_cbranch_scc0 16 // to the reading waves +s_mov_b64 exec, s[4:5] +s_cbranch_execz 7 // never taken: the saved mask is 1 +v_mov_b32 v1, s13 +v_mov_b32 v2, 0 +v_mov_b32 v3, s14 +ds_write_b32 v2, v1 +ds_write_b32 v2, v3 offset:4 +s_mov_b64 exec, -1 +s_waitcnt_depctr 0xffe3 +s_barrier +s_lshl_b32 s4, s13, 12 +s_or_b32 m0, s4, s14 +s_sendmsg sendmsg(MSG_GS_ALLOC_REQ) +s_branch 13 // past the reading waves +s_barrier +s_mov_b64 exec, s[4:5] +s_cbranch_execz 9 // never taken: the saved mask is 1 +v_mov_b32 v2, 0 +ds_read_b32 v1, v2 +ds_read_b32 v3, v2 offset:4 +s_waitcnt lgkmcnt(1) +v_readfirstlane_b32 s13, v1 +s_waitcnt lgkmcnt(0) +v_readfirstlane_b32 s14, v3 +s_mov_b64 exec, -1 +// Back-edge outside both modelled exchanges: s_branch -2 retargets the preceding s_nop. +s_nop 0 +s_branch -2 +v_cmpx_gt_i32 s14, v0 +v_and_b32 v4, 15, v0 +v_lshlrev_b32 v4, 4, v4 +buffer_load_dwordx4 v[16:19], v4, s[16:19], 0 offen +buffer_load_dwordx4 v[20:23], v4, s[16:19], 0 offen offset:192 +s_waitcnt vmcnt(0) +exp pos0 v16, v17, v18, v19 done +exp param0 v20, v21, v22, v23 +s_mov_b64 exec, -1 +v_cmpx_gt_i32 s13, v0 +v_and_b32 v4, 15, v0 +v_lshlrev_b32 v4, 2, v4 +buffer_load_dword v24, v4, s[16:19], 0 offen offset:384 +s_waitcnt vmcnt(0) +exp prim v24, off, off, off done +s_endpgm diff --git a/tests/startup_mesh57_loop_refusal_check.py b/tests/startup_mesh57_loop_refusal_check.py new file mode 100644 index 000000000..83f8da976 --- /dev/null +++ b/tests/startup_mesh57_loop_refusal_check.py @@ -0,0 +1,128 @@ +"""Slot 57 mesh loop refusal outside the accepted group-memory exchanges (#2413 T6). + +usage: startup_mesh57_loop_refusal_check.py + startup_mesh57_loop_refusal_check.py binary + +The source-built fixture (tests/startup_mesh57_loop_refusal.s) keeps the skeleton exchanges and inserts one +back-edge after the count exchange. Tip translate_mesh57 must refuse it with the named loop message. The mutant +replaces that back-edge with a second s_nop so the request no longer stops on the loop refusal (it translates +through the source-only path). A stubbed comparator that ignores the refusal string would accept a different +unsupported reason; this check uses an exact match so that stub fails. +""" +import os +from pathlib import Path +import re +import struct +import subprocess +import sys +import tempfile + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +import gfx2hlsl as G # noqa: E402 + +LOOP_REASON = 'slot 57 mesh: a loop outside the group-memory exchanges is not covered' +# Skeleton words through the count-exchange join (s_mov_b64 exec, -1), then s_nop; s_branch -2; then the body. +MESH = ( + 'bfa00003 befe0481 be84047e 8706ff03 0f000000 bf850007 2c0a0a87 7e0c0280 d8340008 00000506' + ' bfa3ffe3 bf8a0000 bf820004 bf8a0000 7e0c0280 d8d80008 05000006 befe04c1 9386ff03 00040018' + ' 8f078606 d7650000 00000ec1 d7660000 000200c1 bf8cc07f 7e180505 f4080405 fa000000 be8d0308' + ' be8e0309 bf8a0000 bf008006 bf840010 befe0404 bf880007 7e02020d 7e040280 7e06020e d8340000' + ' 00000102 d8340004 00000302 befe04c1 bfa3ffe3 bf8a0000 8f048c0d 887c0e04 bf900009 bf82000d' + ' bf8a0000 befe0404 bf880009 7e040280 d8d80000 01000002 d8d80004 03000002 bf8cc17f 7e1a0501' + ' bf8cc07f 7e1c0503 befe04c1 bf800000 bf82fffe 7d28000e 3608008f 34080884 e0381000 80041004' + ' e03810c0 80041404 bf8c3f70 f80008cf 13121110 f800020f 17161514 befe04c1 7d28000d 3608008f' + ' 34080882 e0301180 80041804 bf8c3f70 f8000941 00000018 bf810000').split() +# Mutant: the same program with the back-edge replaced by a second s_nop. +MUTANT = MESH[: MESH.index('bf82fffe')] + ['bf800000'] + MESH[MESH.index('bf82fffe') + 1:] +PIXEL = 'c8020002 c8060102 c80a0202 c80e0302 f800180f 03020100 bf810000'.split() + +FAILED = [] + + +def expect(what, got, want): + if got != want: + FAILED.append(what) + print('FAIL %s: got %r, want %r' % (what, got, want)) + + +def code(words): + return b''.join(struct.pack(' Date: Thu, 26 Nov 2026 00:55:12 +0100 Subject: [PATCH 020/240] shader: propagate descriptor pointers through s_add_u32/s_addc_u32 in gfx2hlsl (Part of #1723) (#2069) * fix: carry descriptor pointers through s_add_u32/s_addc_u32 in gfx2hlsl A table or root pointer advanced by a literal offset now keeps its source and byte offset, so a following s_load reads the advanced descriptor. A register addend on a pointer is refused instead of silently keeping the old pointer. Part of #1723 * shader: refuse descriptor pointer advances across branches and detached s_addc_u32 in gfx2hlsl (Part of #1723) * shader: keep the pointer-advance bookkeeping safe for stages without branch state (Part of #1723) * fix: keep the branch-join refusal for pointer adds in branching shaders * fix: require the matching high-word add before folding an advanced descriptor pointer * fix: advance 32-bit table pointers without a high word and judge the high operand by content * fix: keep descriptor pointer pair open until its matching s_addc_u32 * fix: let the descriptor pointer pair pass translate's SCC check, add WARP readback case * fix: refuse an untracked-offset pointer as a descriptor, run the pointer check in Linux CI * fix: refuse a root pointer load whose high word was overwritten * Revert "fix: refuse a root pointer load whose high word was overwritten" This reverts commit 0f226c5cb04d401951ef0dded42ce9f8c4f528f5. --- .github/workflows/windows.yml | 1 + CMakeLists.txt | 4 + tests/startup_gfx2hlsl_desc_ptr_prop_check.py | 225 ++++++++++++++++++ tests/startup_smem_address_check.py | 43 ++++ tools/startup/gfx2hlsl.py | 92 ++++++- 5 files changed, 362 insertions(+), 3 deletions(-) create mode 100644 tests/startup_gfx2hlsl_desc_ptr_prop_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 09345a2f4..4cb608731 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -332,6 +332,7 @@ jobs: tests/startup_gfx2hlsl_getpc_refusal_check.py \ tests/startup_gfx2hlsl_image_arity_check.py \ tests/startup_compute_lds_dual_atomics_check.py \ + tests/startup_gfx2hlsl_desc_ptr_prop_check.py \ tests/run_checks_parallel_check.py build-and-test: name: Build and test on Windows diff --git a/CMakeLists.txt b/CMakeLists.txt index bae96dbe6..1c36f54b3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3196,6 +3196,10 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME startup_gfx2hlsl_op_refusals COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_op_refusals_check.py") set_tests_properties(startup_gfx2hlsl_op_refusals PROPERTIES TIMEOUT 60) + # gfx2hlsl carries a descriptor pointer through s_add_u32 / s_addc_u32 with a literal offset (#1723). + add_test(NAME startup_gfx2hlsl_desc_ptr_prop COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_desc_ptr_prop_check.py") + set_tests_properties(startup_gfx2hlsl_desc_ptr_prop PROPERTIES TIMEOUT 60) # gfx2hlsl refuses a binary32 or integer vector operation with a source too few or too many. add_test(NAME startup_gfx2hlsl_operand_count COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_operand_count_check.py") diff --git a/tests/startup_gfx2hlsl_desc_ptr_prop_check.py b/tests/startup_gfx2hlsl_desc_ptr_prop_check.py new file mode 100644 index 000000000..96b082b72 --- /dev/null +++ b/tests/startup_gfx2hlsl_desc_ptr_prop_check.py @@ -0,0 +1,225 @@ +"""Check descriptor pointer propagation through s_add_u32 / s_addc_u32 in tools/startup/gfx2hlsl.py (#1723). + +usage: startup_gfx2hlsl_desc_ptr_prop_check.py + +A shader advances a descriptor table or root pointer with `s_add_u32 sD, sP, ` and +`s_addc_u32 sD+1, sP+1, 0`, into the same or another register pair, then loads descriptors through +the result. The load must read at the advanced byte offset. A non-literal addend must be refused, +never silently treated as the unchanged pointer. +""" +import os +import sys + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup')) +import gfx2hlsl as G # noqa: E402 + +failures = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH ' + detail}") + if not condition: + failures.append(label) + + +class Pipe: + sampler_heap = False + + def __init__(self): + self.keys = [] + self.modified = set() + + def ud(self, key): + return 'ud_%s' % '_'.join(map(str, key)) + + def resource(self, key, kind): + if (key, kind) not in self.keys: + self.keys.append((key, kind)) + return 'r%d' % self.keys.index((key, kind)) + + +def stage(symbols): + s = G.Stage.__new__(G.Stage) + s.pipe, s.sym, s.lines = Pipe(), dict(symbols), [] + s.used_s, s.used_v, s.uniform_v, s.exec_known = set(), set(), set(), True + s.masks, s.varying_s = set(), set() + s.scc_uniform = True + return s + + +def run(symbols, program, branches=False): + """Symbols after the (op, operands) steps, or the Unsupported message.""" + s = stage(symbols) + s.has_branches = branches + s.ins = [(4 * i, 4, op, '') for i, (op, _operands) in enumerate(program)] + try: + for i, (op, operands) in enumerate(program): + s.pc = 4 * i + if op == 's_load_dwordx4': + s.op_s_load_dwordx4(operands.split(', '), []) + else: + s.lower(op, '%s %s' % (op, operands), operands.split(', '), []) + except G.Unsupported as error: + return 'refused: %s' % error + return s + + +TABLE = {8: ('ptr', ('table', 0))} # a table pointer is 32 bits wide: no high word +ROOT = {8: ('ptr', ('root', 1)), 9: ('ptrhi', ('root', 1))} +ADVANCE = [('s_add_u32', 's20, s8, 0x40'), ('s_addc_u32', 's21, s9, 0')] +TABLE_ADVANCE = [('s_add_u32', 's20, s8, 0x40')] +LOAD = [('s_load_dwordx4', 's[4:7], s[20:21], 0x10')] + +s = run(TABLE, TABLE_ADVANCE + LOAD) +check('table pointer advanced into another pair, descriptor read at pointer + 0x40 + 0x10', + not isinstance(s, str) and s.sym.get(4) == ('desc', ('table', 0), 0x50, 0), str(s if isinstance(s, str) else s.sym)) + +same = [('s_add_u32', 's8, s8, 0x20')] +s = run(TABLE, same + [('s_load_dwordx4', 's[4:7], s[8:9], 0')]) +check('table pointer advanced in place', + not isinstance(s, str) and s.sym.get(4) == ('desc', ('table', 0), 0x20, 0), str(s if isinstance(s, str) else s.sym)) + +twice = [('s_add_u32', 's20, s8, 0x40'), ('s_add_u32', 's22, s20, 0x10')] +s = run(TABLE, twice + [('s_load_dwordx4', 's[4:7], s[22:23], 0x4')]) +check('two advances add up', + not isinstance(s, str) and s.sym.get(4) == ('desc', ('table', 0), 0x54, 0), str(s if isinstance(s, str) else s.sym)) + +s = run(ROOT, ADVANCE + LOAD) +check('root constant-buffer pointer advanced, buffer read at the advanced offset', + not isinstance(s, str) and any('Load(80)' in line for line in s.lines), str(s if isinstance(s, str) else s.lines)) + +s = run(TABLE, [('s_add_u32', 's8, s8, s2')]) +check('a register addend on a pointer is refused', isinstance(s, str) and 'non-literal' in s, str(s)) + +s = run(ROOT, ADVANCE + [('s_load_dwordx4', 's[4:7], s[20:21], s2')]) +check('a register offset through an advanced pointer is still refused', isinstance(s, str), str(s)) + +# The untracked-offset mark of a branchy program must be refused here too, never a TypeError. +s = stage({8: ('ptr', ('root', 1), 'added'), 9: ('ptrhi', ('root', 1))}) +try: + s.descriptor('s[8:9]') + check('an untracked-offset pointer used whole as a descriptor is refused', False, 'accepted') +except G.Unsupported: + check('an untracked-offset pointer used whole as a descriptor is refused', True) + +s = run(ROOT, ADVANCE) +try: + s.descriptor('s[20:21]') + check('an advanced pointer used whole as a descriptor is refused', False, 'accepted') +except G.Unsupported: + check('an advanced pointer used whole as a descriptor is refused', True) + +s = run(ROOT, ADVANCE, branches=True) +check('a pointer advance in a program with branches is refused', isinstance(s, str), str(s)) + +# The high-word add is the carry of the low-word add right before it, never of an unrelated carry in SCC. +s = run(ROOT, [('s_cmp_eq_u32', '0, 0'), ('s_addc_u32', 's9, s9, 0')]) +check('s_addc_u32 without the low-word add is refused', isinstance(s, str), str(s)) + +s = run(ROOT, [ADVANCE[0], ('s_cmp_eq_u32', '0, 0'), ADVANCE[1]]) +check('s_addc_u32 separated from its low-word add is refused', isinstance(s, str), str(s)) + +# A fold needs the complete matching pair: the load must not trust the low word alone. +LOW = ADVANCE[0] +s = run(ROOT, [LOW] + LOAD) +check('missing high-word add is refused', isinstance(s, str), str(s)) + +s = run(ROOT, [('s_add_u32', 's8, s8, 0x20'), ('s_load_dwordx4', 's[4:7], s[8:9], 0')]) +check('missing high-word add in place is refused', isinstance(s, str), str(s)) + +s = run(ROOT, ADVANCE + [('s_mov_b32', 's21, 0')] + LOAD) +check('overwritten high word is refused', isinstance(s, str), str(s)) + +mixed = dict(ROOT) +mixed[10], mixed[11] = ('ptr', ('root', 2)), ('ptrhi', ('root', 2)) +s = run(mixed, [LOW, ('s_addc_u32', 's21, s11, 0')] + LOAD) +check('high word from another pointer is refused', isinstance(s, str), str(s)) + +s = run(mixed, [LOW, ('s_addc_u32', 's21, s10, 0')] + LOAD) +check('high word from a different register pair is refused', isinstance(s, str), str(s)) + +s = run(ROOT, [('s_add_u32', 's20, s8, 0xfffff'), ('s_addc_u32', 's21, s9, 0')] + LOAD) +check('complete pair with a large low-word add is folded', + not isinstance(s, str) and any('Load(%d)' % (0xfffff + 0x10) in line for line in s.lines), str(s)) + +# The high word is bound to the accumulated offset: the original word never stands in for an advanced one. +s = run(ROOT, ADVANCE + [('s_mov_b32', 's21, s9')] + LOAD) +check('completed high word overwritten by the original one is refused', isinstance(s, str), str(s)) + +SECOND = [('s_add_u32', 's22, s20, 0x20')] +s = run(ROOT, ADVANCE + SECOND + [('s_addc_u32', 's23, s9, 0'), ('s_load_dwordx4', 's[4:7], s[22:23], 0x10')]) +check('second advance with the original high word is refused', isinstance(s, str), str(s)) + +s = run(ROOT, ADVANCE + SECOND + [('s_addc_u32', 's23, s21, 0'), ('s_load_dwordx4', 's[4:7], s[22:23], 0x10')]) +check('second advance with the completed high word of the first pair is folded', + not isinstance(s, str) and any('Load(%d)' % (0x40 + 0x20 + 0x10) in line for line in s.lines), str(s)) + +s = run(ROOT, [('s_add_u32', 's8, s8, 0x20'), ('s_addc_u32', 's9, s9, 0'), ('s_add_u32', 's8, s8, 0x20'), + ('s_addc_u32', 's9, s9, 0'), ('s_load_dwordx4', 's[4:7], s[8:9], 0')]) +check('in-place advance twice with each completed high word is folded', + not isinstance(s, str) and any('Load(64)' in line for line in s.lines), str(s)) + +# Real entry state: a table pointer is one 32-bit register with no high word, so it advances with +# the low add alone and its neighbour register stays untouched. +def entry(params, kind='vs'): + s = stage({}) + s.kind, s.pipe.root = kind, {'params': params, 'flags': 0} + s.setup_entry() + return s.sym + + +REAL = entry([{'type': 0}, {'type': 2}]) +s = run(REAL, [('s_add_u32', 's20, s8, 0x40')] + LOAD) +check('real table pointer advanced by the low add alone, descriptor read at +0x50', + not isinstance(s, str) and s.sym.get(4) == ('desc', ('table', 0), 0x50, 0), str(s)) + +s = run(REAL, [('s_add_u32', 's8, s8, 0x40'), ('s_load_dwordx4', 's[4:7], s[8:9], 0x10')]) +check('real table pointer advanced in place keeps the next register symbol', + not isinstance(s, str) and s.sym.get(9) == REAL[9] and s.sym.get(4) == ('desc', ('table', 0), 0x50, 0), str(s)) + +s = run(REAL, [('s_add_u32', 's20, s9, 0x40'), ('s_addc_u32', 's21, s10, 0')] + LOAD) +check('real root pointer pair advanced through the load', + not isinstance(s, str) and any('Load(80)' in line for line in s.lines), str(s)) + +s = run(REAL, [('s_add_u32', 's20, s9, 0x40')] + LOAD) +check('real root pointer without its high add is refused', isinstance(s, str), str(s)) + +copied = dict(ROOT) +copied[30] = ('ptrhi', ('root', 1)) +s = run(copied, [LOW, ('s_addc_u32', 's21, s30, 0')] + LOAD) +check('a copied high word completes the pair', not isinstance(s, str), str(s)) + +viam0 = dict(ROOT) +viam0['m0'] = ('ptr', ('root', 1)) +s = run(viam0, [('s_add_u32', 's20, m0, 0x40'), ('s_addc_u32', 's21, s9, 0')] + LOAD) +check('a low word held in m0 completes the pair', not isinstance(s, str), str(s)) + +# A program with branches does not track the added offset: the load through the advanced pointer is a refusal +# (never a crash), and the same straight-line shape keeps folding. +IN_PLACE = [('s_add_u32', 's8, s8, 0x40'), ('s_load_dwordx4', 's[4:7], s[8:9], 0x10')] +s = run(TABLE, IN_PLACE, branches=True) +check('in-place pointer advance then load in a program with branches is refused, not a crash', + isinstance(s, str) and 'untracked offset' in s, str(s)) + +s = run(TABLE, IN_PLACE) +check('the same in-place advance without branches still folds to +0x50', + not isinstance(s, str) and s.sym.get(4) == ('desc', ('table', 0), 0x50, 0), str(s if isinstance(s, str) else s.sym)) + +# The pair is complete only after its s_addc_u32: an in-place pair folds, and a high word that was only +# copied (never advanced) must not stand in for it. +s = run(ROOT, [('s_add_u32', 's8, s8, 0x20'), ('s_addc_u32', 's9, s9, 0'), + ('s_load_dwordx4', 's[4:7], s[8:9], 0x10')]) +check('complete in-place pair folds to +0x30', + not isinstance(s, str) and any('Load(%d)' % 0x30 in line for line in s.lines), str(s if isinstance(s, str) else s.lines)) + +s = run(ROOT, [ADVANCE[0], ('s_mov_b32', 's21, s9')] + LOAD) +check('out-of-place low add with a copied, unadvanced high word is refused', isinstance(s, str), str(s)) + +s = run(ROOT, [ADVANCE[0], ADVANCE[1]] + LOAD) +check('complete out-of-place pair leaves the original high source untouched', + not isinstance(s, str) and s.sym.get(9) == ('ptrhi', ('root', 1)), str(s if isinstance(s, str) else s.sym)) + +if failures: + print('FAILED: %s' % ', '.join(failures)) + sys.exit(1) +print('startup_gfx2hlsl_desc_ptr_prop: ok') diff --git a/tests/startup_smem_address_check.py b/tests/startup_smem_address_check.py index e2d53f0f3..ba169a9e8 100644 --- a/tests/startup_smem_address_check.py +++ b/tests/startup_smem_address_check.py @@ -291,6 +291,22 @@ def controls(): for word in words[:64]: assert 0 < ((word >> 23) & 0xff) < 0xff, hex(word) + # 10. A complete s_add_u32/s_addc_u32 table-pointer pair goes through the full translate() (with its SCC + # check) and reads the same bytes as the single load at the summed offset; any other SCC reader is refused. + assert build_smem_pointer_pair_pipeline().hlsl_vs() == build_smem_dwordx4_pipeline().hlsl_vs() + vs_scc = b''.join(( + encode_sop2(0x00, 20, 0, 128 + 8), + encode_sop2(0x04, 21, 1, 128 + 0), + encode_sop2(0x0a, 30, 129, 128), # s_cselect_b32 s30, 1, 0 reads the carry + encode_smem(SMEM_LOAD_DWORDX4, 16, 20, soffset=125, imm=0x8), + struct.pack('<3I', 0xf80008cf, 0x07060504, 0xbf810000), + )) + try: + G.Pipeline(vs_scc, struct.pack('<3I', 0xf800180f, 0, 0xbf810000), root_with_one_constant()).hlsl_vs() + raise AssertionError('an independent SCC read after the pointer pair was accepted') + except G.Unsupported as error: + assert 'scc' in str(error), error + # ---- D3D12 GPU readback cases ------------------------------------------------------------------------- @@ -309,6 +325,24 @@ def build_smem_dwordx4_pipeline(): return G.Pipeline(vs, ps, root_with_one_constant()) +def build_smem_pointer_pair_pipeline(): + """Same loads as build_smem_dwordx4_pipeline, but the vertex-buffer table pointer s[0:1] is advanced by a complete + s_add_u32 s20, s0, 8 / s_addc_u32 s21, s1, 0 pair and the load adds offset:0x8 (total 0x10).""" + vs = b''.join(( + encode_sop2(0x00, 20, 0, 128 + 8), # s_add_u32 s20, s0, 8 + encode_sop2(0x04, 21, 1, 128 + 0), # s_addc_u32 s21, s1, 0 + encode_smem(SMEM_LOAD_DWORDX4, 16, 20, soffset=125, imm=0x8), + encode_smem(SMEM_BUFFER_LOAD_DWORDX4, 20, 16, soffset=8, imm=0x18, glc=1), + encode_vop1(0x01, 4, 20), + encode_vop1(0x01, 5, 21), + encode_vop1(0x01, 6, 22), + encode_vop1(0x01, 7, 23), + struct.pack('<3I', 0xf80008cf, 0x07060504, 0xbf810000), + )) + ps = struct.pack('<3I', 0xf800180f, 0, 0xbf810000) + return G.Pipeline(vs, ps, root_with_one_constant()) + + def build_smem_m0_and_overlap_pipeline(): """VS: m0 + offset:0x14 dlc, const SGPR + offset:0x08, and overlapping runtime SGPR s[20:21] + offset:0x1c glc.""" vs = b''.join(( @@ -416,6 +450,15 @@ def check_gpu(directory, compiler, consumer, adapter, fxc=None): print(f's_buffer_load_dwordx4 (soffset={soffset}, offset:0x18):', [l for l in res.stdout.splitlines() if 'mismatches=' in l][0]) + # 1b. Vertex-buffer table pointer advanced by a complete s_add_u32/s_addc_u32 pair must read the same bytes as case 1. + p_pair = build_smem_pointer_pair_pipeline() + res_pair = run_buffer_case(directory, compiler, consumer, adapter, p_pair, p_pair.hlsl_vs(), + expected_smem_dwordx4(soffset=32), soffset=32) + if res_pair.returncode: + raise RuntimeError('advanced vertex-buffer table pointer pair:\n' + res_pair.stdout + res_pair.stderr) + print('advanced vertex-buffer table pointer (s_add_u32 + s_addc_u32, offset:0x8):', + [l for l in res_pair.stdout.splitlines() if 'mismatches=' in l][0]) + # 2. m0 + offset:0x14 dlc and destination-overlapping runtime SGPR s[20:21] + offset:0x1c glc. p_m0 = build_smem_m0_and_overlap_pipeline() src_m0 = p_m0.hlsl_vs() diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 9e3cde9cb..eb0d6f7b9 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -620,6 +620,16 @@ def fbits(x): return struct.unpack(' ('s', 8, 11); 's8' -> ('s', 8, 8); 'v[1:3]' -> ('v', 1, 3); 'exec'/'vcc' pairs too.""" @@ -2110,6 +2120,8 @@ def descriptor(self, tok): # descriptors): its offset is the load's offset plus the first register's dword index. return s[1], (None if s[2] is None else s[2] + 4 * s[3]) if s and s[0] == 'ptr': + if len(s) > 2 and s[2]: + raise Unsupported('descriptor operand %s is a pointer with offset %s' % (tok, hex(s[2]) if isinstance(s[2], int) else s[2])) return s[1], None raise Unsupported('descriptor operand %s holds %s' % (tok, s)) @@ -2754,7 +2766,8 @@ def descriptor_scc_reads(self, branches, effects): continue seen.add((off, stale)) size, name, asm = instructions[off] - if stale and off not in self.calculated_pc and reads_scc(name, asm): + if (stale and off not in self.calculated_pc and off not in getattr(self, 'ptr_addc_pcs', ()) + and reads_scc(name, asm)): yield stale, name if off in effects: stale = effects[off] if effects[off] != 'emitted' else None @@ -3141,6 +3154,14 @@ def lower(self, base, asm, ops, mods): return self.set_v(reg_range(ops[0])[1], text.format(*args)) if base in SCA: return self.scalar(base, ops) + if base == 's_addc_u32': + # Only the high word of an advanced descriptor pointer; the carry is not modelled. + hi = reg_range(ops[1]) if len(ops) == 3 else None + if hasattr(self, 'scc_uniform') and self.tracks_uniformity(): + self.scc_uniform = False + if hi and hi[0] == 's' and self.pointer_add(base, ops[0], ops[1:], [self.sym.get(hi[1]), None]): + return None + raise Unsupported(base) if base == 's_getpc_b64': # RDNA 2 GETPC returns the address of its successor: the shader's load address plus a known byte # offset, which is not an integer this model can emit. It is elided only when the program also @@ -3392,6 +3413,54 @@ def sdwa(self, base, ops, mods): destination in self.low16_only_v) self.set_v(destination, sdwa_dest(result, select, unused, 'v%d' % destination), low16_only=keep_low16) + def pointer_add(self, base, dname, srcs, syms): + """Propagate a descriptor pointer through s_add_u32 sD, sP, / s_addc_u32 sD+1, sP+1, 0. + + The pair advances a table or root pointer by a literal byte offset, into the same or + another register pair. The offset rides in the low word as ('ptr', source, offset); the + high word keeps ('ptrhi', source). The low-word carry is taken as zero: the base is a + table or root address and the offset is below 1 MiB. Anything else returns False. + """ + if base not in ('s_add_u32', 's_addc_u32') or len(srcs) != 2 or not syms[0]: + return False + if getattr(self, 'has_branches', False): + # The symbolic update runs once in disassembly order; a branch could skip it or repeat it at run time. + return False + reg = reg_range(dname) + if not reg or reg[0] != 's' or reg[1] != reg[2] or reg[1] > 105: + return False + d = reg[1] + if base == 's_add_u32': + if syms[0][0] != 'ptr' or not re.fullmatch(r'(?:0[xX][0-9a-fA-F]+|\d+)', srcs[1]): + return False + added = int(srcs[1], 0) + if added > 0xfffff: + raise Unsupported('descriptor pointer offset %s' % srcs[1]) + before = syms[0][2] if len(syms[0]) > 2 else 0 + self.sym[d] = ('ptr', syms[0][1], before + added) + if syms[0][1][0] in PTR64_SOURCES and d + 1 <= 105: + # The carry-in of an s_addc_u32 is only the carry of this very add: remember where the next + # instruction starts so that the high-word add is accepted right behind it and nowhere else. + size = next((n for off, n, _name, _asm in getattr(self, 'ins', ()) if off == self.pc), 0) + self.ptr_low_add = (d, self.pc + size, syms[0][1], before, before + added) + # The pair stays open until the matching s_addc_u32 completes it. The high register is left as it + # is (in place it is still the original high source); a load through an open pair is refused. + self.__dict__.setdefault('ptr_open_pairs', set()).add(d) + return True + low = self.sym.get(d - 1) + mark = getattr(self, 'ptr_low_add', None) + hi = reg_range(srcs[0]) + # The high operand is judged by what it holds, not by where it sits: a copied high word still counts. + if (not mark or srcs[1] != '0' or not low or low[0] != 'ptr' or not hi or hi[0] != 's' + or mark[:2] != (d - 1, getattr(self, 'pc', 0)) or low[1] != mark[2] + or self.sym.get(hi[1]) != ptr_high_symbol(mark[2], mark[3])): + return False + self.sym[d] = ptr_high_symbol(mark[2], mark[4]) + getattr(self, 'ptr_open_pairs', set()).discard(d - 1) + # This s_addc_u32 is the only reader of the low add's elided carry; any other SCC reader stays refused. + self.__dict__.setdefault('ptr_addc_pcs', set()).add(self.pc) + return True + # scalar ALU with descriptor-word bookkeeping def exec_absorbed_source(self, base, srcs): """Index of a joined source of the instruction at a branch target whose stale value cannot reach bit 0 of @@ -3483,6 +3552,8 @@ def src_sym(t): raise Unsupported('scc from descriptor data') if word_pack: raise Unsupported('%s on descriptor data' % base) + if self.pointer_add(base, dname, srcs, syms): + return None if dname == 'm0': if scc: raise Unsupported('scc from descriptor data') @@ -3509,6 +3580,10 @@ def src_sym(t): self.sym[d + 1] = hi elif self.tracks_uniformity(): self.varying_s.add(d + 1) + elif (own and own[0] == 'ptr' and base in ('s_add_u32', 's_addc_u32') + and not getattr(self, 'has_branches', False)): + # With branches the offset is not tracked: the 'added' mark below stays, and the join refuses it. + raise Unsupported('%s adds a non-literal to a descriptor pointer' % base) elif raw is not None: self.sym[d] = raw if raw[0] == 'desc': @@ -3853,6 +3928,15 @@ def op_s_load_dwordx4(self, ops, mods, count=4): p = self.sym.get(base[1]) if not p or p[0] != 'ptr': raise Unsupported('s_load through s%d holding %s' % (base[1], p)) + if len(p) > 2 and not isinstance(p[2], int): + # The 'added' mark (an add whose offset is not tracked, as in a program with branches): no byte offset. + raise Unsupported('s_load through s%d: the pointer was advanced by an untracked offset' % base[1]) + base_off = p[2] if len(p) > 2 else 0 # literal bytes added by s_add_u32 on the pointer + if (base_off or len(p) > 2) and p[1][0] in PTR64_SOURCES: + # An advanced 64-bit pointer needs its high word completed by the matching s_addc_u32; + # a table pointer is 32 bits wide and has no high word. + if base[1] in getattr(self, 'ptr_open_pairs', ()) or self.sym.get(base[1] + 1) != ptr_high_symbol(p[1], base_off): + raise Unsupported('s_load through s%d: its high word is not the matching advanced pair' % base[1]) # 'off' names no offset operand at all, so the byte offset is zero, as for the literal 0. token = smem_offset(ops[2]) known = self.const_soffset(token) if p[1] != ('smpheap',) else None @@ -3874,7 +3958,7 @@ def op_s_load_dwordx4(self, ops, mods, count=4): raise Unsupported('s_load destination %s for %d dwords' % (ops[0], count)) buf = self.pipe.resource((p[1], None), 'buf') for i in range(count): - self.set_s(dst[1] + i, '%s.Load(%d)' % (buf, off + 4 * i)) + self.set_s(dst[1] + i, '%s.Load(%d)' % (buf, base_off + off + 4 * i)) return # The pointer symbol does not record an addend or a rewritten high word, so two loads through such a # pointer may read different words under the same (source, offset). In a compute or vertex stage (the @@ -3890,7 +3974,7 @@ def op_s_load_dwordx4(self, ops, mods, count=4): else: load = (self.pc,) for i in range(count): - self.sym[dst[1] + i] = ('desc', p[1], off, i) + load + self.sym[dst[1] + i] = ('desc', p[1], base_off + off, i) + load if into_vcc: self.vcc_lost = True self.vcc_descriptor_overwritten = False @@ -3900,6 +3984,8 @@ def op_s_load_dwordx4(self, ops, mods, count=4): return if into_vcc: raise Unsupported('s_load destination %s for %d dwords' % (ops[0], count)) + if base_off: + raise Unsupported('s_load through %s advanced by %#x' % (p[1], base_off)) if p[1] == ('smpheap',): if self.pipe.sampler_heap and count == 4: # A sampler picked at run time from the sampler heap: keep the byte offset in the From d01afa7bef34afaea966ce559001c71c7cd13749 Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:56:42 +0100 Subject: [PATCH 021/240] startup: re-key slot 57 mesh requests in shader_cache_rekey.py (#2634) shader_cache_rekey.py re-keyed graphics, RTV and slot 67 compute requests and only counted slot 57 mesh requests. mesh57_key hashes the request files under a versioned prefix, so after a revision that changes it a kept cache lost every slot 57 request. The tool now recomputes that key with mesh57_key and copies .ps57, .root and the .m57 ready marker under the new name, with the rules the other kinds follow: everything read first, nothing written on a missing or unreadable part, temporary name then rename, an existing target left alone. Slot 86 is still only counted. AI-assisted. --- docs/startup-runtime.md | 6 +- tests/startup_shader_cache_rekey_check.py | 57 +++++++++++++------ tests/startup_shader_cache_rekey_cli_check.py | 4 +- tools/startup/shader_cache_rekey.py | 30 +++++----- 4 files changed, 63 insertions(+), 34 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index e38af186e..d2bf02406 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1105,7 +1105,7 @@ Archive each run's logs together with a copy of `shader_cache/`, and leave the c When the translator handles more, the next `--pending` pass retries the waiting requests from the same cache. This holds only while the pipeline key is unchanged. The key hashes a translation revision string (`x2w-startup-shader-N`, in `pipeline_key` in `gfx2hlsl.py` and in the runtime). After a revision change the runtime asks for new keys, and the old requests stay in the cache. -**Re-key the old requests after a revision change.** The new cache is cold, so a run would have to request every pipeline again. `tools/startup/shader_cache_rekey.py` copies the graphics, RTV variant and slot 67 compute requests of the old cache under the keys of the current revision, computed with `pipeline_key` and `compute_key` of the `gfx2hlsl.py` next to it. Stop the title and any `--pending` loop first; nothing else may write the cache. Then: +**Re-key the old requests after a revision change.** The new cache is cold, so a run would have to request every pipeline again. `tools/startup/shader_cache_rekey.py` copies graphics, RTV variant, slot 67 compute and slot 57 mesh requests under their current keys. It uses `pipeline_key`, `compute_key` and `mesh57_key` from the adjacent `gfx2hlsl.py` and updates each RTV variant with its new graphics key. Stop the title and any `--pending` loop first; nothing else may write the cache. Then: ```powershell .\out\pe-env\Scripts\python.exe -B tools\startup\shader_cache_rekey.py out\startup\shader_cache out\startup\shader_cache_rekeyed @@ -1113,11 +1113,11 @@ When the translator handles more, the next `--pending` pass retries the waiting robocopy out\startup\shader_cache_rekeyed out\startup\shader_cache /XC /XN /XO ``` -1. The re-key step only reads the old cache and writes request files (`req_*`) only, never results or `.fail`. A file already in the new directory is left as it is, so a second run writes nothing. It reads every request before it writes: if a part is missing or unreadable, or an RTV variant is malformed or names a base that is not in the cache, it prints how many, writes nothing and exits with 1. Slot 57 and slot 86 mesh requests have their own key strings and are not re-keyed. `X2W_TRANSLATE_JOBS` sets the number of hashing processes. +1. The re-key step reads the old cache and writes only request files (`req_*`). A file already in the new directory is left as it is, so a second run writes nothing. It reads every request before it writes. If a part is missing or unreadable, or an RTV variant is malformed or names a base that is not in the cache, it prints how many, writes nothing and exits with 1. A slot 57 request requires `.ps57`, `.root` and the `.m57` ready marker. The `.ps57` file is empty when there is no pixel stage. Slot 86 mesh requests are only counted. `X2W_TRANSLATE_JOBS` sets the number of hashing processes. 2. `--pending` translates the re-keyed requests offline, as it does for a running title's cache. 3. The `robocopy` switches skip every file that already exists in the cache, so results the runtime or a later pass wrote are kept. A `robocopy` exit code below 8 means success: 1 is set when files were copied, and 2 is set because the cache holds files that the new directory does not. A code of 8 or more is a failure. On Linux, run the same steps with `./out/pe-env/bin/python` and merge with `cp -rn out/startup/shader_cache_rekeyed/. out/startup/shader_cache/`, which also keeps existing files. -`tests/startup_shader_cache_rekey_check.py` checks the tool on synthetic requests only: the names match the current keys, a newer revision gives other names, a second run and a current cache change nothing, and an incomplete request or an RTV variant without its base writes nothing. Re-keying recovers the requests, not the translations: some re-keyed pipelines can still fail to translate, which is separate from the cache key. Nothing here shows that a title runs. +`tests/startup_shader_cache_rekey_check.py` checks the tool on synthetic requests only: the names match the current keys, a newer graphics and compute revision gives other names for those requests, a second run and a current cache change nothing, and an incomplete request or an RTV variant without its base writes nothing. Re-keying recovers the requests, not the translations: some re-keyed pipelines can still fail to translate, which is separate from the cache key. Nothing here shows that a title runs. When `fxc` is available, a request that later translates loses its `.fail`. In manifest-only mode (`X2W_FXC` empty) the old `.fail` stays, so on a kept cache the `.fail` categories in `triage.md` can include pipelines that now have a `.txt`. That table counts category tokens over all `.fail` files, up to `--max-items`. diff --git a/tests/startup_shader_cache_rekey_check.py b/tests/startup_shader_cache_rekey_check.py index fc9a5ffa1..978639b90 100644 --- a/tests/startup_shader_cache_rekey_check.py +++ b/tests/startup_shader_cache_rekey_check.py @@ -6,11 +6,11 @@ - An old cache holds requests of the older revision (two graphics requests, one with an input layout, one compute request, an RTV variant of the first graphics request), one current-revision graphics request, the same - pipeline as the first at the current revision, a mesh request, a result and a .fail. Their old names differ - from pipeline_key / compute_key of the current revision. + pipeline as the first at the current revision, an old and a current slot 57 mesh request, a slot 86 marker, + a result and a .fail. Old request names differ from the current pipeline_key, compute_key or mesh57_key. - The tool, run as a script with two hashing processes, writes exactly the current names with the same bytes (the RTV variant re-keyed to its new base), no results or .fail, and gfx2hlsl.pending_keys lists them. -- With the newer revision the same requests get other names again. +- With the newer graphics and compute revision those requests and the RTV variant get other names again. - A second run writes nothing; re-keying a current cache keeps every name. - A missing request part, a truncated RTV variant or an RTV variant whose base request is missing exits with 1 and creates nothing. @@ -75,12 +75,19 @@ def gkey(module, parts): COMPUTE = {'.desc': struct.pack('<12Q', *range(12)), '.sa': struct.pack('<7I', *range(7)), '.sb': b'\x05' * 20, '.data': struct.pack('<2Q', 0x1122334455667788, 0x99), '.root': b'RTS0 synthetic compute root', '.c67': struct.pack('<2I', 0x7e020280, 0xbf810000)} +MESH_OLD = {'.ps57': b'', '.root': b'RTS0 synthetic mesh root', '.m57': b'synthetic mesh'} +MESH_CURRENT = {'.ps57': b'synthetic pixel stage', '.root': b'RTS0 synthetic mesh root', + '.m57': b'another synthetic mesh'} def ckey(module, parts): return module.compute_key(parts['.c67'], parts['.data'], parts['.root'], parts['.desc'], parts['.sa'], parts['.sb']) +def mkey(module, parts): + return module.mesh57_key(parts['.m57'], parts['.ps57'], parts['.root']) + + def rtv_text(base): return 'rtv1 %d 28 87' % base @@ -108,7 +115,7 @@ def run(src, dst, jobs='2'): env=env, timeout=120) -def expected_files(module, requests, computes, rtv_bases): +def expected_files(module, requests, computes, rtv_bases, meshes): """{name: bytes} of the requests named under module's revision.""" files = {} for parts in requests: @@ -120,6 +127,9 @@ def expected_files(module, requests, computes, rtv_bases): for parts in rtv_bases: text = rtv_text(gkey(module, parts)).encode('ascii') files['req_%016x.rtv' % G.fnv(text)] = text + for parts in meshes: + for ext, data in parts.items(): + files['req_%016x%s' % (mkey(module, parts), ext)] = data return files @@ -143,7 +153,12 @@ def main(): old_rtv = write_rtv(src, gkey(older, g1)) write_request(src, gkey(G, g1), g1) # the same pipeline at the current revision write_request(src, gkey(G, g3), g3) # current only - write_request(src, 0x123456789abcdef0, {'.ps57': b'', '.root': b'RTS0 mesh', '.m57': b'\x01' * 8}) + meshes = (MESH_OLD, MESH_CURRENT) + old_mesh = mkey(G, MESH_OLD) ^ 1 + mesh_keys = {mkey(G, parts) for parts in meshes} + write_request(src, old_mesh, MESH_OLD) + write_request(src, mkey(G, MESH_CURRENT), MESH_CURRENT) + write_request(src, 0x123456789abcdef0, {'.m86': b'synthetic slot 86 marker'}) (src / ('%016x.txt' % gkey(older, g1))).write_text('synthetic result\n') (src / ('%016x.fail' % gkey(older, g2))).write_text('synthetic refusal\n') before = snapshot(src) @@ -152,22 +167,26 @@ def main(): current_names = {gkey(G, g1), gkey(G, g2), ckey(G, COMPUTE)} check('older-revision names differ from the current keys', not old_names & current_names) - # (a) re-keyed names are pipeline_key / compute_key of the current revision, with the same bytes. + # (a) re-keyed names use the current key functions, with the same bytes. dst = tmp / 'rekeyed' first = run(src, dst) check('re-key exits 0', first.returncode == 0, first.stderr.strip()) - want = expected_files(G, (g1, g2, g3), (COMPUTE,), (g1,)) + want = expected_files(G, (g1, g2, g3), (COMPUTE,), (g1,), meshes) got = contents(dst) if dst.is_dir() else {} check('re-keyed files are exactly the current requests', got == want, 'extra %s missing %s' % (sorted(set(got) - set(want)), sorted(set(want) - set(got)))) check('no results or .fail written', all(name.startswith('req_') for name in got)) check('graphics summary counts the duplicate and the current request', 'graphics: 4 requests, 2 already current -> 3 keys' in first.stdout, first.stdout) - check('mesh request counted, not re-keyed', 'm57 1, m86 0' in first.stdout, first.stdout) + check('mesh summary counts the old and current slot 57 requests', + 'm57: 2 requests, 1 already current -> 2 keys' in first.stdout, first.stdout) + check('slot 86 marker is only counted', 'not re-keyed (own key strings): m86 1' in first.stdout, + first.stdout) pending = G.pending_keys(str(dst), False) rtv_new = G.fnv(rtv_text(gkey(G, g1)).encode('ascii')) check('gfx2hlsl.pending_keys lists the re-keyed requests', - pending == sorted({gkey(G, g1), gkey(G, g2), gkey(G, g3), ckey(G, COMPUTE), rtv_new}), pending) + pending == sorted({gkey(G, g1), gkey(G, g2), gkey(G, g3), ckey(G, COMPUTE), rtv_new} | mesh_keys), + pending) # (e) the RTV variant names the new base and is named by the hash of its new text. rtv_file = dst / ('req_%016x.rtv' % rtv_new) @@ -186,7 +205,8 @@ def main(): third = run(dst, again, jobs='1') check('current requests keep their names', third.returncode == 0 and contents(again) == want and 'graphics: 3 requests, 3 already current -> 3 keys' in third.stdout - and 'compute: 1 requests, 1 already current -> 1 keys' in third.stdout, third.stdout + third.stderr) + and 'compute: 1 requests, 1 already current -> 1 keys' in third.stdout + and 'm57: 2 requests, 2 already current -> 2 keys' in third.stdout, third.stdout + third.stderr) # (b) under a newer revision the same requests get other names (in process: one job keeps the patch). R.g, saved = newer, R.g @@ -198,18 +218,23 @@ def main(): R.g = saved got_newer = contents(newest) if newest.is_dir() else {} check('newer revision re-keys to its own names', code == 0 - and got_newer == expected_files(newer, (g1, g2, g3), (COMPUTE,), (g1,))) - check('newer names differ from the current names', not set(got_newer) & set(want)) + and got_newer == expected_files(newer, (g1, g2, g3), (COMPUTE,), (g1,), meshes)) + check('only mesh names are shared between the graphics and compute revisions', + set(got_newer) & set(want) == set(expected_files(G, (), (), (), meshes))) # (f) negative controls: an incomplete request, a truncated RTV variant or an RTV variant without its base - # request writes nothing. Without the base's ready marker (.a) there is one graphics request less: 5, not 6. + # request writes nothing. Without the base's ready marker (.a), the request count drops from 8 to 7. for label, total, reason, damage in ( - ('missing .root', 6, 'unreadable req_%016x.root' % gkey(older, g2), + ('missing .root', 8, 'unreadable req_%016x.root' % gkey(older, g2), lambda d: (d / ('req_%016x.root' % gkey(older, g2))).unlink()), - ('truncated RTV variant', 6, '.rtv text does not hash to its name', + ('missing slot 57 .root', 8, 'unreadable req_%016x.root' % old_mesh, + lambda d: (d / ('req_%016x.root' % old_mesh)).unlink()), + ('missing slot 57 .ps57', 8, 'unreadable req_%016x.ps57' % old_mesh, + lambda d: (d / ('req_%016x.ps57' % old_mesh)).unlink()), + ('truncated RTV variant', 8, '.rtv text does not hash to its name', lambda d: (d / ('req_%016x.rtv' % old_rtv)).write_bytes( rtv_text(gkey(older, g1)).encode('ascii')[:-3])), - ('missing RTV base', 5, '.rtv base request %016x is not a complete graphics request' % gkey(older, g1), + ('missing RTV base', 7, '.rtv base request %016x is not a complete graphics request' % gkey(older, g1), lambda d: (d / ('req_%016x.a' % gkey(older, g1))).unlink())): bad = tmp / ('bad_' + label.replace(' ', '_')) shutil.copytree(src, bad) diff --git a/tests/startup_shader_cache_rekey_cli_check.py b/tests/startup_shader_cache_rekey_cli_check.py index c8bee38eb..39a3f850a 100644 --- a/tests/startup_shader_cache_rekey_cli_check.py +++ b/tests/startup_shader_cache_rekey_cli_check.py @@ -80,7 +80,7 @@ def test_positive_main_argv_none_and_subprocess(self): rc, stdout, stderr = _run_main([str(src), str(dst_argv)]) self.assertEqual(rc, 0, stderr) self.assertEqual(stderr, "") - self.assertIn("m57 0, m86 1", stdout) + self.assertIn("not re-keyed (own key strings): m86 1", stdout) expected_names = sorted([ f"req_{keys['g']:016x}.a", f"req_{keys['g']:016x}.b", @@ -116,7 +116,7 @@ def test_positive_main_argv_none_and_subprocess(self): ) self.assertEqual(proc.returncode, 0, proc.stderr) self.assertEqual(proc.stderr, "") - self.assertIn("m57 0, m86 1", proc.stdout) + self.assertIn("not re-keyed (own key strings): m86 1", proc.stdout) self.assertEqual(sorted(p.name for p in dst_sub.iterdir()), expected_names) def test_usage_and_path_guards(self): diff --git a/tools/startup/shader_cache_rekey.py b/tools/startup/shader_cache_rekey.py index 2e49127a8..64db2d903 100644 --- a/tools/startup/shader_cache_rekey.py +++ b/tools/startup/shader_cache_rekey.py @@ -3,16 +3,16 @@ usage: shader_cache_rekey.py -The key of a graphics request (req_.a), of an RTV variant (req_.rtv) and of a device slot 67 compute -request (req_.c67) hashes the translation revision string (pipeline_key and compute_key in gfx2hlsl.py). +Graphics (req_.a), slot 67 compute (req_.c67) and slot 57 mesh (req_.m57) request keys hash their +translation revision strings (pipeline_key, compute_key and mesh57_key in gfx2hlsl.py). RTV variants +(req_.rtv) hash text containing the graphics key. After a revision change the runtime asks for new keys, so a kept cache is cold again. This tool recomputes the key of every such request with the gfx2hlsl.py next to it and copies the request files under the new names into . `gfx2hlsl.py --pending ` can then translate them without a running title. The old cache is only read. Only request files (req_*) are written; results and .fail files are not, and a file that already exists in is left as it is. Each file is written to a temporary name and renamed; -the ready marker (.a, .c67) goes last, as the runtime writes it. Slot 57 and slot 86 mesh requests have their own -key strings and are only counted. +the ready marker (.a, .c67, .m57) goes last, as the runtime writes it. Slot 86 mesh requests are only counted. All requests are read before anything is written. When a request part is missing or unreadable, or an RTV variant is malformed, does not match its own name or names a base request that is not in the cache, the tool @@ -29,7 +29,8 @@ REQUEST = re.compile(r'req_([0-9a-f]{16})\.(a|rtv|c67|m57|m86)') # Request files of each kind; the ready marker is last. -PARTS = {'g': ('.b', '.root', '.ia', '.a'), 'c': ('.desc', '.sa', '.sb', '.data', '.root', '.c67')} +PARTS = {'g': ('.b', '.root', '.ia', '.a'), 'c': ('.desc', '.sa', '.sb', '.data', '.root', '.c67'), + 'm57': ('.ps57', '.root', '.m57')} OPTIONAL = {'.ia'} # a graphics request without an input layout has no .ia @@ -61,6 +62,8 @@ def current_key(job): return kind, key, None, 'unreadable %s: %s' % (os.path.basename(error.filename or ''), error.strerror) if kind == 'g': return kind, key, g.pipeline_key(p['.a'], p['.b'], p['.root'], p.get('.ia', b'')), None + if kind == 'm57': + return kind, key, g.mesh57_key(p['.m57'], p['.ps57'], p['.root']), None return kind, key, g.compute_key(p['.c67'], p['.data'], p['.root'], p['.desc'], p['.sa'], p['.sb']), None @@ -111,7 +114,8 @@ def rekey(src, dst, jobs=None, out=None): if os.path.exists(dst) and os.path.samefile(src, dst): print('error: the new request dir must not be the old cache', file=sys.stderr) return 2 - found = {'g': [], 'c': [], 'rtv': [], 'm57': 0, 'm86': 0} + found = {kind: [] for kind in (*PARTS, 'rtv')} + m86 = 0 try: entries = sorted(os.listdir(src)) except OSError as error: @@ -122,12 +126,12 @@ def rekey(src, dst, jobs=None, out=None): if not m: continue key, ext = int(m.group(1), 16), m.group(2) - if ext in ('m57', 'm86'): - found[ext] += 1 + if ext == 'm86': + m86 += 1 else: - found[{'a': 'g', 'c67': 'c', 'rtv': 'rtv'}[ext]].append(key) + found[{'a': 'g', 'c67': 'c'}.get(ext, ext)].append(key) - work = [(src, kind, key) for kind in ('g', 'c') for key in found[kind]] + work = [(src, kind, key) for kind in PARTS for key in found[kind]] jobs = min(jobs or g.translation_jobs(), len(work)) if jobs < 2: results = [current_key(job) for job in work] @@ -136,7 +140,7 @@ def rekey(src, dst, jobs=None, out=None): with ProcessPoolExecutor(max_workers=jobs) as pool: results = list(pool.map(current_key, work, chunksize=max(1, len(work) // (jobs * 4)))) - new = {'g': {}, 'c': {}} + new = {kind: {} for kind in PARTS} bad = [] for kind, old, key, reason in results: if reason: @@ -165,7 +169,7 @@ def rekey(src, dst, jobs=None, out=None): return 1 stats = {'written': 0, 'kept': 0} try: - for kind, label in (('g', 'graphics'), ('c', 'compute')): + for kind, label in (('g', 'graphics'), ('c', 'compute'), ('m57', 'm57')): done = set() for old, key in sorted(new[kind].items()): if key in done: # requests of the same pipeline from several revisions @@ -182,7 +186,7 @@ def rekey(src, dst, jobs=None, out=None): print('error: failed writing %s: %s' % (dst, error), file=sys.stderr) return 1 print('rtv variants: %d requests -> %d keys' % (len(found['rtv']), len(rtv)), file=out) - print('not re-keyed (own key strings): m57 %d, m86 %d' % (found['m57'], found['m86']), file=out) + print('not re-keyed (own key strings): m86 %d' % m86, file=out) print('files: %d written, %d already present in %s' % (stats['written'], stats['kept'], dst), file=out) return 0 From 4f6a3f45ba6b69c7cb78ab7b34249276a384121c Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Thu, 26 Nov 2026 01:57:56 +0200 Subject: [PATCH 022/240] shader: extract main(argv), bounds checks, and struct/zlib guards in shader_census with CLI suite (#2437) * shader: extract main(argv), bounds checks, and struct/zlib guards in shader_census with CLI suite * tests: accept Python 3.14+ argparse message in shader_census_cli_check --------- Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 2 + tests/shader_census_cli_check.py | 296 +++++++++++++++++++++++++++++++ tools/shader_census.py | 33 ++-- 3 files changed, 319 insertions(+), 12 deletions(-) create mode 100644 tests/shader_census_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 1c36f54b3..cf4f5ec41 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -10263,6 +10263,8 @@ if(EXISTS "${INTAKE_PYTHON}") set_tests_properties(shader_rdna_cvt_pk_u8_cli_check PROPERTIES TIMEOUT 60) add_test(NAME shader_metadata_census COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/shader_census_check.py") + add_test(NAME shader_census_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/shader_census_cli_check.py") add_test(NAME shader_profile_audit_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/shader_profile_audit_check.py") add_test(NAME shader_profile_audit_cli_check COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/shader_census_cli_check.py b/tests/shader_census_cli_check.py new file mode 100644 index 000000000..d02e8fbd4 --- /dev/null +++ b/tests/shader_census_cli_check.py @@ -0,0 +1,296 @@ +"""Pure-Python CLI, boundary, error-guard, and mutation suite for tools/shader_census.py.""" +from __future__ import annotations + +from contextlib import redirect_stderr, redirect_stdout +import io +import json +from pathlib import Path +import struct +import subprocess +import sys +import tempfile +import unittest +from unittest import mock +import zlib + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "shader_census.py" +sys.path.insert(0, str(ROOT / "tools")) + +import shader_census as sc # noqa: E402 + + +def _make_dxbc(digest_byte: int, word: int, stage: int = 0) -> bytes: + program = struct.pack(" bytes: + encoder = zlib.compressobj(wbits=-15) + payload = encoder.compress(blob) + encoder.flush() + return ( + name.encode("ascii") + + b"\0\0" + + struct.pack("<4I", len(payload), 0, len(payload), len(blob)) + + payload + ) + + +def _make_archive() -> bytes: + a = _make_dxbc(1, 17, stage=0) + b = _make_dxbc(1, 18, stage=0) + c = _make_dxbc(2, 19, stage=5) + return _make_record(a) + _make_record(a) + _make_record(b) + _make_record(c) + + +def _make_ps9_cache(entries: list[tuple[int, int]] | None = None) -> tuple[bytes, int]: + entries = entries if entries is not None else [(0, 16), (16, 16), (0, 16), (32, 32)] + index_start = 128 + 0x70 + 2 * 0x18 + 3 * 8 + code_base = index_start + len(entries) * 8 + data = bytearray(code_base + 96) + data[:4] = b"PS\x00\x09" + struct.pack_into("<4I", data, 80, 1, 2, 3, len(entries)) + for i, (offset, size) in enumerate(entries): + struct.pack_into("<2I", data, index_start + i * 8, offset, size) + return bytes(data), code_base + + +class ShaderCensusCliTests(unittest.TestCase): + def _run_main(self, argv: list[str]) -> tuple[int, str, str]: + out, err = io.StringIO(), io.StringIO() + code = 0 + with redirect_stdout(out), redirect_stderr(err): + try: + ret = sc.main(argv) + code = 0 if ret is None else ret + except SystemExit as exc: + code = exc.code if isinstance(exc.code, int) else 1 + return code, out.getvalue(), err.getvalue() + + def _assert_main_fails(self, argv: list[str], *, expected_code: int, fragment: str | tuple[str, ...]) -> str: + code, stdout, stderr = self._run_main(argv) + self.assertEqual(code, expected_code, f"argv={argv!r} stderr={stderr!r}") + self.assertEqual(stdout, "") + self.assertNotIn("Traceback", stderr) + fragments = (fragment,) if isinstance(fragment, str) else fragment + self.assertTrue( + any(f in stderr for f in fragments), + f"none of {fragments!r} found in {stderr!r}", + ) + return stderr + + def test_main_argv_forwarding_and_json_schema(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + archive = root / "owned.archive" + cache = root / "decoded.cache" + archive.write_bytes(_make_archive()) + cache_bytes, base = _make_ps9_cache() + cache.write_bytes(cache_bytes) + + # Mutating sys.argv ensures main(argv) forwards its explicit argv parameter. + with mock.patch.object(sys, "argv", ["shader_census.py", "--bogus-global-flag"]): + for base_arg in (str(base), hex(base)): + out, err = io.StringIO(), io.StringIO() + with redirect_stdout(out), redirect_stderr(err): + rc = sc.main([str(archive), "--cache-blob", str(cache), "--code-base", base_arg]) + self.assertEqual(rc, 0) + self.assertEqual(err.getvalue(), "") + doc = json.loads(out.getvalue()) + self.assertEqual( + set(doc), + { + "archive_records", + "dxbc_header_digests", + "classification_cache", + "cache_index", + "candidate_rejections", + }, + ) + self.assertEqual(doc["archive_records"]["count"], 4) + self.assertEqual(doc["archive_records"]["stages"], {"pixel": 3, "compute": 1}) + self.assertTrue(doc["archive_records"]["coverage_denominator"]) + self.assertEqual(doc["dxbc_header_digests"]["count"], 2) + self.assertFalse(doc["dxbc_header_digests"]["integrity_verified"]) + self.assertEqual(doc["classification_cache"]["count"], 3) + self.assertEqual(doc["cache_index"]["count"], 4) + self.assertEqual(doc["cache_index"]["distinct_spans"], 3) + self.assertEqual(doc["cache_index"]["aliased_entries"], 1) + self.assertEqual(doc["cache_index"]["code_base"], base) + self.assertEqual(doc["cache_index"]["index_offset"], 312) + self.assertEqual(doc["cache_index"]["program_validation"], "not performed") + + # Archive-only subprocess CLI check. + proc = subprocess.run( + [sys.executable, "-B", str(TOOL), str(archive)], + capture_output=True, + text=True, + check=True, + ) + sub_doc = json.loads(proc.stdout) + self.assertEqual(sub_doc["archive_records"]["count"], 4) + self.assertIsNone(sub_doc["cache_index"]) + + def test_zero_byte_archive_and_cache_blob(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + empty_archive = root / "empty.archive" + empty_cache = root / "empty.cache" + empty_archive.write_bytes(b"") + empty_cache.write_bytes(b"") + + # 0-byte archive succeeds cleanly without mmap ValueError. + code, out, err = self._run_main([str(empty_archive)]) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + doc = json.loads(out) + self.assertEqual(doc["archive_records"]["count"], 0) + self.assertIsNone(doc["cache_index"]) + + # 0-byte --cache-blob exits 1 with 'Shader census:' (never mmap ValueError traceback). + stderr = self._assert_main_fails( + [str(empty_archive), "--cache-blob", str(empty_cache), "--code-base", "128"], + expected_code=1, + fragment="Shader census:", + ) + self.assertIn("128-byte header", stderr) + + def test_directory_and_missing_path_guards(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + archive = root / "owned.archive" + archive.write_bytes(_make_archive()) + subdir = root / "a_dir" + subdir.mkdir() + + # Directory passed as archive -> exit 1 with 'Shader census:' and 'directory'. + err_arch = self._assert_main_fails([str(subdir)], expected_code=1, fragment="Shader census:") + self.assertIn("directory", err_arch.lower()) + + # Directory passed as --cache-blob -> exit 1 with 'Shader census:' and 'directory'. + err_blob = self._assert_main_fails( + [str(archive), "--cache-blob", str(subdir), "--code-base", "128"], + expected_code=1, + fragment="Shader census:", + ) + self.assertIn("directory", err_blob.lower()) + + # Missing archive and missing --cache-blob -> exit 1 with 'Shader census:'. + self._assert_main_fails([str(root / "missing.archive")], expected_code=1, fragment="Shader census:") + self._assert_main_fails( + [str(archive), "--cache-blob", str(root / "missing.cache"), "--code-base", "128"], + expected_code=1, + fragment="Shader census:", + ) + + def test_mismatched_and_negative_code_base_exit_2(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + archive = root / "owned.archive" + cache = root / "decoded.cache" + archive.write_bytes(_make_archive()) + cache_bytes, base = _make_ps9_cache() + cache.write_bytes(cache_bytes) + + # Mismatched --cache-blob / --code-base -> argparse exit 2. + self._assert_main_fails([str(archive), "--cache-blob", str(cache)], expected_code=2, fragment="supplied together") + self._assert_main_fails([str(archive), "--code-base", hex(base)], expected_code=2, fragment="supplied together") + + # Negative --code-base (decimal and hex) -> parser.error exit 2. + for args_extra in (["--code-base", "-1"], ["--code-base=-1"], ["--code-base=-0x10"]): + self._assert_main_fails( + [str(archive), "--cache-blob", str(cache), *args_extra], + expected_code=2, + fragment="non-negative", + ) + self._assert_main_fails( + [str(archive), "--cache-blob", str(cache), "--code-base", "-0x10"], + expected_code=2, + fragment=("expected one argument", "non-negative"), + ) + + # Non-integer --code-base -> exit 2. + self._assert_main_fails( + [str(archive), "--cache-blob", str(cache), "--code-base", "not_an_int"], + expected_code=2, + fragment="invalid", + ) + + def test_malformed_truncated_inputs_and_struct_zlib_guards(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + archive = root / "owned.archive" + cache = root / "decoded.cache" + archive.write_bytes(_make_archive()) + + # Truncated PS/9 cache (<128 bytes) -> exit 1 with 'Shader census:'. + cache.write_bytes(b"PS\x00\x09" + b"\x00" * 123) + self._assert_main_fails( + [str(archive), "--cache-blob", str(cache), "--code-base", "128"], + expected_code=1, + fragment="Shader census:", + ) + + # Out-of-bounds code_base or overlapping allocations -> exit 1 with 'Shader census:'. + bad_cache, bad_base = _make_ps9_cache([(0, 32), (16, 16)]) + cache.write_bytes(bad_cache) + self._assert_main_fails( + [str(archive), "--cache-blob", str(cache), "--code-base", str(bad_base)], + expected_code=1, + fragment="Shader census:", + ) + good_cache, good_base = _make_ps9_cache() + cache.write_bytes(good_cache) + self._assert_main_fails( + [str(archive), "--cache-blob", str(cache), "--code-base", str(len(good_cache) + 1)], + expected_code=1, + fragment="Shader census:", + ) + + # Corrupt deflate payload and truncated span in archive -> cleanly counted in candidate_rejections. + corrupt_deflate = b"bad_rec\0\0" + struct.pack("<4I", 20, 0, 20, 64) + b"\xff" * 20 + truncated_span = b"trunc_rec\0\0" + struct.pack("<4I", 64, 0, 64, 64) + b"\x00" * 8 + archive.write_bytes(_make_archive() + corrupt_deflate + truncated_span) + code, out, err = self._run_main([str(archive)]) + self.assertEqual(code, 0, err) + doc = json.loads(out) + self.assertEqual(doc["archive_records"]["count"], 4) + self.assertEqual(doc["candidate_rejections"]["deflate_error"], 1) + self.assertEqual(doc["candidate_rejections"]["truncated_span"], 1) + + # Direct struct.error and zlib.error propagation -> guarded to exit 1 with 'Shader census:'. + archive.write_bytes(_make_archive()) + for err_obj in (struct.error("truncated header"), zlib.error("corrupt deflate stream")): + with mock.patch.object(sc, "scene_records", side_effect=err_obj): + self._assert_main_fails( + [str(archive)], + expected_code=1, + fragment=f"Shader census: {err_obj}", + ) + with mock.patch.object(sc, "cache_index", side_effect=err_obj): + self._assert_main_fails( + [str(archive), "--cache-blob", str(cache), "--code-base", str(good_base)], + expected_code=1, + fragment=f"Shader census: {err_obj}", + ) + + # Subprocess end-to-end negative check verifying zero raw traceback on stderr. + sub_fail = subprocess.run( + [sys.executable, "-B", str(TOOL), str(archive), "--cache-blob", str(cache), "--code-base=-4"], + capture_output=True, + text=True, + ) + self.assertEqual(sub_fail.returncode, 2) + self.assertNotIn("Traceback", sub_fail.stderr) + self.assertIn("non-negative", sub_fail.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/shader_census.py b/tools/shader_census.py index 4f6d17b49..cff1f672a 100644 --- a/tools/shader_census.py +++ b/tools/shader_census.py @@ -1,4 +1,6 @@ """Report shader populations separately; do not classify or execute programs.""" +from __future__ import annotations + import argparse from contextlib import ExitStack import hashlib @@ -6,6 +8,7 @@ import mmap from pathlib import Path import struct +import zlib from resource_inventory import scene_records @@ -64,30 +67,36 @@ def observe(stage, blob, sections): ) -def main(): +def _map_input(stack: ExitStack, path: Path): + if path.is_dir(): + raise ValueError(f"Expected a file, not a directory: {path}") + stream = stack.enter_context(path.open("rb")) + if stream.seek(0, 2) == 0: + return b"" + return stack.enter_context(mmap.mmap(stream.fileno(), 0, access=mmap.ACCESS_READ)) + + +def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("archive", type=Path) parser.add_argument("--cache-blob", type=Path, help="Already decoded PS/9 cache from the same build") parser.add_argument("--code-base", type=lambda value: int(value, 0), help="Independently established code-area base in that cache (decimal or hex)") - args = parser.parse_args() + args = parser.parse_args(argv) if (args.cache_blob is None) != (args.code_base is None): parser.error("--cache-blob and --code-base must be supplied together") + if args.code_base is not None and args.code_base < 0: + parser.error("--code-base must be non-negative") try: with ExitStack() as stack: - def mapped(path): - stream = stack.enter_context(path.open("rb")) - if stream.seek(0, 2) == 0: - return b"" - return stack.enter_context(mmap.mmap(stream.fileno(), 0, access=mmap.ACCESS_READ)) - - archive = mapped(args.archive) - blob = mapped(args.cache_blob) if args.cache_blob is not None else None + archive = _map_input(stack, args.archive) + blob = _map_input(stack, args.cache_blob) if args.cache_blob is not None else None result = census(archive, cache_blob=blob, code_base=args.code_base) - except (OSError, ValueError) as error: + except (OSError, ValueError, struct.error, zlib.error) as error: parser.exit(1, f"Shader census: {error}\n") print(json.dumps(result, indent=2)) + return 0 if __name__ == "__main__": - main() + raise SystemExit(main()) From 1cd73d3a7d8ca53ab635b7059b1e2cf281f1eb39 Mon Sep 17 00:00:00 2001 From: chasegrindy Date: Thu, 26 Nov 2026 01:01:52 +0100 Subject: [PATCH 023/240] startup: invalidate slot 35 tables when the compute view heap changes (#2636) Track ordinary and oversized compute view heaps separately from the graphics lookup. Keep the table when the same heap is rebound and clear it on changes or unset. Cover the recorder in the CPU checks. Co-authored-by: chasegrindy <302242206+chasegrindy@users.noreply.github.com> --- src/startup_stubs/d3d12_draw.inl | 14 +++++------- src/startup_stubs/list_compute_root.h | 24 ++++++++++++++++++-- tests/startup_compute_root.cpp | 32 +++++++++++++++++++++++++-- 3 files changed, 58 insertions(+), 12 deletions(-) diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 16aa47bd0..ecd416690 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -2385,15 +2385,14 @@ const char* draw_translated_indirect(Wrapper* self, ID3D12CommandSignature* sign void __stdcall list_set_descriptor_heaps(Wrapper* self, UINT count, void* const* heaps) { x2w_startup::SamplerSource source; - u64 view_heap = 0; + x2w_startup::ViewHeapSelection view_heaps; if (count && count <= 4 && x2w_local::readable(heaps, std::size_t{count} * sizeof(*heaps))) { AcquireSRWLockShared(¬e_lock); for (UINT i = 0; i < count; ++i) { for (const HeapInfo& heap : heap_infos()) { if (heap.wrapper == reinterpret_cast(heaps[i]) && - heap.type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV && - heap.logical_count > heap.count) - view_heap = heap.wrapper; + heap.type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) + view_heaps.note(heap.wrapper, heap.desktop_gpu != 0, heap.logical_count, heap.count); if (heap.wrapper == reinterpret_cast(heaps[i]) && heap.type == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER && heap.desktop_gpu) source = {static_cast(heap.title_sampler_cpu), heap.count}; @@ -2402,12 +2401,11 @@ void __stdcall list_set_descriptor_heaps(Wrapper* self, UINT count, void* const* ReleaseSRWLockShared(¬e_lock); } auto& pass = pass_of(self); - if (pass.source_view_heap != view_heap) - { + if (pass.source_view_heap != view_heaps.graphics) { for (auto& table : pass.view_tables) table = {}; - pass.compute_tables.clear(); } - pass.source_view_heap = view_heap; + pass.compute_tables.set_view_heap(view_heaps.compute); + pass.source_view_heap = view_heaps.graphics; pass.title_samplers = source; } diff --git a/src/startup_stubs/list_compute_root.h b/src/startup_stubs/list_compute_root.h index 6e5d89c46..a47b3477d 100644 --- a/src/startup_stubs/list_compute_root.h +++ b/src/startup_stubs/list_compute_root.h @@ -14,6 +14,19 @@ namespace x2w_startup { +// Slot 32 builds this selection afresh for each call. The graphics lookup still singles out +// oversized logical heaps; compute table invalidation also needs ordinary shader-visible heaps. +struct ViewHeapSelection { + std::uint64_t graphics = 0; + std::uint64_t compute = 0; + + void note(std::uint64_t wrapper, bool shader_visible, unsigned logical_count, unsigned desktop_count) + { + if (shader_visible) compute = wrapper; + if (logical_count > desktop_count) graphics = wrapper; + } +}; + class ComputeTables { public: static constexpr unsigned max_parameters = 16; // same range as the graphics tables @@ -26,9 +39,10 @@ class ComputeTables { } // Slot 32 with another view heap: the recorded addresses belong to the old one. - void clear() + void set_view_heap(std::uint64_t heap) { - for (auto& table : tables_) table = {}; + if (heap != view_heap_) clear(); + view_heap_ = heap; } // False when the parameter is out of range (counted). @@ -47,7 +61,13 @@ class ComputeTables { std::uint32_t out_of_range_count() const { return out_of_range_; } private: + void clear() + { + for (auto& table : tables_) table = {}; + } + const void* signature_ = nullptr; + std::uint64_t view_heap_ = 0; ViewTable tables_[max_parameters] = {}; std::uint32_t out_of_range_ = 0; }; diff --git a/tests/startup_compute_root.cpp b/tests/startup_compute_root.cpp index b31cd9bcc..d8c065d48 100644 --- a/tests/startup_compute_root.cpp +++ b/tests/startup_compute_root.cpp @@ -7,6 +7,7 @@ namespace { using x2w_startup::ComputeTables; +using x2w_startup::ViewHeapSelection; using x2w_startup::ViewTable; using x2w_startup::resolve_view_table; int failures; @@ -65,9 +66,36 @@ int main() { ComputeTables s; s.set_signature(&root_a); + const auto select = [&](std::uint64_t heap, bool visible, unsigned logical, unsigned desktop) { + ViewHeapSelection selection; + selection.note(heap, visible, logical, desktop); + s.set_view_heap(selection.compute); + return selection; + }; + auto selection = select(1, true, 8, 8); + check(selection.compute == 1 && !selection.graphics, "ordinary heap is selected only for compute invalidation"); s.set_table(7, at(6)); - s.clear(); - check(s.table(7).address == 0 && s.signature() == &root_a, "a view heap change clears the tables and keeps the signature"); + select(1, true, 8, 8); + check(s.table(7).address == at(6).address, "same ordinary heap keeps the table"); + select(2, true, 8, 8); + check(!s.table(7).address, "different ordinary heap clears the table"); + s.set_table(7, at(6)); + selection = select(3, true, 16, 8); + check(selection.compute == 3 && selection.graphics == 3, "oversized heap remains visible to graphics lookup"); + check(!s.table(7).address, "ordinary to oversized clears the table"); + s.set_table(7, at(6)); + select(3, true, 16, 8); + check(s.table(7).address == at(6).address, "same oversized heap keeps the table"); + select(4, true, 16, 8); + check(!s.table(7).address, "different oversized heap clears the table"); + s.set_table(7, at(6)); + select(1, true, 8, 8); + check(!s.table(7).address, "oversized to ordinary clears the table"); + s.set_table(7, at(6)); + s.set_view_heap(ViewHeapSelection{}.compute); + check(!s.table(7).address && s.signature() == &root_a, "unsetting the heap clears the table and keeps the signature"); + selection = select(5, false, 8, 8); + check(!selection.compute && !selection.graphics, "CPU-only heap does not select a view heap"); } { ComputeTables s; From 8ecaa8ec992cf6ac404d9b7f3f044f62778f4796 Mon Sep 17 00:00:00 2001 From: RavenCurseBurg Date: Thu, 26 Nov 2026 08:04:21 +0800 Subject: [PATCH 024/240] tests: run heap-view load references in one batch per compute shader (#2635) Co-authored-by: RavenCurseBurg <360931527+RavenCurseBurg@users.noreply.github.com> Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- docs/experiments.md | 4 +++ tests/compute_heap_view_check.py | 58 +++++++++++++++--------------- tests/compute_load_format_check.py | 12 +++---- 3 files changed, 38 insertions(+), 36 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index c5e36d0f3..0292a18ef 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -6277,6 +6277,10 @@ cmake --build --preset dev --target offscreen_check ctest --preset dev --no-tests=error -R '^compute_(store_aot_heap_view_load_|heap_view_controls$)' -V ``` +The 56 matching references and seven wrong references run in two shader batches, one for XY and one for +XYZW. Each dispatch still checks all 320 words. Each wrong reference must report its first differing +word, including the expected and actual values. The fourteen recompiled mutations run individually. + ```sh python3 -B tests/compute_heap_view_check.py binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 ``` diff --git a/tests/compute_heap_view_check.py b/tests/compute_heap_view_check.py index 6555ec680..68156df83 100644 --- a/tests/compute_heap_view_check.py +++ b/tests/compute_heap_view_check.py @@ -259,58 +259,56 @@ def draw(directory, compiler, renderer, backend): src.write_text(lower(suffix), encoding="ascii") subprocess.run([compiler, "-T", "cs_6_0", "-E", "main", "-Fo", cso, src], check=True) shaders[suffix] = cso - case = directory / "heap.case" - dispatches = 0 + sources = {suffix: source_words(views) for suffix, views in SUFFIXES.items()} + cases = {suffix: [] for suffix in SUFFIXES} - def write(suffix, slot, groups, reference): - words = source_words(SUFFIXES[suffix]) + def write(case, suffix, slot, groups, reference): case.write_bytes(struct.pack("<321I", groups, *reference) + struct.pack("<16I", *constants(slot)) - + struct.pack("<320I", *words)) - return words + + struct.pack("<320I", *sources[suffix])) + + def add(suffix, slot, groups, reference, label, actual=None): + diagnostic = None + if actual is not None: + word = next((i for i, (a, b) in enumerate(zip(reference, actual)) if a != b), None) + if word is None: + raise AssertionError(f"{NAME}: reference '{label}' matches the expected words") + diagnostic = f"word={word} expected={reference[word]:08x} actual={actual[word]:08x}" + path = directory / f"heap_{suffix}_{len(cases[suffix])}.case" + write(path, suffix, slot, groups, reference) + cases[suffix].append((path, f"{suffix} slot {slot} {label} (groups={groups})", diagnostic)) for suffix, views in SUFFIXES.items(): for slot in range(len(views) + 1): - words = source_words(views) - for groups in (1, 2): - write(suffix, slot, groups, expected_words(suffix, slot, groups, words)) - if subprocess.run([*cmd, shaders[suffix], case]).returncode: - return 1 - dispatches += 1 label = views[slot]["label"] if slot < len(views) else "no record" - print(f"{NAME}: {suffix} slot {slot} {'refused' if slot in REFUSED[suffix] or slot >= len(views) else 'read'}" - f" ({label})", flush=True) + action = "refused" if slot in REFUSED[suffix] or slot >= len(views) else "read" + for groups in (1, 2): + add(suffix, slot, groups, expected_words(suffix, slot, groups, sources[suffix]), f"{action} ({label})") + dispatches = sum(map(len, cases.values())) # A refusal must stay distinguishable from a published zero read: zeros against a refused slot must fail. for suffix, slot in (("xy", 4), ("xy", 10), ("xy", 11), ("xyzw", 3)): - words = source_words(SUFFIXES[suffix]) - zeros = [0] * WORDS - write(suffix, slot, 2, zeros) - bad = subprocess.run([*cmd, shaders[suffix], case], capture_output=True, text=True) - if bad.returncode != 1 or "Compute readback differs" not in bad.stderr: - raise AssertionError(f"{NAME}: zeros published for {suffix} slot {slot} escaped detection\n{bad.stderr}") + add(suffix, slot, 2, [0] * WORDS, "zeros published", expected_words(suffix, slot, 2, sources[suffix])) for label, wrong, (suffix, slot) in WRONG: - words = source_words(SUFFIXES[suffix]) + words = sources[suffix] good = expected_words(suffix, slot, 2, words) wrong_words = expected_words(suffix, slot, 2, words, wrong=wrong) - if good == wrong_words: - raise AssertionError(f"{NAME}: reference '{label}' matches the expected words") - write(suffix, slot, 2, wrong_words) - bad = subprocess.run([*cmd, shaders[suffix], case], capture_output=True, text=True) - if bad.returncode != 1 or "Compute readback differs" not in bad.stderr: - raise AssertionError(f"{NAME}: reference '{label}' escaped detection\n{bad.stderr}") + add(suffix, slot, 2, wrong_words, label, good) + for suffix, references in cases.items(): + fmt.check_references(NAME, renderer, backend, shaders[suffix], references) + wrong_count = sum(map(len, cases.values())) - dispatches original = {suffix: lower(suffix) for suffix in SUFFIXES} + case = directory / "mutated.case" for label, old, new, (suffix, slot) in MUTATIONS: mutated = original[suffix].replace(old, new, 1) if mutated == original[suffix]: raise AssertionError(f"{NAME}: mutation '{label}' did not change the source") - words = source_words(SUFFIXES[suffix]) - write(suffix, slot, 2, expected_words(suffix, slot, 2, words)) + write(case, suffix, slot, 2, expected_words(suffix, slot, 2, sources[suffix])) bad_src, bad_cso = directory / "mutated.hlsl", directory / "mutated.cso" bad_src.write_text(mutated, encoding="ascii") subprocess.run([compiler, "-T", "cs_6_0", "-E", "main", "-Fo", bad_cso, bad_src], check=True) bad = subprocess.run([*cmd, bad_cso, case], capture_output=True, text=True) if bad.returncode != 1 or "Compute readback differs" not in bad.stderr: raise AssertionError(f"{NAME}: mutation '{label}' escaped detection\n{bad.stderr}") - print(f"{NAME}: {dispatches} dispatches, {3 + len(WRONG)} wrong references and " + print(f"{NAME}: {dispatches} dispatches, {wrong_count} wrong references and " f"{len(MUTATIONS)} mutated sources checked") return 0 diff --git a/tests/compute_load_format_check.py b/tests/compute_load_format_check.py index bc98b779b..2539cc006 100644 --- a/tests/compute_load_format_check.py +++ b/tests/compute_load_format_check.py @@ -312,7 +312,7 @@ def binary(directory, assembler, objcopy, library): return 0 -def check_references(renderer, backend, shader, cases): +def check_references(name, renderer, backend, shader, cases): paths = [path for path, _label, _diagnostic in cases] result = subprocess.run([renderer, backend, "--compute-store-batch", shader, *paths], capture_output=True, text=True) @@ -324,18 +324,18 @@ def check_references(renderer, backend, shader, cases): if (i >= len(statuses) or statuses[i] != f"case={i} status={status}" or i >= len(messages) or not messages[i].startswith(f"case={i} path={path}\n") or (diagnostic and diagnostic not in messages[i])): - raise AssertionError(f"{NAME}: {label} expected {status}\n{result.stdout}{result.stderr}") + raise AssertionError(f"{name}: {label} expected {status}\n{result.stdout}{result.stderr}") summary = summaries[i] if i < len(summaries) else "" counts = re.fullmatch(r"groups=\d+ compared_words=320 mismatches=(\d+)", summary) if not counts or (int(counts[1]) > 0) != bool(diagnostic): - raise AssertionError(f"{NAME}: {label} unexpected readback\n{result.stdout}{result.stderr}") + raise AssertionError(f"{name}: {label} unexpected readback\n{result.stdout}{result.stderr}") expected_exit = int(any(diagnostic for _, _, diagnostic in cases)) if not (len(cases) == len(statuses) == len(messages) == len(summaries)) or result.returncode != expected_exit: - raise AssertionError(f"{NAME}: unexpected batch result ({result.returncode})\n{result.stdout}{result.stderr}") + raise AssertionError(f"{name}: unexpected batch result ({result.returncode})\n{result.stdout}{result.stderr}") labels = iter(label for _path, label, _diagnostic in cases) for line in result.stdout.splitlines(): if line.startswith("groups="): - print(f"{NAME}: {next(labels)}") + print(f"{name}: {next(labels)}") print(line) @@ -413,7 +413,7 @@ def invalid_formats(number): mutations.append((number, label, case, mutated)) with ThreadPoolExecutor(max_workers=min(LAUNCH_THREADS, os.cpu_count() or 1)) as pool: - batch = pool.submit(check_references, renderer, backend, cso, references) + batch = pool.submit(check_references, NAME, renderer, backend, cso, references) mutants = [pool.submit(run_mutation, *mutation) for mutation in mutations] batch.result() for future in mutants: From 46313981d58bd82d0e65774126f64da1477555a2 Mon Sep 17 00:00:00 2001 From: SimSalabimse <83839581+SimSalabimse@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:17:02 +0100 Subject: [PATCH 025/240] shader: lower s_bitset0/1_b32 in gfx2hlsl (#2023 Item J) (#2638) * shader: lower s_bitset0/1_b32 in gfx2hlsl (#2023 Item J) Port the pixel_aot bit set/clear SOP1 forms so ordinary vertex and pixel pipelines that only need an in-place scalar bit update stop refusing at s_bitset1_b32. SCC stays unchanged; lane masks and descriptor SGPRs refuse. Co-authored-by: SimSalabimse * test: pin sopk descriptor-refusal mutation to sopk-only raise s_bitset0/1_b32 reused the plain-scalar sym allow-list line, so the sopk_accum mutant needle was no longer unique. Match the sopk raise that formats with `base` instead. Co-authored-by: SimSalabimse --------- Co-authored-by: Cursor Agent Co-authored-by: SimSalabimse --- .github/workflows/windows.yml | 1 + AGENTS.md | 1 + CMakeLists.txt | 3 + docs/experiments.md | 9 ++ tests/startup_gfx2hlsl_s_bitset_check.py | 155 +++++++++++++++++++++ tests/startup_gfx2hlsl_sopk_accum_check.py | 6 +- tools/startup/gfx2hlsl.py | 52 +++++++ 7 files changed, 226 insertions(+), 1 deletion(-) create mode 100644 tests/startup_gfx2hlsl_s_bitset_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 4cb608731..5d86ad940 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -293,6 +293,7 @@ jobs: tests/startup_compute_lds_b128_check.py \ tests/startup_compute_translate_check.py \ tests/startup_gfx2hlsl_swap_check.py \ + tests/startup_gfx2hlsl_s_bitset_check.py \ tests/startup_gfx2hlsl_fma_mix_check.py \ tests/startup_gfx2hlsl_shift64_check.py \ tests/startup_gfx2hlsl_mul_mad_i24_check.py \ diff --git a/AGENTS.md b/AGENTS.md index cd477f204..84cb9183a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -173,6 +173,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_compute_store_format_xyzw_check.py ./out/pe-env/bin/python -B tests/startup_compute_translate_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_swap_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_s_bitset_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_fma_mix_check.py ./out/pe-env/bin/python -B tests/startup_image_2d_array_check.py ./out/pe-env/bin/python -B tests/startup_image_sample_a16_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index cf4f5ec41..52c80c494 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3215,6 +3215,9 @@ if(EXISTS "${INTAKE_PYTHON}") # gfx2hlsl lowers s_bitcmp1_b32 and s_bitcmp0_b32 (SOPC): CPU evaluation of the translated SCC test. add_test(NAME startup_gfx2hlsl_s_bitcmp COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_bitcmp_check.py") + # gfx2hlsl lowers s_bitset0_b32 and s_bitset1_b32 (SOP1, #2023 Item J): CPU evaluation and refusals. + add_test(NAME startup_gfx2hlsl_s_bitset COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_bitset_check.py") # gfx2hlsl lowers v_cube{id,sc,tc,ma}_f32: device-free translation controls. add_test(NAME startup_gfx2hlsl_cube_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_cube_check.py") diff --git a/docs/experiments.md b/docs/experiments.md index 0292a18ef..6088bc218 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -7997,6 +7997,15 @@ one. Only the low five bits of the index are used. EXEC, VCC and SGPRs tracked as lane masks are refused because their per-lane projections lose the other bits. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_s_bitcmp$' -V`. +**Scalar bit set and clear.** Startup translation lowers `s_bitset0_b32` and +`s_bitset1_b32` in place: bit `S0[4:0]` of the destination is cleared or set, +and SCC is unchanged (same form as `pixel_aot` / #1579; Refs #2023 Item J). +Lane masks and descriptor-bearing SGPRs are refused. A known constant +destination with a known bit index folds. Run +`ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_s_bitset$' -V` +(or `python3 -B tests/startup_gfx2hlsl_s_bitset_check.py`). The fixture is +CPU-only; Windows WARP/hardware draws are left for an independent retest. + **Scalar immediate comparisons.** The startup translator sign-extends the 16-bit field of `s_movk_i32` and `s_cmpk_*_i32`, and zero-extends the field of `s_cmpk_*_u32`. The source-built check covers all six relations against diff --git a/tests/startup_gfx2hlsl_s_bitset_check.py b/tests/startup_gfx2hlsl_s_bitset_check.py new file mode 100644 index 000000000..baa873e0c --- /dev/null +++ b/tests/startup_gfx2hlsl_s_bitset_check.py @@ -0,0 +1,155 @@ +"""s_bitset0_b32 and s_bitset1_b32 in tools/startup/gfx2hlsl.py (#2023 Item J). + +usage: startup_gfx2hlsl_s_bitset_check.py + +RDNA 2 ISA SOP1: S_BITSET0_B32 clears bit S0[4:0] of D in place; S_BITSET1_B32 sets that bit. +SCC is unchanged. The reference is plain Python integer arithmetic; the translated text is evaluated +on the CPU. Lane-mask and descriptor-bearing destinations or sources are refused. A mutation that +drops the bit update must disagree with the reference. +""" +import re +import struct +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import disasm_rdna2 as D # noqa: E402 +import gfx2hlsl as G # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import Expr # noqa: E402 + +MASK = 0xffffffff +SOP1 = {name: op for op, (name, _) in D.SOP1_OPS.items()} +WORDS = (0x00000000, 0xffffffff, 0x80000001, 0x00010020, 0x55555555, 0xaaaaaaaa, 0x12345678) +INDEXES = (0, 1, 5, 16, 31, 32, 33, 0x21, 0xffffffe5) +SCC_UNSET = 2 +VCC_LO, EXEC_LO = 106, 126 + +failures = [] + + +def check(label, ok, detail=''): + print('%s: %s' % (label, 'ok' if ok else 'MISMATCH'), flush=True) + if not ok: + failures.append(label) + if detail: + print(' ' + detail) + + +def sop1(name, sdst, ssrc): + return struct.pack(' 105: + raise Unsupported('%s destination %s' % (name, ops[0])) + d = dst[1] + if self.is_lane_mask(ops[0]) or d in self.masks: + raise Unsupported('%s on a lane mask' % name) + imm = re.fullmatch(r'-?(0x[0-9a-fA-F]+|\d+)', ops[1]) + bit_sym = None + if imm: + index_imm = int(ops[1], 0) & 31 + else: + src = reg_range(ops[1]) + if not src or src[0] != 's' or src[1] != src[2] or src[1] > 105: + raise Unsupported('%s source %s' % (name, ops[1])) + if self.is_lane_mask(ops[1]) or src[1] in self.masks: + raise Unsupported('%s on a lane mask' % name) + bit_sym = self.sym.get(src[1]) + if bit_sym and bit_sym[0] not in ('const', 'ud', 'fixed_buffer_word'): + raise Unsupported('%s on %s data' % (name, bit_sym[0])) + index_imm = bit_sym[1] & 31 if bit_sym and bit_sym[0] == 'const' else None + sym = self.sym.get(d) + if sym and sym[0] not in ('const', 'ud', 'fixed_buffer_word'): + raise Unsupported('%s on %s data' % (name, sym[0])) + prev = self.S(d) + bit = self.u(ops[1]) + mask = '(1u << (%s & 31))' % bit + result = '(%s & ~%s)' % (prev, mask) if clear else '(%s | %s)' % (prev, mask) + if sym and sym[0] == 'const' and index_imm is not None: + value = ((sym[1] & ~(1 << index_imm)) if clear else (sym[1] | (1 << index_imm))) & 0xffffffff + self.set_s(d, '0x%08xu' % value, ('const', value)) + else: + self.set_s(d, result) + self.masks.discard(d) + return None + def scalar_cmov(self, ops, mods, pair, name=None): """D = SCC ? S0 : D on plain SGPR destinations; SCC is unchanged.""" name = name or 's_cmov_b%d' % (64 if pair else 32) From 4c3fbfbdfb0c958187e3555e788c9d4502daa75e Mon Sep 17 00:00:00 2001 From: tedin7 <110300616+tedin7@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:20:28 +0100 Subject: [PATCH 026/240] startup: implement command-list slot 14 Dispatch (Part of #870) (#1974) * feat: record command-list slot 14 Dispatch on the desktop list Part of #870. Forward Dispatch only with a desktop compute pipeline and root bound and group counts within 65535 per axis; refuse otherwise. * startup: refuse Dispatch under a compute root with unforwarded arguments, document slot 14 * startup: gate Dispatch on bound compute root SRVs and a pipeline built against the bound root Slot 43 clears a parameter's binding when a replacement is rejected, slot 33 clears all bindings, and the compute pipeline records its root so a mismatched pair is refused. * fix: pass pipeline root out-param in slot86 mesh cached pipeline build * tests: drive native slot 14 Dispatch through the stand-in startup_list_dispatch_native creates a guest device on a desktop adapter (WARP or hardware, debug layer on when installed) and drives command-list slots 86, 25, 33, 43, 148, 14, 9 and 139 of the stand-in. Each refused case must write exactly one "x2w-render Dispatch(x, y, z) refused: " line, with the expected reason, to X2W_TRAP_LOG: - a root SRV never set; - a rejected (foreign address) or misaligned slot 43 replacement after a valid one; - a root changed and changed back without a new slot 43; - a pipeline built against another root; - a root with a descriptor table, and a root with a static sampler; - an unset root SRV with zero groups; - 65536 groups on X; - a Dispatch on the closed list; - a Dispatch after Reset without new bindings. A forwarded case must write no line. The fixture wraps a pipeline-statistics query around every slot 14 call on an open list, recorded on the underlying desktop list: CSInvocations must be 4 per group when forwarded and 0 when refused. The fully bound call is recorded alone and read back first, so a slot 14 that records nothing fails on its count. All three recordings are executed to a fence and the debug layer must report no error. The skip_srv control drops slot 43 from the first forwarded case and must report it as refused. Each of these one-line changes to d3d12_xs_device.cpp makes the WARP and hardware tests fail: the refusal branch never taken, compute_srv_bound not cleared by slot 33, the bit not cleared by a rejected slot 43, compute_root_has_arguments forced false, root_matches_pipeline forced true, and the slot 14 registration removed. The docs section now names the device fixture and corrects the sentence on which compute root-argument slots have handlers. Co-Authored-By: Claude Opus 5.5 * docs: list_dispatch header names slot 43 as forwarded --------- Co-authored-by: The Void Co-authored-by: Claude Opus 5.5 Co-authored-by: Royoo <3230853833@qq.com> --- CMakeLists.txt | 22 ++ docs/experiments.md | 11 + src/startup_stubs/d3d12_xs_device.cpp | 48 ++- src/startup_stubs/list_dispatch.h | 58 ++++ src/startup_stubs/mesh86_cache.inl | 3 +- tests/startup_list_dispatch_check.cpp | 90 +++++ tests/startup_list_dispatch_native.cpp | 440 +++++++++++++++++++++++++ 7 files changed, 669 insertions(+), 3 deletions(-) create mode 100644 src/startup_stubs/list_dispatch.h create mode 100644 tests/startup_list_dispatch_check.cpp create mode 100644 tests/startup_list_dispatch_native.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 52c80c494..f88d0d2e9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1925,6 +1925,28 @@ foreach(mutation IN ITEMS sampler-alone bind-unrestorable) add_test(NAME startup_heap_indexed_root_${mutation}_control COMMAND startup_heap_indexed_root_check --mutate ${mutation}) set_tests_properties(startup_heap_indexed_root_${mutation}_control PROPERTIES WILL_FAIL TRUE) endforeach() +# Slot 14 (Dispatch) forward-or-refuse decision (src/startup_stubs/list_dispatch.h), without a device. +add_executable(startup_list_dispatch_check tests/startup_list_dispatch_check.cpp) +target_include_directories(startup_list_dispatch_check PRIVATE src) +target_compile_features(startup_list_dispatch_check PRIVATE cxx_std_17) +add_test(NAME startup_list_dispatch COMMAND startup_list_dispatch_check) +foreach(mutation IN ITEMS no-limit no-state no-root-args no-pairing no-bound) + add_test(NAME startup_list_dispatch_${mutation}_control COMMAND startup_list_dispatch_check --mutate ${mutation}) + set_tests_properties(startup_list_dispatch_${mutation}_control PROPERTIES WILL_FAIL TRUE) +endforeach() +# The same slot driven through the stand-in on a desktop device: one refusal line per refused case, and the +# forwarded calls counted by a pipeline-statistics query on the desktop list. +add_executable(startup_list_dispatch_native tests/startup_list_dispatch_native.cpp) +target_compile_features(startup_list_dispatch_native PRIVATE cxx_std_17) +target_link_libraries(startup_list_dispatch_native PRIVATE d3d12_xs_shim d3d12 dxgi d3dcompiler) +foreach(backend IN ITEMS warp hardware) + add_test(NAME startup_list_dispatch_native_${backend} COMMAND startup_list_dispatch_native ${backend}) + set_tests_properties(startup_list_dispatch_native_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) +endforeach() +# Negative control: without slot 43 the first forwarded case is refused, and the fixture must report it. +add_test(NAME startup_list_dispatch_native_skip_srv_warp_control COMMAND startup_list_dispatch_native warp skip-srv) +set_tests_properties(startup_list_dispatch_native_skip_srv_warp_control PROPERTIES TIMEOUT 60 + PASS_REGULAR_EXPRESSION "bound: expected no Dispatch line, got 1 Dispatch line\\(s\\)[\r\n]+ x2w-render Dispatch\\(2, 3, 1\\) refused: a compute root SRV is not bound") target_sources(offscreen_check PRIVATE tests/startup_image_3d.cpp) target_sources(offscreen_check PRIVATE tests/startup_image_store.cpp) target_sources(offscreen_check PRIVATE tests/startup_flat_param.cpp) diff --git a/docs/experiments.md b/docs/experiments.md index 6088bc218..ab318679b 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15735,6 +15735,17 @@ The [MASM fixture](../tests/cpu/switch_sal.asm) emits explicit `/6` byte sequenc Not covered by this experiment: `SAL` outside leaf/switch-lifted functions, and title CPU code execution. +## Startup list Dispatch + +Command-list slot 14 (`Dispatch`) is recorded on the desktop list only when the list is open and direct or compute, a desktop compute pipeline and a desktop compute root signature are bound, the compute root declares no static samplers and only root SRV parameters (slot 43), the compute pipeline was built against that same root signature, every root SRV the root declares was set since the root was bound (a rejected or unaligned replacement clears its binding), and every group count is at most 65535. Zero groups on an axis is forwarded and runs nothing. A root with other parameters is refused with `compute root arguments are not forwarded`, a pipeline from another root with `compute pipeline was built against another root signature`, an unset or rejected root SRV with `a compute root SRV is not bound`. Of the compute root arguments, only root SRVs (slot 43) reach the desktop list: slot 35 records descriptor tables without setting them, and slots 37, 39, 41 and 45 have no handler yet, so a dispatch under any other argument would run with it unset. The first 16 refusals in a process are logged as `x2w-render Dispatch(x, y, z) refused: `. + +`tests/startup_list_dispatch_check.cpp` checks the decision without a device; its five mutated runs must fail. `tests/startup_list_dispatch_native.cpp` drives slots 86, 25, 33, 43, 148, 14, 9 and 139 of the stand-in on a desktop device, on WARP and on a hardware adapter (77 without one), with the debug layer when it is installed. Each refused case must log exactly one refusal line with the expected reason: a root SRV never set, a rejected or misaligned slot 43 replacement after a valid one, a root changed and changed back without slot 43, a pipeline built against another root, a root with a descriptor table, a root with a static sampler, an unset root SRV with zero groups, more than 65535 groups, a closed list, and a Reset list without new bindings. A forwarded case must log no line. Around each call on an open list the fixture records a pipeline-statistics query on the desktop list: `CSInvocations` must be 4 per group for a forwarded call and 0 for a refused one. The fully bound call is recorded alone and counted first, so a slot 14 that records nothing fails on its count. Each of the three recordings is executed to a fence, and the debug layer must report no error. The shader only declares its root SRV, so this shows that the desktop `Dispatch` is recorded and runs, not what a shader reads through the bound SRV. The `skip_srv` control drops slot 43 from the first forwarded case and must report that case as refused. + +```powershell +cmake --build --preset dev --target startup_list_dispatch_check startup_list_dispatch_native +ctest --preset dev --no-tests=error -R "^startup_list_dispatch" -V +``` + ## Startup translator: explicit-gradient image_sample_d `tools/startup/gfx2hlsl.py` lowers the gfx1013 `image_sample_d` form in a pixel stage to `tex.SampleGrad(smp, uv, ddx, ddy)`. The address dwords are ddx, then ddy (one register per coordinate axis each), then the coordinates: six registers for 2D, seven for a 2D array (slice last), nine for a volume (a contiguous nine-dword volume address encoded as a sixteen-register range is trimmed to nine). Only `dim:`, `dmask:` and the cache-policy bits `dlc`, `glc`, `slc` are accepted. diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 50a37c5aa..85d004b4d 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -29,6 +29,7 @@ #include "startup_stubs/heap_indexed_root.h" #include "startup_stubs/indexed_indirect_guard.h" #include "startup_stubs/indexed_rect_geometry.h" +#include "startup_stubs/list_dispatch.h" #include "startup_stubs/bc7_4k_s.h" #include "startup_stubs/bc64_chain.h" #include "startup_stubs/address_texture.h" @@ -182,6 +183,8 @@ struct alignas(16) WrapperOwn { const void* compute_trace_root; LONG compute_trace_dispatches; bool root_without_bindings; // RootSignature: decoded and has no parameters or static samplers + ID3D12RootSignature* pipeline_root; // PipelineState: desktop root signature its compute stream declared + bool root_srv_only; // RootSignature: decoded, no static samplers, every parameter a root SRV (those are forwarded) volatile LONG queue_wait_seen; // CommandQueue: publish later signals only after GPU completion. void* pass; // CommandList (render mode): recording state (Pass) Wrapper* list_device; // CommandList: wrapper that created this list. @@ -1994,8 +1997,10 @@ HRESULT __stdcall device_create_root_signature(Wrapper* self, UINT node, const v if (SUCCEEDED(deserializer->GetRootSignatureDescAtVersion(D3D_ROOT_SIGNATURE_VERSION_1_1, &desc)) && desc) { heap_flags = static_cast(desc->Desc_1_1.Flags) & x2w_startup::root_flags_heap_indexed; w->own().root_without_bindings = !heap_flags && !desc->Desc_1_1.NumParameters && !desc->Desc_1_1.NumStaticSamplers; + w->own().root_srv_only = !heap_flags && !desc->Desc_1_1.NumStaticSamplers && desc->Desc_1_1.NumParameters; for (UINT i = 0; i < desc->Desc_1_1.NumParameters; ++i) { const auto& parameter = desc->Desc_1_1.pParameters[i]; + if (parameter.ParameterType != D3D12_ROOT_PARAMETER_TYPE_SRV) w->own().root_srv_only = false; RootParameter info{parameter.ParameterType, 0, 0}; if (parameter.ParameterType == D3D12_ROOT_PARAMETER_TYPE_CBV || parameter.ParameterType == D3D12_ROOT_PARAMETER_TYPE_SRV || parameter.ParameterType == D3D12_ROOT_PARAMETER_TYPE_UAV) { @@ -2121,7 +2126,7 @@ std::size_t desktop_stream_size(UINT type) // Converts the supported stream layout to desktop form and creates the pipeline. ID3D12PipelineState* build_stream_pipeline(const D3D12_PIPELINE_STATE_STREAM_DESC* desc, char* why, std::size_t why_size, - bool& compute, IndirectGraphicsPipeline& graphics, + bool& compute, IndirectGraphicsPipeline& graphics, ID3D12RootSignature*& pipeline_root, ID3D12RootSignature* cached_root = nullptr) { const bool cached_mesh = cached_root != nullptr; @@ -2283,6 +2288,8 @@ ID3D12PipelineState* build_stream_pipeline(const D3D12_PIPELINE_STATE_STREAM_DES } check_device("Device CreatePipelineState", 86); } + if (pipeline && compute && root && root->own().kind == root_signature_kind) + pipeline_root = static_cast(root->own().real); if (pipeline && (vertex || mesh) && (pixel || cached_mesh)) { graphics = {cached_mesh ? cached_root : static_cast(root->own().real), targets.RTFormats[0], mesh, cached_mesh}; @@ -2383,8 +2390,11 @@ struct Pass { ID3D12RootSignature* compute_root = nullptr; // latest guest root if it was forwarded x2w_startup::ComPtr desktop_compute_root; // last root actually set on this recording std::array desktop_compute_upload_srvs{}; + ID3D12RootSignature* compute_pipeline_root = nullptr; // root the bound compute pipeline was built against + UINT compute_srv_bound = 0; // root SRV parameters that reached the desktop list since slot 33 const std::vector* compute_params = nullptr; std::unique_ptr compute_trace; + bool compute_root_has_arguments = false; // that root declares parameters other than root SRVs, or static samplers IndirectGraphicsPipeline indirect_graphics; ID3D12RootSignature* graphics_root = nullptr; bool targets_bound = false; @@ -2560,6 +2570,7 @@ void __stdcall list_pipeline(Wrapper* self, void* pipeline) // a recognized desktop graphics pipeline just before it records the draw. pass.pipeline_real = available && !pass.indirect_graphics.root; pass.compute_pipeline = pass.pipeline_real && w->own().compute_pipeline; + pass.compute_pipeline_root = pass.compute_pipeline ? w->own().pipeline_root : nullptr; pass.pipeline = w && w->own().kind == pipeline_kind ? w : nullptr; InterlockedIncrement(pass.pipeline_real ? &render_pipelines_real : &render_pipelines_missing); if (auto* list = recording(self); list && pass.pipeline_real) list->SetPipelineState(static_cast(w->own().real)); @@ -2613,6 +2624,9 @@ void __stdcall list_compute_root(Wrapper* self, void* root) pass.compute_trace = std::make_unique(); pass.compute_trace->root = w; } + pass.compute_srv_bound = 0; + // Root SRV parameters are forwarded by their own slot; anything else the root declares is not. + pass.compute_root_has_arguments = real && !w->own().root_without_bindings && !w->own().root_srv_only; if (pass.compute_root) { if (pass.desktop_compute_root.Get() != pass.compute_root) pass.desktop_compute_upload_srvs.fill(0); @@ -3534,9 +3548,12 @@ void __stdcall list_compute_upload_srv(Wrapper* self, UINT parameter, UINT64 add if (!list || !params || parameter >= params->size() || parameter >= pass.desktop_compute_upload_srvs.size() || (*params)[parameter].type != D3D12_ROOT_PARAMETER_TYPE_SRV) return; const auto gpu = list_upload_gpu(self, address, 1); + // A rejected replacement leaves no valid binding: the desktop list may still hold the previous address. + if (parameter < 32) pass.compute_srv_bound &= ~(1u << parameter); if (gpu && !(gpu % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT)) { pass.desktop_compute_upload_srvs[parameter] = gpu; list->SetComputeRootShaderResourceView(parameter, gpu); + if (parameter < 32) pass.compute_srv_bound |= 1u << parameter; } } @@ -3589,6 +3606,30 @@ void __stdcall list_root_cbv(Wrapper* self, UINT parameter, u64 address) } pass.root_address[parameter] = (address && readable_window(address, 1)) ? address : 0; } +// List slot 14, Dispatch. Forwarded only with a desktop compute pipeline and root bound and group counts within the limit. +void __stdcall list_dispatch(Wrapper* self, UINT x, UINT y, UINT z) +{ + auto* list = recording(self); + x2w_startup::ListDispatch request; + request.list_open = list != nullptr; + if (list) request.type = list->GetType(); + const Pass& pass = pass_of(self); + request.compute_pipeline = pass.compute_pipeline; + request.compute_root = pass.compute_root != nullptr; + request.compute_root_has_arguments = pass.compute_root_has_arguments; + request.root_matches_pipeline = pass.compute_pipeline_root && pass.compute_pipeline_root == pass.compute_root; + const UINT count = pass.compute_params ? static_cast(pass.compute_params->size()) : 0; + request.root_arguments_bound = count <= 32 && (pass.compute_srv_bound & (count >= 32 ? ~0u : (1u << count) - 1)) == (count >= 32 ? ~0u : (1u << count) - 1); + request.x = x, request.y = y, request.z = z; + const x2w_startup::DispatchDecision decision = x2w_startup::decide_dispatch(request); + if (decision != x2w_startup::DispatchDecision::forward) { + static LONG refusals; + if (first_calls(refusals, 16)) + log("x2w-render Dispatch(%u, %u, %u) refused: %s", x, y, z, x2w_startup::dispatch_reason(decision)); + return; + } + list->Dispatch(x, y, z); +} extern LONG translated_draws, untranslated_draws, frame_number; bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UINT start, INT base_vertex, UINT start_instance); // List slot 12, DrawInstanced. @@ -5605,13 +5646,14 @@ HRESULT __stdcall device_create_pipeline_stream_x(Wrapper*, const D3D12_PIPELINE D3D12_RASTERIZER_DESC rasterizer{}; bool has_rasterizer = false; bool compute = false; + ID3D12RootSignature* pipeline_root = nullptr; IndirectGraphicsPipeline graphics; u64 mesh86_key = 0; if (render_mode()) { char why[256] = ""; // Recognized desktop stages must reach the native path before the // guest cache creates a pending translation for any DXBC container. - real_pipeline = build_stream_pipeline(desc, why, sizeof(why), compute, graphics); + real_pipeline = build_stream_pipeline(desc, why, sizeof(why), compute, graphics, pipeline_root); bool mesh_cache_request = false; if (!real_pipeline) real_pipeline = try_cached_mesh86(*desc, why, sizeof(why), graphics, mesh_cache_request, mesh86_key); @@ -5624,6 +5666,7 @@ HRESULT __stdcall device_create_pipeline_stream_x(Wrapper*, const D3D12_PIPELINE } *out = wrap(real_pipeline, pipeline_kind); static_cast(*out)->own().compute_pipeline = real_pipeline && compute; + static_cast(*out)->own().pipeline_root = pipeline_root; static_cast(*out)->own().indirect_graphics = graphics; static_cast(*out)->own().mesh86_key = mesh86_key; note_pipeline(static_cast(*out), 86, nullptr, desc->pPipelineStateSubobjectStream, desc->SizeInBytes < 0x2000 ? desc->SizeInBytes : 0x2000, @@ -6252,6 +6295,7 @@ void build_tables() list_typed[139] = reinterpret_cast(&list_reset); list_typed[148] = reinterpret_cast(&list_allocate_upload); list_typed[12] = reinterpret_cast(&list_draw); + list_typed[14] = reinterpret_cast(&list_dispatch); list_typed[16] = reinterpret_cast(&list_copy_texture); list_typed[20] = reinterpret_cast(&list_topology); list_typed[21] = reinterpret_cast(&list_viewports); diff --git a/src/startup_stubs/list_dispatch.h b/src/startup_stubs/list_dispatch.h new file mode 100644 index 000000000..102446d71 --- /dev/null +++ b/src/startup_stubs/list_dispatch.h @@ -0,0 +1,58 @@ +#pragma once + +// Command-list slot 14, Dispatch(x, y, z). A dispatch is forwarded to the desktop list only when the list is open, +// can run compute, a desktop compute pipeline and a desktop compute root signature are bound, the compute root declares +// no parameters other than root SRVs (of the compute root-argument slots, only slot 43 (root SRV) is forwarded; 35, 37, 39, 41 and 45 are not forwarded yet, so a root that needs +// arguments would run with them unset), and every group count is within the D3D12 limit of 65535 per dimension. Zero groups on any axis is valid and runs nothing. + +#include + +namespace x2w_startup { + +constexpr UINT max_dispatch_groups = 65535; + +struct ListDispatch { + bool list_open = false; + D3D12_COMMAND_LIST_TYPE type = D3D12_COMMAND_LIST_TYPE_DIRECT; + bool compute_pipeline = false; // the bound pipeline is a desktop compute pipeline + bool compute_root = false; // the bound compute root signature is a desktop root signature + bool compute_root_has_arguments = false; // that root declares parameters or static samplers + bool root_matches_pipeline = true; // the compute pipeline was built against the bound compute root + bool root_arguments_bound = true; // every root SRV the root declares reached the desktop list (a rejected set clears it) + UINT x = 0, y = 0, z = 0; +}; + +enum class DispatchDecision { forward, list_closed, wrong_list_type, no_compute_state, unforwarded_root_arguments, + root_pipeline_mismatch, unbound_root_argument, group_count_over_limit }; +constexpr int dispatch_decision_count = 8; + +inline const char* dispatch_reason(DispatchDecision decision) +{ + switch (decision) { + case DispatchDecision::forward: return "forward"; + case DispatchDecision::list_closed: return "list is closed"; + case DispatchDecision::wrong_list_type: return "requires a direct or compute command list"; + case DispatchDecision::no_compute_state: return "requires a desktop compute pipeline and root"; + case DispatchDecision::unforwarded_root_arguments: return "compute root arguments are not forwarded"; + case DispatchDecision::root_pipeline_mismatch: return "compute pipeline was built against another root signature"; + case DispatchDecision::unbound_root_argument: return "a compute root SRV is not bound"; + case DispatchDecision::group_count_over_limit: return "group count is over 65535"; + } + return "unknown"; +} + +inline DispatchDecision decide_dispatch(const ListDispatch& d) +{ + if (!d.list_open) return DispatchDecision::list_closed; + if (d.type != D3D12_COMMAND_LIST_TYPE_DIRECT && d.type != D3D12_COMMAND_LIST_TYPE_COMPUTE) + return DispatchDecision::wrong_list_type; + if (!d.compute_pipeline || !d.compute_root) return DispatchDecision::no_compute_state; + if (d.compute_root_has_arguments) return DispatchDecision::unforwarded_root_arguments; + if (!d.root_matches_pipeline) return DispatchDecision::root_pipeline_mismatch; + if (!d.root_arguments_bound) return DispatchDecision::unbound_root_argument; + if (d.x > max_dispatch_groups || d.y > max_dispatch_groups || d.z > max_dispatch_groups) + return DispatchDecision::group_count_over_limit; + return DispatchDecision::forward; +} + +} // namespace x2w_startup diff --git a/src/startup_stubs/mesh86_cache.inl b/src/startup_stubs/mesh86_cache.inl index 175671c9b..0c2fe5b3e 100644 --- a/src/startup_stubs/mesh86_cache.inl +++ b/src/startup_stubs/mesh86_cache.inl @@ -255,7 +255,8 @@ ID3D12PipelineState* try_cached_mesh86(const D3D12_PIPELINE_STATE_STREAM_DESC& d std::memcpy(request.stream.data() + request.root_offset + 8, &request.root, sizeof(request.root)); const D3D12_PIPELINE_STATE_STREAM_DESC desktop{request.stream.size(), request.stream.data()}; bool compute = false; - auto* result = build_stream_pipeline(&desktop, why, why_size, compute, graphics, + ID3D12RootSignature* pipeline_root = nullptr; + auto* result = build_stream_pipeline(&desktop, why, why_size, compute, graphics, pipeline_root, static_cast(request.root->own().real)); if (result) graphics.cached_srv_root = srv_root; static LONG loaded; diff --git a/tests/startup_list_dispatch_check.cpp b/tests/startup_list_dispatch_check.cpp new file mode 100644 index 000000000..17abf3648 --- /dev/null +++ b/tests/startup_list_dispatch_check.cpp @@ -0,0 +1,90 @@ +// Checks src/startup_stubs/list_dispatch.h without a device: when command-list slot 14 (Dispatch) is forwarded to the +// desktop list and which refusal applies otherwise. Expectations are written out below, not computed with the header. +// +// startup_list_dispatch_check [--mutate no-limit|no-state|no-root-args|no-pairing|no-bound] +// +// The mutations change the expectations to those of a wrong decision (no group-count limit, a forward without a +// compute pipeline and root, or a forward with unforwarded compute root arguments); each must make the check fail. +#include "startup_stubs/list_dispatch.h" + +#include +#include + +namespace { +using namespace x2w_startup; +using D = DispatchDecision; +int failures, cases; +bool no_limit, no_state, no_root_args, no_pairing, no_bound; + +void expect(const char* label, const ListDispatch& in, D expected) +{ + ++cases; + const D got = decide_dispatch(in); + if (got == expected) return; + ++failures; + std::printf("FAIL %s: expected '%s', got '%s'\n", label, dispatch_reason(expected), dispatch_reason(got)); +} + +ListDispatch ready(UINT x, UINT y, UINT z) +{ + ListDispatch d; + d.list_open = true; + d.compute_pipeline = d.compute_root = true; + d.x = x, d.y = y, d.z = z; + return d; +} +} // namespace + +int main(int argc, char** argv) +{ + if (argc == 3 && !std::strcmp(argv[1], "--mutate")) { + no_limit = !std::strcmp(argv[2], "no-limit"); + no_state = !std::strcmp(argv[2], "no-state"); + no_root_args = !std::strcmp(argv[2], "no-root-args"); + no_pairing = !std::strcmp(argv[2], "no-pairing"); + no_bound = !std::strcmp(argv[2], "no-bound"); + if (!no_limit && !no_state && !no_root_args && !no_pairing && !no_bound) return 2; + } + expect("one group", ready(1, 1, 1), D::forward); + expect("limit on every axis", ready(65535, 65535, 65535), D::forward); + expect("zero groups", ready(0, 5, 5), D::forward); + expect("x over limit", ready(65536, 1, 1), no_limit ? D::forward : D::group_count_over_limit); + expect("y over limit", ready(1, 65536, 1), no_limit ? D::forward : D::group_count_over_limit); + expect("z over limit", ready(1, 1, 0xffffffffu), no_limit ? D::forward : D::group_count_over_limit); + ListDispatch d = ready(8, 1, 1); + d.compute_pipeline = false; + expect("graphics pipeline bound", d, no_state ? D::forward : D::no_compute_state); + d = ready(8, 1, 1); + d.compute_root = false; + expect("no compute root", d, no_state ? D::forward : D::no_compute_state); + d = ready(8, 1, 1); + d.compute_root_has_arguments = true; // e.g. a root UAV set through slot 45, which is not forwarded + expect("root with arguments", d, no_root_args ? D::forward : D::unforwarded_root_arguments); + d.x = 0; + expect("root with arguments, zero groups", d, no_root_args ? D::forward : D::unforwarded_root_arguments); + d = ready(8, 1, 1); + d.root_matches_pipeline = false; // pipeline built against a different root signature + expect("root and pipeline differ", d, no_pairing ? D::forward : D::root_pipeline_mismatch); + d = ready(8, 1, 1); + d.root_arguments_bound = false; // a root SRV was never set, or a replacement was rejected + expect("unbound root SRV", d, no_bound ? D::forward : D::unbound_root_argument); + d.x = 0; + expect("unbound root SRV, zero groups", d, no_bound ? D::forward : D::unbound_root_argument); + d = ready(8, 1, 1); + d.root_matches_pipeline = d.root_arguments_bound = true; + expect("paired root with every SRV bound", d, D::forward); + d = ready(8, 1, 1); + d.list_open = false; + expect("closed list", d, D::list_closed); + d = ready(8, 1, 1); + d.type = D3D12_COMMAND_LIST_TYPE_COPY; + expect("copy list", d, D::wrong_list_type); + d.type = D3D12_COMMAND_LIST_TYPE_COMPUTE; + expect("compute list", d, D::forward); + if (failures) { + std::printf("%d of %d cases failed\n", failures, cases); + return 1; + } + std::printf("%d cases passed\n", cases); + return 0; +} diff --git a/tests/startup_list_dispatch_native.cpp b/tests/startup_list_dispatch_native.cpp new file mode 100644 index 000000000..25586fde2 --- /dev/null +++ b/tests/startup_list_dispatch_native.cpp @@ -0,0 +1,440 @@ +// Command-list slot 14 (Dispatch) driven through the d3d12_xs stand-in on a desktop device. Slots 86 (compute +// pipeline stream), 25 (pipeline), 33 (compute root), 43 (compute root SRV in the recording's upload pages), 148 +// (upload allocation), 9 (Close) and 139 (Reset) set up each case. A refused call must log exactly one +// "x2w-render Dispatch(x, y, z) refused: " line to %X2W_TRAP_LOG% and record nothing. A forwarded call must +// log no line, and the desktop Dispatch is observed through a pipeline-statistics query that the fixture wraps +// around the slot 14 call on the underlying desktop list: CSInvocations is groups * 4 for a forwarded call and 0 +// for a refused one. The root SRV roots carry no UAV, so the shader writes nothing; the invocation count is the +// result. The recordings are executed to a fence, and the debug layer, when present, must report no error. +// +// `skip-srv` is the negative control: the first forwarded case omits slot 43, so the fixture must fail on it. +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); + +namespace { +using Microsoft::WRL::ComPtr; + +void check(HRESULT hr, const char* stage) +{ + if (FAILED(hr)) { + std::fprintf(stderr, "%s failed (HRESULT 0x%08lx)\n", stage, static_cast(hr)); + throw std::runtime_error(stage); + } +} + +template +Method slot(IUnknown* object, unsigned index) +{ + return reinterpret_cast((*reinterpret_cast(object))[index]); +} + +using Bind = void(WINAPI*)(IUnknown*, IUnknown*); +using Address = void(WINAPI*)(IUnknown*, UINT, UINT64); +using Dispatch = void(WINAPI*)(IUnknown*, UINT, UINT, UINT); +using Upload = void*(WINAPI*)(IUnknown*, UINT64, UINT64); +using Reset = HRESULT(WINAPI*)(IUnknown*, IUnknown*, void*, void*); +using Close = HRESULT(WINAPI*)(IUnknown*); + +constexpr UINT threads_per_group = 4; +constexpr char shader[] = R"( +ByteAddressBuffer input : register(t0); +[numthreads(4, 1, 1)] +void main() {} +)"; + +template +ComPtr native_object(ID3D12Device* device, ID3D12Device* guest, IUnknown* object) +{ + // SetPrivateDataInterface unwraps a guest argument before the call reaches the shared desktop device. + constexpr GUID key{0x10a62244, 0x1615, 0x4953, {0xa2, 0x52, 0xbe, 0x42, 0x35, 0x27, 0xa0, 0x61}}; + check(guest->SetPrivateDataInterface(key, object), "publish underlying object"); + ComPtr stored; + UINT bytes = sizeof(IUnknown*); + const HRESULT read = device->GetPrivateData(key, &bytes, stored.GetAddressOf()); + check(guest->SetPrivateDataInterface(key, nullptr), "clear underlying object"); + check(read, "retrieve underlying object"); + ComPtr result; + check(stored.As(&result), "query underlying object"); + return result; +} + +ComPtr guest_root(ID3D12Device* guest, const D3D12_ROOT_SIGNATURE_DESC& desc, const char* name) +{ + ComPtr serialized, errors; + check(D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &serialized, &errors), name); + ComPtr result; + check(guest->CreateRootSignature(0, serialized->GetBufferPointer(), serialized->GetBufferSize(), IID_PPV_ARGS(&result)), + name); + return result; +} + +// A compute pipeline created through device slot 86 (pipeline state stream) against a guest root. +ComPtr guest_pipeline(ID3D12Device* guest, ID3D12RootSignature* root, ID3DBlob* code) +{ + struct { + alignas(void*) D3D12_PIPELINE_STATE_SUBOBJECT_TYPE root_type; + ID3D12RootSignature* root; + alignas(void*) D3D12_PIPELINE_STATE_SUBOBJECT_TYPE cs_type; + D3D12_SHADER_BYTECODE code; + } stream{D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS, {code->GetBufferPointer(), code->GetBufferSize()}}; + const D3D12_PIPELINE_STATE_STREAM_DESC desc{sizeof(stream), &stream}; + using Create = HRESULT(WINAPI*)(IUnknown*, const D3D12_PIPELINE_STATE_STREAM_DESC*, REFIID, void**); + ComPtr result; + check(slot(guest, 86)(guest, &desc, __uuidof(ID3D12PipelineState), reinterpret_cast(result.GetAddressOf())), + "create guest compute pipeline"); + return result; +} + +std::wstring log_path; +std::size_t lines_seen = 0; + +// The Dispatch lines logged since the previous call. +std::vector new_dispatch_lines() +{ + std::vector all; + std::ifstream file(log_path, std::ios::binary); + std::string line; + while (std::getline(file, line)) { + while (!line.empty() && (line.back() == '\r' || line.back() == '\n')) line.pop_back(); + if (line.rfind("x2w-render Dispatch(", 0) == 0) all.push_back(line); + } + std::vector fresh; + if (all.size() > lines_seen) fresh.assign(all.begin() + static_cast(lines_seen), all.end()); + lines_seen = all.size(); + return fresh; +} + +struct Case { + const char* label; + UINT x, y, z; + const char* reason; // null: the call is forwarded + int query; // pipeline-statistics query index, or -1 on a closed list +}; + +class Fixture { +public: + Fixture(ID3D12Device* device, ID3D12Device* guest, bool skip_srv) : device_(device), guest_(guest), skip_srv_(skip_srv) + { + ComPtr errors; + const HRESULT hr = D3DCompile(shader, sizeof(shader) - 1, nullptr, nullptr, nullptr, "main", "cs_5_0", 0, 0, + &code_, &errors); + if (FAILED(hr) && errors) std::fprintf(stderr, "%s\n", static_cast(errors->GetBufferPointer())); + check(hr, "compile compute shader"); + + // root_a: one root SRV (t0). root_b: two root SRVs (t0, t1), so its serialized form and desktop object differ + // from root_a's. root_table: one descriptor table. root_sampler: no parameters, one static sampler. + D3D12_ROOT_PARAMETER srvs[2]{}; + for (UINT i = 0; i < 2; ++i) { + srvs[i].ParameterType = D3D12_ROOT_PARAMETER_TYPE_SRV; + srvs[i].Descriptor = {i, 0}; + srvs[i].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + } + root_a_ = guest_root(guest, {1, srvs, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}, "create root with one root SRV"); + root_b_ = guest_root(guest, {2, srvs, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}, "create root with two root SRVs"); + const D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; + D3D12_ROOT_PARAMETER table{}; + table.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + table.DescriptorTable = {1, &range}; + table.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + root_table_ = guest_root(guest, {1, &table, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}, "create root with a table"); + D3D12_STATIC_SAMPLER_DESC sampler{}; + sampler.Filter = D3D12_FILTER_MIN_MAG_MIP_POINT; + sampler.AddressU = sampler.AddressV = sampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; + sampler.MaxLOD = D3D12_FLOAT32_MAX; + sampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + root_sampler_ = guest_root(guest, {0, nullptr, 1, &sampler, D3D12_ROOT_SIGNATURE_FLAG_NONE}, + "create root with a static sampler"); + pso_a_ = guest_pipeline(guest, root_a_.Get(), code_.Get()); + pso_b_ = guest_pipeline(guest, root_b_.Get(), code_.Get()); + pso_table_ = guest_pipeline(guest, root_table_.Get(), code_.Get()); + pso_sampler_ = guest_pipeline(guest, root_sampler_.Get(), code_.Get()); + + const D3D12_QUERY_HEAP_DESC heap_desc{D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS, max_queries, 0}; + check(device->CreateQueryHeap(&heap_desc, IID_PPV_ARGS(&queries_)), "create pipeline-statistics query heap"); + D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; + D3D12_RESOURCE_DESC buffer{}; + buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + buffer.Width = max_queries * sizeof(D3D12_QUERY_DATA_PIPELINE_STATISTICS); + buffer.Height = buffer.DepthOrArraySize = buffer.MipLevels = buffer.SampleDesc.Count = 1; + buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + check(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COPY_DEST, + nullptr, IID_PPV_ARGS(&readback_)), "create query readback buffer"); + const D3D12_COMMAND_QUEUE_DESC queue_desc{}; + check(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue_)), "create desktop queue"); + check(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence_)), "create completion fence"); + + check(guest->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator_)), "create guest allocator"); + using CreateList = HRESULT(WINAPI*)(IUnknown*, const void*, IUnknown*, IUnknown*, REFIID, void**); + const UINT list_desc[]{D3D12_COMMAND_LIST_TYPE_DIRECT, 2, 1, 0}; + check(slot(guest, 73)(guest, list_desc, allocator_.Get(), nullptr, __uuidof(ID3D12GraphicsCommandList), + reinterpret_cast(list_.GetAddressOf())), "create guest command list"); + native_ = native_object(device, guest, list_.Get()); + } + + bool run() + { + // Recording 1: the fully bound call alone, executed and counted before any refused case runs. + reset(); + bool ok = expect({"bound", 2, 3, 1, nullptr, 0}, [&] { + bind(pso_a_.Get(), root_a_.Get()); + if (!skip_srv_) srv(upload_); + }); + if (!ok) return false; + resolve(1); + check(slot(list_.Get(), 9)(list_.Get()), "close first recording"); + if (!execute(0, 1)) return false; + + // Recording 2: each refusal after a fresh Close, so no binding is left over from recording 1. + reset(); + ok = expect({"root SRV never set", 3, 1, 1, "a compute root SRV is not bound", 0}, + [&] { bind(pso_a_.Get(), root_a_.Get()); }); + ok = ok && expect({"rejected replacement after a valid root SRV", 4, 1, 1, "a compute root SRV is not bound", 1}, [&] { + bind(pso_a_.Get(), root_a_.Get()); + srv(upload_); + srv(reinterpret_cast(&foreign_)); // not in this recording's upload pages + }); + ok = ok && expect({"misaligned replacement after a valid root SRV", 5, 1, 1, "a compute root SRV is not bound", 2}, [&] { + bind(pso_a_.Get(), root_a_.Get()); + srv(upload_); + srv(upload_ + 2); // in the upload pages, not 4-byte aligned + }); + ok = ok && expect({"root changed and changed back", 6, 1, 1, "a compute root SRV is not bound", 3}, [&] { + bind(pso_a_.Get(), root_a_.Get()); + srv(upload_); + root(root_b_.Get()); + root(root_a_.Get()); + }); + ok = ok && expect({"pipeline built against another root", 7, 1, 1, + "compute pipeline was built against another root signature", 4}, [&] { + bind(pso_b_.Get(), root_a_.Get()); + srv(upload_); + }); + ok = ok && expect({"root with a descriptor table", 8, 1, 1, "compute root arguments are not forwarded", 5}, + [&] { bind(pso_table_.Get(), root_table_.Get()); }); + ok = ok && expect({"root with a static sampler", 9, 1, 1, "compute root arguments are not forwarded", 6}, + [&] { bind(pso_sampler_.Get(), root_sampler_.Get()); }); + ok = ok && expect({"root SRV never set, zero groups", 0, 10, 1, "a compute root SRV is not bound", 7}, + [&] { bind(pso_a_.Get(), root_a_.Get()); }); + ok = ok && expect({"bound, X over the limit", 65536, 1, 1, "group count is over 65535", 8}, [&] { + bind(pso_a_.Get(), root_a_.Get()); + srv(upload_); + }); + ok = ok && expect({"bound, zero groups", 0, 1, 1, nullptr, 9}, [] {}); + ok = ok && expect({"valid root SRV after a rejected one", 1, 2, 1, nullptr, 10}, [&] { + srv(reinterpret_cast(&foreign_)); + srv(upload_); + }); + if (!ok) return false; + resolve(11); + check(slot(list_.Get(), 9)(list_.Get()), "close second recording"); + // Close drops the recording's bindings; a Dispatch on the closed list is refused before any of them. + if (!expect({"closed list", 11, 1, 1, "list is closed", -1}, [] {})) return false; + if (!execute(0, 11)) return false; + + // Recording 3: Reset without rebinding, then rebound. + reset(); + ok = expect({"after Reset without rebinding", 12, 1, 1, "requires a desktop compute pipeline and root", 0}, [] {}); + ok = ok && expect({"rebound after Reset", 2, 2, 1, nullptr, 1}, [&] { + bind(pso_a_.Get(), root_a_.Get()); + srv(upload_); + }); + if (!ok) return false; + resolve(2); + check(slot(list_.Get(), 9)(list_.Get()), "close third recording"); + return execute(0, 2); + } + +private: + static constexpr UINT max_queries = 16; + + void reset() + { + check(slot(list_.Get(), 139)(list_.Get(), allocator_.Get(), nullptr, nullptr), "reset guest command list"); + upload_ = reinterpret_cast(slot(list_.Get(), 148)(list_.Get(), 256, 256)); + if (!upload_) throw std::runtime_error("allocate upload pages through slot 148"); + expected_.clear(); + } + void bind(IUnknown* pipeline, IUnknown* root_signature) + { + slot(list_.Get(), 25)(list_.Get(), pipeline); + root(root_signature); + } + void root(IUnknown* root_signature) { slot(list_.Get(), 33)(list_.Get(), root_signature); } + void srv(UINT64 address) { slot
(list_.Get(), 43)(list_.Get(), 0, address); } + + template + bool expect(const Case& c, Setup setup) + { + setup(); + if (c.query >= 0) native_->BeginQuery(queries_.Get(), D3D12_QUERY_TYPE_PIPELINE_STATISTICS, c.query); + slot(list_.Get(), 14)(list_.Get(), c.x, c.y, c.z); + if (c.query >= 0) native_->EndQuery(queries_.Get(), D3D12_QUERY_TYPE_PIPELINE_STATISTICS, c.query); + char wanted[256] = ""; + if (c.reason) std::snprintf(wanted, sizeof(wanted), "x2w-render Dispatch(%u, %u, %u) refused: %s", c.x, c.y, c.z, c.reason); + const auto lines = new_dispatch_lines(); + const bool matched = c.reason ? lines.size() == 1 && lines[0] == wanted : lines.empty(); + if (!matched) { + std::fprintf(stderr, "%s: expected %s%s, got %zu Dispatch line(s)\n", c.label, c.reason ? "exactly " : "no Dispatch line", + wanted, lines.size()); + for (const auto& line : lines) std::fprintf(stderr, " %s\n", line.c_str()); + return false; + } + std::printf("%s: Dispatch(%u, %u, %u) %s%s\n", c.label, c.x, c.y, c.z, c.reason ? "refused: " : "forwarded", + c.reason ? c.reason : ""); + if (c.query >= 0) + expected_.push_back({c.label, c.reason ? 0 : UINT64{c.x} * c.y * c.z * threads_per_group}); + return true; + } + + void resolve(UINT count) + { + native_->ResolveQueryData(queries_.Get(), D3D12_QUERY_TYPE_PIPELINE_STATISTICS, 0, count, readback_.Get(), 0); + } + + bool execute(UINT first, UINT count) + { + ID3D12CommandList* lists[]{native_.Get()}; + queue_->ExecuteCommandLists(1, lists); + check(queue_->Signal(fence_.Get(), ++fence_value_), "signal completion fence"); + check(fence_->SetEventOnCompletion(fence_value_, nullptr), "wait for completion"); + check(device_->GetDeviceRemovedReason(), "GPU completion"); + void* mapped = nullptr; + const D3D12_RANGE read{0, count * sizeof(D3D12_QUERY_DATA_PIPELINE_STATISTICS)}; + check(readback_->Map(0, &read, &mapped), "map query readback"); + std::vector stats(count); + std::memcpy(stats.data(), mapped, read.End); + const D3D12_RANGE untouched{0, 0}; + readback_->Unmap(0, &untouched); + if (expected_.size() != count) { + std::fprintf(stderr, "internal: %zu queries recorded, %u resolved\n", expected_.size(), count); + return false; + } + bool ok = true; + for (UINT i = first; i < count; ++i) { + const UINT64 got = stats[i].CSInvocations; + std::printf(" query %u (%s): CSInvocations %llu (expected %llu)\n", i, expected_[i].label, + static_cast(got), static_cast(expected_[i].invocations)); + if (got != expected_[i].invocations) { + std::fprintf(stderr, "%s: CSInvocations %llu, expected %llu\n", expected_[i].label, + static_cast(got), static_cast(expected_[i].invocations)); + ok = false; + } + } + return ok; + } + + struct Expected { + const char* label; + UINT64 invocations; + }; + ID3D12Device* device_; + ID3D12Device* guest_; + bool skip_srv_; + ComPtr code_; + ComPtr root_a_, root_b_, root_table_, root_sampler_; + ComPtr pso_a_, pso_b_, pso_table_, pso_sampler_; + ComPtr queries_; + ComPtr readback_; + ComPtr queue_; + ComPtr fence_; + UINT64 fence_value_ = 0; + ComPtr allocator_; + ComPtr list_; + ComPtr native_; + UINT64 upload_ = 0; + std::uint32_t foreign_ = 0; + std::vector expected_; +}; +} // namespace + +int main(int argc, char** argv) try +{ + const bool warp = argc >= 2 && std::strcmp(argv[1], "warp") == 0; + if (!warp && (argc < 2 || std::strcmp(argv[1], "hardware") != 0)) return 2; + const bool skip_srv = argc == 3 && std::strcmp(argv[2], "skip-srv") == 0; + if (argc > 3 || (argc == 3 && !skip_srv)) return 2; + ComPtr debug; + const HRESULT debug_hr = D3D12GetDebugInterface(IID_PPV_ARGS(&debug)); + if (debug_hr != DXGI_ERROR_SDK_COMPONENT_MISSING) check(debug_hr, "get debug layer"); + if (debug) debug->EnableDebugLayer(); + ComPtr factory; + check(CreateDXGIFactory1(IID_PPV_ARGS(&factory)), "create DXGI factory"); + ComPtr adapter; + if (warp) { + check(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)), "find WARP"); + } else { + bool found = false; + for (UINT index = 0; factory->EnumAdapters1(index, adapter.ReleaseAndGetAddressOf()) == S_OK; ++index) { + DXGI_ADAPTER_DESC1 desc{}; + if (SUCCEEDED(adapter->GetDesc1(&desc)) && !(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && + SUCCEEDED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) { + found = true; + break; + } + } + if (!found) return 77; + } + wchar_t directory[MAX_PATH]; + if (!GetTempPathW(MAX_PATH, directory)) return 4; + log_path = std::wstring(directory) + L"x2w_list_dispatch_" + std::to_wstring(GetCurrentProcessId()) + L".log"; + DeleteFileW(log_path.c_str()); + SetEnvironmentVariableW(L"X2W_TRAP_LOG", log_path.c_str()); + SetEnvironmentVariableA("X2W_D3D12_DEBUG", "0"); // keep the debug messages for the check below + ComPtr device; + check(D3D12XboxCreateDevice(adapter.Get(), nullptr, IID_PPV_ARGS(&device)), "create desktop device through d3d12_xs"); + SetEnvironmentVariableA("X2W_D3D12_PERMISSIVE", "1"); + SetEnvironmentVariableA("X2W_D3D12_LIST_NOOP", "1"); + SetEnvironmentVariableA("X2W_D3D12_RENDER", "1"); + const std::array parameters{}; + ComPtr guest; + check(D3D12XboxCreateDevice(adapter.Get(), parameters.data(), IID_PPV_ARGS(&guest)), "create guest device"); + DXGI_ADAPTER_DESC1 adapter_desc{}; + check(adapter->GetDesc1(&adapter_desc), "get adapter description"); + std::printf("adapter: %ls, debug layer %s\n", adapter_desc.Description, debug ? "enabled" : "unavailable"); + LARGE_INTEGER driver{}; + if (SUCCEEDED(adapter->CheckInterfaceSupport(__uuidof(IDXGIDevice), &driver))) + std::printf("driver: %u.%u.%u.%u\n", HIWORD(driver.HighPart), LOWORD(driver.HighPart), HIWORD(driver.LowPart), + LOWORD(driver.LowPart)); + ComPtr info; + if (debug) check(device.As(&info), "get debug message queue"); + + bool ok = false; + { + Fixture fixture(device.Get(), guest.Get(), skip_srv); + ok = fixture.run(); + } + if (info) { + for (UINT64 i = 0; i < info->GetNumStoredMessages(); ++i) { + SIZE_T bytes = 0; + check(info->GetMessage(i, nullptr, &bytes), "get debug message size"); + std::vector storage(bytes); + auto* message = reinterpret_cast(storage.data()); + check(info->GetMessage(i, message, &bytes), "get debug message"); + if (message->Severity <= D3D12_MESSAGE_SEVERITY_ERROR) { + std::fprintf(stderr, "D3D12 debug message %u: %s\n", static_cast(message->ID), message->pDescription); + ok = false; + } + } + } + DeleteFileW(log_path.c_str()); + if (ok) std::printf("all slot 14 cases matched\n"); + return ok ? 0 : 1; +} +catch (const std::exception&) { + return 3; +} From a8f2d2504a5d53486f50335f2c6297cea393f3dd Mon Sep 17 00:00:00 2001 From: tedin7 <110300616+tedin7@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:20:42 +0100 Subject: [PATCH 027/240] startup: implement command-list slots 37 and 39 root constants and views (Part of #870) (#1975) * startup: record SetComputeRoot32BitConstant(s) (list slots 37, 39) Compute root constants are kept per list next to the graphics ones, in a shared 16 x 8 word store that refuses parameter >= 16 and offset >= 8. A new compute root signature clears them. * fix: track which compute root constant words were set; drop slot 40 claim --- CMakeLists.txt | 4 ++ src/startup_stubs/d3d12_draw.inl | 21 ++++++++ src/startup_stubs/d3d12_xs_device.cpp | 8 ++++ src/startup_stubs/root_constant_store.h | 64 +++++++++++++++++++++++++ tests/startup_root_constant_store.cpp | 62 ++++++++++++++++++++++++ 5 files changed, 159 insertions(+) create mode 100644 src/startup_stubs/root_constant_store.h create mode 100644 tests/startup_root_constant_store.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index f88d0d2e9..f69ff19d8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -941,6 +941,10 @@ endforeach() add_executable(startup_command_list_slot_names tests/startup_command_list_slot_names.cpp) target_compile_features(startup_command_list_slot_names PRIVATE cxx_std_17) add_test(NAME startup_command_list_slot_names COMMAND startup_command_list_slot_names) +# Root constants kept per recorded list (src/startup_stubs/root_constant_store.h, compute list slots 37 and 39, #870; slot 40 keeps its own graphics words). +add_executable(startup_root_constant_store tests/startup_root_constant_store.cpp) +target_compile_features(startup_root_constant_store PRIVATE cxx_std_17) +add_test(NAME startup_root_constant_store COMMAND startup_root_constant_store) # Game-save stand-in storage (src/startup_stubs/save_store.h): a blob written by one process is read by a second. add_executable(startup_gamesave_persist tests/startup_gamesave_persist.cpp) target_compile_features(startup_gamesave_persist PRIVATE cxx_std_17) diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index ecd416690..b81819f68 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -2444,6 +2444,17 @@ void __stdcall list_compute_table(Wrapper* self, UINT parameter, u64 gpu_handle) log("x2w-render compute descriptor table dropped: parameter %u (%u parameters are kept)", parameter, x2w_startup::ComputeTables::max_parameters); } +// Keeps the words of a root constants call; a call outside the 16 x 8 words kept is logged and cut or dropped. +static void store_root_constants(x2w_root_constants::Store& store, const char* kind, UINT parameter, UINT count, + const std::uint32_t* data, UINT offset) +{ + if (!count || !x2w_local::readable(data, std::size_t{count} * 4)) return; + const auto result = store.set(parameter, count, data, offset); + static LONG refused; + if (result != x2w_root_constants::Result::stored && first_calls(refused, 4)) + log("x2w-render %s root constants %s: parameter %u, offset %u, count %u (16 parameters of 8 words are kept)", kind, + result == x2w_root_constants::Result::dropped ? "dropped" : "truncated", parameter, offset, count); +} // List slot 40 (desktop 36 + 4), SetGraphicsRoot32BitConstants(parameter, count, data, offset). void __stdcall list_root_constants(Wrapper* self, UINT parameter, UINT count, const std::uint32_t* data, UINT offset) { @@ -2459,6 +2470,16 @@ void __stdcall list_root_constants(Wrapper* self, UINT parameter, UINT count, co count <= 8 - offset && offset + count <= (*pass.root)[parameter].constants_count) pass.constant_words_bound[parameter] |= static_cast(((1u << count) - 1) << offset); } +// List slot 37 (desktop 33 + 4), SetComputeRoot32BitConstant(parameter, value, offset). +void __stdcall list_compute_constant(Wrapper* self, UINT parameter, UINT value, UINT offset) +{ + store_root_constants(pass_of(self).compute_constants, "compute", parameter, 1, &value, offset); +} +// List slot 39 (desktop 35 + 4), SetComputeRoot32BitConstants(parameter, count, data, offset). +void __stdcall list_compute_constants(Wrapper* self, UINT parameter, UINT count, const std::uint32_t* data, UINT offset) +{ + store_root_constants(pass_of(self).compute_constants, "compute", parameter, count, data, offset); +} // List slot 47 (desktop 43 + 4), IASetIndexBuffer(view). void __stdcall list_index_buffer(Wrapper* self, const D3D12_INDEX_BUFFER_VIEW* view) { diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 85d004b4d..74b148149 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -64,6 +64,7 @@ #include "descriptor_heap_type.h" #include "small_texture_4k.h" #include "null_binding_cause.h" +#include "root_constant_store.h" #include "null_texture_view.h" #include "packed_target_format.h" #include "present_view_format.h" @@ -2418,6 +2419,8 @@ struct Pass { u64 root_address[16] = {}; // title address of each root descriptor std::uint32_t constants[16][8] = {}; unsigned char constant_words_bound[16] = {}; + x2w_root_constants::Store compute_constants; // compute root constants (slots 37 and 39) + Wrapper* compute_root_wrapper = nullptr; // compute root signature last set by slot 33 D3D12_VERTEX_BUFFER_VIEW vb[8] = {}; PlacedVertexView placed_vb[8] = {}; D3D12_INDEX_BUFFER_VIEW ib = {}; @@ -2616,6 +2619,9 @@ void __stdcall list_compute_root(Wrapper* self, void* root) if (!list) return; Wrapper* w = as_wrapper(root); Pass& pass = pass_of(self); + // A different root signature invalidates the title's cached compute root arguments. + if (pass.compute_root_wrapper != w) pass.compute_constants.clear(); + pass.compute_root_wrapper = w; const bool real = w && w->own().kind == root_signature_kind && w->own().real && !root_heap_flags(w); pass.compute_root = real ? static_cast(w->own().real) : nullptr; pass.compute_tables.set_signature(w ? root_info(w) : nullptr); // a different signature leaves no table bound @@ -6314,6 +6320,8 @@ void build_tables() list_typed[13] = reinterpret_cast(&list_draw_indexed); list_typed[35] = reinterpret_cast(&list_compute_table); list_typed[36] = reinterpret_cast(&list_table); + list_typed[37] = reinterpret_cast(&list_compute_constant); + list_typed[39] = reinterpret_cast(&list_compute_constants); list_typed[40] = reinterpret_cast(&list_root_constants); list_typed[47] = reinterpret_cast(&list_index_buffer); list_typed[48] = reinterpret_cast(&list_vertex_buffers); diff --git a/src/startup_stubs/root_constant_store.h b/src/startup_stubs/root_constant_store.h new file mode 100644 index 000000000..45b991400 --- /dev/null +++ b/src/startup_stubs/root_constant_store.h @@ -0,0 +1,64 @@ +// Experimental (docs/startup-runtime.md, #870): the 32-bit compute root arguments a recorded command list keeps +// (list slots 37 and 39; the graphics slot 40 keeps its own words). Plain standard C++ with no Windows types, so it can be tested on its own. +// +// A list keeps 16 root parameters of 8 words each. A write that starts past those limits is dropped and one +// that runs past them is cut off at the end of the parameter, so the caller can log either case. +#pragma once + +#include +#include + +namespace x2w_root_constants { + +inline constexpr unsigned parameter_count = 16; +inline constexpr unsigned words_per_parameter = 8; + +enum class Result { stored, truncated, dropped }; + +struct Store { + std::uint32_t words[parameter_count][words_per_parameter] = {}; + // One bit per word that a write stored, like the graphics path's `constant_words_bound`, so a later + // dispatch can tell "set to 0" from "never set". + std::uint8_t bound[parameter_count] = {}; + + void clear() noexcept + { + for (auto& row : words) + for (auto& word : row) word = 0; + for (auto& mask : bound) mask = 0; + } + + // True when every word in [offset, offset + count) of `parameter` was written since the last clear. + bool is_bound(unsigned parameter, unsigned offset, unsigned count) const noexcept + { + if (!count || parameter >= parameter_count || offset >= words_per_parameter || count > words_per_parameter - offset) + return false; + const unsigned mask = ((1u << count) - 1) << offset; + return (bound[parameter] & mask) == mask; + } + + // SetXxxRoot32BitConstants(parameter, count, data, offset). `data` must hold `count` words. + Result set(unsigned parameter, unsigned count, const std::uint32_t* data, unsigned offset) noexcept + { + if (!count || !data || parameter >= parameter_count || offset >= words_per_parameter) return Result::dropped; + const bool cut = count > words_per_parameter - offset; + const unsigned n = cut ? words_per_parameter - offset : count; + for (unsigned i = 0; i < n; ++i) words[parameter][offset + i] = data[i]; + bound[parameter] |= static_cast(((1u << n) - 1) << offset); + return cut ? Result::truncated : Result::stored; + } + + // SetXxxRoot32BitConstant(parameter, value, offset). + Result set_one(unsigned parameter, std::uint32_t value, unsigned offset) noexcept { return set(parameter, 1, &value, offset); } + + // The word a shader reads; 0 outside the kept range. + std::uint32_t word(int parameter, int offset) const noexcept + { + return parameter >= 0 && parameter < static_cast(parameter_count) && offset >= 0 && + offset < static_cast(words_per_parameter) + ? words[parameter][offset] + : 0; + } +}; + +} // namespace x2w_root_constants diff --git a/tests/startup_root_constant_store.cpp b/tests/startup_root_constant_store.cpp new file mode 100644 index 000000000..a07bb3acf --- /dev/null +++ b/tests/startup_root_constant_store.cpp @@ -0,0 +1,62 @@ +// Experimental (docs/startup-runtime.md, #870): the root constants a command list keeps for compute +// (list slots 37 and 39). Plain standard C++; synthetic values, no title data. +#include "../src/startup_stubs/root_constant_store.h" + +#include +#include + +namespace { +using x2w_root_constants::Result; +using x2w_root_constants::Store; +int failures; + +void expect(bool ok, const std::string& what) +{ + if (!ok) { + std::fprintf(stderr, "FAIL: %s\n", what.c_str()); + ++failures; + } +} +} // namespace + +int main() +{ + Store store; + const std::uint32_t data[4] = {11, 22, 33, 44}; + + expect(store.set(3, 4, data, 2) == Result::stored, "four words at offset 2 are stored"); + expect(store.word(3, 2) == 11 && store.word(3, 5) == 44, "stored words read back at their offsets"); + expect(store.word(3, 1) == 0 && store.word(3, 6) == 0, "neighbouring words stay zero"); + + expect(store.set_one(5, 77, 7) == Result::stored, "a single word at the last offset is stored"); + expect(store.word(5, 7) == 77, "the single word reads back"); + + expect(store.set(6, 4, data, 6) == Result::truncated, "a write past the end of the parameter is cut off"); + expect(store.word(6, 6) == 11 && store.word(6, 7) == 22, "the words that fit are kept"); + expect(store.word(7, 0) == 0, "a cut-off write does not spill into the next parameter"); + + expect(store.set(16, 1, data, 0) == Result::dropped, "parameter 16 is refused"); + expect(store.set(0, 1, data, 8) == Result::dropped, "offset 8 is refused"); + expect(store.set(0, 0, data, 0) == Result::dropped, "an empty write is refused"); + expect(store.set(0, 1, nullptr, 0) == Result::dropped, "a null source is refused"); + expect(store.set_one(15, 5, 0) == Result::stored && store.word(15, 0) == 5, "parameter 15 is the last one kept"); + expect(store.word(16, 0) == 0 && store.word(-1, 0) == 0 && store.word(0, 8) == 0, "reads outside the range give 0"); + + expect(store.is_bound(3, 2, 4) && store.is_bound(3, 3, 1), "written words are marked set"); + expect(!store.is_bound(3, 1, 1) && !store.is_bound(3, 1, 2) && !store.is_bound(3, 6, 1), + "words never written are not set, and a range with one unset word is not set"); + expect(store.is_bound(6, 6, 2) && !store.is_bound(6, 6, 3), "a cut-off write marks only the words that fit"); + expect(!store.is_bound(0, 0, 1), "a dropped write marks nothing"); + expect(!store.is_bound(16, 0, 1) && !store.is_bound(0, 8, 1) && !store.is_bound(0, 0, 0) && !store.is_bound(0, 7, 2), + "ranges outside the kept words are never set"); + expect(store.set_one(1, 0, 0) == Result::stored && store.is_bound(1, 0, 1) && store.word(1, 0) == 0, + "writing 0 is set, unlike never written"); + + store.clear(); + expect(store.word(3, 2) == 0 && store.word(15, 0) == 0, "clear zeroes every word"); + expect(!store.is_bound(3, 2, 4) && !store.is_bound(1, 0, 1), "clear forgets which words were set"); + + if (failures) return 1; + std::puts("root constant store ok"); + return 0; +} From c9f0b8e42c624b930256c7f130193a6dfab74963 Mon Sep 17 00:00:00 2001 From: tedin7 <110300616+tedin7@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:21:27 +0100 Subject: [PATCH 028/240] tests: run both PowerShell shells in parallel in startup_run_ps1 (#2487) --- tests/startup_run_ps1_check.py | 71 ++++++++++++++++++++-------------- 1 file changed, 41 insertions(+), 30 deletions(-) diff --git a/tests/startup_run_ps1_check.py b/tests/startup_run_ps1_check.py index 8d9c55a68..0e9d0dc2f 100644 --- a/tests/startup_run_ps1_check.py +++ b/tests/startup_run_ps1_check.py @@ -14,6 +14,7 @@ import subprocess import sys import tempfile +from concurrent.futures import ThreadPoolExecutor from pathlib import Path RUN_PS1 = Path(__file__).resolve().parent.parent / "tools" / "startup" / "run.ps1" @@ -295,6 +296,41 @@ def mutants_of(script): return {name: None if mutant == lines else "\n".join(mutant) + "\n" for name, mutant in mutants.items()} +def shell_failures(shell, script, tmp): + """Every failure for one shell (None: the text-only checks), in a fixed order.""" + failures = [] + name = Path(shell).stem.lower() if shell else "text" + bad = run_problems(shell, script, tmp, False) + failures += [f"{name}: {item}" for item in bad] + if bad: + return failures + for label, mutant in mutants_of(script).items(): + if mutant is None or not run_problems(shell, mutant, tmp, True): + failures.append(f"{name}: mutant '{label}' was not detected") + if shell: + # Expire the live fixture tree after HasExited has been read. The launcher's + # own taskkill then hits the missing PID and writes native stderr. + kill = f"& {STOP} 2>&1 | Out-Null" + expire = kill + '\nif (-not $translator.WaitForExit(5000)) { throw "fixture watcher still alive" }\n' + race = script.replace(kill, expire + kill) + if race == script: + failures.append(f"{name}: could not exercise the watcher exit during cleanup") + else: + failures += [f"{name}: watcher exit during cleanup: {item}" + for item in run_case(shell, race, 7, tmp, translate=True)] + stopless = "\n".join(line for line in script.splitlines() if STOP not in line) + "\n" + parent_only = script.replace(STOP, "Stop-Process -Id $translator.Id -Force") + for mutant, who in ((stopless, "translator"), (parent_only, "translator's child process")): + problems = run_case(shell, mutant, 7, tmp, translate=True) + if f"-Translate: the {who} was still running after run.ps1 exited" not in problems: + failures.append(f"{name}: expected a surviving {who}, got {problems}") + else: + for removed in (' -and -not $translator.HasExited', '$ErrorActionPreference = "Continue"', '/T '): + if not text_problems(script.replace(removed, '')): + failures.append(f"text: removing {removed.strip()} escaped the cleanup check") + return failures + + def main(): if sys.argv[1:] not in ([], ["--text-only"]): sys.exit("usage: startup_run_ps1_check.py [--text-only]") @@ -311,36 +347,11 @@ def main(): mode = "text only: no PowerShell found" failures = [] with tempfile.TemporaryDirectory() as tmp: - for shell in shells or [None]: - name = Path(shell).stem.lower() if shell else "text" - bad = run_problems(shell, script, tmp, False) - failures += [f"{name}: {item}" for item in bad] - if bad: - continue - for label, mutant in mutants_of(script).items(): - if mutant is None or not run_problems(shell, mutant, tmp, True): - failures.append(f"{name}: mutant '{label}' was not detected") - if shell: - # Expire the live fixture tree after HasExited has been read. The launcher's - # own taskkill then hits the missing PID and writes native stderr. - kill = f"& {STOP} 2>&1 | Out-Null" - expire = kill + '\nif (-not $translator.WaitForExit(5000)) { throw "fixture watcher still alive" }\n' - race = script.replace(kill, expire + kill) - if race == script: - failures.append(f"{name}: could not exercise the watcher exit during cleanup") - else: - failures += [f"{name}: watcher exit during cleanup: {item}" - for item in run_case(shell, race, 7, tmp, translate=True)] - stopless = "\n".join(line for line in script.splitlines() if STOP not in line) + "\n" - parent_only = script.replace(STOP, "Stop-Process -Id $translator.Id -Force") - for mutant, who in ((stopless, "translator"), (parent_only, "translator's child process")): - problems = run_case(shell, mutant, 7, tmp, translate=True) - if f"-Translate: the {who} was still running after run.ps1 exited" not in problems: - failures.append(f"{name}: expected a surviving {who}, got {problems}") - else: - for removed in (' -and -not $translator.HasExited', '$ErrorActionPreference = "Continue"', '/T '): - if not text_problems(script.replace(removed, '')): - failures.append(f"text: removing {removed.strip()} escaped the cleanup check") + # Each shell works in its own scratch dirs, so PowerShell 5.1 and 7 run side by side. + with ThreadPoolExecutor(max_workers=len(shells) or 1) as pool: + jobs = [pool.submit(shell_failures, shell, script, tmp) for shell in shells or [None]] + for job in jobs: + failures += job.result() for item in failures: print("FAIL", item) print(f"startup run.ps1 exit code: {len(failures)} failed ({mode})") From 9260908dc94d6baeb70ae52adaeb0c3ad5c14b68 Mon Sep 17 00:00:00 2001 From: RavenCurseBurg Date: Thu, 26 Nov 2026 08:24:11 +0800 Subject: [PATCH 029/240] shader: preserve proven 32-bit graphics table offsets across forward joins (#2507) * fix: carry descriptor pointers through s_add_u32/s_addc_u32 in gfx2hlsl A table or root pointer advanced by a literal offset now keeps its source and byte offset, so a following s_load reads the advanced descriptor. A register addend on a pointer is refused instead of silently keeping the old pointer. Part of #1723 * shader: refuse descriptor pointer advances across branches and detached s_addc_u32 in gfx2hlsl (Part of #1723) * shader: keep the pointer-advance bookkeeping safe for stages without branch state (Part of #1723) * fix: keep the branch-join refusal for pointer adds in branching shaders * fix: require the matching high-word add before folding an advanced descriptor pointer * fix: advance 32-bit table pointers without a high word and judge the high operand by content * shader: keep 32-bit table offsets at agreeing forward graphics joins Track a literal table address across copies and forward paths only when the incoming resource and byte offset agree. Exercise the published manifest against two GPU resources and compare all 32 pixels, including the root constant used by the branches. AI-assisted with Codex (GPT-6.2 Astra, xhigh). * fix: keep descriptor pointer pair open until its matching s_addc_u32 * tests: cover vertex-table carries and backward edges in pointer propagation Exercise the two surviving mutations reported on #2507 using full source-built programs. AI-assisted with Codex (GPT-6.2 Astra, xhigh). * fix: let the descriptor pointer pair pass translate's SCC check, add WARP readback case * fix: refuse an untracked-offset pointer as a descriptor, run the pointer check in Linux CI * fix: refuse a root pointer load whose high word was overwritten * Revert "fix: refuse a root pointer load whose high word was overwritten" This reverts commit 0f226c5cb04d401951ef0dded42ce9f8c4f528f5. --------- Co-authored-by: tedin7 Co-authored-by: RavenCurseBurg <360931527+RavenCurseBurg@users.noreply.github.com> --- .github/workflows/windows.yml | 2 + CMakeLists.txt | 6 + docs/experiments.md | 12 ++ tests/startup_address_srv.cpp | 29 ++- tests/startup_joined_table_pointer_check.py | 211 ++++++++++++++++++++ tests/startup_stream_consumer.cpp | 3 +- tests/startup_stream_draw.cpp | 2 +- tests/startup_stream_setup.cpp | 5 +- tools/startup/gfx2hlsl.py | 30 ++- 9 files changed, 282 insertions(+), 18 deletions(-) create mode 100644 tests/startup_joined_table_pointer_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 5d86ad940..bac4cec34 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -124,6 +124,7 @@ jobs: (["tests/startup_compute_lds_b128_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_calculated_target_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_join_symbols_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_joined_table_pointer_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_swap_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_dpp_quad_swap_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_shift64_check.py", "binary", "llvm-mc-15"], {}), @@ -274,6 +275,7 @@ jobs: tests/startup_gfx2hlsl_readfirstlane_uniform_check.py \ tests/startup_gfx2hlsl_loop_constants_check.py \ tests/startup_gfx2hlsl_join_symbols_check.py \ + tests/startup_joined_table_pointer_check.py \ tests/startup_gfx2hlsl_readfirstlane_recompute_check.py \ tests/startup_compute_readfirstlane_check.py \ tests/startup_gfx2hlsl_calculated_target_check.py \ diff --git a/CMakeLists.txt b/CMakeLists.txt index f69ff19d8..f68ca1600 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3223,6 +3223,8 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_op_refusals_check.py") set_tests_properties(startup_gfx2hlsl_op_refusals PROPERTIES TIMEOUT 60) # gfx2hlsl carries a descriptor pointer through s_add_u32 / s_addc_u32 with a literal offset (#1723). + add_test(NAME startup_joined_table_pointer_cpu COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_joined_table_pointer_check.py") add_test(NAME startup_gfx2hlsl_desc_ptr_prop COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_desc_ptr_prop_check.py") set_tests_properties(startup_gfx2hlsl_desc_ptr_prop PROPERTIES TIMEOUT 60) @@ -4106,6 +4108,10 @@ if(EXISTS "${INTAKE_PYTHON}") set_tests_properties(startup_draw_depth_target_${backend} startup_draw_depth_target_drop_control_${backend} startup_draw_depth_target_debug_${backend} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) foreach(compiler IN ITEMS fxc dxc) + add_test(NAME startup_joined_table_pointer_${compiler}_${backend} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_joined_table_pointer_check.py" + "$" "${backend}" "${compiler}" "${DXC_EXECUTABLE}" "${STARTUP_FXC}") + set_tests_properties(startup_joined_table_pointer_${compiler}_${backend} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) add_test(NAME startup_mrt_${compiler}_${backend} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_mrt_check.py" "$" "${backend}" "${compiler}" "${DXC_EXECUTABLE}" "${STARTUP_FXC}") diff --git a/docs/experiments.md b/docs/experiments.md index ab318679b..a9b76f5e1 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -393,6 +393,18 @@ ctest --preset dev --no-tests=error -R '^startup_vertex_fetch_formats_(controls| `BUF_FMT_16_16_SNORM` (format 24, DXGI `R16G16_SNORM` 37) sign-extends each half, divides by 32767 and clamps to -1.0, so -32768 and -32767 both give -1.0 (the Direct3D and Vulkan SNORM rule, as in LLVM 15 and Mesa `ac_formats`). The device run compares `round(v * 32767)` against the same byte decode, with a wrong reference that reads the halves unsigned and a mutated translation that does the same. The pattern the harness writes to t0 holds no 0x8000, so `startup_vertex_fetch_formats_controls` also evaluates the emitted expressions on 0x8000, 0x8001, 0x7fff, 0x0000, 0xffff and 0x4000 in each half, and four wrong forms (unsigned read, no clamp, divisor 32768, one half for both) must fail that check. The D3D12 draw has not been run on Linux. +In a graphics shader with only forward branches, a 32-bit root-table pointer +can be advanced by a literal byte offset and copied with `s_mov_b32`. At a +join the table and its offset must agree on every incoming path. A later +write to the source register leaves the copy intact. A path that changes the +copy to another address makes the subsequent descriptor load ambiguous. + +The `startup_joined_table_pointer` checks use two R8 textures with distinct +red values. The guest table stores their 32-byte records at offsets 0 and 32. +Each draw reads the table and exports the branch's root constant in green. +Swapping the textures reverses the red values. Changing the compiled +manifest's byte offset changes all 32 pixels and preserves the green values. + `buffer_load_format_x`, `_xy`, `_xyz` and `_xyzw` (MUBUF) use FORMAT (word 3 bits 12 to 18) and DST_SEL (bits 0 to 11) from the buffer descriptor. The draw snapshots the hardware table descriptor and provides word 3 as `udsrc descword3 `. It refuses missing hardware descriptor metadata, unsupported FORMAT codes and unresolved buffer ranges before submitting the draw. The shader decodes using the same expressions as the tbuffer path. Selectors 4 to 7 choose x, y, z and w, while selectors 0 and 1 choose constants 0 and 1. For a load after a branch, the vertex or pixel shader must load all four descriptor words in the same basic block as the use. The root table pointer must reach the load or its local pointer copy without any intervening write along the control-flow predecessors. It refuses rewritten descriptor words. `startup_vertex_fetch_formats_*` covers twelve formats, component swizzles, integer 1 and mutations that must differ on readback, plus three `buffer_load_format_xyzw` device cases (identity, a two-channel format whose z and w are the defaults 0 and 1, and the word (w, 1, 0, x)), each of which must also fail through the xyz translation of the same load. `startup_mubuf_descriptor_*` draws with the real binding path on WARP and hardware. Missing metadata, unsupported FORMAT and unresolved backing leave the target blue, while valid zero and one draw black and red. `BUF_FMT_8_8_8_8_UINT` (gfx10 format 60, DXGI `R8G8B8A8_UINT` 30) reads four unsigned bytes into X, Y, Z and W in increasing address order. With stride 5 and byte offset 3, the 16-vertex fixture visits all four dword alignments. On WARP, all 64 component words matched the byte reference. Swapping channels in the reference or normalizing the green byte in the generated shader each triggered a mismatch. diff --git a/tests/startup_address_srv.cpp b/tests/startup_address_srv.cpp index 1dab72a30..7e2c58f21 100644 --- a/tests/startup_address_srv.cpp +++ b/tests/startup_address_srv.cpp @@ -21,12 +21,12 @@ struct ViewAt { }; static_assert(offsetof(ViewAt, address) == 0x28 && sizeof(ViewAt) == 0x40); -bool bind_view_table(void* guest, void* list, Word& cpu) +bool bind_view_table(void* guest, void* list, Word& cpu, UINT count = 1, Word address = 0, Word bytes = 0) { struct Extended { D3D12_DESCRIPTOR_HEAP_DESC desc; Word address, bytes; - } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, 0, 0}; + } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, count, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, address, bytes}; void* heap = nullptr; if (FAILED(static_cast(invoke(guest, 14, ptr(&heap_desc), ptr(&__uuidof(ID3D12DescriptorHeap)), ptr(&heap))))) return false; cpu = invoke(heap, 9); @@ -58,7 +58,16 @@ int draw_address_srvs(ID3D12Device* desktop, void* guest, void* list) 0, ptr(&__uuidof(ID3D12Resource)), ptr(&placed[i]))))) return 41; } Word cpu = 0; - if (!bind_view_table(guest, list, cpu)) return 42; + const bool joined_table = GetEnvironmentVariableW(L"X2W_TEST_JOINED_TABLE", nullptr, 0) != 0; + const Word stride = joined_table ? invoke(guest, 15, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) : 0; + static std::vector title_table; // The bound heap retains this backing memory. + if (joined_table) { + if (stride < 32) return 42; + title_table.resize(2 * stride); + } + if (!bind_view_table(guest, list, cpu, joined_table ? 2 : 1, joined_table ? ptr(title_table.data()) : 0, + joined_table ? title_table.size() : 0)) return 42; + if (joined_table && cpu != ptr(title_table.data())) return 42; ViewAt v{}; v.view.Format = DXGI_FORMAT_R8_UNORM; v.view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; @@ -69,6 +78,20 @@ int draw_address_srvs(ID3D12Device* desktop, void* guest, void* list) invoke(list, 22, 1, ptr(&strip)); invoke(list, 12, 3, 1); }; + if (joined_table) { + for (UINT swap = 0; swap < 2; ++swap) { + for (UINT i = 0; i < 2; ++i) + invoke(guest, 18, ptr(placed[i ^ swap]), ptr(&v.view), cpu + i * stride); + // The shader uses packed 32-byte records. Publish both views at native + // slot boundaries, then pack the second token in the guest-owned table. + std::memmove(title_table.data() + 32, title_table.data() + stride, 32); + for (UINT key = 0; key < 4; ++key) { + invoke(list, 40, 1, 1, ptr(&key), 0); + draw(static_cast(swap * 4 + key)); + } + } + return 0; + } const auto publish = [&](const D3D12_RESOURCE_DESC& resource_desc, Word address) { v.address = address; invoke(guest, 70, ptr(&resource_desc), ptr(&v), cpu); diff --git a/tests/startup_joined_table_pointer_check.py b/tests/startup_joined_table_pointer_check.py new file mode 100644 index 000000000..0dfdcb74e --- /dev/null +++ b/tests/startup_joined_table_pointer_check.py @@ -0,0 +1,211 @@ +"""Check 32-bit graphics table pointers at forward joins and read both bound textures (#2463). + +Run with no arguments for the host controls, or with binary to reassemble every source. +The draw arguments are . +""" +import os +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from startup_flat_param_check import G, PS_WORDS, VS_WORDS, assemble +from startup_gfx2hlsl_join_symbols_check import root +from startup_stream_draw_check import container, vertex +from startup_mrt_check import compile_shader + + +# LLVM 15 gfx1013 encodings. Each program is also assembled in full by the binary check. +WORDS = { + 'buffer_load_dword v6, off, s[16:19], 0': '000030e000060480', + 'exp mrt0 v4, v5, v6, v7 done vm': '0f1800f804050607', + 'exp param0 v6, v6, v6, v6': '0f0200f806060606', + 'exp pos0 v6, v6, v6, v6 done': 'cf0800f806060606', + 'image_load v[4:7], v[0:1], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_2D': '080f00f000040400', + 's_add_u32 s24, s24, 32': '18a01880', + 's_add_u32 s24, s0, 16': '00901880', + 's_add_u32 s24, s8, 32': '08a01880', + 's_add_u32 s24, s8, 64': '08c01880', + 's_add_u32 s26, s26, 0xfffff': '1aff1a80ffff0f00', + 's_add_u32 s26, s26, 2': '1a821a80', + 's_add_u32 s26, s26, 32': '1aa01a80', + 's_add_u32 s26, s26, s9': '1a091a80', + 's_cbranch_scc1 1': '010085bf', + 's_cbranch_scc1 65531': 'fbff85bf', + 's_cbranch_scc1 65533': 'fdff85bf', + 's_cmp_eq_u32 s9, 0': '098006bf', + 's_cmp_eq_u32 s9, 1': '098106bf', + 's_cmp_lg_u32 s30, 0': '1e8007bf', + 's_endpgm': '000081bf', + 's_load_dwordx4 s[16:19], s[0:1], 0x20': '000408f4200000fa', + 's_load_dwordx4 s[16:19], s[24:25], 0x10': '0c0408f4100000fa', + 's_load_dwordx8 s[16:23], s[24:25], 0x0': '0c040cf4000000fa', + 's_mov_b32 s24, 5': '850398be', + 's_mov_b32 s24, s26': '1a0398be', + 's_mov_b32 s24, s8': '080398be', + 's_mov_b32 s25, 0': '800399be', + 's_mov_b32 s25, s1': '010399be', + 's_mov_b32 s26, 13': '8d039abe', + 's_mov_b32 s26, s8': '08039abe', + 's_mov_b32 s30, 17': '91039ebe', + 's_mov_b32 s30, 2': '82039ebe', + 's_sub_u32 s30, s30, 1': '1e819e80', + 's_waitcnt lgkmcnt(0)': '7fc08cbf', + 's_waitcnt vmcnt(0)': '703f8cbf', + 's_xor_b32 s26, s26, 16': '1a901a89', + 'v_cvt_f32_u32_e32 v5, s9': '090c0a7e', + 'v_mov_b32 v0, 0': '8002007e', + 'v_mov_b32 v1, 0': '8002027e', + 'v_mul_f32_e32 v5, 0x3e000000, v5': 'ff0a0a100000003e', +} + +PREFIX = """s_cmp_eq_u32 s9, 0 +s_cbranch_scc1 1 +s_mov_b32 s24, 5 +""" +ADVANCE = """s_mov_b32 s26, s8 +s_add_u32 s26, s26, 32 +s_mov_b32 s24, s26 +""" +BRANCH = """s_cmp_eq_u32 s9, 1 +s_cbranch_scc1 1 +""" +HIGH = 's_mov_b32 s25, 0\n' +DRAW = """v_mov_b32 v0, 0 +v_mov_b32 v1, 0 +s_load_dwordx8 s[16:23], s[24:25], 0x0 +s_waitcnt lgkmcnt(0) +image_load v[4:7], v[0:1], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_2D +s_waitcnt vmcnt(0) +v_cvt_f32_u32_e32 v5, s9 +v_mul_f32_e32 v5, 0x3e000000, v5 +exp mrt0 v4, v5, v6, v7 done vm +s_endpgm +""" +HELD = PREFIX + ADVANCE + HIGH + BRANCH +# Each accepted program loads one descriptor. The old arm writes s24 before the copy. +# Once s24 holds the pointer, a write to its source s26 cannot change it. +ACCEPT = { + 'base': ('s_mov_b32 s24, s8\n' + HIGH, 0), + 'straight': (ADVANCE + HIGH, 32), + 'joined': (HELD + 's_mov_b32 s30, 17\n', 32), + 'source changed': (HELD + 's_mov_b32 s26, 13\n', 32), + 'equal addresses': (HELD + 's_add_u32 s24, s8, 32\n', 32), +} +REJECT = { + 'different addresses': (HELD + 's_add_u32 s24, s8, 64\n', 'joined at a branch target'), + 'missing on an arm': (BRANCH + 's_add_u32 s24, s8, 32\n' + HIGH, 'joined at a branch target'), + 'unproven address': (HELD.replace('s_add_u32 s26, s26, 32', 's_add_u32 s26, s26, s9') + + 's_mov_b32 s30, 17\n', 'joined at a branch target'), + 'unsupported arithmetic': (ADVANCE.replace('s_mov_b32 s24, s26', 's_xor_b32 s26, s26, 16\ns_mov_b32 s24, s26') + + HIGH + BRANCH + 's_mov_b32 s30, 17\n', 'untracked offset'), + 'loop-carried address': (ADVANCE + HIGH + 's_add_u32 s24, s24, 32\ns_cmp_eq_u32 s9, 0\ns_cbranch_scc1 65533\n', + 'joined at a branch target'), + # Reset the low word inside each of two iterations. The join alone cannot reject the load: + # it is the restriction to forward edges that prevents the advance from being folded. + 'advance inside a backward loop': ( + 's_mov_b32 s30, 2\ns_mov_b32 s24, s8\ns_add_u32 s24, s24, 32\n' + 's_sub_u32 s30, s30, 1\ns_cmp_lg_u32 s30, 0\ns_cbranch_scc1 65531\n' + HIGH, 'untracked offset'), + 'offset overflow': (HELD.replace('s_add_u32 s26, s26, 32', 's_add_u32 s26, s26, 0xfffff\ns_add_u32 s26, s26, 2') + + 's_mov_b32 s30, 17\n', 'accumulated table pointer offset'), +} + +# The direct load reads VB slot 2. The low add in the second program may carry, so copying +# the original high word is insufficient to prove the same address. +VB_DRAW = """s_waitcnt lgkmcnt(0) +buffer_load_dword v6, off, s[16:19], 0 +s_waitcnt vmcnt(0) +exp pos0 v6, v6, v6, v6 done +exp param0 v6, v6, v6, v6 +s_endpgm +""" +VB_DIRECT = 's_load_dwordx4 s[16:19], s[0:1], 0x20\n' + VB_DRAW +VB_COPIED_HIGH = ('s_add_u32 s24, s0, 16\ns_mov_b32 s25, s1\n' + 's_load_dwordx4 s[16:19], s[24:25], 0x10\n' + VB_DRAW) + + +def encode(source): + return bytes.fromhex(''.join(WORDS[line] for line in source.splitlines())) + + +def bindings(vs, ps): + pipe = G.Pipeline(vs, ps, root('t', 1)) + return [line for line in pipe.manifest().splitlines() if line.startswith('srv ')] + + +def require_refusal(name, vs, ps, reason): + try: + bindings(vs, ps) + except G.Unsupported as error: + assert reason in str(error), (name, str(error)) + else: + raise AssertionError(f'{name} was accepted') + + +def check_host(): + for name, (prefix, offset) in ACCEPT.items(): + assert bindings(VS_WORDS, encode(prefix + DRAW)) == [f'srv 0 tex2d table 0 {offset}'], name + for name, (prefix, reason) in REJECT.items(): + require_refusal(name, VS_WORDS, encode(prefix + DRAW), reason) + assert bindings(encode(VB_DIRECT), PS_WORDS) == ['srv 0 buf vb 2'] + require_refusal('copied vertex buffer table high word', encode(VB_COPIED_HIGH), PS_WORDS, + 'its high word is not the matching advanced pair') + print('Graphics table pointer joins: six resource bindings and eight refusals matched') + + +def expected(offset): + # Each group of four columns sees opposite table contents. G records the root constant + # used by the branches. Multiplication by 1/8 avoids ambiguous half-integer UNORM results. + return bytes(channel for _ in range(4) for x in range(8) for channel in + (16 + 128 * ((offset // 32) ^ (x // 4)), (0, 32, 64, 96)[x % 4], 0, 255)) + + +def draw(folder, consumer, backend, kind, compiler, prefix, offset): + cache = folder / 'cache' + cache.mkdir() + vs, ps, signature, pixels = (folder / file for file in ('vs', 'ps', 'root', 'pixels')) + vs.write_bytes(vertex()) + ps.write_bytes(container(0, [word for word, in struct.iter_unpack(' drawn;' in result.stderr, result.stdout + result.stderr + data = pixels.read_bytes() + assert data == expected(wanted), (data.hex(), expected(wanted).hex()) + changes = sum(data[i:i+4] != baseline[i:i+4] for i in range(0, len(data), 4)) + assert changes == (0 if wanted == offset else 32), changes + print(f'{kind} {backend} table byte {wanted}, {changes} pixels changed from the source expectation') + + +if __name__ == '__main__': + if len(sys.argv) == 1: + check_host() + elif len(sys.argv) == 3 and sys.argv[1] == 'binary': + sources = [prefix + DRAW for prefix, _ in (*ACCEPT.values(), *REJECT.values())] + for source in [*sources, VB_DIRECT, VB_COPIED_HIGH]: + assert assemble(sys.argv[2], source) == encode(source) + print('All fourteen graphics table fixtures match gfx1013 assembly') + elif len(sys.argv) == 6: + consumer, backend, kind, dxc, fxc = sys.argv[1:] + for prefix, offset in ACCEPT.values(): + with tempfile.TemporaryDirectory() as temporary: + draw(Path(temporary), consumer, backend, kind, fxc if kind == 'fxc' else dxc, prefix, offset) + else: + raise SystemExit(__doc__) diff --git a/tests/startup_stream_consumer.cpp b/tests/startup_stream_consumer.cpp index e7dcab0a2..98ce44f36 100644 --- a/tests/startup_stream_consumer.cpp +++ b/tests/startup_stream_consumer.cpp @@ -261,7 +261,8 @@ int main(int argc, char** argv) const bool hardware = draw && std::strcmp(argv[4], "hardware") == 0; const bool textured = bc7.blocks != nullptr || GetEnvironmentVariableW(L"X2W_TEST_D16_SRV", nullptr, 0) != 0 || GetEnvironmentVariableW(L"X2W_TEST_FORMATTED_BUFFER", nullptr, 0) != 0 || - GetEnvironmentVariableW(L"X2W_TEST_FORMATTED_VIEW", nullptr, 0) != 0; + GetEnvironmentVariableW(L"X2W_TEST_FORMATTED_VIEW", nullptr, 0) != 0 || + GetEnvironmentVariableW(L"X2W_TEST_JOINED_TABLE", nullptr, 0) != 0; if (const int rc = prepare_stream_pipeline(argv[1], argv[2], argv[3], hardware, textured, adapter, device, pso)) return rc; // slot67 [case]: WARP device and root only, then slot-67 creations. diff --git a/tests/startup_stream_draw.cpp b/tests/startup_stream_draw.cpp index 34a837861..ed6e4717b 100644 --- a/tests/startup_stream_draw.cpp +++ b/tests/startup_stream_draw.cpp @@ -323,7 +323,7 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* } else if (GetEnvironmentVariableW(L"X2W_TEST_1D_SRV", nullptr, 0)) { extern int draw_1d_srvs(void*, void*); if (const int result = draw_1d_srvs(guest, list)) return result; - } else if (GetEnvironmentVariableW(L"X2W_TEST_ADDRESS_SRV", nullptr, 0)) { + } else if (GetEnvironmentVariableW(L"X2W_TEST_JOINED_TABLE", nullptr, 0) || GetEnvironmentVariableW(L"X2W_TEST_ADDRESS_SRV", nullptr, 0)) { extern int draw_address_srvs(ID3D12Device*, void*, void*); if (const int result = draw_address_srvs(desktop.Get(), guest, list)) return result; } else if (GetEnvironmentVariableW(L"X2W_TEST_MEMORY_SRV_DIAG", nullptr, 0)) { diff --git a/tests/startup_stream_setup.cpp b/tests/startup_stream_setup.cpp index 09a1ad6c0..0c3ed381e 100644 --- a/tests/startup_stream_setup.cpp +++ b/tests/startup_stream_setup.cpp @@ -141,7 +141,8 @@ int prepare_stream_pipeline(const char* vs_path, const char* ps_path, const char if (FAILED(D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), &device))) return 5; D3D12_ROOT_SIGNATURE_DESC root_desc{}; - const D3D12_DESCRIPTOR_RANGE srv{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; + const bool joined_table = GetEnvironmentVariableW(L"X2W_TEST_JOINED_TABLE", nullptr, 0) != 0; + const D3D12_DESCRIPTOR_RANGE srv{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, joined_table ? 2u : 1u, 0, 0, 0}; D3D12_ROOT_PARAMETER textured_parameters[2]{}; if (textured) { D3D12_ROOT_PARAMETER& table = textured_parameters[0]; @@ -150,7 +151,7 @@ int prepare_stream_pipeline(const char* vs_path, const char* ps_path, const char table.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; root_desc.NumParameters = 1; root_desc.pParameters = textured_parameters; - if (GetEnvironmentVariableW(L"X2W_TEST_ROOT_RESET", nullptr, 0)) { + if (joined_table || GetEnvironmentVariableW(L"X2W_TEST_ROOT_RESET", nullptr, 0)) { D3D12_ROOT_PARAMETER& constant = textured_parameters[1]; constant.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; constant.Constants = {0, 0, 1}; diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 7ecf5fa63..1215fc2a4 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -799,11 +799,12 @@ def names_one_value(sym): if sym is None: return False if sym[0] == 'desc': - # ('desc', source, load offset, dword) and, in a compute stage, the offset of the s_load that read it: the - # source does not record an addend on the pointer, so only the same load proves the same words. + # A compute descriptor can also carry an integer tag identifying the load or constant high word. return len(sym) == 4 or (len(sym) == 5 and isinstance(sym[4], int)) - # An add on a pointer keeps its symbol and marks it 'added' (the offset is not in the tuple), so only an - # untouched pointer, exactly (kind, source), names one value. + # A table and a known byte offset identify one descriptor address. The legacy 'added' + # marker carries no offset, so two occurrences of it can denote different addresses. + if sym[0] == 'ptr' and len(sym) == 3 and sym[1][0] == 'table': + return isinstance(sym[2], int) return sym[0] in ('const', 'ud', 'execcopy') or (sym[0] in ('ptr', 'ptrhi') and len(sym) == 2) @@ -2479,6 +2480,10 @@ def translate(self): target = int(parse(asm)[1][0].split('_')[1], 16) targets.add(target) branches.append((off, target)) + # Forward edges reach each block in disassembly order. A back edge could + # repeat a pointer advance before the next table load. + self.forward_table_adds = (getattr(self, 'kind', None) in ('vs', 'ps') and bool(branches) + and all(target > pc for pc, target in branches)) # Targets that only forward s_cbranch_execz branches (and the fall-through) enter: on a taken edge the lane's # exec bit is 0 at the target. Compute stages have their own execz handling and are left out. names = {off: name for off, _n, name, _asm in self.ins} @@ -3424,8 +3429,9 @@ def pointer_add(self, base, dname, srcs, syms): if base not in ('s_add_u32', 's_addc_u32') or len(srcs) != 2 or not syms[0]: return False if getattr(self, 'has_branches', False): - # The symbolic update runs once in disassembly order; a branch could skip it or repeat it at run time. - return False + if (not getattr(self, 'forward_table_adds', False) or base != 's_add_u32' + or syms[0][0] != 'ptr' or syms[0][1][0] != 'table'): + return False reg = reg_range(dname) if not reg or reg[0] != 's' or reg[1] != reg[2] or reg[1] > 105: return False @@ -3437,6 +3443,10 @@ def pointer_add(self, base, dname, srcs, syms): if added > 0xfffff: raise Unsupported('descriptor pointer offset %s' % srcs[1]) before = syms[0][2] if len(syms[0]) > 2 else 0 + if not isinstance(before, int): + raise Unsupported('add through a pointer with unknown byte offset') + if getattr(self, 'forward_table_adds', False) and before + added > 0xfffff: + raise Unsupported('accumulated table pointer offset %#x' % (before + added)) self.sym[d] = ('ptr', syms[0][1], before + added) if syms[0][1][0] in PTR64_SOURCES and d + 1 <= 105: # The carry-in of an s_addc_u32 is only the carry of this very add: remember where the next @@ -3595,7 +3605,7 @@ def src_sym(t): self.sym[d] = own[:4] + ('modified',) getattr(self.pipe, 'other_modified', set()).add(desc_key(own)) else: - self.sym[d] = own if len(own) > 2 else own + ('added',) # the added offset is not tracked + self.sym[d] = own[:2] + ('added',) # this operation has no proven byte offset else: self.sym[d] = ('descnum',) return None @@ -4012,10 +4022,8 @@ def op_s_load_dwordx4(self, ops, mods, count=4): for i in range(count): self.set_s(dst[1] + i, '%s.Load(%d)' % (buf, base_off + off + 4 * i)) return - # The pointer symbol does not record an addend or a rewritten high word, so two loads through such a - # pointer may read different words under the same (source, offset). In a compute or vertex stage (the - # stages that accept a raw descriptor conversion before a store) those loads are told apart by the - # offset of the s_load; loads through the untouched pair keep one identity. + # A compute or vertex raw-store conversion must distinguish loads through different high words + # even when the source and byte offset match. Keep the load PC for a changed pointer pair. # A 32-bit table pointer carries a high word the program sets to a constant: loads through the same # untouched low word and the same constant read the same words (tag -1 - constant). hi = self.sym.get(base[1] + 1) From a35cba9dd6df37f66858726f8273cc8df5b67a29 Mon Sep 17 00:00:00 2001 From: tedin7 <110300616+tedin7@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:24:53 +0100 Subject: [PATCH 030/240] tests: split four long CPU checks into parallel ctest cases (#2489) * tests: split four long CPU checks into parallel ctest cases * docs: say in the file headers that CTest runs the parts and check runs them all * fix: let the no-path x87 aggregate modes parse without file arguments --- CMakeLists.txt | 57 ++++++++++++++++++++++---- tests/cpu/sse_fp_pd_check.py | 25 ++++++++---- tests/cpu/x87_fprem.py | 38 ++++++++++++++++-- tests/cpu/x87_scale.py | 77 +++++++++++++++++++++++------------- tests/cpu/xchg.py | 52 ++++++++++++++++-------- 5 files changed, 189 insertions(+), 60 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index f68ca1600..ca7dd0388 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4411,6 +4411,20 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/cpu/${script}.py" "$" ${pairs} DEPENDS ${image} tests/cpu/${script}.py tools/emit_variants.py ${ARGN} VERBATIM) endfunction() + # A long check is split into parallel CTest cases _. The original keeps its name (the + # form-coverage source header and the docs name it), runs the cheap remainder, and requires every part + # through a CTest fixture, so it is "not run" (not covered) unless every part passed. + function(x2w_add_check_part test part) + add_test(NAME ${test}_${part} COMMAND ${ARGN}) + set_tests_properties(${test}_${part} PROPERTIES FIXTURES_SETUP ${test}_${part}) + endfunction() + function(x2w_require_check_parts test) + set(required) + foreach(part IN LISTS ARGN) + list(APPEND required ${test}_${part}) + endforeach() + set_tests_properties(${test} PROPERTIES FIXTURES_REQUIRED "${required}") + endfunction() function(cpu_translation image translator entry) cmake_parse_arguments(BIND "FFX_DESTROY;IMAGE_DATA;HOST_CPU" "PROVIDER;SYMBOL;LINK_NAME;CALLBACK_OFFSET;IMPORT_ARGUMENTS;RETURN_BYTES;NAME;RANGES;SECOND_PROVIDER;SECOND_SYMBOL;SECOND_LINK_NAME;SECOND_IMPORT_ARGUMENTS;SECOND_RETURN_BYTES" "STACK_OUTPUT" ${ARGN}) @@ -5775,12 +5789,23 @@ if(EXISTS "${INTAKE_PYTHON}") cpu_translation(cpu_sse_fp_pd_${variant} cpu_sse_fp_aot "${cpu_sse_fp_pd_exports}") endforeach() target_compile_definitions(cpu_sse_fp_pd_altered PRIVATE ALTER_IMM) + # The five checks of sse_fp_pd_check.py run as separate cases; cpu_aot_sse_fp_pd runs the rejections + # and requires the other four. + foreach(part IN ITEMS differential modes cmp_differential cmp_modes) + x2w_add_check_part(cpu_aot_sse_fp_pd ${part} "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/cpu/sse_fp_pd_check.py" + "$" + "$" + "$" + "$" ${part}) + endforeach() add_test(NAME cpu_aot_sse_fp_pd COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/sse_fp_pd_check.py" "$" "$" "$" - "$") + "$" rejections) + x2w_require_check_parts(cpu_aot_sse_fp_pd differential modes cmp_differential cmp_modes) # cpu_sse_fp_pd_logic_checks set(cpu_sse_fp_pd_logic_exports "op_andpd,op_andpd_mem,op_andpd_mem_disp,op_andpd_self," @@ -6460,9 +6485,15 @@ if(EXISTS "${INTAKE_PYTHON}") tools/cpu_ranges.py tools/cpu_leaf_aot.py VERBATIM) add_library(cpu_xchg_${variant} SHARED "${xchg_fixture}") endforeach() + x2w_add_check_part(cpu_aot_xchg native "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/xchg.py" + check-native "$") + x2w_add_check_part(cpu_aot_xchg lifted "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/xchg.py" + check-lifted "$") + x2w_add_check_part(cpu_aot_xchg controls "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/xchg.py" + check-controls "$" "$") add_test(NAME cpu_aot_xchg COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/xchg.py" - check "$" "$" - "$" "$") + check-rejections) + x2w_require_check_parts(cpu_aot_xchg native lifted controls) cpu_asm_fixture(cpu_address_size address_size) set(address_fixture "${CMAKE_CURRENT_BINARY_DIR}/cpu_address_size_lifted.cpp") add_custom_command(OUTPUT "${address_fixture}" @@ -7640,9 +7671,15 @@ if(EXISTS "${INTAKE_PYTHON}") list(APPEND x87_scale_control_files "$") endif() endforeach() + x2w_add_check_part(cpu_aot_x87_scale native "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/x87_scale.py" + check-native "$" "$") + x2w_add_check_part(cpu_aot_x87_scale lifted "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/x87_scale.py" + check-lifted "$" "$") + x2w_add_check_part(cpu_aot_x87_scale controls "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/x87_scale.py" + check-controls "$" "$" ${x87_scale_control_files}) add_test(NAME cpu_aot_x87_scale COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/x87_scale.py" - check "$" "$" - "$" ${x87_scale_control_files}) + check-rejections) + x2w_require_check_parts(cpu_aot_x87_scale native lifted controls) cpu_asm_fixture(cpu_x87_fcmov x87_fcmov) # The lifted DLL and eight mutated controls that the check requires to mismatch. set(x87_fcmov_control_files "") @@ -7727,9 +7764,15 @@ if(EXISTS "${INTAKE_PYTHON}") list(APPEND x87_fprem_control_files "$") endif() endforeach() + x2w_add_check_part(cpu_aot_x87_fprem lifted "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/x87_fprem.py" + check-lifted "$" "$") + x2w_add_check_part(cpu_aot_x87_fprem native "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/x87_fprem.py" + check-native "$" "$") + x2w_add_check_part(cpu_aot_x87_fprem controls "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/x87_fprem.py" + check-controls "$" "$" ${x87_fprem_control_files}) add_test(NAME cpu_aot_x87_fprem COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/x87_fprem.py" - check "$" "$" - "$" ${x87_fprem_control_files}) + check-light) + x2w_require_check_parts(cpu_aot_x87_fprem lifted native controls) cpu_asm_fixture(cpu_x87_fldcw x87_fldcw) # The checked translation and seventeen mutated controls that the check requires to mismatch. set(x87_fldcw_control_files "") diff --git a/tests/cpu/sse_fp_pd_check.py b/tests/cpu/sse_fp_pd_check.py index 698468125..3cc7310b6 100644 --- a/tests/cpu/sse_fp_pd_check.py +++ b/tests/cpu/sse_fp_pd_check.py @@ -4,7 +4,10 @@ through the translator in the default control word and under all sixteen combinations of MXCSR rounding mode, DAZ and FTZ, each against the exact reference in sse_fp_pd_ref.py. CMPPD (predicates 0..7, xmm and aligned m128 sources) gets the same treatment against the predicate rules of that reference. The packed -single checks in sse_fp_check.py provide the buffer, driver and encoding helpers.""" +single checks in sse_fp_check.py provide the buffer, driver and encoding helpers. + +CTest runs the parts (differential, modes, cmp_differential, cmp_modes, rejections) as separate cases in +parallel. Passing no part name after the four paths still runs all of them serially, for a direct run.""" from pathlib import Path import random @@ -481,9 +484,17 @@ def cmppd(dst, src, imm): if __name__ == "__main__": - native_dll, lifted_dll, altered_dll, harness_dll = sys.argv[1:5] - check_differential(native_dll, lifted_dll, altered_dll) - check_modes(native_dll, lifted_dll, harness_dll) - check_cmp_differential(native_dll, lifted_dll, altered_dll) - check_cmp_modes(native_dll, lifted_dll, harness_dll) - check_rejections(native_dll) + native_dll, lifted_dll, altered_dll, harness_dll, *selected = sys.argv[1:] + # CTest runs the parts as separate cases; no part runs them all in the original order. + parts = { + "differential": lambda: check_differential(native_dll, lifted_dll, altered_dll), + "modes": lambda: check_modes(native_dll, lifted_dll, harness_dll), + "cmp_differential": lambda: check_cmp_differential(native_dll, lifted_dll, altered_dll), + "cmp_modes": lambda: check_cmp_modes(native_dll, lifted_dll, harness_dll), + "rejections": lambda: check_rejections(native_dll), + } + unknown = [name for name in selected if name not in parts] + if unknown: + raise ValueError(f"unknown part {unknown}; choose from {sorted(parts)}") + for name in selected or parts: + parts[name]() diff --git a/tests/cpu/x87_fprem.py b/tests/cpu/x87_fprem.py index 98ae594df..0d2a120ad 100644 --- a/tests/cpu/x87_fprem.py +++ b/tests/cpu/x87_fprem.py @@ -5,6 +5,8 @@ python tests/cpu/x87_fprem.py emit [control] translate (and optionally mutate) the fixture python tests/cpu/x87_fprem.py check [controls...] +CTest runs the check-* parts as separate cases in parallel; `check` runs every part serially for a direct run. + Each export loads ST(1) from offset 16 and ST(0) from offset 0 of its input block, takes the partial remainder, and stores the result, the divisor and records of the status word in its output block. The translation is lower(..., x87=Checked(REJECT)) inside a checked entry, uint32_t name(word input, @@ -455,8 +457,23 @@ def is_nan(raw): def check(harness_path, native_path, lifted_path, *control_paths): + check_light() + expected = build_expected() + check_lifted(harness_path, lifted_path, expected) + check_native(harness_path, native_path, expected) + check_controls(harness_path, expected, control_paths) + + +def check_light(): print(f"the model agreed with {check_model()} remainders worked by hand") - expected = [(name, data, run(name, data)) for name, data in cases()] + check_rejections() + + +def build_expected(): + return [(name, data, run(name, data)) for name, data in cases()] + + +def check_lifted(harness_path, lifted_path, expected): lifted = CheckedRunner(harness_path, lifted_path) statuses = dict.fromkeys(STATUS.values(), 0) bad = 0 @@ -473,6 +490,9 @@ def check(harness_path, native_path, lifted_path, *control_paths): print(f"{len(expected)} cases over {len(SEQUENCES)} exports matched the model in the checked translation (status, " "output block and guards, and *result, which only status 0 writes)") print("translated statuses: " + ", ".join(f"{name} {statuses[code]}" for name, code in STATUS.items())) + + +def check_native(harness_path, native_path, expected): native = base.Runner(harness_path, native_path) compared = partial_records = nan_results = looped = skipped = 0 for name, data, model in expected: @@ -509,6 +529,9 @@ def check(harness_path, native_path, lifted_path, *control_paths): f"was a NaN in the {nan_results} single-step cases with a NaN model result, and the loops reduced partially " f"and iterated in {looped} cases; {skipped} loop cases with a NaN result ran only translated") print(f"processor: {platform.processor()}") + + +def check_controls(harness_path, expected, control_paths): for path in control_paths: control = Path(path).stem.rsplit("_", 1)[-1] run_control = CheckedRunner(harness_path, path) @@ -516,7 +539,6 @@ def check(harness_path, native_path, lifted_path, *control_paths): print(f"control {control}: {bad}/{len(expected)} mismatches") if not bad: raise AssertionError(f"control {control} matched every case") - check_rejections() def check_rejections(): @@ -567,12 +589,22 @@ def pair(middle, end=clear): # two values loaded, middle, both popped if __name__ == "__main__": - mode, first, second, *rest = sys.argv[1:] + mode, *args = sys.argv[1:] # check-light takes no paths + first, second = (args + [None, None])[:2] + rest = args[2:] if mode == "asm": write_asm(first, second) elif mode == "emit": emit(Path(first), Path(second), *rest) elif mode == "check": check(first, second, *rest) + elif mode == "check-light": # the hand-worked model and the rejections; no fixture needed + check_light() + elif mode == "check-lifted": + check_lifted(first, second, build_expected()) + elif mode == "check-native": + check_native(first, second, build_expected()) + elif mode == "check-controls": # args: harness, unused, then the control DLLs + check_controls(first, build_expected(), rest) else: raise ValueError(mode) diff --git a/tests/cpu/x87_scale.py b/tests/cpu/x87_scale.py index 5120b5f7f..57d186485 100644 --- a/tests/cpu/x87_scale.py +++ b/tests/cpu/x87_scale.py @@ -5,6 +5,8 @@ python tests/cpu/x87_scale.py emit [control] translate (and optionally mutate) the fixture python tests/cpu/x87_scale.py check [controls...] +CTest runs the check-* parts as separate cases in parallel; `check` runs every part serially for a direct run. + The exports, harness and guards follow tests/cpu/x87_add.py, and the other steps use the format of tests/cpu/x87_moves.py. emit checks that every decoded x87 instruction is the form its sequence names. The model scales with Fraction arithmetic and is independent of tools/x87_soft.h. @@ -257,36 +259,40 @@ def cases(): # ---- Check ----------------------------------------------------------------------------------------- -def check(harness_path, native_path, lifted_path, *control_paths): - expected = [(name, data, reference(name, data)) for name, data in cases()] - for label, path in (("native", native_path), ("lifted", lifted_path)): - run = base.Runner(harness_path, path) - bad = 0 - for name, data, want in expected: - got, state = run(name, data) - if not base.entry_state_ok(state): - raise AssertionError(f"{label} {name} left state {state:#014x}; the profile requires control " - "0x027f and an empty stack at TOP 0") - if got != want: - if bad < 3: - print(f"{label} mismatch: {name}(input {data[:48].hex()})\n got {got[:48].hex()}\n" - f" expected {want[:48].hex()}") - bad += 1 - if bad: - raise AssertionError(f"{label}: {bad}/{len(expected)} mismatches") - print(f"{len(expected)} cases over {len(SEQUENCES)} exports (output block and guards) matched the reference " - "in native and translated DLLs; each export returned with control 0x027f and an empty stack") +def build_expected(): + return [(name, data, reference(name, data)) for name, data in cases()] + + +def check_target(label, harness_path, path, expected): + """Every case, then the x87_call caller-state check, against one DLL (native or translated).""" + run = base.Runner(harness_path, path) + bad = 0 + for name, data, want in expected: + got, state = run(name, data) + if not base.entry_state_ok(state): + raise AssertionError(f"{label} {name} left state {state:#014x}; the profile requires control " + "0x027f and an empty stack at TOP 0") + if got != want: + if bad < 3: + print(f"{label} mismatch: {name}(input {data[:48].hex()})\n got {got[:48].hex()}\n" + f" expected {want[:48].hex()}") + bad += 1 + if bad: + raise AssertionError(f"{label}: {bad}/{len(expected)} mismatches") + print(f"{label}: {len(expected)} cases over {len(SEQUENCES)} exports (output block and guards) matched the " + "reference; each export returned with control 0x027f and an empty stack") print(f"processor: {platform.processor()}") first = {} for name, data, want in expected: first.setdefault(name, (data, want)) - for label, path in (("native", native_path), ("lifted", lifted_path)): - run = base.Runner(harness_path, path) - failed = [name for name, (data, want) in first.items() if not base.preserved(run, "x87_call", name, data, want)] - if failed: - raise AssertionError(f"x87_call lost a live caller value or control word around {label} {failed}") - print(f"x87_call kept a live caller ST(0) value and control word around all {len(first)} native and " - "translated exports") + run = base.Runner(harness_path, path) + failed = [name for name, (data, want) in first.items() if not base.preserved(run, "x87_call", name, data, want)] + if failed: + raise AssertionError(f"x87_call lost a live caller value or control word around {label} {failed}") + print(f"x87_call kept a live caller ST(0) value and control word around all {len(first)} {label} exports") + + +def check_controls(harness_path, expected, control_paths): for path in control_paths: control = Path(path).stem.rsplit("_", 1)[-1] run = base.Runner(harness_path, path) @@ -294,6 +300,13 @@ def check(harness_path, native_path, lifted_path, *control_paths): print(f"control {control}: {bad}/{len(expected)} mismatches") if not bad: raise AssertionError(f"control {control} matched every case") + + +def check(harness_path, native_path, lifted_path, *control_paths): + expected = build_expected() + check_target("native", harness_path, native_path, expected) + check_target("lifted", harness_path, lifted_path, expected) + check_controls(harness_path, expected, control_paths) check_rejections() @@ -324,12 +337,22 @@ def attempt(hex_bytes): if __name__ == "__main__": - mode, first, second, *rest = sys.argv[1:] + mode, *args = sys.argv[1:] # check-rejections takes no paths + first, second = (args + [None, None])[:2] + rest = args[2:] if mode == "asm": write_asm(first, second) elif mode == "emit": emit(Path(first), Path(second), *rest) elif mode == "check": check(first, second, *rest) + elif mode == "check-rejections": # no fixture needed + check_rejections() + elif mode == "check-native": # args: harness, native DLL + check_target("native", first, second, build_expected()) + elif mode == "check-lifted": # args: harness, lifted DLL + check_target("lifted", first, second, build_expected()) + elif mode == "check-controls": # args: harness, unused, then the control DLLs + check_controls(first, build_expected(), rest) else: raise ValueError(mode) diff --git a/tests/cpu/xchg.py b/tests/cpu/xchg.py index 87739375d..ba09c13aa 100644 --- a/tests/cpu/xchg.py +++ b/tests/cpu/xchg.py @@ -1,4 +1,8 @@ -"""Compare native and translated XCHG, and check that the memory form stays atomic under contention.""" +"""Compare native and translated XCHG, and check that the memory form stays atomic under contention. + +CTest runs the parts as separate cases (check-native, check-lifted, check-controls, in parallel) and keeps +check-rejections on the aggregate. The `check` mode still runs every part serially for a direct run; the +parts above are not the only coverage of that mode, they are the same checks split up.""" from collections import Counter import ctypes import os @@ -167,18 +171,20 @@ def token_errors(lib, rounds): return threads, worst -def check(native_path, lifted_path, *control_paths): - for label, path in (("native", native_path), ("lifted", lifted_path)): - lib = load_lib(path) - cases, bad = value_mismatches(lib) - if bad: - name, x, y, want, got = bad[0] - raise AssertionError(f"{label}: {len(bad)} mismatches; first {name}({x:#x}, {y:#x}) = {got}, expected {want}") - threads, errors = token_errors(lib, rounds=3) - if any(errors.values()): - raise AssertionError(f"{label}: token exchange lost or duplicated values: {errors}") - print(f"{label}: {cases} value cases matched; {threads} threads x 100000 tokens x 3 rounds, " - f"lost or duplicated tokens {errors}") +def check_library(label, path): + lib = load_lib(path) + cases, bad = value_mismatches(lib) + if bad: + name, x, y, want, got = bad[0] + raise AssertionError(f"{label}: {len(bad)} mismatches; first {name}({x:#x}, {y:#x}) = {got}, expected {want}") + threads, errors = token_errors(lib, rounds=3) + if any(errors.values()): + raise AssertionError(f"{label}: token exchange lost or duplicated values: {errors}") + print(f"{label}: {cases} value cases matched; {threads} threads x 100000 tokens x 3 rounds, " + f"lost or duplicated tokens {errors}") + + +def check_controls(control_paths): for path in control_paths: control = Path(path).stem.rsplit("_", 1)[-1] lib = load_lib(path) @@ -189,6 +195,12 @@ def check(native_path, lifted_path, *control_paths): raise AssertionError(f"control {control} matched every case") +def check(native_path, lifted_path, *control_paths): + check_library("native", native_path) + check_library("lifted", lifted_path) + check_controls(control_paths) + + def check_rejections(): # An explicit LOCK on XCHG is redundant but still goes through the prefix rejection. try: @@ -208,11 +220,19 @@ def check_rejections(): if __name__ == "__main__": - mode, native, other, *rest = sys.argv[1:] + mode, *args = sys.argv[1:] if mode == "emit": - emit(Path(native), Path(other), *rest) + emit(Path(args[0]), Path(args[1]), *args[2:]) elif mode == "check": - check(native, other, *rest) + check(*args) + check_rejections() + elif mode == "check-native": + check_library("native", *args) + elif mode == "check-lifted": + check_library("lifted", *args) + elif mode == "check-controls": + check_controls(args) + elif mode == "check-rejections": # no fixture needed check_rejections() else: raise ValueError(mode) From 886b8fe228b2f5963b396c77b9fb25f8076e325e Mon Sep 17 00:00:00 2001 From: SimSalabimse <83839581+SimSalabimse@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:25:43 +0100 Subject: [PATCH 031/240] shader: lower s_abs_i32 in gfx2hlsl (Part of #1723) (#2640) * shader: lower s_abs_i32 in gfx2hlsl (#1723) Port the pixel_aot signed absolute SOP1 so ordinary pipelines that only need |S0| stop refusing. SCC is the nonzero test of the result; INT_MIN stays. Lane masks and descriptor words are refused. CPU fixture with a negative control. Co-authored-by: SimSalabimse * test: pin sopk descriptor-refusal mutation to sopk-only raise s_bitset0/1_b32 reused the plain-scalar sym allow-list line, so the sopk_accum mutant needle was no longer unique. Match the sopk raise that formats with `base` instead. Co-authored-by: SimSalabimse * test: add D3D12 WARP dispatch readback for s_abs_i32 Mirror the #2639 / pack_absdiff UAV dump pattern. Cover INT_MIN, -1, 0, a positive word, SCC, and an SCC-dependent branch on the adapter. Co-authored-by: SimSalabimse * build: register s_abs_i32 WARP/hardware dispatch ctests Wire startup_gfx2hlsl_s_abs_dispatch_{warp,hardware} to the new UAV-readback mode so Windows CI and Sander can run the fixture. Co-authored-by: SimSalabimse --------- Co-authored-by: Cursor Agent Co-authored-by: SimSalabimse Co-authored-by: Royoo <3230853833@qq.com> --- .github/workflows/windows.yml | 1 + AGENTS.md | 1 + CMakeLists.txt | 10 + docs/experiments.md | 11 ++ tests/startup_gfx2hlsl_s_abs_check.py | 254 ++++++++++++++++++++++++++ tools/startup/gfx2hlsl.py | 36 ++++ 6 files changed, 313 insertions(+) create mode 100644 tests/startup_gfx2hlsl_s_abs_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index bac4cec34..fc2fb553b 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -295,6 +295,7 @@ jobs: tests/startup_compute_lds_b128_check.py \ tests/startup_compute_translate_check.py \ tests/startup_gfx2hlsl_swap_check.py \ + tests/startup_gfx2hlsl_s_abs_check.py \ tests/startup_gfx2hlsl_s_bitset_check.py \ tests/startup_gfx2hlsl_fma_mix_check.py \ tests/startup_gfx2hlsl_shift64_check.py \ diff --git a/AGENTS.md b/AGENTS.md index 84cb9183a..b7eb67ad7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -173,6 +173,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_compute_store_format_xyzw_check.py ./out/pe-env/bin/python -B tests/startup_compute_translate_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_swap_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_s_abs_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_s_bitset_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_fma_mix_check.py ./out/pe-env/bin/python -B tests/startup_image_2d_array_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index ca7dd0388..d07c81da1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3243,6 +3243,16 @@ if(EXISTS "${INTAKE_PYTHON}") # gfx2hlsl lowers s_bitcmp1_b32 and s_bitcmp0_b32 (SOPC): CPU evaluation of the translated SCC test. add_test(NAME startup_gfx2hlsl_s_bitcmp COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_bitcmp_check.py") + # gfx2hlsl lowers s_abs_i32 (SOP1, #1723): CPU evaluation, then a D3D12 UAV readback on + # WARP/hardware (same dispatch pattern as startup_gfx2hlsl_s_ff1 / pack_absdiff). + add_test(NAME startup_gfx2hlsl_s_abs COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_abs_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_s_abs_dispatch_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_abs_check.py" dispatch "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_gfx2hlsl_s_abs_dispatch_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl lowers s_bitset0_b32 and s_bitset1_b32 (SOP1, #2023 Item J): CPU evaluation and refusals. add_test(NAME startup_gfx2hlsl_s_bitset COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_bitset_check.py") diff --git a/docs/experiments.md b/docs/experiments.md index a9b76f5e1..11011d9cc 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -8009,6 +8009,17 @@ one. Only the low five bits of the index are used. EXEC, VCC and SGPRs tracked as lane masks are refused because their per-lane projections lose the other bits. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_s_bitcmp$' -V`. +**Scalar absolute value.** Startup translation lowers `s_abs_i32` to +`(asint(S0) < 0 ? (0u - S0) : S0)` with `SCC = (D != 0)`, matching `pixel_aot` +(INT_MIN stays). Lane masks and descriptor-bearing sources are refused. Run +`ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_s_abs$' -V` +(or `python3 -B tests/startup_gfx2hlsl_s_abs_check.py`). The `_dispatch_warp` +/ `_dispatch_hardware` variants compile the translated expression into a +compute shader and compare UAV readback for INT_MIN, -1, 0 and a positive +word (plus an SCC-dependent branch token) against the same reference: +`ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_s_abs_dispatch_warp$' -V`. +[Refs #1723](https://github.com/R0Y00/Xbox2Windows/issues/1723). + **Scalar bit set and clear.** Startup translation lowers `s_bitset0_b32` and `s_bitset1_b32` in place: bit `S0[4:0]` of the destination is cleared or set, and SCC is unchanged (same form as `pixel_aot` / #1579; Refs #2023 Item J). diff --git a/tests/startup_gfx2hlsl_s_abs_check.py b/tests/startup_gfx2hlsl_s_abs_check.py new file mode 100644 index 000000000..306731689 --- /dev/null +++ b/tests/startup_gfx2hlsl_s_abs_check.py @@ -0,0 +1,254 @@ +"""s_abs_i32 in tools/startup/gfx2hlsl.py (#1723). + +usage: startup_gfx2hlsl_s_abs_check.py + startup_gfx2hlsl_s_abs_check.py dispatch + +RDNA 2 ISA SOP1: S_ABS_I32 sets D to the absolute value of S0 as a signed 32-bit word +(INT_MIN stays 0x80000000) and SCC = (D != 0). Matches pixel_aot. Lane masks and +descriptor sources are refused. The reference is plain Python; the translated text is +evaluated on the CPU. + +With `dispatch`, the lowering runs as a compute shader on the adapter (D3D12 UAV +readback via offscreen_check, same pattern as startup_gfx2hlsl_s_ff1_check / +startup_gfx2hlsl_pack_absdiff_check). Each case stores D, SCC, and an SCC-dependent +branch token so `asint` / `0u - x` and the nonzero SCC test are exercised on device. +""" +import re +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import disasm_rdna2 as D # noqa: E402 +import gfx2hlsl as G # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import Expr # noqa: E402 + +MASK = 0xffffffff +SOP1 = {name: op for op, (name, _) in D.SOP1_OPS.items()} +WORDS = (0x00000000, 0x00000001, 0xffffffff, 0x80000000, 0x7fffffff, 0xfffffff1, 0x12345678) +# GPU cases from review: INT_MIN, -1, 0, a positive value (SCC follows D != 0). +DRAW = (0x80000000, 0xffffffff, 0x00000000, 0x12345678) +SCC_BRANCH_TAKEN = 0x00a11ced +SCC_BRANCH_NOT = 0x00dead00 +VCC_LO, EXEC_LO = 106, 126 + +failures = [] + + +def check(label, ok, detail=''): + print('%s: %s' % (label, 'ok' if ok else 'MISMATCH'), flush=True) + if not ok: + failures.append(label) + if detail: + print(' ' + detail) + + +def sop1(name, sdst, ssrc): + return struct.pack(' 105: + raise Unsupported('s_abs_i32 destination %s' % ops[0]) + if self.is_lane_mask(ops[0]) or dst[1] in self.masks: + raise Unsupported('s_abs_i32 on a lane mask') + imm = re.fullmatch(r'-?(0x[0-9a-fA-F]+|\d+)', ops[1]) + src_sym = None + if imm: + value = int(ops[1], 0) & 0xffffffff + else: + src = reg_range(ops[1]) + if not src or src[0] != 's' or src[1] != src[2] or src[1] > 105: + raise Unsupported('s_abs_i32 source %s' % ops[1]) + if self.is_lane_mask(ops[1]) or src[1] in self.masks: + raise Unsupported('s_abs_i32 on a lane mask') + src_sym = self.sym.get(src[1]) + if src_sym and src_sym[0] not in ('const', 'ud', 'fixed_buffer_word'): + raise Unsupported('s_abs_i32 on %s data' % src_sym[0]) + value = src_sym[1] & 0xffffffff if src_sym and src_sym[0] == 'const' else None + if value is not None: + folded = (-value if value & 0x80000000 else value) & 0xffffffff + self.set_s(dst[1], '0x%08xu' % folded, ('const', folded), scc='$ != 0') + return None + expr = '(asint(%s) < 0 ? (0u - %s) : %s)' % ((self.u(ops[1]),) * 3) + self.set_s(dst[1], expr, scc='$ != 0') + return None + # ---- slot 57 mesh stage: instructions mesh_skeleton() puts in place of the group-memory exchanges ---- def op_x2w_mesh_lane0(self, ops, mods): # `s_mov_b64 exec, 1` leaves lane 0 of each wave running. The saved copy of that mask is not modelled. From f4f89946e74ee77904bf8210393386a9cd27e4cd Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:31:19 +0100 Subject: [PATCH 032/240] startup: accept the slot 57 count exchange entered under a v_cmpx-narrowed EXEC (Part of #2413) (#2643) * startup: accept the slot 57 count exchange entered under a v_cmpx-narrowed EXEC The region before the count exchange may end with s_mov_b64 exec, -1, a v_cmpx_gt_u32_e32 or v_cmpx_lt_u32_e32 of an SGPR against the proven thread index, and an s_cbranch_execz to the exchange's first s_barrier. The skipped block may hold lane-only instructions and scalar ALU whose results are dead at the exchange: no SGPR it writes is read from the exchange on, and SCC is rewritten by the exchange's s_cmp_eq_i32 before any read. Both count-exchange arms replace EXEC before lane-dependent work, and the HLSL barrier runs for every thread. Branches into the skipped block, other compare sources, scalar loads and other execz blocks stay refused. AI-assisted. * startup: accept any defined operands in the slot 57 count-entry compare The entry before the count exchange no longer requires the compare to use the thread index. The skipped block only leaves lane-predicated VGPR writes and scalar results that are dead at the exchange, and both exchange arms replace EXEC, so any per-lane EXEC from v_cmpx_gt_u32_e32 or v_cmpx_lt_u32_e32 gives the same visible result for a per-lane skip as for a per-wave skip. Each VGPR operand must be defined for every lane (not an entry value or left stale by an exchange); SGPRs and constants are taken. AI-assisted. --- docs/experiments.md | 16 +++++- tests/startup_mesh57_skeleton_check.py | 67 +++++++++++++++++++++++- tools/startup/gfx2hlsl.py | 72 ++++++++++++++++++++++---- 3 files changed, 142 insertions(+), 13 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 11011d9cc..80f8646ec 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9510,8 +9510,20 @@ stores the primitive and vertex counts, every wave passes a barrier, wave 0 sends one allocation request and the other wave reads the counts back; the code around it exports vertex and primitive `thread` under `count > thread`. `mesh_skeleton` in `tools/startup/gfx2hlsl.py` states -the shape and refuses every other program with the first difference. The -lowering clamps both counts to the 128 threads of a group and each index to +the shape and refuses every other program with the first difference. Before +the count exchange, a full EXEC reset followed by +`v_cmpx_gt_u32_e32` or `v_cmpx_lt_u32_e32` may narrow EXEC. Only nops and waits +may separate the compare from an `s_cbranch_execz` to the first count barrier. +The compare accepts SGPRs, inline constants or literals, and VGPRs defined +for every lane. The skipped block allows nops, waits, clauses and +lane-predicated instructions without scalar or EXEC writes, and scalar ALU +whose SGPR results are not read from the count exchange on (SCC is rewritten by the exchange's +`s_cmp_eq_i32`). Both guest exchange paths replace the incoming mask before +lane-dependent work, so skipping per lane in HLSL has the same visible effects +as skipping per wave on the guest for any compare predicate. In HLSL thread 0 +stores both counts, every thread passes the group barrier, and full EXEC is +restored before exports. +The lowering clamps both counts to the 128 threads of a group and each index to the last vertex. It reads 9-bit indices, ignores the edge flags, and gives a primitive whose null bit (31) is set one vertex three times, so it covers no pixel. A depth-only pixel program is refused. The source-built fixture draws diff --git a/tests/startup_mesh57_skeleton_check.py b/tests/startup_mesh57_skeleton_check.py index 563545090..e4da014b7 100644 --- a/tests/startup_mesh57_skeleton_check.py +++ b/tests/startup_mesh57_skeleton_check.py @@ -140,6 +140,39 @@ def masked_vertex_red(): PRIMITIVE_EXPORT = MESH.index('f8000941') +def count_entry_red(*extra_words): + wait = MESH.index('bf8c3f70') + return MESH[:COUNT] + [ + '7e0e0280', # v_mov_b32_e32 v7, 0 + 'befe04c1', # s_mov_b64 exec, -1 + '7da8000d', # v_cmpx_gt_u32_e32 s13, v0 (the proven thread index) + branch(0xbf88, COUNT + 3, COUNT + 5 + len(extra_words)), # s_cbranch_execz to the first count barrier + '7e0e02f2', # v_mov_b32_e32 v7, 1.0 + ] + list(extra_words) + MESH[COUNT:wait + 1] + [ + '7e280307', # v_mov_b32_e32 v20, v7 + ] + MESH[wait + 1:] + + +COUNT_ENTRY = count_entry_red() +COUNT_ENTRY_LT = mutate('7da8000d', '7da2000d', mesh=COUNT_ENTRY) +# v_mov_b32_e32 v8, 4 before the reset, then v_cmpx_lt_u32_e32 v8, v0. +COUNT_ENTRY_VGPRS = mutate('7da8000d', '7da20108', mesh=COUNT_ENTRY) +COUNT_ENTRY_VGPRS = COUNT_ENTRY_VGPRS[:COUNT + 1] + ['7e100284'] + COUNT_ENTRY_VGPRS[COUNT + 1:] +DEAD_SCALAR = '87288080' # s_and_b32 s40, 0, 0 +COUNT_ENTRY_SCALAR = count_entry_red(DEAD_SCALAR) +COUNT_ENTRY_CASES = ( + ('EXEC-zero branch to the count exchange after GT', COUNT_ENTRY, lambda lane: 255 if lane < 4 else 0), + ('EXEC-zero branch to the count exchange after LT', COUNT_ENTRY_LT, lambda lane: 255 if lane > 4 else 0), + ('EXEC-zero branch to the count exchange after LT with two VGPRs', COUNT_ENTRY_VGPRS, + lambda lane: 255 if lane > 4 else 0), + ('EXEC compare with a defined VGPR other than the thread index', + mutate('7da8000d', '7da80e0d', mesh=COUNT_ENTRY), lambda lane: 255), # s13 > v7 (4 > 0) + ('EXEC-zero branch to the count exchange over dead scalar ALU', COUNT_ENTRY_SCALAR, + lambda lane: 255 if lane < 4 else 0), +) +EXCHANGE_BRANCH_REFUSAL = 'slot 57 mesh: a branch enters or crosses a group-memory exchange' + + def joined_vertex_masks(): pos = MESH.index('f80008cf') # Move the vertex narrowing after the loads so the join cannot make any export operands stale. @@ -190,6 +223,36 @@ def expect(what, got, want): ('a branch into the count exchange', MESH[:COUNT] + [branch(0xbf82, COUNT, COUNT + 2)] + MESH[COUNT:], 'slot 57 mesh: a branch enters or crosses a group-memory exchange'), + ('an EXEC compare with an undefined first VGPR operand', + mutate('7da20108', '7da20101', mesh=COUNT_ENTRY_VGPRS), EXCHANGE_BRANCH_REFUSAL), + ('an EXEC compare with an unmodelled entry VGPR', + mutate('7da8000d', '7da8020d', mesh=COUNT_ENTRY), EXCHANGE_BRANCH_REFUSAL), + ('no EXEC reset before the compare', + mutate('befe04c1', 'bf800000', 1, mesh=COUNT_ENTRY), EXCHANGE_BRANCH_REFUSAL), + ('an EXEC-nonzero branch to the count exchange', + mutate('bf880001', 'bf890001', mesh=COUNT_ENTRY), EXCHANGE_BRANCH_REFUSAL), + ('an EXEC write in the skipped block', + mutate('7e0e02f2', 'befe04c1', mesh=COUNT_ENTRY), EXCHANGE_BRANCH_REFUSAL), + # Replace v_mov_b32 v20, v7 after the count exchange with v_mov_b32 v20, s40. + ('scalar ALU in the count-entry block with a live SGPR', + mutate('7e280307', '7e280228', mesh=COUNT_ENTRY_SCALAR), EXCHANGE_BRANCH_REFUSAL), + ('scalar ALU writing VCC in the count-entry block', + count_entry_red('876a8080'), EXCHANGE_BRANCH_REFUSAL), # s_and_b32 vcc_lo, 0, 0 + ('a scalar load in the count-entry block', + count_entry_red('f4000a05', 'fa000000'), EXCHANGE_BRANCH_REFUSAL), # s_load_dword s40, s[10:11], 0 + ('dead scalar ALU in a different EXEC-zero block', + vertex_red('7e0e02f2 bf880001 ' + DEAD_SCALAR), + 'slot 57 mesh: s_cbranch_execz skips code with effects outside active lanes'), + ('a v_cmpx in the skipped block', + mutate('7e0e02f2', '7da8000d', mesh=COUNT_ENTRY), EXCHANGE_BRANCH_REFUSAL), + ('an EXEC-zero branch over the count exchange', + mutate('bf880001', branch(0xbf88, COUNT + 3, POST_COUNT + 5), mesh=COUNT_ENTRY), EXCHANGE_BRANCH_REFUSAL), + ('an EXEC-zero branch past the start of the count exchange', + mutate('bf880001', 'bf880002', mesh=COUNT_ENTRY), EXCHANGE_BRANCH_REFUSAL), + ('a branch that bypasses the EXEC reset', + COUNT_ENTRY[:COUNT] + ['bf850002'] + COUNT_ENTRY[COUNT:], EXCHANGE_BRANCH_REFUSAL), + ('a branch into the skipped count-entry block', + COUNT_ENTRY[:COUNT] + ['bf850004'] + COUNT_ENTRY[COUNT:], EXCHANGE_BRANCH_REFUSAL), ('a branch over the group-index exchange', MESH[:1] + [branch(0xbf82, 1, GROUP_END + 1)] + MESH[1:], 'slot 57 mesh: a branch enters or crosses a group-memory exchange'), # s_branch .post_count replaces s_waitcnt lgkmcnt(0) between the exchanges. @@ -326,7 +389,7 @@ def controls(): expect('outputs follow the allocation', all(body.index(line) > body.index(want[-1]) for line in body if 'verts[tid]' in line or 'tris[tid]' in line), True) prefix = MESH[:1] + 'bf008080 bf850001 bf800000 bf800000'.split() + MESH[1:] - for what, mesh, _ in BRANCH_CASES + (('SCC branch before the group-index exchange', prefix, None),): + for what, mesh, _ in BRANCH_CASES + COUNT_ENTRY_CASES + (('SCC branch before the group-index exchange', prefix, None),): with tempfile.TemporaryDirectory() as tmp: key, result = request(tmp, mesh) expect(what + ' translates', result, 'ok') @@ -567,7 +630,7 @@ def draw(dxc, renderer, adapter, publisher=None): expect('a reference with one wrong pixel fails', (r.returncode, 'pixels=1024 mismatches=1' in r.stdout, 'Draw reference mismatch' in r.stderr), (1, True, True)) - for what, mesh, red in BRANCH_CASES: + for what, mesh, red in BRANCH_CASES + COUNT_ENTRY_CASES: key, result = request(tmp, mesh) expect(what + ' translates and compiles', result, 'ok') if result != 'ok': diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 1833941f6..23c6433ce 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -1396,6 +1396,9 @@ def mesh_skeleton(ins, vcc_branches, wave_limits): - Exchange: exec = 1 (lane 0 of each wave), the mask saved in an SGPR pair; wave 0 (s3 bits 24..27 zero) stores entry v5 >> 7 at byte 8, waits and passes a barrier; every other wave passes a barrier and reads byte 8 to v5. - Code up to the next barrier. Its only read of v5 may be one v_readfirstlane_b32 under exec = -1. + After a full EXEC reset, an unsigned GT or LT EXEC compare with defined operands may guard a forward + execz branch to that barrier. The skipped instructions only affect active lanes or dead scalars, and + both exchange arms replace EXEC, so a per-lane skip has the same visible effects as a per-wave skip. - Counts: one barrier; the wave whose index (s_bfe_u32 of s3, 4 bits at 24) is zero stores SGPR P at byte 0 and SGPR V at byte 4 under the saved lane-0 mask, waits, passes a barrier and sends one allocation request with m0 = P << 12 | V; every other wave passes a barrier and reads both words back into the same P and V. @@ -1438,6 +1441,40 @@ def lands(key, index, what): offsets = {item[0]: i for i, item in enumerate(ins)} edges = {} + count_entry = count_entry_branch = None + no_effect = lambda i: ins[i][2].startswith(('s_nop', 's_waitcnt', 's_clause')) + exchange_branch_refusal = 'slot 57 mesh: a branch enters or crosses a group-memory exchange' + + def lane_only(i): + _, _, name, asm = ins[i] + return (name.startswith(('v_', 'buffer_load')) and not name.startswith(EXECZ_REFUSED) + and not scalar_effects(name, asm)[2]) + + def dead_count_entry_scalar(i): + _, _, name, asm = ins[i] + if not re.fullmatch( + r's_(and|or|xor|andn2|orn2|bfe|max|min|mul|add|sub|lshl|lshr|ashr|mov|movk)_[biu]\d+', name): + return False + _, must, may = scalar_effects(name, asm) + written = must | may + regs = written - {'scc'} + if not written or any(not re.fullmatch(r's\d+', reg) for reg in regs): + return False + # Uses within the skipped block are fine. Every path out of it joins at the count exchange. + if any(regs & scalar_effects(*ins[j][2:])[0] for j in range(count_at, len(ins))): + return False + if 'scc' in written: + for j in range(count_at, len(ins)): + reads, must, may = scalar_effects(*ins[j][2:]) + if ins[j][2].startswith(('s_cbranch', 's_branch', 's_setpc', 's_call', 's_swappc', 's_endpgm')): + return False + if 'scc' in reads: + return False + if 'scc' in must: # a may-write alone (s_barrier) neither reads nor kills it + return True + return False + return True + for lo, hi in ((0, start), (a_end, count_at), (b_end, len(ins))): for i in range(lo, hi): off, _, name, asm = ins[i] @@ -1451,10 +1488,23 @@ def lands(key, index, what): dest = offsets.get(target) if dest is None: raise Unsupported('slot 57 mesh: a branch target is not an instruction boundary') - # The first instruction of an exchange is also the preceding region's join. - # Branches must reconverge before that instruction. if not lo <= dest < hi: - raise Unsupported('slot 57 mesh: a branch enters or crosses a group-memory exchange') + # Both count exchange arms replace the incoming EXEC before lane-dependent work. + if lo != a_end or dest != count_at or name != 's_cbranch_execz': + raise Unsupported(exchange_branch_refusal) + compare = i - 1 + while compare >= lo and ins[compare][2] in ('s_nop', 's_waitcnt'): + compare -= 1 + if (compare <= lo or ins[compare - 1][3] != 's_mov_b64 exec, -1' + or ins[compare][2] not in ('v_cmpx_gt_u32_e32', 'v_cmpx_lt_u32_e32') + or any(not (no_effect(k) or lane_only(k) or dead_count_entry_scalar(k)) + for k in range(i + 1, dest))): + raise Unsupported(exchange_branch_refusal) + _, sources, _ = parse(ins[compare][3]) + if len(sources) != 2 or any(not (re.fullmatch(r'[sv]\d+', tok) or tok in FLOATS + or pc_word(tok) is not None) for tok in sources): + raise Unsupported(exchange_branch_refusal) + count_entry, count_entry_branch = compare, i if target <= off: raise Unsupported('slot 57 mesh: a loop outside the group-memory exchanges is not covered') if name not in ('s_branch', 's_cbranch_scc0', 's_cbranch_scc1', 's_cbranch_execz') + MESH_VCC_BRANCHES: @@ -1462,7 +1512,8 @@ def lands(key, index, what): edges[i] = dest targets = set(edges.values()) - no_effect = lambda i: ins[i][2].startswith(('s_nop', 's_waitcnt', 's_clause')) + if count_entry is not None and targets.intersection(range(count_entry, count_at)): + raise Unsupported(exchange_branch_refusal) first_post_count_branch = next((i for i in edges if i >= b_end), None) shift_branch = None for source, target in edges.items(): @@ -1477,12 +1528,11 @@ def lands(key, index, what): # s_branch may land at the execz target or past it over instructions without effect (the # `s_branch .else` over `.empty: s_nop` of an if/else), so both paths meet with the same state. for i in range(source + 1, target): - _, _, name, asm = ins[i] + name = ins[i][2] if not (no_effect(i) or name == 'exp' or (name == 's_branch' and edges[i] >= target and all(no_effect(k) for k in range(target, edges[i]))) - or (name.startswith(('v_', 'buffer_load')) and not name.startswith(EXECZ_REFUSED) - and not scalar_effects(name, asm)[2])): + or lane_only(i) or (source == count_entry_branch and dead_count_entry_scalar(i))): raise Unsupported('slot 57 mesh: s_cbranch_execz skips code with effects outside active lanes') elif any(ins[i][2] == 'exp' for i in range(source + 1, target)): raise Unsupported('slot 57 mesh: a branch bypasses an export') @@ -1505,7 +1555,7 @@ def lands(key, index, what): exports = [] incoming = {} falls = True - for index in (list(range(first, start)) + [start] + list(range(a_end, count_at)) + [None] + for index in (list(range(first, start)) + [start] + list(range(a_end, count_at + 1)) + list(range(b_end, len(ins)))): if index in targets: paths = incoming[index] @@ -1537,7 +1587,7 @@ def lands(key, index, what): if base == a_bits or base in lane: base = None continue - if index is None: + if index == count_at: if not wave_known: raise Unsupported('slot 57 mesh count exchange: the compared register is not the wave index') out.append(span(count_at, b_end - 2) + ( @@ -1630,6 +1680,10 @@ def lands(key, index, what): stale |= pending pending.clear() mask, scc_stale = ('else', mask), True + elif index == count_entry: + if mask is not None or mesh_vregs(ops) & stale: + raise Unsupported(exchange_branch_refusal) + mask = 'count_entry' elif base_name.startswith('v_cmpx'): count = {env['verts']: 'verts', env['prims']: 'prims'}.get(ops[0] if ops else None) if (base_name != 'v_cmpx_gt_i32' or not after or mask is not None or count is None From 8972929cbe62fe3b217564359681b58975d920ea Mon Sep 17 00:00:00 2001 From: RavenCurseBurg Date: Thu, 26 Nov 2026 08:36:59 +0800 Subject: [PATCH 033/240] tests: select the hardware adapter for indirect Dispatch readbacks (#2652) Co-authored-by: RavenCurseBurg <360931527+RavenCurseBurg@users.noreply.github.com> --- CMakeLists.txt | 4 +++ docs/experiments.md | 4 +++ tests/adapter_name_filter.h | 37 ++++++++++++++++++++++++ tests/hardware_adapter_filter_check.py | 21 ++++++++++++++ tests/startup_indirect_dispatch.cpp | 6 +++- tests/startup_stream_rasterizer_check.py | 13 ++------- tests/startup_stream_setup.cpp | 21 ++++---------- 7 files changed, 78 insertions(+), 28 deletions(-) create mode 100644 tests/adapter_name_filter.h create mode 100644 tests/hardware_adapter_filter_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index d07c81da1..8fde67c4d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4071,6 +4071,10 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stream_rasterizer_check.py" "$" hardware filter) set_tests_properties(startup_stream_adapter_filter PROPERTIES TIMEOUT 30 SKIP_RETURN_CODE 77) + add_test(NAME startup_indirect_dispatch_adapter_filter COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/hardware_adapter_filter_check.py" + "$" hardware count) + set_tests_properties(startup_indirect_dispatch_adapter_filter PROPERTIES TIMEOUT 30) foreach(backend IN ITEMS warp hardware) add_test(NAME startup_stream_draw_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stream_draw_check.py" diff --git a/docs/experiments.md b/docs/experiments.md index 80f8646ec..bdc4c617a 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9151,6 +9151,10 @@ cmake --build --preset dev --target startup_indirect_dispatch ctest --preset dev --no-tests=error -R '^startup_indirect_count_(warp|hardware)$' -V ``` +On a multi-GPU system, set `$env:XBOX2WINDOWS_ADAPTER` to a case-insensitive part of the hardware +adapter's name, then run `startup_indirect_count_hardware`. The fixture prints the selected adapter, +driver, GPU-written count and fenced result. An unmatched or overlong hardware selector fails the test. + #### Root constants in an indirect dispatch signature Device slot 41 also accepts a compute signature with a root signature, whose diff --git a/tests/adapter_name_filter.h b/tests/adapter_name_filter.h new file mode 100644 index 000000000..a82ebbe02 --- /dev/null +++ b/tests/adapter_name_filter.h @@ -0,0 +1,37 @@ +#pragma once + +#include +#include +#include +#include + +// Hardware fixtures match XBOX2WINDOWS_ADAPTER against the DXGI description. +class AdapterNameFilter { +public: + bool read() + { + length = GetEnvironmentVariableW(L"XBOX2WINDOWS_ADAPTER", name, static_cast(std::size(name))); + if (length < std::size(name)) return true; + std::fputs("XBOX2WINDOWS_ADAPTER is longer than 127 characters\n", stderr); + return false; + } + + bool matches(const wchar_t* description) const + { + if (!length) return true; + for (const wchar_t* p = description; *p; ++p) + if (_wcsnicmp(p, name, length) == 0) return true; + return false; + } + + int no_match() const + { + if (!length) return 77; + std::fprintf(stderr, "No D3D12 hardware adapter matches XBOX2WINDOWS_ADAPTER=%ls\n", name); + return 4; + } + +private: + wchar_t name[128]{}; + DWORD length = 0; +}; diff --git a/tests/hardware_adapter_filter_check.py b/tests/hardware_adapter_filter_check.py new file mode 100644 index 000000000..2196c24f1 --- /dev/null +++ b/tests/hardware_adapter_filter_check.py @@ -0,0 +1,21 @@ +"""Check failure diagnostics for hardware adapter selectors in a GPU test executable.""" +import os +import subprocess +import sys + + +def check(args, env, allow_missing_factory=False): + missing = "x2w-no-such-hardware-adapter" + for selector, message in (("x" * 128, "XBOX2WINDOWS_ADAPTER is longer than 127 characters"), + (missing, f"No D3D12 hardware adapter matches XBOX2WINDOWS_ADAPTER={missing}")): + run = subprocess.run(args, env=dict(env, XBOX2WINDOWS_ADAPTER=selector), capture_output=True, text=True) + if allow_missing_factory and selector == missing and run.returncode == 77: + return 77 + if run.returncode != 4 or message not in run.stderr: + raise RuntimeError(f"expected {message!r}, got exit {run.returncode}\n{run.stdout}{run.stderr}") + print("overlong and unmatched hardware adapter filters rejected") + return 0 + + +if __name__ == "__main__": + sys.exit(check(sys.argv[1:], os.environ)) diff --git a/tests/startup_indirect_dispatch.cpp b/tests/startup_indirect_dispatch.cpp index 99d28e7bb..773fb1c04 100644 --- a/tests/startup_indirect_dispatch.cpp +++ b/tests/startup_indirect_dispatch.cpp @@ -4,6 +4,7 @@ #include #include +#include "adapter_name_filter.h" #include "desktop_gpu.h" #include @@ -317,12 +318,15 @@ int main(int argc, char** argv) try if (warp) { check(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)), "find WARP"); } else { + AdapterNameFilter filter; + if (!filter.read()) return 4; for (UINT index = 0; factory->EnumAdapters1(index, adapter.ReleaseAndGetAddressOf()) == S_OK; ++index) { DXGI_ADAPTER_DESC1 desc{}; if (SUCCEEDED(adapter->GetDesc1(&desc)) && !(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && + filter.matches(desc.Description) && SUCCEEDED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) break; } - if (!adapter) return 77; + if (!adapter) return filter.no_match(); } check(D3D12XboxCreateDevice(adapter.Get(), nullptr, IID_PPV_ARGS(&device)), "create desktop device through d3d12_xs"); SetEnvironmentVariableA("X2W_D3D12_PERMISSIVE", "1"); diff --git a/tests/startup_stream_rasterizer_check.py b/tests/startup_stream_rasterizer_check.py index bc3c55c84..2f094c361 100644 --- a/tests/startup_stream_rasterizer_check.py +++ b/tests/startup_stream_rasterizer_check.py @@ -6,6 +6,7 @@ import sys import tempfile +from hardware_adapter_filter_check import check as check_adapter_filter from startup_stream_check import gfx2hlsl from startup_stream_draw_check import pixel, vertex @@ -25,17 +26,7 @@ def check(directory, consumer, backend, mode): X2W_D3D12_DEBUG="1", X2W_SHADER_CACHE=str(cache)) base_args = [consumer, str(vs), str(ps), str(root), backend] if mode == "filter": - missing = "x2w-no-such-hardware-adapter" - for selector, message in (("x" * 128, "XBOX2WINDOWS_ADAPTER is longer than 127 characters"), - (missing, f"No D3D12 hardware adapter matches XBOX2WINDOWS_ADAPTER={missing}")): - req = subprocess.run(base_args, env=dict(env, XBOX2WINDOWS_ADAPTER=selector), - capture_output=True, text=True) - if selector == missing and req.returncode == 77: - return 77 - if req.returncode != 4 or message not in req.stderr: - raise RuntimeError(f"expected {message!r}, got exit {req.returncode}\n{req.stdout}{req.stderr}") - print("overlong and unmatched hardware adapter filters rejected") - return 0 + return check_adapter_filter(base_args, env, allow_missing_factory=True) req = subprocess.run(base_args, env=env, capture_output=True, text=True) if backend == "hardware" and req.returncode == 77: print("No D3D12 feature-level 12 hardware adapter") diff --git a/tests/startup_stream_setup.cpp b/tests/startup_stream_setup.cpp index 0c3ed381e..b031a9eca 100644 --- a/tests/startup_stream_setup.cpp +++ b/tests/startup_stream_setup.cpp @@ -12,6 +12,7 @@ #include #include +#include "adapter_name_filter.h" #include "startup_stream_setup.h" using Microsoft::WRL::ComPtr; @@ -79,32 +80,20 @@ int pick_stream_adapter(bool hardware, ComPtr& adapter) if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 4; if (!hardware) return SUCCEEDED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter))) ? 0 : 4; - wchar_t wanted[128]{}; - const DWORD length = GetEnvironmentVariableW(L"XBOX2WINDOWS_ADAPTER", wanted, 128); - if (length >= 128) { - std::fputs("XBOX2WINDOWS_ADAPTER is longer than 127 characters\n", stderr); - return 4; - } + AdapterNameFilter filter; + if (!filter.read()) return 4; ComPtr factory6; if (FAILED(factory.As(&factory6))) return 77; for (UINT n = 0;; ++n) { ComPtr candidate; const HRESULT hr = factory6->EnumAdapterByGpuPreference( n, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&candidate)); - if (hr == DXGI_ERROR_NOT_FOUND) { - if (!length) return 77; - std::fprintf(stderr, "No D3D12 hardware adapter matches XBOX2WINDOWS_ADAPTER=%ls\n", wanted); - return 4; - } + if (hr == DXGI_ERROR_NOT_FOUND) return filter.no_match(); if (FAILED(hr)) return 4; DXGI_ADAPTER_DESC1 desc{}; if (FAILED(candidate->GetDesc1(&desc))) return 4; if (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) continue; - bool matches = length == 0; - for (const wchar_t* p = desc.Description; !matches && *p; ++p) { - matches = _wcsnicmp(p, wanted, length) == 0; - } - if (matches && SUCCEEDED(D3D12CreateDevice(candidate.Get(), D3D_FEATURE_LEVEL_12_0, + if (filter.matches(desc.Description) && SUCCEEDED(D3D12CreateDevice(candidate.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) { adapter = candidate; return 0; From b32eb9eb139a2aba54fc1769287dc4404309b1fc Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Thu, 26 Nov 2026 01:40:26 +0100 Subject: [PATCH 034/240] gfx2hlsl: lower the compute buffer store `off` form when its data is proven wave-uniform (#2651) * gfx2hlsl: lower the compute buffer store `off` form when its data is proven wave-uniform A MUBUF store with neither offen nor idxen gives every lane the same byte address (soffset plus the immediate), so the active lanes race on one location. When every data VGPR holds one proven value in all enabled lanes the order does not matter, and the store lowers like the offen form with no VGPR term. The proof is the one v_readfirstlane_b32 already uses (entry block with a known EXEC, or a recomputable expression with no join or EXEC write since the definition), now shared as Stage.proven_uniform_v. v_lshrrev_b64 / v_lshlrev_b64 / v_ashrrev_i64 with scalar or literal sources now mark both destination halves uniform, under the same conditions Stage.one applies to the 32-bit VALU forms. Any other `off` store keeps a named refusal: "buffer store off with data not proven wave-uniform". The atomic `off` form is unchanged. Co-Authored-By: Claude Opus 5.5 * tests: cover the off store proof past the entry block Co-Authored-By: Claude Opus 5.5 * tests: dispatch two off-store compute cases and decode the hand-assembled words Cases O-dword (8 lanes, SGPR soffset plus immediate) and O-shift (32 lanes, dwordx4 of a 64-bit shift of a scalar pair) store in the off form, so every lane of a group writes one address. Their expected words are computed from the instruction semantics, and the dispatch mode compares all 320 words. The hand-assembled words are decoded with the repository disassembler and must match their source lines. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- tests/startup_gfx2hlsl_compute_check.py | 114 +++++++++++++++++++++++- tools/startup/gfx2hlsl.py | 41 +++++++-- 2 files changed, 145 insertions(+), 10 deletions(-) diff --git a/tests/startup_gfx2hlsl_compute_check.py b/tests/startup_gfx2hlsl_compute_check.py index fd4c3bd58..073786826 100644 --- a/tests/startup_gfx2hlsl_compute_check.py +++ b/tests/startup_gfx2hlsl_compute_check.py @@ -34,6 +34,10 @@ - case G reads two independently offset LDS dwords with the address in the first destination VGPR. - cases L-uint and L-unorm use the same formatted load with native descriptor stride and word 3 supplied by the harness. The descriptor selects unaligned UINT16 pairs or an UNORM8 field and permutes the outputs. +- cases O-dword and O-shift store in the `off` form (no VGPR address), so every lane of a group writes the same + address. O-dword: 8 lanes per group store key ^ group ID at byte 4 * group + 8 (SGPR soffset plus immediate). + O-shift: 32 lanes per group store (group ID, the (key, stride) pair shifted right by 4, 0) as four words at + byte 16 * group, the shape of a 64-bit shift of a scalar pair. The dispatch runs on a plain D3D12 device (the stand-in has no slot-67 path yet). The root signature is the runner's: root SRV t0 (read buffer), root UAV u0 (writable buffer) and 16 root constants at b0, which match the translation's @@ -484,6 +488,12 @@ def saveexec_fixture(): 's_mov_b32 s19, s31': '1f0393be', 's_mov_b32 s17, s29': '1d0391be', 's_cbranch_scc1 2': '020085bf', + 'buffer_store_dword v5, off, s[16:19], 0': '000070e000050480', + 'buffer_store_dword v5, off, s[16:19], s20 offset:8': '080070e000050414', + 'buffer_store_dwordx2 v[5:6], off, s[16:19], 0': '000074e000050480', + 'v_lshrrev_b64 v[5:6], 4, s[20:21]': '050000d784280000', + 'v_lshrrev_b64 v[5:6], 4, v[3:4]': '050000d784060200', + 's_cbranch_execz 4': '040088bf', } @@ -491,6 +501,11 @@ def splice(*lines, at=STORE_A): return WORDS_A[:at] + b''.join(bytes.fromhex(SPLICE[line]) for line in lines) + WORDS_A[at:] +def replace_store(*lines): + """Case A with its store replaced by `lines` (the last one is the new store).""" + return WORDS_A[:STORE_A] + b''.join(bytes.fromhex(SPLICE[line]) for line in lines) + WORDS_A[STORE_A + 8:] + + # Case I is case A with the store descriptor's stride field cleared before the store (expected words as case A). STRIDE_CLEAR = 's_and_b32 s17, s17, 0xc000ffff' CASES['I'] = (SOURCE_A.replace('buffer_store_dword', STRIDE_CLEAR + '\nbuffer_store_dword'), splice(STRIDE_CLEAR), @@ -510,6 +525,33 @@ def splice(*lines, at=STORE_A): CASES['A-ff1'] = ('s_ff1_i32_b32 s5, exec_lo\n' + SOURCE_A, bytes.fromhex('7e1385be') + WORDS_A, *CASES['A'][2:]) +# `off` stores: the words are hand-assembled from the RDNA 2 SOP1/SOP2/VOP1/VOP3/MUBUF field layouts (the binary +# mode reassembles them with llvm-mc); check_hand_words decodes them with the repository disassembler. +OFF_PROLOGUE = 's_mov_b32 s10, s6\ns_mov_b32 s11, 0\ns_load_dwordx8 s[12:19], s[10:11], 0x0\ns_waitcnt lgkmcnt(0)\n' +OFF_PROLOGUE_WORDS = '06038abe' '80038bbe' '05030cf4000000fa' '7fc08cbf' +SOURCE_O_DWORD = OFF_PROLOGUE + """\ +s_lshl_b32 s20, s7, 2 +s_xor_b32 s21, s4, s7 +v_mov_b32 v5, s21 +buffer_store_dword v5, off, s[16:19], s20 offset:8 +s_endpgm +""" +WORDS_O_DWORD = bytes.fromhex(OFF_PROLOGUE_WORDS + '0782148f' '04071589' '15020a7e' '080070e000050414' '000081bf') +SOURCE_O_SHIFT = OFF_PROLOGUE + """\ +s_mov_b32 s20, s4 +s_mov_b32 s21, s5 +s_lshl_b32 s22, s7, 4 +v_lshrrev_b64 v[5:6], 4, s[20:21] +v_mov_b32 v4, s7 +v_mov_b32 v7, 0 +buffer_store_dwordx4 v[4:7], off, s[16:19], s22 +s_endpgm +""" +WORDS_O_SHIFT = bytes.fromhex(OFF_PROLOGUE_WORDS + '040394be' '050395be' '0784168f' '050000d784280000' '0702087e' + '80020e7e' '000078e000040416' '000081bf') +CASES['O-dword'] = (SOURCE_O_DWORD, WORDS_O_DWORD, USER7 | TGID_X | tidig(1), (8, 1, 1), (4, 1, 1)) +CASES['O-shift'] = (SOURCE_O_SHIFT, WORDS_O_SHIFT, USER7 | TGID_X | tidig(1), (32, 1, 1), (4, 1, 1)) + def root_blob(constants=2, table_range=False): """RTS0: param 0 = root constants (b0), param 1 = a descriptor table with no ranges. @@ -546,6 +588,15 @@ def expected(name): if name in ('I', 'I-raw'): return expected('A') out = [SENTINEL] * WORDS + if name == 'O-dword': + for group in range(4): + out[2 + group] = KEY ^ group + return out + if name == 'O-shift': + pair = (STRIDE << 32 | KEY) >> 4 + for group in range(4): + out[4 * group:4 * group + 4] = [group, pair & MASK, pair >> 32, 0] + return out _, _, _, local, groups = CASES[name] if name in L_WORD3: data = formatted_input() @@ -871,6 +922,62 @@ def proof(code): assert switch in translate('L-uint', code=skip_one + bytes.fromhex('000080bf') + copy + high + target + load + tail).hlsl_cs() +def check_hand_words(): + """Hand-assembled words decode, with the repository disassembler, to the source line they stand for.""" + def decoded(words, at=0): + n, _, text, _ = G.D.decode_instruction(words, at) + return n, text.replace('_e32 ', ' ') + for line in ('buffer_store_dword v5, off, s[16:19], 0', 'buffer_store_dword v5, off, s[16:19], s20 offset:8', + 'buffer_store_dwordx2 v[5:6], off, s[16:19], 0', 'v_lshrrev_b64 v[5:6], 4, s[20:21]', + 'v_lshrrev_b64 v[5:6], 4, v[3:4]'): + assert decoded(bytes.fromhex(SPLICE[line]))[1] == line, (line, decoded(bytes.fromhex(SPLICE[line]))) + # A branch decodes to its target: 4 bytes past the branch plus 4 bytes per dword of the simm16. + assert decoded(bytes.fromhex(SPLICE['s_cbranch_execz 4']))[1] == 's_cbranch_execz label_0x14' + for name in ('O-dword', 'O-shift'): + source, words = CASES[name][:2] + at, texts = 0, [] + while at < len(words): + n, text = decoded(words, at) + texts.append(text) + at += n + assert texts == source.splitlines(), (name, texts) + + +def check_off_stores(): + """The `off` store (MUBUF offen = idxen = 0): every lane writes the same address, accepted with uniform data.""" + def lines(*code): + return translate('A', code=replace_store(*code)).hlsl_cs().splitlines() + hlsl = lines('v_mov_b32 v5, s20', 'buffer_store_dword v5, off, s[16:19], 0') + at = hlsl.index(' a = (0) & 0xfffffffcu;') + assert hlsl[at + 1] == ' u0.Store(a, v5);', hlsl[at:at + 2] + hlsl = lines('v_mov_b32 v5, s20', 'buffer_store_dword v5, off, s[16:19], s20 offset:8') + at = hlsl.index(' a = (s20 + 8) & 0xfffffffcu;') + assert hlsl[at + 1] == ' u0.Store(a, v5);', hlsl[at:at + 2] + # A 64-bit shift of scalar sources is uniform in both halves. + hlsl = lines('v_lshrrev_b64 v[5:6], 4, s[20:21]', 'buffer_store_dwordx2 v[5:6], off, s[16:19], 0') + at = hlsl.index(' a = (0) & 0xfffffffcu;') + assert hlsl[at + 1] == ' u0.Store2(a, uint2(v5, v6));', hlsl[at:at + 2] + # Past the entry block (inside a guard that skips per lane) the recomputable expression carries the proof. + guard = ['v_cmp_gt_u32 vcc_lo, 1, v0', 's_and_saveexec_b32 s0, vcc_lo'] + hlsl = lines(*guard, 's_cbranch_execz 3', 'v_mov_b32 v5, s20', 'buffer_store_dword v5, off, s[16:19], 0', + 's_or_b32 exec_lo, exec_lo, s0') + assert 'if (exec & 1) u0.Store(a, v5);' in [line.strip() for line in hlsl], hlsl + hlsl = lines(*guard, 's_cbranch_execz 4', 'v_lshrrev_b64 v[5:6], 4, s[20:21]', + 'buffer_store_dwordx2 v[5:6], off, s[16:19], 0', 's_or_b32 exec_lo, exec_lo, s0') + assert 'if (exec & 1) u0.Store2(a, uint2(v5, v6));' in [line.strip() for line in hlsl], hlsl + # The saveexec between the definition and the store ends the proof (conservative: these lanes are a subset). + refused('buffer store off with data not proven wave-uniform', lambda: lines( + 'v_mov_b32 v5, s20', *guard, 's_cbranch_execz 3', 's_waitcnt lgkmcnt(0)', + 'buffer_store_dword v5, off, s[16:19], 0', 's_or_b32 exec_lo, exec_lo, s0')) + # Negative controls: per-lane data (a shift of the thread index; the per-lane load), and uniform data written + # before an EXEC change, where the entry-block proof no longer knows which lanes store. + for code in (('v_lshrrev_b64 v[5:6], 4, v[3:4]', 'buffer_store_dwordx2 v[5:6], off, s[16:19], 0'), + ('buffer_store_dword v5, off, s[16:19], 0',), + ('v_mov_b32 v5, s20', 'v_cmp_gt_u32 vcc_lo, 3, v0', 's_mov_b32 exec_lo, vcc_lo', + 'buffer_store_dword v5, off, s[16:19], 0')): + refused('buffer store off with data not proven wave-uniform', lambda code=code: lines(*code)) + + def check_controls(): ff1 = bytes.fromhex('7e1385be') end = bytes.fromhex('000081bf') @@ -923,7 +1030,7 @@ def check_controls(): refused('numeric use of s7', lambda: translate('A', rsrc2=(8 << 1) | tidig(3)).hlsl_cs()) # Store forms outside this slice (the store is the dword at +0x60 of WORDS_A: offen, soffset 0x80, s[16:19]). store = '001070e004050480' - for word, fragment in (('000070e004050480', 'offen address form'), # off: no offen + for word, fragment in (('000070e004050480', 'not proven wave-uniform'), # off: one address, per-lane data ('002070e004050480', 'modifier idxen'), # idxen, no offen ('005070e004050480', 'modifier glc'), # glc offen ('001070e004050380', 'used for a load and a store')): # store through the read descriptor @@ -936,6 +1043,11 @@ def check_controls(): assert str(reason) == text, str(reason) else: raise AssertionError('graphics store accepted') + check_hand_words() + check_off_stores() + for name in ('O-dword', 'O-shift'): + hlsl = translate(name).hlsl_cs().splitlines() + assert any('u0.Store' in line for line in hlsl), (name, hlsl) # A register soffset is added to the address. hlsl = translate('A', code=patch(WORDS_A, store, '001070e004050414')).hlsl_cs() assert ' a = (v4 + s20 + 0) & 0xfffffffcu;' in hlsl.splitlines(), hlsl diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 23c6433ce..ae0fcd2d2 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -4435,7 +4435,7 @@ def store_descriptor(self, tok, words, what, stride0_ok=False, raw_conversion_ok return key def raw_table_uav_store(self, kind_label, ops, mods, data_count, *, allow_glc=False, allow_scalar_address=False, - raw_conversion_ok=False): + raw_conversion_ok=False, uniform_off=False): """Validate a fixed-table raw UAV descriptor, data range, byte address, and 4-byte alignment.""" offset = 0 glc = False @@ -4447,7 +4447,7 @@ def raw_table_uav_store(self, kind_label, ops, mods, data_count, *, allow_glc=Fa elif m != 'offen': raise Unsupported('%s modifier %s' % (kind_label, m)) offen = 'offen' in mods - if len(ops) != 4 or (not offen and not (allow_scalar_address and glc and ops[1] == 'off')): + if len(ops) != 4 or not (offen or ops[1] == 'off' and (allow_scalar_address and glc or uniform_off)): raise Unsupported('%s without the offen address form' % kind_label) data = reg_range(ops[0]) if not data or data[0] != 'v' or data[2] - data[1] != data_count - 1 or data[2] > 255: @@ -4459,7 +4459,7 @@ def raw_table_uav_store(self, kind_label, ops, mods, data_count, *, allow_glc=Fa key = self.store_descriptor(ops[2], 4, kind_label, stride0_ok=True, raw_conversion_ok=raw_conversion_ok) terms = [self.u(ops[1])] if offen else [] if re.fullmatch(r'0x[0-9a-f]+|\d+', ops[3]): - if not offen: + if not offen and not uniform_off: raise Unsupported('%s off requires a scalar register soffset' % kind_label) offset += int(ops[3], 0) else: @@ -4481,7 +4481,12 @@ def op_buffer_store_dword(self, ops, mods, count=1): return self.op_buffer_store_vs(ops, mods, count) if self.kind != 'cs': raise Unsupported('buffer_store_dword' + ('x%d' % count if count > 1 else '')) # the unknown-op refusal - src, uav, address, _ = self.raw_table_uav_store('buffer store', ops, mods, count, raw_conversion_ok=True) + src, uav, address, _ = self.raw_table_uav_store('buffer store', ops, mods, count, raw_conversion_ok=True, + uniform_off=True) + # The `off` form (no VGPR address, MUBUF offen = idxen = 0) gives every lane the same byte address, so the + # lanes race; with one proven value in all of them any order stores the same words. + if ops[1] == 'off' and not all(self.proven_uniform_v(n) for n in range(src[1], src[2] + 1)): + raise Unsupported('buffer store off with data not proven wave-uniform') words = [self.u('v%d' % n) for n in range(src[1], src[2] + 1)] data = words[0] if count == 1 else 'uint%d(%s)' % (count, ', '.join(words)) # Store* needs a multiple of four. As in #2059, the run-time part (VGPR and register soffset) is rounded down: @@ -5741,14 +5746,21 @@ def op_v_mbcnt_lo_u32_b32(self, ops, mods, high=False): def op_v_mbcnt_hi_u32_b32(self, ops, mods): self.op_v_mbcnt_lo_u32_b32(ops, mods, high=True) + def proven_uniform_v(self, n): + """VGPR n holds one value in every lane EXEC enables now. In the entry block EXEC is known; past it, a + recomputable expression proves no join, EXEC write or overwrite lies between the definition and here.""" + if not self.tracks_uniformity() or n not in self.uniform_v: + return False + # Past the entry block of a branch-free program is only dead code after s_endpgm: nothing to recompute. + if getattr(self, 'past_entry', True): + return n in getattr(self, 'uniform_expr', {}) and getattr(self, 'has_branches', False) + return getattr(self, 'exec_known', False) + def op_v_readfirstlane_b32(self, ops, mods): src, dst = reg_range(ops[1]), reg_range(ops[0]) past_entry = getattr(self, 'past_entry', True) - # Past the entry block of a branch-free program is only dead code after s_endpgm: nothing to recompute. - if (mods or not self.tracks_uniformity() or not dst or dst[0] != 's' or dst[1] != dst[2] or - not src or src[0] != 'v' or src[1] != src[2] or src[1] not in self.uniform_v or - (src[1] not in getattr(self, 'uniform_expr', {}) or not getattr(self, 'has_branches', False) - if past_entry else not getattr(self, 'exec_known', False))): + if (mods or not dst or dst[0] != 's' or dst[1] != dst[2] or + not src or src[0] != 'v' or src[1] != src[2] or not self.proven_uniform_v(src[1])): raise Unsupported('v_readfirstlane_b32 requires a proven uniform source') if past_entry: # The first active lane ran the definition: no join, EXEC write or overwrite of the VGPR and no write @@ -6239,6 +6251,17 @@ def shift64(self, ops, mods, helper): self.clear_low16(dst[2]) self.used_v.update((dst[1], dst[2])) self.emit(body if self.exec_known else 'if (exec & 1) ' + body) + # Scalar or literal sources give every lane the same result, under the conditions Stage.one uses for VALU. + pair = reg_range(ops[2]) + sources = [ops[1]] + (['%s%d' % (pair[0], pair[1]), '%s%d' % (pair[0], pair[2])] if pair else []) + if (self.tracks_uniformity() and not any(reg_range(t)[0] == 'v' for t in sources if reg_range(t)) and + all(self.uniform_source(t) for t in sources) and + (getattr(self, 'past_entry', False) and hasattr(self, 'uniform_expr') or + not getattr(self, 'past_entry', True) and getattr(self, 'exec_known', False))): + self.uniform_v.update((dst[1], dst[2])) + if hasattr(self, 'uniform_expr'): + for n, half in ((dst[1], 'x'), (dst[2], 'y')): + self.uniform_expr[n] = '%s(%s, %s, %s).%s' % (helper, low, high, amount, half) def carry_out_op(self, ops, mods, kind): """v_{add,sub,subrev}_co_u32 D, SDST, S0, S1: a 32-bit add or subtract with a carry or borrow out. From 014778ae64318f332e2ceb7a9d24da89e600764c Mon Sep 17 00:00:00 2001 From: tedin7 <110300616+tedin7@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:44:48 +0100 Subject: [PATCH 035/240] shader: lower 64-bit scalar bit-count and scan ops in gfx2hlsl (Part of #1723) (#2072) * shader: lower s_bcnt0/1, s_ff0/ff1_i32_b64 and s_flbit_i32_b64/i64 in gfx2hlsl (Part of #1723) * docs: document startup scalar bit count and scan lowering (Part of #1723) * test: draw the 64-bit scalar bit scans on the adapter and read them back (#1723) * docs: describe the scalar bit scan draw test and list it in the Linux checks (#1723) * Carry bit-scan words through the float render target --------- Co-authored-by: Royoo <3230853833@qq.com> --- .github/workflows/windows.yml | 1 + CMakeLists.txt | 11 +- docs/experiments.md | 14 ++ tests/startup_gfx2hlsl_s_bit_scan_check.py | 214 +++++++++++++++++++++ tools/startup/gfx2hlsl.py | 46 +++++ 5 files changed, 285 insertions(+), 1 deletion(-) create mode 100644 tests/startup_gfx2hlsl_s_bit_scan_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index fc2fb553b..a835e9c03 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -315,6 +315,7 @@ jobs: tests/startup_gfx2hlsl_mul_hi_check.py \ tests/startup_gfx2hlsl_sad_check.py \ tests/startup_gfx2hlsl_scalar_brev_fold_check.py \ + tests/startup_gfx2hlsl_s_bit_scan_check.py \ tests/startup_gfx2hlsl_pack_b32_f16_check.py \ tests/startup_inline_sampler_check.py \ tests/startup_buffer_address_check.py \ diff --git a/CMakeLists.txt b/CMakeLists.txt index 8fde67c4d..6fd6646d2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3385,7 +3385,7 @@ if(EXISTS "${INTAKE_PYTHON}") # Scalar SOPK accumulate: s_addk_i32 signed-overflow SCC and s_mulk_i32 against an integer reference. add_test(NAME startup_gfx2hlsl_sopk_accum COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_sopk_accum_check.py") - # s_pack_ll_b32_b16, s_pack_lh_b32_b16 and s_absdiff_i32 against an integer reference (#1723). + # s_pack_ll_b32_b16, s_pack_lh_b32_b16 and s_absdiff_i32 against an integer reference (#1723); the _warp/_hardware tests also draw them (D3D12 readback). add_test(NAME startup_gfx2hlsl_pack_absdiff COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_pack_absdiff_check.py") foreach(adapter IN ITEMS warp hardware) @@ -3664,6 +3664,15 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(raster_winding_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() + # s_bcnt0/1_i32_b32/b64, s_ff0/ff1_i32_b64 and s_flbit_i32_b64/i64 against an integer reference (#1723); the _warp/_hardware tests also draw them (D3D12 readback). + add_test(NAME startup_gfx2hlsl_s_bit_scan COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_s_bit_scan_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_s_bit_scan_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_s_bit_scan_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_s_bit_scan_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl per-lane bit operations: CPU evaluation of the translated text against an independent # reference with mutation controls, then a desktop draw of the translated pairs (FXC 5_1 and DXC 6_0). add_test(NAME startup_gfx2hlsl_bit_alu_controls COMMAND "${INTAKE_PYTHON}" -B diff --git a/docs/experiments.md b/docs/experiments.md index bdc4c617a..6c043a309 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15659,6 +15659,20 @@ rewrite the lowering to the uncapped `frac` and to a `min`-form cap and require ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_fract$' -V ``` +## Startup scalar bit counts and scans + +`tools/startup/gfx2hlsl.py` lowers eight scalar bit operations that it used to refuse with `Unsupported`: `s_bcnt0_i32_b32`, `s_bcnt1_i32_b32`, `s_bcnt0_i32_b64`, `s_bcnt1_i32_b64`, `s_ff0_i32_b64`, `s_ff1_i32_b64`, `s_flbit_i32_b64` and `s_flbit_i32_i64`. Each writes one 32-bit SGPR. The counts set `SCC` to `result != 0`. The scans return `0xffffffff` when no bit qualifies and leave `SCC` alone. `s_flbit_i32_i64` counts the leading bits equal to the sign bit, so it complements a negative value before it counts. The 32-bit scan forms were already covered elsewhere and are not changed. + +Scope: the source is a register only (`s0` to `s105`, an even-aligned pair for the `b64` forms; an odd start is refused). Literals, inline constants, `exec`, `vcc`, `m0`, a pair that crosses `s105`, source or destination modifiers and a wrong operand count are refused. A source that holds a lane mask is refused with `... on a lane mask`; a destination that held a mask stops being one. The destination must be one SGPR in `s0..s105`. + +`tests/startup_gfx2hlsl_s_bit_scan_check.py` builds the SOP1 words, translates them, runs the emitted HLSL on the integer evaluator of `startup_gfx2hlsl_bit_alu_check.py` and compares every result with a loop-and-string reference written from the ISA description. The same file has a `draw` mode: a pixel stage loads literals into `s4`/`s5`, runs each of the eight forms on four lanes, and the adapter output words are read back against the same reference (FXC 5_1 and DXC 6_0). The fixture XORs the result with `0x3f000000` before the float export so every expected integer is carried as a finite normal bit pattern. A wrong-count reference must produce a readback mismatch. + +```bash +python3 -B tests/startup_gfx2hlsl_s_bit_scan_check.py +ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_s_bit_scan$' -V +ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_s_bit_scan_warp$' -V +``` + ## Vulkan subnormal preservation in a pixel shader `tests/pixel_denorm_vulkan_check.py` compiles one source-built `ps_6_2` pixel shader with DXC for Vulkan 1.2 and draws it with `tests/vk_pixel_draw.c`. Seven operations (`1 * 2^-149`, `0x007fffff + 0`, `minnorm * 0.5`, `minnorm - 2^-149`, `2^-149 + 2^-149`, `-0x00000003 * 1` and `2^-149 * 2^23`) take or produce binary32 subnormals. The inputs come from a constant buffer so DXC cannot fold them, and each result word is read back from an RGBA32UI pixel. The reference is IEEE binary32 arithmetic in Python. `-denorm preserve` must match it on all seven; `-denorm ftz` is the negative control and must differ on at least one, which shows that the probe separates preserve from flush. A device with `shaderDenormPreserveFloat32` false is a capability skip, and a module that `spirv-val` or the driver refuses is a validation refusal; both are reported apart from mismatches. The check shows how a driver treats subnormals in this one shader. It does not show that translated shaders from `tools/pixel_aot.py` render the same bits under Vulkan. diff --git a/tests/startup_gfx2hlsl_s_bit_scan_check.py b/tests/startup_gfx2hlsl_s_bit_scan_check.py new file mode 100644 index 000000000..0b97327eb --- /dev/null +++ b/tests/startup_gfx2hlsl_s_bit_scan_check.py @@ -0,0 +1,214 @@ +"""Scalar bit counts and scans in tools/startup/gfx2hlsl.py (Frontier next batch 3 #1, #1723). + +usage: startup_gfx2hlsl_s_bit_scan_check.py [draw [fxc]] + +With `draw` the same instructions also run as a pixel shader on the adapter and the result words are read back +and compared with the integer reference (D3D12 readback, FXC 5_1 and DXC 6_0). + +s_bcnt0/1_i32_b32/b64 count zero/one bits (SCC = result != 0). s_ff0/ff1_i32_b64 return the index of the lowest +zero/one bit of a 64-bit source, s_flbit_i32_b64 the number of leading zeros, s_flbit_i32_i64 the number of leading +bits equal to the sign bit; the scans return -1 when nothing qualifies and leave SCC alone. The translator refused +all of them with `Unsupported`. The instruction words are built from the SOP1 layout the decoder reads, the emitted +HLSL runs on the integer evaluator of startup_gfx2hlsl_bit_alu_check.py, and every result is compared with a plain +integer reference written from the ISA description (string and loop based, not the lowering's expressions). +""" +import struct +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import Expr # noqa: E402 + +MASK = 0xffffffff +failures = [] +OPCODES = {'s_bcnt0_i32_b32': 0x0d, 's_bcnt0_i32_b64': 0x0e, 's_bcnt1_i32_b32': 0x0f, 's_bcnt1_i32_b64': 0x10, + 's_ff0_i32_b64': 0x12, 's_ff1_i32_b64': 0x14, 's_flbit_i32_b64': 0x16, 's_flbit_i32_i64': 0x18} +EXEC_LO, M0 = 126, 124 + + +def check(label, ok, detail=''): + print('%s: %s' % (label, 'ok' if ok else 'MISMATCH')) + if not ok: + failures.append(label) + if detail: + print(' ' + detail) + + +def encode(name, sdst, ssrc0): + return struct.pack('> i) & 1 for i in range(width)] + + +def ref(name, value): + """(result, scc or None) from the ISA text, with the source as a 32- or 64-bit integer.""" + width = 32 if name.endswith('b32') else 64 + b = bits(value, width) + if 'bcnt0' in name: + return b.count(0), True + if 'bcnt1' in name: + return b.count(1), True + if 'ff0' in name or 'ff1' in name: + want = 0 if 'ff0' in name else 1 + return next((i for i, x in enumerate(b) if x == want), MASK), False + sign = b[63] if name.endswith('i64') else 0 + n = 0 + for x in reversed(b): + if x != sign: + return n, False + n += 1 + return MASK, False + + +VALUES = [0, 1, 2, 0x80, 0xff, 0x7fffffff, 0x80000000, 0xffffffff, 0x12345678, 0xfffffffe, 0xdeadbeef] +WIDE = [0, 1, 1 << 31, 1 << 32, 1 << 33, 1 << 62, 1 << 63, (1 << 64) - 1, (1 << 63) - 1, (1 << 64) - 2, + 0x00000000ffffffff, 0xffffffff00000000, 0x0123456789abcdef, 0xfedcba9876543210, 0x8000000000000001, + 0xffffffff7fffffff] + [1 << k for k in range(64)] + [((1 << 64) - 1) ^ (1 << k) for k in range(64)] + +for name in OPCODES: + wide = not name.endswith('b32') + asm, lines = translate(name, 3, 4 if wide else 2) + src = 's[4:5]' if wide else 's2' + check('%s decodes' % name, asm == ['%s s3, %s' % (name, src)], repr(asm)) + bad = [] + for value in (WIDE if wide else VALUES): + regs = {'scc': 0, 's4': value & MASK, 's5': value >> 32, 's2': value & MASK} + env = run(lines, regs) + want, scc = ref(name, value) + want_scc = int(want != 0) if scc else 0 + if env['s3'] != want or env['scc'] != want_scc: + bad.append((hex(value), env['s3'], env['scc'], want, want_scc)) + if len(bad) == 3: + break + check('%s values' % name, not bad, repr(bad)) + scc_emitted = any(line.startswith('scc') for line in lines) + check('%s SCC %s' % (name, 'follows result' if 'bcnt' in name else 'untouched'), scc_emitted == ('bcnt' in name), + repr(lines)) + +# Refusals that must not widen: a 64-bit scan needs a register pair, 32-bit one register, and no lane-mask data. +check('b64 refuses an inline constant source', refused('s_ff1_i32_b64', 3, 0x80)) +check('b32 refuses exec destination', refused('s_bcnt1_i32_b32', EXEC_LO, 2)) +check('b32 refuses m0 destination', refused('s_bcnt1_i32_b32', M0, 2)) +check('b32 refuses exec source', refused('s_bcnt1_i32_b32', 3, EXEC_LO)) +check('b64 refuses a lane-mask source', refused('s_bcnt1_i32_b64', 3, 4, masks=(5,))) +check('b32 refuses a lane-mask source', refused('s_bcnt0_i32_b32', 3, 2, masks=(2,))) + + +# ---- a real draw: the translated pixel shader runs on the adapter and its words are read back ---------------- +# Each channel loads a 64-bit (or 32-bit) literal into s4/s5 and runs the scalar op into s3. +# Counts and bit indices are 0..64 or 0xffffffff. XOR moves each expected word into a distinct +# finite normal float bit pattern before the RGBA32_FLOAT export. A raw small result can flush to zero. +DRAW_TRANSPORT_XOR = 0x3f000000 +DRAW_VALUES = { + 32: [0, MASK, 0x80000000, 0x12345678, 1, 0xfffffffe, 0x0000ff00, 0xdeadbeef], + 64: [0, (1 << 64) - 1, 1 << 63, 1 << 32, 0x00000000ffffffff, 0xffffffff00000000, 0x0123456789abcdef, + 0xfedcba9876543210, 0x8000000000000001, (1 << 64) - 2, 1 << 31, 0xffffffff7fffffff], +} +POST_WORDS = bytes.fromhex('0f1800f80c0d0e0f000081bf') # exp mrt0 v12..v15 done vm; s_endpgm + + +def sop1(op, sdst, ssrc0): + return struct.pack('> 32) + xor_s3_literal = (0b10 << 30) | (0x12 << 23) | (3 << 16) | (255 << 8) | 3 + return out + sop1(OPCODES[name], 3, 4) + struct.pack('<2I', xor_s3_literal, DRAW_TRANSPORT_XOR) + + +def ps_words_for(name, chunk): + from startup_gfx2hlsl_bit_alu_check import PRE_WORDS + body = b'' + for lane, value in enumerate(chunk): + body += lane_words(name, value) + struct.pack(' 1: + if sys.argv[1] != 'draw': + raise SystemExit(__doc__) + draw_check(*sys.argv[2:]) +print('PASS') diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index ae0fcd2d2..248169608 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -6985,6 +6985,52 @@ def handler(self, ops, mods): self.set_scc((cast % op).format(self.u(ops[0]), '0x%08xu' % sopk_imm(ops[1], signed))) return handler setattr(Stage, 'op_s_cmpk_%s_%s' % (_name, _typ), _make_cmpk()) +# Scalar bit counts and scans with a 32-bit result. `lo`/`hi` are the uint words of the source: a 32-bit source has only +# `lo`. The scans return 0xffffffff (-1) when no bit qualifies. Only the counts set SCC (result != 0). +def _clz64(lo, hi): + return ('(%(h)s != 0u ? 31u - firstbithigh(%(h)s) : (%(l)s != 0u ? 63u - firstbithigh(%(l)s) : 0xffffffffu))' + % {'l': lo, 'h': hi}) + + +def _ctz64(lo, hi): + return ('(%(l)s != 0u ? firstbitlow(%(l)s) : (%(h)s != 0u ? 32u + firstbitlow(%(h)s) : 0xffffffffu))' + % {'l': lo, 'h': hi}) + + +def _flbit_i64(lo, hi): + # first bit that differs from the sign bit: complement a negative value, then count leading zeros + neg = '((%s & 0x80000000u) != 0u)' % hi + return _clz64('(%s ? ~%s : %s)' % (neg, lo, lo), '(%s ? ~%s : %s)' % (neg, hi, hi)) + + +# name -> (source is a register pair, expression over (lo, hi), SCC rule or None) +SCALAR_BITS = { + 's_bcnt0_i32_b32': (False, lambda lo, hi: '(32u - countbits(%s))' % lo, '$ != 0'), + 's_bcnt1_i32_b32': (False, lambda lo, hi: 'countbits(%s)' % lo, '$ != 0'), + 's_bcnt0_i32_b64': (True, lambda lo, hi: '(64u - countbits(%s) - countbits(%s))' % (lo, hi), '$ != 0'), + 's_bcnt1_i32_b64': (True, lambda lo, hi: '(countbits(%s) + countbits(%s))' % (lo, hi), '$ != 0'), + 's_ff0_i32_b64': (True, lambda lo, hi: _ctz64('(~%s)' % lo, '(~%s)' % hi), None), + 's_ff1_i32_b64': (True, _ctz64, None), + 's_flbit_i32_b64': (True, _clz64, None), + 's_flbit_i32_i64': (True, _flbit_i64, None), +} +for _name, (_pair, _expr, _scc) in SCALAR_BITS.items(): + def _make_scalar_bits(name=_name, pair=_pair, expr=_expr, scc=_scc): + def handler(self, ops, mods): + if len(ops) != 2 or mods: + raise Unsupported('%s requires two unmodified operands' % name) + dst, src = reg_range(ops[0]), reg_range(ops[1]) + if dst is None or dst[0] != 's' or dst[1] != dst[2] or dst[1] > 105: + raise Unsupported('%s destination %s' % (name, ops[0])) + if src is None or src[0] != 's' or src[2] > 105 or src[2] - src[1] != (1 if pair else 0): + raise Unsupported('%s source %s' % (name, ops[1])) + if any(r in self.masks for r in range(src[1], src[2] + 1)): + raise Unsupported('%s on a lane mask' % name) + lo, hi = self.S(src[1]), self.S(src[2]) + self.masks.discard(dst[1]) + self.set_s(dst[1], expr(lo, hi), scc=scc) + return handler + setattr(Stage, 'op_' + _name, _make_scalar_bits()) # s_bitcmp1_b32 / s_bitcmp0_b32: SCC = S0[S1[4:0]] == 1 / == 0. for _bit in (0, 1): def _make_bitcmp(bit=_bit): From fa39f25d7fb91747a449af2b496413c9d98cf83b Mon Sep 17 00:00:00 2001 From: RavenCurseBurg Date: Thu, 26 Nov 2026 08:45:28 +0800 Subject: [PATCH 036/240] tests: batch heap-view store references by compute shader (#2654) Co-authored-by: RavenCurseBurg <360931527+RavenCurseBurg@users.noreply.github.com> Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- docs/experiments.md | 5 +++ tests/compute_heap_store_check.py | 57 ++++++++++++++---------------- tests/compute_load_format_check.py | 5 ++- 3 files changed, 35 insertions(+), 32 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 6c043a309..f7ddc0803 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -6240,6 +6240,11 @@ Run `ctest --preset dev -R '^compute_(heap_store_controls|store_aot_heap_view_st ### Packed D16 heap-view stores +The `compute_store_aot_heap_view_store_{warp,hardware}` tests group matching readbacks by shader. +One renderer process per shader runs 12 UINT4 cases and 12, 16, 17 and 17 cases for D16 XYZW, X, +XY and XYZ respectively. Each case dispatches separately and compares 320 words. The 52 shader +mutations run individually and retain their readback diagnostics. + With the same `--heap-store-view` binding, gfx1013 `buffer_store_format_d16_xyzw` reads X/Y from the low/high halves of the first VGPR and Z/W from the second. A live identity `BUF_FMT_32_32_32_32_FLOAT` view (format 77) receives four binary32 words. Two source VGPRs still require 16 writable bytes in the destination. `buffer_store_format_d16_x` takes one source VGPR, converts its low 16 bits (`& 0xffffu`) via `f16tof32`, and writes one 4-byte binary32 word into a live identity `BUF_FMT_32_FLOAT` view (format 22, `0x01016fac`), enforcing 4-byte offset/stride/base alignment and `(bytes - view.x - offset - 4u) / stride` bounds without a raw UAV read-modify-write. A view whose format differs from the required component count or numeric type leaves the output untouched. [AMD RDNA 2 instruction set](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) · [HLSL half-to-float conversion](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/f16tof32) The heap-store CTest selection above runs the UINT4 program and all four packed D16 widths. Each D16 fixture checks 320 words across its heap-view cases (with `D16_X` additionally checking four binary16 payload patterns with poisoned high halves: `1.0`..`1.00293`, `-2.0`.., minimum positive subnormal + `+0.0`, and `-0.0` + negative subnormals, plus `UINT1` and `FLOAT4` mismatch rejections and untouched adjacent sentinel dwords). Eleven compiled shader mutations check addressing, view selection, and half-float extraction, including swapping high for low bits, checking the wrong format word, and writing packed values directly. diff --git a/tests/compute_heap_store_check.py b/tests/compute_heap_store_check.py index 21e8906b7..30f6ecffe 100644 --- a/tests/compute_heap_store_check.py +++ b/tests/compute_heap_store_check.py @@ -5,6 +5,7 @@ import sys import tempfile +from compute_load_format_check import check_references import compute_store_check as base @@ -211,10 +212,12 @@ def compile_shader(text): default_payload = 0x42000001 if mode == "d16_xyz" else D16_X_PAYLOADS[0][1] - def run(slot, payload=default_payload, expected_x=D16_X, table_words=table, expected_y=0x40400000, - expected_z=0x33800000): + def write_case(path, slot, payload=default_payload, expected_x=D16_X, table_words=table, + expected_y=0x40400000, expected_z=0x33800000, written_offsets=None): result = [base.SENTINEL] * WORDS - for thread, start in enumerate(cases[slot][2]): + if written_offsets is None: + written_offsets = cases[slot][2] + for thread, start in enumerate(written_offsets): if mode == "d16_x": result[start] = expected_x[thread] elif mode == "d16_xy": @@ -226,49 +229,39 @@ def run(slot, payload=default_payload, expected_x=D16_X, table_words=table, expe result[start:start + 4] = [D16_X[thread], 0xc0000000, 0x33800000, 0x80000000] else: result[start:start + 4] = [thread, 0x12345678, 0x80000001, 0x3F800001] - case = directory / "store.case" - case.write_bytes(struct.pack("<321I", 1, *result) + struct.pack("<16I", slot, payload, *([0] * 14)) + path.write_bytes(struct.pack("<321I", 1, *result) + struct.pack("<16I", slot, payload, *([0] * 14)) + struct.pack("<320I", *table_words)) - return subprocess.run([renderer, backend, "--compute-store-case", cso, case], capture_output=True, text=True) + + references = [] + + def add(label, slot, **values): + path = directory / f"store_{len(references)}.case" + write_case(path, slot, **values) + references.append((path, label, None)) compile_shader(source) for slot, (label, _, _) in enumerate(cases): - result = run(slot) - if result.returncode == 77 and backend == "hardware": - return 77 - assert result.returncode == 0, (mode, label, result.stderr) - extra = 0 + add(f"slot {slot} {label}", slot) if mode == "d16_x": for label, payload, want in D16_X_PAYLOADS[1:]: - result = run(0, payload=payload, expected_x=want) - assert result.returncode == 0, (label, result.stderr) - extra += 1 + add(label, 0, payload=payload, expected_x=want) # A FLOAT4 format word must be refused just like UINT1 by store_heap_word_d16. wrong_float4 = list(table) wrong_float4[TABLE_BYTE // 4 + 3] = FLOAT4 - case = directory / "store.case" - case.write_bytes(struct.pack("<321I", 1, *([base.SENTINEL] * WORDS)) + struct.pack("<16I", 0, D16_X_PAYLOADS[0][1], *([0] * 14)) - + struct.pack("<320I", *wrong_float4)) - result = subprocess.run([renderer, backend, "--compute-store-case", cso, case], capture_output=True, text=True) - assert result.returncode == 0, ("wrong FLOAT4 format", result.stderr) - extra += 1 + add("wrong FLOAT4 format", 0, table_words=wrong_float4, written_offsets=()) if mode == "d16_xy": for payload, expected_y in ((0x80003c00, 0x80000000), (0x00013c00, 0x33800000), (0xc0003c00, 0xc0000000)): - result = run(0, payload=payload, expected_y=expected_y) - assert result.returncode == 0, (hex(payload), result.stderr) - extra += 1 + add(f"payload {payload:#x}", 0, payload=payload, expected_y=expected_y) elif mode == "d16_xyz": for payload, z in ((0x7e010001, 0x33800000), (0x3c008000, 0x80000000), (0x4200c000, 0xc0000000)): - result = run(0, payload=payload, expected_z=z) - assert result.returncode == 0, (hex(payload), result.stderr) - extra += 1 + add(f"payload {payload:#x}", 0, payload=payload, expected_z=z) mismatched_formats = {"d16_xy": (FLOAT4, base.aot.descriptor_format_word(62)), "d16_xyz": (FLOAT2, FLOAT4)} for wrong_format in mismatched_formats.get(mode, ()): wrong_view = table.copy() wrong_view[TABLE_BYTE // 4 + 5 * 8 + 3] = wrong_format - result = run(5, table_words=wrong_view) - assert result.returncode == 0, (hex(wrong_format), result.stderr) - extra += 1 + add(f"wrong format {wrong_format:#x}", 5, table_words=wrong_view) + if check_references(f"heap-store {mode}", renderer, backend, cso, references, allow_hardware_skip=True) == 77: + return 77 width_str = {"d16_x": "4u", "d16_xy": "8u", "d16_xyz": "12u"}.get(mode, "16u") format_guard = {"d16_x": f"{FLOAT1:#x}u", "d16_xy": f"{FLOAT2:#x}u", "d16_xyz": f"{FLOAT3:#x}u"}.get(mode, "formatWord") @@ -315,14 +308,16 @@ def run(slot, payload=default_payload, expected_x=D16_X, table_words=table, expe for old, new, slot, *first_mismatch in mutations: assert source.count(old) == 1, old compile_shader(source.replace(old, new)) - result = run(slot) + case = directory / "mutated.case" + write_case(case, slot) + result = subprocess.run([renderer, backend, "--compute-store-case", cso, case], capture_output=True, text=True) assert result.returncode == 1 and "Compute readback differs" in result.stderr, (old, result.stderr) if first_mismatch: words = [line for line in result.stderr.splitlines() if line.startswith("word=")] assert words[:1] == first_mismatch, (old, result.stderr) kind = {"uint4": "UINT4", "d16_xyzw": "D16-to-FLOAT4", "d16_x": "D16_X-to-FLOAT1", "d16_xy": "D16_XY-to-FLOAT2", "d16_xyz": "D16_XYZ-to-FLOAT3"}[mode] - print(f"{backend} {kind}: {len(cases) + extra} heap-store cases and {len(mutations)} shader mutations checked") + print(f"{backend} {kind}: {len(references)} heap-store cases and {len(mutations)} shader mutations checked") return 0 diff --git a/tests/compute_load_format_check.py b/tests/compute_load_format_check.py index 2539cc006..90ba550ee 100644 --- a/tests/compute_load_format_check.py +++ b/tests/compute_load_format_check.py @@ -312,10 +312,12 @@ def binary(directory, assembler, objcopy, library): return 0 -def check_references(name, renderer, backend, shader, cases): +def check_references(name, renderer, backend, shader, cases, *, allow_hardware_skip=False): paths = [path for path, _label, _diagnostic in cases] result = subprocess.run([renderer, backend, "--compute-store-batch", shader, *paths], capture_output=True, text=True) + if allow_hardware_skip and backend == "hardware" and result.returncode == 77: + return 77 statuses = [line for line in result.stdout.splitlines() if line.startswith("case=")] messages = re.split(r"(?=^case=\d+ path=)", result.stderr, flags=re.MULTILINE)[1:] summaries = [line for line in result.stdout.splitlines() if line.startswith("groups=")] @@ -337,6 +339,7 @@ def check_references(name, renderer, backend, shader, cases): if line.startswith("groups="): print(f"{name}: {next(labels)}") print(line) + return 0 def draw(directory, compiler, renderer, backend): From f40691e72230c3635352d72339d4a09ad5518a7f Mon Sep 17 00:00:00 2001 From: pigalot Date: Thu, 26 Nov 2026 00:46:21 +0000 Subject: [PATCH 037/240] runtime: create committed resources through device slot 76 (#2648) * runtime: create committed resources through device slot 76 Device slot 76 (Xbox order, +0x260) takes the seven arguments of desktop CreateCommittedResource (heap properties, heap flags, desc, initial state, clear value, riid, ppv); on main the wrapper trapped on it. A console package module creates its resources through it. The slot-127 body becomes create_committed(slot, ...): slot 127 calls it as before, slot 76 without a protected session or castable formats, so both share the per-heap initial state, clear-value retry and title memory. The log line names the slot. New fixture with a negative control: startup_committed_slot76_warp and _hardware (a render target with a clear value and default, upload and readback buffers); the control asks for a 2D texture on an upload heap. * Require exact rejection in the slot 76 control --------- Co-authored-by: Royoo <3230853833@qq.com> --- CMakeLists.txt | 11 +++ docs/startup-runtime.md | 14 +++ src/startup_stubs/d3d12_xs_device.cpp | 35 +++++-- tests/startup_committed_slot76_check.cpp | 116 +++++++++++++++++++++++ 4 files changed, 169 insertions(+), 7 deletions(-) create mode 100644 tests/startup_committed_slot76_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 6fd6646d2..3e130b0ea 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2113,6 +2113,17 @@ endforeach() add_test(NAME startup_committed_heap_state_upload_texture_control COMMAND startup_committed_heap_state_check warp --mutate upload-texture) set_tests_properties(startup_committed_heap_state_hardware PROPERTIES SKIP_RETURN_CODE 77) set_tests_properties(startup_committed_heap_state_upload_texture_control PROPERTIES WILL_FAIL TRUE) +# Device slot 76 (desktop CreateCommittedResource argument order) through the device wrapper: a render +# target with a clear value and buffers on the default, upload and readback heaps. The control asks for a +# 2D texture on an upload heap, which no runtime creates, and must FAIL. +add_executable(startup_committed_slot76_check tests/startup_committed_slot76_check.cpp) +target_compile_features(startup_committed_slot76_check PRIVATE cxx_std_17) +target_link_libraries(startup_committed_slot76_check PRIVATE d3d12_xs_shim d3d12 dxgi) +foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_committed_slot76_${adapter} COMMAND startup_committed_slot76_check ${adapter}) +endforeach() +set_tests_properties(startup_committed_slot76_hardware PROPERTIES SKIP_RETURN_CODE 77) +add_test(NAME startup_committed_slot76_control COMMAND startup_committed_slot76_check warp --control) # Opt-in BC7 4 KiB standard surfaces (src/startup_stubs/bc7_4k_s.h): accepted descriptions, padded # sizes, block order and detile; the mutated run (x-first bit order) is the negative control. add_executable(startup_bc7_4k_s_check tests/startup_bc7_4k_s_check.cpp) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index d2bf02406..f36bebf5e 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -2866,6 +2866,20 @@ freed slots are reused in address order so that pages reused together share a vi bytes from the queried page to the end of the view, not one page. A placed buffer on such memory is not affected: section-backed pages already took the committed, not-aliased path. +## Committed resources (device slot 76) + +Device slot 76 (Xbox order, +0x260) takes the seven arguments of desktop `CreateCommittedResource`: +heap properties, heap flags, desc, initial state, clear value, riid and ppv. Measured: a console +package module (an upscaler) creates its resources through it. The stand-in shares the +committed-resource path of slot 127 (the `CreateCommittedResource3` order, with protected session and +castable formats, which slot 76 does not pass): the same initial-state choice per heap, the same +clear-value retry and title memory, and a log line naming the slot. Run +`ctest --preset dev --no-tests=error -R '^startup_committed_slot76_(warp|control)$'` +(`tests/startup_committed_slot76_check.cpp`): a render target with a clear value and buffers on the +default, upload and readback heaps, passed with initial state 0xffffffff as a title passes them, must +be created and leave the device alive. The control asks for a 2D texture on an upload heap and must +return `E_INVALIDARG` with no resource and leave the device alive. The control also requires all four valid creations to pass. `startup_committed_slot76_hardware` runs the creation checks on a physical GPU. + - `ctest --preset release --no-tests=error -R '^xmem_shim_(mapped_pages|page_runs)$' -V` runs the earlier contract check and `tests/xmem_page_runs_check.py`: a batch across two sections with holes, moved and reused pages; `VirtualQuery` before and after a view is split; two views of diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 74b148149..8e70b95f9 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -5767,10 +5767,10 @@ HRESULT __stdcall device_create_derived_pipeline(Wrapper*, void* base, UINT coun // COMMON, GENERIC_READ on an upload heap and COPY_DEST on a readback heap (the initial states D3D12 // requires there; the Windows 10 runtime refuses COMMON with E_INVALIDARG). When desktop rejects the // clear value it is retried without one. -HRESULT __stdcall device_create_committed_x(Wrapper* self, const D3D12_HEAP_PROPERTIES* props, UINT heap_flags, - const D3D12_RESOURCE_DESC* desc, UINT state, const D3D12_CLEAR_VALUE* clear, - void* session, UINT castable_count, const void* castable, const GUID* iid, - void** out) +// Slot 76 shares the work with the slot number in the log line. +HRESULT create_committed(int slot, Wrapper* self, const D3D12_HEAP_PROPERTIES* props, UINT heap_flags, + const D3D12_RESOURCE_DESC* desc, UINT state, const D3D12_CLEAR_VALUE* clear, void* session, + UINT castable_count, const void* castable, const GUID* iid, void** out) { char text[48]; guid_text(iid, text, sizeof(text)); @@ -5779,7 +5779,7 @@ HRESULT __stdcall device_create_committed_x(Wrapper* self, const D3D12_HEAP_PROP const D3D12_RESOURCE_DESC copy = sanitized(*desc); const auto flags = static_cast(heap_flags); const D3D12_RESOURCE_ALLOCATION_INFO info = device_of(self)->GetResourceAllocationInfo(0, 1, ©); - check_device("Device before slot", 127); + check_device("Device before slot", slot); void* const title_memory = info.SizeInBytes != ~0ull ? title_resource_memory(info.SizeInBytes, info.Alignment) : nullptr; ID3D12Resource* resource = nullptr; const D3D12_RESOURCE_STATES initial = props->Type == D3D12_HEAP_TYPE_UPLOAD ? D3D12_RESOURCE_STATE_GENERIC_READ @@ -5797,8 +5797,9 @@ HRESULT __stdcall device_create_committed_x(Wrapper* self, const D3D12_HEAP_PROP } static LONG calls; if (first_calls(calls, 12)) - log("x2w-d3d12 Device::slot127(CreateCommittedResource3?) heap=%d flags=0x%x dim=%d %llux%u fmt=%d rflags=0x%x " - "state=0x%x clear=%p%s session=%p castable=%u/%p riid=%s -> 0x%08lx", props->Type, heap_flags, desc->Dimension, + log("x2w-d3d12 Device::slot%d(%s) heap=%d flags=0x%x dim=%d %llux%u fmt=%d rflags=0x%x " + "state=0x%x clear=%p%s session=%p castable=%u/%p riid=%s -> 0x%08lx", slot, + slot == 76 ? "CreateCommittedResource" : "CreateCommittedResource3?", props->Type, heap_flags, desc->Dimension, desc->Width, desc->Height, desc->Format, desc->Flags, state, static_cast(clear), clear && !cleared ? "(dropped)" : "", session, castable_count, castable, text, static_cast(hr)); if (FAILED(hr)) return hr; @@ -5812,6 +5813,25 @@ HRESULT __stdcall device_create_committed_x(Wrapper* self, const D3D12_HEAP_PROP return S_OK; } +HRESULT __stdcall device_create_committed_x(Wrapper* self, const D3D12_HEAP_PROPERTIES* props, UINT heap_flags, + const D3D12_RESOURCE_DESC* desc, UINT state, const D3D12_CLEAR_VALUE* clear, + void* session, UINT castable_count, const void* castable, const GUID* iid, + void** out) +{ + return create_committed(127, self, props, heap_flags, desc, state, clear, session, castable_count, castable, iid, out); +} + +// Device slot 76 (Xbox order, +0x260): the seven arguments of desktop CreateCommittedResource +// (heap properties, heap flags, desc, initial state, clear value, riid, ppv). Seen from a console +// package module (an upscaler) that a title loaded only on the Series S profile. Same desktop +// creation as slot 127 (tests/startup_committed_slot76_check.cpp). +HRESULT __stdcall device_create_committed(Wrapper* self, const D3D12_HEAP_PROPERTIES* props, UINT heap_flags, + const D3D12_RESOURCE_DESC* desc, UINT state, const D3D12_CLEAR_VALUE* clear, + const GUID* iid, void** out) +{ + return create_committed(76, self, props, heap_flags, desc, state, clear, nullptr, 0, nullptr, iid, out); +} + // Device slot 80 (Xbox order): (type, timeout, 0, flags, &token) -> HRESULT, the frame-event wait // that hands out a frame token (called with type 2 / timeout -1 and type 0 / timeout 0, flags 0/2). // Paces to the interval from slot 78 (33.3 ms by default) and returns increasing tokens. @@ -6266,6 +6286,7 @@ void build_tables() tables[device_kind][48] = reinterpret_cast(&device_create_command_queue_x); tables[device_kind][70] = reinterpret_cast(&device_memory_srv); tables[device_kind][73] = reinterpret_cast(&device_create_command_list_x); + tables[device_kind][76] = reinterpret_cast(&device_create_committed); tables[device_kind][78] = reinterpret_cast(&device_frame_interval); tables[device_kind][79] = reinterpret_cast(&device_frame_event); tables[device_kind][80] = reinterpret_cast(&device_wait_frame_event); diff --git a/tests/startup_committed_slot76_check.cpp b/tests/startup_committed_slot76_check.cpp new file mode 100644 index 000000000..284d472b2 --- /dev/null +++ b/tests/startup_committed_slot76_check.cpp @@ -0,0 +1,116 @@ +// Device check for committed resources made through the startup device wrapper's slot 76 (Xbox +// order, +0x260): the seven arguments of desktop CreateCommittedResource (heap properties, heap +// flags, desc, initial state, clear value, riid, ppv). It shares the desktop creation of slot 127 +// (tests/startup_committed_heap_state_check.cpp). A 2D render target with a clear value and buffers on +// the default, upload and readback heaps, passed as a title passes them (initial state 0xffffffff), +// must all be created and the device must stay alive. +// usage: startup_committed_slot76_check warp|hardware [--control] +// --control also requires a 2D upload-heap texture to return E_INVALIDARG with no output resource. +#include "xmem_test_device.h" + +#include +#include + +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); + +namespace { +HRESULT create_wrapper(IUnknown* adapter, REFIID iid, void** out) +{ + unsigned char parameters[64]{}; + return D3D12XboxCreateDevice(adapter, parameters, iid, out); +} + +using Committed76 = HRESULT (*)(void*, const D3D12_HEAP_PROPERTIES*, UINT, const D3D12_RESOURCE_DESC*, UINT, + const D3D12_CLEAR_VALUE*, const GUID*, void**); +constexpr UINT state_undefined = 0xffffffff; + +Committed76 slot76(ID3D12Device* device) +{ + return reinterpret_cast((*reinterpret_cast(device))[76]); +} + +D3D12_RESOURCE_DESC buffer(UINT64 bytes) +{ + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = bytes; + desc.Height = 1; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + return desc; +} + +D3D12_RESOURCE_DESC texture(UINT width, UINT height, D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) +{ + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = width; + desc.Height = height; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + desc.SampleDesc.Count = 1; + desc.Flags = flags; + return desc; +} + +const char* heap_name(D3D12_HEAP_TYPE type) +{ + return type == D3D12_HEAP_TYPE_DEFAULT ? "default" : type == D3D12_HEAP_TYPE_UPLOAD ? "upload" : "readback"; +} + +// Returns 0 only when the requested creation or rejection is observed and the device stays alive. +int check(ID3D12Device* wrapper, D3D12_HEAP_TYPE type, const D3D12_RESOURCE_DESC& desc, + const D3D12_CLEAR_VALUE* clear = nullptr, bool reject = false) +{ + const D3D12_HEAP_PROPERTIES props{type}; + const GUID iid = __uuidof(ID3D12Resource); + void* created = nullptr; + const HRESULT hr = slot76(wrapper)(wrapper, &props, 0, &desc, state_undefined, clear, &iid, &created); + const HRESULT removed = wrapper->GetDeviceRemovedReason(); + const char* what = desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER ? "buffer" : "2D texture"; + std::printf("%s heap, %s of 0x%llx%s: slot 76 -> 0x%08lx\n", heap_name(type), what, + static_cast(desc.Width), clear ? " with clear value" : "", static_cast(hr)); + const bool expected = reject ? hr == E_INVALIDARG && !created : SUCCEEDED(hr) && created; + const int result = expected && SUCCEEDED(removed) ? 0 : 1; + if (reject && !result) std::puts("slot 76 rejected the upload-heap texture with E_INVALIDARG and no resource"); + if (result) + std::printf("FAIL: %s heap %s: hr 0x%08lx object %p device 0x%08lx\n", heap_name(type), what, static_cast(hr), + created, static_cast(removed)); + if (created) static_cast(created)->Release(); + return result; +} +} // namespace + +int main(int argc, char** argv) +{ + if (argc != 2 && !(argc == 3 && std::strcmp(argv[2], "--control") == 0)) return 1; + const bool warp = std::strcmp(argv[1], "warp") == 0; + const bool control = argc == 3; + bool unmatched = false; + SetEnvironmentVariableW(L"X2W_D3D12_PERMISSIVE", L"1"); + auto wrapper = create_device(warp, unmatched, create_wrapper); + if (!wrapper) { + if (warp || unmatched) { + std::puts("FAIL: no wrapped device"); + return 1; + } + return 77; + } + int failures = 0; + D3D12_CLEAR_VALUE clear{}; + clear.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + failures += check(wrapper.Get(), D3D12_HEAP_TYPE_DEFAULT, texture(128, 64, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET), &clear); + failures += check(wrapper.Get(), D3D12_HEAP_TYPE_DEFAULT, buffer(0x10000)); + failures += check(wrapper.Get(), D3D12_HEAP_TYPE_UPLOAD, buffer(0x10000)); + failures += check(wrapper.Get(), D3D12_HEAP_TYPE_READBACK, buffer(768)); + if (control) failures += check(wrapper.Get(), D3D12_HEAP_TYPE_UPLOAD, texture(64, 64), nullptr, true); + if (failures) { + std::printf("startup_committed_slot76: FAIL (%d)\n", failures); + return 1; + } + std::puts("startup_committed_slot76: PASS (render target, default, upload and readback resources created through slot 76)"); + return 0; +} From 5aac1ed4af598e16596765b6b5925cdcaa998732 Mon Sep 17 00:00:00 2001 From: triggered02 <153171514+triggered02@users.noreply.github.com> Date: Thu, 26 Nov 2026 06:25:25 +0530 Subject: [PATCH 038/240] startup: lower abs (|src| and -|src|) on v_cndmask_b32_e64 sources (#2439) Co-authored-by: Royoo <3230853833@qq.com> --- CMakeLists.txt | 11 + docs/experiments.md | 20 + tests/startup_gfx2hlsl_cndmask_abs_check.py | 398 ++++++++++++++++++++ tests/startup_gfx2hlsl_cndmask_neg_check.py | 13 +- tools/startup/gfx2hlsl.py | 18 +- 5 files changed, 446 insertions(+), 14 deletions(-) create mode 100644 tests/startup_gfx2hlsl_cndmask_abs_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 3e130b0ea..f7b690009 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3694,6 +3694,17 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_gfx2hlsl_bit_alu_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl abs (`|src|` and `-|src|`) on v_cndmask_b32_e64 data sources: CPU evaluation of the translated + # text over 32-bit bit patterns, then a desktop draw of the translated pair (FXC ps_5_1 and DXC ps_6_0) + # with order-reversed and abs-dropped mutation controls. + add_test(NAME startup_gfx2hlsl_cndmask_abs_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_cndmask_abs_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_cndmask_abs_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_cndmask_abs_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_cndmask_abs_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl v_cube{id,sc,tc,ma}_f32: the source-built cube directions are drawn and compared with the # LLVM ConstantFoldAMDGCNCubeIntrinsic model; swapped id/sc, tie-order and cubema-factor controls must fail. foreach(adapter IN ITEMS warp hardware) diff --git a/docs/experiments.md b/docs/experiments.md index f7ddc0803..1b51213f0 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15948,6 +15948,26 @@ Building on #2443 (Slice 1), `X2W_D3D12_RELEASE_RETIRED=1` extends desktop objec ctest --preset dev --no-tests=error -R '^startup_resource_(retire|budget)' -V ``` +## Source `abs` modifiers (`|src|` and `-|src|`) on `v_cndmask_b32_e64` in the startup translator + +`Stage.u_src` in [`tools/startup/gfx2hlsl.py`](../tools/startup/gfx2hlsl.py#L1506-L1521) now strips `|...|` after `split_neg(tok)` for `v_cndmask_b32_e64` data sources (`src0` and `src1`, both VGPRs and SGPRs), clearing the `off_diag.py` refusal `operand '|v0|' at v_cndmask_b32_e64 v0, v0, |v0|, s30`. Per the RDNA2 VOP3A source-modifier order, `abs` clears bit 31 (`& 0x7fffffffu`) first and `neg` flips bit 31 (`^ 0x80000000u`) second: + +- `|src|` emits `(src & 0x7fffffffu)` +- `-|src|` (and `neg(|src|)`) emits `((src & 0x7fffffffu) ^ 0x80000000u)` (forces bit 31 to `1`) +- `-src` keeps `(src ^ 0x80000000u)` + +`check_encoding()` still refuses `ABS` on inline or literal immediates (`v_cndmask_b32_e64 ABS on an immediate`), `Stage.u()` still refuses `|vN|` when `vN` is in `low16_only_v` (whole-word 32-bit read), `op_v_cndmask_b32` still refuses `abs`/`neg` on the mask operand (`src2`), `v_cndmask_b32` stays out of `UNIFORM_VALU`, and other integer instructions keep using `Stage.u()` so unexpected `|...|` modifiers remain refused. + +```powershell +out\pe-env\Scripts\python.exe -B tests\startup_gfx2hlsl_cndmask_abs_check.py +out\pe-env\Scripts\python.exe -B tests\startup_gfx2hlsl_cndmask_abs_check.py draw dxc.exe out\build\dev\offscreen_check.exe warp fxc.exe +ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_cndmask_abs_(controls|warp|hardware)$' -V +``` + +### Measured results and open scope + +[`tests/startup_gfx2hlsl_cndmask_abs_check.py`](../tests/startup_gfx2hlsl_cndmask_abs_check.py) decodes synthetic VOP3A bytes with `G.decode()` (no game data) covering `v_cndmask_b32_e64 v0, v0, |v0|, s30`, `|v0|` / `-|v0|` on `src0` and `src1`, SGPR `|s4|` / `-|s4|`, `neg(|v0|)`, and 17 refusal controls, then evaluates the emitted HLSL across 11 32-bit patterns (`+0.0`, `-0.0`, `+1.0`, `-1.0`, `+qNaN`, `-qNaN`, `+inf`, `-inf`, `-denormal`, `0x12345678`, `0x92345678`) under both mask states (`22/22` exact matches; both order-reversed and `abs`-dropped mutations mismatch on `22/22` cases). On WARP (`Microsoft Basic Render Driver` `1414:008c`, driver `10.0.26100.9818`, `debug_layer=unavailable`) with FXC (`ps_5_1`) and DXC (`ps_6_0`), all 44 positive draws (22 FXC + 22 DXC) matched bit-for-bit and all 8 mutated draws (4 reverse-order + 4 drop-abs) failed with their expected wrong words. Physical GPU (`startup_gfx2hlsl_cndmask_abs_hardware`) and title shader execution remain unverified here. + ## Binary16 SDWA arithmetic, rounding, scaling and conversions in pixel_aot [The pixel shader translator](../tools/pixel_aot.py) adds 14 contracted binary16 `SDWA` forms (counted in both `docs/coverage/gfx1013.tsv` and `docs/coverage/rdna2.tsv`): diff --git a/tests/startup_gfx2hlsl_cndmask_abs_check.py b/tests/startup_gfx2hlsl_cndmask_abs_check.py new file mode 100644 index 000000000..4d4b31002 --- /dev/null +++ b/tests/startup_gfx2hlsl_cndmask_abs_check.py @@ -0,0 +1,398 @@ +"""Absolute-value (`|src|` and `-|src|`) modifiers on `v_cndmask_b32_e64` in tools/startup/gfx2hlsl.py. + + (no arguments) translation controls, pure Python + draw [fxc] + compile the translated pair with FXC ps_5_1 when given and with DXC ps_6_0, + draw one pixel per input set and compare the four exported words + +Per RDNA2 ISA VOP3A, `abs` clears bit 31 (`& 0x7fffffffu`) FIRST and `neg` flips bit 31 (`^ 0x80000000u`) +SECOND, so `-|x|` forces bit 31 to 1 (`((x & 0x7fffffffu) ^ 0x80000000u)`), whereas `-x` flips bit 31. +All instruction bytes are **constructed here** from the RDNA2 field layout decoded by `G.decode()` (no game data): + VOP3A w0: [31:26] = 0b110101, [25:16] opcode (VOP2 e64 = 0x100 + op, VOPC e64 = op), + [15] clamp, [10:8] abs for src2..src0, [7:0] vdst + w1: [8:0] src0, [17:9] src1, [26:18] src2, [28:27] omod, [31:29] neg for src2..src0 +""" +import re +import struct +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import VS_WORDS, compile_hlsl, draw # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import Expr, mov_literal # noqa: E402 + +MASK = 0xffffffff +SIGN_BIT = 0x80000000 +MAG_MASK = 0x7fffffff + +VOP2_E64_BASE = 0x100 +CNDMASK = 0x01 +AND_B32 = 0x1b +V_CMP_NE_U32 = 0xc5 + +# RDNA2 9-bit VOP3 source encoding: 0..105 = s0..s105, 256..511 = v0..v255. +S4 = 4 +S8 = 8 +V0 = 256 + 0 +V1 = 256 + 1 +V2 = 256 + 2 +V30 = 256 + 30 + +# 32-bit bit patterns covering signed zero, normal floats, qNaNs, infinities, negative denormal, and bit payloads. +PATTERNS = ( + 0x00000000, # +0.0 + 0x80000000, # -0.0 + 0x3f800000, # +1.0 + 0xbf800000, # -1.0 + 0x7fc00001, # +qNaN + 0xffc00001, # -qNaN + 0x7f800000, # +inf + 0xff800000, # -inf + 0x80000001, # -denormal + 0x12345678, # +arbitrary + 0x92345678, # -arbitrary +) + + +def encode_vop3a(opcode, vdst, src0, src1, src2=0, *, + neg0=0, neg1=0, neg2=0, abs0=0, abs1=0, abs2=0, clamp=0, omod=0): + """Encode a VOP3A instruction (VOP2 e64 or VOPC e64).""" + w0 = ((0b110101 << 26) | ((opcode & 0x3ff) << 16) | ((clamp & 1) << 15) + | ((abs2 & 1) << 10) | ((abs1 & 1) << 9) | ((abs0 & 1) << 8) | (vdst & 0xff)) + w1 = ((src0 & 0x1ff) | ((src1 & 0x1ff) << 9) | ((src2 & 0x1ff) << 18) | ((omod & 0x3) << 27) + | ((neg0 & 1) << 29) | ((neg1 & 1) << 30) | ((neg2 & 1) << 31)) + return struct.pack(' `((reg ^ 0x80000000u) & 0x7fffffffu)` (wrong neg-then-abs).""" + mutated = re.sub(r'\(\((\w+) & 0x7fffffffu\) \^ 0x80000000u\)', + r'((\1 ^ 0x80000000u) & 0x7fffffffu)', hlsl_text) + assert mutated != hlsl_text + return mutated + + +def mutate_drop_abs(hlsl_text): + r"""Mutate `(\w+ & 0x7fffffffu)` -> `\1` (drops abs from both `|x|` and `-|x|`).""" + mutated = re.sub(r'\((\w+) & 0x7fffffffu\)', r'\1', hlsl_text) + assert mutated != hlsl_text + return mutated + + +def reverse_order_outputs(x_word, y_word, mask_bit): + v12 = isa_abs(x_word) if mask_bit else x_word + v13 = wrong_neg_before_abs(x_word) if mask_bit else isa_abs(x_word) + v14 = isa_neg(y_word) if mask_bit else wrong_neg_before_abs(y_word) + v15 = wrong_neg_before_abs(S4_SEED) if mask_bit else isa_abs(S4_SEED) + return (v12, v13, v14, v15) + + +def drop_abs_outputs(x_word, y_word, mask_bit): + v12 = x_word + v13 = isa_neg(x_word) if mask_bit else x_word + v14 = isa_neg(y_word) + v15 = isa_neg(S4_SEED) if mask_bit else S4_SEED + return (v12, v13, v14, v15) + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH'}") + if not condition: + raise AssertionError(f"{label}: {detail}" if detail else label) + + +def check_controls(): + # 1. Exact off_diag.py shape: v_cndmask_b32_e64 v0, v0, |v0|, s30. + asm, emitted = translate_code(encode_vop2_e64(CNDMASK, 0, V0, V0, 30, abs1=1)) + check('decodes exact off_diag shape', + asm == ['v_cndmask_b32_e64 v0, v0, |v0|, s30'], repr(asm)) + check('lowers |v0| on src1 with s30 mask', + emitted == 'v0 = (s30 & 1) ? (v0 & 0x7fffffffu) : v0;', emitted) + + # 2. |v0| and -|v0| on src0 and src1, and mixed combinations. + asm, emitted = translate_code(encode_vop2_e64(CNDMASK, 0, V0, V1, 30, abs0=1)) + check('|v0| on src0', + asm == ['v_cndmask_b32_e64 v0, |v0|, v1, s30'] + and emitted == 'v0 = (s30 & 1) ? v1 : (v0 & 0x7fffffffu);', emitted) + + asm, emitted = translate_code(encode_vop2_e64(CNDMASK, 0, V0, V1, 30, abs0=1, neg0=1)) + check('-|v0| on src0 applies abs before neg', + asm == ['v_cndmask_b32_e64 v0, -|v0|, v1, s30'] + and emitted == 'v0 = (s30 & 1) ? v1 : ((v0 & 0x7fffffffu) ^ 0x80000000u);', emitted) + + asm, emitted = translate_code(encode_vop2_e64(CNDMASK, 0, V0, V1, 30, abs1=1, neg1=1)) + check('-|v1| on src1 applies abs before neg', + asm == ['v_cndmask_b32_e64 v0, v0, -|v1|, s30'] + and emitted == 'v0 = (s30 & 1) ? ((v1 & 0x7fffffffu) ^ 0x80000000u) : v0;', emitted) + + asm, emitted = translate_code(encode_vop2_e64(CNDMASK, 0, V0, V1, 30, abs0=1, neg0=1, abs1=1)) + check('-|v0| on src0 and |v1| on src1 together', + asm == ['v_cndmask_b32_e64 v0, -|v0|, |v1|, s30'] + and emitted == 'v0 = (s30 & 1) ? (v1 & 0x7fffffffu) : ((v0 & 0x7fffffffu) ^ 0x80000000u);', emitted) + + # 3. SGPR |s4| and -|s4|. + asm, emitted = translate_code(encode_vop2_e64(CNDMASK, 0, S4, S4, 30, abs0=1, abs1=1, neg1=1)) + check('|s4| and -|s4| on SGPR sources', + asm == ['v_cndmask_b32_e64 v0, |s4|, -|s4|, s30'] + and emitted == 'v0 = (s30 & 1) ? ((s4 & 0x7fffffffu) ^ 0x80000000u) : (s4 & 0x7fffffffu);', emitted) + + # 4. Existing -v30 behavior unchanged, and neg(|v0|) spelling also lowers identically. + asm, emitted = translate_code(encode_vop2_e64(CNDMASK, 31, V30, V30, 0, neg1=1)) + check('-v30 keeps existing bit-31 flip', + emitted == 'v31 = (s0 & 1) ? (v30 ^ 0x80000000u) : v30;', emitted) + s_neg_paren = Stage() + s_neg_paren.one('v_cndmask_b32_e64', 'v_cndmask_b32_e64 v0, v0, neg(|v0|), s30') + check('neg(|v0|) spelling applies abs before neg', + ' '.join(s_neg_paren.lines) == 'v0 = (s30 & 1) ? ((v0 & 0x7fffffffu) ^ 0x80000000u) : v0;') + + # 5. Refusals preserved: ABS on immediates, ABS/NEG on mask, ABS on other integer ops, low16_only_v. + literal = struct.pack(' Date: Thu, 26 Nov 2026 02:02:03 +0100 Subject: [PATCH 039/240] startup: handle vertex fetch with invalid input layout in gfx2hlsl (Part of #1723) (#2002) * startup: translate a stream vertex fetch whose pipeline declares an empty input layout A stream vertex shader that calls the fetch routine was refused whenever the pipeline had no input layout elements. A layout declared with zero elements is now published as 'ia1 0'; the translator reads each fetched register as zero instead of refusing. A stream without a readable layout is still refused. * docs: describe the empty input layout request (ia1 0) and its zero default * test: draw readback for an empty declared input layout * fix: gate zero-element input layout zero-fill behind X2W_STREAM_ZERO_FILL opt-in --- docs/startup-runtime.md | 6 ++++- src/startup_stubs/d3d12_draw.inl | 8 +++++- tests/startup_stream_fetch_check.py | 38 +++++++++++++++++++++++++++-- tests/startup_stream_setup.cpp | 5 +++- tools/startup/gfx2hlsl.py | 13 +++++++++- 5 files changed, 64 insertions(+), 6 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index f36bebf5e..09800fd3d 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -118,7 +118,11 @@ the registers the routine loaded. The routine's code is not in the shader contai The stand-in reads the `INPUT_LAYOUT` subobject and publishes it next to the request as `req_.ia`, before `.a`. The file holds `ia1 ` and then one line per element: semantic, index, format, slot, offset, class -and step rate. A stream with a non-empty layout includes that text in its cache key; other keys are unchanged. +and step rate. A stream with a non-empty layout includes that text in its cache key; other keys are unchanged. A layout declared +with zero elements publishes nothing by default, so the fetch is refused and not drawn, like an absent or unreadable +layout. With the experimental opt-in `X2W_STREAM_ZERO_FILL=1` it is published as the single line `ia1 0`, and the +translation reads every fetched register as zero. That zero value is an assumption, not a measurement: no independent +reference shows what a fetched input holds for a zero-element layout, so no startup claim rests on it. One log line per stream gives the element count and, for each element, format, slot, offset and class: `x2w-draw stream input layout: 2 elements (format/slot/offset/class) 6/0/0/0 6/0/4294967295/0`. diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index b81819f68..209c82255 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -451,7 +451,13 @@ bool stream_input_layout(const unsigned char* subobject, std::string& text) { D3D12_INPUT_LAYOUT_DESC layout; std::memcpy(&layout, subobject + 8, sizeof(layout)); - if (!layout.NumElements) return true; + if (!layout.NumElements) { + // Declared without elements. The value of a fetched input here is unverified, so the zero-fill translation + // is an experimental opt-in (X2W_STREAM_ZERO_FILL=1); by default nothing is published and the fetch is refused. + const char* zero_fill = std::getenv("X2W_STREAM_ZERO_FILL"); + if (zero_fill && zero_fill[0] == '1') text = "ia1 0\n"; + return true; + } if (layout.NumElements > D3D12_IA_VERTEX_INPUT_STRUCTURE_ELEMENT_COUNT || !x2w_local::readable(layout.pInputElementDescs, sizeof(D3D12_INPUT_ELEMENT_DESC) * layout.NumElements)) return false; text = "ia1 " + std::to_string(layout.NumElements) + "\n"; diff --git a/tests/startup_stream_fetch_check.py b/tests/startup_stream_fetch_check.py index 94fc6499f..c7b253041 100644 --- a/tests/startup_stream_fetch_check.py +++ b/tests/startup_stream_fetch_check.py @@ -101,7 +101,7 @@ def first_difference(actual, want): class Run: - def __init__(self, directory, consumer, backend, vs_bytes, layout): + def __init__(self, directory, consumer, backend, vs_bytes, layout, zero_fill=False): self.cache = directory / "cache" self.cache.mkdir(parents=True) self.vs, ps, self.root, self.output = (directory / name for name in ("vs", "ps", "root", "pixels")) @@ -112,8 +112,11 @@ def __init__(self, directory, consumer, backend, vs_bytes, layout): self.env = dict(os.environ, X2W_D3D12_PERMISSIVE="1", X2W_D3D12_LIST_NOOP="1", X2W_D3D12_RENDER="1", X2W_SHADER_CACHE=str(self.cache), X2W_TEST_VERTEX_FETCH="1") self.env.setdefault("X2W_D3D12_DEBUG", "0") + self.env.pop("X2W_STREAM_ZERO_FILL", None) + if zero_fill: + self.env["X2W_STREAM_ZERO_FILL"] = "1" if layout: - self.env["X2W_TEST_INPUT_LAYOUT"] = "1" + self.env["X2W_TEST_INPUT_LAYOUT"] = layout if isinstance(layout, str) else "1" else: self.env.pop("X2W_TEST_INPUT_LAYOUT", None) subprocess.run(self.args, env=self.env, check=True) @@ -191,6 +194,29 @@ def patched(*args): if "-> drawn;" in result.stderr: raise AssertionError("a vertex shader with a fetch call and no layout was drawn") print(f"{backend} no layout: refused and not drawn") + + # empty layout, production default: declared with no elements, nothing is published and the fetch is refused. + refused = Run(directory / "empty_default", consumer, backend, vertex(), "empty") + assert not list(refused.cache.glob("req_*.ia")), "an empty layout was published without the opt-in" + result = refused.draw() + if "-> drawn;" in result.stderr: + raise AssertionError("an empty declared layout was drawn without X2W_STREAM_ZERO_FILL") + print(f"{backend} empty layout, default: refused and not drawn") + + # empty layout, experimental opt-in X2W_STREAM_ZERO_FILL=1: every fetched input reads zero (an assumption, not a + # measurement); the vertices collapse and nothing but the blue clear reaches the readback. + empty = Run(directory / "empty", consumer, backend, vertex(), "empty", zero_fill=True) + layout = (empty.cache / ("req_%016x.ia" % empty.key)).read_bytes() + assert layout == b"ia1 0\n", layout + status = gfx2hlsl.translate_request(str(empty.cache), empty.key) + assert status == "ok", status + result = empty.draw() + if result.returncode or "-> drawn;" not in result.stderr: + raise RuntimeError(f"empty layout draw failed on {backend}: {result.returncode}\n{result.stderr}") + difference = first_difference(empty.output.read_bytes(), expected(lambda x, y: False)) + if difference: + raise AssertionError(f"empty layout: {difference}") + print(f"{backend} empty layout: zero-fed vertices draw nothing, all {WIDTH * HEIGHT} pixels exact") return 0 @@ -252,6 +278,14 @@ def translate_cases(directory): for line in ("w = ldu(r0, a);", "v4 = w & 255u;", "v5 = (w >> 8) & 255u;", "v6 = (w >> 16) & 255u;"): assert " %s\n" % line in vs, line + "\n" + vs + # A layout declared with no elements translates: no vertex-buffer load, every fetched register reads zero. + status, vs, manifest = translate(directory / "empty_layout", vertex(), "ia1 0\n") + assert status == "ok", status + for line in ("v4 = 0u;", "v6 = 0u;", "v8 = 0u;", "v10 = 0u;"): + assert " %s\n" % line in vs, line + "\n" + vs + assert "r0.Load(" not in vs and "buf vb" not in manifest, vs + manifest + print("translate: an empty declared layout reads every fetched input as zero") + # Refused: no layout; a register nothing defines; the only write masked off by exec, or bypassed by a branch. for label, words, layout, want in ( ("no layout", None, None, NO_LAYOUT), diff --git a/tests/startup_stream_setup.cpp b/tests/startup_stream_setup.cpp index b031a9eca..0ae81cfa5 100644 --- a/tests/startup_stream_setup.cpp +++ b/tests/startup_stream_setup.cpp @@ -188,7 +188,10 @@ int prepare_stream_pipeline(const char* vs_path, const char* ps_path, const char &stream_alternate_root))) return 7; } - LayoutStream with_layout{{D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT, {layout_elements, 2}}, + wchar_t layout_mode[8] = L""; + GetEnvironmentVariableW(L"X2W_TEST_INPUT_LAYOUT", layout_mode, 8); + const bool empty_layout = std::wcscmp(layout_mode, L"empty") == 0; // declared layout with zero elements + LayoutStream with_layout{{D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT, {layout_elements, empty_layout ? 0u : 2u}}, {{D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, {ps.data(), ps.size()}}, {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root}, {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, {vs.data(), vs.size()}}}}; diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index be0ae6b79..ce212659d 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -262,7 +262,8 @@ def starts_with_fetch_call(code): def parse_input_layout(text): """'ia1 ' then one ' ' line per element.""" lines = text.split('\n') - if not re.fullmatch(r'ia1 ([1-9]|[12][0-9]|3[0-2])', lines[0]) or lines[-1] != '' or len(lines) != int(lines[0][4:]) + 2: + # 'ia1 0' is a layout the pipeline declares with no elements: no fetched input has a source. + if not re.fullmatch(r'ia1 (0|[1-9]|[12][0-9]|3[0-2])', lines[0]) or lines[-1] != '' or len(lines) != int(lines[0][4:]) + 2: raise Unsupported('invalid input layout request') elements, ends = [], {} for line in lines[1:-1]: @@ -314,6 +315,12 @@ def stream_fetch(vs_container, layout_text): if register not in inputs: raise Unsupported('vertex fetch record for input register %d outside the signature' % register) name, index, _ = inputs[register] + if not layout: + # Declared layout without elements: the input has no vertex buffer; its registers read as zero + # (shortcut: the zero default is an assumption, not a measurement). + fetch.append(dict(vgpr=vgpr, count=count, empty=True)) + at += 5 + continue match = [e for e in layout if (e['name'], e['index']) == (name, index)] if len(match) != 1: raise Unsupported('input layout has %d elements for vertex input register %d' % (len(match), register)) @@ -4675,6 +4682,10 @@ def op_s_swappc_b64(self, ops, mods): raise Unsupported('vertex stage calls a fetch routine and the pipeline declares no input layout') base = self.pipe.ud(('basevertex',)) for e in self.pipe.vs_fetch: + if e.get('empty'): + for i in range(e['count']): + self.set_v(e['vgpr'] + i, '0u') + continue key = (('vbtab',), 16 * e['slot']) buf = self.pipe.resource(key, 'buf') stride = self.pipe.ud(('stride', self.pipe.resources[key]['index'])) From fbe249f680f0f67600cf17b3a87b04799c6fbe53 Mon Sep 17 00:00:00 2001 From: yjs <1245206726@qq.com> Date: Thu, 26 Nov 2026 09:02:18 +0800 Subject: [PATCH 040/240] shader: lower gfx1030 comparison sample LOD and bias (#1568) --- .github/workflows/windows.yml | 1 + CMakeLists.txt | 8 ++ README.md | 1 + docs/experiments.md | 42 +++++++ tests/desktop_gpu.h | 2 +- tests/offscreen_check.cpp | 31 +++++ tests/pixel_compare_lod_check.py | 203 +++++++++++++++++++++++++++++++ tests/pixel_compare_render.cpp | 43 +++++-- tools/pixel_aot.py | 35 ++++-- 9 files changed, 344 insertions(+), 22 deletions(-) create mode 100644 tests/pixel_compare_lod_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index a835e9c03..cd22a2a6c 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -65,6 +65,7 @@ jobs: (["tests/spirv_window/check.py"], {}), (["tests/spirv_window/compare_sampler.py", *SPIRV], {}), (["tests/pixel_sample_offset_check.py", *COMMON_LLVM], {}), + (["tests/pixel_compare_lod_check.py", *COMMON_LLVM], {}), (["tests/pixel_compare_sample_check.py", *COMMON_LLVM], {}), (["tests/pixel_compare_check.py", *COMMON_LLVM], {}), (["tests/pixel_attribute_sampled_check.py", *COMMON_LLVM], {}), diff --git a/CMakeLists.txt b/CMakeLists.txt index f7b690009..2ef17d51b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -10253,6 +10253,14 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(pixel_aot_pack_b32_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_pack_b32_${adapter}.txt") + foreach(mode IN ITEMS level bias) + set(test_name pixel_aot_compare_lod_${mode}_${adapter}) + add_test(NAME ${test_name} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/pixel_compare_lod_check.py" draw "${mode}" "${DXC_EXECUTABLE}" + "$" "${adapter}") + set_tests_properties(${test_name} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/${test_name}.txt") + endforeach() add_test(NAME pixel_aot_compare_sample_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/pixel_compare_sample_check.py" draw "${DXC_EXECUTABLE}" "$" "${adapter}") diff --git a/README.md b/README.md index 39a74b438..a82343fc1 100644 --- a/README.md +++ b/README.md @@ -172,6 +172,7 @@ The control-flow CPU translator supports [source-built string memory transfers]( | Heap-view buffer loads | Lower [gfx1013 indexed `buffer_load_format_xy/xyzw` from a run-time view record](docs/experiments.md#heap-view-buffer-loads): base, stride, `num_records` and format come from the record at a chosen slot. An index past `num_records` reads zero; a view that is not live, a bad slot or a bad format leaves the output unwritten. The record table is a side table inside t0; the SM 6.6 heap lookup is not wired yet. | `ctest --preset dev --no-tests=error -R '^compute_(store_aot_heap_view_load_\|heap_view_controls$)'` | | Descriptor-format buffer stores | Lower [indexed `buffer_store_format_x/xy/xyz/xyzw` and the d16 forms](docs/experiments.md#descriptor-format-buffer-stores), reading the GFX10 or legacy format from V# word 3. Unknown formats are refused. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_descriptor_store_format_'` | | gfx1030 depth-comparison sampling | Lower [2D comparison samples with and without offsets](docs/experiments.md#gfx1030-2d-comparison-sampling). | `ctest --preset dev --no-tests=error -R '^pixel_aot_compare_sample_' -V` | +| gfx1030 comparison sample LOD and bias | Lower [2D comparison samples with explicit LOD or instruction bias](docs/experiments.md#gfx1030-2d-comparison-sample-lod-and-bias) for two point-filtered mips, with optional signed offsets. | `ctest --preset dev --no-tests=error -j 1 -R '^pixel_aot_compare_lod_' -V` | | gfx1030 pixel sampling offsets | Lower [four 2D sample offset forms](docs/experiments.md#offline-pixel-shader-recompilation) with a known packed XY displacement. | `ctest --preset dev --no-tests=error -R '^pixel_aot_sample_offset_' -V` | | gfx1030 coarse-gradient pixel sampling | Lower [four 2D coarse-gradient forms](docs/experiments.md#gfx1030-2d-explicit-and-coarse-gradient-sampling) with statically known finite slopes. | `ctest --preset dev --no-tests=error -R '^pixel_aot_sample_coarse_gradient_' -V` | | gfx1030 explicit-gradient pixel sampling | Lower [four 2D gradient sample forms](docs/experiments.md#offline-pixel-shader-recompilation), including packed binary16 slopes and immediate offsets. | `ctest --preset dev --no-tests=error -R '^pixel_aot_sample_gradient_' -V` | diff --git a/docs/experiments.md b/docs/experiments.md index 1b51213f0..009153b30 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -8722,6 +8722,48 @@ python3 -B tests/pixel_compare_sample_check.py binary llvm-mc-15 llvm-objcopy-15 ctest --preset dev --no-tests=error -R '^pixel_aot_compare_sample_(warp|hardware)$' -V ``` +### gfx1030 2D comparison sample LOD and bias + +`image_sample_c_l` and `image_sample_c_l_o` lower to `SampleCmpLevel`. +`image_sample_c_b` and `image_sample_c_b_o` lower to `SampleCmpBias`. +The forms accept a contiguous sequence of full-width address VGPRs with an +optional packed XY offset, an instruction bias for `_b`, the reference, U and V, +and an explicit LOD for `_l`. Bias and LOD each accept binary32 `+0.0` and `1.0` +when known statically. The bias forms require whole-quad UVs. The matching +comparison sampler uses point XY and mip filtering, clamp-to-edge addressing, +`MIN_LOD = 0`, `MAX_LOD = 1`, and no sampler LOD bias. Bind a 2D R32_FLOAT view +with both mips visible and a desktop comparison sampler with the same LOD range. +The forms use `dmask:0x1` and the existing reference range, offset and wait rules. + +The synthetic fixture uses different depth patterns in its 8×8 and 4×4 mips. +It draws at 8×8 and 16×16 with a mip-zero footprint of one texel per pixel, so +explicit LOD 1 and instruction bias +1 each select the second mip. A CPU model +predicts all RGBA values, including where the signed offset `(1, -2)` clamps to +an edge. Zeroing the LOD or bias selects mip zero. Zeroing the offset changes the +lookup in mip one. Each mutated draw must match its own full CPU reference and +first differ from the original reference at the predicted pixel and values. + +LLVM 15 assembles and disassembles the four forms and checks that the container +CLI emits the same HLSL as the text path. The optional `compile` command runs +DXC and computes the expected first differences on the CPU. + +```sh +python3 -B tests/pixel_compare_lod_check.py binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 +``` + +```powershell +python -B tests/pixel_compare_lod_check.py compile level dxc +python -B tests/pixel_compare_lod_check.py compile bias dxc +ctest --preset dev --no-tests=error -j 1 -R '^pixel_aot_compare_lod_(level|bias)_(warp|hardware)$' -V +``` + +The Level tests require PS 6.7 and `AdvancedTextureOpsSupported`. The Bias tests +require PS 6.8 and `SampleCmpGradientAndBiasSupported`. The renderer uses the +Windows SDK 10.0.26100 headers for these capability queries. CTest reports an +unsupported profile, SDK header set or device capability as a skip (77). +Intel Arc B390 and WARP passed the Level tests. WARP passed the Bias tests. +Arc B390 reported the Bias capability unavailable and skipped those tests. + ### Desktop xmem.dll `src/xmem_shim.cpp` builds `xmem.dll`, which exports the four functions the package DLLs import by name. The call shapes come from the observed call sites, not from a published header: diff --git a/tests/desktop_gpu.h b/tests/desktop_gpu.h index b09835fa1..6ec555f55 100644 --- a/tests/desktop_gpu.h +++ b/tests/desktop_gpu.h @@ -102,7 +102,7 @@ void check_pixel_quad_lod(ID3D12Device* device, const char* shader, const char* bool allowUpperRawLodStep = false); void check_pixel_mip_clamp(ID3D12Device* device, const char* shader, unsigned expectedLevel); void check_pixel_mip_blend(ID3D12Device* device, const char* shader, float clamp, float tolerance); -void check_pixel_compare(ID3D12Device* device, const char* shader, const char* reference); +void check_pixel_compare(ID3D12Device* device, const char* shader, const char* reference, bool twoMips = false); void check_pixel_gather(ID3D12Device* device, const char* shader, const char* reference); void check_pixel_compare_gather(ID3D12Device* device, const char* shader, const char* reference, const char* sampler_line, const char* vsPath = nullptr); diff --git a/tests/offscreen_check.cpp b/tests/offscreen_check.cpp index 963f442ca..5c1b653c8 100644 --- a/tests/offscreen_check.cpp +++ b/tests/offscreen_check.cpp @@ -794,6 +794,35 @@ OperationResult run_sampled_coverage(const OperationContext& ctx) return {OutcomeKind::pass, nullptr}; } +OperationResult run_check_pixel_compare_lod(const OperationContext& ctx) +{ +// Windows SDK 10.0.22621 does not declare the SM 6.8 capability query. +#if defined(__ID3D12Device14_INTERFACE_DEFINED__) + const bool bias = std::strcmp(ctx.argv[2], "--check-pixel-compare-bias") == 0; + const D3D_SHADER_MODEL required = bias ? D3D_SHADER_MODEL_6_8 : D3D_SHADER_MODEL_6_7; + D3D12_FEATURE_DATA_SHADER_MODEL shaderModel{required}; + if (FAILED(check_feature(ctx.device, D3D12_FEATURE_SHADER_MODEL, &shaderModel, sizeof(shaderModel))) || + shaderModel.HighestShaderModel < required) + return {OutcomeKind::skip, bias ? "Comparison bias requires SM 6.8" : "Comparison LOD requires SM 6.7"}; + if (bias) { + D3D12_FEATURE_DATA_D3D12_OPTIONS21 options{}; + if (FAILED(check_feature(ctx.device, D3D12_FEATURE_D3D12_OPTIONS21, &options, sizeof(options))) || + !options.SampleCmpGradientAndBiasSupported) + return {OutcomeKind::skip, "Comparison bias requires SampleCmpGradientAndBiasSupported"}; + } else { + D3D12_FEATURE_DATA_D3D12_OPTIONS14 options{}; + if (FAILED(check_feature(ctx.device, D3D12_FEATURE_D3D12_OPTIONS14, &options, sizeof(options))) || + !options.AdvancedTextureOpsSupported) + return {OutcomeKind::skip, "Comparison LOD requires AdvancedTextureOpsSupported"}; + } + check_pixel_compare(ctx.device, ctx.argv[3], ctx.argv[4], true); + return {OutcomeKind::pass, nullptr}; +#else + (void)ctx; + return {OutcomeKind::skip, "Comparison LOD/bias fixture requires Windows SDK 10.0.26100 headers"}; +#endif +} + OperationResult run_check_pixel_compare(const OperationContext& ctx) { check_pixel_compare(ctx.device, ctx.argv[3], ctx.argv[4]); @@ -1697,6 +1726,8 @@ const OperationSpec kOperations[] = { {"--dual-pixel-swapped", 5, 5, nullptr, kNoGate, run_dual_pixel_swapped}, {"--sampled-coverage", 5, 5, nullptr, kNoGate, run_sampled_coverage}, {"--check-pixel-compare", 5, 5, nullptr, kNoGate, run_check_pixel_compare}, + {"--check-pixel-compare-level", 5, 5, nullptr, kNoGate, run_check_pixel_compare_lod}, + {"--check-pixel-compare-bias", 5, 5, nullptr, kNoGate, run_check_pixel_compare_lod}, {"--check-pixel-gather", 5, 5, nullptr, kNoGate, run_check_pixel_gather}, {"--check-pixel-compare-gather", 6, 7, nullptr, kNoGate, run_check_pixel_compare_gather}, {"--check-pixel-case", 5, 6, nullptr, kNoGate, run_check_pixel_case}, diff --git a/tests/pixel_compare_lod_check.py b/tests/pixel_compare_lod_check.py new file mode 100644 index 000000000..401dce160 --- /dev/null +++ b/tests/pixel_compare_lod_check.py @@ -0,0 +1,203 @@ +"""Compare gfx1030 explicit LOD and biased depth samples on two depth mips.""" +from fractions import Fraction +import math +import os +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from compute_store_check import assemble +from pixel_aot_check import envelope, write_record +from pixel_compare_check import ( + CONSTANT_REFERENCE, D3D12_FILTER, DEPTHS, pixel_aot, prefix, sampler_moves, sampler_words, tail, translate, +) +from pixel_compare_sample_check import must_reject + +FORMS = {"level": ("image_sample_c_l", "image_sample_c_l_o"), + "bias": ("image_sample_c_b", "image_sample_c_b_o")} +FEATURES = "+wavefrontsize64,-wavefrontsize32" +OFFSET = (1, -2) +MIPS = (DEPTHS, [((x * 5 + y * 9 + 8) % 16 * 4 + 1) / 64 for y in range(4) for x in range(4)]) + + +def sampler(): + return sampler_words("LESS", "point", w1=0x100000, w2=1 << 26) + + +def program(op, *, operand="1.0", scale=1, packed="0x3e01", quad=True, words=None): + words = sampler() if words is None else words + lines = prefix() + if quad: + lines = ["s_mov_b64 s[50:51], exec", "s_wqm_b64 exec, exec", *lines] + if scale == 2: + lines += ["v_add_f32_e32 v8, v8, v8", "v_add_f32_e32 v9, v9, v9"] + lines.append("s_and_b64 exec, exec, s[50:51]") + bias = "_b" in op + first, last = (6, 9) if bias else (7, 10) + lines += [*sampler_moves(words), "v_mov_b32_e32 v7, s60", + f"v_mov_b32_e32 v{6 if bias else 10}, {operand}"] + if op.endswith("_o"): + first -= 1 + lines.append(f"v_mov_b32_e32 v{first}, {packed}") + return [*lines, f"{op} v12, v[{first}:{last}], s[28:35], s[40:43] dmask:0x1 dim:SQ_RSRC_IMG_2D", + *tail(reference="v7")] + + +def controls(): + def lower(lines, words): + return pixel_aot.lower(lines, 20, 24, words, constant_descriptor=64) + + words = sampler() + for mode, forms in FORMS.items(): + for op in forms: + hlsl = lower(program(op), words) + method = "SampleCmpBias" if mode == "bias" else "SampleCmpLevel" + assert f"tex.{method}(samp" in hlsl + assert (", int2(1, -2))" in hlsl) == op.endswith("_o") + for operand in ("s61", "0.5", "-1.0"): + must_reject(lambda: lower(program(op, operand=operand), words), "statically 0 or 1") + for state, diagnostic in ( + (sampler_words("LESS", "point"), "MAX_LOD 1"), + (sampler_words("LESS", "point", w1=0x100000, w2=2 << 26), "point mip"), + (sampler_words("LESS", "bilinear", w1=0x100000, w2=1 << 26), "point XY"), + ): + must_reject(lambda: lower(program(op, words=state), state), diagnostic) + for old, new, diagnostic in ( + ("dmask:0x1", "dmask:0x2", "Unsupported instruction"), + ("SQ_RSRC_IMG_2D", "SQ_RSRC_IMG_2D a16", "Unsupported instruction"), + ("s_waitcnt vmcnt(0)", "v_add_f32_e32 v12, 0, v12", "outstanding sample"), + ): + lines = [line.replace(old, new) for line in program(op)] + must_reject(lambda: lower(lines, words), diagnostic) + if mode == "bias": + must_reject(lambda: lower(program(op, quad=False), words), "quad provenance") + else: + lower(program(op, quad=False), words) + if op.endswith("_o"): + must_reject(lambda: lower(program(op, packed="8"), words), "[-8, 7]") + + +def binary(directory, assembler, objcopy, library): + words = sampler() + for forms in FORMS.values(): + for op in forms: + lines = program(op, scale=2) + code = assemble(directory, assembler, objcopy, lines, cpu="gfx1030", features=FEATURES) + decoded = pixel_aot.disassemble(code, library, cpu=b"gfx1030", features=FEATURES.encode(), offsets=True) + assert [line for _, line in decoded if line.startswith("image_")] == [ + line for line in lines if line.startswith("image_") + ] + expected = translate(lines, words) + assert translate(decoded, words) == expected + archive, output = directory / "fixture.bin", directory / "fixture.hlsl" + archive.write_bytes(envelope(code)) + subprocess.run([sys.executable, "-B", pixel_aot.__file__, archive, "fixture", "--llvm", library, + "--cpu", "gfx1030", "--texture-sgpr", "20", "--interp-sgpr", "24", + "--sampler-words", *(hex(w) for w in words), "--constant-descriptor", "0x40", + "--output", output], check=True) + assert output.read_text(encoding="utf-8") == expected + + +def reference_rows(size, scale, mip, displacement): + # Mip zero covers exactly one texel per pixel at both viewport sizes. + # For the bias forms this makes the implicit LOD zero before applying the bias. + width = 8 >> mip + rows = [] + for y in range(size): + for x in range(size): + u = Fraction(width * scale * (2 * x + 1), 2 * size) + displacement[0] + v = Fraction(width * scale * (2 * y + 1), 2 * size) + displacement[1] + tx = min(width - 1, max(0, math.floor(u))) + ty = min(width - 1, max(0, math.floor(v))) + red = float(CONSTANT_REFERENCE < MIPS[mip][ty * width + tx]) + rows.append((red, CONSTANT_REFERENCE, 0.5, 1.0)) + return rows + + +def first_mismatch(size, expected, actual): + for i, (wanted, observed) in enumerate(zip(expected, actual, strict=True)): + if wanted != observed: + want = ",".join(f"{channel:.9g}" for channel in wanted) + got = ",".join(f"{channel:.9g}" for channel in observed) + return f"pixel_mismatch x={i % size} y={i // size} expected={want} actual={got}" + raise AssertionError("Negative control does not distinguish the CPU references") + + +def write_case(path, size, rows): + data = bytearray(struct.pack("<6I", D3D12_FILTER["point"], 2, 8, 8, size, size)) + data.extend(struct.pack("<64f", CONSTANT_REFERENCE, *([0.0] * 63))) + data.extend(struct.pack("<80f", *MIPS[0], *MIPS[1])) + for row in rows: + data.extend(struct.pack("<4f", *row)) + path.write_bytes(data) + + +def check_shader(directory, mode, compiler, renderer=None, adapter=None): + target = "ps_6_8" if mode == "bias" else "ps_6_7" + probe = directory / "probe.hlsl" + probe.write_text("float4 main() : SV_Target { return 0; }\n", encoding="ascii") + args = [compiler, "-T", target, "-E", "main"] + result = subprocess.run([*args, "-Fo", directory / "probe.cso", probe], capture_output=True, text=True) + if result.returncode: + diagnostic = result.stdout + result.stderr + if "invalid profile" in diagnostic.lower() or "unable to parse shader model" in diagnostic.lower(): + print(f"skip: DXC does not support {target}: {diagnostic.strip()}") + raise SystemExit(77) + raise AssertionError(diagnostic) + + def run_draw(case, expected_mismatch=None): + run = subprocess.run([renderer, adapter, f"--check-pixel-compare-{mode}", shader, case], + capture_output=True, text=True) + print(run.stdout, end="") + if run.returncode == 77: + print(run.stderr, end="", file=sys.stderr) + raise SystemExit(77) + if expected_mismatch is None: + assert run.returncode == 0, (run.stdout, run.stderr) + else: + observed = next((line for line in run.stderr.splitlines() if line.startswith("pixel_mismatch ")), None) + assert run.returncode == 1 and observed == expected_mismatch, ( + expected_mismatch, run.stdout, run.stderr) + + source = directory / "sample.hlsl" + shader, case = source.with_suffix(".cso"), source.with_suffix(".case") + mutated_case = directory / "mutated.case" + for op in FORMS[mode]: + displacement = OFFSET if op.endswith("_o") else (0, 0) + for size in (8, 16): + scale = size // 8 + baseline = reference_rows(size, scale, 1, displacement) + write_case(case, size, baseline) + variants = [("original", 1, displacement), ("operand-zero", 0, displacement)] + if op.endswith("_o"): + variants.append(("offset-zero", 1, (0, 0))) + for variant, mip, offset in variants: + lines = program(op, scale=scale, operand=f"{mip}.0", packed="0x3e01" if offset != (0, 0) else "0") + source.write_text(translate(lines, sampler()), encoding="ascii") + subprocess.run([*args, "-Fo", shader, source], check=True) + if variant == "original": + if renderer: + run_draw(case) + continue + mutated = reference_rows(size, scale, mip, offset) + mismatch = first_mismatch(size, baseline, mutated) + if renderer: + write_case(mutated_case, size, mutated) + run_draw(mutated_case) + run_draw(case, mismatch) + print(f"{op} {size} {variant} {'readback' if renderer else 'CPU prediction'} {mismatch}") + if renderer: + write_record(os.environ.get("FORM_COVERAGE_RECORD")) + + +if __name__ == "__main__": + controls() + if len(sys.argv) > 1: + out = Path(__file__).resolve().parents[1] / "out" + out.mkdir(exist_ok=True) + with tempfile.TemporaryDirectory(prefix="compare-lod-", dir=out) as directory: + {"binary": binary, "draw": check_shader, "compile": check_shader}[sys.argv[1]]( + Path(directory), *sys.argv[2:]) + print("gfx1030 depth-comparison LOD/bias checks passed") diff --git a/tests/pixel_compare_render.cpp b/tests/pixel_compare_render.cpp index ba0e719a6..5d82a5cca 100644 --- a/tests/pixel_compare_render.cpp +++ b/tests/pixel_compare_render.cpp @@ -20,7 +20,7 @@ struct CompareCase { std::vector> expected; }; -CompareCase read_case(const char* path) +CompareCase read_case(const char* path, UINT mipLevels) { std::ifstream file(path, std::ios::binary); if (!file) throw std::runtime_error("Cannot open comparison case"); @@ -40,7 +40,11 @@ CompareCase read_case(const char* path) c.filter != D3D12_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT)) throw std::runtime_error("Invalid comparison case header"); file.read(reinterpret_cast(c.constants.data()), sizeof(c.constants)); - c.depths.resize(size_t(c.texWidth) * c.texHeight); + if (mipLevels == 2 && (c.texWidth < 2 || c.texHeight < 2)) + throw std::runtime_error("Two-mip comparison case needs both texture dimensions at least 2"); + size_t texels = size_t(c.texWidth) * c.texHeight; + if (mipLevels == 2) texels += size_t(c.texWidth / 2) * (c.texHeight / 2); + c.depths.resize(texels); file.read(reinterpret_cast(c.depths.data()), std::streamsize(c.depths.size() * sizeof(float))); c.expected.resize(size_t(c.width) * c.height); file.read(reinterpret_cast(c.expected.data()), std::streamsize(c.expected.size() * 16)); @@ -61,9 +65,10 @@ ComPtr upload_bytes(ID3D12Device* device, const void* data, UINT } } -void check_pixel_compare(ID3D12Device* device, const char* shader, const char* casePath) +void check_pixel_compare(ID3D12Device* device, const char* shader, const char* casePath, bool twoMips) { - const auto c = read_case(casePath); + const UINT mipLevels = twoMips ? 2 : 1; + const auto c = read_case(casePath, mipLevels); std::ifstream stream(shader, std::ios::binary); std::vector ps{std::istreambuf_iterator(stream), {}}; if (ps.empty()) throw std::runtime_error("Cannot read compiled pixel shader"); @@ -113,16 +118,25 @@ void check_pixel_compare(ID3D12Device* device, const char* shader, const char* c texDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; texDesc.Width = c.texWidth; texDesc.Height = c.texHeight; - texDesc.DepthOrArraySize = texDesc.MipLevels = texDesc.SampleDesc.Count = 1; + texDesc.DepthOrArraySize = texDesc.SampleDesc.Count = 1; + texDesc.MipLevels = static_cast(mipLevels); texDesc.Format = DXGI_FORMAT_R32_FLOAT; auto texture = resource(device, texDesc, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COPY_DEST); - D3D12_PLACED_SUBRESOURCE_FOOTPRINT texLayout{}; + std::array texLayouts{}; UINT64 texBytes = 0; - device->GetCopyableFootprints(&texDesc, 0, 1, 0, &texLayout, nullptr, nullptr, &texBytes); + device->GetCopyableFootprints(&texDesc, 0, mipLevels, 0, texLayouts.data(), nullptr, nullptr, &texBytes); std::vector staged(static_cast(texBytes)); - for (UINT y = 0; y < c.texHeight; ++y) - std::memcpy(staged.data() + texLayout.Offset + size_t(y) * texLayout.Footprint.RowPitch, - c.depths.data() + size_t(y) * c.texWidth, c.texWidth * sizeof(float)); + size_t texelOffset = 0; + for (UINT mip = 0; mip < mipLevels; ++mip) { + const auto& layout = texLayouts[mip]; + const UINT width = c.texWidth >> mip; + const UINT height = c.texHeight >> mip; + for (UINT y = 0; y < height; ++y) { + std::memcpy(staged.data() + layout.Offset + size_t(y) * layout.Footprint.RowPitch, + c.depths.data() + texelOffset + size_t(y) * width, width * sizeof(float)); + } + texelOffset += size_t(width) * height; + } auto staging = upload_bytes(device, staged.data(), texBytes); auto constants = upload_bytes(device, c.constants.data(), sizeof(c.constants)); @@ -138,7 +152,7 @@ void check_pixel_compare(ID3D12Device* device, const char* shader, const char* c sampler.AddressU = sampler.AddressV = sampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; sampler.MaxAnisotropy = 1; sampler.ComparisonFunc = D3D12_COMPARISON_FUNC(c.func); - sampler.MaxLOD = D3D12_FLOAT32_MAX; + sampler.MaxLOD = twoMips ? 1.0f : D3D12_FLOAT32_MAX; device->CreateSampler(&sampler, samplers->GetCPUDescriptorHandleForHeapStart()); heapDesc = {D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE}; check(device->CreateDescriptorHeap(&heapDesc, IID_PPV_ARGS(&rtvs)), "Comparison target heap"); @@ -162,10 +176,13 @@ void check_pixel_compare(ID3D12Device* device, const char* shader, const char* c D3D12_TEXTURE_COPY_LOCATION src{}, dst{}; src.pResource = staging.Get(); src.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; - src.PlacedFootprint = texLayout; dst.pResource = texture.Get(); dst.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; - list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + for (UINT mip = 0; mip < mipLevels; ++mip) { + src.PlacedFootprint = texLayouts[mip]; + dst.SubresourceIndex = mip; + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + } transition(list, texture.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); ID3D12DescriptorHeap* heaps[]{views.Get(), samplers.Get()}; list->SetDescriptorHeaps(2, heaps); diff --git a/tools/pixel_aot.py b/tools/pixel_aot.py index 20d01a27e..068652de8 100644 --- a/tools/pixel_aot.py +++ b/tools/pixel_aot.py @@ -5199,17 +5199,20 @@ def sample_coord(reg): for dst, value in zip(dests, values): vector[dst] = value sample_dest[dst] = vector_loads - elif m := match(r"(image_sample_c(?:_lz)?(?:_o)?) (v\d+), (?:v\[(\d+):(\d+)\]|\[(v\d+), (v\d+), (v\d+)\]), " + elif m := match(r"(image_sample_c(?:_lz|_l|_b)?(?:_o)?) (v\d+), (?:v\[(\d+):(\d+)\]|\[(v\d+), (v\d+), (v\d+)\]), " r"s\[(\d+):(\d+)\], s\[(\d+):(\d+)\] dmask:0x1 dim:SQ_RSRC_IMG_2D"): - # The optional packed offset precedes the reference, followed by the UV pair. + # RDNA 2 orders the address as offset, bias, reference, UV, explicit LOD. + # Only the reference and UV pair are present in every comparison form. op, dst, first, last, *nsa = m.groups()[:7] image = registers(*m.groups()[7:9], 8) state = registers(*m.groups()[9:11], 4) has_offset = op.endswith("_o") - explicit_zero = op.removesuffix("_o") == "image_sample_c_lz" + base_op = op.removesuffix("_o") + explicit_level = base_op in ("image_sample_c_lz", "image_sample_c_l") + has_level_operand = base_op in ("image_sample_c_l", "image_sample_c_b") if first is None and op != "image_sample_c_lz": raise ValueError("Comparison sample requires a contiguous address") - address = ([f"v{n}" for n in registers(first, last, 3 + has_offset)] + address = ([f"v{n}" for n in registers(first, last, 3 + has_offset + has_level_operand)] if first is not None else nsa) if any(int(reg[1:]) > 255 for reg in (dst, *address)): raise ValueError("Comparison sample VGPR out of range") @@ -5222,10 +5225,24 @@ def sample_coord(reg): or descriptor != [("tex", j) for j in range(8)] or [scalar.get(f"s{n}") for n in state] != list(sampler)): raise ValueError("Unsupported image or sampler binding") - if not explicit_zero and sampler[1] & 0xfff000: + if has_level_operand: + if sampler[1] & 0xfff000 != 0x100000 or (sampler[2] >> 26) & 3 != 1: + raise ValueError("Comparison LOD/bias requires MAX_LOD 1 and point mip filtering") + if (sampler[2] >> 20) & 0xf: + raise ValueError("Comparison LOD/bias requires point XY filtering") + elif not explicit_level and sampler[1] & 0xfff000: raise ValueError("Implicit comparison sampling requires MAX_LOD 0") offset_arg = sample_offset_arg(address.pop(0), vector, sample_dest, known_ssa_bits) if has_offset else "" - if not explicit_zero and any(vector.get(reg) not in quad_values for reg in address[1:]): + level_arg = "" + if has_level_operand: + operand = address.pop() if explicit_level else address.pop(0) + if operand in sample_dest: + raise ValueError("Comparison LOD operand used before vmcnt wait") + value = vector.get(operand) + if not isinstance(value, str) or known_ssa_bits.get(value) not in (0, 0x3f800000): + raise ValueError("Comparison LOD or bias must be statically 0 or 1") + level_arg = f", {value}" + if not explicit_level and any(vector.get(reg) not in quad_values for reg in address[1:]): raise ValueError("Implicit comparison sampling requires coordinates with quad provenance") if not xy_coordinates([vector.get(reg) for reg in address[1:]], quad_values): if attribute_scales: @@ -5242,8 +5259,10 @@ def sample_coord(reg): if not isinstance(value, str) or not (value in quad_values or value.startswith(("sample", "alu", "params"))): raise ValueError("Unsupported comparison sample operand") reference, u, v = values - method = "SampleCmpLevelZero" if explicit_zero else "SampleCmp" - lines.append(f" float sample{i} = tex.{method}(samp, float2({u}, {v}), {reference}{offset_arg});") + method = {"image_sample_c_lz": "SampleCmpLevelZero", "image_sample_c_l": "SampleCmpLevel", + "image_sample_c_b": "SampleCmpBias", "image_sample_c": "SampleCmp"}[base_op] + lines.append(f" float sample{i} = tex.{method}(samp, float2({u}, {v}), " + f"{reference}{level_arg}{offset_arg});") samples += 1 sampled_textures.add("tex") vector_loads += 1 From d76a954cbfb7ca4000c90d06acdaa903312180da Mon Sep 17 00:00:00 2001 From: RavenCurseBurg Date: Thu, 26 Nov 2026 09:07:01 +0800 Subject: [PATCH 041/240] gfx2hlsl: lower the carry of adjacent compute address adds (#2658) Co-authored-by: RavenCurseBurg <360931527+RavenCurseBurg@users.noreply.github.com> --- docs/experiments.md | 11 +++++++ tests/startup_gfx2hlsl_compute_check.py | 41 +++++++++++++++++++++++++ tools/startup/gfx2hlsl.py | 36 ++++++++++++++++++++++ 3 files changed, 88 insertions(+) diff --git a/docs/experiments.md b/docs/experiments.md index 009153b30..4fc2c2333 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15038,6 +15038,17 @@ python -B tests/startup_compute_store_format_xyzw_check.py binary llvm-mc-15 Not covered here: hardware adapters, the `llvm-mc-15` `binary` step, formats with fewer than four channels (they write nothing), `OOB_SELECT` 1, a dispatch against a host view shorter than the guest range (the guard is checked only as emitted text), and runtime binding of the three entry constants. +### Startup compute address carry + +The startup compute translator accepts a numeric `s_add_u32 sN, a, b` followed +immediately by `s_add_u32 sN+1, 0, src_scc` when both execute in the same +basic block. The first add produces the low word and unsigned carry. The second +stores the carry as the high word and clears SCC. A branch directly to the high +add, a lane-mask addend or symbolic descriptor arithmetic keeps the refusal. +The `address-carry` fixture +adds group IDs 0 through 3 to `0xfffffffe` and reads back both words and the +final SCC. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_compute_(controls|warp|hardware)$' -V`. + ### First active lane at compute entry The startup compute translator accepts `s_ff1_i32_b32 sN, exec_lo` in the diff --git a/tests/startup_gfx2hlsl_compute_check.py b/tests/startup_gfx2hlsl_compute_check.py index 073786826..1d7b56d17 100644 --- a/tests/startup_gfx2hlsl_compute_check.py +++ b/tests/startup_gfx2hlsl_compute_check.py @@ -397,9 +397,33 @@ def saveexec_fixture(): 'L-unorm': (1 << 12) | 1 | (4 << 3) | (7 << 6) | (5 << 9), # one, X, W, Y } +# Each group uses its ID as a low addend, overwrites that SGPR, and stores the +# low word, high word and SCC left by the high add. The fourth word stays untouched. +SOURCE_CARRY = """\ +s_mov_b32 s10, s6 +s_mov_b32 s11, 0 +s_load_dwordx8 s[12:19], s[10:11], 0 +s_waitcnt lgkmcnt(0) +s_mul_i32 s20, s7, 1 +s_add_u32 s20, s20, -2 +s_add_u32 s21, 0, src_scc +s_cselect_b32 s22, 1, 0 +s_lshl_b32 s23, s7, 4 +v_mov_b32_e32 v4, s23 +v_mov_b32_e32 v8, s20 +v_mov_b32_e32 v9, s21 +v_mov_b32_e32 v10, s22 +buffer_store_dwordx3 v[8:10], v4, s[16:19], 0 offen +s_endpgm +""" +WORDS_CARRY = bytes.fromhex( + '06038abe 80038bbe 05030cf4000000fa 7fc08cbf 07811493 14c21480 80fd1580 81801685' + ' 0784178f 1702087e 1402107e 1502127e 1602147e 00107ce004080480 000081bf') + CASES = { # name: (source, words, rsrc2, group size, group counts) 'A': (SOURCE_A, WORDS_A, USER7 | TGID_X | TGID_Y | TGID_Z | tidig(3), (2, 3, 4), (3, 2, 2)), + 'address-carry': (SOURCE_CARRY, WORDS_CARRY, USER7 | TGID_X, (1, 1, 1), (4, 1, 1)), 'B': (SOURCE_B, WORDS_B, USER7 | TGID_X | TGID_Z | tidig(2), (5, 2, 1), (4, 1, 3)), 'C': (SOURCE_C, WORDS_C, USER7 | TGID_Y | tidig(1), (8, 1, 1), (1, 5, 1)), 'D': (SOURCE_D, WORDS_D, USER7 | TGID_X | tidig(3), (4, 2, 4), (2, 1, 1)), @@ -598,6 +622,11 @@ def expected(name): out[4 * group:4 * group + 4] = [group, pair & MASK, pair >> 32, 0] return out _, _, _, local, groups = CASES[name] + if name == 'address-carry': + for group in range(groups[0]): + total = group + 0xfffffffe + out[4 * group:4 * group + 3] = [total & 0xffffffff, total >> 32, 0] + return out if name in L_WORD3: data = formatted_input() for lane in range(16): @@ -979,6 +1008,18 @@ def lines(*code): def check_controls(): + carry = translate('address-carry').hlsl_cs() + assert 's21 = (scc ? 1u : 0u);' in carry + lo, hi, end = (bytes.fromhex(x) for x in ('04051480', '80fd1580', '000081bf')) + for near_miss in ( + lo + bytes.fromhex('81809e80') + hi, # intervening s_sub_u32 writes SCC + lo + bytes.fromhex('000080bf') + hi, # non-adjacent + bytes.fromhex('010084bf') + lo + hi, # branch into the high add + bytes.fromhex('06811480') + hi, # elided descriptor arithmetic + lo + bytes.fromhex('81fd1580'), # high addend is one + lo + bytes.fromhex('80fd1680')): # high register is not the next SGPR + refused('src_scc', lambda: translate('address-carry', code=near_miss + end)) + refused('lane mask', lambda: translate('address-carry', code=bytes.fromhex('7e811480') + hi + end)) ff1 = bytes.fromhex('7e1385be') end = bytes.fromhex('000081bf') # A write to EXEC can disable lane zero; a backward branch can re-enter diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index ce212659d..e6b2ca14f 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -1743,6 +1743,23 @@ def dead_count_entry_scalar(i): return out +def adjacent_address_carries(ins, targets): + """Map each candidate low add to its high-word carry read in the same basic block.""" + pairs = {} + for index, (high_pc, _, name, asm) in enumerate(ins): + if name != 's_add_u32' or 'src_scc' not in asm or not index or high_pc in targets: + continue + low_pc, _, low_name, low_asm = ins[index - 1] + if low_name != 's_add_u32': + continue + low = parse(low_asm)[1] + if len(low) == 3 and re.fullmatch(r's\d+', low[0]): + reg = int(low[0][1:]) + if reg < 105 and parse(asm)[1] == ['s%d' % (reg + 1), '0', 'src_scc']: + pairs[low_pc] = high_pc + return pairs + + class Stage: """Translates one stage. Shares the resource and entry-constant registries of its pipeline.""" @@ -1764,6 +1781,8 @@ class Stage: bad_sgprs = None _uniform_written = None raw_code = b'' + address_carry_pairs = () + address_carry_reader = None def __init__(self, pipe, kind, code, refusals=None, decoded=None): self.pipe, self.kind = pipe, kind @@ -2549,6 +2568,8 @@ def translate(self): target = int(parse(asm)[1][0].split('_')[1], 16) targets.add(target) branches.append((off, target)) + if getattr(self, 'kind', None) == 'cs': + self.address_carry_pairs = adjacent_address_carries(self.ins, targets) # Forward edges reach each block in disassembly order. A back edge could # repeat a pointer advance before the next table load. self.forward_table_adds = (getattr(self, 'kind', None) in ('vs', 'ps') and bool(branches) @@ -2593,6 +2614,7 @@ def translate(self): for _ in range(max(4, len(self.ins) + 2)): scc_effects = {} + self.address_carry_reader = None uniform_vcc_compares = set() self.lines = [] self.blocks = [] # (offset, [lines], terminator) @@ -3568,6 +3590,11 @@ def scalar(self, base, ops): if base == 's_movk_i32' and len(ops) != 2: raise Unsupported('s_movk_i32 with %d operands, expected 2' % len(ops)) text, scc = SCA[base] + if base == 's_add_u32' and self.address_carry_reader is not None and self.pc == self.address_carry_reader: + # The immediately preceding numeric add emitted the carry; no branch can enter here. + self.set_s(reg_range(ops[0])[1], '(scc ? 1u : 0u)') + self.set_scc('false') # 0 + a single bit never produces another carry. + return None if base in SCC_UNMODELLED and self.tracks_uniformity(): self.scc_uniform = False dst = reg_range(ops[0]) @@ -3691,6 +3718,15 @@ def src_sym(t): self.used_s.add(reg_range(srcs[absorbed])[1]) values = [t if i == absorbed else self.u(t) for i, t in enumerate(srcs)] expr = text.format(*values) + if base == 's_add_u32' and getattr(self, 'pc', None) in self.address_carry_pairs: + for tok in srcs: + self.reject_lane_mask_data(base, tok) + r = reg_range(tok) + if r and r[1] in getattr(self, 'join_masks', ()): + raise Unsupported('address carry on a lane mask joined at a branch target') + # Compute carry before writing the low register, which can also be an addend. + self.set_scc('(%s) < %s' % (expr, values[0])) + self.address_carry_reader = self.address_carry_pairs[self.pc] if shift_add: # carry = bits shifted out of S0, or a wrap of the 32-bit sum; read before the destination is written n = SHIFT_ADD[base] From 7ff6f3b99a92f4583b787a8e85db21b8a2a80016 Mon Sep 17 00:00:00 2001 From: yjs <1245206726@qq.com> Date: Thu, 26 Nov 2026 09:08:04 +0800 Subject: [PATCH 042/240] shader: lower experimental gfx1030 2D sample clamps (#1638) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- .github/workflows/windows.yml | 1 + CMakeLists.txt | 10 ++ docs/experiments.md | 80 +++++++++ tests/pixel_sample_clamp_check.py | 275 ++++++++++++++++++++++++++++++ tools/pixel_aot.py | 64 ++++++- 5 files changed, 422 insertions(+), 8 deletions(-) create mode 100644 tests/pixel_sample_clamp_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index cd22a2a6c..0a36fcd1a 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -50,6 +50,7 @@ jobs: (["tests/sampled_coverage_check.py", *COMMON_LLVM], {}), (["tests/pixel_compare_gather_check.py", "--binary", "llvm-mc-15", "llvm-objcopy-15", "libLLVM-15.so.1"], {}), (["tests/pixel_gather_check.py", "--binary", "llvm-mc-15", "llvm-objcopy-15", "libLLVM-15.so.1"], {}), + (["tests/pixel_sample_clamp_check.py", *COMMON_LLVM, "llc-15"], {}), (["tests/pixel_sample_gradient_check.py", *COMMON_LLVM, "llc-15"], {}), (["tests/pixel_sample_gradient_check.py", "binary-coarse", "llvm-mc-15", "llvm-objcopy-15", "libLLVM-15.so.1", "llc-15"], {}), (["tests/depth_mask_check.py", *COMMON_LLVM], {}), diff --git a/CMakeLists.txt b/CMakeLists.txt index 2ef17d51b..ca080c17d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -9156,6 +9156,11 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/awc_metadata_cli_check.py") add_test(NAME sgd5_effect_candidates COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/sgd5_effects_check.py") + add_test(NAME pixel_aot_sample_clamp_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/pixel_sample_clamp_check.py") + add_test(NAME pixel_aot_sample_clamp_compile COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/pixel_sample_clamp_check.py" compile "${DXC_EXECUTABLE}") + set_tests_properties(pixel_aot_sample_clamp_compile PROPERTIES TIMEOUT 90) add_test(NAME shader_sgd5_effects_cli_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/sgd5_effects_cli_check.py") set_tests_properties(shader_sgd5_effects_cli_check PROPERTIES TIMEOUT 60) @@ -9989,6 +9994,11 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(pixel_aot_sample_offset_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_sample_offset_${adapter}.txt") + # Keep these desktop differential results out of opcode coverage until native gfx1030 is measured. + add_test(NAME pixel_aot_sample_clamp_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/pixel_sample_clamp_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(pixel_aot_sample_clamp_${adapter} PROPERTIES TIMEOUT 180 SKIP_RETURN_CODE 77 RUN_SERIAL TRUE) add_test(NAME pixel_aot_sample_gradient_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/pixel_sample_gradient_check.py" draw "${DXC_EXECUTABLE}" "$" ${adapter}) diff --git a/docs/experiments.md b/docs/experiments.md index 4fc2c2333..4dd6c5d84 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -4850,6 +4850,86 @@ ctest --preset dev --no-tests=error -j 1 -R '^compute_store_aot_mimg_msaa_(warp| python3 -B tests/compute_mimg_msaa_check.py --binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 ``` +### Experimental gfx1030 2D per-instruction minimum LOD + +The ordinary pixel path accepts the following full-width, non-comparison +`dmask:0xf` Texture2D forms with sequential VGPRs. The output is four VGPRs, +and the existing `vmcnt(0)` rule applies. Coordinates must retain whole-quad +provenance. The offset is a known canonical packed XY DWORD, with signed +six-bit fields at bits 5:0 and 13:8, limited to the DXIL range `[-8, 7]`. + +| Instruction | gfx1030 opcode | Active address DWORDs | Desktop HLSL | +| --- | --- | --- | --- | +| `image_sample_cl` | `0x21` | `u, v, clamp` | `Sample(s, uv, int2(0, 0), clamp)` | +| `image_sample_cl_o` | `0x31` | `offset, u, v, clamp` | `Sample(s, uv, offset, clamp)` | +| `image_sample_b_cl` | `0x26` | `bias, u, v, clamp` | `SampleBias(s, uv, bias, int2(0, 0), clamp)` | +| `image_sample_b_cl_o` | `0x36` | `offset, bias, u, v, clamp` | `SampleBias(s, uv, bias, offset, clamp)` | + +`--cpu gfx1030 --sample-clamp-mips N` opts into this experiment. The caller +must bind matching float 2D views of 1 to 16 visible mips and a normalized +clamp-to-edge sampler with point XY and mip filters, zero sampler bias and +minimum LOD, and maximum LOD at or above the last view mip. The instruction +clamp must be a known finite float in `[0, N-1]`. The instruction bias, when +present, must be a known float in the HLSL range `[-16, 15.99]`. The draw +cases use integral LODs and avoid point mip ties. Fractional and near-tie +native rounding remain unmeasured. Comparison, explicit gradient, gather, +NSA, `a16`, `d16`, runtime LOD operands and other sampler profiles are outside +this experiment. + +**Source discrepancy.** The [AMD RDNA 2 reference](https://docs.amd.com/v/u/en-US/rdna2-shader-instruction-set-architecture), +Table 44, says `_CL` clamps computed LOD “to be no larger than this value.” +Table 43 and section 8.2.5 describe the address order. LLVM 15.0.7's +[AMDGPU intrinsic definitions](https://github.com/llvm/llvm-project/blob/llvmorg-15.0.7/llvm/include/llvm/IR/IntrinsicsAMDGPU.td) +append the operand named `clamp` after the coordinates, and its +[MIMG instruction table](https://github.com/llvm/llvm-project/blob/llvmorg-15.0.7/llvm/lib/Target/AMDGPU/MIMGInstructions.td) +assigns the four opcodes above. Those LLVM definitions establish the operand +order and encoding. In Mesa 25.1.0, the +[SPIR-V reader](https://github.com/chaotic-cx/mesa-mirror/blob/mesa-25.1.0/src/compiler/spirv/spirv_to_nir.c) +maps `MinLod` to `nir_tex_src_min_lod`. The +[ACO selector](https://github.com/chaotic-cx/mesa-mirror/blob/mesa-25.1.0/src/amd/compiler/aco_instruction_selection.cpp) +selects the four `_cl` forms, and the +[Mesa AMD LLVM builder](https://github.com/chaotic-cx/mesa-mirror/blob/mesa-25.1.0/src/amd/llvm/ac_llvm_build.c) +appends `min_lod` to the `.cl` intrinsics. The +[Vulkan scale-factor rules](https://registry.khronos.org/vulkan/specs/latest/html/vkspec.html#textures-level-of-detail-operation) +and [Direct3D per-sample MinLOD rules](https://microsoft.github.io/DirectX-Specs/d3d/archive/D3D11_3_FunctionalSpec.htm#5.9.4.5.4%20Per-sample%20MinLOD%20Clamp) +define a lower bound on the biased LOD. The desktop experiment follows the +compiler mapping and uses the native DXIL `Sample` and `SampleBias` clamp +operands. AMD's pinned LLPC independently maps SPIR-V `MinLod` to the same +AMDGPU intrinsics. [AMD LLPC SPIR-V reader](https://github.com/GPUOpen-Drivers/llpc/blob/40cb8d95ad8d6f7f1652e3fd47d39667594cce08/llpc/translator/lib/SPIRV/SPIRVReader.cpp#L7814) · +[AMD LLPC image builder](https://github.com/GPUOpen-Drivers/llpc/blob/40cb8d95ad8d6f7f1652e3fd47d39667594cce08/lgc/builder/ImageBuilder.cpp) + +The fixture checks four LLVM intrinsic-to-ISA argument orders with distinct +literal words and four source assembly-to-container CLI round trips. The +CPU model selects `max(implicit LOD + bias, clamp)` before point mip selection +and predicts all 64 RGBA pixels from three spatially distinct mips. The +translated shader and independent desktop `SampleLevel` oracle use the same +texture, sampler and CPU reference. Controls drop the clamp, force the clamp +as the LOD, drop the bias, apply it after the clamp, or remove the offset. +For example, dropping the `_cl` clamp first changes pixel `(0,0)` red from +`0.5` to `0.25` in the CPU model. The offline DXC check verifies the clamp, +bias and nonzero offset operands in the emitted DXIL. + +```bash +python3 -B tests/pixel_sample_clamp_check.py binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 llc-15 +``` + +```powershell +ctest --preset dev --no-tests=error -R '^pixel_aot_sample_clamp_(controls|compile)$' -V +cmake --build --preset dev --target offscreen_check +ctest --preset dev --no-tests=error -j 1 -R '^pixel_aot_sample_clamp_(warp|hardware)$' -V +``` + +**Native publication gate.** Before publishing opcode support or recording +form coverage, capture the rendered mip identifiers from a source-built +native gfx1030 pixel shader for all four opcodes. Use the same sampler and +spatial mips, confirm the native instruction in the submitted shader's +disassembly, and record device target, driver, shader hash and full readback. +Use cases where the computed LOD is below and above the operand, plus the +negative bias case that distinguishes bias-before-clamp from the opposite +order. Desktop DXIL readback tests the Direct3D implementation. The test +registration omits form coverage records while the native direction remains +unresolved. + ### gfx1030 2D image gathers The pixel AOT tool accepts `image_gather4`, `image_gather4_o`, diff --git a/tests/pixel_sample_clamp_check.py b/tests/pixel_sample_clamp_check.py new file mode 100644 index 000000000..4a6763e41 --- /dev/null +++ b/tests/pixel_sample_clamp_check.py @@ -0,0 +1,275 @@ +"""Verify the bounded gfx1030 2D per-instruction minimum LOD profile.""" +import math +from pathlib import Path +import re +import struct +import subprocess +import sys +import tempfile + +from compute_store_check import assemble +from pixel_aot_check import envelope, pixel_aot +from pixel_sample_lod_check import base_prefix, compile_ps, export_tail +from pixel_sample_offset_check import draw + + +# Clamp addressing, zero sampler LOD floor and bias, max LOD 2, point XY and mip. +SAMPLER = (0x12, 0x200000, 0x04000000, 0) +FEATURES = "+wavefrontsize64,-wavefrontsize32" +FORMS = { + "image_sample_cl": (0x21, 8), + "image_sample_cl_o": (0x31, 7), + "image_sample_b_cl": (0x26, 7), + "image_sample_b_cl_o": (0x36, 6), +} +SIDE, MIPS = 8, 3 + + +def program(op, *, floor="1.0", bias="0.0", offset="0x3f01", scale=1, runtime=False, sampler=SAMPLER): + _, first = FORMS[op] + prefix = base_prefix(quad_scale=runtime) + if scale != 1: + prefix.insert(prefix.index("s_and_b64 exec, exec, s[50:51]"), f"v_fma_f32 v8, {scale}.0, v8, 0") + body = ["v_mov_b32_e32 v10, " + floor] + if "_b_" in op: + body.append(f"v_mov_b32_e32 v7, {bias}") + if op.endswith("_o"): + body.append(f"v_mov_b32_e32 v{first}, {offset}") + body.append(f"{op} v[12:15], v[{first}:10], s[28:35], s[40:43] dmask:0xf dim:SQ_RSRC_IMG_2D") + for index, value in enumerate(sampler, 40): + prefix[prefix.index(f"s_mov_b32 s{index}, {index - 39}")] = f"s_mov_b32 s{index}, 0x{value:x}" + return prefix + body + export_tail() + + +def translate(lines, *, sampler=SAMPLER, **kwargs): + profile = dict(cpu="gfx1030", sample_clamp_mips=MIPS, constant_descriptor=0x40) | kwargs + return pixel_aot.lower(lines, 20, 24, sampler, **profile) + + +def rejects(lines, message, **kwargs): + try: + translate(lines, **kwargs) + except ValueError as exc: + assert message in str(exc), (message, str(exc)) + else: + raise AssertionError(f"Expected rejection with {message!r}") + + +def check_lowering(): + for op in FORMS: + lines = program(op) + offset = "int2(1, -1)" if op.endswith("_o") else "int2(0, 0)" + method = "SampleBias(samp, float2(uv.x, uv.y), 0.0f" if "_b_" in op else "Sample(samp, float2(uv.x, uv.y)" + assert f"tex.{method}, {offset}, 1.0f);" in translate(lines), op + rejects(lines, "requires --sample-clamp-mips", sample_clamp_mips=None) + rejects(lines, "gfx1030", cpu="gfx1013") + for floor in ("-1.0", "3.0", "0x7f800000", "0x7fc00000"): + rejects(program(op, floor=floor), "known minimum LOD inside the view") + rejects(program(op, floor="s60", runtime=True), "known minimum LOD inside the view") + first = FORMS[op][1] + nsa = "[" + ", ".join(f"v{i}" for i in range(first, 11)) + "]" + rejects([line.replace(f"v[{first}:10]", nsa) for line in lines], "Unsupported instruction") + for old, new, diagnostic in ( + ("dmask:0xf", "dmask:0x7", "requires dmask:0xf"), + ("IMG_2D", "IMG_2D a16", "Unsupported instruction"), + ("IMG_2D", "IMG_2D d16", "Unsupported instruction"), + ("IMG_2D", "IMG_3D", "Unsupported instruction"), + (":10]", ":9]", "width mismatch"), + ("s[40:43]", "s[44:47]", "Unsupported image or sampler binding"), + ): + rejects([line.replace(old, new) for line in lines], diagnostic) + rejects([line for line in lines if line != "s_waitcnt vmcnt(0)"], "Unsupported pack operand") + op = "image_sample_b_cl_o" + for bias in ("-17.0", "16.0", "0x7fc00000"): + rejects(program(op, bias=bias), "known LOD bias") + rejects(program(op, bias="s60", runtime=True), "known LOD bias") + rejects(program(op, offset="0x08"), "outside the DXIL immediate range") + rejects(program(op, offset="0x10000"), "canonical 2D offset word") + assert "int2(-8, 7), 0.75f" in translate(program(op, floor="0.75", offset="0x738")) + for sampler in ((0x13, *SAMPLER[1:]), (0x12, 0x200001, *SAMPLER[2:]), + (0x12, 0x100000, *SAMPLER[2:]), (*SAMPLER[:2], 0x04500000, 0), + (*SAMPLER[:2], 0x04000001, 0)): + rejects(program(op, sampler=sampler), "requires a normalized clamp sampler", sampler=sampler) + + +def texel(mip, x, y): + # Exactly representable as binary16, with independent mip, X and Y channels. + return ((mip + 1) / 4, (x + 1) / 16, (y + 1) / 16, (mip + x + 2 * y + 1) / 32) + + +def mip_for(scale, bias, floor): + lod = max(math.log2(scale) + bias, floor) + return min(MIPS - 1, math.floor(lod + 0.5)) + + +def reference(mip, scale, offset): + size = SIDE >> mip + def point(coord, slope, shift): + return max(0, min(size - 1, math.floor((coord + 0.5) * slope * size / SIDE) + shift)) + return [texel(mip, point(x, scale, offset[0]), point(y, 1, offset[1])) + for y in range(SIDE) for x in range(SIDE)] + + +def case_data(expected): + colors = [texel(m, x, y) for m in range(MIPS) for y in range(SIDE >> m) for x in range(SIDE >> m)] + return struct.pack("<2I", 0, MIPS) + b"".join(struct.pack("<4f", *color) for color in colors + expected) + + +def cases(op): + # Bias-before-floor needs a negative bias and a nonzero floor. A separate + # positive-bias case ensures that bias can also select a mip above the floor. + if "_b_" in op: + yield "raised", 2, -1.0, 2.0, 2 + yield "higher", 1, 2.0, 1.0, 2 + else: + yield "raised", 1, 0.0, 1.0, 1 + yield "higher", 4, 0.0, 1.0, 2 + + +def wrong_cases(op, name, scale, bias, floor): + offset = (1, -1) if op.endswith("_o") else (0, 0) + if name == "raised": + yield "drop_floor", mip_for(scale, bias, 0.0), offset + if "_b_" in op: + yield "floor_before_bias", math.floor(max(math.log2(scale), floor) + bias + 0.5), offset + if offset != (0, 0): + yield "drop_offset", mip_for(scale, bias, floor), (0, 0) + elif "_b_" in op: + yield "drop_bias", mip_for(scale, 0, floor), offset + else: + yield "force_floor", int(floor), offset + + +def check_reference(): + for op in FORMS: + offset = (1, -1) if op.endswith("_o") else (0, 0) + for name, scale, bias, floor, mip in cases(op): + assert mip_for(scale, bias, floor) == mip + correct = reference(mip, scale, offset) + assert len(correct) == 64 and correct[0] == texel(mip, offset[0], 0) + for kind, wrong_mip, wrong_offset in wrong_cases(op, name, scale, bias, floor): + wrong = reference(wrong_mip, scale, wrong_offset) + assert correct[0] != wrong[0], (op, name, kind) + print(f"CPU {op}/{kind} (0,0) expected={correct[0]} actual={wrong[0]}") + + +def check_intrinsic_order(directory, llc): + # Use distinct non-inline literals to observe their assigned VGPRs. Mesa's + # AMD LLVM backend maps NIR min_lod to the final float on these intrinsics. + for op in FORMS: + has_offset, has_bias = op.endswith("_o"), "_b_" in op + mods = op.removeprefix("image_sample").replace("_", ".") + intrinsic = f"llvm.amdgcn.image.sample{mods}.2d.v4f32.f32" + (".f32" if has_bias else "") + operands = [("float", "0.125", 0x3E000000), ("float", "0.375", 0x3EC00000), ("float", "1.25", 0x3FA00000)] + if has_bias: + operands.insert(0, ("float", "-0.75", 0xBF400000)) + if has_offset: + operands.insert(0, ("i32", "16129", 0x3F01)) + types = ", ".join(kind for kind, _, _ in operands) + args = ", ".join(f"{kind} {value}" for kind, value, _ in operands) + ir = directory / f"{op}.ll" + ir.write_text(f'''target triple = "amdgcn-amd-amdpal" +declare <4 x float> @{intrinsic}(i32 immarg, {types}, <8 x i32>, <4 x i32>, i1 immarg, i32 immarg, i32 immarg) +define amdgpu_ps <4 x float> @order(<8 x i32> inreg %rsrc, <4 x i32> inreg %sampler) {{ + %value = call <4 x float> @{intrinsic}(i32 15, {args}, <8 x i32> %rsrc, <4 x i32> %sampler, i1 false, i32 0, i32 0) + ret <4 x float> %value +}} +''', encoding="ascii") + asm = subprocess.run([llc, "-mcpu=gfx1030", f"-mattr={FEATURES},-nsa-encoding", "-o", "-", ir], + check=True, capture_output=True, text=True).stdout + match = re.search(rf"{op} v\[\d+:\d+\], v\[(\d+):(\d+)\].*dim:SQ_RSRC_IMG_2D", asm) + assert match and " a16" not in match[0], asm + first, last = map(int, match.groups()) + assert last - first + 1 == len(operands), match[0] + for reg, (_, _, bits) in enumerate(operands, first): + assert re.search(rf"v_mov_b32_e32 v{reg}, 0x{bits:x}\b", asm), asm + print(f"{op} LLVM intrinsic address order: " + ", ".join(f"0x{bits:08x}" for _, _, bits in operands)) + + +def check_binary(directory, assembler, objcopy, library, llc): + check_intrinsic_order(directory, llc) + for op, (opcode, first) in FORMS.items(): + lines = program(op, bias="-1.0") + # LLVM MC requires the padded sequential tuple for a five-word address. + assembly = [line.replace(f"v[{first}:10]", f"v[{first}:{first + 7}]") + if line.startswith(op + " ") and first == 6 else line for line in lines] + data = assemble(directory, assembler, objcopy, assembly, cpu="gfx1030", features=FEATURES) + decoded = pixel_aot.disassemble(data, library, cpu=b"gfx1030", features=FEATURES.encode(), offsets=True) + image = [(pc, text) for pc, text in decoded if text.startswith("image_")] + assert len(image) == 1 and image[0][1] == next(line for line in lines if line.startswith(op + " ")), image + pc, _ = image[0] + w0, w1 = struct.unpack_from("<2I", data, pc) + assert ((w0 >> 18) & 0x7f, w1 & 0xff, w0 & 0x6) == (opcode, first, 0), (op, hex(w0), hex(w1)) + print(f"{op}: {data[pc:pc + 8].hex(' ')}") + expected = translate(lines) + assert translate(decoded) == expected + archive, output = directory / "fixture.bin", directory / "fixture.hlsl" + archive.write_bytes(envelope(data)) + subprocess.run([sys.executable, "-B", pixel_aot.__file__, archive, "fixture", "--llvm", library, + "--cpu", "gfx1030", "--texture-sgpr", "20", "--interp-sgpr", "24", + "--sampler-words", *(hex(word) for word in SAMPLER), "--sample-clamp-mips", str(MIPS), + "--constant-descriptor", "0x40", + "--output", output], check=True) + assert output.read_text() == expected + + +def direct_hlsl(scale, mip, offset): + return f"""Texture2D tex : register(t0); +SamplerState samp : register(s0); +float4 main(float4 uv : TEXCOORD0) : SV_Target0 {{ + return tex.SampleLevel(samp, float2(uv.x * {scale}.0f, uv.y), {mip}.0f, int2{offset}); +}} +""" + + +def check_draw(directory, compiler, renderer=None, adapter=None): + case = directory / "sample-clamp.case" + for op in FORMS: + offset = (1, -1) if op.endswith("_o") else (0, 0) + for name, scale, bias, floor, mip in cases(op): + stem = f"{op}_{name}" + source = translate(program(op, scale=scale, bias=str(bias), floor=str(floor))) + shader = compile_ps(compiler, source, directory, stem) + dxil = subprocess.run([compiler, "-dumpbin", shader], check=True, capture_output=True, text=True).stdout + dxop = "sampleBias" if "_b_" in op else "sample" + call = re.search(rf"call .* @dx\.op\.{dxop}\.f32\(([^)\n]+)\)", dxil) + assert call, dxil + args = call[1].split(", ") + assert float(args[-1].removeprefix("float ")) == floor, call[0] + if "_b_" in op: + assert float(args[-2].removeprefix("float ")) == bias, call[0] + if offset != (0, 0): + assert args[7:9] == [f"i32 {component}" for component in offset], call[0] + direct = compile_ps(compiler, direct_hlsl(scale, mip, offset), directory, stem + "_direct") + case.write_bytes(case_data(reference(mip, scale, offset))) + if renderer is not None: + if op == "image_sample_cl" and name == "raised": + draw(renderer, adapter, "--check-pixel-mip-exact", shader, "1") + draw(renderer, adapter, "--check-pixel-gather", shader, case) + draw(renderer, adapter, "--check-pixel-gather", direct, case) + for kind, wrong_mip, wrong_offset in wrong_cases(op, name, scale, bias, floor): + if kind == "drop_floor": + marker = f", {floor}f);" + assert source.count(marker) == 1 + wrong = source.replace(marker, ", 0.0f);") + elif kind == "drop_bias": + wrong = translate(program(op, scale=scale, bias="0.0", floor=str(floor))) + elif kind == "drop_offset": + wrong = translate(program(op, scale=scale, bias=str(bias), floor=str(floor), offset="0")) + else: + wrong = direct_hlsl(scale, wrong_mip, wrong_offset) + mutated = compile_ps(compiler, wrong, directory, f"{stem}_{kind}") + if renderer is not None: + draw(renderer, adapter, "--check-pixel-gather", mutated, case, mismatch=True) + + +if __name__ == "__main__": + check_reference() + check_lowering() + if len(sys.argv) > 1: + mode, *args = sys.argv[1:] + out = Path(__file__).resolve().parents[1] / "out" + out.mkdir(exist_ok=True) + with tempfile.TemporaryDirectory(prefix="sample-clamp-", dir=out) as tmp: + {"binary": check_binary, "compile": check_draw, "draw": check_draw}[mode](Path(tmp), *args) + print("Four 2D minimum-LOD sample forms checked") diff --git a/tools/pixel_aot.py b/tools/pixel_aot.py index 068652de8..a064c669a 100644 --- a/tools/pixel_aot.py +++ b/tools/pixel_aot.py @@ -315,6 +315,15 @@ def sample_offset_arg(reg, vector, sample_dest, known_ssa_bits): return f", int2({x}, {y})" +def check_sample_clamp_sampler(words, mips): + # Normalized clamp-to-last-texel in X/Y, point filters, zero sampler + # bias and minimum LOD. The sampler must leave the whole view accessible. + w0, w1, w2, w3 = words + if (w0 != 0x12 or w1 & ~0x00fff000 or (w1 >> 12) < ((mips - 1) << 8) + or w2 != 0x04000000 or w3 != 0): + raise ValueError("Sample clamp requires a normalized clamp sampler with point XY/mip filters and no LOD modifiers") + + # Word 2 bits 28-30 (value >> 28): MIP_POINT_PRECLAMP, ANISO_OVERRIDE, BLEND_ZERO_PRT. At an explicit level zero # with anisotropy refused and no partially resident texture, none of them changes the result. LEVEL_ZERO_IGNORED_W2 = 0x7 @@ -3536,10 +3545,12 @@ def discard_dead_integer_temporaries(lines, candidates): def lower(instructions, texture_sgpr, interp_sgpr, sampler, constant_descriptor=None, *, texture_offset=0, second_texture_offset=None, integer_export=False, texcoord_components=2, extra_constants=(), title_ranges=None, flat_global_only=False, return_write_mask=False, wave_size=None, half_denorm=None, - pointer_constants=(), cpu="gfx1013", gather_mips=None): + pointer_constants=(), cpu="gfx1013", gather_mips=None, sample_clamp_mips=None): """Track descriptor provenance, interpolation and packed or uncompressed exports. texture_offset is the aligned byte offset of t0 in the texture descriptor table. + sample_clamp_mips opts into the experimental minimum-LOD interpretation of ordinary _cl + samples, with the declared number of visible mips in matching gfx1030 and desktop views. gather_mips declares the number of visible mips in matching gfx1030 and desktop 2D views. For comparison gather the selected red texel values and the reference must be in [0, 1]. Gather coordinates must map to the same half-texel lattice on both views (see experiments.md). @@ -3574,6 +3585,10 @@ def lower(instructions, texture_sgpr, interp_sgpr, sampler, constant_descriptor= if (cpu != "gfx1030" or sampler is None or second_texture_offset is not None or integer_export or type(gather_mips) is not int or not 1 <= gather_mips <= 16): raise ValueError("Gather requires a gfx1030 float pixel profile with one texture and 1 to 16 visible mips") + if sample_clamp_mips is not None: + if (cpu != "gfx1030" or sampler is None or second_texture_offset is not None or integer_export + or type(sample_clamp_mips) is not int or not 1 <= sample_clamp_mips <= 16): + raise ValueError("Sample clamp requires a gfx1030 float pixel profile with one texture and 1 to 16 visible mips") if title_ranges is not None and (isinstance(title_ranges, bool) or not isinstance(title_ranges, int) or not 1 <= title_ranges <= 0xffffffff): raise ValueError("Invalid title range count") @@ -3680,6 +3695,7 @@ def lower(instructions, texture_sgpr, interp_sgpr, sampler, constant_descriptor= mask = "entry" wqm_width = None samples = 0 + sample_clamp_used = False sampled_textures = set() sample_kind = None # "plain", "comparison" or "gather" resource interpretation vector_loads = 0 # image samples and title loads issued, in vmcnt order @@ -5016,7 +5032,7 @@ def match(pattern): vector[dst] = f"uv.{component}" if mask == "quad" else ("entry_uv", component) else: raise ValueError("Unpaired interpolation") - elif m := match(r"(image_sample(?:(?:_lz|_l|_b)?(?:_o)?|_c?d(?:_o)?(?:_g16)?)) (?:v\[(\d+):(\d+)\]|v(\d+)), " + elif m := match(r"(image_sample(?:(?:_lz|_l|_b|_cl|_b_cl)?(?:_o)?|_c?d(?:_o)?(?:_g16)?)) (?:v\[(\d+):(\d+)\]|v(\d+)), " r"v\[(\d+):(\d+)\], s\[(\d+):(\d+)\], s\[(\d+):(\d+)\] dmask:0x([1-9a-f]) dim:SQ_RSRC_IMG_2D"): op, dst_first, dst_last, dst_single, *rest, dmask_hex = m.groups() dmask = int(dmask_hex, 16) @@ -5030,11 +5046,15 @@ def match(pattern): gradient = coarse or base_op == "image_sample_d" if coarse and cpu != "gfx1030": raise ValueError("Coarse-gradient sampling requires gfx1030") + has_clamp = base_op.endswith("_cl") + has_bias = base_op in ("image_sample_b", "image_sample_b_cl") + if has_clamp and sample_clamp_mips is None: + raise ValueError(f"{op} requires --sample-clamp-mips") if gradient: # LLVM disassembly lists only the live address operands. coord_width = (4 if g16 else 6) + has_offset else: - coord_width = (3 if base_op in ("image_sample_l", "image_sample_b") else 2) + has_offset + coord_width = 2 + (base_op == "image_sample_l" or has_bias) + has_offset + has_clamp channels = ["xyzw"[bit] for bit in range(4) if (dmask >> bit) & 1] if len(channels) == 1: if dst_single is None: @@ -5083,6 +5103,24 @@ def sample_coord(reg): return value return fp_operand(reg, scalar, vector, pending, sample_dest) + def known_sample_float(reg): + if reg in sample_dest: + raise ValueError("Sample LOD operand used before vmcnt wait") + raw = known_ssa_bits.get(vector[reg]) + return struct.unpack(" Date: Thu, 26 Nov 2026 03:10:37 +0200 Subject: [PATCH 043/240] startup: return E_OUTOFMEMORY when a D3D12 wrapper cannot be allocated (#2656) * startup: return E_OUTOFMEMORY when a D3D12 wrapper cannot be allocated wrap() used the _aligned_malloc result without a check, so a failed allocation under the job commit limit became a write through a null pointer inside d3d12_xs.dll (seen at the slot 55 derived-pipeline placeholder). wrap() now returns nullptr when the allocation or the registry insert fails. Each of its 16 callers releases the desktop object it created and returns E_OUTOFMEMORY with a null output. startup_wrap_allocation_warp forces the failure through the fixture-only export x2w_d3d12_fail_wraps for device creation and slots 8, 14, 16 and 55; the control never arms it and must report the failure. Fixes #2653 Co-Authored-By: Claude Opus 5.5 * tests: cover the allocator, command list and committed-resource wrap failures Review follow-up on #2653. startup_wrap_allocation now also arms the failure for device slot 9 (CreateCommandAllocator, the shared create_slot path), slot 73 (command list) and slot 127 (committed resource). Each must return E_OUTOFMEMORY with a null output, then succeed. Removing the slot 73 null check makes the test crash at that slot. Co-Authored-By: Claude Opus 5.5 * Preserve the published D3D12 device on wrapper allocation failure --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: Royoo <3230853833@qq.com> --- CMakeLists.txt | 12 ++ docs/startup-runtime.md | 20 +++ src/startup_stubs/d3d12_xs_device.cpp | 89 ++++++++++++- src/startup_stubs/placed_build.h | 3 +- tests/startup_wrap_allocation.cpp | 178 ++++++++++++++++++++++++++ 5 files changed, 295 insertions(+), 7 deletions(-) create mode 100644 tests/startup_wrap_allocation.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index ca080c17d..b50d1ba1e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1403,6 +1403,18 @@ foreach(backend IN ITEMS warp hardware) endforeach() endforeach() +# #2653: a failed wrapper allocation returns E_OUTOFMEMORY with a null output from device creation and slots 8, 9, 14, +# 16, 55, 73 and 127. `control` never arms the failure, so the fixture must report it. +add_executable(startup_wrap_allocation tests/startup_wrap_allocation.cpp) +target_compile_features(startup_wrap_allocation PRIVATE cxx_std_17) +target_link_libraries(startup_wrap_allocation PRIVATE d3d12_xs_shim d3d12 dxgi) +add_test(NAME startup_wrap_allocation_warp COMMAND startup_wrap_allocation) +add_test(NAME startup_wrap_allocation_control_warp COMMAND startup_wrap_allocation control) +set_tests_properties(startup_wrap_allocation_warp startup_wrap_allocation_control_warp PROPERTIES + TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_DEBUG=0") +set_tests_properties(startup_wrap_allocation_control_warp PROPERTIES + PASS_REGULAR_EXPRESSION "FAIL: Device::slot55 derived pipeline with the wrapper allocation failing") + add_executable(startup_resource_retire_title tests/startup_resource_retire_title.cpp) target_include_directories(startup_resource_retire_title PRIVATE src) target_compile_features(startup_resource_retire_title PRIVATE cxx_std_17) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 09800fd3d..9b093fe86 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1581,6 +1581,26 @@ cmake --build --preset dev --target startup_view_census ctest --preset dev --no-tests=error -R "^startup_view_census" -V ``` +## Wrapper allocation failure + +Every object the D3D12 stand-in returns is a wrapper allocated in `wrap()`. When that allocation (or its +registration) fails, the creating call releases the desktop object it made and returns `E_OUTOFMEMORY` with +a null output ([#2653](https://github.com/R0Y00/Xbox2Windows/issues/2653)). Before, the failure was a write +through a null pointer inside the stand-in. This was seen at the job commit limit in a startup run, at the +slot 55 derived-pipeline placeholder. Whether the title handles the error is not established. + +`startup_wrap_allocation_warp` makes the next wrapper allocation fail through the fixture-only export +`x2w_d3d12_fail_wraps`. Device creation and slots 8, 9, 14, 16, 55, 73 and 127 must return +`E_OUTOFMEMORY` with a null output, then succeed. After a failed attempt to create a second device, +`GetDevice` on a live queue must still return the original device. The +`startup_wrap_allocation_control_warp` test leaves the failure injection disabled and checks that +the fixture detects the unexpected success. + +```powershell +cmake --build --preset dev --target startup_wrap_allocation +ctest --preset dev --no-tests=error -R "^startup_wrap_allocation" -V +``` + ## Input script `X2W_INPUT_SCRIPT` (`run.ps1 -InputScript`) drives the virtual gamepad of the `GameInput.dll` diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 8e70b95f9..0dcb9e742 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -461,10 +461,22 @@ u64 unwrap(u64 value) return w ? reinterpret_cast(w->own().real) : value; } +volatile LONG wraps_to_fail; // fixture-only, set by x2w_d3d12_fail_wraps +constexpr u64 out_of_memory = static_cast(E_OUTOFMEMORY); // for slots that return u64 + +// Returns nullptr when the wrapper cannot be allocated or registered (#2653). The caller still owns +// `real` then: it releases what it created and returns E_OUTOFMEMORY. Wrapper* wrap(IUnknown* real, Kind kind) { + for (LONG n = wraps_to_fail; n > 0; n = wraps_to_fail) + if (InterlockedCompareExchange(&wraps_to_fail, n - 1, n) == n) return nullptr; const std::size_t area = kind == list_kind ? 0x10000 : sizeof(Wrapper); auto* block = static_cast(_aligned_malloc(sizeof(WrapperOwn) + area, 16)); + if (!block) { + static LONG failed; + if (first_calls(failed, 4)) log("x2w-d3d12 wrap(%s): wrapper allocation failed -> E_OUTOFMEMORY", kind_names[kind]); + return nullptr; + } std::memset(block, 0, sizeof(WrapperOwn) + area); auto* w = reinterpret_cast(block + sizeof(WrapperOwn)); w->vtable = tables[kind]; @@ -473,7 +485,13 @@ Wrapper* wrap(IUnknown* real, Kind kind) w->own().kind = kind; if (kind == fence_kind && real) w->own().completed = static_cast(static_cast(real)->GetCompletedValue()); AcquireSRWLockExclusive(®istry_lock); - registry().insert(w); + try { + registry().insert(w); + } catch (const std::bad_alloc&) { + ReleaseSRWLockExclusive(®istry_lock); + _aligned_free(block); + return nullptr; + } ReleaseSRWLockExclusive(®istry_lock); return w; } @@ -876,6 +894,11 @@ __declspec(noinline) u64 create_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d, if (Desc >= 0 && kind == resource_kind && requested_format != DXGI_FORMAT_UNKNOWN) x2w_startup::mark_packed_stand_in(static_cast(*out), requested_format); Wrapper* child = wrap(static_cast(*out), kind); + if (!child) { + static_cast(*out)->Release(); + *out = nullptr; + return out_of_memory; + } if constexpr (K == device_kind && N == 27) { if (kind == resource_kind && args[0]) retire_set_class(child, *reinterpret_cast(args[0]), @@ -1047,6 +1070,10 @@ HRESULT __stdcall device_create_command_queue(Wrapper* self, const D3D12_COMMAND desc->Priority, desc->Flags, desc->NodeMask, text, static_cast(hr)); if (FAILED(hr)) return hr; *out = wrap(queue, queue_kind); + if (!*out) { + queue->Release(); + return E_OUTOFMEMORY; + } register_retire_queue(static_cast(*out)); return S_OK; } @@ -1071,6 +1098,10 @@ HRESULT __stdcall device_create_command_queue_x(Wrapper* self, const D3D12_COMMA desc->Type, desc->Priority, desc->Flags, desc->NodeMask, text, static_cast(hr)); if (FAILED(hr)) return hr; *out = wrap(queue, queue_kind); + if (!*out) { + queue->Release(); + return E_OUTOFMEMORY; + } register_retire_queue(static_cast(*out)); return S_OK; } @@ -1167,7 +1198,7 @@ u64 __stdcall device_create_command_signature(Wrapper* self, const D3D12_COMMAND } } *output = wrap(nullptr, command_signature_kind); - return S_OK; + return *output ? u64{S_OK} : out_of_memory; } const u64 result = create_slot(self, reinterpret_cast(desc), root, iid, out, 0, 0, 0, 0); if (SUCCEEDED(static_cast(result)) && out && desc && root && desc->NumArgumentDescs > 1) { @@ -1220,7 +1251,7 @@ u64 __stdcall device_create_command_signature(Wrapper* self, const D3D12_COMMAND for (UINT i = 0; i < desc->NumArgumentDescs; ++i) { if (static_cast(desc->pArgumentDescs[i].Type) > D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH) { *output = wrap(nullptr, command_signature_kind); - return S_OK; + return *output ? u64{S_OK} : out_of_memory; } } } @@ -1989,6 +2020,10 @@ HRESULT __stdcall device_create_root_signature(Wrapper* self, UINT node, const v return hr; } Wrapper* w = wrap(root, root_signature_kind); + if (!w) { + root->Release(); + return E_OUTOFMEMORY; + } note_root_blob(w, blob, size); std::vector parameters; UINT heap_flags = 0; @@ -4114,6 +4149,7 @@ HRESULT __stdcall device_create_descriptor_heap(Wrapper* self, const D3D12_DESCR // Some callers pass the 16-byte desktop descriptor; the words after it are then unrelated stack // data. The extension is taken only when it holds a pointer and exactly the heap's size. std::uint64_t title_memory = extra[0] >= 0x10000 && extra[1] == bytes ? extra[0] : 0; + const std::uint64_t supplied_memory = title_memory; // The title copies descriptors between heaps with its own memory copies. A view heap without // title memory therefore gets plain memory of ours as its CPU side, so that the view ids written // there (note_view) travel with those copies; the desktop heap behind it is still filled. A heap @@ -4125,6 +4161,11 @@ HRESULT __stdcall device_create_descriptor_heap(Wrapper* self, const D3D12_DESCR return E_OUTOFMEMORY; } Wrapper* w = wrap(heap, descriptor_heap_kind); + if (!w) { + if (title_memory != supplied_memory) VirtualFree(reinterpret_cast(title_memory), 0, MEM_RELEASE); + heap->Release(); + return E_OUTOFMEMORY; + } if (title_memory) { w->own().title_cpu = title_memory; AcquireSRWLockExclusive(&descriptor_lock); @@ -4368,6 +4409,10 @@ HRESULT __stdcall device_create_command_list_x(Wrapper* self, const void* desc, allocator, pso, text, static_cast(hr)); if (FAILED(hr)) return hr; Wrapper* child = wrap(list, list_kind); + if (!child) { + list->Release(); + return E_OUTOFMEMORY; + } child->own().list_device = self; *out = child; return S_OK; @@ -4460,6 +4505,11 @@ HRESULT publish_placed_buffer(Wrapper* self, void* address, const D3D12_RESOURCE ID3D12Resource* resource, bool aliased, x2w_budget::Ticket* backing_budget, void** out) { Wrapper* w = wrap(resource, resource_kind); + if (!w) { + if (x2w_startup::linear_buffer_mode() != x2w_startup::LinearBufferMode::off) linear_buffers().discard(resource); + resource->Release(); + return E_OUTOFMEMORY; + } if (release_retired_enabled()) w->own().retire_never = static_cast(RetireNever::buffer); w->own().title_memory = address; const ResourceInfo record{*desc, desc->Width, aliased ? Placement::aliased_buffer : Placement::copied_buffer, self, initial_state}; @@ -4530,6 +4580,10 @@ HRESULT __stdcall device_place_resource_x(Wrapper* self, void* address, const D3 if (FAILED(texture_hr)) return texture_hr; x2w_startup::mark_packed_stand_in(created, desktop_format(desc->Format)); Wrapper* w = wrap(created, resource_kind); + if (!w) { + created->Release(); + return E_OUTOFMEMORY; + } w->own().budget = x2w_budget::committed(device_of(self), created, props.Type); w->own().title_memory = address; note_resource(w, desc, 0); @@ -5353,6 +5407,12 @@ extern "C" __declspec(dllexport) std::size_t x2w_d3d12_view_census_line(char* ou return view_census_line(out, capacity); } +// Fixture-only: the next `count` wrapper allocations fail as an exhausted heap would (#2653). +extern "C" __declspec(dllexport) void x2w_d3d12_fail_wraps(LONG count) +{ + InterlockedExchange(&wraps_to_fail, count); +} + // Fixture probe (startup_resource_retire): what still names a resource of the class by its raw desktop pointer, how many // resources the open recording of a list moved out of COMMON, and how many it holds. Counts entries only. struct RetireProbe { @@ -5619,6 +5679,7 @@ HRESULT __stdcall device_create_compute_pipeline_x(Wrapper*, const D3D12_COMPUTE static_cast(desc->CS.BytecodeLength), desc->NodeMask, desc->Flags, extra0, extra1, text, bytes); if (kind_for(*iid) != pipeline_kind) return E_NOINTERFACE; *out = wrap(nullptr, pipeline_kind); + if (!*out) return E_OUTOFMEMORY; auto* pipeline = static_cast(*out); note_pipeline(pipeline, 62, nullptr, desc, sizeof(*desc)); note_compute_binding_pipeline(pipeline, *desc); @@ -5671,6 +5732,10 @@ HRESULT __stdcall device_create_pipeline_stream_x(Wrapper*, const D3D12_PIPELINE log("x2w-render stream pipeline -> %s%s", real_pipeline ? "REAL desktop pipeline" : "placeholder: ", real_pipeline ? "" : why); } *out = wrap(real_pipeline, pipeline_kind); + if (!*out) { + if (real_pipeline) real_pipeline->Release(); + return E_OUTOFMEMORY; + } static_cast(*out)->own().compute_pipeline = real_pipeline && compute; static_cast(*out)->own().pipeline_root = pipeline_root; static_cast(*out)->own().indirect_graphics = graphics; @@ -5729,6 +5794,7 @@ HRESULT __stdcall device_create_pipeline_placeholder(Wrapper*, const void* desc, } if constexpr (N == 67) publish_compute_request(desc); *out = wrap(nullptr, pipeline_kind); + if (!*out) return E_OUTOFMEMORY; note_pipeline(static_cast(*out), N, nullptr, desc, 0x300); return S_OK; } @@ -5756,6 +5822,7 @@ HRESULT __stdcall device_create_derived_pipeline(Wrapper*, void* base, UINT coun w ? kind_names[w->own().kind] : "not a wrapper", count, bytes, text); } *out = wrap(nullptr, pipeline_kind); + if (!*out) return E_OUTOFMEMORY; note_pipeline(static_cast(*out), 55, base, desc, bytes_in_patches); return S_OK; } @@ -5805,6 +5872,10 @@ HRESULT create_committed(int slot, Wrapper* self, const D3D12_HEAP_PROPERTIES* p if (FAILED(hr)) return hr; x2w_startup::mark_packed_stand_in(resource, desktop_format(desc->Format)); Wrapper* w = wrap(resource, resource_kind); + if (!w) { + resource->Release(); // title_memory came from the title's allocator, which has no free hook here + return E_OUTOFMEMORY; + } w->own().budget = x2w_budget::committed(device_of(self), resource, props->Type); w->own().title_memory = title_memory; retire_set_class(w, *props, flags, copy, title_memory); @@ -6406,9 +6477,14 @@ void x2w_startup::attach_device(ID3D12Device* device, void** wrapped) { static const bool ready = (build_tables(), true); (void)ready; + Wrapper* const candidate = wrap(device, device_kind); + *wrapped = candidate; + if (!candidate) { + device->Release(); + return; + } + the_device = candidate; removal_device = device; - the_device = wrap(device, device_kind); - *wrapped = the_device; } HRESULT x2w_startup::resolve_placed_build(void* guest_device, UINT64 dest, UINT64 scratch, @@ -6491,7 +6567,8 @@ HRESULT x2w_d3d12_permissive_create_device(IUnknown* adapter, const void* parame log("x2w-d3d12 D3D12XboxCreateDevice adapter=%p params=[%s] riid=%s -> 0x%08lx build=%s", static_cast(adapter), block, text, static_cast(hr), x2w_build_rev); if (FAILED(hr)) return hr; - if (debug) device->QueryInterface(IID_PPV_ARGS(&info_queue)); x2w_startup::attach_device(device, out); + if (!*out) return E_OUTOFMEMORY; + if (debug) device->QueryInterface(IID_PPV_ARGS(&info_queue)); return S_OK; } diff --git a/src/startup_stubs/placed_build.h b/src/startup_stubs/placed_build.h index a8967cbe4..c64520a24 100644 --- a/src/startup_stubs/placed_build.h +++ b/src/startup_stubs/placed_build.h @@ -3,7 +3,8 @@ #include namespace x2w_startup { -// Takes ownership of one reference to the desktop device chosen by the caller. +// Takes ownership of one reference to the desktop device chosen by the caller. *wrapped is null +// when the wrapper cannot be allocated; the reference is released then. void attach_device(ID3D12Device* device, void** wrapped); // Internal desktop build preparation. The caller retains the registered resources diff --git a/tests/startup_wrap_allocation.cpp b/tests/startup_wrap_allocation.cpp new file mode 100644 index 000000000..6aa966ce2 --- /dev/null +++ b/tests/startup_wrap_allocation.cpp @@ -0,0 +1,178 @@ +// #2653: when the D3D12 stand-in cannot allocate an object wrapper, the slot that creates the object returns +// E_OUTOFMEMORY with a null output instead of writing through a null pointer. The fixture-only export +// x2w_d3d12_fail_wraps makes the next wrapper allocations fail; each slot is then called once armed and once +// normally. +// +// startup_wrap_allocation [control] (X2W_D3D12_PERMISSIVE=1 X2W_D3D12_DEBUG=0) +// "control" never arms the failure, so every armed expectation must fail and the fixture must print FAIL. +#include + +#include +#include +#include + +#include +#include +#include + +using Microsoft::WRL::ComPtr; + +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); +extern "C" __declspec(dllimport) void x2w_d3d12_fail_wraps(LONG count); + +namespace { + +bool control; +int failures; + +template +HRESULT invoke(IUnknown* object, unsigned slot, Args... args) +{ + using Call = HRESULT (WINAPI*)(IUnknown*, Args...); + return reinterpret_cast((*reinterpret_cast(object))[slot])(object, args...); +} + +void arm() +{ + if (!control) x2w_d3d12_fail_wraps(1); +} + +// One creation: armed it must return E_OUTOFMEMORY and leave the output null; then it must succeed. +template +void check(const char* name, Create create) +{ + ComPtr object; + arm(); + HRESULT hr = create(object.ReleaseAndGetAddressOf()); + x2w_d3d12_fail_wraps(0); + const bool refused = hr == E_OUTOFMEMORY && !object; + if (!refused) { + std::printf("FAIL: %s with the wrapper allocation failing returned 0x%08lx and %s output\n", name, + static_cast(hr), object ? "a non-null" : "a null"); + ++failures; + } + hr = create(object.ReleaseAndGetAddressOf()); + if (FAILED(hr) || !object) { + std::printf("FAIL: %s afterwards returned 0x%08lx\n", name, static_cast(hr)); + ++failures; + return; + } + if (refused) std::printf("%s: E_OUTOFMEMORY with a null output, then S_OK\n", name); +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc > 2 || (argc == 2 && std::strcmp(argv[1], "control"))) return 2; + control = argc == 2; + + ComPtr factory; + ComPtr adapter; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory))) || FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)))) + return 77; + std::array parameters{}; + + // Device creation itself: the desktop device reference is released and the output stays null. + ComPtr device; + check("D3D12XboxCreateDevice", [&](IUnknown** out) { + return D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), reinterpret_cast(out)); + }); + if (FAILED(D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), + reinterpret_cast(device.GetAddressOf()))) || !device) { + std::puts("FAIL: no device to continue with"); + return 3; + } + + // Slot 55, derived pipeline: the placeholder path of the reported stop. + check("Device::slot55 derived pipeline", [&](IUnknown** out) { + return invoke(device.Get(), 55, static_cast(nullptr), 0u, static_cast(nullptr), + &__uuidof(ID3D12PipelineState), reinterpret_cast(out)); + }); + + // Slot 8, command queue: a desktop queue is created before the wrapper. + const D3D12_COMMAND_QUEUE_DESC queue{D3D12_COMMAND_LIST_TYPE_DIRECT}; + check("Device::CreateCommandQueue", [&](IUnknown** out) { + return invoke(device.Get(), 8, &queue, &__uuidof(ID3D12CommandQueue), reinterpret_cast(out)); + }); + + // A failed device creation must leave the previously published device visible to its children. + if (!control) { + ComPtr existing_queue; + HRESULT hr = invoke(device.Get(), 8, &queue, &__uuidof(ID3D12CommandQueue), + reinterpret_cast(existing_queue.GetAddressOf())); + if (FAILED(hr) || !existing_queue) return 3; + + ComPtr second_device; + arm(); + hr = D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), + reinterpret_cast(second_device.GetAddressOf())); + x2w_d3d12_fail_wraps(0); + if (hr != E_OUTOFMEMORY || second_device) { + std::puts("FAIL: second device allocation did not return E_OUTOFMEMORY and a null output"); + ++failures; + } + ComPtr parent; + hr = existing_queue->GetDevice(__uuidof(ID3D12Device), reinterpret_cast(parent.GetAddressOf())); + if (FAILED(hr) || parent.Get() != device.Get()) { + std::puts("FAIL: failed device creation changed the existing queue's device"); + ++failures; + } + } + + // Slot 16, root signature: a desktop root signature is created before the wrapper. + ComPtr blob; + const D3D12_ROOT_SIGNATURE_DESC empty{}; + if (FAILED(D3D12SerializeRootSignature(&empty, D3D_ROOT_SIGNATURE_VERSION_1, &blob, nullptr))) return 3; + check("Device::CreateRootSignature", [&](IUnknown** out) { + return invoke(device.Get(), 16, 0u, blob->GetBufferPointer(), blob->GetBufferSize(), &__uuidof(ID3D12RootSignature), + reinterpret_cast(out)); + }); + + // Slot 14, descriptor heap: memory of the stand-in's own may back the heap before the wrapper. + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 backing, bytes; + } heap{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 4}, 0, 0}; + check("Device::CreateDescriptorHeap", [&](IUnknown** out) { + return invoke(device.Get(), 14, &heap, &__uuidof(ID3D12DescriptorHeap), reinterpret_cast(out)); + }); + + // Slot 9, command allocator: the shared creation path (create_slot) wraps what desktop returned. + check("Device::CreateCommandAllocator", [&](IUnknown** out) { + return invoke(device.Get(), 9, D3D12_COMMAND_LIST_TYPE_DIRECT, &__uuidof(ID3D12CommandAllocator), + reinterpret_cast(out)); + }); + + // Slot 73, command list on that allocator: a desktop list is created before the 64 KiB list wrapper. + ComPtr allocator; + if (FAILED(invoke(device.Get(), 9, D3D12_COMMAND_LIST_TYPE_DIRECT, &__uuidof(ID3D12CommandAllocator), + reinterpret_cast(allocator.GetAddressOf())))) + return 3; + const std::array list_desc{D3D12_COMMAND_LIST_TYPE_DIRECT}; + check("Device::slot73 command list", [&](IUnknown** out) { + return invoke(device.Get(), 73, static_cast(list_desc.data()), static_cast(allocator.Get()), + static_cast(nullptr), &__uuidof(ID3D12GraphicsCommandList), reinterpret_cast(out)); + }); + + // Slot 127, committed resource: a desktop buffer is created before the wrapper. + const D3D12_HEAP_PROPERTIES props{D3D12_HEAP_TYPE_DEFAULT}; + D3D12_RESOURCE_DESC buffer{}; + buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + buffer.Width = 65536; + buffer.Height = buffer.DepthOrArraySize = buffer.MipLevels = 1; + buffer.SampleDesc.Count = 1; + buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + check("Device::slot127 committed resource", [&](IUnknown** out) { + return invoke(device.Get(), 127, &props, 0u, &buffer, 0u, static_cast(nullptr), + static_cast(nullptr), 0u, static_cast(nullptr), &__uuidof(ID3D12Resource), + reinterpret_cast(out)); + }); + + if (failures) { + std::printf("FAIL: %d check(s)\n", failures); + return 1; + } + std::puts("PASS"); + return 0; +} From f4c6998ad6a82d6ec80d8a1bb0b2b350b28386c5 Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:10:41 +0100 Subject: [PATCH 044/240] startup: lower one slot 57 scalar load in a pre-exchange execz block (#2660) A pre-exchange s_cbranch_execz block may hold one s_buffer_load_dword whose result is live after the join, when EXEC there comes from s_mov_b64 exec, -1 then v_cmpx_gt_u32_e32 of a wave-uniform SGPR bound against the proven thread index, with no EXEC write or branch target in between. The guest runs the block for the whole wave when any lane is active, so the HLSL computes wave_any = (tid & ~63u) < bound at the compare, branches around the block only when the wave is empty, and gives the loaded word to every lane of a wave that has an active lane. An empty wave issues no load and keeps the previous value. Vector writes in the block stay predicated per lane. Other compares, non-uniform bounds or offsets, s_load_dword, wider loads and a second live scalar stay refused. AI-assisted. --- docs/experiments.md | 22 ++++- tests/startup_mesh57_skeleton_check.py | 125 +++++++++++++++++++++++++ tools/startup/gfx2hlsl.py | 87 ++++++++++++++++- 3 files changed, 228 insertions(+), 6 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 4dd6c5d84..eb8ef6869 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9719,7 +9719,27 @@ vertex red. The draw checks a vertex in the upper half of a partially active wave and vertices in a second, empty wave that retain the previous value. It also compiles a per-lane branch and checks its different image. The proof requires a straight path from the count exchange and an immediate EXEC -restore. Scalar memory operations in the skipped region remain unsupported. +restore. + +Between the group-index and count exchanges, one forward EXEC-zero block can +contain a single `s_buffer_load_dword` whose SGPR result is live at the join. +Full EXEC followed by `v_cmpx_gt_u32_e32` must select the proven thread indices +below a wave-uniform SGPR bound. The translator evaluates +`(tid & ~63u) < bound` at the compare and branches around the load when the +guest wave is empty. A mixed wave gets the loaded word in every lane. Vector +instructions inside the block still follow per-lane EXEC. The proof requires a +wave-uniform address and a defined, wave-uniform previous value. It refuses +other scalar instructions inside the block, wider loads, non-buffer scalar +loads, stores, atomics and branches into the block. + +The slot 57 skeleton `draw` fixture uses bound 6 and vertices from threads 39 +and 5 in the mixed wave. Their flat red is 255, and only thread 5 gets green +255 from the lane-predicated write. The empty wave keeps red 64 and green 0. +Its byte address is 736, beyond the 512 bytes of input and the renderer's +80-byte trace padding. The CPU reference reads byte 480 +only for the mixed wave, reuses that word across its lanes, then rasterizes +the triangles. Swapping the two waves' red values in the reference must +change every covered pixel. The `startup_mesh57_formatted_load_{warp,hardware}` tests use one `buffer_load_format_x` to set vertex red. The fixture supplies descriptor word 3 diff --git a/tests/startup_mesh57_skeleton_check.py b/tests/startup_mesh57_skeleton_check.py index e4da014b7..4ddf5a74e 100644 --- a/tests/startup_mesh57_skeleton_check.py +++ b/tests/startup_mesh57_skeleton_check.py @@ -139,6 +139,49 @@ def masked_vertex_red(): GROUP_END = MESH.index('05000006') + 1 PRIMITIVE_EXPORT = MESH.index('f8000941') +WAVE_LOAD_ASM = """s_mov_b32 s40, 0x3e808081 +s_lshl_b32 s41, s6, 8 +s_mov_b32 s42, 6 +v_mov_b32 v7, 0 +s_mov_b64 exec, -1 +v_cmpx_gt_u32_e32 s42, v0 +s_mov_b32 s42, 0 +s_cbranch_execz 4 +s_buffer_load_dword s40, s[16:19], s41 offset:0x1e0 +v_mov_b32 v7, 1.0 +s_waitcnt lgkmcnt(0) +s_mov_b64 exec, -1""" +WAVE_LOAD_PREFIX = 'bea803ff 3e808081 8f298806 beaa0386 7e0e0280 befe04c1 7da8002a beaa0380' +WAVE_LOAD_BODY = 'f4200a08 520001e0 7e0e02f2 bf8cc07f' + + +def wave_load_mesh(prefix=WAVE_LOAD_PREFIX, body=WAVE_LOAD_BODY, *, exports='7e280228 7e2a0307'): + """Insert the scalar load before the count exchange and export its value as vertex red.""" + body = body.split() + before = MESH.index('be8d0308') + wait = MESH.index('bf8c3f70') + return (MESH[:before] + prefix.split() + [branch(0xbf88, 0, len(body) + 1)] + body + ['befe04c1'] + + MESH[before:wait + 1] + exports.split() + MESH[wait + 1:]) + + +WAVE_LOAD_MESH = wave_load_mesh() +WAVE_LOAD_REFUSAL = 'slot 57 mesh: s_cbranch_execz skips code with effects outside active lanes' +WAVE_LOAD_REFUSALS = ( + ('different EXEC compare', wave_load_mesh(WAVE_LOAD_PREFIX.replace('7da8002a', '7d28002a'))), + ('missing full EXEC reset', wave_load_mesh(WAVE_LOAD_PREFIX.replace('befe04c1', 'bf800000'))), + ('different compare index', wave_load_mesh(WAVE_LOAD_PREFIX.replace('7da8002a', '7da80e2a'))), + ('EXEC write between compare and branch', wave_load_mesh(WAVE_LOAD_PREFIX.replace('beaa0380', 'befe04c1'))), + ('branch into load block', wave_load_mesh('bf840009 ' + WAVE_LOAD_PREFIX)), + ('branch to the EXEC-zero instruction', wave_load_mesh('bf840008 ' + WAVE_LOAD_PREFIX)), + ('second live scalar write', + wave_load_mesh(body=WAVE_LOAD_BODY + ' beab0386', exports='7e280228 7e2a022b')), + ('ordinary SMEM load', wave_load_mesh(body=WAVE_LOAD_BODY.replace('f4200a08', 'f4000a05'))), + ('wider SMEM load', wave_load_mesh(body=WAVE_LOAD_BODY.replace('f4200a08', 'f4240a08'))), + ('buffer store', wave_load_mesh(body=WAVE_LOAD_BODY + ' f4600a08 520001e0')), + ('buffer atomic', wave_load_mesh(body=WAVE_LOAD_BODY + ' e0c81000 80040700')), + ('dead scalar result', wave_load_mesh(exports='7e2a0307')), +) + def count_entry_red(*extra_words): wait = MESH.index('bf8c3f70') @@ -398,6 +441,26 @@ def controls(): expect(what + ' uses forward block dispatch', ('if (pc ==' in text, '[loop]' in text), (True, False)) expect(what + ' guards the position export', bool(re.search( r'if \(exec & 1\) \{[^\n]*o\.pos = [^\n]*mesh_vertex = true;', text)), True) + with tempfile.TemporaryDirectory() as tmp: + key, result = request(tmp, WAVE_LOAD_MESH) + expect('pre-exchange wave load translates', result, 'ok') + if result == 'ok': + text = (Path(tmp) / ('%016x.ms57.hlsl' % key)).read_text() + expect('the branch uses the wave predicate captured at the compare', + ('wave_any = (tid & ~63u) < ' in text, 'pc = (!wave_any) ?' in text), (True, True)) + expect('the scalar buffer read is inside a branched fall-through', + bool(re.search(r'\[branch\] if \(pc == \d+\) \{[^}]*s40 = [^\n]*\.Load\(', text)), True) + for what, mesh in WAVE_LOAD_REFUSALS: + expect(what, request(tmp, mesh)[1], 'unsupported: ' + WAVE_LOAD_REFUSAL) + # The accepted mesh opcodes cannot produce a lane-varying numeric SGPR here. + # Inject that analysis fact at the Stage boundary to exercise the uniformity refusal. + from unittest.mock import patch + + uniform_source = G.Stage.uniform_source + with patch.object(G.Stage, 'uniform_source', lambda stage, token: token != 's42' and uniform_source(stage, token)): + expect('non-uniform wave load bound', request(tmp, WAVE_LOAD_MESH)[1], 'unsupported: ' + WAVE_LOAD_REFUSAL) + with patch.object(G.Stage, 'uniform_source', lambda stage, token: token != 's41' and uniform_source(stage, token)): + expect('unproven wave load address', request(tmp, WAVE_LOAD_MESH)[1], 'unsupported: ' + WAVE_LOAD_REFUSAL) with tempfile.TemporaryDirectory() as tmp: key, result = request(tmp, FORMATTED_MESH) expect('formatted mesh translates', result, 'ok') @@ -476,6 +539,9 @@ def binary(mc): shift = mesh.replace('v_cmpx_gt_i32 s14, v0', SHIFT_ASM + '\nv_cmpx_gt_i32 s14, v0') shift = shift.replace('exp pos0', 'v_mov_b32 v20, v7\nexp pos0') expect('scalar shift mesh words match llvm-mc', assemble(mc, shift), SHIFT_MESH) + wave_load = mesh.replace('s_mov_b32 s13, s8', WAVE_LOAD_ASM + '\ns_mov_b32 s13, s8') + wave_load = wave_load.replace('exp pos0', 'v_mov_b32 v20, s40\nv_mov_b32 v21, v7\nexp pos0') + expect('pre-exchange wave load words match llvm-mc', assemble(mc, wave_load), WAVE_LOAD_MESH) # ---- draw: four triangles in a 32x32 target, vertices stored out of order ---------------------- @@ -537,6 +603,63 @@ def rasterise(points, colours, indices, verts, prims): return image +def draw_wave_load(directory, renderer, adapter): + key, result = request(directory, WAVE_LOAD_MESH) + expect('pre-exchange wave load compiles', result, 'ok') + if result != 'ok': + return 0 + base = Path(directory) / ('%016x' % key) + points, colours, indices = geometry() + # Provoking threads 39 and 5 share the mixed wave; threads 67 and 70 are + # in the empty wave. Every vertex keeps its original low-four-bit slot. + triangles = [tuple(slot + wave for slot in tri) for tri, wave in zip(indices, (32, 0, 64, 64))] + words = [a | b << 10 | c << 20 for a, b, c in triangles] + data = bytearray(buffer(points, colours, words)) + struct.pack_into(' 0, True) + path = Path(directory) / 'wave-load.bin' + for label, image, status, mismatches in ( + ('wave load', correct, 0, 0), ('swapped wave load selection', swapped, 1, different)): + path.write_bytes(bytes(constants) + bytes(data) + b'\xcd' * 80 + b''.join(map(bytes, image))) + run = subprocess.run([renderer, adapter, '--mesh-indexed', base.with_suffix('.ms57.cso'), + base.with_suffix('.ps57.cso'), path], capture_output=True, text=True) + if run.returncode == 77: + print(run.stdout + run.stderr) + return 77 + expect(label, (run.returncode, f'pixels=1024 mismatches={mismatches}' in run.stdout), (status, True)) + return 0 + + def publish_request(directory, publisher, adapter): ms, ps = code(MESH), code(PIXEL) (directory / 'ms.bin').write_bytes(ms) @@ -649,6 +772,8 @@ def draw(dxc, renderer, adapter, publisher=None): print(r.stdout + r.stderr) return 77 expect('draw of ' + what, (r.returncode, 'pixels=1024 mismatches=0' in r.stdout), (0, True)) + if publisher is None: + return draw_wave_load(tmp, renderer, adapter) return 0 diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index e6b2ca14f..8d4afc39a 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -1396,7 +1396,7 @@ def mesh_run(ins, at, what, patterns, env): VCC_KEYS = {'vcc', 'vcc_hi'} -def mesh_skeleton(ins, vcc_branches, wave_limits): +def mesh_skeleton(ins, vcc_branches, wave_limits, wave_loads): """Prove the one accepted group-memory shape of a slot 57 mesh program and replace it by per-thread instructions. Accepted shape, in program order (anything else is refused with its own message): @@ -1523,6 +1523,33 @@ def dead_count_entry_scalar(i): raise Unsupported(exchange_branch_refusal) first_post_count_branch = next((i for i in edges if i >= b_end), None) shift_branch = None + load_compare = None + execz_effects = 'slot 57 mesh: s_cbranch_execz skips code with effects outside active lanes' + + def live_at_join(reg, join): + pending, seen = [join], set() + while pending: + i = pending.pop() + if i >= len(ins) or i in seen: + continue + seen.add(i) + if i == count_at: + if reg in (env['prims'], env['verts']): + return True + if reg != env['b_tmp']: + pending.append(b_end) + continue + name, asm = ins[i][2:] + reads, writes, _ = scalar_effects(name, asm) + if reg in reads: + return True + if reg not in writes: + if i in edges: + pending.append(edges[i]) + if name not in ('s_branch', 's_endpgm'): + pending.append(i + 1) + return False + for source, target in edges.items(): if ins[source][2] == 's_cbranch_execz': # A single scalar shift followed by a full EXEC restore has a separate wave-level proof below. @@ -1530,6 +1557,24 @@ def dead_count_entry_scalar(i): and ins[source + 1][2] == 's_lshl_b32' and ins[target][3] == 's_mov_b64 exec, -1'): shift_branch = source continue + if a_end <= source < target < count_at and load_compare is None: + loads = [i for i in range(source + 1, target) if ins[i][2] == 's_buffer_load_dword'] + if len(loads) == 1: + load = loads[0] + compare = source - 1 + while compare > a_end and not writes_exec(ins[compare][2], parse(ins[compare][3])[1]): + compare -= 1 + match = re.fullmatch(r'v_cmpx_gt_u32_e32 (s\d+), v(\d+)', ins[compare][3]) + dst = parse(ins[load][3])[1][0] + if (compare <= a_end or ins[compare - 1][3] != 's_mov_b64 exec, -1' or not match + or targets.intersection(range(compare, target)) + or any(i != load and not (no_effect(i) or lane_only(i)) + for i in range(source + 1, target)) + or not re.fullmatch(r's\d+', dst) or not live_at_join(dst, target)): + raise Unsupported(exchange_branch_refusal if target == count_at else execz_effects) + load_compare, load_bound, load_thread = compare, match[1], int(match[2]) + wave_loads[ins[source][0]] = (ins[compare][0], load_bound, ins[load][0], dst) + continue # The model skips per lane, while the guest skips per wave. The difference is invisible when # lanes with clear EXEC can only bypass predicated writes before the paths meet. A skipped # s_branch may land at the execz target or past it over instructions without effect (the @@ -1540,7 +1585,7 @@ def dead_count_entry_scalar(i): or (name == 's_branch' and edges[i] >= target and all(no_effect(k) for k in range(target, edges[i]))) or lane_only(i) or (source == count_entry_branch and dead_count_entry_scalar(i))): - raise Unsupported('slot 57 mesh: s_cbranch_execz skips code with effects outside active lanes') + raise Unsupported(execz_effects) elif any(ins[i][2] == 'exp' for i in range(source + 1, target)): raise Unsupported('slot 57 mesh: a branch bypasses an export') @@ -1691,6 +1736,10 @@ def dead_count_entry_scalar(i): if mask is not None or mesh_vregs(ops) & stale: raise Unsupported(exchange_branch_refusal) mask = 'count_entry' + elif index == load_compare: + if mask is not None or thread != load_thread or load_thread in stale: + raise Unsupported(execz_effects) + mask = 'wave_load' elif base_name.startswith('v_cmpx'): count = {env['verts']: 'verts', env['prims']: 'prims'}.get(ops[0] if ops else None) if (base_name != 'v_cmpx_gt_i32' or not after or mask is not None or count is None @@ -1795,7 +1844,8 @@ def __init__(self, pipe, kind, code, refusals=None, decoded=None): if kind == 'ms': self.mesh_vcc_branches = {} self.mesh_wave_limits = {} - self.ins = mesh_skeleton(self.ins, self.mesh_vcc_branches, self.mesh_wave_limits) + self.mesh_wave_loads = {} + self.ins = mesh_skeleton(self.ins, self.mesh_vcc_branches, self.mesh_wave_limits, self.mesh_wave_loads) # A loop header is translated before the back edges into it, so whether a back edge brings the symbol kept # there is known only afterwards: translate again with that register read at run time or refused there. A # register only moves from kept to 'run' to 'refuse', so this ends. @@ -2551,6 +2601,10 @@ def translate(self): refusals = getattr(self, 'refusals', None) # unit probes build a Stage without __init__ vcc_branches = getattr(self, 'mesh_vcc_branches', {}) wave_limits = getattr(self, 'mesh_wave_limits', {}) + wave_loads = getattr(self, 'mesh_wave_loads', {}) + wave_load_compares = {compare: bound for compare, bound, _, _ in wave_loads.values()} + wave_load_sites = {load for _, _, load, _ in wave_loads.values()} + execz_effects = 'slot 57 mesh: s_cbranch_execz skips code with effects outside active lanes' vcc_compares = set().union(*vcc_branches.values()) try: self.calculated_pc = calculated_pc_proof(self.ins, getattr(self, 'kind', None)) @@ -2765,6 +2819,17 @@ def translate(self): if off in refused: raise Unsupported(refused[off]) base = re.sub(r'_e(32|64)$', '', name) + if off in wave_load_compares: + bound = wave_load_compares[off] + if not self.uniform_source(bound) or int(bound[1:]) not in self.defined_uniform_s: + raise Unsupported(execz_effects) + # Capture the bound at the compare, before any intervening SGPR write. + self.emit('wave_any = (tid & ~63u) < %s;' % self.u(bound)) + if off in wave_load_sites: + offset = smem_offset(parse(asm)[1][2]) + if not self.uniform_source(offset) or ( + re.fullmatch(r's\d+', offset) and int(offset[1:]) not in self.defined_uniform_s): + raise Unsupported(execz_effects) if off in vcc_compares and all( not mesh_vregs([tok]) and self.uniform_source(tok) for tok in parse(asm)[1][1:] @@ -2772,7 +2837,13 @@ def translate(self): uniform_vcc_compares.add(off) if base.startswith('s_cbranch_'): cond = base[10:] - cond_uniform = (cond in ('scc0', 'scc1') and self.scc_uniform) or off in wave_limits + if off in wave_loads: + dst = wave_loads[off][3] + if not self.uniform_source(dst) or int(dst[1:]) not in self.defined_uniform_s: + raise Unsupported(execz_effects) + self.u(dst) # declare the variable; refuses a symbol with no run-time value + cond_uniform = ((cond in ('scc0', 'scc1') and self.scc_uniform) + or off in wave_limits or off in wave_loads) if off in vcc_branches: if not vcc_branches[off] <= uniform_vcc_compares: raise Unsupported('slot 57 mesh: %s on a wave-wide condition is not covered' % name) @@ -2788,6 +2859,8 @@ def translate(self): term = self.one(name, asm) if off in wave_limits: term = ('branch', '(tid & ~63u) >= %du' % wave_limits[off], term[2]) + if off in wave_loads: + term = ('branch', '!wave_any', term[2]) except Unsupported as reason: if refusals is None: if not hasattr(reason, 'instruction'): @@ -6757,13 +6830,15 @@ def goto(off): raise Unsupported('branch into the middle of a block (+0x%x)' % off) return index[off] out.append(' uint pc = 0;') + wave_load_blocks = {off + n for off, n, _, _ in self.ins if off in getattr(self, 'mesh_wave_loads', {})} if loops: out.append(' [loop] for (uint guard = 0; guard < 65536 && pc != 0xffffu; ++guard) {') for i, (off, lines, term) in enumerate(self.blocks): if off == getattr(self, 'mesh_allocation_block', None): out.append(' {') else: - out.append(' %sif (pc == %d) {' % ('else ' if loops and i else '', i)) + attribute = '[branch] ' if off in wave_load_blocks else '' + out.append(' %s%sif (pc == %d) {' % ('else ' if loops and i else '', attribute, i)) out += [' ' + line for line in lines] nxt = i + 1 if i + 1 < len(self.blocks) else 0xffff if not term: @@ -6791,6 +6866,8 @@ def declarations(self): if getattr(self, 'spill_slots', None): lines.append(' uint %s;' % ', '.join('sp%d_%d = 0' % k for k in sorted(self.spill_slots))) lines.append(' uint vcc = 0, exec = 1, m0 = 0, a = 0, w = 0; bool scc = false; float4 t = 0;') + if getattr(self, 'mesh_wave_loads', {}): + lines.append(' bool wave_any = false;') if getattr(self, 'used_atomic', None): if 'uint' in self.used_atomic: lines.append(' uint ao = 0;') From edbc8b5ec1addea610442f638fd093078130e7f7 Mon Sep 17 00:00:00 2001 From: SimSalabimse <83839581+SimSalabimse@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:15:50 +0100 Subject: [PATCH 045/240] compute: accept gfx1013 image_atomic_umin on R32_UINT (#2662) gfx1013 image atomics covered add, umax and cmpswap only; M200-01 A stops at unsigned image minimum. Allow umin with the shared gfx1030 InterlockedMin lowering, keep it unsigned, and extend the gfx1013 fixture (high-bit operand 0x80000011 vs smin). Other ops stay refused. Refs #2618 Co-authored-by: Cursor Agent Co-authored-by: SimSalabimse Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- docs/experiments.md | 18 ++++---- tests/compute_image_atomics_gfx1013_check.py | 45 +++++++++++++------- tests/compute_store_check.py | 6 +-- tools/compute_store_aot.py | 7 +-- 4 files changed, 46 insertions(+), 30 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index eb8ef6869..691a34a15 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -4550,19 +4550,21 @@ python3 -B tests/compute_mimg_float_store_d16_check.py --binary llvm-mc-15 llvm- ### gfx1013 2D image atomics -The gfx1013 profile accepts `image_atomic_add`, `image_atomic_umax` and -`image_atomic_cmpswap` on a 2D `R32_UINT` UAV at mip 0 and lowers them with -the gfx1030 image atomic lowering described below. The emitted HLSL is -identical for both targets. The atomics return nothing: `glc` and the other -cache, `a16`, `d16`, `tfe`, `lwe` and `r128` flags stay refused, as on gfx1030. -On gfx1013 every other image atomic (`sub`, `and`, `or`, `xor`, `umin`, +The gfx1013 profile accepts `image_atomic_add`, `image_atomic_umin`, +`image_atomic_umax` and `image_atomic_cmpswap` on a 2D `R32_UINT` UAV at mip 0 +and lowers them with the gfx1030 image atomic lowering described below. The +emitted HLSL is identical for both targets. The atomics return nothing: `glc` +and the other cache, `a16`, `d16`, `tfe`, `lwe` and `r128` flags stay refused, as +on gfx1030. On gfx1013 every other image atomic (`sub`, `and`, `or`, `xor`, `swap`, `inc`, `dec`) is refused by name. So are the signed and float formats, a nonzero UAV mip, array and 3D dimensions, a second atomic and a store to the -same image. +same image. `umin` stays unsigned (`InterlockedMin` without `asint`); the +minmax operand `0x80000011` makes unsigned ordering differ from signed `smin` +on the CPU reference (M200-01 A). The fixtures are the gfx1030 cases with the gfx1013 profile. One add writes unique texels, a contended add sends two lanes to each texel of one row, and a -`umax` and a `cmpswap` each write unique texels. Each runs with one and two +`umin`, a `umax` and a `cmpswap` each write unique texels. Each runs with one and two groups, and the readback compares all 336 words of a three-mip texture with a CPU reference, including the untouched texels and mips. For each case and group count, one mutant must mismatch at the first word its reference diff --git a/tests/compute_image_atomics_gfx1013_check.py b/tests/compute_image_atomics_gfx1013_check.py index aee7656f7..da7fca6a1 100644 --- a/tests/compute_image_atomics_gfx1013_check.py +++ b/tests/compute_image_atomics_gfx1013_check.py @@ -1,10 +1,11 @@ -"""Check gfx1013 image_atomic_add, umax and cmpswap on a 2D R32_UINT UAV. +"""Check gfx1013 image_atomic_add, umin, umax and cmpswap on a 2D R32_UINT UAV (M200-01 A). -gfx1013 takes the gfx1030 image atomic lowering for these three operations. The cases are the +gfx1013 takes the gfx1030 image atomic lowering for these four operations. The cases are the gfx1030 ones (tests/compute_store_check.py, mimg_atomic_cases) with the gfx1013 profile: the controls pin identical HLSL, the gfx1013 refusals and, with --binary, the gfx1013 machine words; --draw dispatches them on an adapter and compares every texel of a three-level texture with an -independent reference, including mutants that must mismatch. +independent reference, including mutants that must mismatch. The minmax operand is 0x80000011 so +unsigned umin/umax ordering differs from signed smin/smax on several texels. """ import argparse import os @@ -20,11 +21,12 @@ mimg_atomic_cases, mimg_atomic_reference, rejects, store_container, variant) HERE = Path(__file__).resolve().parent -ACCEPTED = ("add", "umax", "cmpswap") -SUITES = {"add": "integer", "umax": "minmax", "cmpswap": "exchange"} -FLAGS = {"add": MIMG_ATOMIC_UINT_FLAG, "umax": MIMG_ATOMIC_MINMAX_FLAGS["u"], "cmpswap": MIMG_ATOMIC_EXCHANGE_FLAG} +ACCEPTED = ("add", "umin", "umax", "cmpswap") +SUITES = {"add": "integer", "umin": "minmax", "umax": "minmax", "cmpswap": "exchange"} +FLAGS = {"add": MIMG_ATOMIC_UINT_FLAG, "umin": MIMG_ATOMIC_MINMAX_FLAGS["u"], + "umax": MIMG_ATOMIC_MINMAX_FLAGS["u"], "cmpswap": MIMG_ATOMIC_EXCHANGE_FLAG} # Every other integer image atomic the shared lowering knows, refused on gfx1013. -REFUSED_UINT = ("sub", "and", "or", "xor", "umin", "swap", "inc", "dec") +REFUSED_UINT = ("sub", "and", "or", "xor", "swap", "inc", "dec") def cases(): @@ -34,7 +36,7 @@ def cases(): for name, contended, lines, binding in mimg_atomic_cases(suite=SUITES[op]): if name.removesuffix("_contended") == op: found.append((name, op, contended, lines, binding | {"cpu": "gfx1013"})) - assert [name for name, *_ in found] == ["add", "add_contended", "umax", "cmpswap"], found + assert [name for name, *_ in found] == ["add", "add_contended", "umin", "umax", "cmpswap"], found return found @@ -52,23 +54,31 @@ def controls(): sources[name] = source value = f"{MIMG_ATOMIC_VALUE:#010x}u" assert f"InterlockedAdd(outputData[uint2(" in sources["add"] and f", {value});" in sources["add"] + assert "InterlockedMin(outputData[uint2(" in sources["umin"] and f", {value});" in sources["umin"] + assert "asint(" not in sources["umin"], "umin must stay unsigned" assert "InterlockedMax(outputData[uint2(" in sources["umax"] and f", {value});" in sources["umax"] assert "asint(" not in sources["umax"], "umax must stay unsigned" assert (f", {MIMG_ATOMIC_COMPARE:#010x}u, {MIMG_ATOMIC_REPLACEMENT:#010x}u);" in sources["cmpswap"] and sources["cmpswap"].count("InterlockedCompareStore(") == 1), sources["cmpswap"] + # High-bit unsigned ordering: the minmax operand has bit 31 set, so umin and smin differ. + assert MIMG_ATOMIC_VALUE >= 0x80000000 + _, umin_exp = mimg_atomic_reference("umin", False, 1) + _, smin_exp = mimg_atomic_reference("smin", False, 1) + assert umin_exp != smin_exp and sum(a != b for a, b in zip(umin_exp, smin_exp)) >= 1 + print("umin high-bit ordering differs from smin on the reference texture", flush=True) name, op, _, lines, binding = cases()[0] instruction = next(line for line in lines if line.startswith("image_atomic_")) for other in REFUSED_UINT: - rejects("gfx1013 image atomics require add, umax or cmpswap", lowered, + rejects("gfx1013 image atomics require add, umin, umax or cmpswap", lowered, variant(lines, ("image_atomic_add", f"image_atomic_{other}")), binding) # Signed and float formats are refused on gfx1013 before any instruction is read. - umax_lines, umax_binding = cases()[2][3], cases()[2][4] + umin_lines, umin_binding = next((lines, binding) for name, op, _, lines, binding in cases() if op == "umin") for change in ({"image_format": "R32_SINT"}, {"image_format": "R32_FLOAT", "image_float_domain": "finite-normal"}, {"image_uav_mip": 1}): - rejects("Invalid image UAV binding", lowered, umax_lines, umax_binding | change) - smin = variant(umax_lines, ("image_atomic_umax", "image_atomic_smin")) - rejects("Invalid image UAV binding", lowered, smin, umax_binding | {"image_format": "R32_SINT"}) + rejects("Invalid image UAV binding", lowered, umin_lines, umin_binding | change) + smin = variant(umin_lines, ("image_atomic_umin", "image_atomic_smin")) + rejects("Invalid image UAV binding", lowered, smin, umin_binding | {"image_format": "R32_SINT"}) for changed, diagnostic in ( (instruction + "\n" + instruction, "Unsupported image atomic target or binding"), (instruction.replace("IMG_2D", "IMG_2D_ARRAY"), "Unsupported compute instruction"), @@ -87,10 +97,10 @@ def controls(): return sources -# The two MIMG dwords of each atomic as LLVM 15 encodes them for gfx1013: opcode 17 (add), 23 (umax) -# or 16 (cmpswap) in bits 24:18, dmask in 11:8, unorm in bit 12, dim 1 (2D) in bits 5:3. +# The two MIMG dwords of each atomic as LLVM 15 encodes them for gfx1013: opcode 17 (add), 21 (umin), +# 23 (umax) or 16 (cmpswap) in bits 24:18, dmask in 11:8, unorm in bit 12, dim 1 (2D) in bits 5:3. ATOMIC_WORDS = {"add": "080144f0080e0600", "add_contended": "081144f0080e0600", - "umax": "08015cf0080e0600", "cmpswap": "081340f0080e0600"} + "umin": "080154f0080e0600", "umax": "08015cf0080e0600", "cmpswap": "081340f0080e0600"} def binary(directory, assembler, objcopy, library, sources): @@ -120,6 +130,9 @@ def mutants(op, source): if op == "add": assert source.count(f", {value});") == 1 return "subtracts instead of adds", source.replace(f", {value});", f", (0u - {value}));"), ("sub", None) + if op == "umin": + assert source.count("InterlockedMin(") == 1 + return "maximum instead of minimum", source.replace("InterlockedMin(", "InterlockedMax("), ("umax", None) if op == "umax": assert source.count("InterlockedMax(") == 1 return "minimum instead of maximum", source.replace("InterlockedMax(", "InterlockedMin("), ("umin", None) diff --git a/tests/compute_store_check.py b/tests/compute_store_check.py index 964b2447f..8848bf567 100644 --- a/tests/compute_store_check.py +++ b/tests/compute_store_check.py @@ -7805,16 +7805,16 @@ def mimg_atomic_controls(*, suite="integer"): msaa = "image_msaa_load v[14:17], v[8:10], s[24:31] dmask:0xf dim:SQ_RSRC_IMG_2D_MSAA unorm" rejects("requires an unguarded R32_UINT MSAA binding", aot.lower, variant(lines, (instruction, msaa)), MIMG_STORE_GROUP, **binding) - # gfx1013 shares this lowering for add, umax and cmpswap on R32_UINT only + # gfx1013 shares this lowering for add, umin, umax and cmpswap on R32_UINT only # (tests/compute_image_atomics_gfx1013_check.py); every other op and format stays refused there. for op, (case, case_binding) in cases.items(): gfx1013 = case_binding | {"cpu": "gfx1013"} if case_binding["image_format"] != "R32_UINT": rejects("Invalid image UAV binding", aot.lower, case, MIMG_STORE_GROUP, **gfx1013) - elif op.removesuffix("_contended") in ("add", "umax", "cmpswap"): + elif op.removesuffix("_contended") in ("add", "umin", "umax", "cmpswap"): assert aot.lower(case, MIMG_STORE_GROUP, **gfx1013) == aot.lower(case, MIMG_STORE_GROUP, **case_binding) else: - rejects("gfx1013 image atomics require add, umax or cmpswap", aot.lower, case, MIMG_STORE_GROUP, **gfx1013) + rejects("gfx1013 image atomics require add, umin, umax or cmpswap", aot.lower, case, MIMG_STORE_GROUP, **gfx1013) for case, case_binding in cases.values(): wrong_format = "R32_UINT" if case_binding["image_format"] == "R32_SINT" else "R32_SINT" rejects("Unsupported image atomic target or binding", aot.lower, case, MIMG_STORE_GROUP, diff --git a/tools/compute_store_aot.py b/tools/compute_store_aot.py index a76f40afd..037267560 100644 --- a/tools/compute_store_aot.py +++ b/tools/compute_store_aot.py @@ -878,7 +878,8 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N raise ValueError("Unknown image SRV dimension") if image_srv_dimension == "1d" and not (rgba32_float_image and image_srv_descriptor is not None): raise ValueError("1D image loads require a separate gfx1013 RGBA32 FLOAT SRV binding") - # gfx1013 takes the shared image atomic lowering on an R32_UINT UAV only (add, umax, cmpswap; see lower()). + # gfx1013 takes the shared image atomic lowering on an R32_UINT UAV only + # (add, umin, umax, cmpswap; see lower()). gfx1013_image_atomic = cpu == "gfx1013" and image_atomic_type is not None and image_format == "R32_UINT" if image_output: if ((cpu != "gfx1030" and not float_image and not gfx1013_image_atomic) @@ -2500,8 +2501,8 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N op = m["op"] signed = op in ("smin", "smax") # gfx1013 is limited to the forms its draws cover; the lowering itself is the gfx1030 one. - if cpu == "gfx1013" and op not in ("add", "umax", "cmpswap"): - raise ValueError("gfx1013 image atomics require add, umax or cmpswap") + if cpu == "gfx1013" and op not in ("add", "umin", "umax", "cmpswap"): + raise ValueError("gfx1013 image atomics require add, umin, umax or cmpswap") if (image_atomic_type != ("int" if signed else "uint") or image_float != (op in IMAGE_FLOAT_ATOMIC_OPS) or guard_span is not None or stores): raise ValueError("Unsupported image atomic target or binding") From 31bcd9ad2284ca0ce587978169482ebfe7abc051 Mon Sep 17 00:00:00 2001 From: RavenCurseBurg Date: Thu, 26 Nov 2026 09:22:54 +0800 Subject: [PATCH 046/240] tests: make explicit gradients select the mip above a MinLod floor (#2663) Co-authored-by: RavenCurseBurg <360931527+RavenCurseBurg@users.noreply.github.com> Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- tests/spirv_window/minlod.py | 2 ++ tests/spirv_window/minlod.spvasm | 2 ++ 2 files changed, 4 insertions(+) diff --git a/tests/spirv_window/minlod.py b/tests/spirv_window/minlod.py index 49119430c..50a2c4c01 100644 --- a/tests/spirv_window/minlod.py +++ b/tests/spirv_window/minlod.py @@ -9,6 +9,8 @@ ("implicit", "OpImageSampleImplicitLod %v4 %sampled %uv MinLod %one"), ("bias", "OpImageSampleImplicitLod %v4 %sampled %uv Bias|ConstOffset|MinLod %bias %offset %one"), ("grad", "OpImageSampleExplicitLod %v4 %sampled %uv Grad|MinLod %dx %dy %one"), + # On the 8x8 texture these gradients cover two texels, so they select mip 1 with a floor of 0. + ("grad-above-clamp", "OpImageSampleExplicitLod %v4 %sampled %uv Grad|MinLod %twoTexelsDx %twoTexelsDy %zero"), ("no-clamp", "OpImageSampleImplicitLod %v4 %sampled %uv"), ) diff --git a/tests/spirv_window/minlod.spvasm b/tests/spirv_window/minlod.spvasm index fd2782d60..08ee595e3 100644 --- a/tests/spirv_window/minlod.spvasm +++ b/tests/spirv_window/minlod.spvasm @@ -32,6 +32,8 @@ OpDecorate %color Location 0 %uv = OpConstantComposite %v2 %quarter %quarter %dx = OpConstantComposite %v2 %step %zero %dy = OpConstantComposite %v2 %zero %step +%twoTexelsDx = OpConstantComposite %v2 %quarter %zero +%twoTexelsDy = OpConstantComposite %v2 %zero %quarter %ix = OpConstant %int 1 %iy = OpConstant %int 0 %offset = OpConstantComposite %iv2 %ix %iy From f06646ba5c3d901302349d09e20e2e4e25c178fd Mon Sep 17 00:00:00 2001 From: SimSalabimse <83839581+SimSalabimse@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:27:27 +0100 Subject: [PATCH 047/240] startup: accept entry-prefix DPP broadcasts when a later loop exists (#2657) * startup: accept entry-prefix DPP broadcasts when a later loop exists A later uniform loop used to refuse every DPP16 quad broadcast in the same pixel stage via has_branches, even when the broadcast still ran in the entry prefix under s_wqm with EXEC unchanged (M200-01/003). Keep the blocks/exec/wqm gates so a broadcast after a branch target or with divergent EXEC stays refused. Extend the broadcast fixture with a loop case, divergent control, and the same CPU lane reference for draws. Refs #2618, #2125 Co-authored-by: SimSalabimse * startup: keep vertex DPP refusal needle for cvt_off Split the non-ps check from the entry-prefix gate so startup_gfx2hlsl_cvt_off_f32_i4_check still matches "straight-line pixel stage" while later loops stay accepted. Refs #2618 Co-authored-by: SimSalabimse * Reject DPP broadcasts when a back edge reaches the entry prefix --------- Co-authored-by: Cursor Agent Co-authored-by: SimSalabimse Co-authored-by: Royoo <3230853833@qq.com> Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- docs/experiments.md | 4 +- ...artup_gfx2hlsl_dpp_quad_broadcast_check.py | 63 ++++++++++++++++--- tools/startup/gfx2hlsl.py | 18 ++++-- 3 files changed, 68 insertions(+), 17 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 691a34a15..8fa7647e6 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15719,9 +15719,9 @@ ctest --preset release --no-tests=error -R '^cpu_aot_vex_parity$' -V ### gfx1013 pixel DPP16 quad broadcast -The pixel translator lowers `quad_perm:[k,k,k,k]` (k = 0 to 3) with full `row_mask` and `bank_mask` on `v_mov_b32` and the VOP1/VOP2 float, integer and integer-to-float forms to `QuadReadLaneAt(value, k)`. The four lanes of a pixel quad are one 2 x 2 block (lane = x & 1 | (y & 1) << 1). It is accepted only in a straight-line pixel stage that ran `s_wqm_b64 exec, exec` (or `s_wqm_b32 exec_lo, exec_lo`) with EXEC unchanged since: the entry EXEC can leave out lanes of a partly covered quad, and the guest would then read an inactive source lane while `QuadReadLaneAt` returns a helper lane's value. Without that proof the instruction is refused, as are swaps, pair broadcasts, row shifts, mirrors, DPP8, partial masks, `bound_ctrl:0`, non-VGPR sources and vertex stages. `fi:1` is accepted with the proof and changes nothing, since no source lane is disabled. A stage that holds a quad read compiles as `ps_6_0` with DXC (`X2W_DXC`, the Windows Kits `bin` folder or `PATH`), and its vertex stage as `vs_6_0`. +The pixel translator lowers `quad_perm:[k,k,k,k]` (k = 0 to 3) with full `row_mask` and `bank_mask` on `v_mov_b32` and the VOP1/VOP2 float, integer and integer-to-float forms to `QuadReadLaneAt(value, k)`. The four lanes of a pixel quad are one 2 x 2 block (lane = x & 1 | (y & 1) << 1). It is accepted in the entry straight-line prefix of a pixel stage that ran `s_wqm_b64 exec, exec` (or `s_wqm_b32 exec_lo, exec_lo`) with EXEC unchanged since: the entry EXEC can leave out lanes of a partly covered quad, and the guest would then read an inactive source lane while `QuadReadLaneAt` returns a helper lane's value. A later uniform loop or forward branch elsewhere in the same stage does not drop that proof (the M200-01/003 shape). Without the proof the instruction is refused, as are a broadcast after a branch target, after EXEC changed, or with divergent EXEC before the broadcast, swaps, pair broadcasts, row shifts, mirrors, DPP8, partial masks, `bound_ctrl:0`, non-VGPR sources and vertex stages. `fi:1` is accepted with the proof and changes nothing, since no source lane is disabled. A stage that holds a quad read compiles as `ps_6_0` with DXC (`X2W_DXC`, the Windows Kits `bin` folder or `PATH`), and its vertex stage as `vs_6_0`. -Reproduce: `ctest --preset dev --no-tests=error -R "^startup_gfx2hlsl_dpp_quad_broadcast" -V`. The controls cover the translation, every refusal and the missing `s_wqm`; the WARP and hardware draws compare all 256 pixels of two fixtures with a CPU reference, with wrong-lane and own-lane translations as failing controls. This does not establish full-game startup. +Reproduce: `ctest --preset dev --no-tests=error -R "^startup_gfx2hlsl_dpp_quad_broadcast" -V`. The controls cover the translation, every refusal, the missing `s_wqm`, the loop fixture and the divergent-EXEC control; the WARP and hardware draws compare all 256 pixels of the integer, float and loop fixtures with a CPU reference, with wrong-lane and own-lane translations as failing controls. This does not establish full-game startup. ## Startup root signature changes diff --git a/tests/startup_gfx2hlsl_dpp_quad_broadcast_check.py b/tests/startup_gfx2hlsl_dpp_quad_broadcast_check.py index db9e81b77..9c726fc01 100644 --- a/tests/startup_gfx2hlsl_dpp_quad_broadcast_check.py +++ b/tests/startup_gfx2hlsl_dpp_quad_broadcast_check.py @@ -1,4 +1,4 @@ -"""DPP16 quad broadcasts (quad_perm:[k,k,k,k]) in tools/startup/gfx2hlsl.py (#2125 item A). +"""DPP16 quad broadcasts (quad_perm:[k,k,k,k]) in tools/startup/gfx2hlsl.py (#2125 item A; M200-01/003). (no arguments) translation controls and refusals, pure Python binary assemble the pixel fixtures with llvm-mc (gfx1013) and compare the words @@ -19,12 +19,15 @@ second source is a plain VGPR, so a permuted second source or a lane-0 read through the add would differ float: the coarse derivative idiom, v_sub_f32_dpp (lane 1 minus own lane), and v_mul_f32_dpp with a negated permuted source (the modifier applies to the word the lane read) + loop: the integer broadcasts, then a uniform scalar loop (two trips) that does not touch EXEC; the exported + words match the integer reference. A later loop used to refuse the entry-prefix broadcasts (M200-01/003). Two mutated translations, one that reads lane k + 1 and one that reads the lane's own word, must fail the draw against the reference and match their own plain-Python image. Refused (the single-lane model cannot read a neighbour, or the quad may be partly off): swaps, pair broadcasts, row -shifts, mirrors, DPP8, a partial row_mask or bank_mask, fi:1 without the whole-quad proof, bound_ctrl:0, a scalar or constant source, a vertex -stage, a pixel stage after EXEC changed or with branches, and operations outside the VOP1/VOP2 tables. +shifts, mirrors, DPP8, a partial row_mask or bank_mask, fi:1 without the whole-quad proof, bound_ctrl:0, a scalar or +constant source, a vertex stage, a broadcast after a branch target, after EXEC changed, or with divergent EXEC before +the broadcast, and operations outside the VOP1/VOP2 tables. """ import re import struct @@ -98,9 +101,25 @@ def vop1(op, vdst, src0): """ % {'m': DPP} FLOAT_WORDS = (WQM + vop1(6, 5, 0) + dpp16(True, 0x4, 6, 5, 5, (1, 1, 1, 1), True) + dpp16(True, 0x8, 7, 5, 5, (0, 0, 0, 0), True, neg0=True) + export((6, 7, 5, 5))) +# Uniform scalar loop after the integer broadcasts (two trips); EXEC and the exported words are unchanged. +# s_mov_b32 s0, 0; s_add_u32 s0, s0, 1; s_cmp_lt_u32 s0, 2; s_cbranch_scc1 back to the add. +def sopp(op, simm): + return struct.pack(' 0) pixel_hlsl(kind, how) + check('loop fixture matches the integer reference image', image('loop') == image('integer')) plain = pixel_stage(vop1(6, 5, 0) + export((5, 5, 5, 5))) check('a stage without a quad read stays ps_5_1', plain.ps_profile() == 'ps_5_1') # The four lanes of the integer image are four distinct words in every quad, so a lane mix-up cannot hide. @@ -237,7 +273,13 @@ def controls(): check('refused: no s_wqm exec, exec before the broadcast', refused(sane, quad_exec=False)) check('refused: the stage translator without s_wqm', refused_in_stage(NO_WQM_WORDS)) check('refused: s_wqm into another register', refused_in_stage(OTHER_WQM_WORDS)) - check('refused: pixel stage with branches', refused(sane, branches=True)) + # A later loop in the same stage used to refuse entry-prefix broadcasts; Probe(branches=True) still + # has an empty block list, so the entry-prefix proof holds (M200-01/003). + check('entry-prefix broadcast still translates when the stage later has branches', + not refused(sane, branches=True)) + check('refused: broadcast after a branch target', refused_in_stage(AFTER_BRANCH_WORDS)) + check('refused: branch back to the broadcast entry block', refused_in_stage(ENTRY_BACKEDGE_WORDS)) + check('refused: divergent EXEC before the broadcast', refused_in_stage(DIVERGENT_WORDS)) check('control: the sane line itself translates', not refused(sane)) # fi:1 only decides what a disabled source lane returns, and the whole quad is proven active. with_fi = 'v_subrev_f32_dpp v1, v0, v0 quad_perm:[0,0,0,0]' + DPP + ' bound_ctrl:1 fi:1' @@ -250,12 +292,15 @@ def controls(): stages[0].lines == ['v256 = QuadReadLaneAt(v0, 0u);', 'v1 = U(F(v0) - F(v256));'], str(stages[0].lines)) check('refused: fi:1 without s_wqm exec, exec', refused(with_fi, quad_exec=False)) check('refused: fi:1 with EXEC no longer the entry mask', refused(with_fi, exec_known=False)) - check('refused: fi:1 in a pixel stage with branches', refused(with_fi, branches=True)) + check('fi:1 still translates when the stage later has branches', not refused(with_fi, branches=True)) check('refused: fi:1 in a vertex stage', refused(with_fi, kind='vs')) def check_binary(llvm_mc): for kind, (source, words) in FIXTURES.items(): + if kind == 'loop': + # The loop fixture's branch label is decoder text; llvm-mc needs a real symbol. + continue check('llvm-mc assembles the %s fixture to the same words' % kind, assemble(llvm_mc, source) == words) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 8d4afc39a..6031d69a6 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -3343,10 +3343,13 @@ def lower(self, base, asm, ops, mods): # lane k of its own quad (RDNA 2 ISA, "DPP": a lane reads lane (lane & ~3) | perm[lane & 3] of the row; LLVM 15 # AMDGPU DPP quad_perm). A pixel stage's four consecutive lanes are a 2x2 pixel quad (lane = x & 1 | (y & 1) << 1), # which is what SM 6.0 QuadReadLaneAt(value, k) reads, so the stage is compiled as ps_6_0 (Stage.needs_sm6). - # Accepted only where the whole quad is proven active: a straight-line pixel stage that ran s_wqm exec, exec and - # whose EXEC is still that mask (helper lanes are active, so no source lane is off). bound_ctrl then has - # nothing to decide (the source lane is never disabled), so it is accepted and ignored. Everything else a DPP word can say stays refused: other controls (pair - # broadcasts, row shifts, mirrors, DPP8), a masked row or bank, and a vertex stage (dpp() drops fi:1 first). + # Accepted only where the whole quad is proven active: the entry straight-line prefix of a pixel stage that ran + # s_wqm exec, exec and whose EXEC is still that mask (helper lanes are active, so no source lane is off). A later + # uniform loop or forward branch elsewhere in the stage does not drop the proof: every path still reaches the + # broadcast with the same EXEC and cannot jump back to the prefix. bound_ctrl then has nothing to + # decide (the source lane is never disabled), so it is accepted and ignored. A broadcast after a branch target, + # after EXEC changed, or with divergent EXEC stays refused, as do other DPP controls (pair broadcasts, row shifts, + # mirrors, DPP8), a masked row or bank, and a vertex stage (dpp() drops fi:1 first). DPP_TEMP = 256 # hidden VGPR that holds the quad read; the hardware has v0..v255 only DPP_OUTPUT_MODS = ('clamp', 'mul:2', 'mul:4', 'div:2') @@ -3368,9 +3371,12 @@ def dpp_broadcast(self, base, ops, mods): raise Unsupported('%s_dpp with a partial row_mask or bank_mask' % base) if fields.get('bound_ctrl', '1') != '1': raise Unsupported('%s_dpp bound_ctrl:%s' % (base, fields['bound_ctrl'])) - if (self.kind != 'ps' or getattr(self, 'has_branches', True) or getattr(self, 'blocks', []) - or not getattr(self, 'exec_known', False)): + if self.kind != 'ps': raise Unsupported('%s_dpp outside a straight-line pixel stage with the entry EXEC mask' % base) + # A branch to offset zero also makes the nominal entry block re-entrant. + if (getattr(self, 'past_entry', bool(getattr(self, 'blocks', ()))) or + not getattr(self, 'exec_known', False)): + raise Unsupported('%s_dpp outside the entry prefix of a pixel stage with the entry EXEC mask' % base) if not getattr(self, 'wqm_exec', False): # The entry EXEC can leave out lanes of a partly covered quad, and the guest then reads an inactive # source lane (bound_ctrl / fi), while QuadReadLaneAt would return a helper lane's value. From 728797973394af8088106e7ef8531b1d1f59b00b Mon Sep 17 00:00:00 2001 From: triggered02 <153171514+triggered02@users.noreply.github.com> Date: Thu, 26 Nov 2026 07:01:35 +0530 Subject: [PATCH 048/240] startup: refuse modifiers on modifier-free handlers (#1778) Fixes #1771. Co-authored-by: Royoo <3230853833@qq.com> --- CMakeLists.txt | 3 + docs/experiments.md | 14 ++ tests/startup_gfx2hlsl_modifier_free_check.py | 179 ++++++++++++++++++ ...up_gfx2hlsl_readfirstlane_uniform_check.py | 1 + tools/startup/gfx2hlsl.py | 12 ++ 5 files changed, 209 insertions(+) create mode 100644 tests/startup_gfx2hlsl_modifier_free_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index b50d1ba1e..fd491c10d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3302,6 +3302,9 @@ if(EXISTS "${INTAKE_PYTHON}") # lowering of the same selections. add_test(NAME startup_gfx2hlsl_sdwa COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_sdwa_check.py") + # Handlers that do not model a modifier they can receive refuse it (#1771). + add_test(NAME startup_gfx2hlsl_modifier_free COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_modifier_free_check.py") # image_sample_c_lz with sampler word 2 bits 28-30 set (#1723). add_test(NAME startup_gfx2hlsl_sample_c_lz_mip COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_sample_c_lz_mip_check.py") diff --git a/docs/experiments.md b/docs/experiments.md index 8fa7647e6..38fa8d0ff 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -16103,6 +16103,20 @@ Building on #2443 (Slice 1), `X2W_D3D12_RELEASE_RETIRED=1` extends desktop objec ctest --preset dev --no-tests=error -R '^startup_resource_(retire|budget)' -V ``` +## Refusing unmodelled modifiers in the startup translator + +Several `Stage` instruction handlers accepted a `mods` list without reading it, so an encoding modifier such as +`clamp`, `omod` (`mul:2`), or `op_sel` on `v_mov_b32`, `v_cvt_pkrtz_f16_f32`, or `v_interp_mov_f32` was silently +dropped from the emitted HLSL (#1771). `MODIFIER_FREE_HANDLERS` declares these five handlers (`op_v_mov_b32`, +`op_v_cvt_pkrtz_f16_f32`, `op_v_interp_p1_f32`, `op_v_interp_p2_f32`, and `op_v_interp_mov_f32`), and `Stage.one` +refuses any non-empty `mods` list before dispatching to them. Scalar-ALU handlers are omitted because their encodings +have no modifier field. Separately, `op_v_interp_p1_f32` and `op_v_interp_p2_f32` refuse `abs`/`neg` modifiers (`|...|` +or `-...`) printed on the ignored data-source operand (`ops[1]`). + +```powershell +ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_modifier_free$' -V +``` + ## Source `abs` modifiers (`|src|` and `-|src|`) on `v_cndmask_b32_e64` in the startup translator `Stage.u_src` in [`tools/startup/gfx2hlsl.py`](../tools/startup/gfx2hlsl.py#L1506-L1521) now strips `|...|` after `split_neg(tok)` for `v_cndmask_b32_e64` data sources (`src0` and `src1`, both VGPRs and SGPRs), clearing the `off_diag.py` refusal `operand '|v0|' at v_cndmask_b32_e64 v0, v0, |v0|, s30`. Per the RDNA2 VOP3A source-modifier order, `abs` clears bit 31 (`& 0x7fffffffu`) first and `neg` flips bit 31 (`^ 0x80000000u`) second: diff --git a/tests/startup_gfx2hlsl_modifier_free_check.py b/tests/startup_gfx2hlsl_modifier_free_check.py new file mode 100644 index 000000000..e18d4c1d1 --- /dev/null +++ b/tests/startup_gfx2hlsl_modifier_free_check.py @@ -0,0 +1,179 @@ +"""Handlers whose lowering does not model a modifier they can receive (issue #1771). + +usage: startup_gfx2hlsl_modifier_free_check.py + +Several handlers take the modifier list and never read it, so a modifier their encoding can carry was dropped +from the emitted HLSL - the same class as the `op_sel`/`clamp` cases fixed one at a time earlier +(`set_vf`, `op_v_cndmask_b32`, `compare`). The dispatch now refuses a modifier for the handlers declared in +`MODIFIER_FREE_HANDLERS`, before the handler can ignore it. + +The instruction bytes are **constructed here** from the field layout the checked-in decoder reads +(`tools/disasm_rdna2.py`): VOP1/VOP2-as-VOP3 use prefix `0b110101` with opcode `0x180 + n` / `0x100 + n`, +modifiers at `w0[15]` (clamp), `w0[14:11]` (op_sel) and `w1[28:27]` (omod); VOP3A uses the opcode in `w0[25:16]`. +""" +import os +import struct +import sys + +here = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(here, '..', 'tools')) +sys.path.insert(0, os.path.join(here, '..', 'tools', 'startup')) +import gfx2hlsl as G # noqa: E402 + +failures = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH'}") + if not condition: + failures.append(label) + if detail: + print(' ' + detail) + + +VOP1_E64_BASE = 0x180 +VOP2_E64_BASE = 0x100 +VOP1_MOV_B32 = 0x01 +VOP2_CVT_PKRTZ_F16_F32 = 0x2F +VOP3A_INTERP_P1 = 0x200 +VOP3A_INTERP_P2 = 0x201 +VOP3A_INTERP_MOV = 0x202 +V1, V2, V3 = 0x101, 0x102, 0x103 + + +def _word0(opcode, vdst, *, clamp=0, op_sel=(0, 0, 0, 0)): + w0 = (0b110101 << 26) | ((opcode & 0x3FF) << 16) | ((clamp & 1) << 15) | (vdst & 0xFF) + for i, bit in enumerate(op_sel): + w0 |= (bit & 1) << (11 + i) + return w0 + + +def encode_vop1(op, vdst, src0, *, clamp=0): + return struct.pack(' Date: Thu, 26 Nov 2026 01:36:17 +0000 Subject: [PATCH 049/240] runtime: add an opt-in console profile for the OEM ConsoleMode read (#2650) * runtime: add an opt-in console profile for the OEM ConsoleMode read X2W_DEVICE_TYPE (with X2W_RUNTIME_PROXY) answers the title's reads of HKLM\Software\Microsoft\Windows NT\CurrentVersion\OEM\ConsoleMode: 6 = 0x60 (Series S), 7 = 0x64 (Series X), 1 = value missing (PC). Unset, every call goes to the real registry. The proxy rewrites five registry imports of the EXE and package helpers (regular IAT and GetProcAddress by name); visit_imports_with takes a classifier for them and visit_imports keeps its own behaviour. Opening the key and reading the value are logged a few times either way. New fixture with a negative control: startup_console_mode, against fake registry functions; the control leaves the switch unset for the answered cases. * runtime: hook registry imports only from the Windows registry providers Both console-mode routes matched the import name alone, so a package DLL exporting RegQueryValueExW or RegOpenKeyExW could be hooked and, because the first address is kept, become the registry later calls reach. The IAT route now needs the import DLL to be advapi32.dll, kernelbase.dll, kernel32.dll or an api-ms-win-core-registry-* API set, and the bound address to lie in the system-directory copy of one of those modules. The GetProcAddress route needs the module to be one of them. Only addresses inside them are remembered as the real function. startup_console_mode loads a source-built decoy DLL with the same export names and a distinct result. With X2W_DEVICE_TYPE unset and set, its GetProcAddress lookups and synthetic IAT entries naming it (or naming advapi32.dll but bound to it) stay untouched, and the hooks still reach the fake registry. startup_console_mode_provider_control matches by name alone and must fail. startup_runtime_proxy_scope checks the same through the real loader against advapi32.dll. A full 16-entry OEM handle table is now logged once. --- CMakeLists.txt | 18 + docs/startup-runtime.md | 29 ++ src/startup_stubs/console_mode.h | 96 +++++ src/startup_stubs/registry_console_mode.inl | 314 +++++++++++++++ src/startup_stubs/runtime_gpa_patch.h | 28 +- src/startup_stubs/runtime_proxy.cpp | 12 + tests/startup_console_mode_check.cpp | 409 ++++++++++++++++++++ tests/startup_console_mode_decoy.cpp | 28 ++ tests/startup_console_mode_decoy.def | 5 + tests/startup_runtime_proxy_scope/decoy.cpp | 13 +- tests/startup_runtime_proxy_scope/decoy.def | 2 + tests/startup_runtime_proxy_scope/host.cpp | 37 +- 12 files changed, 979 insertions(+), 12 deletions(-) create mode 100644 src/startup_stubs/console_mode.h create mode 100644 src/startup_stubs/registry_console_mode.inl create mode 100644 tests/startup_console_mode_check.cpp create mode 100644 tests/startup_console_mode_decoy.cpp create mode 100644 tests/startup_console_mode_decoy.def diff --git a/CMakeLists.txt b/CMakeLists.txt index fd491c10d..c8612e7b3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1059,6 +1059,24 @@ target_compile_features(startup_runtime_gpa_patch PRIVATE cxx_std_17) add_test(NAME startup_runtime_gpa_patch COMMAND startup_runtime_gpa_patch) add_test(NAME startup_runtime_gpa_patch_name_only_control COMMAND startup_runtime_gpa_patch --mutate name-only) set_tests_properties(startup_runtime_gpa_patch_name_only_control PROPERTIES PASS_REGULAR_EXPRESSION "FAIL: ") +# X2W_DEVICE_TYPE: the OEM ConsoleMode registry read, answered or passed on, against fake registry +# functions. A source-built decoy DLL exports the same registry names and must stay unhooked. The +# control leaves the switch unset for the answered cases; the provider control matches registry +# imports by name alone. Both must FAIL. +add_library(startup_console_mode_decoy SHARED + tests/startup_console_mode_decoy.cpp + tests/startup_console_mode_decoy.def) +target_compile_features(startup_console_mode_decoy PRIVATE cxx_std_17) +add_executable(startup_console_mode tests/startup_console_mode_check.cpp) +target_include_directories(startup_console_mode PRIVATE src) +target_compile_features(startup_console_mode PRIVATE cxx_std_17) +add_dependencies(startup_console_mode startup_console_mode_decoy) +add_test(NAME startup_console_mode COMMAND startup_console_mode --decoy "$") +add_test(NAME startup_console_mode_control + COMMAND startup_console_mode --control --decoy "$") +add_test(NAME startup_console_mode_provider_control + COMMAND startup_console_mode --control provider --decoy "$") +set_tests_properties(startup_console_mode_control startup_console_mode_provider_control PROPERTIES PASS_REGULAR_EXPRESSION "FAIL: ") # EXE + late-loaded package helper through the real Windows loader: proxied xgameruntime QueryApiImpl, # unrelated same-named export stays original. Notification only enqueues; rewrite runs after link. if (WIN32) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 9b093fe86..0f3b0cdef 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1364,6 +1364,7 @@ ctest --preset dev --no-tests=error -R '^startup_trap_header(_prefix_control|_pr | `X2W_RUNTIME_PROXY=1` | proxies the gaming runtime and logs every call. Rewrites regular-IAT `GetProcAddress` and a direct `xgameruntime.dll!QueryApiImpl` import on the main EXE and on DLLs that share its directory (package helpers). Dynamic `QueryApiImpl` / `InitializeApiImpl*` are wrapped only when the provider module's basename is `xgameruntime.dll`. `LdrRegisterDllNotification` only flags that another scan is needed. A worker holds each matching module live while rewriting after linking. Loading a helper and immediately calling it can precede the scan. The enabled proxy stays loaded until process exit. Delay-import IAT slots are not rewritten. Skips this stand-in's own `GetProcAddress` IAT so the hook does not recurse (`src/startup_stubs/runtime_gpa_patch.h`, `ctest --preset dev --no-tests=error -R '^startup_runtime_gpa_patch(_name_only_control)?$'`, and the control must print `FAIL:`; Windows also runs `startup_runtime_proxy_scope` for a late-loaded helper through the real loader) | | `X2W_FAKE_USER=1` | answers the user, gamertag and save APIs for one local user, and creates one offline store context for that user | | `X2W_RUNTIME_LOCAL=1` | with `X2W_RUNTIME_PROXY` and `X2W_FAKE_USER`, for a host where the system gaming runtime cannot initialize (no Gaming Services). The first failed `InitializeApiImpl*` is reported as `S_OK`, and every later initialization call returns `S_OK` without calling the real export. Once initialization failure is latched, a failed real `QueryApiImpl` call can fall back only with an exact match of both GUIDs to a supported provider/interface pair for user (including gamertag), game save, package, title, connectivity or store. Persistent local storage uses its existing fake-user gate and requires its exact provider GUID and IID. Unmatched failed queries keep the real HRESULT. The proxy clears a writable output on failure only when fake user is enabled and the initialization failure is latched. A local object's `QueryInterface` accepts only `IID_IUnknown` and the IID it was created for. The local answers above apply, calls that carry the local user or store handle fail as before, and other unanswered methods return `E_NOTIMPL`. `XUserAddAsync` and async operations completed on behalf of a local answer require the real runtime's `QueryApiImpl` to return the XAsync provider (`073b7dcb`). Those operations complete with `S_OK` through XAsync, or return the query failure if XAsync is unavailable (`ctest --preset dev --no-tests=error -R '^startup_runtime_local(_control)?$'`, and the control must print `FAIL:`). | +| `X2W_DEVICE_TYPE=` | with `X2W_RUNTIME_PROXY=1`, answers the title's reads of the OEM `ConsoleMode` registry value: `6` = 0x60 (Series S), `7` = 0x64 (Series X), `1` = value missing (PC); unset, the real registry answers. See [Console profile](#console-profile) | | `X2W_STORAGE_PATH`, `X2W_STORAGE_MB`, `X2W_TITLE_ID` | persistent local storage and the manifest values the runtime would return. The path is UTF-8, with a trailing separator added when missing. If the path is invalid or exceeds 259 bytes including the separator, the proxy logs the refusal and uses `S:\` (`src/startup_stubs/storage_root_utf8.h`, `ctest --preset release --no-tests=error -R '^startup_storage_root'`). | | `X2W_INPUT_SCRIPT=mask@sec,...` | timed virtual gamepad presses, holds, stick or trigger values and waits for the presented picture: see [Input script](#input-script); keyboard and XInput pad 0 also work. Up to 256 entries and 4,095 characters; a longer value is ignored and logged, and dropped or malformed entries are logged (`ctest --preset dev --no-tests=error -R '^startup_gameinput_script_(long|entries|syntax)$'`) | | `X2W_SAMPLER_HEAP=1` | `gfx2hlsl.py` translates a sampler-heap load with a run-time offset into `SamplerState qh[2048] : register(s0, space1)` and writes `smpheap 2048 1 fallback 2047`. The stand-in uses entries 0 to 2046 for the bound heap and reserves entry 2047 for unaligned or out-of-range offsets. It also accepts the original `smpheap 2048 1` manifest with all 2,048 entries available. [#1143](https://github.com/R0Y00/Xbox2Windows/issues/1143) | @@ -1391,6 +1392,34 @@ together under their original name. A 16-dword table load can contain two independent image descriptors at offsets 0 and 32 from the load address. For a read-only census of cached shader refusals, use `python -B tools/startup/gfx2hlsl.py --refusals [--json]` with a translator that supports the flag. Earlier versions treat it as `--pending` and write into the directory. See [Startup translator refusal census](experiments.md#startup-translator-refusal-census). +## Console profile + +`X2W_DEVICE_TYPE` answers the two registry reads a title makes of +`HKLM\Software\Microsoft\Windows NT\CurrentVersion\OEM\ConsoleMode` +(`src/startup_stubs/console_mode.h`, `registry_console_mode.inl`): with `X2W_RUNTIME_PROXY=1` the +stand-in rewrites the registry imports of the EXE and package helpers. `6` answers 0x60 (Series S), +`7` answers 0x64 (Series X) and `1` reports the value missing (PC); unset, every call goes to the real +registry. Only registry imports that the Windows registry provides are rewritten: an IAT entry must +name `advapi32.dll`, `kernelbase.dll`, `kernel32.dll` or an `api-ms-win-core-registry-*` API set and be +bound inside the system-directory copy of the first three, and `GetProcAddress` must be called on one +of those modules. A package DLL that exports the same names keeps its own exports and is never kept as +the real registry. Opening the key and reading the value are logged a few times either way, and a +seventeenth OEM key handle open at once is logged once and not tracked. What the values mean on the +console is taken from public notes, not measured here. +`ctest --preset dev --no-tests=error -R '^startup_console_mode(_control|_provider_control)?$'` runs it +against fake registry functions and a source-built decoy DLL with the same export names, with the switch +unset and set. The control leaves the switch unset for the answered cases and the provider control +matches registry imports by name alone; both must print `FAIL:`. `startup_runtime_proxy_scope` checks the +same decoy rule through the real loader against `advapi32.dll`. + +The switch changes only what the registry reads answer. A title can take a different start-up path +for each profile: on the Series S profile, one loaded an upscaler package module that the other +profiles do not, and that module met desktop refusals the other profiles did not reach +(`Device::slot76`, views with `ViewDimension` 0, and `R9G9B9E5_SHAREDEXP` textures with unordered +access, the last covered by the +[shared-exponent stand-in](#shared-exponent-render-and-unordered-access-targets)). Choosing a profile +is not evidence that the path it leads to runs. + ## D3D12 resource budget Set `X2W_D3D12_BUDGET=1` before startup to add one `x2w-budget` line to each diff --git a/src/startup_stubs/console_mode.h b/src/startup_stubs/console_mode.h new file mode 100644 index 000000000..7bc01ac3f --- /dev/null +++ b/src/startup_stubs/console_mode.h @@ -0,0 +1,96 @@ +// Experimental (docs/startup-runtime.md): which console the title is told it runs on. +// +// Public GDK documentation describes XSystemGetDeviceType and the XSystemDeviceType values +// (Pc = 1, XboxScarlettLockhart = 6, XboxScarlettAnaconda = 7). The proxied runtime calls seen in +// startup runs include no device-type method. A public runtime reimplementation's notes +// (github.com/Marvisak/VIctory, facts only) say the value is not a runtime call: title code reads +// HKLM\Software\Microsoft\Windows NT\CurrentVersion\OEM, DWORD value ConsoleMode, where 0x60 is +// Series S, 0x64 is Series X and a missing value is a PC. Those three readings are that source's, +// not measured here. +// +// X2W_DEVICE_TYPE= (with X2W_RUNTIME_PROXY) answers that one value: 6 -> 0x60, 7 -> 0x64, +// 1 -> missing. Unset or any other number passes every read to the real registry. +// Pure helpers, no Windows calls, so a source-built control can check them. +#pragma once + +#include +#include + +namespace x2w_console_mode { + +constexpr long status_ok = 0, status_not_found = 2, status_invalid = 87, status_more_data = 234, status_wrong_type = 1630; +constexpr unsigned long type_dword = 4; +constexpr unsigned long rrf_rt_reg_dword = 0x10; +constexpr std::uint32_t series_s = 0x60, series_x = 0x64; + +inline wchar_t fold(wchar_t c) noexcept +{ + return (c >= L'A' && c <= L'Z') ? static_cast(c - L'A' + L'a') : c; +} + +inline bool equal_ci(const wchar_t* a, const wchar_t* b) noexcept +{ + if (!a || !b) return false; + for (;; ++a, ++b) { + if (fold(*a) != fold(*b)) return false; + if (!*a) return true; + } +} + +// Subkey of HKEY_LOCAL_MACHINE. One leading or trailing backslash is accepted. +inline bool is_oem_subkey(const wchar_t* subkey) noexcept +{ + static constexpr wchar_t expect[] = L"software\\microsoft\\windows nt\\currentversion\\oem"; + if (!subkey) return false; + if (*subkey == L'\\') ++subkey; + std::size_t i = 0; + for (; expect[i]; ++i) + if (fold(subkey[i]) != expect[i]) return false; + return !subkey[i] || (subkey[i] == L'\\' && !subkey[i + 1]); +} + +inline bool is_console_mode_value(const wchar_t* name) noexcept +{ + return equal_ci(name, L"ConsoleMode"); +} + +enum class Answer { pass, value, missing }; + +// device_set is false when X2W_DEVICE_TYPE is absent or not a number. +inline Answer answer_for(bool device_set, unsigned long device_type, std::uint32_t* mode) noexcept +{ + if (!device_set) return Answer::pass; + switch (device_type) { + case 1: return Answer::missing; + case 6: if (mode) *mode = series_s; return Answer::value; + case 7: if (mode) *mode = series_x; return Answer::value; + default: return Answer::pass; + } +} + +// RegQueryValueExW's output rules for one REG_DWORD. +inline long fill_query(std::uint32_t value, unsigned long* type, unsigned char* data, unsigned long* bytes) noexcept +{ + if (data && !bytes) return status_invalid; + if (type) *type = type_dword; + if (!data) { + if (bytes) *bytes = sizeof(value); + return status_ok; + } + if (*bytes < sizeof(value)) { + *bytes = sizeof(value); + return status_more_data; + } + for (std::size_t i = 0; i < sizeof(value); ++i) data[i] = static_cast(value >> (8 * i)); + *bytes = sizeof(value); + return status_ok; +} + +// RegGetValueW's: the flags must allow a DWORD (RRF_RT_REG_DWORD, part of RRF_RT_DWORD and RRF_RT_ANY). +inline long fill_get(unsigned long flags, std::uint32_t value, unsigned long* type, void* data, unsigned long* bytes) noexcept +{ + if (!(flags & rrf_rt_reg_dword)) return status_wrong_type; + return fill_query(value, type, static_cast(data), bytes); +} + +} // namespace x2w_console_mode diff --git a/src/startup_stubs/registry_console_mode.inl b/src/startup_stubs/registry_console_mode.inl new file mode 100644 index 000000000..7af9b49ae --- /dev/null +++ b/src/startup_stubs/registry_console_mode.inl @@ -0,0 +1,314 @@ +// Experimental (docs/startup-runtime.md): registry reads of the console mode (see console_mode.h). +// Included inside runtime_proxy.cpp's anonymous namespace, and on its own by +// tests/startup_console_mode_check.cpp. Needs , , local_log.h, +// runtime_gpa_patch.h and console_mode.h. +// +// With X2W_RUNTIME_PROXY the stand-in rewrites five registry imports of the EXE and package helpers +// (regular IAT and GetProcAddress by name), only where the Windows registry provides them: see +// registry_provider_module below. Every call goes to the real function except a read of +// ConsoleMode under HKLM\...\OEM while X2W_DEVICE_TYPE names a known console. Opening the OEM +// key and reading the value are logged a few times in either case, so a run shows whether the +// title asks at all. + +enum RegistryImport { reg_open_key_ex_w, reg_open_key_w, reg_query_value_ex_w, reg_get_value_w, reg_close_key, registry_imports }; +constexpr const char* registry_import_names[registry_imports] = {"RegOpenKeyExW", "RegOpenKeyW", "RegQueryValueExW", "RegGetValueW", + "RegCloseKey"}; +using RegOpenKeyExWFn = LSTATUS(WINAPI*)(HKEY, LPCWSTR, DWORD, REGSAM, PHKEY); +using RegOpenKeyWFn = LSTATUS(WINAPI*)(HKEY, LPCWSTR, PHKEY); +using RegQueryValueExWFn = LSTATUS(WINAPI*)(HKEY, LPCWSTR, LPDWORD, LPDWORD, LPBYTE, LPDWORD); +using RegGetValueWFn = LSTATUS(WINAPI*)(HKEY, LPCWSTR, LPCWSTR, DWORD, LPDWORD, PVOID, LPDWORD); +using RegCloseKeyFn = LSTATUS(WINAPI*)(HKEY); + +std::atomic real_registry[registry_imports]; + +int registry_import_index(const char* name) noexcept +{ + if (!name) return -1; + for (int i = 0; i < registry_imports; ++i) + if (std::strcmp(name, registry_import_names[i]) == 0) return i; + return -1; +} + +// ---- which modules are the Windows registry ----------------------------------------------------- +// A package DLL can export the same names. Only these system modules count as the registry, for the +// GetProcAddress module, for the module that holds a bound IAT address and for what is remembered +// as the real function. The api-ms-win-core-registry API sets resolve to kernelbase.dll. +constexpr const wchar_t* registry_provider_names[] = {L"advapi32.dll", L"kernelbase.dll", L"kernel32.dll"}; + +#if defined(X2W_CONSOLE_MODE_FIXTURE) +// tests/startup_console_mode_check.cpp keeps its fake registry in the test EXE, which counts as one +// more provider there. Its provider control sets registry_any_provider (name-only matching), which +// the decoy checks must catch. +bool registry_any_provider; +bool fixture_registry_provider(HMODULE module) noexcept { return module == GetModuleHandleW(nullptr); } +#else +constexpr bool registry_any_provider = false; +constexpr bool fixture_registry_provider(HMODULE) noexcept { return false; } +#endif + +// The loaded system-directory copy of a provider, by full path, so a same-named DLL elsewhere does not match. +bool registry_provider_module(HMODULE module) noexcept +{ + if (registry_any_provider) return true; + if (!module) return false; + if (fixture_registry_provider(module)) return true; + const DWORD saved = GetLastError(); + wchar_t path[MAX_PATH]{}; + const UINT length = GetSystemDirectoryW(path, MAX_PATH); + bool found = false; + for (const wchar_t* name : registry_provider_names) { + if (found || !length || length >= MAX_PATH) break; + std::size_t at = length, i = 0; + path[at++] = L'\\'; + for (; name[i] && at + 1 < MAX_PATH; ++i) path[at++] = name[i]; + if (name[i]) break; + path[at] = 0; + found = GetModuleHandleW(path) == module; + } + SetLastError(saved); + return found; +} + +bool registry_provider_address(const void* address) noexcept +{ + if (registry_any_provider) return true; + const DWORD saved = GetLastError(); + HMODULE module = nullptr; + const bool known = address && GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + static_cast(address), &module); + SetLastError(saved); + return known && registry_provider_module(module); +} + +// Import DLL names (any case) that supply the registry: the providers above and the +// api-ms-win-core-registry-* API sets. +bool registry_provider_dll(const char* dll) noexcept +{ + if (registry_any_provider) return true; + if (!dll) return false; + const auto lower = [](char c) { return (c >= 'A' && c <= 'Z') ? static_cast(c - 'A' + 'a') : c; }; + const auto equal = [&](const char* expect) { + std::size_t i = 0; + for (; expect[i]; ++i) + if (lower(dll[i]) != expect[i]) return false; + return dll[i] == 0; + }; + if (equal("advapi32.dll") || equal("kernelbase.dll") || equal("kernel32.dll")) return true; + static constexpr char api_set[] = "api-ms-win-core-registry-"; + for (std::size_t i = 0; api_set[i]; ++i) + if (lower(dll[i]) != api_set[i]) return false; + return true; +} + +// ---- OEM key handles the title opened ----------------------------------------------------------- +SRWLOCK oem_lock = SRWLOCK_INIT; +HKEY oem_keys[16]; + +void note_oem_table_full() noexcept +{ + static volatile LONG logged; + if (x2w_local::first_calls(logged, 1)) + x2w_local::logf("x2w-runtime console mode: %u OEM key handles already open, another is not tracked", + static_cast(sizeof(oem_keys) / sizeof(oem_keys[0]))); +} + +void track_oem(HKEY key) noexcept +{ + AcquireSRWLockExclusive(&oem_lock); + bool tracked = false; + for (HKEY& slot : oem_keys) { + if (!slot) { + slot = key; + tracked = true; + break; + } + } + ReleaseSRWLockExclusive(&oem_lock); + if (!tracked) note_oem_table_full(); +} + +bool oem_key(HKEY key) noexcept +{ + if (!key) return false; + AcquireSRWLockShared(&oem_lock); + bool found = false; + for (HKEY slot : oem_keys) found = found || slot == key; + ReleaseSRWLockShared(&oem_lock); + return found; +} + +void untrack_oem(HKEY key) noexcept +{ + AcquireSRWLockExclusive(&oem_lock); + for (HKEY& slot : oem_keys) + if (slot == key) slot = nullptr; + ReleaseSRWLockExclusive(&oem_lock); +} + +// ---- the answer --------------------------------------------------------------------------------- +x2w_console_mode::Answer console_answer(std::uint32_t* mode, unsigned long* device) noexcept +{ + const DWORD saved = GetLastError(); + char text[16]{}; + const DWORD length = GetEnvironmentVariableA("X2W_DEVICE_TYPE", text, sizeof(text)); + SetLastError(saved); + char* end = nullptr; + const unsigned long value = length && length < sizeof(text) ? std::strtoul(text, &end, 0) : 0; + const bool set = length && length < sizeof(text) && end && end != text && !*end; + *device = value; + return x2w_console_mode::answer_for(set, value, mode); +} + +void note_oem_open(const char* via, LSTATUS status) noexcept +{ + static volatile LONG logged; + if (x2w_local::first_calls(logged, 4)) + x2w_local::logf("x2w-runtime console mode: %s opened the OEM key, real status %ld", via, static_cast(status)); +} + +// One line per read (the first eight): what was answered, and the real status or value when passed on. +void note_console_read(const char* via, x2w_console_mode::Answer answer, unsigned long device, std::uint32_t value, LSTATUS status) noexcept +{ + static volatile LONG logged; + if (!x2w_local::first_calls(logged, 8)) return; + if (answer == x2w_console_mode::Answer::value) + x2w_local::logf("x2w-runtime console mode: %s ConsoleMode -> 0x%x for X2W_DEVICE_TYPE=%lu, status %ld", via, value, device, + static_cast(status)); + else if (answer == x2w_console_mode::Answer::missing) + x2w_local::logf("x2w-runtime console mode: %s ConsoleMode -> missing (PC) for X2W_DEVICE_TYPE=%lu", via, device); + else if (status == ERROR_SUCCESS) + x2w_local::logf("x2w-runtime console mode: %s ConsoleMode passed through -> 0x%x", via, value); + else + x2w_local::logf("x2w-runtime console mode: %s ConsoleMode passed through -> status %ld", via, static_cast(status)); +} + +template +Fn real_reg(RegistryImport which) noexcept +{ + return reinterpret_cast(real_registry[which].load(std::memory_order_acquire)); +} + +LSTATUS WINAPI hooked_reg_open_key_ex_w(HKEY root, LPCWSTR subkey, DWORD options, REGSAM access, PHKEY out) +{ + const auto real = real_reg(reg_open_key_ex_w); + if (!real) return ERROR_PROC_NOT_FOUND; + const LSTATUS status = real(root, subkey, options, access, out); + if (root == HKEY_LOCAL_MACHINE && x2w_console_mode::is_oem_subkey(subkey)) { + note_oem_open("RegOpenKeyExW", status); + if (status == ERROR_SUCCESS && out) track_oem(*out); + } + return status; +} + +LSTATUS WINAPI hooked_reg_open_key_w(HKEY root, LPCWSTR subkey, PHKEY out) +{ + const auto real = real_reg(reg_open_key_w); + if (!real) return ERROR_PROC_NOT_FOUND; + const LSTATUS status = real(root, subkey, out); + if (root == HKEY_LOCAL_MACHINE && x2w_console_mode::is_oem_subkey(subkey)) { + note_oem_open("RegOpenKeyW", status); + if (status == ERROR_SUCCESS && out) track_oem(*out); + } + return status; +} + +std::uint32_t dword_read(LSTATUS status, const void* data, const DWORD* bytes) noexcept +{ + std::uint32_t value = 0; + if (status == ERROR_SUCCESS && data && bytes && *bytes >= sizeof(value)) std::memcpy(&value, data, sizeof(value)); + return value; +} + +LSTATUS WINAPI hooked_reg_query_value_ex_w(HKEY key, LPCWSTR name, LPDWORD reserved, LPDWORD type, LPBYTE data, LPDWORD bytes) +{ + const auto real = real_reg(reg_query_value_ex_w); + if (!x2w_console_mode::is_console_mode_value(name) || !oem_key(key)) + return real ? real(key, name, reserved, type, data, bytes) : ERROR_PROC_NOT_FOUND; + std::uint32_t mode = 0; + unsigned long device = 0; + const auto answer = console_answer(&mode, &device); + LSTATUS status = ERROR_FILE_NOT_FOUND; + if (answer == x2w_console_mode::Answer::value) + status = x2w_console_mode::fill_query(mode, reinterpret_cast(type), data, reinterpret_cast(bytes)); + else if (answer == x2w_console_mode::Answer::pass) + status = real ? real(key, name, reserved, type, data, bytes) : ERROR_PROC_NOT_FOUND; + note_console_read("RegQueryValueExW", answer, device, answer == x2w_console_mode::Answer::value ? mode : dword_read(status, data, bytes), status); + return status; +} + +LSTATUS WINAPI hooked_reg_get_value_w(HKEY key, LPCWSTR subkey, LPCWSTR name, DWORD flags, LPDWORD type, PVOID data, LPDWORD bytes) +{ + const auto real = real_reg(reg_get_value_w); + const bool oem = (key == HKEY_LOCAL_MACHINE && x2w_console_mode::is_oem_subkey(subkey)) || (oem_key(key) && (!subkey || !*subkey)); + if (!oem || !x2w_console_mode::is_console_mode_value(name)) + return real ? real(key, subkey, name, flags, type, data, bytes) : ERROR_PROC_NOT_FOUND; + std::uint32_t mode = 0; + unsigned long device = 0; + const auto answer = console_answer(&mode, &device); + LSTATUS status = ERROR_FILE_NOT_FOUND; + if (answer == x2w_console_mode::Answer::value) + status = x2w_console_mode::fill_get(flags, mode, reinterpret_cast(type), data, reinterpret_cast(bytes)); + else if (answer == x2w_console_mode::Answer::pass) + status = real ? real(key, subkey, name, flags, type, data, bytes) : ERROR_PROC_NOT_FOUND; + note_console_read("RegGetValueW", answer, device, answer == x2w_console_mode::Answer::value ? mode : dword_read(status, data, bytes), status); + return status; +} + +LSTATUS WINAPI hooked_reg_close_key(HKEY key) +{ + const auto real = real_reg(reg_close_key); + untrack_oem(key); + return real ? real(key) : ERROR_PROC_NOT_FOUND; +} + +void* const registry_hooks[registry_imports] = { + reinterpret_cast(&hooked_reg_open_key_ex_w), reinterpret_cast(&hooked_reg_open_key_w), + reinterpret_cast(&hooked_reg_query_value_ex_w), reinterpret_cast(&hooked_reg_get_value_w), + reinterpret_cast(&hooked_reg_close_key)}; + +// Keep the first real address for each import: one inside a registry provider, never one of the +// hooks themselves. +bool remember_registry(int which, void* real) noexcept +{ + if (which < 0 || which >= registry_imports || !real) return false; + for (void* hook : registry_hooks) + if (real == hook) return false; + if (!registry_provider_address(real)) return false; + void* expected = nullptr; + real_registry[which].compare_exchange_strong(expected, real, std::memory_order_acq_rel); + return true; +} + +// GetProcAddress by name: the hook for a registry import looked up on a registry provider, or null +// for any other name or module. +FARPROC registry_hook_for(HMODULE module, LPCSTR name, FARPROC real) noexcept +{ + const int which = registry_import_index(name); + if (which < 0 || !registry_provider_module(module) || !remember_registry(which, reinterpret_cast(real))) return nullptr; + return reinterpret_cast(registry_hooks[which]); +} + +// Rewrite one image's regular registry IAT slots that import from a registry provider and are bound +// inside one. Delay-import slots hold a thunk and are left alone. +int patch_registry_imports(unsigned char* base, std::size_t image_size) noexcept +{ + int patched = 0; + const auto classify = [](const char* dll, const char* name, x2w_runtime_patch::Kind* kind) { + if (registry_import_index(name) < 0 || !registry_provider_dll(dll)) return false; + *kind = x2w_runtime_patch::Kind::registry; + return true; + }; + x2w_runtime_patch::visit_imports_with(base, image_size, classify, [&](const x2w_runtime_patch::Hit& hit) { + if (hit.delay_import) return; + const int which = registry_import_index(hit.import_name); + auto* slot = reinterpret_cast(base + hit.first_thunk_rva); + if (*slot == reinterpret_cast(registry_hooks[which])) return; + if (!remember_registry(which, reinterpret_cast(*slot))) return; + DWORD old = 0; + if (!VirtualProtect(slot, 8, PAGE_READWRITE, &old)) return; + *slot = reinterpret_cast(registry_hooks[which]); + VirtualProtect(slot, 8, old, &old); + ++patched; + }); + return patched; +} diff --git a/src/startup_stubs/runtime_gpa_patch.h b/src/startup_stubs/runtime_gpa_patch.h index e5b23da82..b9dd8a4d0 100644 --- a/src/startup_stubs/runtime_gpa_patch.h +++ b/src/startup_stubs/runtime_gpa_patch.h @@ -16,7 +16,8 @@ namespace x2w_runtime_patch { -enum class Kind : unsigned char { get_proc_address = 1, query_api_impl = 2 }; +// registry: one of the registry imports named by console_mode.h (classified by its own caller). +enum class Kind : unsigned char { get_proc_address = 1, query_api_impl = 2, registry = 3 }; struct Hit { Kind kind; @@ -113,9 +114,9 @@ inline bool c_string_in_image(const unsigned char* base, std::size_t image_size, return false; } -template +template int visit_named_thunks(const unsigned char* base, std::size_t image_size, const char* dll, std::uint32_t name_table_rva, - std::uint32_t iat_rva, bool delay_import, Fn on_hit) + std::uint32_t iat_rva, bool delay_import, Classify classify, Fn on_hit) { int hits = 0; for (std::uint32_t ti = 0;; ++ti) { @@ -139,10 +140,11 @@ int visit_named_thunks(const unsigned char* base, std::size_t image_size, const return hits; } -// Walk a PE image's import and delay-import tables. Invokes `on_hit(Hit)` for each classified import. -// Returns the number of hits. Malformed images stop the walk and return what was found. -template -int visit_imports(const unsigned char* base, std::size_t image_size, Fn on_hit) +// Walk a PE image's import and delay-import tables. Invokes `on_hit(Hit)` for each import that +// `classify(dll, name, &kind)` accepts. Returns the number of hits. Malformed images stop the walk +// and return what was found. +template +int visit_imports_with(const unsigned char* base, std::size_t image_size, Classify classify, Fn on_hit) { if (!readable_range(base, image_size, 0, sizeof(DosStub))) return 0; const auto* dos = reinterpret_cast(base); @@ -167,7 +169,7 @@ int visit_imports(const unsigned char* base, std::size_t image_size, Fn on_hit) if (!imp->name || !imp->original_first_thunk || !imp->first_thunk) continue; if (!c_string_in_image(base, image_size, imp->name)) continue; const char* dll = reinterpret_cast(base + imp->name); - hits += visit_named_thunks(base, image_size, dll, imp->original_first_thunk, imp->first_thunk, false, on_hit); + hits += visit_named_thunks(base, image_size, dll, imp->original_first_thunk, imp->first_thunk, false, classify, on_hit); } } @@ -181,10 +183,18 @@ int visit_imports(const unsigned char* base, std::size_t image_size, Fn on_hit) if (!delay->dll_name || !delay->original_first_thunk || !delay->first_thunk) continue; if (!c_string_in_image(base, image_size, delay->dll_name)) continue; const char* dll = reinterpret_cast(base + delay->dll_name); - hits += visit_named_thunks(base, image_size, dll, delay->original_first_thunk, delay->first_thunk, true, on_hit); + hits += visit_named_thunks(base, image_size, dll, delay->original_first_thunk, delay->first_thunk, true, classify, on_hit); } } return hits; } +// The runtime proxy's own imports: GetProcAddress from any module, QueryApiImpl from xgameruntime.dll. +template +int visit_imports(const unsigned char* base, std::size_t image_size, Fn on_hit) +{ + return visit_imports_with(base, image_size, [](const char* dll, const char* name, Kind* kind) { return classify(dll, name, kind); }, + on_hit); +} + } // namespace x2w_runtime_patch diff --git a/src/startup_stubs/runtime_proxy.cpp b/src/startup_stubs/runtime_proxy.cpp index 7c9a17046..1f0e7890a 100644 --- a/src/startup_stubs/runtime_proxy.cpp +++ b/src/startup_stubs/runtime_proxy.cpp @@ -14,6 +14,7 @@ // X2W_FAKE_USER=1 additionally answers the user API for one local user (see fake_user below) // and, while the proxy is on, XStoreCreateContext for that user (see area_call). #include "startup_stubs/api_trace.h" +#include "startup_stubs/console_mode.h" #include "startup_stubs/local_log.h" #include "startup_stubs/runtime_gpa_patch.h" #include "startup_stubs/save_blob_pack.h" @@ -484,12 +485,16 @@ bool module_is_exe_or_package_helper(HMODULE module) noexcept return true; } +#include "startup_stubs/registry_console_mode.inl" + FARPROC WINAPI hooked_get_proc_address(HMODULE module, LPCSTR name) { const FARPROC real = GetProcAddress(module, name); if (real && reinterpret_cast(name) > 0xffff) { static LONG logged; if (x2w_local::first_calls(logged, 40)) x2w_local::logf("x2w-runtime GetProcAddress(%p, \"%s\") -> %p", static_cast(module), name, static_cast(real)); + // Registry exports only when the module is a Windows registry provider (registry_console_mode.inl). + if (const FARPROC hook = registry_hook_for(module, name, real)) return hook; // Wrap gaming-runtime exports only when the provider module is xgameruntime.dll. if (module_is_xgameruntime(module) && std::strcmp(name, "QueryApiImpl") == 0 && remember_real_query(reinterpret_cast(real))) @@ -555,6 +560,13 @@ int patch_module(HMODULE module) } VirtualProtect(slot, 8, old, &old); }); + // Registry imports for the console mode (registry_console_mode.inl), counted on their own line. + if (!self) { + const int registry = patch_registry_imports(base, image_size); + if (registry > 0) + x2w_local::logf("x2w-runtime console mode: %d registry import(s) patched in the %s", registry, + module == GetModuleHandleW(nullptr) ? "main module" : "package module"); + } return patched; } diff --git a/tests/startup_console_mode_check.cpp b/tests/startup_console_mode_check.cpp new file mode 100644 index 000000000..79a8bde24 --- /dev/null +++ b/tests/startup_console_mode_check.cpp @@ -0,0 +1,409 @@ +// Source-built control for console_mode.h and registry_console_mode.inl: the console mode a title +// reads from HKLM\Software\Microsoft\Windows NT\CurrentVersion\OEM (value ConsoleMode). +// +// The real registry functions are replaced by local fakes that report the value as missing (a PC), +// so no machine state is read or changed. The hooks are reached the way a title reaches them +// through GetProcAddress. Cases: unset passes the read to the fake; 6 and 7 answer 0x60 and 0x64 +// without calling it; 1 answers missing; other keys, values and closed handles pass through. +// --control leaves X2W_DEVICE_TYPE unset for the answered cases, which must print FAIL. +// +// The fake registry lives in this EXE, which X2W_CONSOLE_MODE_FIXTURE counts as a registry +// provider. --decoy loads a source-built DLL that exports RegOpenKeyExW and RegQueryValueExW +// with a distinct result. With the switch unset and set, neither GetProcAddress on the decoy nor a +// synthetic IAT entry naming it (or naming advapi32.dll but bound to the decoy) may be hooked or +// remembered, and the hooks must still reach the fake registry. --control provider matches +// registry imports by name alone, which must print FAIL. +#define X2W_CONSOLE_MODE_FIXTURE 1 +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "startup_stubs/console_mode.h" +#include "startup_stubs/local_log.h" +#include "startup_stubs/runtime_gpa_patch.h" + +namespace x2w_local { +std::string fixture_log; +void fixture_logf(const char* format, ...) +{ + char line[512]; + va_list args; + va_start(args, format); + std::vsnprintf(line, sizeof(line), format, args); + va_end(args); + fixture_log += line; + fixture_log += '\n'; +} +} // namespace x2w_local + +#define logf fixture_logf +namespace { +#include "../src/startup_stubs/registry_console_mode.inl" +} +#undef logf + +namespace { +int failures; +bool control; + +void check(const char* what, bool ok) +{ + if (!ok) { + std::printf("FAIL: %s\n", what); + ++failures; + } +} + +HKEY const fake_oem = reinterpret_cast(0x5100); +HKEY const fake_other = reinterpret_cast(0x5200); +int real_queries, real_gets, real_closes; + +LSTATUS WINAPI fake_open_ex(HKEY root, LPCWSTR subkey, DWORD, REGSAM, PHKEY out) +{ + if (root != HKEY_LOCAL_MACHINE || !out) return ERROR_FILE_NOT_FOUND; + *out = x2w_console_mode::is_oem_subkey(subkey) ? fake_oem : fake_other; + return ERROR_SUCCESS; +} +LSTATUS WINAPI fake_open(HKEY root, LPCWSTR subkey, PHKEY out) { return fake_open_ex(root, subkey, 0, 0, out); } +LSTATUS WINAPI fake_query(HKEY, LPCWSTR, LPDWORD, LPDWORD, LPBYTE, LPDWORD) +{ + ++real_queries; + return ERROR_FILE_NOT_FOUND; // as on a PC: the value is absent +} +LSTATUS WINAPI fake_get(HKEY, LPCWSTR, LPCWSTR, DWORD, LPDWORD, PVOID, LPDWORD) +{ + ++real_gets; + return ERROR_FILE_NOT_FOUND; +} +LSTATUS WINAPI fake_close(HKEY) +{ + ++real_closes; + return ERROR_SUCCESS; +} + +// The fakes live in this EXE, the fixture's registry provider. +template +Fn hook(const char* name, Fn fake) +{ + return reinterpret_cast(registry_hook_for(GetModuleHandleW(nullptr), name, reinterpret_cast(fake))); +} + +void device(const char* value, bool answered_case) +{ + // In the control the answered cases run without the switch, so their checks must fail. + if (!value || (control && answered_case)) + SetEnvironmentVariableA("X2W_DEVICE_TYPE", nullptr); + else + SetEnvironmentVariableA("X2W_DEVICE_TYPE", value); +} + +void pure_checks() +{ + using namespace x2w_console_mode; + check("OEM subkey", is_oem_subkey(L"Software\\Microsoft\\Windows NT\\CurrentVersion\\OEM")); + check("OEM subkey in capitals", is_oem_subkey(L"SOFTWARE\\MICROSOFT\\WINDOWS NT\\CURRENTVERSION\\OEM")); + check("OEM subkey with a leading and a trailing backslash", + is_oem_subkey(L"\\Software\\Microsoft\\Windows NT\\CurrentVersion\\OEM\\")); + check("a longer subkey is not the OEM key", !is_oem_subkey(L"Software\\Microsoft\\Windows NT\\CurrentVersion\\OEMx")); + check("a child of the OEM key is not the OEM key", !is_oem_subkey(L"Software\\Microsoft\\Windows NT\\CurrentVersion\\OEM\\a")); + check("a parent is not the OEM key", !is_oem_subkey(L"Software\\Microsoft\\Windows NT\\CurrentVersion")); + check("null subkey", !is_oem_subkey(nullptr)); + check("value name ignores case", is_console_mode_value(L"consolemode")); + check("other value name", !is_console_mode_value(L"ConsoleModeX")); + + std::uint32_t mode = 0; + check("unset passes", answer_for(false, 7, &mode) == Answer::pass); + check("6 is Series S", answer_for(true, 6, &mode) == Answer::value && mode == series_s); + check("7 is Series X", answer_for(true, 7, &mode) == Answer::value && mode == series_x); + check("1 is missing", answer_for(true, 1, &mode) == Answer::missing); + check("8 is passed on", answer_for(true, 8, &mode) == Answer::pass); + + unsigned long type = 0, bytes = 0; + unsigned char data[8] = {}; + check("size query", fill_query(series_x, &type, nullptr, &bytes) == status_ok && bytes == 4 && type == type_dword); + bytes = 3; + check("short buffer", fill_query(series_x, &type, data, &bytes) == status_more_data && bytes == 4 && data[0] == 0); + check("data without size", fill_query(series_x, &type, data, nullptr) == status_invalid); + bytes = sizeof(data); + check("value written", fill_query(series_x, &type, data, &bytes) == status_ok && bytes == 4 && data[0] == 0x64 && data[1] == 0); + bytes = sizeof(data); + check("RegGetValue refuses a string-only request", fill_get(0x2 /* RRF_RT_REG_SZ */, series_s, &type, data, &bytes) == status_wrong_type); + bytes = sizeof(data); + check("RegGetValue with RRF_RT_DWORD", fill_get(0x18, series_s, &type, data, &bytes) == status_ok && data[0] == 0x60); +} + +DWORD query(RegQueryValueExWFn query_fn, HKEY key, const wchar_t* name, LSTATUS* status) +{ + DWORD type = 0, value = 0xffffffff, bytes = sizeof(value); + *status = query_fn(key, name, nullptr, &type, reinterpret_cast(&value), &bytes); + return value; +} + +void hook_checks() +{ + const auto open_ex = hook("RegOpenKeyExW", &fake_open_ex); + const auto open = hook("RegOpenKeyW", &fake_open); + const auto query_fn = hook("RegQueryValueExW", &fake_query); + const auto get = hook("RegGetValueW", &fake_get); + const auto close = hook("RegCloseKey", &fake_close); + check("every registry name has a hook", open_ex && open && query_fn && get && close); + if (!(open_ex && open && query_fn && get && close)) return; + const HMODULE exe = GetModuleHandleW(nullptr); + check("other names have no hook", !registry_hook_for(exe, "RegSetValueExW", reinterpret_cast(&fake_close))); + check("a hook is never kept as the real function", !registry_hook_for(exe, "RegCloseKey", reinterpret_cast(close))); + + const wchar_t* oem_path = L"Software\\Microsoft\\Windows NT\\CurrentVersion\\OEM"; + HKEY key = nullptr, other = nullptr; + check("OEM key opens through the hook", open_ex(HKEY_LOCAL_MACHINE, oem_path, 0, KEY_READ, &key) == ERROR_SUCCESS && key == fake_oem); + check("other key opens through the hook", open_ex(HKEY_LOCAL_MACHINE, L"Software\\Other", 0, KEY_READ, &other) == ERROR_SUCCESS); + + LSTATUS status = 0; + device(nullptr, false); + int before = real_queries; + query(query_fn, key, L"ConsoleMode", &status); + check("unset: the read reaches the registry", real_queries == before + 1 && status == ERROR_FILE_NOT_FOUND); + + device("6", true); + before = real_queries; + DWORD value = query(query_fn, key, L"ConsoleMode", &status); + check("6: Series S answered locally", status == ERROR_SUCCESS && value == 0x60 && real_queries == before); + + device("7", true); + value = query(query_fn, key, L"ConsoleMode", &status); + check("7: Series X answered locally", status == ERROR_SUCCESS && value == 0x64 && real_queries == before); + + DWORD type = 0, bytes = 0; + status = query_fn(key, L"ConsoleMode", nullptr, &type, nullptr, &bytes); + check("7: size query", status == ERROR_SUCCESS && bytes == 4 && type == REG_DWORD); + + DWORD got = 0, got_bytes = sizeof(got); + before = real_gets; + status = get(HKEY_LOCAL_MACHINE, oem_path, L"ConsoleMode", RRF_RT_REG_DWORD, &type, &got, &got_bytes); + check("7: RegGetValueW by path answered locally", status == ERROR_SUCCESS && got == 0x64 && real_gets == before); + + device("1", false); + before = real_queries; + query(query_fn, key, L"ConsoleMode", &status); + check("1: missing, as on a PC", status == ERROR_FILE_NOT_FOUND && real_queries == before); + + device("7", false); + before = real_queries; + query(query_fn, key, L"OtherValue", &status); + check("7: another value passes through", real_queries == before + 1); + query(query_fn, other, L"ConsoleMode", &status); + check("7: ConsoleMode under another key passes through", real_queries == before + 2); + device("not-a-number", false); + query(query_fn, key, L"ConsoleMode", &status); + check("a value that is not a number passes through", real_queries == before + 3); + + HKEY second = nullptr; + device("7", true); + check("RegOpenKeyW opens the OEM key", open(HKEY_LOCAL_MACHINE, oem_path, &second) == ERROR_SUCCESS && second == fake_oem); + check("RegCloseKey reaches the registry", close(key) == ERROR_SUCCESS && real_closes == 1); + device("7", false); + before = real_queries; + query(query_fn, key, L"ConsoleMode", &status); + check("a closed OEM handle passes through", real_queries == before + 1); + + // A full table of OEM handles: one more open is logged once and not tracked. + const char* full_line = "OEM key handles already open, another is not tracked"; + check("no full-table line before the table fills", x2w_local::fixture_log.find(full_line) == std::string::npos); + HKEY extra = nullptr; + for (int i = 0; i < 17; ++i) open_ex(HKEY_LOCAL_MACHINE, oem_path, 0, KEY_READ, &extra); + const std::size_t full_at = x2w_local::fixture_log.find(full_line); + check("a full OEM handle table is logged", full_at != std::string::npos); + check("the full-table line is logged once", full_at != std::string::npos && + x2w_local::fixture_log.find(full_line, full_at + 1) == std::string::npos); + close(second); + check("closing the OEM handle empties the table", !oem_key(fake_oem)); + + device(nullptr, false); + const std::string& log = x2w_local::fixture_log; + check("open is logged", log.find("RegOpenKeyExW opened the OEM key, real status 0") != std::string::npos); + check("pass-through is logged", log.find("RegQueryValueExW ConsoleMode passed through -> status 2") != std::string::npos); + check("answer is logged", log.find("ConsoleMode -> 0x64 for X2W_DEVICE_TYPE=7") != std::string::npos); +} + +// ---- a package DLL with the same export names ----------------------------------------------------- +constexpr LSTATUS decoy_status = 0x5EC0; // startup_console_mode_decoy.cpp + +struct Import { + const char* name; + void* bound; +}; +struct ImportDll { + const char* dll; + std::vector imports; +}; + +// Synthetic PE32+ image with one regular import descriptor per entry, each slot already bound. +std::vector build_image(const std::vector& dlls, std::vector>* slots) +{ + namespace patch = x2w_runtime_patch; + std::vector image(0x1000, 0); + auto* dos = reinterpret_cast(image.data()); + dos->e_magic = 0x5A4D; + dos->e_lfanew = 0x80; + auto* nt = image.data() + 0x80; + *reinterpret_cast(nt) = 0x00004550; + *reinterpret_cast(nt + 24) = 0x20B; + auto* dirs = reinterpret_cast(nt + 24 + 112); + dirs[1].virtual_address = 0x200; + dirs[1].size = static_cast(sizeof(patch::ImportDesc) * (dlls.size() + 1)); + std::uint32_t next = 0x400; + const auto take = [&](std::size_t bytes) { + const std::uint32_t at = next; + next = static_cast((next + bytes + 7) & ~std::size_t{7}); + return at; + }; + slots->clear(); + for (std::size_t d = 0; d < dlls.size(); ++d) { + auto* imp = reinterpret_cast(image.data() + 0x200) + d; + const std::size_t count = dlls[d].imports.size(); + imp->original_first_thunk = take(8 * (count + 1)); + imp->first_thunk = take(8 * (count + 1)); + imp->name = take(std::strlen(dlls[d].dll) + 1); + std::memcpy(image.data() + imp->name, dlls[d].dll, std::strlen(dlls[d].dll) + 1); + slots->emplace_back(); + for (std::size_t i = 0; i < count; ++i) { + const char* name = dlls[d].imports[i].name; + const std::uint32_t hint = take(2 + std::strlen(name) + 1); + std::memcpy(image.data() + hint + 2, name, std::strlen(name) + 1); + reinterpret_cast(image.data() + imp->original_first_thunk)[i].value = hint; + reinterpret_cast(image.data() + imp->first_thunk)[i].value = + reinterpret_cast(dlls[d].imports[i].bound); + slots->back().push_back(imp->first_thunk + static_cast(8 * i)); + } + } + return image; +} + +// What hooked_get_proc_address returns: the hook for a registry provider, else the real export. +FARPROC resolve(HMODULE module, const char* name) +{ + const FARPROC real = GetProcAddress(module, name); + const FARPROC hooked = real ? registry_hook_for(module, name, real) : nullptr; + return hooked ? hooked : real; +} + +void* remembered(RegistryImport which) { return real_registry[which].load(); } + +void decoy_checks(HMODULE decoy, const char* pass) +{ + using SeenFn = LONG(WINAPI*)(); + const auto seen = reinterpret_cast(GetProcAddress(decoy, "decoy_calls")); + void* const decoy_open = reinterpret_cast(GetProcAddress(decoy, "RegOpenKeyExW")); + void* const decoy_query = reinterpret_cast(GetProcAddress(decoy, "RegQueryValueExW")); + const std::string label = std::string(pass) + ": "; + const auto say = [&](const char* what, bool ok) { check((label + what).c_str(), ok); }; + say("the decoy exports both registry names", seen && decoy_open && decoy_query); + if (!(seen && decoy_open && decoy_query)) return; + + // GetProcAddress on the decoy: its own exports, which keep their own result. + const auto open_fn = reinterpret_cast(resolve(decoy, "RegOpenKeyExW")); + const auto query_fn = reinterpret_cast(resolve(decoy, "RegQueryValueExW")); + say("GetProcAddress(decoy, RegOpenKeyExW) is the decoy's export", reinterpret_cast(open_fn) == decoy_open); + say("GetProcAddress(decoy, RegQueryValueExW) is the decoy's export", reinterpret_cast(query_fn) == decoy_query); + LONG before = seen(); + HKEY out = nullptr; + LSTATUS status = 0; + query(query_fn, fake_other, L"ConsoleMode", &status); + say("the decoy's RegQueryValueExW answers its own result", status == decoy_status && seen() == before + 1); + say("the decoy's RegOpenKeyExW answers its own result", + open_fn(HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows NT\\CurrentVersion\\OEM", 0, KEY_READ, &out) == decoy_status && + seen() == before + 2); + say("a decoy address is refused under the provider module", + !registry_hook_for(GetModuleHandleW(nullptr), "RegQueryValueExW", reinterpret_cast(decoy_query))); + + // A synthetic IAT: the decoy by name, advapi32.dll by name but bound to the decoy, and + // advapi32.dll bound to the fake registry (the one entry that is rewritten). + std::vector> slots; + auto image = build_image({{"startup_console_mode_decoy.dll", {{"RegOpenKeyExW", decoy_open}, {"RegQueryValueExW", decoy_query}}}, + {"ADVAPI32.dll", {{"RegQueryValueExW", decoy_query}}}, + {"advapi32.dll", {{"RegQueryValueExW", reinterpret_cast(&fake_query)}, + {"RegCloseKey", reinterpret_cast(&fake_close)}}}}, + &slots); + const auto slot = [&](std::size_t d, std::size_t i) { return *reinterpret_cast(image.data() + slots[d][i]); }; + const int patched = patch_registry_imports(image.data(), image.size()); + say("only the provider-bound imports are rewritten", patched == 2); + say("the decoy's RegOpenKeyExW slot is untouched", slot(0, 0) == decoy_open); + say("the decoy's RegQueryValueExW slot is untouched", slot(0, 1) == decoy_query); + say("advapi32.dll bound to the decoy is untouched", slot(1, 0) == decoy_query); + say("advapi32.dll bound to the registry is rewritten", + slot(2, 0) == registry_hooks[reg_query_value_ex_w] && slot(2, 1) == registry_hooks[reg_close_key]); + before = seen(); + query(reinterpret_cast(slot(0, 1)), fake_other, L"ConsoleMode", &status); + say("a call through the decoy's slot reaches the decoy", status == decoy_status && seen() == before + 1); + + // Neither route made the decoy the real registry: the hooks still reach the fake registry. + say("the decoy's RegOpenKeyExW is never remembered", remembered(reg_open_key_ex_w) != decoy_open); + say("the decoy's RegQueryValueExW is never remembered", + remembered(reg_query_value_ex_w) != decoy_query && remembered(reg_query_value_ex_w) == reinterpret_cast(&fake_query)); + before = seen(); + const int real_before = real_queries; + query(reinterpret_cast(registry_hooks[reg_query_value_ex_w]), fake_other, L"ConsoleMode", &status); + say("the hook still reaches the registry, not the decoy", + status == ERROR_FILE_NOT_FOUND && real_queries == real_before + 1 && seen() == before); +} + +void provider_checks(HMODULE decoy) +{ + const HMODULE advapi = LoadLibraryW(L"advapi32.dll"); // this EXE does not import it + check("advapi32.dll is a registry provider", registry_provider_module(advapi)); + check("kernelbase.dll is a registry provider", registry_provider_module(GetModuleHandleW(L"kernelbase.dll"))); + check("advapi32.dll's RegQueryValueExW lies in a provider", + advapi && registry_provider_address(reinterpret_cast(GetProcAddress(advapi, "RegQueryValueExW")))); + check("the decoy is not a registry provider", decoy && !registry_provider_module(decoy)); + check("import names: advapi32.dll in any case", registry_provider_dll("ADVAPI32.dll")); + check("import names: the registry API set", registry_provider_dll("api-ms-win-core-registry-l1-1-0.dll")); + check("import names: kernelbase.dll", registry_provider_dll("KernelBase.dll")); + check("import names: the decoy is refused", !registry_provider_dll("startup_console_mode_decoy.dll")); + check("import names: a longer name is refused", !registry_provider_dll("advapi32.dll.x")); + check("import names: another API set is refused", !registry_provider_dll("api-ms-win-core-file-l1-1-0.dll")); +} +} // namespace + +int main(int argc, char** argv) +{ + const char* decoy_path = nullptr; + for (int i = 1; i < argc; ++i) { + if (std::strcmp(argv[i], "--control") == 0) { + if (i + 1 < argc && std::strcmp(argv[i + 1], "provider") == 0) { + registry_any_provider = true; // name-only matching; the decoy checks must fail + ++i; + } else { + control = true; + } + } else if (std::strcmp(argv[i], "--decoy") == 0 && i + 1 < argc) { + decoy_path = argv[++i]; + } + } + pure_checks(); + std::string decoy_file = decoy_path ? decoy_path : ""; + for (char& c : decoy_file) + if (c == '/') c = '\\'; + const HMODULE decoy = decoy_path ? LoadLibraryA(decoy_file.c_str()) : nullptr; + check("load the decoy DLL (--decoy)", decoy != nullptr); + if (!registry_any_provider) provider_checks(decoy); + // Before hook_checks registers the fake registry, so a name-only match would keep the decoy first. + if (decoy) { + SetEnvironmentVariableA("X2W_DEVICE_TYPE", nullptr); + decoy_checks(decoy, "decoy, switch unset"); + SetEnvironmentVariableA("X2W_DEVICE_TYPE", "7"); + decoy_checks(decoy, "decoy, X2W_DEVICE_TYPE=7"); + SetEnvironmentVariableA("X2W_DEVICE_TYPE", nullptr); + } + hook_checks(); + if (failures) { + std::printf("startup_console_mode: FAIL (%d)\n", failures); + return 1; + } + std::puts("startup_console_mode: ok"); + return 0; +} diff --git a/tests/startup_console_mode_decoy.cpp b/tests/startup_console_mode_decoy.cpp new file mode 100644 index 000000000..d0fa5f677 --- /dev/null +++ b/tests/startup_console_mode_decoy.cpp @@ -0,0 +1,28 @@ +// Source-built package-style DLL for startup_console_mode: exports RegOpenKeyExW and +// RegQueryValueExW under the registry names (startup_console_mode_decoy.def) with a result no +// registry returns. The console-mode hooks must leave it alone: neither route may hook it or keep +// its address as the real registry function. +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include + +namespace { +LONG calls; +constexpr LONG decoy_status = 0x5EC0; +} + +extern "C" LONG WINAPI decoy_calls() { return InterlockedCompareExchange(&calls, 0, 0); } + +extern "C" LONG WINAPI decoy_open_key_ex_w(HKEY, LPCWSTR, DWORD, REGSAM, PHKEY out) +{ + InterlockedIncrement(&calls); + if (out) *out = reinterpret_cast(static_cast(0xDEC0)); + return decoy_status; +} + +extern "C" LONG WINAPI decoy_query_value_ex_w(HKEY, LPCWSTR, LPDWORD, LPDWORD, LPBYTE, LPDWORD) +{ + InterlockedIncrement(&calls); + return decoy_status; +} diff --git a/tests/startup_console_mode_decoy.def b/tests/startup_console_mode_decoy.def new file mode 100644 index 000000000..8e0e44b36 --- /dev/null +++ b/tests/startup_console_mode_decoy.def @@ -0,0 +1,5 @@ +LIBRARY startup_console_mode_decoy +EXPORTS + RegOpenKeyExW = decoy_open_key_ex_w + RegQueryValueExW = decoy_query_value_ex_w + decoy_calls diff --git a/tests/startup_runtime_proxy_scope/decoy.cpp b/tests/startup_runtime_proxy_scope/decoy.cpp index ddba2565e..86f8aefe3 100644 --- a/tests/startup_runtime_proxy_scope/decoy.cpp +++ b/tests/startup_runtime_proxy_scope/decoy.cpp @@ -1,4 +1,5 @@ -// Unrelated DLL that also exports QueryApiImpl; must not become the cached gaming-runtime provider. +// Unrelated DLL that also exports QueryApiImpl and RegQueryValueExW; must not become the cached +// gaming-runtime provider or the remembered registry function. #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif @@ -6,6 +7,7 @@ namespace { LONG calls; +LONG registry_calls; } extern "C" __declspec(dllexport) LONG WINAPI query_calls() { return InterlockedCompareExchange(&calls, 0, 0); } @@ -16,3 +18,12 @@ extern "C" __declspec(dllexport) HRESULT WINAPI QueryApiImpl(const GUID*, const if (out) *out = nullptr; return 0xA11C0001; // distinct from the fake xgameruntime path } + +extern "C" LONG WINAPI registry_query_calls() { return InterlockedCompareExchange(®istry_calls, 0, 0); } + +// Exported as RegQueryValueExW (decoy.def): a result no registry returns. +extern "C" LONG WINAPI decoy_reg_query_value_ex_w(HKEY, LPCWSTR, LPDWORD, LPDWORD, LPBYTE, LPDWORD) +{ + InterlockedIncrement(®istry_calls); + return 0x5EC1; +} diff --git a/tests/startup_runtime_proxy_scope/decoy.def b/tests/startup_runtime_proxy_scope/decoy.def index 223c116b5..9da19864b 100644 --- a/tests/startup_runtime_proxy_scope/decoy.def +++ b/tests/startup_runtime_proxy_scope/decoy.def @@ -2,3 +2,5 @@ LIBRARY startup_runtime_proxy_decoy EXPORTS QueryApiImpl query_calls + RegQueryValueExW = decoy_reg_query_value_ex_w + registry_query_calls diff --git a/tests/startup_runtime_proxy_scope/host.cpp b/tests/startup_runtime_proxy_scope/host.cpp index ec4221b3e..516e65269 100644 --- a/tests/startup_runtime_proxy_scope/host.cpp +++ b/tests/startup_runtime_proxy_scope/host.cpp @@ -4,7 +4,8 @@ // unrelated decoy that also exports QueryApiImpl, then a helper beside the EXE. The helper's // GetProcAddress IAT is rewritten after linking (outside LdrDllNotification). Looking up // QueryApiImpl on xgameruntime must return the proxy; the same name on the decoy must still be the -// decoy's export. No game files. +// decoy's export. RegQueryValueExW is hooked on advapi32.dll only: the decoy's same-named export stays +// its own, with X2W_DEVICE_TYPE unset and set, and never becomes the registry the hook calls. No game files. #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif @@ -25,6 +26,8 @@ void check(const char* label, bool ok) using ResolveFn = FARPROC(WINAPI*)(HMODULE); using QueryFn = HRESULT(WINAPI*)(const GUID*, const GUID*, void**); +using RegQueryFn = LONG(WINAPI*)(HKEY, LPCWSTR, LPDWORD, LPDWORD, LPBYTE, LPDWORD); +using SeenFn = LONG(WINAPI*)(); std::wstring dir_of_self() { @@ -69,6 +72,11 @@ int main() const FARPROC xgr_query = xgr ? GetProcAddress(xgr, "QueryApiImpl") : nullptr; check("xgameruntime exports QueryApiImpl", xgr_query != nullptr); check("decoy and xgameruntime exports differ", decoy_query && xgr_query && decoy_query != xgr_query); + const FARPROC decoy_reg = decoy ? GetProcAddress(decoy, "RegQueryValueExW") : nullptr; + check("decoy exports RegQueryValueExW", decoy_reg != nullptr); + const HMODULE advapi = LoadLibraryW(L"advapi32.dll"); + const FARPROC advapi_reg = advapi ? GetProcAddress(advapi, "RegQueryValueExW") : nullptr; + check("advapi32.dll exports RegQueryValueExW", advapi_reg != nullptr && advapi_reg != decoy_reg); const HMODULE carrier = load_beside(dir, L"startup_runtime_proxy_carrier.dll"); check("load proxy carrier", carrier != nullptr); @@ -99,7 +107,6 @@ int main() check("helper GetProcAddress(decoy) stays original", helper_decoy == decoy_query); // Intended call: invoke the proxied entry; the fake xgameruntime must run. - using SeenFn = LONG(WINAPI*)(); const auto xgr_seen = xgr ? reinterpret_cast(GetProcAddress(xgr, "query_calls")) : nullptr; const auto decoy_seen = decoy ? reinterpret_cast(GetProcAddress(decoy, "query_calls")) : nullptr; const LONG xgr_before = xgr_seen ? xgr_seen() : -1; @@ -109,6 +116,32 @@ int main() check("proxied call reached xgameruntime", xgr_seen && xgr_seen() == xgr_before + 1); check("decoy call reached decoy only", decoy_seen && decoy_seen() == decoy_before + 1); + // Registry names, with the switch unset and set. The decoy is looked up first each time, so a + // match by name alone would keep the decoy as the registry the hook calls. + const auto decoy_reg_seen = decoy ? reinterpret_cast(GetProcAddress(decoy, "registry_query_calls")) : nullptr; + DWORD type = 0, bytes = 0; + const LONG expect_real = advapi_reg ? reinterpret_cast(advapi_reg)(nullptr, L"ConsoleMode", nullptr, &type, nullptr, &bytes) : -1; + check("advapi32.dll's own answer differs from the decoy's", expect_real != 0x5EC1); + for (const wchar_t* device : {static_cast(nullptr), L"7"}) { + SetEnvironmentVariableW(L"X2W_DEVICE_TYPE", device); + const std::string pass = device ? "X2W_DEVICE_TYPE=7: " : "switch unset: "; + const FARPROC host_decoy_reg = decoy ? GetProcAddress(decoy, "RegQueryValueExW") : nullptr; + check((pass + "host GetProcAddress(decoy, RegQueryValueExW) stays original").c_str(), host_decoy_reg == decoy_reg); + const LONG decoy_before = decoy_reg_seen ? decoy_reg_seen() : -1; + const LONG decoy_answer = + host_decoy_reg ? reinterpret_cast(host_decoy_reg)(nullptr, L"ConsoleMode", nullptr, &type, nullptr, &bytes) : -1; + check((pass + "decoy RegQueryValueExW answers its own result").c_str(), + decoy_answer == 0x5EC1 && decoy_reg_seen && decoy_reg_seen() == decoy_before + 1); + const FARPROC host_advapi_reg = advapi ? GetProcAddress(advapi, "RegQueryValueExW") : nullptr; + check((pass + "host GetProcAddress(advapi32, RegQueryValueExW) is hooked").c_str(), + host_advapi_reg && host_advapi_reg != advapi_reg && host_advapi_reg != decoy_reg); + const LONG hooked_answer = + host_advapi_reg ? reinterpret_cast(host_advapi_reg)(nullptr, L"ConsoleMode", nullptr, &type, nullptr, &bytes) : -1; + check((pass + "hooked RegQueryValueExW reaches advapi32.dll, not the decoy").c_str(), + hooked_answer == expect_real && decoy_reg_seen && decoy_reg_seen() == decoy_before + 1); + } + SetEnvironmentVariableW(L"X2W_DEVICE_TYPE", nullptr); + if (failures) { std::printf("startup_runtime_proxy_scope: FAIL (%d)\n", failures); return 1; From c99b7b894baa210f50c30ac6bc92f27a0ae30433 Mon Sep 17 00:00:00 2001 From: pigalot Date: Thu, 26 Nov 2026 01:45:53 +0000 Subject: [PATCH 050/240] runtime: composite the presented planes in the output window (#2647) * runtime: composite the presented planes in the output window A console present (CommandQueue slot 32) can carry several planes. The output window showed plane 0 alone; on a two-plane present plane 0 was black and plane 1 held the picture. The window now composites the planes bottom to top: the lowest drawn plane opaque (its alpha ignored), each later plane blended by its own alpha (src-alpha / inv-src-alpha) in plane order. Unreadable or empty records, surfaces the presenter cannot draw and repeats of a surface are left out. X2W_PRESENT_PLANE= shows one plane alone for diagnosis, and the first presents log each plane. The draw (shaders, opaque and blend pipelines, per-plane draws) moves into plane_compositor.h, shared by the window presenter and a new WARP readback fixture. New fixtures with negative controls: startup_present_planes (record layout and order) and startup_present_composite_warp (single-plane baseline, stacked transparent, partly transparent and opaque overlays, skipped repeats; the control composites only the black first plane). * runtime: keep the plane composite opt-in and tighten its control The output window shows plane 0 alone again by default; the multi-plane composite runs only with the experimental X2W_PRESENT_COMPOSITE=1. The baseline capture is restored: the frame capture, the presented signature, the surface dump and the x2w-render presented readback read plane 0's first resource as before. Under the switch the highest plane above plane 0 is sampled separately and logged as "x2w-render raw plane (not composited)". The WARP control is renamed startup_present_composite_overlay_removed_control_warp. It runs the baseline, stacked and skipped cases, then removes the overlays, and passes only on "control ok:", printed when the baseline matched, every fence completed without device removal and the overlay-free picture differs from the stacked expectation in exactly the six overlay cells. Any FAIL line, including setup failure, a fence that does not complete or device removal, now fails it. * Keep the default window presenter single-plane at setup --------- Co-authored-by: Royoo <3230853833@qq.com> --- CMakeLists.txt | 22 ++ docs/startup-runtime.md | 63 +++ src/startup_stubs/d3d12_present.inl | 118 ++---- src/startup_stubs/d3d12_xs_device.cpp | 144 ++++++- src/startup_stubs/plane_compositor.h | 186 +++++++++ src/startup_stubs/present_planes.h | 61 +++ tests/startup_present_composite_warp.cpp | 481 +++++++++++++++++++++++ tests/startup_present_planes_check.cpp | 89 +++++ 8 files changed, 1066 insertions(+), 98 deletions(-) create mode 100644 src/startup_stubs/plane_compositor.h create mode 100644 src/startup_stubs/present_planes.h create mode 100644 tests/startup_present_composite_warp.cpp create mode 100644 tests/startup_present_planes_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index c8612e7b3..68a025209 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2007,6 +2007,28 @@ foreach(adapter IN ITEMS warp hardware) add_test(NAME startup_sharedexp_target_${adapter} COMMAND offscreen_check ${adapter} --startup-sharedexp-target) set_tests_properties(startup_sharedexp_target_${adapter} PROPERTIES TIMEOUT 45 SKIP_RETURN_CODE 77) endforeach() +# Presented planes (src/startup_stubs/present_planes.h): the plane record layout and the composite order +# on synthetic records. The control reads 0x40-byte records and composites plane 0 alone, and must FAIL. +add_executable(startup_present_planes tests/startup_present_planes_check.cpp) +target_include_directories(startup_present_planes PRIVATE src) +target_compile_features(startup_present_planes PRIVATE cxx_std_17) +add_test(NAME startup_present_planes COMMAND startup_present_planes) +add_test(NAME startup_present_planes_control COMMAND startup_present_planes --control) +set_tests_properties(startup_present_planes_control PROPERTIES PASS_REGULAR_EXPRESSION "FAIL: ") +# The window's plane composite (src/startup_stubs/plane_compositor.h) read back on WARP: a single-plane +# baseline, stacked planes with transparent, partly transparent and opaque overlays, and skipped repeats +# and empty records. The control then removes the overlays and passes only on "control ok:", printed when +# the baseline matched, every fence completed and the overlay-free picture differs from the stacked +# expectation in exactly the overlay cells. Any FAIL line (setup, fence, device removal, pixels) fails it. +add_executable(startup_present_composite_warp tests/startup_present_composite_warp.cpp) +target_include_directories(startup_present_composite_warp PRIVATE src) +target_compile_features(startup_present_composite_warp PRIVATE cxx_std_17) +target_link_libraries(startup_present_composite_warp PRIVATE d3d12 dxgi d3dcompiler) +add_test(NAME startup_present_composite_warp COMMAND startup_present_composite_warp) +add_test(NAME startup_present_composite_overlay_removed_control_warp COMMAND startup_present_composite_warp --control) +set_tests_properties(startup_present_composite_warp PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +set_tests_properties(startup_present_composite_overlay_removed_control_warp PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60 + PASS_REGULAR_EXPRESSION "control ok: baseline matched" FAIL_REGULAR_EXPRESSION "FAIL: ") # Static samplers built from smp and smpc manifest lines (src/startup_stubs/translated_sampler_bindings.h). add_executable(startup_sampler_comparison_check tests/startup_sampler_comparison_check.cpp) target_include_directories(startup_sampler_comparison_check PRIVATE src) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 0f3b0cdef..62b42c17e 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -275,6 +275,67 @@ presenter, its owned window and a dialog stay visible. Where the host lets the t it also checks that the foreground moves to the output window. A run under Wine did; the fixture prints which case applied. +### Presented planes + +A console present (CommandQueue slot 32) carries a plane count and an array of plane records +(`src/startup_stubs/present_planes.h`). Measured from the first presents: one record is 0x48 bytes, +with +0x00 a frame token, +0x08 the resource count and +0x10 a pointer to the resource array. On the +Series S profile a title presented two planes: plane 0 at 1920x1080 stayed black and plane 1 at +3840x2160 held the picture, with alpha 255 wherever it drew. Showing plane 0 alone gave a black +window. Why plane 0 stays black is not known. + +By default the output window still shows plane 0 alone, as before the planes were decoded. The +experimental `X2W_PRESENT_COMPOSITE=1` makes it composite the planes instead +(`src/startup_stubs/plane_compositor.h`, shared by the window presenter and its fixture). It stays +opt-in until a matched comparison on the same executable, with this change alone, shows what it does +to a real present. The contract under the switch: + +- Order: plane 0 first, each later plane over it, in plane order (`composite_steps`). At most four + planes are read. +- The lowest drawn plane is opaque: its colour replaces the window and its alpha is ignored. +- Each later plane is blended by its own alpha, not premultiplied: + `rgb = src.rgb * src.a + dst.rgb * (1 - src.a)`, `a = src.a + dst.a * (1 - src.a)` (D3D12 + `SRC_ALPHA` / `INV_SRC_ALPHA`, alpha `ONE` / `INV_SRC_ALPHA`). Alpha 0 leaves what is below, + alpha 255 replaces it, and the window alpha stays 255. +- Left out: a plane whose record or resource array is unreadable or empty, a surface that is not a + known resource or that the presenter cannot draw (`present_view_format.h`), and a repeat of a + surface already drawn. If plane 0 is left out, the next drawn plane is the opaque base. +- Each plane is scaled to the whole window with a linear, clamped sampler. The planes' source and + destination rectangles in the record (after +0x10) are not decoded; a plane that covers only part + of the screen on the console is stretched here. +- The baseline capture is unchanged with or without the switch: the frame capture, the presented + signature, `X2W_D3D12_DUMP_SURFACE` and the `x2w-render presented` readback all read plane 0's + first resource, as before. Under the switch the highest plane above plane 0 with a known resource + is also sampled on the same frames, before compositing, and logged as a raw plane: + + ```text + x2w-render raw plane (not composited): surface x format , sample , mean level /255, mean alpha /255 + ``` + + Neither line is the composited window picture. + +The first presents and every 300th log each plane: + +```text +x2w-present frame plane /: x format flags=0x +``` + +`ctest --preset dev --no-tests=error -R '^startup_present_planes(_control)?$'` checks the record layout +and the composite order on synthetic records; the control reads 0x40-byte records and composites +plane 0 alone, and must print `FAIL:`. +`ctest --preset dev --no-tests=error -R '^startup_present_composite_(warp|overlay_removed_control_warp)$'` +draws source-built planes through the same records, `composite_steps` and compositor (directly, without +the switch) into a 64x32 RGBA8 target on WARP and reads every texel back: a single plane is shown as is (including a cell with alpha 0); a black +plane 0 under a plane with alpha 0, 128, 5 and 255 cells and a third plane with opaque and +half-transparent cells gives 0, 128, 5 and 255 levels and the plane-order result 128,0,127 for half +red over blue (within 1 for blended cells, exact otherwise); a repeated surface and an empty record +are left out. The control runs the same cases, then removes the overlays and composites the black +plane 0 alone. It passes only on `control ok: baseline matched, ...`, printed when the baseline and +stacked cases matched, every fence completed without device removal, and the overlay-free picture is +black and differs from the stacked expectation in exactly the six cells the overlays draw. Any `FAIL:` +line fails it, including queue, compositor, target or plane setup, a fence that does not complete and +device removal. Both exit 77 without a WARP adapter. + ## Null Texture2D descriptors When the adapter lacks typed UAV support for B5G5R5A1_UNORM or render-target support for @@ -1358,6 +1419,8 @@ ctest --preset dev --no-tests=error -R '^startup_trap_header(_prefix_control|_pr | `X2W_DEPTH_STATE=1` | translated draws of slot 57 pipelines take their depth-stencil state and stencil reference from state block A instead of the desktop default (depth and stencil off); a refused block keeps the default. Off by default, then nothing changes: see [Shortcuts that are known to be wrong](#shortcuts-that-are-known-to-be-wrong) | | `X2W_PRESENT_SIGNATURE_EVERY=` | in render mode, samples a coarse signature of the presented picture every `n` presents from the start, without a script request (`0` off). Unset, sampling starts, every 4 presents, only once a script with a `wait` asks for it: see [Waiting for the presented picture](#waiting-for-the-presented-picture) | | `X2W_D3D12_DUMP_SURFACE=` | writes the last presented surface | +| `X2W_PRESENT_COMPOSITE=1` | experimental, in render mode: the output window composites every presented plane, bottom to top, instead of showing plane 0 alone, and the highest plane above plane 0 is sampled as `x2w-render raw plane (not composited)`. Off by default; the baseline capture and `x2w-render presented` read plane 0 either way. See [Presented planes](#presented-planes) | +| `X2W_PRESENT_PLANE=` | diagnostic, in render mode: the output window shows plane `n` of each present alone (plane 0 when `n` is past the count), with or without `X2W_PRESENT_COMPOSITE`. See [Presented planes](#presented-planes) | | `X2W_HIDE_TITLE_WINDOW=1` (`run.sh --hide-title-window`) | once a present has reached the output window, hides the title's own window; dialogs stay visible, and the window is shown again when a present misses the output window, until the next present reaches it ([Output window and fallback diagnostics](#output-window-and-fallback-diagnostics)). Keyboard input to the title after the hide is not measured. Off by default on every host | | `X2W_DRAW_DUMP_FRAME=`, `X2W_DRAW_DUMP_DIR` | Full-resolution RGB snapshots of single-sample RGBA8/BGRA8 UNORM or sRGB targets after translated draws. A later present writes completed queue-fenced copies. At most 48 copies are pending or written; a copy whose fence reports device removal (`UINT64_MAX`) is released unwritten and frees its slot (`src/startup_stubs/draw_dump_tracking.h`, `ctest --preset dev --no-tests=error -R '^startup_dump_fence_(removed_control_)?warp$' -V`; the control must fail). | | `X2W_AUDIO_PERMISSIVE=1` | enables the audio stand-ins. Without a DSP provider, `XDspActivate` clears valid outputs and reports unavailable resources, and failed `XDspSubmitCommand` calls leave the sequence unchanged. `XDspDeactivate` and `XDspDisconnect` refuse null and unknown handles with `E_INVALIDARG`. | diff --git a/src/startup_stubs/d3d12_present.inl b/src/startup_stubs/d3d12_present.inl index 58bec8cf4..40ff3f6a5 100644 --- a/src/startup_stubs/d3d12_present.inl +++ b/src/startup_stubs/d3d12_present.inl @@ -2,25 +2,25 @@ // Included inside d3d12_xs_device.cpp's anonymous namespace, before queue_present. // // A flip-model swap chain on the title window, created on the queue the title presents with; each -// present draws the presented surface into the back buffer with a full-window triangle (the surface -// is usually larger than the window) and flips. Diagnostics go to the window title, because GDI -// drawing does not mix with a flip-model swap chain. +// present draws its planes into the back buffer, bottom to top, with the plane compositor +// (plane_compositor.h: one full-window triangle a plane; a surface is usually larger than the +// window), and flips. Plane 0 alone by default; every plane with X2W_PRESENT_COMPOSITE=1. Diagnostics go to the window title, because GDI drawing does not mix with a +// flip-model swap chain. struct WindowPresenter { IDXGISwapChain3* chain = nullptr; ID3D12DescriptorHeap* targets = nullptr; - ID3D12DescriptorHeap* textures = nullptr; ID3D12Resource* buffers[2] = {}; ID3D12CommandAllocator* allocator = nullptr; ID3D12GraphicsCommandList* list = nullptr; - ID3D12RootSignature* root = nullptr; - ID3D12PipelineState* pipeline = nullptr; + x2w_startup::PlaneCompositor compositor; // shaders, pipelines and plane views ID3D12Fence* fence = nullptr; HANDLE reached = nullptr; UINT64 fence_value = 0; UINT width = 0, height = 0; bool failed = false; }; +constexpr UINT window_planes = 4; WindowPresenter window_presenter; LONG window_presents; @@ -97,7 +97,7 @@ HWND output_window() return output_handle; } -bool create_window_presenter(ID3D12CommandQueue* queue, HWND window) +bool create_window_presenter(ID3D12CommandQueue* queue, HWND window, UINT plane_capacity) { WindowPresenter& p = window_presenter; ID3D12Device* device = device_of(the_device); @@ -124,9 +124,7 @@ bool create_window_presenter(ID3D12CommandQueue* queue, HWND window) if (chain1) chain1->Release(); if (factory) factory->Release(); const D3D12_DESCRIPTOR_HEAP_DESC target_heap{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 2, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; - const D3D12_DESCRIPTOR_HEAP_DESC texture_heap{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; if (SUCCEEDED(hr)) hr = device->CreateDescriptorHeap(&target_heap, IID_PPV_ARGS(&p.targets)); - if (SUCCEEDED(hr)) hr = device->CreateDescriptorHeap(&texture_heap, IID_PPV_ARGS(&p.textures)); const UINT step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV); for (UINT i = 0; SUCCEEDED(hr) && i < 2; ++i) { hr = p.chain->GetBuffer(i, IID_PPV_ARGS(&p.buffers[i])); @@ -138,100 +136,52 @@ bool create_window_presenter(ID3D12CommandQueue* queue, HWND window) if (SUCCEEDED(hr)) hr = p.list->Close(); if (SUCCEEDED(hr)) hr = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&p.fence)); p.reached = CreateEventW(nullptr, FALSE, FALSE, nullptr); - static const char source[] = - "Texture2D surface : register(t0); SamplerState smooth : register(s0);\n" - "struct V { float4 position : SV_Position; float2 uv : TEXCOORD0; };\n" - "V vs(uint id : SV_VertexID) { V o; o.uv = float2((id << 1) & 2, id & 2); o.position = float4(o.uv * float2(2, -2) + float2(-1, 1), 0, 1); return o; }\n" - "float4 ps(V i) : SV_Target0 { return float4(surface.Sample(smooth, i.uv).rgb, 1); }\n"; - ID3DBlob* vs = nullptr; - ID3DBlob* ps = nullptr; - ID3DBlob* blob = nullptr; - if (SUCCEEDED(hr)) hr = D3DCompile(source, sizeof(source) - 1, "present", nullptr, nullptr, "vs", "vs_5_0", 0, 0, &vs, nullptr); - if (SUCCEEDED(hr)) hr = D3DCompile(source, sizeof(source) - 1, "present", nullptr, nullptr, "ps", "ps_5_0", 0, 0, &ps, nullptr); - if (SUCCEEDED(hr)) { - const D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; - D3D12_ROOT_PARAMETER parameter{}; - parameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; - parameter.DescriptorTable = {1, &range}; - parameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; - D3D12_STATIC_SAMPLER_DESC sampler{}; - sampler.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR; - sampler.AddressU = sampler.AddressV = sampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; - sampler.MaxLOD = D3D12_FLOAT32_MAX; - sampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; - const D3D12_ROOT_SIGNATURE_DESC desc{1, ¶meter, 1, &sampler, D3D12_ROOT_SIGNATURE_FLAG_NONE}; - hr = D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1_0, &blob, nullptr); - if (SUCCEEDED(hr)) hr = device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&p.root)); - } - if (SUCCEEDED(hr)) { - D3D12_GRAPHICS_PIPELINE_STATE_DESC desc{}; - desc.pRootSignature = p.root; - desc.VS = {vs->GetBufferPointer(), vs->GetBufferSize()}; - desc.PS = {ps->GetBufferPointer(), ps->GetBufferSize()}; - desc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; - desc.SampleMask = ~0u; - desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; - desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; - desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; - desc.NumRenderTargets = 1; - desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; - desc.SampleDesc.Count = 1; - hr = device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&p.pipeline)); - } - if (vs) vs->Release(); - if (ps) ps->Release(); - if (blob) blob->Release(); + if (SUCCEEDED(hr)) hr = p.compositor.create(device, DXGI_FORMAT_R8G8B8A8_UNORM, plane_capacity); log("x2w-present window swap chain %ux%u -> 0x%08lx", p.width, p.height, static_cast(hr)); check_device("window presenter", 0); return SUCCEEDED(hr); } -// Draws `surface` (resting in COMMON) into the window and flips. Returns false if not shown. -bool present_to_window(ID3D12CommandQueue* queue, ID3D12Resource* surface) +// Whether the window presenter can draw `surface` (present_view_format.h); logs the first refusals. +bool presentable_surface(ID3D12Resource* surface) +{ + if (!surface) return false; + const D3D12_RESOURCE_DESC desc = surface->GetDesc(); + if (x2w_startup::present_surface_supported(desc)) return true; + static LONG refused; + if (first_calls(refused, 4)) + log("x2w-present surface dim=%d samples=%u flags=0x%x format=%d not supported (present_view_format.h)", + desc.Dimension, desc.SampleDesc.Count, desc.Flags, desc.Format); + return false; +} + +// Composites the steps of a present (present_planes.h composite_steps) into the window and flips. +// plane_surfaces[step.plane] is that plane's surface (resting in COMMON and presentable), or null to +// leave it out. Returns false if not shown. +bool present_to_window(ID3D12CommandQueue* queue, const x2w_startup::PlaneStep* steps, unsigned count, + ID3D12Resource* const* plane_surfaces, UINT plane_capacity) { X2W_ZONE("window present (blit + fence wait)"); WindowPresenter& p = window_presenter; - if (p.failed || !queue || !surface) return false; - const D3D12_RESOURCE_DESC desc = surface->GetDesc(); - if (!x2w_startup::present_surface_supported(desc)) { - static LONG refused; - if (first_calls(refused, 4)) - log("x2w-present surface dim=%d samples=%u flags=0x%x format=%d not supported (present_view_format.h)", - desc.Dimension, desc.SampleDesc.Count, desc.Flags, desc.Format); - return false; - } + if (p.failed || !queue || !steps || !count || !plane_surfaces) return false; HWND window = output_window(); if (!window) return false; - if (!p.chain && !create_window_presenter(queue, window)) { + if (!p.chain && !create_window_presenter(queue, window, plane_capacity)) { p.failed = true; return false; } ID3D12Device* device = device_of(the_device); - const DXGI_FORMAT view_format = x2w_startup::present_view_format(desc.Format); - D3D12_SHADER_RESOURCE_VIEW_DESC view{}; - view.Format = view_format; - view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; - view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - view.Texture2D.MipLevels = 1; - device->CreateShaderResourceView(surface, &view, p.textures->GetCPUDescriptorHandleForHeapStart()); const UINT index = p.chain->GetCurrentBackBufferIndex(); const D3D12_CPU_DESCRIPTOR_HANDLE target{p.targets->GetCPUDescriptorHandleForHeapStart().ptr + SIZE_T{index} * device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV)}; - if (FAILED(p.allocator->Reset()) || FAILED(p.list->Reset(p.allocator, p.pipeline))) return false; - transition(p.list, surface, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); + if (FAILED(p.allocator->Reset()) || FAILED(p.list->Reset(p.allocator, p.compositor.initial_pipeline()))) return false; transition(p.list, p.buffers[index], D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET); - const D3D12_VIEWPORT viewport{0, 0, static_cast(p.width), static_cast(p.height), 0, 1}; - const D3D12_RECT scissor{0, 0, static_cast(p.width), static_cast(p.height)}; - p.list->SetGraphicsRootSignature(p.root); - p.list->SetDescriptorHeaps(1, &p.textures); - p.list->SetGraphicsRootDescriptorTable(0, p.textures->GetGPUDescriptorHandleForHeapStart()); - p.list->RSSetViewports(1, &viewport); - p.list->RSSetScissorRects(1, &scissor); - p.list->OMSetRenderTargets(1, &target, FALSE, nullptr); - p.list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - p.list->DrawInstanced(3, 1, 0, 0); + const UINT drawn = p.compositor.record(device, p.list, target, p.width, p.height, steps, count, plane_surfaces); transition(p.list, p.buffers[index], D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT); - transition(p.list, surface, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COMMON); + if (!drawn) { + p.list->Close(); + return false; + } if (FAILED(p.list->Close())) { p.failed = true; return false; diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 0dcb9e742..432e63b43 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -56,6 +56,8 @@ #include "startup_stubs/slice_footprints.h" #include "startup_stubs/present_signature_sampler.h" +#include "startup_stubs/present_planes.h" +#include "startup_stubs/plane_compositor.h" #include #include "command_list_slot_names.h" @@ -1843,8 +1845,22 @@ SRWLOCK shown_lock = SRWLOCK_INIT; char shown_note[160] = "no frame read back yet"; void write_file(const wchar_t* path, const void* data, std::size_t bytes); -void read_back_presented(ID3D12CommandQueue* queue, ID3D12Resource* surface) -{ +// raw_plane < 0: the baseline capture of the presented surface (plane 0), reduced for the window and +// logged as `x2w-render presented`. raw_plane >= 0 (X2W_PRESENT_COMPOSITE=1 only): a sample of that +// plane's own surface, before compositing, logged as `x2w-render raw plane `; it leaves the window +// copy, the note and the dump alone. Neither is the composited window picture. +void read_back_presented(ID3D12CommandQueue* queue, ID3D12Resource* surface, int raw_plane = -1) +{ + const bool raw = raw_plane >= 0; + char failure[160] = ""; + const auto report_failure = [&] { + if (!raw) { + std::snprintf(shown_note, sizeof(shown_note), "%s", failure); + return; + } + static LONG raw_failures; + if (first_calls(raw_failures, 4)) log("x2w-render raw plane %d (not composited): %s", raw_plane, failure); + }; static ID3D12CommandAllocator* allocator; static ID3D12GraphicsCommandList* list; static ID3D12Fence* fence; @@ -1860,7 +1876,8 @@ void read_back_presented(ID3D12CommandQueue* queue, ID3D12Resource* surface) const bool rgba = desc.Format == DXGI_FORMAT_R8G8B8A8_UNORM || desc.Format == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; const bool bgra = desc.Format == DXGI_FORMAT_B8G8R8A8_UNORM || desc.Format == DXGI_FORMAT_B8G8R8A8_UNORM_SRGB; if ((!rgba && !bgra) || total == 0 || total == ~0ull) { - std::snprintf(shown_note, sizeof(shown_note), "presented surface format %d not shown yet", desc.Format); + std::snprintf(failure, sizeof(failure), "presented surface format %d not shown yet", desc.Format); + report_failure(); return; } HRESULT hr = S_OK; @@ -1890,7 +1907,8 @@ void read_back_presented(ID3D12CommandQueue* queue, ID3D12Resource* surface) if (SUCCEEDED(hr)) hr = allocator->Reset(); if (SUCCEEDED(hr)) hr = list->Reset(allocator, nullptr); if (FAILED(hr)) { - std::snprintf(shown_note, sizeof(shown_note), "readback setup failed 0x%08lx", static_cast(hr)); + std::snprintf(failure, sizeof(failure), "readback setup failed 0x%08lx", static_cast(hr)); + report_failure(); return; } transition(list, surface, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); @@ -1908,32 +1926,36 @@ void read_back_presented(ID3D12CommandQueue* queue, ID3D12Resource* surface) queue->Signal(fence, ++fence_value); fence->SetEventOnCompletion(fence_value, event); if (WaitForSingleObject(event, 3000) != WAIT_OBJECT_0) { - std::snprintf(shown_note, sizeof(shown_note), "readback timed out"); + std::snprintf(failure, sizeof(failure), "readback timed out"); + report_failure(); return; } void* mapped = nullptr; const D3D12_RANGE range{0, static_cast(total)}; if (FAILED(readback->Map(0, &range, &mapped))) return; - AcquireSRWLockExclusive(&shown_lock); - shown_pixels.resize(shown_width * shown_height); - std::uint64_t sum = 0; + if (!raw) { + AcquireSRWLockExclusive(&shown_lock); + shown_pixels.resize(shown_width * shown_height); + } + std::uint64_t sum = 0, alpha_sum = 0; for (int y = 0; y < shown_height; ++y) { const auto* row = static_cast(mapped) + footprint.Offset + static_cast(y) * desc.Height / shown_height * footprint.Footprint.RowPitch; for (int x = 0; x < shown_width; ++x) { const unsigned char* texel = row + static_cast(x) * desc.Width / shown_width * 4; const unsigned r = rgba ? texel[0] : texel[2], g = texel[1], b = rgba ? texel[2] : texel[0]; - shown_pixels[y * shown_width + x] = (r << 16) | (g << 8) | b; + if (!raw) shown_pixels[y * shown_width + x] = (r << 16) | (g << 8) | b; sum += r + g + b; + alpha_sum += texel[3]; } } - ReleaseSRWLockExclusive(&shown_lock); + if (!raw) ReleaseSRWLockExclusive(&shown_lock); // X2W_D3D12_DUMP_SURFACE=: every 40th read-back is also written at full resolution as a // 32-bit BMP (overwritten each time), for looking at detail the reduced overlay copy loses. { static wchar_t dump_path[MAX_PATH]; static const bool dump = GetEnvironmentVariableW(L"X2W_D3D12_DUMP_SURFACE", dump_path, MAX_PATH) != 0; - if (dump && (shown_frames % 4) == 3 && desc.Width <= 8192 && desc.Height <= 8192) { + if (!raw && dump && (shown_frames % 4) == 3 && desc.Width <= 8192 && desc.Height <= 8192) { const UINT width = static_cast(desc.Width), height = desc.Height; std::vector file(54 + std::size_t{width} * height * 4); const std::uint32_t header[] = {static_cast(file.size()), 0, 54, 40, width, static_cast(-static_cast(height)), @@ -1956,6 +1978,15 @@ void read_back_presented(ID3D12CommandQueue* queue, ID3D12Resource* surface) } const D3D12_RANGE none{0, 0}; readback->Unmap(0, &none); + if (raw) { + static LONG raw_frames; + const LONG count = InterlockedIncrement(&raw_frames); + if ((count > 0 && count <= 3) || count % 40 == 0) + log("x2w-render raw plane %d (not composited): surface %llux%u format %d, sample %ld, mean level %.2f/255, mean alpha %.2f/255", + raw_plane, desc.Width, desc.Height, desc.Format, count, sum / (3.0 * shown_width * shown_height), + alpha_sum / (1.0 * shown_width * shown_height)); + return; + } const LONG count = InterlockedIncrement(&shown_frames); std::snprintf(shown_note, sizeof(shown_note), "surface %llux%u format %d, readback %ld, mean level %.2f/255", desc.Width, desc.Height, desc.Format, count, sum / (3.0 * shown_width * shown_height)); @@ -6093,6 +6124,74 @@ void report_budget(ID3D12CommandQueue* queue) log("x2w-budget local=%s nonlocal=%s%s unmeasured=%llu", local, nonlocal, text, counts.unmeasured); } +// X2W_PRESENT_COMPOSITE=1 (experimental, docs/startup-runtime.md#presented-planes): the output +// window composites every presented plane. Unset, the window shows plane 0 alone, as before. +bool present_composite_enabled() +{ + static const bool on = x2w_local::env_on("X2W_PRESENT_COMPOSITE"); + return on; +} + +// The planes the output window draws for a present, resolved to real resources it can draw. +// X2W_PRESENT_PLANE= (diagnostic) keeps plane n alone (plane 0 when n is past the count). Otherwise +// plane 0 alone is kept, unless X2W_PRESENT_COMPOSITE=1 keeps every plane for the composite +// (present_planes.h). The baseline capture and readback do not use this: they read plane 0 as before. +struct PresentedPlanes { + ID3D12Resource* drawable[window_planes] = {}; // per plane, null when left out + x2w_startup::PlaneStep steps[window_planes]; + unsigned count = 0; // composite steps + unsigned top_plane = 0; // the highest kept plane with a known resource + ID3D12Resource* top = nullptr; // its surface +}; +PresentedPlanes presented_planes(UINT planes, const void* plane_parameters) +{ + static const long wanted = [] { + char value[16]{}; + return GetEnvironmentVariableA("X2W_PRESENT_PLANE", value, sizeof(value)) ? std::atol(value) : -1L; + }(); + const auto readable = [](const void* address, std::size_t bytes) { return x2w_local::readable(address, bytes); }; + PresentedPlanes out; + std::uint64_t shown[window_planes] = {}; + const unsigned total = planes < window_planes ? planes : window_planes; + const unsigned only = wanted >= 0 ? (static_cast(wanted) < planes ? static_cast(wanted) : 0u) + : present_composite_enabled() ? ~0u + : 0u; + for (unsigned i = 0; i < total; ++i) { + if (only != ~0u && i != only) continue; + const std::uint64_t resource = x2w_startup::present_plane_resource(plane_parameters, planes, i, readable); + Wrapper* const surface = resource ? as_wrapper(reinterpret_cast(resource)) : nullptr; + if (!surface || surface->own().kind != resource_kind || !surface->own().real) continue; + auto* const real = static_cast(surface->own().real); + out.top_plane = i; + out.top = real; + if (!presentable_surface(real)) continue; + out.drawable[i] = real; + shown[i] = resource; + } + out.count = x2w_startup::composite_steps(shown, total, out.steps, window_planes); + return out; +} + +// The first presents and every 300th: each plane's first resource and its shape. +void log_present_planes(LONG frame, UINT planes, const void* plane_parameters) +{ + if (frame > 2 && frame % 300 != 0) return; + static LONG lines; + if (!first_calls(lines, 24)) return; + const auto readable = [](const void* address, std::size_t bytes) { return x2w_local::readable(address, bytes); }; + for (unsigned i = 0; i < planes && i < 4; ++i) { + const std::uint64_t resource = x2w_startup::present_plane_resource(plane_parameters, planes, i, readable); + Wrapper* const surface = resource ? as_wrapper(reinterpret_cast(resource)) : nullptr; + if (!surface || surface->own().kind != resource_kind || !surface->own().real) { + log("x2w-present frame %ld plane %u/%u: resource %p is not a known resource", frame, i, planes, reinterpret_cast(resource)); + continue; + } + const D3D12_RESOURCE_DESC desc = static_cast(surface->own().real)->GetDesc(); + log("x2w-present frame %ld plane %u/%u: %llux%u format %d flags=0x%x", frame, i, planes, + static_cast(desc.Width), desc.Height, desc.Format, static_cast(desc.Flags)); + } +} + // Queue slot 32 (Xbox order): (plane count, plane parameters*, present parameters*) -> HRESULT, the // console present. Nothing is shown yet; frames are counted and a heartbeat is logged. HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_parameters, const void* present_parameters) @@ -6128,7 +6227,13 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa } } bool shown_in_window = false; + log_present_planes(frame, planes, plane_parameters); + // X2W_PRESENT_COMPOSITE=1: the highest plane above plane 0, sampled raw below. + ID3D12Resource* raw_surface = nullptr; + unsigned raw_plane = 0; { + // The baseline: plane 0's first resource, captured, sampled and read back as before the planes + // were decoded, with or without X2W_PRESENT_COMPOSITE. Wrapper* surface = nullptr; const auto* words = static_cast(plane_parameters); if (planes && words && x2w_local::readable(words, 0x18) && words[1] >= 1 && x2w_local::readable(reinterpret_cast(words[2]), 8)) @@ -6136,9 +6241,18 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa capture::present(frame, surface); if (surface && surface->own().kind == resource_kind) red_producers().present(static_cast(surface->own().real)); - // Render mode: the presented surface goes to the title's window through a swap chain. - if (render_mode() && surface && surface->own().kind == resource_kind && surface->own().real) - shown_in_window = present_to_window(static_cast(self->own().real), static_cast(surface->own().real)); + // Render mode: the presented planes go to the output window through a swap chain: plane 0 alone + // by default, every plane with X2W_PRESENT_COMPOSITE=1. The compositor draws the steps in order. + if (render_mode()) { + const PresentedPlanes presented = presented_planes(planes, plane_parameters); + if (presented.count) + shown_in_window = present_to_window(static_cast(self->own().real), presented.steps, presented.count, + presented.drawable, present_composite_enabled() ? window_planes : 1); + if (present_composite_enabled() && presented.top && presented.top_plane > 0) { + raw_surface = presented.top; + raw_plane = presented.top_plane; + } + } InterlockedExchange(&last_frame_shown, shown_in_window ? 1 : 0); if (render_mode()) present_signature(self, surface, frame); } @@ -6161,6 +6275,8 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa std::snprintf(shown_note, sizeof(shown_note), "presented object %p is not a known resource", *reinterpret_cast(words[2])); } + // The raw plane sample is that plane's own surface, not the composited window picture. + if (raw_surface) read_back_presented(static_cast(self->own().real), raw_surface, static_cast(raw_plane)); } if (shown_in_window) { if (frame % 30 == 0) { diff --git a/src/startup_stubs/plane_compositor.h b/src/startup_stubs/plane_compositor.h new file mode 100644 index 000000000..b41cd5895 --- /dev/null +++ b/src/startup_stubs/plane_compositor.h @@ -0,0 +1,186 @@ +// Experimental (docs/startup-runtime.md#presented-planes): the draw that composites the planes of a +// console present into one render target. The output window (d3d12_present.inl) records it into its +// back buffer; tests/startup_present_composite_warp.cpp records it into a texture it reads back. +// +// Contract: the steps come from composite_steps (present_planes.h), bottom to top. The first step +// drawn replaces the target with its plane's colour and ignores that plane's alpha (nothing is below +// it); each later step with `blended` set is drawn over the result with +// colour = src.rgb * src.a + dst.rgb * (1 - src.a), alpha = src.a + dst.a * (1 - src.a) +// (SRC_ALPHA / INV_SRC_ALPHA, ONE / INV_SRC_ALPHA), so after an opaque base the target alpha stays 1. +// A step without `blended` (or whose plane has no surface) after the first is drawn opaque or left +// out. Each plane is one full-target triangle sampled with a linear, clamped sampler: a plane the +// size of the target is copied texel for texel; a larger or smaller plane is scaled to fit. +// Plane surfaces must rest in COMMON and pass present_surface_supported (present_view_format.h); they +// are left in COMMON. The target must be in RENDER_TARGET. +#pragma once + +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include + +#include +#include + +#include "startup_stubs/present_planes.h" +#include "startup_stubs/present_view_format.h" + +namespace x2w_startup { + +class PlaneCompositor { +public: + // Create the opaque pipeline and a heap for up to `max_planes` views. More than one plane also needs a blend pipeline. + HRESULT create(ID3D12Device* device, DXGI_FORMAT target_format, UINT max_planes) + { + release(); + max_planes_ = max_planes ? max_planes : 1; + static const char source[] = + "Texture2D surface : register(t0); SamplerState smooth : register(s0);\n" + "struct V { float4 position : SV_Position; float2 uv : TEXCOORD0; };\n" + "V vs(uint id : SV_VertexID) { V o; o.uv = float2((id << 1) & 2, id & 2); o.position = float4(o.uv * float2(2, -2) + float2(-1, 1), 0, 1); return o; }\n" + "float4 ps(V i) : SV_Target0 { return float4(surface.Sample(smooth, i.uv).rgb, 1); }\n" + "float4 ps_over(V i) : SV_Target0 { return surface.Sample(smooth, i.uv); }\n"; + ID3DBlob* vs = nullptr; + ID3DBlob* ps = nullptr; + ID3DBlob* ps_over = nullptr; + ID3DBlob* blob = nullptr; + const D3D12_DESCRIPTOR_HEAP_DESC heap{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, max_planes_, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + HRESULT hr = device->CreateDescriptorHeap(&heap, IID_PPV_ARGS(&textures_)); + if (SUCCEEDED(hr)) hr = D3DCompile(source, sizeof(source) - 1, "present", nullptr, nullptr, "vs", "vs_5_0", 0, 0, &vs, nullptr); + if (SUCCEEDED(hr)) hr = D3DCompile(source, sizeof(source) - 1, "present", nullptr, nullptr, "ps", "ps_5_0", 0, 0, &ps, nullptr); + if (SUCCEEDED(hr) && max_planes_ > 1) + hr = D3DCompile(source, sizeof(source) - 1, "present", nullptr, nullptr, "ps_over", "ps_5_0", 0, 0, &ps_over, nullptr); + if (SUCCEEDED(hr)) { + const D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; + D3D12_ROOT_PARAMETER parameter{}; + parameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + parameter.DescriptorTable = {1, &range}; + parameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + D3D12_STATIC_SAMPLER_DESC sampler{}; + sampler.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR; + sampler.AddressU = sampler.AddressV = sampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; + sampler.MaxLOD = D3D12_FLOAT32_MAX; + sampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + const D3D12_ROOT_SIGNATURE_DESC desc{1, ¶meter, 1, &sampler, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + hr = D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1_0, &blob, nullptr); + if (SUCCEEDED(hr)) hr = device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&root_)); + } + if (SUCCEEDED(hr)) { + D3D12_GRAPHICS_PIPELINE_STATE_DESC desc{}; + desc.pRootSignature = root_; + desc.VS = {vs->GetBufferPointer(), vs->GetBufferSize()}; + desc.PS = {ps->GetBufferPointer(), ps->GetBufferSize()}; + desc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + desc.SampleMask = ~0u; + desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + desc.NumRenderTargets = 1; + desc.RTVFormats[0] = target_format; + desc.SampleDesc.Count = 1; + hr = device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&opaque_)); + if (SUCCEEDED(hr) && ps_over) { + desc.PS = {ps_over->GetBufferPointer(), ps_over->GetBufferSize()}; + D3D12_RENDER_TARGET_BLEND_DESC& blend = desc.BlendState.RenderTarget[0]; + blend.BlendEnable = TRUE; + blend.SrcBlend = D3D12_BLEND_SRC_ALPHA; + blend.DestBlend = D3D12_BLEND_INV_SRC_ALPHA; + blend.BlendOp = D3D12_BLEND_OP_ADD; + blend.SrcBlendAlpha = D3D12_BLEND_ONE; + blend.DestBlendAlpha = D3D12_BLEND_INV_SRC_ALPHA; + blend.BlendOpAlpha = D3D12_BLEND_OP_ADD; + hr = device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&blend_)); + } + } + if (vs) vs->Release(); + if (ps) ps->Release(); + if (ps_over) ps_over->Release(); + if (blob) blob->Release(); + if (FAILED(hr)) release(); + return hr; + } + + // The pipeline a list can be reset with before record(). + ID3D12PipelineState* initial_pipeline() const { return opaque_; } + UINT max_planes() const { return max_planes_; } + + // Records the composite into `list` (open) over `target` (width x height, in RENDER_TARGET). + // steps[0..count) as from composite_steps; plane_surfaces[step.plane] is that plane's surface, + // or null to leave the step out. Returns the number of planes drawn (0: nothing recorded). + UINT record(ID3D12Device* device, ID3D12GraphicsCommandList* list, D3D12_CPU_DESCRIPTOR_HANDLE target, UINT width, + UINT height, const PlaneStep* steps, unsigned count, ID3D12Resource* const* plane_surfaces) + { + if (!opaque_ || !list || !steps || !plane_surfaces) return 0; + ID3D12Resource* drawn[16] = {}; + bool blended[16] = {}; + UINT planes = 0; + const UINT limit = max_planes_ < 16 ? max_planes_ : 16; + for (unsigned i = 0; i < count && planes < limit; ++i) { + ID3D12Resource* const surface = plane_surfaces[steps[i].plane]; + if (!surface) continue; + blended[planes] = planes != 0 && steps[i].blended; // the first plane drawn is the opaque base + drawn[planes++] = surface; + } + if (!planes) return 0; + const UINT step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + for (UINT i = 0; i < planes; ++i) { + D3D12_SHADER_RESOURCE_VIEW_DESC view{}; + view.Format = present_view_format(drawn[i]->GetDesc().Format); + view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + view.Texture2D.MipLevels = 1; + device->CreateShaderResourceView(drawn[i], &view, + D3D12_CPU_DESCRIPTOR_HANDLE{textures_->GetCPUDescriptorHandleForHeapStart().ptr + SIZE_T{i} * step}); + } + for (UINT i = 0; i < planes; ++i) transition(list, drawn[i], D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); + const D3D12_VIEWPORT viewport{0, 0, static_cast(width), static_cast(height), 0, 1}; + const D3D12_RECT scissor{0, 0, static_cast(width), static_cast(height)}; + list->SetGraphicsRootSignature(root_); + list->SetDescriptorHeaps(1, &textures_); + list->RSSetViewports(1, &viewport); + list->RSSetScissorRects(1, &scissor); + list->OMSetRenderTargets(1, &target, FALSE, nullptr); + list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + for (UINT i = 0; i < planes; ++i) { + list->SetPipelineState(blended[i] ? blend_ : opaque_); + list->SetGraphicsRootDescriptorTable(0, D3D12_GPU_DESCRIPTOR_HANDLE{textures_->GetGPUDescriptorHandleForHeapStart().ptr + UINT64{i} * step}); + list->DrawInstanced(3, 1, 0, 0); + } + for (UINT i = 0; i < planes; ++i) transition(list, drawn[i], D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COMMON); + return planes; + } + + void release() + { + if (blend_) blend_->Release(); + if (opaque_) opaque_->Release(); + if (root_) root_->Release(); + if (textures_) textures_->Release(); + blend_ = opaque_ = nullptr; + root_ = nullptr; + textures_ = nullptr; + } + +private: + static void transition(ID3D12GraphicsCommandList* list, ID3D12Resource* resource, D3D12_RESOURCE_STATES from, D3D12_RESOURCE_STATES to) + { + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier.Transition.pResource = resource; + barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + barrier.Transition.StateBefore = from; + barrier.Transition.StateAfter = to; + list->ResourceBarrier(1, &barrier); + } + + ID3D12DescriptorHeap* textures_ = nullptr; + ID3D12RootSignature* root_ = nullptr; + ID3D12PipelineState* opaque_ = nullptr; // the bottom plane, alpha ignored + ID3D12PipelineState* blend_ = nullptr; // later planes, over it by their alpha + UINT max_planes_ = 0; +}; + +} // namespace x2w_startup diff --git a/src/startup_stubs/present_planes.h b/src/startup_stubs/present_planes.h new file mode 100644 index 000000000..0c71c7ac1 --- /dev/null +++ b/src/startup_stubs/present_planes.h @@ -0,0 +1,61 @@ +// Experimental (docs/startup-runtime.md): the planes of a console present (CommandQueue slot 32). +// +// The present takes a plane count and an array of plane records. Measured from the first presents +// of a console executable: one record is 0x48 bytes, with +0x00 a frame token, +0x08 the resource +// count and +0x10 a pointer to the array of resources; the second plane's token sits at +0x48 when +// two planes are presented. The fields after +0x10 (source and destination rectangles, flags) are +// not decoded here. Pure: the caller passes a readability check, so a control can run it on +// synthetic records. +#pragma once + +#include +#include +#include + +namespace x2w_startup { +inline constexpr std::size_t present_plane_stride = 0x48; + +// The first resource of plane `index`, or 0 when the plane, its record or its resource array is +// not readable or has no resource. readable(address, bytes) answers whether memory can be read. +template +std::uint64_t present_plane_resource(const void* planes, unsigned count, unsigned index, Readable&& readable, + std::size_t stride = present_plane_stride) +{ + if (!planes || index >= count) return 0; + const auto* record = static_cast(planes) + std::size_t{index} * stride; + if (!readable(record, 0x18)) return 0; + std::uint64_t resources = 0, resource_count = 0, first = 0; + std::memcpy(&resource_count, record + 0x08, 8); + std::memcpy(&resources, record + 0x10, 8); + if (resource_count == 0 || !resources || !readable(reinterpret_cast(resources), 8)) return 0; + std::memcpy(&first, reinterpret_cast(resources), 8); + return first; +} + +// One draw of the window composite: plane `plane`, either replacing what is below (the bottom +// layer) or blended over it by the plane's own alpha. +struct PlaneStep { + unsigned plane = 0; + bool blended = false; +}; + +// The window composite of a present, bottom to top, the way planes stack on the console: plane 0 +// first, each later plane over it. `resources[i]` is plane i's surface, 0 when it cannot be shown; +// those planes and repeats of a surface already drawn are left out. The lowest drawn plane is +// opaque (nothing is below it), every later one blended. Returns the number of steps written. +// Measured on a two-plane present: plane 0 was black and plane 1, with alpha 255 wherever the +// picture was, held it; showing plane 0 alone gave a black window. +inline unsigned composite_steps(const std::uint64_t* resources, unsigned count, PlaneStep* steps, unsigned max_steps) +{ + unsigned written = 0; + for (unsigned i = 0; resources && i < count && written < max_steps; ++i) { + if (!resources[i]) continue; + bool repeat = false; + for (unsigned j = 0; j < written; ++j) repeat = repeat || resources[steps[j].plane] == resources[i]; + if (repeat) continue; + steps[written] = PlaneStep{i, written != 0}; + ++written; + } + return written; +} +} // namespace x2w_startup diff --git a/tests/startup_present_composite_warp.cpp b/tests/startup_present_composite_warp.cpp new file mode 100644 index 000000000..e7e054724 --- /dev/null +++ b/tests/startup_present_composite_warp.cpp @@ -0,0 +1,481 @@ +// Pixel readback of the presented-plane composite on WARP (docs/startup-runtime.md#presented-planes). +// Source-built planes go through the code the output window uses: synthetic 0x48-byte plane records +// read by present_plane_resource, the order from composite_steps (present_planes.h), and the draws of +// PlaneCompositor (plane_compositor.h) into a 64 x 32 RGBA8 target that is read back. +// +// Contract checked: the bottom plane is drawn opaque, its alpha ignored; each later plane is blended +// over the result in plane order, colour = src * a + dst * (1 - a); the target alpha stays 255; +// repeats of a surface and planes whose record has no readable resource are left out. +// +// Cases: +// baseline one plane of four colours, one cell with alpha 0, shown as is. +// stacked black opaque plane 0; plane 1 with a fully transparent cell, a half-transparent cell, +// a nearly transparent cell (alpha 5) and an opaque cell; plane 2 with an opaque cell, a +// cell blended over plane 1's opaque cell (order) and transparent elsewhere. +// skipped plane 0 black, plane 1 as above, plane 2 the same surface as plane 1, plane 3 a record +// with no resource: the same picture as plane 0 and 1 alone. +// --control runs the same cases and then removes the overlay: stacked composited from the black +// plane 0 alone. It prints "control ok:" and exits 0 only when the baseline and stacked cases matched, +// every fence completed without device removal, and the overlay-free result is black and differs from +// the stacked expectation in exactly the six cells the overlays draw. A setup failure, a missing +// fence, device removal or any other difference prints FAIL and exits 1. +// usage: startup_present_composite_warp [--control] (exit 77 when no WARP adapter is available) +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include + +#include "startup_stubs/plane_compositor.h" +#include "startup_stubs/present_planes.h" + +#include +#include + +#include +#include +#include +#include +#include + +namespace { + +int failures = 0; +void fail(const char* format, const char* a, unsigned b, unsigned c, const unsigned char* got, const unsigned char* want) +{ + ++failures; + std::printf(format, a, b, c, got[0], got[1], got[2], got[3], want[0], want[1], want[2], want[3]); +} + +constexpr UINT width = 64, height = 32; +constexpr UINT columns = 4, rows = 2; // cells of 16 x 16 texels +constexpr UINT cell_w = width / columns, cell_h = height / rows; + +struct Rgba { + unsigned char r, g, b, a; +}; +// A plane picture: one colour per cell, row-major. +using Cells = Rgba[rows][columns]; + +struct Gpu { + ID3D12Device* device = nullptr; + ID3D12CommandQueue* queue = nullptr; + ID3D12CommandAllocator* allocator = nullptr; + ID3D12GraphicsCommandList* list = nullptr; + ID3D12Fence* fence = nullptr; + UINT64 value = 0; + HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + + // Executes the list and waits for its fence. A list that does not close or execute, a fence that + // does not reach the value in time, or one that reports device removal (UINT64_MAX) is a failure. + bool run() + { + const HRESULT closed = list->Close(); + if (FAILED(closed)) { + ++failures; + std::printf("FAIL: command list close 0x%08lx\n", static_cast(closed)); + return false; + } + ID3D12CommandList* lists[] = {list}; + queue->ExecuteCommandLists(1, lists); + const HRESULT signalled = queue->Signal(fence, ++value); + if (SUCCEEDED(signalled) && fence->GetCompletedValue() < value && SUCCEEDED(fence->SetEventOnCompletion(value, event))) + WaitForSingleObject(event, 10000); + const UINT64 completed = fence->GetCompletedValue(); + if (FAILED(signalled) || completed == UINT64_MAX || completed < value) { + ++failures; + std::printf("FAIL: fence %llu not completed (completed %llu, signal 0x%08lx)\n", static_cast(value), + static_cast(completed), static_cast(signalled)); + return false; + } + ++fences; + allocator->Reset(); + list->Reset(allocator, nullptr); + return true; + } + unsigned fences = 0; // fences that completed +}; + +void barrier(ID3D12GraphicsCommandList* list, ID3D12Resource* resource, D3D12_RESOURCE_STATES from, D3D12_RESOURCE_STATES to) +{ + D3D12_RESOURCE_BARRIER b{}; + b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + b.Transition.pResource = resource; + b.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + b.Transition.StateBefore = from; + b.Transition.StateAfter = to; + list->ResourceBarrier(1, &b); +} + +D3D12_RESOURCE_DESC texture_desc(D3D12_RESOURCE_FLAGS flags) +{ + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = width; + desc.Height = height; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + desc.SampleDesc.Count = 1; + desc.Flags = flags; + return desc; +} + +ID3D12Resource* buffer(Gpu& gpu, D3D12_HEAP_TYPE type, UINT64 bytes, D3D12_RESOURCE_STATES state) +{ + D3D12_HEAP_PROPERTIES heap{}; + heap.Type = type; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = bytes; + desc.Height = 1; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + ID3D12Resource* out = nullptr; + gpu.device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, IID_PPV_ARGS(&out)); + return out; +} + +// A plane surface holding `cells`, left in COMMON as the compositor expects. +ID3D12Resource* plane(Gpu& gpu, const Cells& cells) +{ + const D3D12_RESOURCE_DESC desc = texture_desc(D3D12_RESOURCE_FLAG_NONE); + D3D12_HEAP_PROPERTIES heap{}; + heap.Type = D3D12_HEAP_TYPE_DEFAULT; + ID3D12Resource* texture = nullptr; + if (FAILED(gpu.device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&texture)))) + return nullptr; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; + UINT64 total = 0; + gpu.device->GetCopyableFootprints(&desc, 0, 1, 0, &footprint, nullptr, nullptr, &total); + ID3D12Resource* upload = buffer(gpu, D3D12_HEAP_TYPE_UPLOAD, total, D3D12_RESOURCE_STATE_GENERIC_READ); + void* mapped = nullptr; + upload->Map(0, nullptr, &mapped); + for (UINT y = 0; y < height; ++y) + for (UINT x = 0; x < width; ++x) { + const Rgba& c = cells[y / cell_h][x / cell_w]; + unsigned char* t = static_cast(mapped) + footprint.Offset + std::size_t{y} * footprint.Footprint.RowPitch + x * 4; + t[0] = c.r, t[1] = c.g, t[2] = c.b, t[3] = c.a; + } + upload->Unmap(0, nullptr); + barrier(gpu.list, texture, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST); + D3D12_TEXTURE_COPY_LOCATION to{}, from{}; + to.pResource = texture; + to.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + from.pResource = upload; + from.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + from.PlacedFootprint = footprint; + gpu.list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); + barrier(gpu.list, texture, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON); + const bool ran = gpu.run(); + upload->Release(); + if (!ran) { + texture->Release(); + return nullptr; + } + return texture; +} + +// Plane records as a console present passes them: 0x48 bytes each, +0x08 the resource count and +// +0x10 a pointer to the resource array. A null surface gives a record with no resource. +struct Records { + alignas(8) unsigned char bytes[4 * x2w_startup::present_plane_stride] = {}; + std::uint64_t arrays[4][1] = {}; + explicit Records(ID3D12Resource* const* surfaces, unsigned count) + { + for (unsigned i = 0; i < count; ++i) { + unsigned char* record = bytes + i * x2w_startup::present_plane_stride; + const std::uint64_t token = 7, resources = surfaces[i] ? 1 : 0; + arrays[i][0] = reinterpret_cast(surfaces[i]); + const std::uint64_t pointer = reinterpret_cast(arrays[i]); + std::memcpy(record + 0x00, &token, 8); + std::memcpy(record + 0x08, &resources, 8); + std::memcpy(record + 0x10, &pointer, 8); + } + } +}; + +struct Target { + ID3D12Resource* texture = nullptr; + ID3D12DescriptorHeap* heap = nullptr; + ID3D12Resource* readback = nullptr; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; +}; + +// Runs the window's composite path on `count` plane records and reads the target back. +// Returns width * height RGBA texels, or nothing when the composite drew no plane. +std::vector composite(Gpu& gpu, x2w_startup::PlaneCompositor& compositor, Target& target, ID3D12Resource* const* surfaces, + unsigned count, unsigned* steps_out) +{ + Records records(surfaces, count); + const auto readable = [&](const void* address, std::size_t bytes) { + const auto* a = static_cast(address); + const auto* lo = reinterpret_cast(&records); + return a >= lo && a + bytes <= lo + sizeof(records); + }; + // As queue_present: plane i's first resource, 0 when the record has none. + std::uint64_t resources[4] = {}; + ID3D12Resource* plane_surfaces[4] = {}; + for (unsigned i = 0; i < count; ++i) { + resources[i] = x2w_startup::present_plane_resource(records.bytes, count, i, readable); + plane_surfaces[i] = reinterpret_cast(resources[i]); + } + x2w_startup::PlaneStep steps[4]; + const unsigned n = x2w_startup::composite_steps(resources, count, steps, 4); + *steps_out = n; + barrier(gpu.list, target.texture, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET); + const float clear[4] = {0.25f, 0.5f, 0.75f, 0.0f}; // nothing of this may survive the opaque base + gpu.list->ClearRenderTargetView(target.heap->GetCPUDescriptorHandleForHeapStart(), clear, 0, nullptr); + const UINT drawn = compositor.record(gpu.device, gpu.list, target.heap->GetCPUDescriptorHandleForHeapStart(), width, height, steps, n, + plane_surfaces); + barrier(gpu.list, target.texture, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE); + D3D12_TEXTURE_COPY_LOCATION to{}, from{}; + to.pResource = target.readback; + to.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + to.PlacedFootprint = target.footprint; + from.pResource = target.texture; + from.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + gpu.list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); + std::vector pixels; + if (!gpu.run() || !drawn) return pixels; + pixels.resize(std::size_t{width} * height * 4); + void* mapped = nullptr; + const D3D12_RANGE range{0, static_cast(target.footprint.Footprint.RowPitch) * height}; + target.readback->Map(0, &range, &mapped); + for (UINT y = 0; y < height; ++y) + std::memcpy(&pixels[std::size_t{y} * width * 4], + static_cast(mapped) + target.footprint.Offset + std::size_t{y} * target.footprint.Footprint.RowPitch, + std::size_t{width} * 4); + const D3D12_RANGE none{0, 0}; + target.readback->Unmap(0, &none); + return pixels; +} + +// Whether every texel of a cell is within `tolerance` of `want` (alpha 255); the first texel off it +// goes to `got`. +bool cell_matches(const std::vector& pixels, UINT row, UINT column, const Rgba& want, int tolerance, unsigned char* got) +{ + const unsigned char w[4] = {want.r, want.g, want.b, 255}; + for (UINT y = row * cell_h; y < (row + 1) * cell_h; ++y) + for (UINT x = column * cell_w; x < (column + 1) * cell_w; ++x) { + const unsigned char* g = &pixels[(std::size_t{y} * width + x) * 4]; + for (int k = 0; k < 4; ++k) + if (std::abs(int{g[k]} - int{w[k]}) > tolerance) { + std::memcpy(got, g, 4); + return false; + } + } + return true; +} + +// Every texel of every cell must be within `tolerance` of the expected colour (alpha 255). +void expect(const char* name, const std::vector& pixels, const Rgba (&want)[rows][columns], const int (&tolerance)[rows][columns]) +{ + if (pixels.empty()) { + ++failures; + std::printf("FAIL: %s: nothing composited\n", name); + return; + } + for (UINT row = 0; row < rows; ++row) + for (UINT column = 0; column < columns; ++column) { + const unsigned char w[4] = {want[row][column].r, want[row][column].g, want[row][column].b, 255}; + bool reported = false; + for (UINT y = row * cell_h; y < (row + 1) * cell_h && !reported; ++y) + for (UINT x = column * cell_w; x < (column + 1) * cell_w && !reported; ++x) { + const unsigned char* g = &pixels[(std::size_t{y} * width + x) * 4]; + for (int k = 0; k < 4 && !reported; ++k) + if (std::abs(int{g[k]} - int{w[k]}) > tolerance[row][column]) { + fail("FAIL: %s cell row %u column %u: got %u,%u,%u,%u want %u,%u,%u,%u\n", name, row, column, g, w); + reported = true; + } + } + if (!reported) + std::printf("%s cell row %u column %u: %u,%u,%u,255 (+/-%d)\n", name, row, column, w[0], w[1], w[2], tolerance[row][column]); + } +} + +} // namespace + +int main(int argc, char** argv) +{ + const bool control = argc > 1 && std::strcmp(argv[1], "--control") == 0; + IDXGIFactory4* factory = nullptr; + IDXGIAdapter* warp = nullptr; + Gpu gpu; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory))) || FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&warp))) || + FAILED(D3D12CreateDevice(warp, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&gpu.device)))) { + std::printf("SKIP: no WARP device\n"); + return 77; + } + const D3D12_COMMAND_QUEUE_DESC queue_desc{D3D12_COMMAND_LIST_TYPE_DIRECT}; + if (FAILED(gpu.device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&gpu.queue))) || + FAILED(gpu.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&gpu.allocator))) || + FAILED(gpu.device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, gpu.allocator, nullptr, IID_PPV_ARGS(&gpu.list))) || + FAILED(gpu.device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&gpu.fence)))) { + std::printf("FAIL: WARP queue setup\n"); + return 1; + } + x2w_startup::PlaneCompositor compositor; + const HRESULT created = compositor.create(gpu.device, DXGI_FORMAT_R8G8B8A8_UNORM, 1); + if (FAILED(created)) { + std::printf("FAIL: compositor setup 0x%08lx\n", static_cast(created)); + return 1; + } + + Target target; + { + const D3D12_RESOURCE_DESC desc = texture_desc(D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET); + D3D12_HEAP_PROPERTIES heap{}; + heap.Type = D3D12_HEAP_TYPE_DEFAULT; + gpu.device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_SOURCE, nullptr, + IID_PPV_ARGS(&target.texture)); + const D3D12_DESCRIPTOR_HEAP_DESC rtv{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + gpu.device->CreateDescriptorHeap(&rtv, IID_PPV_ARGS(&target.heap)); + gpu.device->CreateRenderTargetView(target.texture, nullptr, target.heap->GetCPUDescriptorHandleForHeapStart()); + UINT64 total = 0; + gpu.device->GetCopyableFootprints(&desc, 0, 1, 0, &target.footprint, nullptr, nullptr, &total); + target.readback = buffer(gpu, D3D12_HEAP_TYPE_READBACK, total, D3D12_RESOURCE_STATE_COPY_DEST); + } + if (!target.texture || !target.heap || !target.readback) { + std::printf("FAIL: target setup\n"); + return 1; + } + + // Plane pictures. The baseline plane's last cell has alpha 0 to show that the bottom plane's + // alpha is ignored. + const Cells baseline = {{{200, 40, 10, 255}, {10, 200, 40, 255}, {40, 10, 200, 128}, {250, 250, 250, 255}}, + {{0, 0, 0, 255}, {128, 64, 32, 255}, {1, 2, 3, 255}, {90, 180, 60, 0}}}; + const Cells black = {{{0, 0, 0, 255}, {0, 0, 0, 255}, {0, 0, 0, 255}, {0, 0, 0, 255}}, + {{0, 0, 0, 255}, {0, 0, 0, 255}, {0, 0, 0, 255}, {0, 0, 0, 255}}}; + // Plane 1: row 0 transparent (alpha 0), half (128), nearly transparent (5), opaque; row 1 opaque + // blue under plane 2's blended cell, opaque blue under plane 2's opaque cell, transparent twice. + const Cells overlay = {{{255, 0, 0, 0}, {0, 255, 0, 128}, {255, 255, 255, 5}, {0, 0, 255, 255}}, + {{0, 0, 255, 255}, {0, 0, 255, 255}, {255, 255, 255, 0}, {255, 255, 255, 0}}}; + // Plane 2: row 0 transparent; row 1 half red over blue (order), opaque yellow over blue, opaque + // cyan over black, transparent. + const Cells top = {{{255, 255, 0, 0}, {255, 255, 0, 0}, {255, 255, 0, 0}, {255, 255, 0, 0}}, + {{255, 0, 0, 128}, {255, 255, 0, 255}, {0, 255, 255, 255}, {255, 0, 255, 0}}}; + ID3D12Resource* const p_baseline = plane(gpu, baseline); + ID3D12Resource* const p_black = plane(gpu, black); + ID3D12Resource* const p_overlay = plane(gpu, overlay); + ID3D12Resource* const p_top = plane(gpu, top); + if (!p_baseline || !p_black || !p_overlay || !p_top) { + std::printf("FAIL: plane setup\n"); + return 1; + } + + const int exact[rows][columns] = {{0, 0, 0, 0}, {0, 0, 0, 0}}; + unsigned steps = 0; + + // Baseline: one plane, shown as is, alpha forced to 255. + { + ID3D12Resource* const planes[] = {p_baseline}; + const auto pixels = composite(gpu, compositor, target, planes, 1, &steps); + Rgba want[rows][columns]; + for (UINT r = 0; r < rows; ++r) + for (UINT c = 0; c < columns; ++c) want[r][c] = baseline[r][c]; + if (steps != 1) { + ++failures; + std::printf("FAIL: baseline: %u steps, want 1\n", steps); + } + expect("baseline", pixels, want, exact); + } + + const HRESULT composite_created = compositor.create(gpu.device, DXGI_FORMAT_R8G8B8A8_UNORM, 4); + if (FAILED(composite_created)) { + std::printf("FAIL: multi-plane compositor setup 0x%08lx\n", static_cast(composite_created)); + return 1; + } + + // Stacked: black, overlay, top. + // Expected (UNORM8, src * a/255 + dst * (1 - a/255)): 128/255 of 255 is 128; 5/255 of 255 is 5; + // half red over blue is 128,0,127. + const Rgba stacked_want[rows][columns] = {{{0, 0, 0, 255}, {0, 128, 0, 255}, {5, 5, 5, 255}, {0, 0, 255, 255}}, + {{128, 0, 127, 255}, {255, 255, 0, 255}, {0, 255, 255, 255}, {0, 0, 0, 255}}}; + const int blended[rows][columns] = {{0, 1, 1, 0}, {1, 0, 0, 0}}; + { + ID3D12Resource* const planes[] = {p_black, p_overlay, p_top}; + const auto pixels = composite(gpu, compositor, target, planes, 3, &steps); + if (steps != 3) { + ++failures; + std::printf("FAIL: stacked: %u steps, want 3\n", steps); + } + expect("stacked", pixels, stacked_want, blended); + } + + // Skipped: plane 2 repeats plane 1's surface and plane 3 has no resource. Drawing the repeat + // would blend the half-green cell twice (0,191,0) and the nearly transparent one twice (10). + { + ID3D12Resource* const planes[] = {p_black, p_overlay, p_overlay, nullptr}; + const auto pixels = composite(gpu, compositor, target, planes, 4, &steps); + if (steps != 2) { + ++failures; + std::printf("FAIL: skipped: %u steps, want 2 (plane 0 and plane 1)\n", steps); + } + const Rgba want[rows][columns] = {{{0, 0, 0, 255}, {0, 128, 0, 255}, {5, 5, 5, 255}, {0, 0, 255, 255}}, + {{0, 0, 255, 255}, {0, 0, 255, 255}, {0, 0, 0, 255}, {0, 0, 0, 255}}}; + const int tolerance[rows][columns] = {{0, 1, 1, 0}, {0, 0, 0, 0}}; + expect("skipped", pixels, want, tolerance); + } + + // Control: the overlays removed, stacked is composited from the black plane 0 alone. That must be + // black everywhere, and must differ from the stacked expectation in exactly the cells the overlays + // draw: every cell except row 0 column 0 (plane 1 transparent) and row 1 column 3 (both transparent). + unsigned control_differences = 0; + if (control && !failures) { + const bool overlay_drawn[rows][columns] = {{false, true, true, true}, {true, true, true, false}}; + const Rgba black_want = {0, 0, 0, 255}; + ID3D12Resource* const planes[] = {p_black}; + const auto pixels = composite(gpu, compositor, target, planes, 1, &steps); + if (steps != 1) { + ++failures; + std::printf("FAIL: control: overlay removed: %u steps, want 1\n", steps); + } + if (pixels.empty()) { + ++failures; + std::printf("FAIL: control: overlay removed: nothing composited\n"); + } + for (UINT row = 0; row < rows && !pixels.empty(); ++row) + for (UINT column = 0; column < columns; ++column) { + unsigned char got[4] = {}; + const unsigned char black[4] = {0, 0, 0, 255}; + if (!cell_matches(pixels, row, column, black_want, 0, got)) { + fail("FAIL: %s cell row %u column %u: got %u,%u,%u,%u want %u,%u,%u,%u\n", "control: overlay removed", row, column, got, + black); + continue; + } + const bool differs = !cell_matches(pixels, row, column, stacked_want[row][column], blended[row][column], got); + if (differs) ++control_differences; + if (differs != overlay_drawn[row][column]) { + ++failures; + std::printf("FAIL: control: overlay removed: cell row %u column %u %s the stacked expectation, want it to %s\n", row, + column, differs ? "differs from" : "matches", overlay_drawn[row][column] ? "differ" : "match"); + } else { + std::printf("control: overlay removed: cell row %u column %u %s the stacked expectation\n", row, column, + differs ? "differs from" : "matches"); + } + } + } + + const HRESULT removed = gpu.device->GetDeviceRemovedReason(); + if (FAILED(removed)) { + ++failures; + std::printf("FAIL: device removed 0x%08lx\n", static_cast(removed)); + } + if (failures) { + std::printf("startup_present_composite: FAIL (%d)\n", failures); + return 1; + } + if (control) { + std::printf("control ok: baseline matched, %u fences completed, removing the overlay changed %u of %u cells as expected\n", + gpu.fences, control_differences, rows * columns); + return 0; + } + std::puts("startup_present_composite: ok (baseline, stacked and skipped planes on WARP)"); + return 0; +} diff --git a/tests/startup_present_planes_check.cpp b/tests/startup_present_planes_check.cpp new file mode 100644 index 000000000..88473d3c6 --- /dev/null +++ b/tests/startup_present_planes_check.cpp @@ -0,0 +1,89 @@ +// Checks src/startup_stubs/present_planes.h on synthetic plane records: two 0x48-byte records, each +// with a frame token, a resource count and a pointer to its resource array. +// Also checks the window composite order (composite_steps) on synthetic plane surfaces. +// --control reads the records with a 0x40-byte stride (the record size before the second plane was +// measured) and composites plane 0 alone (the window present before planes were composited); the +// second-plane rows must print FAIL. +#include "startup_stubs/present_planes.h" + +#include +#include + +namespace { +int failures; + +void check(const char* what, bool ok) +{ + if (!ok) { + std::printf("FAIL: %s\n", what); + ++failures; + } +} + +void put(unsigned char* at, std::uint64_t value) { std::memcpy(at, &value, 8); } +} // namespace + +int main(int argc, char** argv) +{ + const bool control = argc > 1 && std::strcmp(argv[1], "--control") == 0; + const std::size_t stride = control ? 0x40 : x2w_startup::present_plane_stride; + const std::uint64_t first_plane[] = {0x1111}, second_plane[] = {0x2222, 0x3333}; + alignas(8) unsigned char records[2 * 0x48] = {}; + alignas(8) unsigned char empty[0x48] = {}; + // Readable: only this fixture's own records and resource arrays. + const auto inside = [](const void* address, std::size_t bytes, const void* base, std::size_t size) { + const auto* a = static_cast(address); + const auto* b = static_cast(base); + return a >= b && a + bytes <= b + size; + }; + const auto readable = [&](const void* address, std::size_t bytes) { + return inside(address, bytes, records, sizeof(records)) || inside(address, bytes, empty, sizeof(empty)) || + inside(address, bytes, first_plane, sizeof(first_plane)) || inside(address, bytes, second_plane, sizeof(second_plane)); + }; + put(records + 0x00, 7); // frame token + put(records + 0x08, 1); + put(records + 0x10, reinterpret_cast(first_plane)); + put(records + 0x48, 7); + put(records + 0x50, 2); + put(records + 0x58, reinterpret_cast(second_plane)); + + using x2w_startup::present_plane_resource; + check("plane 0 resource", present_plane_resource(records, 2, 0, readable, stride) == 0x1111); + check("plane 1 resource (the second record starts at +0x48)", present_plane_resource(records, 2, 1, readable, stride) == 0x2222); + check("a plane past the count has no resource", present_plane_resource(records, 1, 1, readable, stride) == 0); + check("no records", present_plane_resource(nullptr, 2, 0, readable, stride) == 0); + + put(empty + 0x10, reinterpret_cast(first_plane)); + check("a plane with no resources has none", present_plane_resource(empty, 1, 0, readable, stride) == 0); + const auto unreadable = [](const void*, std::size_t) { return false; }; + check("an unreadable record has no resource", present_plane_resource(records, 2, 0, unreadable, stride) == 0); + + // Composite order: the lowest shown plane is opaque, later ones blend over it. + using x2w_startup::PlaneStep; + const auto composite = [&](const std::uint64_t* resources, unsigned count, PlaneStep* steps) { + return x2w_startup::composite_steps(resources, control && count > 1 ? 1 : count, steps, 4); + }; + PlaneStep steps[4]; + const std::uint64_t two[] = {0x1111, 0x2222}; + unsigned n = composite(two, 2, steps); + check("two planes give two steps", n == 2); + check("plane 0 is drawn first, opaque", n >= 1 && steps[0].plane == 0 && !steps[0].blended); + check("plane 1 is drawn over plane 0, blended", n >= 2 && steps[1].plane == 1 && steps[1].blended); + const std::uint64_t missing_base[] = {0, 0x2222}; + n = composite(missing_base, 2, steps); + check("with plane 0 not shown, plane 1 is the opaque base", n == 1 && steps[0].plane == 1 && !steps[0].blended); + const std::uint64_t repeated[] = {0x1111, 0x1111}; + n = x2w_startup::composite_steps(repeated, 2, steps, 4); + check("a surface presented twice is drawn once", n == 1 && steps[0].plane == 0); + const std::uint64_t one[] = {0x1111}; + n = composite(one, 1, steps); + check("one plane is one opaque step", n == 1 && steps[0].plane == 0 && !steps[0].blended); + check("no planes, no steps", x2w_startup::composite_steps(nullptr, 2, steps, 4) == 0); + + if (failures) { + std::printf("startup_present_planes: FAIL (%d)\n", failures); + return 1; + } + std::puts("startup_present_planes: ok"); + return 0; +} From 63ba73a96922ddb09a3cf8bddccbde3efac9cd32 Mon Sep 17 00:00:00 2001 From: thepatrickworld Date: Thu, 26 Nov 2026 02:48:48 +0100 Subject: [PATCH 051/240] startup: give the placed page aliases and the draw dumps the teardown boundary (#2631) * startup: give the placed page aliases and the draw dumps the teardown boundary Four function-local statics in the shim own desktop D3D12 objects and are destroyed during the module's CRT teardown, which runs at process exit after Windows has detached the display driver. #2590 fixed the two the startup_indirect runs fault in (the indexed-validation pipeline and the rectangle-list converter). This adds the two it did not touch: - the placed page aliases of the translated indirect address route, which the translated-indexed-alias run does populate: a probe reports two placed pages still held when the process exits; - the draw-dump readbacks, which fill only when a dump frame is requested. Both detach their references when DllMain saw a process detach carrying lpReserved, and release them normally on FreeLibrary, through the flag in startup_stubs/d3d12_teardown.h. In the page cache begin()/end() keep the lookup and free-slot scan unchanged; in the readbacks the destructor walks entries_. The heap and page words stay plain addresses, not owned. Neither site is a crash reproduced here: with the detach disabled, the alias run still exits 0 while releasing its two pages at teardown. The boundary is made uniform with #2590's, which is where the fault was reproduced. The remaining static of this shape, RedProducers in red_producer_diagnostic.inl, is safe by construction: its live instance is heap-allocated and never destroyed, and the static fallback is built through the Disabled tag and owns nothing. * tests: exercise the placed page aliases and the draw readbacks through unload and exit The review asked for a source-built check of the ownership change: the alias run establishes that the cache is populated, but it exits the same way with or without the guard, and the draw-dump path had no populated test at all. x2w_d3d12_cached_objects_probe grows two bits. Bit 4 creates a heap and a placed buffer on the desktop device, enters it where the translated indirect address route keeps its aliases and answers 1; bit 8 creates the readback buffer and the fence a recorded dump holds and answers 2. startup_teardown_unload now covers four caches. On unload it requires each one to give back what it took: the device reference count for the two original caches, the entry's own object count for the two new ones, which hold no reference on the device. On process termination the child reports through X2W_TEARDOWN_REPORT how many references each cache detached and how many it released, and the parent requires detached= released=0. The test then re-runs the child once per cache with X2W_TEARDOWN_NO_GUARD=, which turns that cache's detach into a normal release, and requires the check to fail: without it the guard would be untested, which is what the review said. Two defects surfaced while building it. The probe answered 0 because a fixture created without a parameter block gets a bare D3D12CreateDevice device back, which is not in the shim registry, so as_wrapper() finds nothing -- that device is already the desktop one and is now used as such. And widen() kept the terminating null MultiByteToWideChar writes with -1, so CreateProcessW truncated the child command line. * tests: hand the placed page heap to the fixture so it outlives the buffer The probe kept the heap alive by detaching the creator's reference, which abandoned it: the cache holds only a non-owning heap pointer, so after FreeLibrary nothing owned the heap that backed the placed buffer. The probe now hands the heap over with a reference the fixture owns, and startup_teardown_unload holds it across the unload, checks that the placed buffer was released first, and then releases the heap last: warm placed-pages: backing heap handed over with 1 reference unload placed-pages: heap alive after the unload, 1 reference, placed buffer released first unload placed-pages: heap released last, 1 -> 0 Releasing after FreeLibrary is safe here because the heap is a D3D12 object created on the desktop device, not on the shim: its vtable lives in d3d12.dll, and the fixture still holds that device at that point. The reference-count and process-exit controls for the alias, the readback and the fence are unchanged. * Unload the placed-cache fixture before dropping its backing heap on error --------- Co-authored-by: panam Co-authored-by: Royoo <3230853833@qq.com> --- CMakeLists.txt | 9 +- docs/experiments.md | 46 ++- docs/startup-runtime.md | 1 + src/startup_stubs/d3d12_teardown.h | 63 +++- src/startup_stubs/d3d12_xs_device.cpp | 260 ++++++++++++-- src/startup_stubs/draw_dump_tracking.h | 62 ++++ tests/startup_teardown_unload.cpp | 476 ++++++++++++++++++++++--- 7 files changed, 823 insertions(+), 94 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 68a025209..6c484970e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1570,11 +1570,12 @@ add_test(NAME startup_indirect_other_refusal_census_control_warp set_tests_properties(startup_indirect_other_refusal_census_control_warp PROPERTIES TIMEOUT 60 PASS_REGULAR_EXPRESSION "got +'x2w-d3d12 indirect-other refusals: total 3. distinct keys 2, distinct pairs 2 \\(overflow calls 0\\)'") -# Teardown of the two per-device caches that keep desktop D3D12 objects (#2572): the built d3d12_xs.dll is +# Teardown of the four per-device caches that keep desktop D3D12 objects (#2572): the built d3d12_xs.dll is # loaded by explicit path, warmed through its own probe, then unloaded -- the caches must release what they -# own and the module must go -- and a second load is left to process termination, where the caches must -# release nothing because the display driver is already stopped. This check runs the built DLL itself, so -# unlike the Python-driven startup_* tests it needs no INTAKE_PYTHON guard. +# own and the module must go -- and a second load is run in a child process that leaves the module loaded to +# process termination, where the caches must detach every owned reference (the shim reports it under +# X2W_TEARDOWN_REPORT, and X2W_TEARDOWN_NO_GUARD has to make that check fail). This check runs the built DLL +# itself, so unlike the Python-driven startup_* tests it needs no INTAKE_PYTHON guard. add_executable(startup_teardown_unload tests/startup_teardown_unload.cpp) target_compile_features(startup_teardown_unload PRIVATE cxx_std_17) target_link_libraries(startup_teardown_unload PRIVATE d3d12 dxgi) diff --git a/docs/experiments.md b/docs/experiments.md index 38fa8d0ff..bc13ee77c 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -16203,7 +16203,9 @@ PSO-cache change. Canonical output bytes remain unchanged. Two caches keep desktop D3D12 objects for a device for as long as the module that holds them is loaded: the indexed-validation pipeline (`startup_stubs/d3d12_draw.inl`) and the rectangle-list argument converter -(`startup_stubs/rect_indirect_args.h`). Both are function-local statics, so they are destroyed during the +(`startup_stubs/rect_indirect_args.h`); the same boundary covers the placed page aliases of the translated +indirect address route (`startup_stubs/d3d12_xs_device.cpp`) and the draw-dump readbacks +(`startup_stubs/draw_dump_tracking.h`). All four are function-local statics, so they are destroyed during the module's CRT teardown, and that teardown happens at two different moments. At process exit Windows has already detached the display driver: releasing a pipeline state then faults inside the driver (`amdxc64`, at `0x35f2a19`, through `D3D12Core!CPipelineState::FinalRelease`) and the loader turns it into `0xC0000409`. @@ -16221,18 +16223,44 @@ ctest --preset dev --no-tests=error -R "^startup_teardown_unload_(warp|hardware) ctest --preset dev --no-tests=error -R "^startup_indirect_(translated_indexed|rectlist)" -V ``` -The fixture (`tests/startup_teardown_unload.cpp`) loads the built `d3d12_xs.dll` by path, warms both caches -through the module's own probe, and unloads it: the caches must release what they own, the device's reference +The fixture (`tests/startup_teardown_unload.cpp`) loads the built `d3d12_xs.dll` by path, warms one cache at a +time through the module's own probe, and unloads it: the cache must release what it owns, the device's reference count must come back, and the module must be gone. A second load is warmed and left loaded, so process termination exercises the other path. It is source-built and loads no title. +The two caches added with the ownership change own desktop objects that hold no reference on the device handle +the fixture holds, so the fixture measures them on the object: `x2w_d3d12_cached_object_probe` hands over one +reference of the placed buffer, of the readback buffer and of its fence, and that reference has to stay alone +once the module is unloaded. The placed-buffer case also owns the heap that buffer is placed on: the alias +entry keeps the heap as a key only, as the real route does, so `x2w_d3d12_cached_objects_probe` creates the +heap and hands its one reference to the fixture through an out parameter, and bit 4 is not warmed without that +pointer rather than leaving an unowned heap behind. The fixture keeps that heap across the unload, drops the +cache's and its own reference on the placed buffer first, and only then releases the heap -- a heap must +outlive the resources placed in it -- and requires that release to be the last reference, so a heap the cache +still owned would fail the case instead of leaking quietly. The termination load runs in a child of the fixture +(the fixture itself, `--termination-only`), because the evidence only exists while that process tears the module +down: with `X2W_TEARDOWN_REPORT=1` each cache writes `x2w-teardown detached= released=` straight +to stderr (no stdio buffer survives a CRT teardown), and the child has to report every owned reference detached +and none released. `X2W_TEARDOWN_NO_GUARD=` is the negative control: it makes that cache +release instead of detach, and the same check has to fail. Each passing run re-runs the child once per new cache +with the hook set and requires that failure, so a check that passes with and without a guard cannot report +success. Neither variable is read by an ordinary run. + +```powershell +startup_teardown_unload.exe warp +set X2W_TEARDOWN_REPORT=1 +set X2W_TEARDOWN_NO_GUARD=pages +startup_teardown_unload.exe warp # must fail: the pages guard is what detaches +``` + Measured on Windows 11 25H2 (26200.9974, MSVC 19.44.35230), AMD Radeon RX 9070 XT (`1002:7550`, driver -`32.0.32029.2010`), debug layer unavailable: `startup_teardown_unload` passes on WARP and on the card, and the -five `startup_indirect_*_hardware` runs that died with `0xC0000409` now reach their last assertion and exit -`0`. Removing either destructor brings its own failure back and only its own: without the validation-pipeline -destructor the four `translated_indexed*` runs fail and `rectlist` passes; without the converter destructor -`rectlist` fails and the four pass. Not covered: an explicit unload while a device is still referenced by a -title, and any adapter other than the one above. +`32.0.32029.2010`), debug layer unavailable: with the two original cases, `startup_teardown_unload` passes on +WARP and on the card, and the five `startup_indirect_*_hardware` runs that died with `0xC0000409` now reach +their last assertion and exit `0`. Removing either destructor brings its own failure back and only its own: +without the validation-pipeline destructor the four `translated_indexed*` runs fail and `rectlist` passes; +without the converter destructor `rectlist` fails and the four pass. The backing-heap handover is newer than +that run and has not been exercised on either machine yet. Not covered: an explicit unload while a device is +still referenced by a title, and any adapter other than the one above. ## Exact binary16 min, max, fract, and frexp forms (VOP1/VOP2/VOP3/DPP16/DPP8/SDWA) in pixel_aot diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 62b42c17e..de017909f 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1423,6 +1423,7 @@ ctest --preset dev --no-tests=error -R '^startup_trap_header(_prefix_control|_pr | `X2W_PRESENT_PLANE=` | diagnostic, in render mode: the output window shows plane `n` of each present alone (plane 0 when `n` is past the count), with or without `X2W_PRESENT_COMPOSITE`. See [Presented planes](#presented-planes) | | `X2W_HIDE_TITLE_WINDOW=1` (`run.sh --hide-title-window`) | once a present has reached the output window, hides the title's own window; dialogs stay visible, and the window is shown again when a present misses the output window, until the next present reaches it ([Output window and fallback diagnostics](#output-window-and-fallback-diagnostics)). Keyboard input to the title after the hide is not measured. Off by default on every host | | `X2W_DRAW_DUMP_FRAME=`, `X2W_DRAW_DUMP_DIR` | Full-resolution RGB snapshots of single-sample RGBA8/BGRA8 UNORM or sRGB targets after translated draws. A later present writes completed queue-fenced copies. At most 48 copies are pending or written; a copy whose fence reports device removal (`UINT64_MAX`) is released unwritten and frees its slot (`src/startup_stubs/draw_dump_tracking.h`, `ctest --preset dev --no-tests=error -R '^startup_dump_fence_(removed_control_)?warp$' -V`; the control must fail). | +| `X2W_TEARDOWN_REPORT=1`, `X2W_TEARDOWN_NO_GUARD=` | Test accounting for the caches whose destructors run during the module's CRT teardown (`src/startup_stubs/d3d12_teardown.h`, #2572). With `X2W_TEARDOWN_REPORT`, each destroyed cache writes one `x2w-teardown detached= released=` line to stderr with `WriteFile`, because a stdio buffer would not be flushed from a CRT teardown. `X2W_TEARDOWN_NO_GUARD` names a cache whose detach at process exit becomes an ordinary release again: the negative control `startup_teardown_unload` runs against itself, where the termination check has to fail. Unset, both change nothing and no line is written. | | `X2W_AUDIO_PERMISSIVE=1` | enables the audio stand-ins. Without a DSP provider, `XDspActivate` clears valid outputs and reports unavailable resources, and failed `XDspSubmitCommand` calls leave the sequence unchanged. `XDspDeactivate` and `XDspDisconnect` refuse null and unknown handles with `E_INVALIDARG`. | | `X2W_RUNTIME_PROXY=1` | proxies the gaming runtime and logs every call. Rewrites regular-IAT `GetProcAddress` and a direct `xgameruntime.dll!QueryApiImpl` import on the main EXE and on DLLs that share its directory (package helpers). Dynamic `QueryApiImpl` / `InitializeApiImpl*` are wrapped only when the provider module's basename is `xgameruntime.dll`. `LdrRegisterDllNotification` only flags that another scan is needed. A worker holds each matching module live while rewriting after linking. Loading a helper and immediately calling it can precede the scan. The enabled proxy stays loaded until process exit. Delay-import IAT slots are not rewritten. Skips this stand-in's own `GetProcAddress` IAT so the hook does not recurse (`src/startup_stubs/runtime_gpa_patch.h`, `ctest --preset dev --no-tests=error -R '^startup_runtime_gpa_patch(_name_only_control)?$'`, and the control must print `FAIL:`; Windows also runs `startup_runtime_proxy_scope` for a late-loaded helper through the real loader) | | `X2W_FAKE_USER=1` | answers the user, gamertag and save APIs for one local user, and creates one offline store context for that user | diff --git a/src/startup_stubs/d3d12_teardown.h b/src/startup_stubs/d3d12_teardown.h index 278f27580..31bbee990 100644 --- a/src/startup_stubs/d3d12_teardown.h +++ b/src/startup_stubs/d3d12_teardown.h @@ -1,8 +1,10 @@ // Lifetime boundary of the desktop D3D12 objects the stand-in keeps in function-local statics: -// the indexed-validation pipeline (startup_stubs/d3d12_draw.inl) and the rectangle-list argument -// converter (startup_stubs/rect_indirect_args.h). #2572. +// the indexed-validation pipeline (startup_stubs/d3d12_draw.inl), the rectangle-list argument +// converter (startup_stubs/rect_indirect_args.h), the placed page aliases of the translated +// indirect address route (startup_stubs/d3d12_xs_device.cpp) and the draw-dump readbacks +// (startup_stubs/draw_dump_tracking.h). #2572. // -// Both caches hold their objects for as long as this module is loaded -- a conversion or a validation +// These caches hold their objects for as long as this module is loaded -- a conversion or a validation // may still be queued when the call that built the entry returns -- so they are destroyed during this // module's CRT teardown. That teardown runs at two different moments: // @@ -23,10 +25,65 @@ // caches compiled into another module (the test executables include rect_indirect_args.h) keep // releasing normally, and only the DLL that owns the DllMain can silence its own teardown. Being a // zero-initialized bool, it needs no dynamic initialization and no destruction order. +// +// The accounting below is what makes that boundary observable. startup_teardown_unload loads this +// module, warms one cache, and has to show both paths: that the cache releases what it owns when the +// module is unloaded, and that it detaches instead of releasing when the process exits. The two +// variables are read when a cache is destroyed and absent from an ordinary run: +// +// X2W_TEARDOWN_REPORT=1 the cache prints one line on stderr as it is destroyed: +// x2w-teardown detached= released= +// where n counts the owned references (objects), not the entries. The +// line is written with WriteFile straight to the stderr handle: these +// destructors run during this module's CRT teardown, so a stdio buffer +// would never be flushed. No file is written and no buffer is deferred. +// X2W_TEARDOWN_NO_GUARD= disables the detach of cache (pages, readbacks, or all): that +// cache then releases normally during process exit, which is the crash +// path this boundary exists for. Absent, every guard behaves as it did. +// This is the negative control startup_teardown_unload runs against +// itself: with the variable set, its termination check must fail. +// +// Neither read is cached in a static: a function-local static here would be initialized for the first +// time inside the destructor, during teardown, after the atexit table has already run. #pragma once +#include + +#include +#include + namespace x2w_startup { inline bool d3d12_process_terminating = false; +// True when the caller asked the named cache to release instead of detach during process exit. +inline bool teardown_guard_disabled(const char* cache) noexcept +{ + const DWORD saved = GetLastError(); + char value[64]{}; + const DWORD length = GetEnvironmentVariableA("X2W_TEARDOWN_NO_GUARD", value, sizeof(value)); + SetLastError(saved); + if (!length || length >= sizeof(value)) return false; + return std::strcmp(value, "all") == 0 || std::strcmp(value, cache) == 0; +} + +// One stable line per destroyed cache, on stderr, only when X2W_TEARDOWN_REPORT is set. +inline void teardown_report(const char* cache, unsigned detached, unsigned released) noexcept +{ + const DWORD saved = GetLastError(); + char on[2]{}; + const bool wanted = GetEnvironmentVariableA("X2W_TEARDOWN_REPORT", on, sizeof(on)) != 0; + if (wanted) { + char line[128]; + const int length = std::snprintf(line, sizeof(line), "x2w-teardown %s detached=%u released=%u\r\n", cache, + detached, released); + if (length > 0) { + DWORD written = 0; + const int bytes = length < static_cast(sizeof(line)) ? length : static_cast(sizeof(line)) - 1; + WriteFile(GetStdHandle(STD_ERROR_HANDLE), line, static_cast(bytes), &written, nullptr); + } + } + SetLastError(saved); +} + } // namespace x2w_startup diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 432e63b43..61f9199e0 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -4483,6 +4483,70 @@ struct ExistingHeap { }; std::vector> existing_heaps; +// Lifetime boundary: one cross-adapter page alias per (heap, page) at a title address, kept for as long as +// this module is loaded, because the GPU may still read a page the title keeps live for the device's +// lifetime. It is the function-local static of placed_page_aliases() below, so it is destroyed during +// this module's CRT teardown -- see startup_stubs/d3d12_teardown.h for the two detaches. On process exit +// the display driver may already be stopped, so the placed buffers are detached and nothing reaches it; +// FreeLibrary leaves the process and the driver alive and the pages release their objects normally. The +// heap and page words are plain addresses, not owned. Each owned buffer is accounted for on the path it +// took and, with X2W_TEARDOWN_REPORT, reported as one x2w-teardown pages line. +struct PlacedPageAliases { + struct Page { + ID3D12Heap* heap; + u64 page; + x2w_startup::ComPtr resource; + }; + using iterator = std::array::iterator; + iterator begin() { return entries.begin(); } + iterator end() { return entries.end(); } + + // Test hook (startup_teardown_unload, #2572; the review of the ownership change asked for one): + // enters one alias for a heap and page the caller owns, where the translated indirect address route + // would keep it after its first call. False when that pair is already there or the cache is full. No + // real path calls it, and the entry keeps the heap as a key only, as the route does. + bool insert_for_test(ID3D12Heap* heap, u64 page, ID3D12Resource* resource) + { + if (!heap || !resource) return false; + for (const Page& entry : entries) + if (entry.heap == heap && entry.page == page) return false; + for (Page& entry : entries) { + if (entry.heap) continue; + entry.resource = resource; // AddRef: the cache owns this reference + entry.page = page; + entry.heap = heap; + return true; + } + return false; + } + + ~PlacedPageAliases() + { + const bool detach = x2w_startup::d3d12_process_terminating && !x2w_startup::teardown_guard_disabled("pages"); + unsigned detached = 0, released = 0; + for (auto& entry : entries) { + if (!entry.resource) continue; + if (detach) { + entry.resource.Detach(); + ++detached; + } else { + ++released; + } + } + x2w_startup::teardown_report("pages", detached, released); + } + std::array entries{}; +}; + +// The cache lives in its own accessor so the fixture probe can reach it, the way +// indexed_validation_pipeline(device) exposes the validation pipeline. One function-local static, built +// on the first translated indirect address. +PlacedPageAliases& placed_page_aliases() +{ + static PlacedPageAliases pages{}; + return pages; +} + IndirectAddressAlias indirect_address_alias(Wrapper* device, u64 address, u64 bytes) { static const bool enabled = x2w_local::env_on("X2W_TRANSLATED_INDIRECT_ADDRESS_ALIAS"); @@ -4506,8 +4570,8 @@ IndirectAddressAlias indirect_address_alias(Wrapper* device, u64 address, u64 by [&](const auto& entry) { return entry.first == memory.base; }); if (known == existing_heaps.end()) return {}; auto* heap = known->second.real; - struct Page { ID3D12Heap* heap; u64 page; x2w_startup::ComPtr resource; }; - static std::array pages{}; + using Page = PlacedPageAliases::Page; + auto& pages = placed_page_aliases(); auto it = std::find_if(pages.begin(), pages.end(), [&](const Page& entry) { return entry.heap == heap && entry.page == page; }); if (it != pages.end()) return {it->resource.Get(), offset}; it = std::find_if(pages.begin(), pages.end(), [](const Page& entry) { return !entry.heap; }); @@ -5479,16 +5543,28 @@ extern "C" __declspec(dllexport) BOOL x2w_d3d12_retire_probe(void* resource, voi return TRUE; } -// Fixture probe (startup_teardown_unload, #2572) for the two caches that keep desktop objects for a -// device: the indexed-validation pipeline (d3d12_draw.inl, bit 0) and the rectangle-list argument -// converter (rect_indirect_args.h, bit 1). Warms the selected caches the way their first real call -// would -- the validation pipeline directly, the converter through one record-only conversion, nothing -// executed -- and answers how many objects they now hold for `device`: the validation entry's device, -// root signature and pipeline (3), plus the converter entry's root signature and pipeline (2). The -// caller can warm one cache at a time to see each one release what it owns when the module is unloaded. -extern "C" __declspec(dllexport) UINT x2w_d3d12_cached_objects_probe(ID3D12Device* device, UINT caches) -{ - if (!device || !caches || (caches & ~3u)) return 0; +// Fixture probe (startup_teardown_unload, #2572) for the four caches that keep desktop objects for a +// device, one bit each: the indexed-validation pipeline (d3d12_draw.inl, bit 1) and the rectangle-list +// argument converter (rect_indirect_args.h, bit 2), the placed page aliases of the translated indirect +// address route (bit 4) and the draw-dump readbacks (bit 8). Warms the selected caches the way their +// first real call would -- the validation pipeline directly, the converter through one record-only +// conversion, an alias entry on a placed buffer of this device, a recorded readback -- and answers how +// many objects they now hold for `device`: the validation entry's device, root signature and pipeline +// (3), the converter entry's root signature and pipeline (2), the alias entry's placed buffer (1), the +// readback entry's buffer and fence (2). The caller can warm one cache at a time to see each one release +// what it owns when the module is unloaded. +// +// `placed_heap` is how bit 4 hands the heap it creates over to the caller. The alias entry keeps that heap +// as a key only -- it owns no reference, as the route's heap belongs to the device's allocation -- so the +// one reference this probe holds is the caller's from the moment the entry is entered, and the caller must +// release it after the cache released the placed buffer (a heap must outlive the resources placed in it). +// Bit 4 is not warmed when `placed_heap` is null: an entry whose backing heap nobody owns is the leak this +// handover exists to rule out. Every other bit leaves `*placed_heap` null. +extern "C" __declspec(dllexport) UINT x2w_d3d12_cached_objects_probe(ID3D12Device* device, UINT caches, + ID3D12Heap** placed_heap) +{ + if (placed_heap) *placed_heap = nullptr; + if (!device || !caches || (caches & ~15u)) return 0; UINT owned = 0; if (caches & 1u) { const auto& validation = indexed_validation_pipeline(device); @@ -5496,31 +5572,147 @@ extern "C" __declspec(dllexport) UINT x2w_d3d12_cached_objects_probe(ID3D12Devic if (validation.root) ++owned; if (validation.pipeline) ++owned; } - if (!(caches & 2u)) return owned; - - x2w_startup::ComPtr allocator; - x2w_startup::ComPtr list; - if (FAILED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator))) || - FAILED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.Get(), nullptr, - IID_PPV_ARGS(&list)))) - return owned; - D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; - D3D12_RESOURCE_DESC buffer{}; - buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; - buffer.Width = 256; - buffer.Height = buffer.DepthOrArraySize = buffer.MipLevels = buffer.SampleDesc.Count = 1; - buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; - // convert() copies its 16 source words; an uninitialised buffer in the state it requires is enough. - x2w_startup::ComPtr source; - if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COPY_SOURCE, - nullptr, IID_PPV_ARGS(&source)))) - return owned; - const auto scratch = x2w_startup::RectIndirectArguments::make_scratch(device); - if (scratch && x2w_startup::rect_indirect_arguments().convert(list.Get(), source.Get(), 0, scratch.Get())) - owned += 2; // the converter's root signature and pipeline for this device + if (caches & 2u) { + x2w_startup::ComPtr allocator; + x2w_startup::ComPtr list; + if (FAILED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator))) || + FAILED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.Get(), nullptr, + IID_PPV_ARGS(&list)))) + return owned; + D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + D3D12_RESOURCE_DESC buffer{}; + buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + buffer.Width = 256; + buffer.Height = buffer.DepthOrArraySize = buffer.MipLevels = buffer.SampleDesc.Count = 1; + buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + // convert() copies its 16 source words; an uninitialised buffer in the state it requires is enough. + x2w_startup::ComPtr source; + if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COPY_SOURCE, + nullptr, IID_PPV_ARGS(&source)))) + return owned; + const auto scratch = x2w_startup::RectIndirectArguments::make_scratch(device); + if (scratch && x2w_startup::rect_indirect_arguments().convert(list.Get(), source.Get(), 0, scratch.Get())) + owned += 2; // the converter's root signature and pipeline for this device + } + if (!(caches & 12u)) return owned; + + // The two caches below hold desktop objects, as their real entries do: draw_dump_after() creates the + // readback buffer on the desktop device, and execute() creates the fence on the desktop device it + // reads from the desktop queue. Two shapes of device reach this probe. A title gets a wrapper from + // D3D12XboxCreateDevice (attach_device wraps the created device), and the desktop device is then the + // one behind it. A fixture creates its device without a parameter block, so that entry returns a + // plain D3D12CreateDevice() result: an unwrapped desktop device. The handle itself is the desktop + // device then. removal_device is not a fallback: attach_device is where it is written, so on the + // unwrapped path it is null or names another device. + Wrapper* wrapper = as_wrapper(device); + ID3D12Device* desktop = wrapper ? device_of(wrapper) : device; + + // Diagnostics for the fixture, off unless X2W_CACHE_PROBE_DEBUG is set: one line per step, so a probe + // that answers fewer objects than expected names the call that refused. Temporary, together with the + // two caches they measure. + char probe_debug[2]{}; + const bool trace = GetEnvironmentVariableA("X2W_CACHE_PROBE_DEBUG", probe_debug, sizeof(probe_debug)) != 0; + if (trace) + std::fprintf(stderr, "x2w-cache-probe device=%p wrapper=%p desktop=%p caches=0x%x\n", + static_cast(device), static_cast(wrapper), static_cast(desktop), caches); + + // Bit 4 needs an owner for the heap it creates, and that owner is the caller: with no out pointer + // there is nowhere to put the reference, so the alias is not warmed at all rather than entered on a + // heap nobody owns for the rest of the process. + if ((caches & 4u) && !placed_heap && trace) + std::fputs("x2w-cache-probe placed: no heap out pointer, bit 4 not warmed\n", stderr); + if ((caches & 4u) && placed_heap) { + // One placed buffer on a heap of this device, entered where the translated indirect address route + // keeps its aliases. The page word is only the cache key: no title address is involved here, and + // the entry never dereferences the heap. The route's buffers carry ALLOW_CROSS_ADAPTER; sharing + // them across adapters needs a heap opened for it and plays no part in the lifetime measured + // here, so this buffer is an ordinary placed buffer. + D3D12_HEAP_PROPERTIES properties{D3D12_HEAP_TYPE_DEFAULT}; + D3D12_HEAP_DESC heap_desc{}; + heap_desc.SizeInBytes = 65536; + heap_desc.Properties = properties; + heap_desc.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS; + x2w_startup::ComPtr heap; + const HRESULT heap_hr = desktop->CreateHeap(&heap_desc, IID_PPV_ARGS(&heap)); + if (trace) std::fprintf(stderr, "x2w-cache-probe heap hr=0x%08lx\n", static_cast(heap_hr)); + if (FAILED(heap_hr)) return owned; + const D3D12_RESOURCE_DESC placed{D3D12_RESOURCE_DIMENSION_BUFFER, 0, 65536, 1, 1, 1, DXGI_FORMAT_UNKNOWN, + {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; + x2w_startup::ComPtr alias; + const HRESULT placed_hr = desktop->CreatePlacedResource(heap.Get(), 0, &placed, D3D12_RESOURCE_STATE_COMMON, + nullptr, IID_PPV_ARGS(&alias)); + if (trace) std::fprintf(stderr, "x2w-cache-probe placed hr=0x%08lx\n", static_cast(placed_hr)); + if (FAILED(placed_hr)) return owned; + { + std::lock_guard lock(placed_mutex); + auto& pages = placed_page_aliases(); + const bool entered = pages.insert_for_test(heap.Get(), 0x10000, alias.Get()); + unsigned used = 0; + for (const auto& entry : pages) + if (entry.heap) ++used; + if (trace) std::fprintf(stderr, "x2w-cache-probe insert=%d used=%u/64\n", entered ? 1 : 0, used); + if (entered) { + // The route's heap belongs to the device's allocation, not to an alias entry: the shim + // keeps it for the device's lifetime, and the entry only stores the pointer. This probe + // created its own heap, so the one reference it holds is not abandoned here but handed to + // the caller, who owns it from now on and releases it after the placed buffer this entry + // keeps -- a heap must outlive the resources placed in it. + *placed_heap = heap.Detach(); + ++owned; + } + } + } + if (caches & 8u) { + // One recorded draw readback: the READBACK buffer draw_dump_after() keeps and the queue fence + // execute() attaches once the copy is submitted. execute() builds both on the desktop device it + // reads from the desktop queue, so both are desktop objects here too. + D3D12_HEAP_PROPERTIES properties{D3D12_HEAP_TYPE_READBACK}; + D3D12_RESOURCE_DESC buffer{}; + buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + buffer.Width = 256; + buffer.Height = buffer.DepthOrArraySize = buffer.MipLevels = buffer.SampleDesc.Count = 1; + buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + x2w_startup::ComPtr staging; + x2w_startup::ComPtr fence; + const HRESULT staging_hr = desktop->CreateCommittedResource(&properties, D3D12_HEAP_FLAG_NONE, &buffer, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&staging)); + if (trace) std::fprintf(stderr, "x2w-cache-probe readback hr=0x%08lx\n", static_cast(staging_hr)); + if (FAILED(staging_hr)) return owned; + const HRESULT fence_hr = desktop->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)); + if (trace) std::fprintf(stderr, "x2w-cache-probe fence hr=0x%08lx\n", static_cast(fence_hr)); + if (FAILED(fence_hr)) return owned; + const bool recorded = draw_dumps().record_for_test(std::move(staging), std::move(fence)); + if (trace) std::fprintf(stderr, "x2w-cache-probe record=%d\n", recorded ? 1 : 0); + if (recorded) owned += 2; + } return owned; } +// Fixture probe (startup_teardown_unload, #2572) for the ownership of the two caches above: hands the +// caller one reference to an object a warmed entry owns, so the fixture can watch that reference go away +// when the module is unloaded. `cache` and `slot`: 4/0 the placed buffer, 8/0 the readback buffer, 8/1 its +// fence; null for anything else. The caller's reference keeps the object alive after the module is gone, +// which is what makes its count readable then. +extern "C" __declspec(dllexport) IUnknown* x2w_d3d12_cached_object_probe(UINT cache, UINT slot) +{ + IUnknown* object = nullptr; + if (cache == 4u) { + std::lock_guard lock(placed_mutex); + auto& pages = placed_page_aliases(); + for (auto& entry : pages) { + if (!entry.resource) continue; + object = entry.resource.Get(); + break; + } + } else if (cache == 8u) { + object = draw_dumps().owned_for_test(slot); + } + if (!object) return nullptr; + object->AddRef(); + return object; +} + // Fixture probes (startup_resource_retire_title) for state the retire bookkeeping maintains for one resource. They read // the same maps the shim reads and never change them; the address index and the upload cache exist with and without // the switch, so these answer in both modes. diff --git a/src/startup_stubs/draw_dump_tracking.h b/src/startup_stubs/draw_dump_tracking.h index cbbbbae61..d7ef6d5dd 100644 --- a/src/startup_stubs/draw_dump_tracking.h +++ b/src/startup_stubs/draw_dump_tracking.h @@ -3,6 +3,8 @@ #include #include +#include "startup_stubs/d3d12_teardown.h" + #include #include #include @@ -51,6 +53,34 @@ class DrawReadbacks { return true; } + // Test hook (startup_teardown_unload, #2572; the review of the ownership change asked for one): + // enters one recorded copy exactly as execute() leaves it after a submit -- the readback buffer and + // the queue fence that decides its completion -- without a command list, a queue or a draw. No real + // path calls it. False when the capture budget is full. + bool record_for_test(Microsoft::WRL::ComPtr buffer, Microsoft::WRL::ComPtr fence) + { + std::lock_guard lock(mutex_); + if (entries_.size() + consumed_ >= limit) return false; + DrawDump dump; + dump.buffer = std::move(buffer); + dump.index = ++sequence_; + entries_.push_back({nullptr, std::move(fence), std::move(dump)}); + return true; + } + + // Test hook: the object the first recorded entry owns, without adding a reference -- slot 0 the + // readback buffer, 1 its fence. The fixture takes its own reference and watches it stay alone once + // the module is unloaded. Null for an unknown slot or an empty cache. + IUnknown* owned_for_test(unsigned slot) + { + std::lock_guard lock(mutex_); + for (auto& entry : entries_) { + if (slot == 0 && entry.dump.buffer) return entry.dump.buffer.Get(); + if (slot == 1 && entry.fence) return entry.fence.Get(); + } + return nullptr; + } + void discard(ID3D12CommandList* list) { std::lock_guard lock(mutex_); @@ -101,5 +131,37 @@ class DrawReadbacks { } return complete; } + + // Lifetime boundary, same contract as the caches in startup_stubs/d3d12_teardown.h: a recorded copy and + // its fence live for as long as this module is loaded, because a list that was resubmitted still holds + // them. This object is a function-local static in draw_dumps(), so it is destroyed during the module's + // CRT teardown. On process exit the display driver is already detached and a release there faults + // inside it, so the references are detached; FreeLibrary keeps the process and the driver alive and + // the entries release their objects normally. Each reference is accounted for on the path it took and, + // with X2W_TEARDOWN_REPORT, reported as one x2w-teardown readbacks line. + ~DrawReadbacks() + { + const bool detach = d3d12_process_terminating && !teardown_guard_disabled("readbacks"); + unsigned detached = 0, released = 0; + for (auto& entry : entries_) { + if (entry.dump.buffer) { + if (detach) { + entry.dump.buffer.Detach(); + ++detached; + } else { + ++released; + } + } + if (entry.fence) { + if (detach) { + entry.fence.Detach(); + ++detached; + } else { + ++released; + } + } + } + teardown_report("readbacks", detached, released); + } }; } // namespace x2w_startup diff --git a/tests/startup_teardown_unload.cpp b/tests/startup_teardown_unload.cpp index 44cc0297d..af71c53d3 100644 --- a/tests/startup_teardown_unload.cpp +++ b/tests/startup_teardown_unload.cpp @@ -1,20 +1,46 @@ -// Loads the built d3d12_xs.dll by explicit path, warms the two caches that keep desktop D3D12 objects +// Loads the built d3d12_xs.dll by explicit path, warms the four caches that keep desktop D3D12 objects // (#2572) through that module, and walks both detach paths it has to survive: // // startup_teardown_unload // // Unload: FreeLibrary detaches the module with lpReserved == nullptr. Each cache is loaded and warmed on -// its own, so its release can be seen alone: the device's reference count must return to the count the -// test itself holds (otherwise an owned object was leaked), the module must be gone, and the process must -// still run. +// its own, so its release can be seen alone: the module must be gone, what it owned must be released, and +// the process must still run. The two original caches hold a reference on the device handle this fixture +// holds, so the count of that handle is the measure there. The caches added with the placed page aliases +// and the draw dumps own desktop objects instead, and a desktop object holds no reference on the wrapper: +// for them the probe hands over one reference of every object an entry owns (x2w_d3d12_cached_object_probe) +// and that reference has to stay alone once the module is gone -- the count of the entry's own object is +// the release measure. // -// Termination: a second load warms both caches and is deliberately left loaded. On process exit the +// The placed-alias case also owns the heap its buffer is placed on. The probe creates that heap and hands +// its one reference over (the entry keeps the heap as a key only, as the real route does), so the fixture +// holds it across the unload and releases it only after the cache released the placed buffer: a heap must +// outlive the resources placed in it. That release has to be the last reference on the heap, and the case +// fails when it is not, because a heap left with no owner is the leak this check exists to catch. +// +// Termination: a second load warms every cache and is deliberately left loaded. On process exit the // loader detaches the module with lpReserved != nullptr, after Windows has stopped the display driver; // releasing a pipeline state then faults inside the driver (amdxc64 offset 0x35f2a19, through // D3D12Core!CPipelineState::FinalRelease) and the process dies with 0xC0000409 before it can report a // result. The caches must detach their references instead. This is the path the five // startup_indirect_*_hardware runs hit. // +// That second load runs in a child process (this executable again, --termination-only), because the +// evidence only exists while that process tears the module down: the shim prints one line per destroyed +// cache on stderr, +// +// x2w-teardown detached= released= +// +// when X2W_TEARDOWN_REPORT is set. The child is run with it set and its report is required to say, for +// both caches that own something new here, that every owned reference was detached and none released. +// +// Negative control, the test hook the review of the ownership change asked for: X2W_TEARDOWN_NO_GUARD= +// makes that cache's destructor release instead of detach during process exit, so +// the termination check has to fail with it set. Every passing run re-runs the child once per cache with +// the hook set and requires the check to fail, so a check that passes with and without a guard cannot +// report success. Set in this process's own environment the hook is passed through to the child, and this +// run fails with the reason. +// // The fixture is source-built and loads no title. #include #include @@ -30,19 +56,28 @@ using Microsoft::WRL::ComPtr; namespace { using XboxCreateDevice = HRESULT(WINAPI*)(IUnknown*, const void*, REFIID, void**); -// Probe bits: 1 the indexed-validation pipeline, 2 the rectangle-list argument converter. -using CachedObjectsProbe = UINT(WINAPI*)(ID3D12Device*, UINT); +// Probe bits: 1 the indexed-validation pipeline, 2 the rectangle-list argument converter, 4 the placed +// page aliases, 8 the draw-dump readbacks. Bit 4 also creates a heap and hands its one reference over +// through the third argument, which only it fills; the alias entry keeps that heap as a key only. +using CachedObjectsProbe = UINT(WINAPI*)(ID3D12Device*, UINT, ID3D12Heap**); +// One reference of an object a warmed entry owns: cache 4 slot 0 the placed buffer, cache 8 slot 0 the +// readback buffer, cache 8 slot 1 its fence. +using CachedObjectProbe = IUnknown*(WINAPI*)(UINT, UINT); struct CacheCase { const char* name; UINT probe_bits; - UINT owned; // objects the warmed cache holds for one device + UINT owned; // objects the warmed cache holds for one device + unsigned slots; // owned objects the probe hands out; 0: measured through the device count + bool heap; // the probe also hands over the placed buffer's backing heap }; // One case per cache, so a leak names the cache that kept it. constexpr CacheCase cache_cases[] = { - {"indexed-validation", 1u, 3u}, // device, root signature, pipeline - {"rect-converter", 2u, 2u}, // root signature, pipeline + {"indexed-validation", 1u, 3u, 0u, false}, // device, root signature, pipeline + {"rect-converter", 2u, 2u, 0u, false}, // root signature, pipeline + {"placed-pages", 4u, 1u, 1u, true}, // the placed buffer behind the alias entry, and its heap + {"draw-readbacks", 8u, 2u, 2u, false}, // the readback buffer and the fence that owns its completion }; // Same selection convention as the other D3D12 fixtures: WARP on request, otherwise the first @@ -83,13 +118,41 @@ int select_adapter(bool warp, ComPtr& factory, ComPtr(length), L'\0'); if (!MultiByteToWideChar(CP_ACP, 0, path, -1, wide.data(), length)) return std::wstring(); + // -1 makes the conversion include the terminating null. Keeping it would put a null inside the path, + // and a command line built from this string would end there: CreateProcessW truncates at the first one. + wide.resize(static_cast(length) - 1); return wide; } -HMODULE load_shim(const std::wstring& path, XboxCreateDevice& create, CachedObjectsProbe& probe) +std::wstring narrow_to_wide(const std::string& text) +{ + return std::wstring(text.begin(), text.end()); +} + +std::wstring quoted(const std::wstring& text) +{ + return L'"' + text + L'"'; +} + +std::wstring executable_path() +{ + std::wstring path(MAX_PATH, L'\0'); + for (;;) { + const DWORD length = GetModuleFileNameW(nullptr, path.data(), static_cast(path.size())); + if (!length) return std::wstring(); + if (length < path.size()) { + path.resize(length); + return path; + } + path.resize(path.size() * 2); + } +} + +HMODULE load_shim(const std::wstring& path, XboxCreateDevice& create, CachedObjectsProbe& probe, + CachedObjectProbe& object_probe) { HMODULE module = LoadLibraryExW(path.c_str(), nullptr, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32); @@ -100,18 +163,23 @@ HMODULE load_shim(const std::wstring& path, XboxCreateDevice& create, CachedObje } create = reinterpret_cast(GetProcAddress(module, "D3D12XboxCreateDevice")); probe = reinterpret_cast(GetProcAddress(module, "x2w_d3d12_cached_objects_probe")); - if (!create || !probe) { - std::fputs("d3d12_xs.dll does not export D3D12XboxCreateDevice and x2w_d3d12_cached_objects_probe\n", stderr); + object_probe = reinterpret_cast(GetProcAddress(module, "x2w_d3d12_cached_object_probe")); + if (!create || !probe || !object_probe) { + std::fputs("d3d12_xs.dll does not export D3D12XboxCreateDevice, x2w_d3d12_cached_objects_probe " + "and x2w_d3d12_cached_object_probe\n", stderr); FreeLibrary(module); return nullptr; } - HMODULE owner = nullptr; - if (!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, - reinterpret_cast(probe), &owner) || - owner != module) { - std::fputs("x2w_d3d12_cached_objects_probe does not resolve inside d3d12_xs.dll\n", stderr); - FreeLibrary(module); - return nullptr; + const LPCWSTR entries[] = {reinterpret_cast(probe), reinterpret_cast(object_probe)}; + for (LPCWSTR entry : entries) { + HMODULE owner = nullptr; + if (!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + entry, &owner) || + owner != module) { + std::fputs("a cache probe does not resolve inside d3d12_xs.dll\n", stderr); + FreeLibrary(module); + return nullptr; + } } return module; } @@ -124,12 +192,32 @@ ULONG reference_count(IUnknown* object) return object->Release(); } +void release_objects(IUnknown* (&objects)[2]) +{ + for (IUnknown*& object : objects) { + if (object) object->Release(); + object = nullptr; + } +} + +// Gives back what the fixture holds of a placed alias entry on an error path: the placed buffer's +// reference first, then the heap behind it. A heap must outlive the resources placed in it, so the two +// releases are not interchangeable; the success path below releases them one at a time instead, because +// it reports each count. +void release_placed(ComPtr& heap, IUnknown* (&objects)[2], bool unloaded = true) +{ + release_objects(objects); + if (unloaded) heap.Reset(); + else (void)heap.Detach(); // The still-loaded cache owns a placed buffer until process exit. +} + // Phase 1: load, warm one cache, unload explicitly, and check that this cache released what it owned. int unload_path(const std::wstring& path, IDXGIAdapter* adapter, const CacheCase& cache) { XboxCreateDevice create = nullptr; CachedObjectsProbe probe = nullptr; - HMODULE shim = load_shim(path, create, probe); + CachedObjectProbe object_probe = nullptr; + HMODULE shim = load_shim(path, create, probe, object_probe); if (!shim) return 1; ComPtr device; @@ -141,30 +229,116 @@ int unload_path(const std::wstring& path, IDXGIAdapter* adapter, const CacheCase return 4; } - const ULONG before = reference_count(device.Get()); - const UINT owned = probe(device.Get(), cache.probe_bits); + ULONG before = 0, warm = 0; + IUnknown* objects[2] = {nullptr, nullptr}; + ULONG held[2] = {0, 0}; + // The backing heap of the placed buffer, when this case has one: the probe hands it over with the one + // reference it holds, so the fixture owns it from here to the end of this function -- across the + // unload -- and it is released last, after the cache and the fixture both let the placed buffer go. + ComPtr heap; + const auto unload_after_error = [&] { + const bool unloaded = FreeLibrary(shim) && !GetModuleHandleW(L"d3d12_xs.dll"); + release_placed(heap, objects, unloaded); + }; + ULONG heap_held = 0; + if (!cache.slots) before = reference_count(device.Get()); + + ID3D12Heap* warmed_heap = nullptr; + const UINT owned = probe(device.Get(), cache.probe_bits, &warmed_heap); + if (warmed_heap) heap.Attach(warmed_heap); if (owned != cache.owned) { std::fprintf(stderr, "%s: probe reports %u cached objects, expected %u\n", cache.name, owned, cache.owned); - FreeLibrary(shim); + unload_after_error(); return 5; } - const ULONG warm = reference_count(device.Get()); - if (warm <= before) { - std::fprintf(stderr, "%s: the cache holds no reference on the device: %lu before, %lu warm\n", cache.name, - static_cast(before), static_cast(warm)); - FreeLibrary(shim); - return 6; + if (cache.heap != (heap.Get() != nullptr)) { + std::fprintf(stderr, "%s: the probe %s a backing heap for the placed buffer, expected %s\n", cache.name, + heap ? "also handed over" : "handed over no", cache.heap ? "one" : "none"); + unload_after_error(); + return 15; + } + if (heap) { + heap_held = reference_count(heap.Get()); + std::printf("warm %s: backing heap handed over with %lu reference%s\n", cache.name, + static_cast(heap_held), heap_held == 1 ? "" : "s"); + } + + if (cache.slots) { + // One reference of each object the entry owns: before the unload it is the cache's plus this one. + for (unsigned slot = 0; slot < cache.slots; ++slot) { + objects[slot] = object_probe(cache.probe_bits, slot); + if (!objects[slot]) { + std::fprintf(stderr, "%s: the warmed cache owns no object in slot %u\n", cache.name, slot); + unload_after_error(); + return 6; + } + held[slot] = reference_count(objects[slot]); + if (held[slot] < 2) { + std::fprintf(stderr, "%s: slot %u reports %lu references, expected the cache's and this fixture's\n", + cache.name, slot, static_cast(held[slot])); + unload_after_error(); + return 6; + } + } + } else { + warm = reference_count(device.Get()); + if (warm <= before) { + std::fprintf(stderr, "%s: the cache holds no reference on the device: %lu before, %lu warm\n", cache.name, + static_cast(before), static_cast(warm)); + FreeLibrary(shim); + return 6; + } } if (!FreeLibrary(shim)) { std::fprintf(stderr, "%s: FreeLibrary failed: %lu\n", cache.name, static_cast(GetLastError())); + release_placed(heap, objects, false); return 7; } if (GetModuleHandleW(L"d3d12_xs.dll")) { std::fprintf(stderr, "%s: d3d12_xs.dll is still loaded after FreeLibrary\n", cache.name); + release_placed(heap, objects, false); return 8; } + + if (cache.slots) { + for (unsigned slot = 0; slot < cache.slots; ++slot) { + const ULONG after = reference_count(objects[slot]); + if (after + 1 != held[slot]) { + std::fprintf(stderr, "%s: the unloaded module kept a reference on slot %u: %lu -> %lu (expected %lu)\n", + cache.name, slot, static_cast(held[slot]), + static_cast(after), static_cast(held[slot] - 1)); + release_placed(heap, objects); + return 9; + } + std::printf("unload %s: slot %u reference %lu -> %lu\n", cache.name, slot, + static_cast(held[slot]), static_cast(after)); + } + // The module dropped its reference on the placed buffer above; this drops the fixture's. The heap + // has to outlive the buffer placed in it, so it is released only now -- and that release is the + // last reference, which is what proves the fixture, and not the cache, owned the heap. + release_objects(objects); + if (heap) { + // Still alive with the module gone, and what keeps it alive is the fixture's reference: it was + // taken from the probe before the unload and this scope is where it ends. + const ULONG alive = reference_count(heap.Get()); + std::printf("unload %s: heap alive after the unload, %lu reference%s, placed buffer released first\n", + cache.name, static_cast(alive), alive == 1 ? "" : "s"); + ID3D12Heap* released = heap.Detach(); + const ULONG last = released->Release(); + if (last != 0) { + std::fprintf(stderr, "%s: the fixture's heap release was not the last: %lu references left, so " + "something else owns the backing heap\n", + cache.name, static_cast(last)); + return 16; + } + std::printf("unload %s: heap released last, %lu -> 0\n", cache.name, static_cast(alive)); + } + std::printf("unload %s: %u objects released, module unloaded\n", cache.name, owned); + return 0; + } + const ULONG after = reference_count(device.Get()); if (after != before) { std::fprintf(stderr, "%s: the unloaded module left %lu device references behind (expected %lu)\n", @@ -176,40 +350,253 @@ int unload_path(const std::wstring& path, IDXGIAdapter* adapter, const CacheCase return 0; } -// Phase 2: load and warm both caches, then let the process exit with the module still loaded. Nothing may -// be released from the caches then, so nothing reaches the driver Windows has already stopped. -int termination_path(const std::wstring& path, IDXGIAdapter* adapter) +// The child body: load, warm every cache, return without unloading, so the loader detaches the module +// during process exit. Nothing else runs here -- the report lines come out of the CRT teardown. +int termination_warm(const std::wstring& path, const std::string& backend) { + ComPtr factory; + ComPtr adapter; + const int selected = select_adapter(backend == "warp", factory, adapter); + if (selected) return selected; + DXGI_ADAPTER_DESC desc{}; + if (SUCCEEDED(adapter->GetDesc(&desc))) + std::printf("termination child backend=%s adapter=%ls vendor=%04x device=%04x\n", backend.c_str(), + desc.Description, desc.VendorId, desc.DeviceId); + XboxCreateDevice create = nullptr; CachedObjectsProbe probe = nullptr; - HMODULE shim = load_shim(path, create, probe); + CachedObjectProbe object_probe = nullptr; + HMODULE shim = load_shim(path, create, probe, object_probe); if (!shim) return 1; ComPtr device; - HRESULT hr = create(adapter, nullptr, __uuidof(ID3D12Device), + HRESULT hr = create(adapter.Get(), nullptr, __uuidof(ID3D12Device), reinterpret_cast(device.GetAddressOf())); if (FAILED(hr) || !device) { - std::fprintf(stderr, "D3D12XboxCreateDevice failed on the second load: 0x%08lx\n", + std::fprintf(stderr, "D3D12XboxCreateDevice failed on the termination load: 0x%08lx\n", static_cast(hr)); return 4; } - UINT expected = 0; - for (const CacheCase& cache : cache_cases) expected += cache.owned; - const UINT owned = probe(device.Get(), 3u); + UINT caches = 0, expected = 0; + for (const CacheCase& cache : cache_cases) { + caches |= cache.probe_bits; + expected += cache.owned; + } + ID3D12Heap* placed_heap = nullptr; + const UINT owned = probe(device.Get(), caches, &placed_heap); if (owned != expected) { std::fprintf(stderr, "termination: probe reports %u cached objects, expected %u\n", owned, expected); return 5; } + if (!placed_heap) { + std::fputs("termination: the placed alias probe handed over no backing heap\n", stderr); + return 6; + } // Deliberately no FreeLibrary: the shim stays loaded, so the loader detaches it during process exit. // Releasing the device here, while the process and the driver still run, is the test's own reference. + // The backing heap is kept for the same reason and is not released either: the exit path detaches the + // placed buffer instead of releasing it, so the heap has to outlive the process exit. Unlike before + // this reference has an owner -- this child -- instead of being abandoned by the probe. std::printf("termination: %u objects left to the process exit path\n", owned); return 0; } +// One x2w-teardown line of the child's report, if it printed one for this cache. +bool teardown_line(const std::string& text, const char* cache, unsigned& detached, unsigned& released) +{ + const std::string prefix = std::string("x2w-teardown ") + cache + " detached="; + for (std::size_t at = text.find(prefix); at != std::string::npos; at = text.find(prefix, at + 1)) { + unsigned detached_value = 0, released_value = 0; + if (std::sscanf(text.c_str() + at + prefix.size(), "%u released=%u", &detached_value, &released_value) == 2) { + detached = detached_value; + released = released_value; + return true; + } + } + return false; +} + +// The termination contract: the child exited cleanly and both caches that own something here report every +// reference detached and none released. Answers the failures found, empty when the contract holds. +struct ChildRun { + DWORD exit_code = 0; + std::string text; // everything the child wrote, stdout and stderr on one pipe +}; + +std::string termination_failure(const ChildRun& run) +{ + std::string failure; + char line[256]; + const auto add = [&failure](const char* text) { + if (!failure.empty()) failure += "; "; + failure += text; + }; + if (run.exit_code != 0) { + std::snprintf(line, sizeof(line), "the child exited 0x%08lx instead of returning", + static_cast(run.exit_code)); + add(line); + } + struct Expectation { + const char* cache; + unsigned detached; + }; + constexpr Expectation expectations[] = {{"pages", 1u}, {"readbacks", 2u}}; + for (const Expectation& want : expectations) { + unsigned detached = 0, released = 0; + if (!teardown_line(run.text, want.cache, detached, released)) { + std::snprintf(line, sizeof(line), "x2w-teardown %s: no report line", want.cache); + add(line); + } else if (detached != want.detached || released != 0) { + std::snprintf(line, sizeof(line), "x2w-teardown %s detached=%u released=%u (want detached=%u released=0)", + want.cache, detached, released, want.detached); + add(line); + } + } + return failure; +} + +// An environment variable of this process; empty when it is unset or empty (the shim reads both the same +// way). +std::wstring variable(const wchar_t* name) +{ + wchar_t value[64]{}; + const DWORD length = GetEnvironmentVariableW(name, value, 64); + return length && length < 64 ? std::wstring(value, length) : std::wstring(); +} + +// Sets (non-empty) or clears (empty) an environment variable of this process. +void set_variable(const wchar_t* name, const std::wstring& value) +{ + SetEnvironmentVariableW(name, value.empty() ? nullptr : value.c_str()); +} + +// The caller's own X2W_TEARDOWN_NO_GUARD, passed through to the guarded child so that setting it makes +// this run fail -- that is the documented negative control at fixture level. +std::wstring caller_no_guard() +{ + return variable(L"X2W_TEARDOWN_NO_GUARD"); +} + +// Runs this executable once as a termination child. Its stdout and stderr share one pipe, read while it +// runs, so a child that dies mid-teardown still leaves whatever it printed; stdin comes from NUL. The +// child inherits this process's environment, so the two teardown variables are set here around +// CreateProcessW and the caller's values are put back afterwards. +bool run_child(const std::wstring& command, const std::wstring& no_guard, ChildRun& run) +{ + SECURITY_ATTRIBUTES security{sizeof(SECURITY_ATTRIBUTES), nullptr, TRUE}; + HANDLE read_end = nullptr, write_end = nullptr; + if (!CreatePipe(&read_end, &write_end, &security, 0)) { + std::fprintf(stderr, "CreatePipe failed: %lu\n", static_cast(GetLastError())); + return false; + } + HANDLE input = CreateFileW(L"NUL", GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, &security, OPEN_EXISTING, 0, + nullptr); + STARTUPINFOW startup{}; + startup.cb = sizeof(startup); + startup.dwFlags = STARTF_USESTDHANDLES; + startup.hStdInput = input; + startup.hStdOutput = write_end; + startup.hStdError = write_end; + PROCESS_INFORMATION process{}; + const std::wstring saved_report = variable(L"X2W_TEARDOWN_REPORT"); + const std::wstring saved_guard = variable(L"X2W_TEARDOWN_NO_GUARD"); + set_variable(L"X2W_TEARDOWN_REPORT", L"1"); + set_variable(L"X2W_TEARDOWN_NO_GUARD", no_guard); + std::wstring line = command; // CreateProcessW may write to its command line + const BOOL created = CreateProcessW(nullptr, line.data(), nullptr, nullptr, TRUE, CREATE_NO_WINDOW, nullptr, + nullptr, &startup, &process); + const DWORD error = GetLastError(); + set_variable(L"X2W_TEARDOWN_REPORT", saved_report); + set_variable(L"X2W_TEARDOWN_NO_GUARD", saved_guard); + CloseHandle(write_end); + if (input != INVALID_HANDLE_VALUE) CloseHandle(input); + if (!created) { + std::fprintf(stderr, "CreateProcessW failed: %lu for %ls\n", static_cast(error), + command.c_str()); + CloseHandle(read_end); + return false; + } + CloseHandle(process.hThread); + for (;;) { + char buffer[4096]; + DWORD got = 0; + if (!ReadFile(read_end, buffer, sizeof(buffer), &got, nullptr) || !got) break; + run.text.append(buffer, got); + } + CloseHandle(read_end); + WaitForSingleObject(process.hProcess, INFINITE); + GetExitCodeProcess(process.hProcess, &run.exit_code); + CloseHandle(process.hProcess); + return true; +} + +// Phase 2: the termination load runs in a child of this process. The guarded child has to pass; with +// X2W_TEARDOWN_NO_GUARD naming one cache, the same checks have to fail -- the negative control the review +// asked for, run per cache on every pass so that a check insensitive to either guard cannot go green. +int termination_path(const std::wstring& path, const std::string& backend) +{ + const std::wstring executable = executable_path(); + if (executable.empty()) { + std::fputs("GetModuleFileNameW failed: cannot run the termination child\n", stderr); + return 10; + } + const std::wstring command = quoted(executable) + L" --termination-only " + quoted(path) + L" " + + narrow_to_wide(backend); + const std::wstring no_guard = caller_no_guard(); + if (!no_guard.empty()) + std::printf("termination: X2W_TEARDOWN_NO_GUARD=%ls is set in this environment: the guarded check must fail\n", + no_guard.c_str()); + + ChildRun guarded; + if (!run_child(command, no_guard, guarded)) return 10; + std::printf("%s", guarded.text.c_str()); + const std::string failure = termination_failure(guarded); + if (!failure.empty()) { + std::fprintf(stderr, "termination: %s\n", failure.c_str()); + return 11; + } + std::printf("termination: both caches detached every owned reference, released none\n"); + if (!no_guard.empty()) { + // The caller set the hook and the check still passed: the hook did nothing, so nothing here + // proves the guard is needed. + std::fprintf(stderr, "negative control: the termination check passed with X2W_TEARDOWN_NO_GUARD=%ls: " + "the hook has no effect on this build\n", no_guard.c_str()); + return 14; + } + + for (const char* cache : {"pages", "readbacks"}) { + ChildRun unguarded; + if (!run_child(command, narrow_to_wide(cache), unguarded)) return 12; + const std::string unguarded_failure = termination_failure(unguarded); + if (unguarded_failure.empty()) { + std::fprintf(stderr, "negative control: the termination check passed with X2W_TEARDOWN_NO_GUARD=%s, " + "so it does not prove the %s guard is needed\n", cache, cache); + std::fprintf(stderr, "%s", unguarded.text.c_str()); + return 13; + } + std::printf("negative control X2W_TEARDOWN_NO_GUARD=%s: the check failed as it must (%s)\n", cache, + unguarded_failure.c_str()); + } + return 0; +} + } // namespace int main(int argc, char** argv) { + if (argc == 4 && std::string_view(argv[1]) == "--termination-only") { + const std::string_view backend = argv[3]; + if (backend != "warp" && backend != "hardware") { + std::fputs("unknown backend\n", stderr); + return 2; + } + const std::wstring path = widen(argv[2]); + if (path.empty()) { + std::fputs("cannot convert the d3d12_xs.dll path\n", stderr); + return 2; + } + return termination_warm(path, std::string(backend)); + } if (argc != 3) { std::fprintf(stderr, "usage: %s \n", argv[0]); return 2; @@ -231,15 +618,16 @@ int main(int argc, char** argv) if (selected) return selected; DXGI_ADAPTER_DESC desc{}; if (SUCCEEDED(adapter->GetDesc(&desc))) - std::printf("startup_teardown_unload backend=%s adapter=%ls vendor=%04x device=%04x\n", argv[2], - desc.Description, desc.VendorId, desc.DeviceId); + std::printf("startup_teardown_unload backend=%.*s adapter=%ls vendor=%04x device=%04x\n", + static_cast(backend.size()), backend.data(), desc.Description, desc.VendorId, desc.DeviceId); int result = 0; for (const CacheCase& cache : cache_cases) { result = unload_path(path, adapter.Get(), cache); if (result) break; } - if (result == 0) result = termination_path(path, adapter.Get()); - std::printf("startup_teardown_unload %s: %s\n", argv[2], result == 0 ? "PASS" : "FAIL"); + if (result == 0) result = termination_path(path, std::string(backend)); + std::printf("startup_teardown_unload %.*s: %s\n", static_cast(backend.size()), backend.data(), + result == 0 ? "PASS" : "FAIL"); return result; } From b2564017a84ade6cc38639f59494ce6777e72e02 Mon Sep 17 00:00:00 2001 From: pigalot Date: Thu, 26 Nov 2026 01:49:01 +0000 Subject: [PATCH 052/240] runtime: give unknown-dimension views a default view and skip mismatched ones (#2649) * runtime: give unknown-dimension views a default view and skip mismatched ones Desktop D3D12 removes the device for a view description with ViewDimension 0 (UNKNOWN) or a dimension that does not suit the resource, instead of failing the call. A console package module made such SRVs on 2D RGBA8 textures. Views of device slots 18 to 21 are now checked first (view_dimension.h): dimension 0 gets the resource's default view (null description) where desktop allows one, else the view is skipped; a mismatched dimension is skipped. Both are logged, and a view that still removes the device logs its forwarded description and the resource's shape. New fixture with a negative control: startup_view_dimension; the control swaps the resource dimension of the mismatched cases. * runtime: limit unknown-dimension default views to typed SRVs and null refused SRVs The default view for a view description with ViewDimension 0 replaces the whole description, including its format and component mapping. Only the shader resource view case is measured, so by default only slot 18 views of typed, non-depth textures get it. UAV, RTV and DSV descriptions with dimension 0 are skipped unless the experimental X2W_D3D12_VIEW_DEFAULTS=all is set; =off skips the SRV case too. A refused SRV now writes a null SRV into its destination descriptor. The skipped call used to leave the slot's previous descriptor there, bindable and copied by CopyDescriptors, after the slot's record had dropped the reference that kept its resource alive. New fixture startup_view_dimension_warp (and _hardware) through d3d12_xs.dll: an unknown-dimension SRV samples its texture's colour, an explicit TEXTURE3D SRV of a 2D texture is refused without device removal, and a refused replacement over a valid view reads zero, as does a copy of that slot. startup_view_dimension_off_control_warp runs it with X2W_D3D12_VIEW_DEFAULTS=off and must fail on the missing default view alone, with the device not removed. * Preserve live non-SRV descriptor records when a replacement is refused --------- Co-authored-by: Royoo <3230853833@qq.com> --- CMakeLists.txt | 24 ++ docs/startup-runtime.md | 47 +++ src/startup_stubs/d3d12_xs_device.cpp | 126 +++++-- src/startup_stubs/view_dimension.h | 105 ++++++ tests/startup_view_dimension_check.cpp | 122 +++++++ tests/startup_view_dimension_device.cpp | 425 ++++++++++++++++++++++++ 6 files changed, 825 insertions(+), 24 deletions(-) create mode 100644 src/startup_stubs/view_dimension.h create mode 100644 tests/startup_view_dimension_check.cpp create mode 100644 tests/startup_view_dimension_device.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 6c484970e..71ed38e44 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -614,6 +614,30 @@ target_compile_features(startup_null_texture_view_check PRIVATE cxx_std_17) add_test(NAME startup_null_texture_view COMMAND startup_null_texture_view_check) add_test(NAME startup_null_texture_view_unchecked_fallback_control COMMAND startup_null_texture_view_check --mutate unchecked-fallback) set_tests_properties(startup_null_texture_view_unchecked_fallback_control PROPERTIES WILL_FAIL TRUE) +# Device views with ViewDimension 0 (UNKNOWN) or a dimension that does not fit the resource +# (src/startup_stubs/view_dimension.h). The control must FAIL. +add_executable(startup_view_dimension tests/startup_view_dimension_check.cpp) +target_include_directories(startup_view_dimension PRIVATE src) +target_compile_features(startup_view_dimension PRIVATE cxx_std_17) +add_test(NAME startup_view_dimension COMMAND startup_view_dimension) +add_test(NAME startup_view_dimension_control COMMAND startup_view_dimension --control) +set_tests_properties(startup_view_dimension_control PROPERTIES PASS_REGULAR_EXPRESSION "FAIL: ") +# The same through d3d12_xs.dll: an unknown-dimension SRV samples its texture's colour, an incompatible explicit SRV is +# refused without device removal, and a refused replacement leaves a null descriptor, not the slot's old view. The +# off control (X2W_D3D12_VIEW_DEFAULTS=off) must fail on the missing default view alone, with the device not removed. +add_executable(startup_view_dimension_device tests/startup_view_dimension_device.cpp) +target_compile_features(startup_view_dimension_device PRIVATE cxx_std_17) +target_link_libraries(startup_view_dimension_device PRIVATE d3d12_xs_shim d3d12 dxgi d3dcompiler) +foreach(backend IN ITEMS warp hardware) + add_test(NAME startup_view_dimension_${backend} COMMAND startup_view_dimension_device ${backend}) + set_tests_properties(startup_view_dimension_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_DEBUG=0") +endforeach() +add_test(NAME startup_view_dimension_off_control_warp COMMAND startup_view_dimension_device warp off) +set_tests_properties(startup_view_dimension_off_control_warp PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_DEBUG=0;X2W_D3D12_VIEW_DEFAULTS=off" + PASS_REGULAR_EXPRESSION "FAIL: \\(a\\) default view reads 0\\.000 0\\.000 0\\.000 0\\.000, expected 0\\.200 0\\.600 0\\.800 1\\.000; device not removed.*cases complete" + FAIL_REGULAR_EXPRESSION "FAIL: setup|FAIL: \\(b\\)|FAIL: \\(c\\)|FAIL: \\(d\\)|DEVICE REMOVED|removed the device") # The slot and label of the x2w-render totals line each null-binding cause is counted under # (src/startup_stubs/null_binding_cause.h). The mutated run is the negative control. add_executable(startup_null_cause_labels_check tests/startup_null_cause_labels_check.cpp) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index de017909f..cb1659989 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -350,6 +350,52 @@ dimensions, formats, resources and counters that are left alone. A rewrite must field of the description. `startup_null_texture_view_unchecked_fallback_control` rewrites without asking about R8G8B8A8 and must fail. +## Unknown and mismatched view dimensions + +A view description with `ViewDimension` 0 (UNKNOWN) makes desktop D3D12 remove the device instead of +failing the call, and so does a dimension that does not suit the resource (debug layer: "The +ViewDimension in the View Desc is incompatible with the type of the Resource"). Measured: a console +package module made such SRVs on 2D RGBA8 textures. Views of device slots 18 to 21 (shader resource, +unordered access, render target, depth stencil) are now checked before they are forwarded: + +- an SRV (slot 18) with dimension 0 gets the resource's default view (a null description) where + desktop allows one: a texture with a typed format that is not a depth format. The default view + replaces the whole description, including its format and component mapping. Only this SRV case is + measured. With dimension 0 every other view is skipped; +- a dimension whose resource dimension differs from the resource's is skipped. + +The default view for UAV, RTV and DSV descriptions with dimension 0 is an explicit experiment, +`X2W_D3D12_VIEW_DEFAULTS=all`: it is unmeasured, and it drops the requested format the same way. +`X2W_D3D12_VIEW_DEFAULTS=off` skips the SRV case too. Any other value, or none, keeps the SRV +default. + +A refused SRV, for any reason, writes a null SRV (R8G8B8A8_UNORM, the requested dimension where it +is a texture dimension, else 2D) into its destination descriptor. Otherwise the slot would keep the +view it held before. That view would still be bindable and would be copied by `CopyDescriptors`, +although the slot's record no longer keeps its resource alive. Translated draws already resolve the +slot to nothing. + +A refused UAV, RTV or DSV leaves the previous descriptor and its tracking record in place. + +The first of each are logged (`x2w-d3d12 Device::slot view dimension ...`), and when a view still +removes the device, its forwarded description and the resource's shape are logged +(`removing view desc`). Run +`ctest --preset dev --no-tests=error -R '^startup_view_dimension(_control)?$'` +(`src/startup_stubs/view_dimension.h`); the control swaps the resource dimension of the mismatched +cases for the matching one and must print `FAIL:`. + +`startup_view_dimension_warp` goes through `d3d12_xs.dll` on WARP. A compute shader samples each +descriptor of a shader-visible heap through the wrapper's desktop heap. The fixture checks three +cases. An unknown-dimension SRV of a texture filled with one distinct colour must read back that +colour. An explicit TEXTURE3D SRV of a 2D texture must be refused with the device not removed. +A descriptor slot that held a valid view of a second colour, then receives a refused TEXTURE2D +SRV of a buffer, must read zero, and so must a `CopyDescriptorsSimple` copy of it. The slot gate +for UAV, RTV and DSV is checked without a device by `startup_view_dimension`. +`startup_view_dimension_off_control_warp` runs the same fixture with +`X2W_D3D12_VIEW_DEFAULTS=off`. It must print `FAIL: (a) default view` with `device not removed`, +so it fails on the missing default view and not on setup or a removed device. Both return 77 +without WARP. + ## 16-bit packed targets A description that asks for a B5G5R5A1_UNORM, B4G4R4A4_UNORM or B5G6R5_UNORM render target is created as @@ -1414,6 +1460,7 @@ ctest --preset dev --no-tests=error -R '^startup_trap_header(_prefix_control|_pr | `X2W_D3D12_RELEASE_RETIRED=1` | opt-in, effective with `X2W_D3D12_RENDER=1` only (the list handlers that record holds exist only there): frees the desktop object of a released committed 2D texture of one narrow class once no recorded list, submission or release-time fence refers to it ([details](#d3d12-resource-budget)). Unset, nothing changes | | `X2W_D3D12_RELEASE_RETIRED_VIEWS=1` | opt-in, effective only together with `X2W_D3D12_RELEASE_RETIRED=1`: a released class texture that only tracked slot-18 descriptor slots keep alive (the title never overwrites them) is freed once those slots are replaced by null descriptors ([details](#d3d12-resource-budget)). Unset, nothing changes | | `X2W_D3D12_RETIRE_REASONS=1` | diagnostic only, effective with `X2W_D3D12_RELEASE_RETIRED=1` and `X2W_D3D12_BUDGET=1`: adds one `x2w-retire held:` line to the heartbeat that counts final-released resources whose desktop object is still alive, by reason ([details](#d3d12-resource-budget)). Unset, nothing is recorded | +| `X2W_D3D12_VIEW_DEFAULTS=all` or `=off` | `all` is experimental: UAV, RTV and DSV descriptions with `ViewDimension` 0 also get the resource's default view, which drops their requested format and component mapping. `off` skips the measured SRV case too. Unset, only SRVs of typed non-depth textures get the default view ([details](#unknown-and-mismatched-view-dimensions)) | | `X2W_D3D12_VIEW_CENSUS=1` | diagnostic only: counts new distinct view records by device slot (a heartbeat line), and logs the record vector capacity and hash bucket count before either grows ([details](#d3d12-view-census)). Unset, nothing is counted or logged | | `X2W_DRAW_NULL_IDENTITY=1` | null descriptors read as identity values instead of zero | | `X2W_DEPTH_STATE=1` | translated draws of slot 57 pipelines take their depth-stencil state and stencil reference from state block A instead of the desktop default (depth and stencil off); a refused block keeps the default. Off by default, then nothing changes: see [Shortcuts that are known to be wrong](#shortcuts-that-are-known-to-be-wrong) | diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 61f9199e0..92b6f2ff9 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -49,6 +49,7 @@ #include "startup_stubs/buffer_format_word3.h" #include "startup_stubs/memory_srv_buffer.h" #include "startup_stubs/single_element_srv.h" +#include "startup_stubs/view_dimension.h" #include "startup_stubs/list_copy.h" #include "startup_stubs/d3d12_teardown.h" #include "startup_stubs/rect_indirect_args.h" @@ -4214,6 +4215,39 @@ HRESULT __stdcall device_create_descriptor_heap(Wrapper* self, const D3D12_DESCR return S_OK; } +// A null R8G8B8A8_UNORM SRV of a texture dimension (2 to 10; any other value gives texture 2D). A null resource +// reads no more of the description than its format and dimension. +D3D12_SHADER_RESOURCE_VIEW_DESC null_srv_desc(unsigned dimension) +{ + D3D12_SHADER_RESOURCE_VIEW_DESC desc{}; + desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + desc.ViewDimension = static_cast(x2w_view_dimension::refused_srv_null_dimension(dimension)); + switch (desc.ViewDimension) { + case D3D12_SRV_DIMENSION_TEXTURE1D: desc.Texture1D.MipLevels = 1; break; + case D3D12_SRV_DIMENSION_TEXTURE1DARRAY: desc.Texture1DArray.MipLevels = 1; desc.Texture1DArray.ArraySize = 1; break; + case D3D12_SRV_DIMENSION_TEXTURE2DARRAY: desc.Texture2DArray.MipLevels = 1; desc.Texture2DArray.ArraySize = 1; break; + case D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY: desc.Texture2DMSArray.ArraySize = 1; break; + case D3D12_SRV_DIMENSION_TEXTURE3D: desc.Texture3D.MipLevels = 1; break; + case D3D12_SRV_DIMENSION_TEXTURECUBE: desc.TextureCube.MipLevels = 1; break; + case D3D12_SRV_DIMENSION_TEXTURECUBEARRAY: desc.TextureCubeArray.MipLevels = 1; desc.TextureCubeArray.NumCubes = 1; break; + case D3D12_SRV_DIMENSION_TEXTURE2DMS: break; + default: desc.Texture2D.MipLevels = 1; break; + } + return desc; +} + +// X2W_D3D12_VIEW_DEFAULTS (view_dimension.h): which slots give an unknown-dimension view the resource's default view. +x2w_view_dimension::DefaultViews view_defaults_mode() +{ + static const x2w_view_dimension::DefaultViews mode = [] { + char value[8]{}; + const DWORD n = GetEnvironmentVariableA("X2W_D3D12_VIEW_DEFAULTS", value, sizeof(value)); + return x2w_view_dimension::default_views_mode(n && n < sizeof(value) ? value : nullptr); + }(); + return mode; +} + // Device view slots: forwarded with the destination CPU handle (argument D, 0-based after the // object) translated from title to desktop. // Desktop removes the device (DXGI_ERROR_INVALID_CALL) on view calls it rejects, so they are checked @@ -4243,6 +4277,7 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) described_bytes, title_dest, args[D], materialized); }; const char* skip = nullptr; + bool default_view = false; if (N == 17) skip = "constant buffer view (title GPU address)"; if (N >= 18 && N <= 21 && args[0]) { const UINT flags = reinterpret_cast(args[0])->GetDesc().Flags; @@ -4250,9 +4285,56 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) if (N == 19 && !(flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) skip = "resource lacks unordered access"; if (N == 20 && !(flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET)) skip = "resource lacks render target"; if (N == 21 && !(flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) skip = "resource lacks depth stencil"; + // Every view description of slots 18-21 starts with Format, then ViewDimension. + const u64 described = N == 19 ? args[2] : args[1]; + UINT view_dimension = 0; + if (!skip && described && x2w_local::readable(reinterpret_cast(described), 8)) { + std::memcpy(&view_dimension, reinterpret_cast(described) + 4, sizeof(view_dimension)); + const D3D12_RESOURCE_DESC resource_desc = reinterpret_cast(args[0])->GetDesc(); + const auto dimension = static_cast(resource_desc.Dimension); + if (view_dimension == 0) { + // UNKNOWN: desktop refuses it; make the resource's default view where that is allowed. By default only + // SRVs (slot 18) get one; UAV, RTV and DSV need X2W_D3D12_VIEW_DEFAULTS=all (view_dimension.h). + const auto mode = view_defaults_mode(); + if (x2w_view_dimension::default_view_allowed(N, dimension, static_cast(resource_desc.Format), mode)) + default_view = true; + else if (x2w_view_dimension::default_view_allowed(N, dimension, static_cast(resource_desc.Format), + x2w_view_dimension::DefaultViews::all)) + skip = mode == x2w_view_dimension::DefaultViews::off + ? "unknown view dimension, and default views are off (X2W_D3D12_VIEW_DEFAULTS=off)" + : "unknown view dimension; a default view of this type needs X2W_D3D12_VIEW_DEFAULTS=all"; + else + skip = "unknown view dimension, and the resource has no default view"; + static LONG unknown_dimension; + if (first_calls(unknown_dimension, 6)) + log("x2w-d3d12 Device::slot%d view dimension 0 (unknown), view format %u, resource dim=%u fmt=%d -> %s", N, + *reinterpret_cast(described), dimension, resource_desc.Format, + default_view ? "default view" : "skipped"); + } else if (!x2w_view_dimension::fits(N, view_dimension, dimension)) { + skip = "view dimension does not suit the resource"; + static LONG mismatched; + if (first_calls(mismatched, 6)) + log("x2w-d3d12 Device::slot%d view dimension %u needs resource dimension %u, resource has %u", N, view_dimension, + x2w_view_dimension::needed(N, view_dimension), dimension); + } + } } + // Replace a refused SRV in both the desktop heap and the descriptor record. A skipped UAV, RTV or DSV + // does not write a replacement to the desktop heap, so its previous descriptor record must stay live. + const auto refuse_view = [&] { + if constexpr (N == 18) { + UINT requested = D3D12_SRV_DIMENSION_TEXTURE2D; + if (args[1] && x2w_local::readable(reinterpret_cast(args[1]), 8)) + std::memcpy(&requested, reinterpret_cast(args[1]) + 4, sizeof(requested)); + const D3D12_SHADER_RESOURCE_VIEW_DESC null_view = null_srv_desc(requested); + device_of(self)->CreateShaderResourceView(nullptr, &null_view, D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(args[D])}); + record_view(false); + } else if constexpr (N == 17) { + record_view(false); // Translated constant-buffer views use only the descriptor record. + } + }; if (skip) { - record_view(false); + refuse_view(); static LONG skipped; if (first_calls(skipped, 6)) log("x2w-d3d12 Device::slot%d view skipped: %s", N, skip); return 0; @@ -4274,7 +4356,7 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) const auto actual = resource->GetDesc().Format; const auto verdict = x2w_startup::packed_view(mapped, actual, x2w_startup::packed_stand_in_of(resource)); if (verdict == x2w_startup::PackedView::refused) { - record_view(false); + refuse_view(); static LONG refused; if (first_calls(refused, 6)) log("x2w-d3d12 Device::slot%d view skipped: packed format %d on a texture of format %d that does not stand in for it", @@ -4302,6 +4384,8 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) *reinterpret_cast(b), null_rtv)) args[1] = reinterpret_cast(&null_rtv); } + if (default_view) args[desc_index] = 0; + const LONG removed_before = removal_reported; const u64 result = method_of(self->own().real, N)(self->own().real, args[0], args[1], args[2], args[3], 0, 0, 0, 0); // A desktop view creation returns void, so the only failure it reports is a removed device. Only a created view // may keep the resource: on failure the slot is recorded unmaterialized, which releases the slot's previous view @@ -4318,6 +4402,19 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) if ((N == 20 || N == 21) && args[0] && created) note_view_target(args[D], reinterpret_cast(args[0]), N); check_device("Device view", N); + if (!removed_before && removal_reported && N >= 18 && N <= 21) { + // The view that removed the device: its forwarded description and the resource's shape. + char bytes[3 * 40 + 1] = {}; + const u64 described = args[desc_index]; + if (described) hex_text(reinterpret_cast(described), 40, bytes, sizeof(bytes)); + log("x2w-d3d12 Device::slot%d removing view desc %s", N, described ? bytes : "(null)"); + if (args[0]) { + const D3D12_RESOURCE_DESC rd = reinterpret_cast(args[0])->GetDesc(); + log("x2w-d3d12 Device::slot%d removing view resource: dim=%d %llux%u depth/array=%u mips=%u fmt=%d samples=%u flags=0x%x", N, + rd.Dimension, static_cast(rd.Width), rd.Height, rd.DepthOrArraySize, rd.MipLevels, rd.Format, + rd.SampleDesc.Count, static_cast(rd.Flags)); + } + } static LONG calls; if (first_calls(calls)) log("x2w-d3d12 Device::slot%d view(0x%llx, 0x%llx, 0x%llx, 0x%llx) dest 0x%llx -> 0x%llx", N, a, b, c, d, @@ -5059,28 +5156,9 @@ void retire_resource(Wrapper* w) // resolves to nothing). A null resource reads no more of the description than its format and dimension. D3D12_SHADER_RESOURCE_VIEW_DESC retire_null_srv_desc(const ViewRecord& record) { - D3D12_SHADER_RESOURCE_VIEW_DESC desc{}; - desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; - desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - desc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; - if (record.desc_bytes >= 40) { - D3D12_SRV_DIMENSION dimension; - std::memcpy(&dimension, record.desc + 4, sizeof(dimension)); - if (dimension >= D3D12_SRV_DIMENSION_TEXTURE1D && dimension <= D3D12_SRV_DIMENSION_TEXTURECUBEARRAY) - desc.ViewDimension = dimension; - } - switch (desc.ViewDimension) { - case D3D12_SRV_DIMENSION_TEXTURE1D: desc.Texture1D.MipLevels = 1; break; - case D3D12_SRV_DIMENSION_TEXTURE1DARRAY: desc.Texture1DArray.MipLevels = 1; desc.Texture1DArray.ArraySize = 1; break; - case D3D12_SRV_DIMENSION_TEXTURE2DARRAY: desc.Texture2DArray.MipLevels = 1; desc.Texture2DArray.ArraySize = 1; break; - case D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY: desc.Texture2DMSArray.ArraySize = 1; break; - case D3D12_SRV_DIMENSION_TEXTURE3D: desc.Texture3D.MipLevels = 1; break; - case D3D12_SRV_DIMENSION_TEXTURECUBE: desc.TextureCube.MipLevels = 1; break; - case D3D12_SRV_DIMENSION_TEXTURECUBEARRAY: desc.TextureCubeArray.MipLevels = 1; desc.TextureCubeArray.NumCubes = 1; break; - case D3D12_SRV_DIMENSION_TEXTURE2DMS: break; - default: desc.Texture2D.MipLevels = 1; break; - } - return desc; + unsigned dimension = D3D12_SRV_DIMENSION_TEXTURE2D; + if (record.desc_bytes >= 40) std::memcpy(&dimension, record.desc + 4, sizeof(dimension)); + return null_srv_desc(dimension); } // True when the release-time fence of every queue has passed (retire_lock held). diff --git a/src/startup_stubs/view_dimension.h b/src/startup_stubs/view_dimension.h new file mode 100644 index 000000000..52bf92e38 --- /dev/null +++ b/src/startup_stubs/view_dimension.h @@ -0,0 +1,105 @@ +// Experimental (docs/startup-runtime.md): whether a view description's ViewDimension suits the +// resource it is made on. Desktop D3D12 removes the device (DXGI_ERROR_INVALID_CALL, debug-layer +// message "The ViewDimension in the View Desc is incompatible with the type of the Resource") +// instead of failing the call, so the stand-in checks first and skips such a view with a log. +// Values are the public d3d12.h enumerations. Pure, no Windows calls, so a control can check it. +#pragma once + +namespace x2w_view_dimension { + +enum ResourceDimension : unsigned { unknown = 0, buffer = 1, texture1d = 2, texture2d = 3, texture3d = 4 }; + +// Which resource dimension one view dimension needs, by the device slot that makes the view +// (18 shader resource, 19 unordered access, 20 render target, 21 depth stencil). unknown when the +// view dimension is not one of that view type's values (or is 0); such a view is not judged here. +inline unsigned needed(int slot, unsigned view_dimension) noexcept +{ + switch (slot) { + case 18: // D3D12_SRV_DIMENSION + switch (view_dimension) { + case 1: return buffer; + case 2: case 3: return texture1d; + case 4: case 5: case 6: case 7: case 9: case 10: return texture2d; // 2D, arrays, MS, cube, cube array + case 8: return texture3d; + default: return unknown; // 11 is a raytracing structure, made with a null resource + } + case 19: // D3D12_UAV_DIMENSION + case 20: // D3D12_RTV_DIMENSION (same numbering) + switch (view_dimension) { + case 1: return buffer; + case 2: case 3: return texture1d; + case 4: case 5: case 6: case 7: return texture2d; + case 8: return texture3d; + default: return unknown; + } + case 21: // D3D12_DSV_DIMENSION + switch (view_dimension) { + case 1: case 2: return texture1d; + case 3: case 4: case 5: case 6: return texture2d; + default: return unknown; + } + default: + return unknown; + } +} + +// False only when the view dimension names a resource dimension other than the resource's. +inline bool fits(int slot, unsigned view_dimension, unsigned resource_dimension) noexcept +{ + const unsigned need = needed(slot, view_dimension); + return need == unknown || need == resource_dimension; +} + +// A description with ViewDimension 0 (UNKNOWN) is always refused by desktop D3D12. Measured: a +// title module makes one on a two-dimensional RGBA8 texture (format R32G32B32A32_FLOAT, default +// component mapping). The stand-in makes the resource's default view instead (a null description), +// which desktop allows only for a texture with a typed format, and for a shader resource view not +// a depth format. Whether the console gives UNKNOWN that meaning is a hypothesis. +inline bool typeless(unsigned format) noexcept +{ + switch (format) { + case 1: case 5: case 9: case 15: case 19: case 23: case 27: case 33: case 39: case 44: case 48: case 53: case 59: + case 70: case 73: case 76: case 79: case 82: case 90: case 92: case 94: case 97: + return true; + default: + return false; + } +} + +inline bool depth_format(unsigned format) noexcept { return format == 20 || format == 40 || format == 45 || format == 55; } + +// Which slots may get the default view. It is measured only for shader resource views (slot 18) of +// typed textures, so that is the default. The default view also drops the requested format and +// component mapping, so for the other view types it stays an explicit experiment +// (X2W_D3D12_VIEW_DEFAULTS=all). off: every unknown-dimension view is skipped. +enum class DefaultViews : unsigned { off, srv, all }; + +// X2W_D3D12_VIEW_DEFAULTS: "all" or "off"; anything else, or unset, is srv. +inline DefaultViews default_views_mode(const char* value) noexcept +{ + if (!value) return DefaultViews::srv; + if (value[0] == 'a' && value[1] == 'l' && value[2] == 'l' && value[3] == 0) return DefaultViews::all; + if (value[0] == 'o' && value[1] == 'f' && value[2] == 'f' && value[3] == 0) return DefaultViews::off; + return DefaultViews::srv; +} + +inline bool default_view_allowed(int slot, unsigned resource_dimension, unsigned resource_format, DefaultViews mode) noexcept +{ + if (slot < 18 || slot > 21) return false; + if (mode == DefaultViews::off || (mode == DefaultViews::srv && slot != 18)) return false; + if (resource_dimension == unknown || resource_dimension == buffer) return false; + if (resource_format == 0 || typeless(resource_format)) return false; + if (slot == 18 && depth_format(resource_format)) return false; + return true; +} + +// The dimension of the null SRV that replaces a refused one in its destination slot, so that the slot +// cannot keep the view it held before (a skipped call would otherwise leave that descriptor in place, +// bindable and copyable, after the slot's record has dropped its resource). The requested dimension +// when it is a texture dimension (2 to 10), else texture 2D (4). +inline unsigned refused_srv_null_dimension(unsigned requested) noexcept +{ + return requested >= 2 && requested <= 10 ? requested : 4; +} + +} // namespace x2w_view_dimension diff --git a/tests/startup_view_dimension_check.cpp b/tests/startup_view_dimension_check.cpp new file mode 100644 index 000000000..a4b328a7a --- /dev/null +++ b/tests/startup_view_dimension_check.cpp @@ -0,0 +1,122 @@ +// Source-built control for view_dimension.h: whether a view's ViewDimension suits the dimension of +// the resource it is made on (desktop D3D12 removes the device for a mismatch). Values are the +// public d3d12.h enumerations. --control swaps the resource dimension of the mismatched cases for +// the matching one and enables default views for every slot in the gated cases, so the checks +// that expect a refusal must print FAIL. +#include +#include + +#include "startup_stubs/view_dimension.h" + +namespace { +int failures; +bool control; + +void check(const char* what, bool ok) +{ + if (!ok) { + std::printf("FAIL: %s\n", what); + ++failures; + } +} + +// A refusal case: in the control the resource is given the dimension the view needs. +bool refused(int slot, unsigned view_dimension, unsigned resource_dimension) +{ + using namespace x2w_view_dimension; + if (control) resource_dimension = needed(slot, view_dimension); + return !fits(slot, view_dimension, resource_dimension); +} +} // namespace + +int main(int argc, char** argv) +{ + using namespace x2w_view_dimension; + control = argc > 1 && std::strcmp(argv[1], "--control") == 0; + + // Matching shapes are accepted. + check("SRV texture 2D on a 2D texture", fits(18, 4, texture2d)); + check("SRV cube on a 2D texture", fits(18, 9, texture2d)); + check("SRV cube array on a 2D texture", fits(18, 10, texture2d)); + check("SRV texture 3D on a 3D texture", fits(18, 8, texture3d)); + check("SRV buffer on a buffer", fits(18, 1, buffer)); + check("SRV texture 1D array on a 1D texture", fits(18, 3, texture1d)); + check("UAV texture 2D array on a 2D texture", fits(19, 5, texture2d)); + check("UAV texture 3D on a 3D texture", fits(19, 8, texture3d)); + check("RTV buffer on a buffer", fits(20, 1, buffer)); + check("RTV texture 2D on a 2D texture", fits(20, 4, texture2d)); + check("DSV texture 1D on a 1D texture", fits(21, 1, texture1d)); + check("DSV texture 2D on a 2D texture", fits(21, 3, texture2d)); + + // Values this check does not judge pass on: unknown dimension, raytracing structure, other slots. + check("SRV unknown dimension is not judged", fits(18, 0, texture3d)); + check("SRV raytracing structure is not judged", fits(18, 11, unknown)); + check("out-of-range SRV dimension is not judged", fits(18, 99, buffer)); + check("DSV dimension 7 is not judged", fits(21, 7, buffer)); + check("sampler slot is not judged", fits(22, 4, buffer)); + + // Mismatches are refused (the control turns each into a match, so these print FAIL). + check("SRV texture 2D on a 3D texture is refused", refused(18, 4, texture3d)); + check("SRV texture 3D on a 2D texture is refused", refused(18, 8, texture2d)); + check("SRV buffer on a 2D texture is refused", refused(18, 1, texture2d)); + check("SRV cube on a 3D texture is refused", refused(18, 9, texture3d)); + check("UAV texture 2D on a buffer is refused", refused(19, 4, buffer)); + check("RTV texture 3D on a 2D texture is refused", refused(20, 8, texture2d)); + check("DSV texture 2D on a 1D texture is refused", refused(21, 3, texture1d)); + + // ViewDimension 0 (unknown): a default view only where desktop allows a null description. Under + // X2W_D3D12_VIEW_DEFAULTS=all (experimental) every view type may get one. + const auto all = DefaultViews::all, srv = DefaultViews::srv, off = DefaultViews::off; + check("default SRV of an RGBA8 2D texture", default_view_allowed(18, texture2d, 28, all)); + check("default RTV of an RGBA8 2D texture", default_view_allowed(20, texture2d, 28, all)); + check("default DSV of a D32 2D texture", default_view_allowed(21, texture2d, 40, all)); + check("default SRV of a 3D texture", default_view_allowed(18, texture3d, 10, all)); + const auto no_default = [all](int slot, unsigned dimension, unsigned format) { + if (control) dimension = texture2d, format = 28; // a texture that has a default view + return !default_view_allowed(slot, dimension, format, all); + }; + check("no default view of a buffer", no_default(18, buffer, 28)); + check("no default view of a typeless texture", no_default(18, texture2d, 27)); + check("no default view of a typeless BC7 texture", no_default(19, texture2d, 97)); + check("no default SRV of a depth texture", no_default(18, texture2d, 40)); + check("no default view of an unknown format", no_default(18, texture2d, 0)); + check("no default view on the constant-buffer slot", !default_view_allowed(17, texture2d, 28, all)); + + // The default (srv): only the measured typed-SRV case; UAV, RTV and DSV need the experiment. + // The control enables all slots, so the three refusals print FAIL. + const auto gated = [all, srv](int slot, unsigned dimension, unsigned format) { + return !default_view_allowed(slot, dimension, format, control ? all : srv); + }; + check("default SRV of an RGBA8 2D texture without the experiment", default_view_allowed(18, texture2d, 28, srv)); + check("default SRV of a 3D texture without the experiment", default_view_allowed(18, texture3d, 10, srv)); + check("no default SRV of a depth texture without the experiment", !default_view_allowed(18, texture2d, 40, srv)); + check("no default UAV without the experiment", gated(19, texture2d, 28)); + check("no default RTV without the experiment", gated(20, texture2d, 28)); + check("no default DSV without the experiment", gated(21, texture2d, 40)); + check("off: no default SRV", !default_view_allowed(18, texture2d, 28, off)); + check("off: no default RTV", !default_view_allowed(20, texture2d, 28, off)); + + // X2W_D3D12_VIEW_DEFAULTS parsing: exact "all" or "off", anything else is the default. + check("unset is srv", default_views_mode(nullptr) == srv); + check("empty is srv", default_views_mode("") == srv); + check("all", default_views_mode("all") == all); + check("off", default_views_mode("off") == off); + check("ALL is srv", default_views_mode("ALL") == srv); + check("allx is srv", default_views_mode("allx") == srv); + check("1 is srv", default_views_mode("1") == srv); + + // A refused SRV's null descriptor keeps a texture dimension and turns the rest into texture 2D. + check("null for a refused 3D view is 3D", refused_srv_null_dimension(8) == 8); + check("null for a refused cube array is a cube array", refused_srv_null_dimension(10) == 10); + check("null for a refused 1D view is 1D", refused_srv_null_dimension(2) == 2); + check("null for a refused unknown view is 2D", refused_srv_null_dimension(0) == 4); + check("null for a refused buffer view is 2D", refused_srv_null_dimension(1) == 4); + check("null for a refused raytracing view is 2D", refused_srv_null_dimension(11) == 4); + + if (failures) { + std::printf("startup_view_dimension: FAIL (%d)\n", failures); + return 1; + } + std::puts("startup_view_dimension: ok"); + return 0; +} diff --git a/tests/startup_view_dimension_device.cpp b/tests/startup_view_dimension_device.cpp new file mode 100644 index 000000000..823b6c7c7 --- /dev/null +++ b/tests/startup_view_dimension_device.cpp @@ -0,0 +1,425 @@ +// Device slot 18 (CreateShaderResourceView) through d3d12_xs.dll with view descriptions whose ViewDimension is +// unknown or does not suit the resource (src/startup_stubs/view_dimension.h, docs/startup-runtime.md#unknown-and- +// mismatched-view-dimensions). +// +// startup_view_dimension_device [off] +// +// The fixture reads the desktop descriptors the shim wrote: a compute shader on the fixture's own desktop queue +// samples texel (0,0) through a slot of a shader-visible guest heap, by the desktop heap behind it. A null +// descriptor reads zero. +// (a) an SRV with ViewDimension 0 and a requested format that differs from the texture's (R32G32B32A32_FLOAT on an +// R8G8B8A8_UNORM texture) gets the texture's default view: the slot samples the texture's distinct colour. +// (b) an explicit TEXTURE3D SRV of the 2D texture is refused: the device is not removed. +// (c) a slot that holds a valid view of a second texture (its colour is read first) receives a refused TEXTURE2D +// SRV of a buffer. The device is not removed and the slot reads zero: the refusal leaves a null SRV, not the +// old descriptor. A CopyDescriptorsSimple copy of the slot over another valid view reads zero too. +// (d) a refused UAV replacement leaves the prior descriptor and its title token intact. +// +// `off` is the negative control and needs X2W_D3D12_VIEW_DEFAULTS=off: (a) must then fail, printing +// "FAIL: (a) default view reads 0.000 0.000 0.000 0.000 ... device not removed", and nothing else may fail. +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +using Microsoft::WRL::ComPtr; + +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); + +namespace { + +constexpr UINT side = 4, pitch = 256, image_bytes = side * pitch; +constexpr DWORD wait_ms = 10000; +constexpr std::uint8_t colour_a[4] = {51, 153, 204, 255}; // 0.2 0.6 0.8 1.0 +constexpr std::uint8_t colour_b[4] = {255, 64, 0, 128}; + +template +Result invoke(IUnknown* object, unsigned slot, Args... args) +{ + using Call = Result (WINAPI*)(IUnknown*, Args...); + return reinterpret_cast((*reinterpret_cast(object))[slot])(object, args...); +} + +template +ComPtr desktop_object(IUnknown* guest, ID3D12Device* device, IUnknown* object) +{ + constexpr GUID key{0x0e34d52f, 0xd5a5, 0x4790, {0x91, 0xd4, 0x11, 0xa6, 0x7c, 0xbc, 0x2b, 0xc1}}; + ComPtr output; + if (FAILED(invoke(guest, 5, &key, object))) return output; + ComPtr reference; + UINT bytes = sizeof(IUnknown*); + const HRESULT hr = device->GetPrivateData(key, &bytes, reference.GetAddressOf()); + invoke(guest, 5, &key, static_cast(nullptr)); + if (SUCCEEDED(hr)) reference.As(&output); + return output; +} + +bool require(HRESULT hr, const char* stage) +{ + if (FAILED(hr)) std::printf("FAIL: setup: %s hr=0x%08lx\n", stage, static_cast(hr)); + return SUCCEEDED(hr); +} + +ComPtr pick_adapter(IDXGIFactory4* factory, bool warp) +{ + ComPtr adapter; + if (warp) { + factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)); + return adapter; + } + wchar_t name[128]{}; + GetEnvironmentVariableW(L"XBOX2WINDOWS_ADAPTER", name, static_cast(std::size(name))); + for (UINT i = 0; factory->EnumAdapters1(i, &adapter) == S_OK; ++i, adapter.Reset()) { + DXGI_ADAPTER_DESC1 desc{}; + if (SUCCEEDED(adapter->GetDesc1(&desc)) && !(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && + (!name[0] || std::wcsstr(desc.Description, name)) && + SUCCEEDED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) + return adapter; + } + return nullptr; +} + +constexpr char probe_shader[] = R"( +Texture2D source : register(t0); +SamplerState point_sampler : register(s0); +RWByteAddressBuffer result : register(u0); +[numthreads(1, 1, 1)] void main() +{ + result.Store4(0, asuint(source.SampleLevel(point_sampler, float2(0.125, 0.125), 0))); +} +)"; + +struct Context { + IUnknown* guest; + ID3D12Device* device; + ComPtr queue; + ComPtr allocator; + ComPtr list; + ComPtr fence; + UINT64 value = 0; + HANDLE event = nullptr; + ComPtr upload, readback, probe_out; + ComPtr root; + ComPtr pso; + ComPtr heap; + ComPtr heap_real; + UINT64 heap_cpu = 0; + UINT increment = 0; + + bool run() + { + if (!require(list->Close(), "list close")) return false; + ID3D12CommandList* lists[] = {list.Get()}; + queue->ExecuteCommandLists(1, lists); + if (!require(queue->Signal(fence.Get(), ++value), "signal")) return false; + if (fence->GetCompletedValue() >= value) return true; + if (!require(fence->SetEventOnCompletion(value, event), "fence event")) return false; + if (WaitForSingleObject(event, wait_ms) == WAIT_OBJECT_0) return true; + std::puts("FAIL: setup: queue timed out"); + return false; + } + bool begin() { return require(allocator->Reset(), "allocator reset") && require(list->Reset(allocator.Get(), nullptr), "list reset"); } + ComPtr committed(const D3D12_RESOURCE_DESC& desc, const char* name) + { + const D3D12_HEAP_PROPERTIES props{D3D12_HEAP_TYPE_DEFAULT}; + D3D12_RESOURCE_DESC d = desc; + const GUID iid = __uuidof(ID3D12Resource); + ComPtr out; + if (!require(invoke(guest, 127, &props, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_COMMON, nullptr, nullptr, 0u, + nullptr, &iid, out.GetAddressOf()), name)) + out.Reset(); + return out; + } + // Fills every texel of a guest 2D texture with one colour through its desktop object. + bool fill(IUnknown* texture, const std::uint8_t (&colour)[4]) + { + const auto real = desktop_object(guest, device, texture); + if (!real) { + std::puts("FAIL: setup: texture has no desktop object"); + return false; + } + void* mapped = nullptr; + const D3D12_RANGE none{}; + if (!require(upload->Map(0, &none, &mapped), "upload map")) return false; + auto* dst = static_cast(mapped); + for (UINT y = 0; y < side; ++y) + for (UINT x = 0; x < side; ++x) std::memcpy(dst + y * pitch + x * 4, colour, 4); + upload->Unmap(0, nullptr); + if (!begin()) return false; + D3D12_TEXTURE_COPY_LOCATION to{real.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {}}; + to.SubresourceIndex = 0; + D3D12_TEXTURE_COPY_LOCATION from{upload.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, {}}; + from.PlacedFootprint.Footprint = {DXGI_FORMAT_R8G8B8A8_UNORM, side, side, 1, pitch}; + list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); + D3D12_RESOURCE_BARRIER b{D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, D3D12_RESOURCE_BARRIER_FLAG_NONE, {}}; + b.Transition = {real.Get(), D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_COMMON}; + list->ResourceBarrier(1, &b); + return run(); + } + // Samples texel (0,0) through the desktop descriptor behind slot `index` of the guest heap. + bool read_slot(UINT index, float (&texel)[4]) + { + if (!begin()) return false; + ID3D12DescriptorHeap* bound = heap_real.Get(); + D3D12_GPU_DESCRIPTOR_HANDLE gpu = heap_real->GetGPUDescriptorHandleForHeapStart(); + gpu.ptr += std::uint64_t{index} * increment; + list->SetDescriptorHeaps(1, &bound); + list->SetComputeRootSignature(root.Get()); + list->SetPipelineState(pso.Get()); + list->SetComputeRootDescriptorTable(0, gpu); + list->SetComputeRootUnorderedAccessView(1, probe_out->GetGPUVirtualAddress()); + list->Dispatch(1, 1, 1); + D3D12_RESOURCE_BARRIER b{D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, D3D12_RESOURCE_BARRIER_FLAG_NONE, {}}; + b.Transition = {probe_out.Get(), D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COPY_SOURCE}; + list->ResourceBarrier(1, &b); + list->CopyBufferRegion(readback.Get(), 0, probe_out.Get(), 0, 16); + b.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_SOURCE; + b.Transition.StateAfter = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + list->ResourceBarrier(1, &b); + if (!run()) return false; + void* mapped = nullptr; + const D3D12_RANGE all{0, 16}; + if (!require(readback->Map(0, &all, &mapped), "readback map")) return false; + std::memcpy(texel, mapped, sizeof(texel)); + readback->Unmap(0, nullptr); + return true; + } + const char* device_state() + { + return SUCCEEDED(device->GetDeviceRemovedReason()) && SUCCEEDED(invoke(guest, 37)) ? "device not removed" + : "DEVICE REMOVED"; + } + bool device_ok() { return SUCCEEDED(device->GetDeviceRemovedReason()) && SUCCEEDED(invoke(guest, 37)); } + // want: the colour the slot must sample, or nullptr for null (all zero). *failed is set on a mismatch; false is + // returned only when the probe itself could not run. + bool expect(UINT index, const std::uint8_t* want, const char* what, bool* failed) + { + float texel[4]{}; + if (!read_slot(index, texel)) return false; + bool match = true; + for (int i = 0; i < 4; ++i) { + const float expected = want ? want[i] / 255.0f : 0.0f; + if (std::fabs(texel[i] - expected) > 0.5f / 255.0f) match = false; + } + if (match) { + std::printf("%s: reads %.3f %.3f %.3f %.3f as expected\n", what, texel[0], texel[1], texel[2], texel[3]); + return true; + } + std::printf("FAIL: %s reads %.3f %.3f %.3f %.3f, expected ", what, texel[0], texel[1], texel[2], texel[3]); + if (want) std::printf("%.3f %.3f %.3f %.3f", want[0] / 255.0f, want[1] / 255.0f, want[2] / 255.0f, want[3] / 255.0f); + else std::printf("null (all zero)"); + std::printf("; %s\n", device_state()); + *failed = true; + return true; + } + UINT64 slot(UINT index) const { return heap_cpu + std::uint64_t{index} * increment; } +}; + +D3D12_SHADER_RESOURCE_VIEW_DESC texture2d_view() +{ + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Texture2D.MipLevels = 1; + return srv; +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc < 2 || argc > 3 || (std::strcmp(argv[1], "warp") && std::strcmp(argv[1], "hardware")) || + (argc == 3 && std::strcmp(argv[2], "off"))) + return 2; + const bool off = argc == 3; + char mode[8]{}; + const DWORD mode_n = GetEnvironmentVariableA("X2W_D3D12_VIEW_DEFAULTS", mode, sizeof(mode)); + const bool env_off = mode_n == 3 && std::strcmp(mode, "off") == 0; + if (env_off != off || (!off && mode_n)) { + std::puts("FAIL: setup: X2W_D3D12_VIEW_DEFAULTS must be unset, or off with the `off` argument"); + return 2; + } + ComPtr factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 3; + const auto adapter = pick_adapter(factory.Get(), std::strcmp(argv[1], "warp") == 0); + if (!adapter) return 77; + ComPtr guest; + ComPtr device; + std::array parameters{}; + if (!require(D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), + reinterpret_cast(guest.GetAddressOf())), "Xbox device") || + !require(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&device)), "desktop device")) + return 3; + DXGI_ADAPTER_DESC1 adapter_desc{}; + adapter->GetDesc1(&adapter_desc); + std::printf("adapter=%ls debug_layer=off view_defaults=%s\n", adapter_desc.Description, off ? "off" : "unset (srv)"); + + Context c{guest.Get(), device.Get()}; + c.increment = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + c.event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + const D3D12_COMMAND_QUEUE_DESC direct{}; + const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}, readback_heap{D3D12_HEAP_TYPE_READBACK}, + default_heap{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_RESOURCE_DESC buffer{D3D12_RESOURCE_DIMENSION_BUFFER, 0, image_bytes, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; + D3D12_RESOURCE_DESC out_desc = buffer; + out_desc.Width = 256; + out_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + if (!c.event || !require(device->CreateCommandQueue(&direct, IID_PPV_ARGS(&c.queue)), "queue") || + !require(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&c.allocator)), "allocator") || + !require(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, c.allocator.Get(), nullptr, IID_PPV_ARGS(&c.list)), "list") || + !require(c.list->Close(), "list close") || + !require(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&c.fence)), "fence") || + !require(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_GENERIC_READ, + nullptr, IID_PPV_ARGS(&c.upload)), "upload") || + !require(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COPY_DEST, + nullptr, IID_PPV_ARGS(&c.readback)), "readback") || + !require(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &out_desc, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, IID_PPV_ARGS(&c.probe_out)), "probe output")) + return 4; + + // The probe: samples (0,0) through descriptor table slot 0 with a point sampler. + const D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; + D3D12_ROOT_PARAMETER root_parameters[2]{}; + root_parameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + root_parameters[0].DescriptorTable = {1, &range}; + root_parameters[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + root_parameters[1].Descriptor = {0, 0}; + D3D12_STATIC_SAMPLER_DESC sampler{}; + sampler.Filter = D3D12_FILTER_MIN_MAG_MIP_POINT; + sampler.AddressU = sampler.AddressV = sampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; + sampler.MaxLOD = D3D12_FLOAT32_MAX; + sampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + const D3D12_ROOT_SIGNATURE_DESC root_desc{2, root_parameters, 1, &sampler, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + ComPtr root_blob, errors, code; + if (!require(D3D12SerializeRootSignature(&root_desc, D3D_ROOT_SIGNATURE_VERSION_1, root_blob.GetAddressOf(), + errors.GetAddressOf()), "root serialize") || + !require(device->CreateRootSignature(0, root_blob->GetBufferPointer(), root_blob->GetBufferSize(), IID_PPV_ARGS(&c.root)), + "root signature") || + !require(D3DCompile(probe_shader, std::strlen(probe_shader), nullptr, nullptr, nullptr, "main", "cs_5_1", 0, 0, + code.GetAddressOf(), errors.ReleaseAndGetAddressOf()), "probe shader")) + return 4; + D3D12_COMPUTE_PIPELINE_STATE_DESC pso{}; + pso.pRootSignature = c.root.Get(); + pso.CS = {code->GetBufferPointer(), code->GetBufferSize()}; + if (!require(device->CreateComputePipelineState(&pso, IID_PPV_ARGS(&c.pso)), "probe pipeline")) return 4; + + // A shader-visible guest heap of four SRV slots. + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 backing, bytes; + } request{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 4, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, 0, 0}; + if (!require(invoke(c.guest, 14, &request, &__uuidof(ID3D12DescriptorHeap), c.heap.GetAddressOf()), "guest heap")) return 4; + c.heap_real = desktop_object(c.guest, device.Get(), c.heap.Get()); + if (!c.heap_real) { + std::puts("FAIL: setup: guest heap has no desktop object"); + return 4; + } + c.heap_cpu = invoke(c.heap.Get(), 9); + + const D3D12_RESOURCE_DESC texture_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, side, side, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, + {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE}; + D3D12_RESOURCE_DESC small_buffer = buffer; + small_buffer.Width = 256; + const auto texture_a = c.committed(texture_desc, "texture A"); + const auto texture_b = c.committed(texture_desc, "texture B"); + const auto buffer_c = c.committed(small_buffer, "buffer"); + if (!texture_a || !texture_b || !buffer_c || !c.fill(texture_a.Get(), colour_a) || !c.fill(texture_b.Get(), colour_b)) + return 4; + if (!c.device_ok()) { + std::puts("FAIL: setup: device removed before the cases"); + return 4; + } + + bool failed = false; + // (a) ViewDimension 0 with another format: the texture's default view. + D3D12_SHADER_RESOURCE_VIEW_DESC unknown{}; + unknown.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; + unknown.ViewDimension = D3D12_SRV_DIMENSION_UNKNOWN; + unknown.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + invoke(c.guest, 18, texture_a.Get(), &unknown, c.slot(0)); + if (!c.device_ok()) { + std::puts("FAIL: (a) the unknown-dimension SRV removed the device"); + return 5; + } + if (!c.expect(0, colour_a, "(a) default view", &failed)) return 4; + + // (b) an explicit TEXTURE3D SRV of the 2D texture: refused, the device stays. + D3D12_SHADER_RESOURCE_VIEW_DESC volume = texture2d_view(); + volume.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D; + volume.Texture3D = {0, 1, 0.0f}; + invoke(c.guest, 18, texture_a.Get(), &volume, c.slot(1)); + if (!c.device_ok()) { + std::puts("FAIL: (b) the incompatible explicit SRV was forwarded and removed the device"); + return 5; + } + std::puts("(b) TEXTURE3D SRV of a 2D texture: refused, device not removed"); + + // (c) a refused replacement over a valid view, and a copy of the slot over another valid view. + const auto valid = texture2d_view(); + invoke(c.guest, 18, texture_b.Get(), &valid, c.slot(2)); + invoke(c.guest, 18, texture_b.Get(), &valid, c.slot(3)); + bool setup_failed = false; + if (!c.expect(2, colour_b, "(c) valid view before the replacement", &setup_failed) || + !c.expect(3, colour_b, "(c) valid copy target before the copy", &setup_failed)) + return 4; + if (setup_failed) { + std::puts("FAIL: setup: valid views do not read their texture"); + return 4; + } + invoke(c.guest, 18, buffer_c.Get(), &valid, c.slot(2)); // TEXTURE2D of a buffer + if (!c.device_ok()) { + std::puts("FAIL: (c) the refused replacement removed the device"); + return 5; + } + if (!c.expect(2, nullptr, "(c) slot after the refused replacement", &failed)) return 4; + invoke(c.guest, 24, 1u, c.slot(3), c.slot(2), D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + if (!c.expect(3, nullptr, "(c) copy of the refused slot", &failed)) return 4; + + auto uav_desc = texture_desc; + uav_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + const auto uav_texture = c.committed(uav_desc, "UAV texture"); + if (!uav_texture) return 4; + D3D12_UNORDERED_ACCESS_VIEW_DESC uav{}; + uav.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + uav.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; + const auto uav_slot = c.slot(1); + invoke(c.guest, 19, uav_texture.Get(), static_cast(nullptr), &uav, uav_slot); + if (!c.device_ok()) return 5; + std::array before{}, after{}; + std::memcpy(before.data(), reinterpret_cast(uav_slot), sizeof(before)); + if (!before[0] || before[2] != 19) { + std::puts("FAIL: (d) no valid UAV token before the replacement"); + return 4; + } + uav.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D; + uav.Texture3D = {0, 0, 1}; + invoke(c.guest, 19, uav_texture.Get(), static_cast(nullptr), &uav, uav_slot); + std::memcpy(after.data(), reinterpret_cast(uav_slot), sizeof(after)); + if (after != before) { + std::puts("FAIL: (d) refused UAV replacement changed the live descriptor token"); + failed = true; + } else { + std::puts("(d) refused UAV replacement kept the live descriptor token"); + } + + if (!c.device_ok()) { + std::puts("FAIL: device removed after the cases"); + return 5; + } + std::printf("cases complete, %s\n", failed ? "with failures" : "all passed"); + if (failed) return 1; + std::puts("startup_view_dimension_device: default SRV samples its texture; refused SRVs leave null descriptors; " + "device not removed"); + return 0; +} From d26cbc5487c07464fb0eab4a2cff473004860bfe Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Thu, 26 Nov 2026 03:02:34 +0100 Subject: [PATCH 053/240] startup: translate slot 57 mesh requests with a depth-only pixel stage (#2606) * startup: write nothing for the null export target in gfx2hlsl The null target carries no channel; its only effect is the vm discard emitted before it. Same change as the open #2026, so a rebase onto it drops this commit. Co-Authored-By: Claude Opus 5.5 * startup: translate slot 57 mesh requests with a depth-only pixel stage (Part of #2413) A pixel stage whose only export is the null target was refused with 'slot 57 mesh with a depth-only pixel stage is not covered'. It now translates with the pair: the pixel stage has no SV_Target, keeps the vm discard of an alpha test, and the manifest has an empty targets line. Co-Authored-By: Claude Opus 5.5 * startup: refuse a slot 57 null export mixed with another export (Part of #2413) The slot 57 depth-only profile is a pixel stage whose only export target is null. A null export before or after an mrt0, mrtz or param0 export passed the role check and was published; it is now refused in translate_mesh57 before any source or manifest is written. The general pixel path keeps its mixed forms. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- .github/workflows/windows.yml | 1 + AGENTS.md | 1 + CMakeLists.txt | 3 + docs/experiments.md | 21 ++++++- tests/startup_gfx2hlsl_watch_check.py | 5 +- tests/startup_mesh57_depth_only_check.py | 78 ++++++++++++++++++++++++ tests/startup_mesh57_skeleton_check.py | 3 +- tools/startup/gfx2hlsl.py | 8 ++- 8 files changed, 110 insertions(+), 10 deletions(-) create mode 100644 tests/startup_mesh57_depth_only_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 0a36fcd1a..866609b3f 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -272,6 +272,7 @@ jobs: tests/startup_gfx2hlsl_scalar_m0_check.py \ tests/startup_gfx2hlsl_waitcnt_depctr_check.py \ tests/startup_mesh57_skeleton_check.py \ + tests/startup_mesh57_depth_only_check.py \ tests/startup_mesh57_loop_refusal_check.py \ tests/startup_gfx2hlsl_scalar_shift64_bfe_check.py \ tests/startup_gfx2hlsl_readfirstlane_uniform_check.py \ diff --git a/AGENTS.md b/AGENTS.md index b7eb67ad7..f370ff3e2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -193,6 +193,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_scalar_m0_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_waitcnt_depctr_check.py ./out/pe-env/bin/python -B tests/startup_mesh57_skeleton_check.py +./out/pe-env/bin/python -B tests/startup_mesh57_depth_only_check.py ./out/pe-env/bin/python -B tests/startup_mesh57_loop_refusal_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_readfirstlane_uniform_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_loop_constants_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 71ed38e44..2a3abf887 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3470,6 +3470,9 @@ if(EXISTS "${INTAKE_PYTHON}") # Slot 57 mesh requests (#2413): the one accepted group-memory shape translates; each mutation is refused. add_test(NAME startup_mesh57_skeleton COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_mesh57_skeleton_check.py") + # Slot 57 mesh with a depth-only pixel stage (#2413 T5): the null export keeps its discard, no colour target. + add_test(NAME startup_mesh57_depth_only COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_mesh57_depth_only_check.py") # Slot 57 mesh loop refusal outside the accepted exchanges (#2413 T6); mutant drops the back-edge. add_test(NAME startup_mesh57_loop_refusal COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_mesh57_loop_refusal_check.py") diff --git a/docs/experiments.md b/docs/experiments.md index bc13ee77c..90f788d08 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9659,7 +9659,7 @@ restored before exports. The lowering clamps both counts to the 128 threads of a group and each index to the last vertex. It reads 9-bit indices, ignores the edge flags, and gives a primitive whose null bit (31) is set one vertex three times, so it covers no -pixel. A depth-only pixel program is refused. The source-built fixture draws +pixel. A depth-only pixel program is translated (see below). The source-built fixture draws on WARP and a hardware adapter and matches a CPU rasteriser. The runtime does not load the translated pair, so the dispatch stays unforwarded. @@ -9675,11 +9675,26 @@ The one-pixel negative control uses that same published pair. The translator also accepts the same slot 57 mesh shape with an empty `req_.ps57`. It emits the mesh stage alone, keeping position and -primitive exports, and records `ps none` in `.ms57.txt`. A null-export -depth-only pixel stage is still refused. Run +primitive exports, and records `ps none` in `.ms57.txt`. Run `python -B tests/startup_mesh57_skeleton_check.py` for the source and cache checks, or run the `startup_mesh57_skeleton` CTest checks below for the DXC mode. +A pixel stage whose only export is `exp null off, off, off, off done vm` (the +depth-only form of LLVM `SILateBranchLowering` and Mesa ACO +`create_fs_null_export`) is translated with the pair. The null target writes +no channel; when the stage narrowed EXEC first, as an alpha test does, the `vm` +flag keeps its `discard`. The pixel stage is emitted as `void main(PSIn i)` +with no `SV_Target`, and the manifest has an empty `targets` line instead of +`ps none`, because the stage still decides coverage. Run +`python -B tests/startup_mesh57_depth_only_check.py`: it checks the discard, +the empty `targets` line, a control without the EXEC narrowing (no discard) +and a null export followed by a position export (still refused). A slot 57 +pixel stage that has the null export next to an `mrt0`, `mrtz` or `param0` +export, in either order, is refused before any source or manifest is written; +the general pixel path keeps those mixed forms. Nothing is +drawn. The runtime does not load slot 57 results yet, so these draws are not +submitted. + The pending scan checks the DXContainer header and file length for every required slot 57 bytecode artifact. A `ps none` result needs the mesh artifact only. A missing or truncated required artifact leaves the request pending diff --git a/tests/startup_gfx2hlsl_watch_check.py b/tests/startup_gfx2hlsl_watch_check.py index 99e552a10..946900b02 100644 --- a/tests/startup_gfx2hlsl_watch_check.py +++ b/tests/startup_gfx2hlsl_watch_check.py @@ -107,9 +107,10 @@ def mesh57_fixture(ms, ps, expected, tamper=False): # A pair without a pixel stage is translated when the mesh has the accepted shape; this synthetic mesh does not. mesh57_fixture(mesh, b'', 'slot 57 mesh group-index exchange: instruction 1 of the accepted shape (s_mov_b64) is absent') mesh57_fixture(vertex, pixel, 'slot 57 mesh stage has no verified allocation and primitive export') -# A pixel stage whose only export is the null target (done, vm, no channels) is a depth-only stage and passes the role check. +# A pixel stage whose only export is the null target (done, vm, no channels) is a depth-only stage and passes the role check; +# the pair is translated when the mesh has the accepted shape, which this synthetic mesh does not. null_export = struct.pack('<3I', 0xf8001890, 0, endpgm) -mesh57_fixture(mesh, null_export, 'slot 57 mesh with a depth-only pixel stage is not covered') +mesh57_fixture(mesh, null_export, 'slot 57 mesh group-index exchange: instruction 1 of the accepted shape (s_mov_b64) is absent') # Controls: a position export, or a null export mixed with one, stays refused. mesh57_fixture(mesh, struct.pack('<3I', *position, endpgm), 'slot 57 pixel stage has an incompatible export or termination') mesh57_fixture(mesh, struct.pack('<5I', 0xf8001890, 0, *position, endpgm), 'slot 57 pixel stage has an incompatible export or termination') diff --git a/tests/startup_mesh57_depth_only_check.py b/tests/startup_mesh57_depth_only_check.py new file mode 100644 index 000000000..5fc61785f --- /dev/null +++ b/tests/startup_mesh57_depth_only_check.py @@ -0,0 +1,78 @@ +"""Slot 57 mesh requests with a depth-only pixel stage translate in tools/startup/gfx2hlsl.py (#2413, T5). + +usage: startup_mesh57_depth_only_check.py + +A pixel stage without a colour output ends in `exp null off, off, off, off done vm` (LLVM SILateBranchLowering, +Mesa ACO create_fs_null_export). Before an alpha test it narrows EXEC, so the `vm` export kills the lanes it left. +The mesh stage is the accepted fixture of startup_mesh57_skeleton_check.py. The pixel words are built here: +v_interp_mov_f32 v0, p0, attr0.x; v_cmp_gt_f32 vcc, 0.5, v0; s_andn2_b64 exec, exec, vcc; exp null done vm; +s_endpgm. The pair must translate to a pixel stage with no SV_Target that keeps the discard, and a manifest with +an empty `targets` line. Controls: without the EXEC narrowing there is no discard, a null export followed by +a position export is still refused by the role check, and a null export before or after an mrt0, mrtz or param0 +export is refused with no source or manifest written. +""" +import os +from pathlib import Path +import sys +import tempfile + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import startup_mesh57_skeleton_check as S # noqa: E402 + +INTERP, COMPARE, NARROW = 'c8020002', '7c0800f0', '8afe6a7e' +NULL_EXPORT, ENDPGM = ['f8001890', '00000000'], 'bf810000' +ALPHA_TEST = [INTERP, COMPARE, NARROW] + NULL_EXPORT + [ENDPGM] + + +def translate(pixel): + with tempfile.TemporaryDirectory() as tmp: + key, result = S.request(tmp, S.MESH, pixel) + files = [Path(tmp) / ('%016x.%s' % (key, ext)) for ext in ('ps57.hlsl', 'ms57.txt')] + return (result,) + tuple(f.read_text() if f.exists() else '' for f in files) + + +def main(): + os.environ['X2W_FXC'] = '' # source and manifest only; no compiler needed + S.expect('alpha-test words decode', [x[3] for x in S.G.decode(S.code(ALPHA_TEST))], + ['v_interp_mov_f32_e32 v0, p0, attr0.x', 'v_cmp_gt_f32_e32 vcc_lo, 0.5, v0', 's_andn2_b64 exec, exec, vcc', + 'exp null off, off, off, off done vm', 's_endpgm']) + result, hlsl, manifest = translate(ALPHA_TEST) + S.expect('depth-only pair translates', result, 'ok') + S.expect('pixel stage has no colour output', ('SV_Target' in hlsl, 'void main(PSIn i)' in hlsl), (False, True)) + S.expect('pixel stage keeps the vm discard', 'if (!(exec & 1)) discard;' in hlsl, True) + S.expect('manifest names no target', manifest.splitlines()[-1:], ['targets ']) + S.expect('manifest is not the mesh-only form', 'ps none' in manifest.splitlines(), False) + # Control: the same stage with all lanes alive exports under the entry EXEC, so nothing is discarded. + result, hlsl, _ = translate([INTERP] + NULL_EXPORT + [ENDPGM]) + S.expect('null export alone translates', result, 'ok') + S.expect('no narrowing, no discard', 'discard' in hlsl, False) + # Control: a null export followed by a position export is not a depth-only pixel stage. + position = ['f80008cf', '03020100'] + S.expect('null plus position is refused', translate(NULL_EXPORT + position + [ENDPGM])[0], + 'unsupported: slot 57 pixel stage has an incompatible export or termination') + # Control: the slot 57 profile is the null export alone. A colour, depth or parameter export before or after + # it is refused before any source or manifest is written. + null_first = ['f8000090', '00000000'] # exp null off, off, off, off + for target, before, after in (('mrt0', 'f800000f', 'f800180f'), ('mrtz', 'f8000081', 'f8001881'), + ('param0', 'f800020f', 'f8001a0f')): + for label, words, order in ( + ('%s + null' % target, [INTERP, before, '00000000'] + NULL_EXPORT + [ENDPGM], [target, 'null']), + ('null + %s' % target, [INTERP] + null_first + [after, '00000000', ENDPGM], ['null', target])): + decoded = [x[3] for x in S.G.decode(S.code(words))] + S.expect(label + ' decodes', ([a.split()[1] for a in decoded[1:3]], decoded[2].endswith('done vm')), + (order, True)) + with tempfile.TemporaryDirectory() as tmp: + key, result = S.request(tmp, S.MESH, words) + S.expect(label + ' is refused', result, + 'unsupported: slot 57 pixel stage mixes the null export with another export') + S.expect(label + ' leaves only the failure', sorted(p.name for p in Path(tmp).iterdir() + if not p.name.startswith('req_')), + ['%016x.fail' % key]) + if S.FAILED: + return 1 + print('ok') + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/startup_mesh57_skeleton_check.py b/tests/startup_mesh57_skeleton_check.py index 4ddf5a74e..b3814fc88 100644 --- a/tests/startup_mesh57_skeleton_check.py +++ b/tests/startup_mesh57_skeleton_check.py @@ -510,8 +510,7 @@ def controls(): os.environ['X2W_FXC'] = '' # exp null off, off, off, off done vm; s_endpgm: a pixel stage without a colour output. with tempfile.TemporaryDirectory() as tmp: - expect('a depth-only pixel stage', request(tmp, MESH, 'f8001890 00000000 bf810000'.split())[1], - 'unsupported: slot 57 mesh with a depth-only pixel stage is not covered') + expect('a depth-only pixel stage', request(tmp, MESH, 'f8001890 00000000 bf810000'.split())[1], 'ok') # The request path refuses a missing s_endpgm earlier; the walk takes the last instruction as the terminator # unread, so the pipeline refuses it too (s_nop in its place). try: diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 1c20f5c68..c00b5fd93 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -8301,11 +8301,13 @@ def translate_mesh57(out_dir, key): if ps: pixel = decode(strip_header(ps)) # A pixel shader with no colour output ends in a null-target export (LLVM SILateBranchLowering, Mesa ACO create_fs_null_export): depth-only. - null_only = {a.split()[1] for _, _, op, a in pixel if op == 'exp'} == {'null'} + targets = {a.split()[1] for _, _, op, a in pixel if op == 'exp'} + null_only = targets == {'null'} if not pixel or pixel[-1][2] != 's_endpgm' or classify_decoded(pixel) != 'ps' and not null_only: raise Unsupported('slot 57 pixel stage has an incompatible export or termination') - if null_only: - raise Unsupported('slot 57 mesh with a depth-only pixel stage is not covered') + # The slot 57 depth-only profile is the null export alone; the general pixel path keeps its mixed forms. + if 'null' in targets and not null_only: + raise Unsupported('slot 57 pixel stage mixes the null export with another export') pipe = MeshPipeline(ms, ps or None, root) sources = [('ms', 'ms_6_5', pipe.hlsl_ms())] if ps: From 572723f9acac83be9bcec9c21fc63a0222713f72 Mon Sep 17 00:00:00 2001 From: SimSalabimse <83839581+SimSalabimse@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:02:53 +0100 Subject: [PATCH 054/240] shader: lower s_flbit_i32_b32 in gfx2hlsl (Part of #1723) (#2641) * shader: lower s_flbit_i32_b32 in gfx2hlsl (#1723) Port the pixel_aot leading-zero count SOP1 (31 - firstbithigh, -1 if zero). SCC is unchanged. Lane masks and descriptor words are refused. CPU fixture with a negative control. Co-authored-by: SimSalabimse * docs: note s_flbit_i32_b32 startup lowering (#1723) Co-authored-by: SimSalabimse * test: add D3D12 WARP dispatch readback for s_flbit_i32_b32 Mirror the s_ff1 / s_abs UAV dump pattern. Cover zero (0xffffffff), bit 0, bit 31 and a mid-word bit so firstbithigh is exercised on the adapter. Co-authored-by: SimSalabimse * docs: note s_flbit_i32_b32 WARP dispatch ctest Document the UAV-readback filter next to the CPU-only command. Co-authored-by: SimSalabimse --------- Co-authored-by: Cursor Agent Co-authored-by: SimSalabimse --- .github/workflows/windows.yml | 1 + AGENTS.md | 1 + CMakeLists.txt | 11 ++ docs/experiments.md | 12 ++ tests/startup_gfx2hlsl_s_flbit_check.py | 229 ++++++++++++++++++++++++ tools/startup/gfx2hlsl.py | 37 ++++ 6 files changed, 291 insertions(+) create mode 100644 tests/startup_gfx2hlsl_s_flbit_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 866609b3f..f39c8903a 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -300,6 +300,7 @@ jobs: tests/startup_gfx2hlsl_swap_check.py \ tests/startup_gfx2hlsl_s_abs_check.py \ tests/startup_gfx2hlsl_s_bitset_check.py \ + tests/startup_gfx2hlsl_s_flbit_check.py \ tests/startup_gfx2hlsl_fma_mix_check.py \ tests/startup_gfx2hlsl_shift64_check.py \ tests/startup_gfx2hlsl_mul_mad_i24_check.py \ diff --git a/AGENTS.md b/AGENTS.md index f370ff3e2..11f41b9b5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -175,6 +175,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_swap_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_s_abs_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_s_bitset_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_s_flbit_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_fma_mix_check.py ./out/pe-env/bin/python -B tests/startup_image_2d_array_check.py ./out/pe-env/bin/python -B tests/startup_image_sample_a16_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 2a3abf887..8d24b1632 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3344,6 +3344,17 @@ if(EXISTS "${INTAKE_PYTHON}") # gfx2hlsl lowers s_bitset0_b32 and s_bitset1_b32 (SOP1, #2023 Item J): CPU evaluation and refusals. add_test(NAME startup_gfx2hlsl_s_bitset COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_bitset_check.py") + # gfx2hlsl lowers s_flbit_i32_b32 (SOP1, #1723): CPU evaluation, then a D3D12 UAV + # readback on WARP/hardware (same dispatch pattern as s_ff1 / s_abs / pack_absdiff). + + add_test(NAME startup_gfx2hlsl_s_flbit COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_flbit_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_s_flbit_dispatch_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_flbit_check.py" dispatch "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_gfx2hlsl_s_flbit_dispatch_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl lowers v_cube{id,sc,tc,ma}_f32: device-free translation controls. add_test(NAME startup_gfx2hlsl_cube_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_cube_check.py") diff --git a/docs/experiments.md b/docs/experiments.md index 90f788d08..7e69d617f 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -8116,6 +8116,18 @@ destination with a known bit index folds. Run (or `python3 -B tests/startup_gfx2hlsl_s_bitset_check.py`). The fixture is CPU-only; Windows WARP/hardware draws are left for an independent retest. +**Scalar find-first-bit-high.** Startup translation lowers `s_flbit_i32_b32` to +`S0 == 0 ? 0xffffffff : 31 - firstbithigh(S0)`, matching `pixel_aot` / +`dpp_ffbh_u32`. SCC is unchanged. Lane masks and descriptor-bearing sources +are refused. Run +`ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_s_flbit$' -V` +(or `python3 -B tests/startup_gfx2hlsl_s_flbit_check.py`). The `_dispatch_warp` +/ `_dispatch_hardware` variants compile the translated expression into a +compute shader and compare UAV readback for 0, 1, 0x80000000 and 0x00010000 +against the same reference (including `flbit(0) == 0xffffffff`): +`ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_s_flbit_dispatch_warp$' -V`. +[Refs #1723](https://github.com/R0Y00/Xbox2Windows/issues/1723). + **Scalar immediate comparisons.** The startup translator sign-extends the 16-bit field of `s_movk_i32` and `s_cmpk_*_i32`, and zero-extends the field of `s_cmpk_*_u32`. The source-built check covers all six relations against diff --git a/tests/startup_gfx2hlsl_s_flbit_check.py b/tests/startup_gfx2hlsl_s_flbit_check.py new file mode 100644 index 000000000..ee0b67850 --- /dev/null +++ b/tests/startup_gfx2hlsl_s_flbit_check.py @@ -0,0 +1,229 @@ +"""s_flbit_i32_b32 in tools/startup/gfx2hlsl.py (#1723). + +usage: startup_gfx2hlsl_s_flbit_check.py + startup_gfx2hlsl_s_flbit_check.py dispatch + +RDNA 2 ISA SOP1: S_FLBIT_I32_B32 returns the number of leading zero bits +(0xffffffff if the word is zero). SCC is unchanged. Matches pixel_aot / +dpp_ffbh_u32. Lane masks and descriptor sources are refused. The reference is +plain Python; the translated text is evaluated on the CPU. + +With `dispatch`, the lowering runs as a compute shader on the adapter (D3D12 UAV +readback via offscreen_check, same pattern as startup_gfx2hlsl_s_ff1_check / +startup_gfx2hlsl_s_abs_check). Cases cover zero (0xffffffff), bit 0, bit 31 and +a mid-word bit so firstbithigh is exercised on the device. +""" +import re +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import disasm_rdna2 as D # noqa: E402 +import gfx2hlsl as G # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import Expr # noqa: E402 + +MASK = 0xffffffff +SOP1 = {name: op for op, (name, _) in D.SOP1_OPS.items()} +WORDS = (0x00000000, 0x00000001, 0x80000000, 0xffffffff, 0x00010020, 0x55555555, 0x12345678) +DRAW = (0x00000000, 0x00000001, 0x80000000, 0x00010000) +SCC_UNSET = 2 +VCC_LO, EXEC_LO = 106, 126 + +failures = [] + + +def check(label, ok, detail=''): + print('%s: %s' % (label, 'ok' if ok else 'MISMATCH'), flush=True) + if not ok: + failures.append(label) + if detail: + print(' ' + detail) + + +def sop1(name, sdst, ssrc): + return struct.pack(' firstbithigh=4 -> 31-4=27 + check('s_flbit_i32_b32 folds a constant source', + lines == ['s3 = 0x0000001bu;'] and sym.get(3) == ('const', 0x1b), + str((lines, sym.get(3)))) + + lines, sym = translate(sop1('s_flbit_i32_b32', 3, 1), sym={1: ('const', 0)}) + check('s_flbit_i32_b32 of zero is -1', + lines == ['s3 = 0xffffffffu;'] and sym.get(3) == ('const', MASK), + str((lines, sym.get(3)))) + + refused = [translate(sop1('s_flbit_i32_b32', d, s))[0][0] for d, s in ( + (3, VCC_LO), (3, EXEC_LO), (VCC_LO, 1), (EXEC_LO, 1))] + check('s_flbit_i32_b32 refuses lane-mask destinations/sources', + all(r.startswith('refused: ') for r in refused), str(refused)) + + stage = Probe() + stage.masks.add(1) + try: + stage.one('s_flbit_i32_b32', 's_flbit_i32_b32 s3, s1') + check('s_flbit_i32_b32 refuses a tracked lane-mask source', False, stage.lines) + except G.Unsupported as error: + check('s_flbit_i32_b32 refuses a tracked lane-mask source', 'lane mask' in str(error), str(error)) + + stage = Probe() + stage.sym[1] = ('desc', ('root', 0), 0, 0) + try: + stage.one('s_flbit_i32_b32', 's_flbit_i32_b32 s3, s1') + check('s_flbit_i32_b32 refuses a descriptor source', False, stage.lines) + except G.Unsupported as error: + check('s_flbit_i32_b32 refuses a descriptor source', 'desc' in str(error), str(error)) + + stage = Probe() + stage.one('s_flbit_i32_b32', 's_flbit_i32_b32 s3, s1') + mutated = [re.sub(r'31u - firstbithigh\(s1\)', 'firstbithigh(s1)', stage.lines[0])] + assert mutated != stage.lines, stage.lines + out_ok = run(stage.lines, {'s1': 0x10, 'scc': 0}) + out_bad = run(mutated, {'s1': 0x10, 'scc': 0}) + check('mutation that drops the 31-offset diverges', + out_ok['s3'] == 27 and out_bad['s3'] == 4, + str((out_ok['s3'], out_bad['s3']))) + + if failures: + print('FAILED: %s' % ', '.join(failures)) + sys.exit(1) + print('all ok') + + +def dispatch_flbit(dxc, runner, adapter, cases, directory): + """Translate s_flbit_i32_b32 once; feed each case through a UAV and read the result back.""" + lines, _ = translate(sop1('s_flbit_i32_b32', 3, 1)) + assert lines and not lines[0].startswith('refused'), lines + fill = tuple(((i + 1) * 0x9e3779b1 & MASK) | 1 for i in range(len(cases))) + hlsl = ['RWByteAddressBuffer data : register(u0);', '[numthreads(1, 1, 1)]', 'void main() {'] + for i, word in enumerate(cases): + dst_byte = 4 * (len(fill) + i) + hlsl.extend(( + ' {', + ' uint s1 = data.Load(%d) ^ %s;' % (4 * i, '%#010xu' % (fill[i] ^ word)), + ' uint s3;', + ' bool scc = true;', + )) + hlsl.extend(' ' + line for line in lines) + hlsl.append(' data.Store(%d, s3);' % dst_byte) + hlsl.append(' }') + hlsl.append('}') + + src, cso, output = (directory / ('s_flbit_i32_b32' + suffix) for suffix in ('.hlsl', '.cso', '.bin')) + src.write_text('\n'.join(hlsl) + '\n', encoding='ascii') + compile_result = subprocess.run([dxc, '-T', 'cs_6_0', '-E', 'main', '-Fo', str(cso), str(src)], + stderr=subprocess.PIPE, text=True) + if compile_result.returncode or compile_result.stderr: + raise AssertionError(compile_result.stderr or 'DXC exited with %d' % compile_result.returncode) + word_count = len(fill) + len(cases) + dump_words = (word_count + 3) // 4 * 4 + run_result = subprocess.run( + [runner, adapter, '--raw-uav-dump', str(cso), '1', str(4 * dump_words), str(output)], + capture_output=True, text=True) + print(run_result.stdout, end='') + if run_result.returncode == 77: + sys.exit(77) + if run_result.returncode or run_result.stderr: + raise AssertionError(run_result.stderr or 'raw UAV dump exited with %d' % run_result.returncode) + actual = struct.unpack('<%dI' % dump_words, output.read_bytes()) + assert actual[:len(fill)] == fill, 'operand region changed: %s' % (actual[:len(fill)],) + return actual[len(fill):word_count] + + +def check_dispatch(dxc, runner, adapter): + controls() + runner = str(Path(runner).resolve()) + out = HERE.parent / 'out' + out.mkdir(exist_ok=True) + with tempfile.TemporaryDirectory(dir=out) as tmp: + got = dispatch_flbit(dxc, runner, adapter, DRAW, Path(tmp)) + for i, word in enumerate(DRAW): + want = ref_flbit(word) + check('dispatch s_flbit_i32_b32 %#010x' % word, got[i] == want, + 'got %#x want %#x' % (got[i], want)) + check('dispatch proves flbit(0) is 0xffffffff', got[0] == MASK, hex(got[0])) + check('dispatch flbit(0x80000000) is 0', got[2] == 0, hex(got[2])) + if failures: + print('FAILED: %s' % ', '.join(failures)) + sys.exit(1) + print('dispatch ok') + + +if __name__ == '__main__': + if len(sys.argv) == 1: + controls() + elif len(sys.argv) == 5 and sys.argv[1] == 'dispatch': + check_dispatch(*sys.argv[2:]) + else: + sys.exit(__doc__) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index c00b5fd93..1bc2770ea 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -5801,6 +5801,43 @@ def op_s_abs_i32(self, ops, mods): self.set_s(dst[1], expr, scc='$ != 0') return None + def op_s_flbit_i32_b32(self, ops, mods): + """Find first bit high (leading-zero count); SCC unchanged (#1723). + + RDNA 2 ISA SOP1 / pixel_aot dpp_ffbh_u32: D = S0 == 0 ? 0xffffffff : 31 - firstbithigh(S0). + Lane masks and descriptor-bearing SGPRs are refused. + """ + if mods or len(ops) != 2: + raise Unsupported('s_flbit_i32_b32 with %d operands, expected 2 unmodified' % len(ops)) + dst = reg_range(ops[0]) + if not dst or dst[0] != 's' or dst[1] != dst[2] or dst[1] > 105: + raise Unsupported('s_flbit_i32_b32 destination %s' % ops[0]) + if self.is_lane_mask(ops[0]) or dst[1] in self.masks: + raise Unsupported('s_flbit_i32_b32 on a lane mask') + imm = re.fullmatch(r'-?(0x[0-9a-fA-F]+|\d+)', ops[1]) + if imm: + value = int(ops[1], 0) & 0xffffffff + folded = 0xffffffff if value == 0 else 31 - (value.bit_length() - 1) + self.set_s(dst[1], '0x%08xu' % folded, ('const', folded)) + return None + src = reg_range(ops[1]) + if not src or src[0] != 's' or src[1] != src[2] or src[1] > 105: + raise Unsupported('s_flbit_i32_b32 source %s' % ops[1]) + if self.is_lane_mask(ops[1]) or src[1] in self.masks: + raise Unsupported('s_flbit_i32_b32 on a lane mask') + sym = self.sym.get(src[1]) + if sym and sym[0] not in ('const', 'ud', 'fixed_buffer_word'): + raise Unsupported('s_flbit_i32_b32 on %s data' % sym[0]) + if sym and sym[0] == 'const': + value = sym[1] & 0xffffffff + folded = 0xffffffff if value == 0 else 31 - (value.bit_length() - 1) + self.set_s(dst[1], '0x%08xu' % folded, ('const', folded)) + return None + src_u = self.u(ops[1]) + self.set_s(dst[1], '(%s == 0u ? 0xffffffffu : 31u - firstbithigh(%s))' % (src_u, src_u)) + return None + + # ---- slot 57 mesh stage: instructions mesh_skeleton() puts in place of the group-memory exchanges ---- def op_x2w_mesh_lane0(self, ops, mods): # `s_mov_b64 exec, 1` leaves lane 0 of each wave running. The saved copy of that mask is not modelled. From c1e4c709288fb9875551394085f886bd8a73d3d3 Mon Sep 17 00:00:00 2001 From: Roan System Date: Thu, 26 Nov 2026 03:04:57 +0100 Subject: [PATCH 055/240] startup: take pixel input masks from the exact pipeline's stream description (#1629) (#2592) * startup: take pixel input masks from the exact pipeline's stream description (#1629) Pipeline lays out the entry VGPRs by SPI_PS_INPUT_ADDR and loads them by SPI_PS_INPUT_ENA, so distinct masks are accepted; an enabled input that is not allocated is refused as contradictory. request_ps_inputs() reads the separately captured description req_.psin and refuses one that names another pipeline (key in the line or recomputed pipeline_key), a missing enable or address mask, or a malformed line. translate_request and request_refusals pass the masks on; no description keeps today's model. tests/startup_packed_position_provenance_check.py: a source-built target (position in v4 from enable 0x8002 / address 0x8003) and a decoy (v2) in one cache directory; pure controls, then the #1634 gradient draw on WARP and hardware with a wrong-register control. The #1634 check is unchanged. * startup: make the pixel input masks part of the request identity (#1629) Two pipelines with identical stage bytes, root signature and input layout but different SPI_PS_INPUT_ENA/ADDR masks hashed to the same pipeline_key(), so they shared every request file name and the second description replaced the first in the cache. - pipeline_key() takes the description's masks (ps_inputs) and hashes b'psin1' + ENA + ADDR (little-endian u32) after the input layout, as the layout itself is hashed. Without a description the key is unchanged, so existing caches keep their keys. - request_ps_inputs() recomputes the key with the masks. A description rewritten with another mask pair under an existing key is refused by name (pixel input description names another pipeline), and the result already published for that key is withdrawn instead of being served. - pending_keys() checks a published result again when its description is newer than its manifest; translate_request() marks the manifest as checked when the description still matches, so the check runs once. - The base and RTV source key check in load_request (#2595) and shader_cache_rekey.py hash the masks too; with a description, a base key mismatch is reported as the description naming another pipeline. The re-keyer rewrites the description line under the new key. The provenance check gains same-cache controls: three pipelines with the target's exact bytes and three mask pairs get three keys and each takes its own masks; a different pair after a result exists is translated as its own request and leaves that result untouched; an in-place rewrite is refused and withdrawn. The draw mode adds two same-byte pipelines to the target's cache (0x8003/0x8003 draws the gradient, 0x8002/0x8002 fails at (1,0) as expected) and checks the compiled-result path with FXC. * startup: watch the stream description each translation reads (#1629) An RTV variant is translated from its source pipeline's blobs and stream description, but pending_keys compared req_.psin with the variant's manifest, and a failure was retried only when .a or .rtv changed. A wrong mask pair written into a base description therefore withdrew the base result and left the variant's result published, and a corrected description did not requeue the refused request. request_source() now names the request's source key and the one description its translation depends on (req_.psin for a base request, req_.psin for a variant). load_request, request_ps_inputs and pending_keys all use it: a description newer than the manifest rechecks the result, and a description newer than the .fail retries the request, for base requests and variants alike. Requests without a description keep the legacy key and behaviour. The new control publishes a base and an `rtv1 28` variant, writes the wrong pair into the base description (both are refused by name and both manifests withdrawn), then restores the valid line (both are republished without touching .a or .rtv). * startup: withdraw results whose stream description was removed (#1629) With a published base and an rtv1 variant of it, removing only req_.psin left both manifests in place: pending_keys saw no description and nothing newer, so the watcher kept serving results that a forced translation refuses (shader request source key mismatch and RTV variant source key mismatch). - translate_request writes .psdep, the description line the result is translated with, before the manifest is published, for a base request and an RTV variant alike. A legacy request that never had a description gets no record. - pending_keys queues a published result again when it has a record and the description request_source() names is gone. A request without a record is not read again, so legacy caches keep today's cost. - translate_request refuses such a request by name, "pixel input description missing for a request translated with one", and withdraws its manifest. The refusal is not retried until the description is written again, newer than the .fail. The provenance check keeps the wrong-pair and restore controls and adds: both results record their description line; removing only the base description queues the base and its variant, refuses both by name and withdraws both manifests; nothing is retried while it stays missing; the restored description republishes both; a legacy request publishes without a record and stays done. * startup: recheck a result whose description is gone despite an old .fail (#1629) On the manifest-only path a successful translation leaves an earlier .fail in place. A published result whose recorded stream description was later removed then fell through to the failure check, which compared that old .fail only with the request file (no description time is left) and skipped the result, so its manifest stayed published. pending_keys now queues such a result while its manifest exists; the translation refuses it by name and withdraws the manifest, and the new .fail keeps it from being retried until the description returns. The provenance check no longer deletes the failures of the wrong-pair cycle before removing the description, so it covers this order. --- .github/workflows/windows.yml | 1 + CMakeLists.txt | 8 + ...tartup_packed_position_provenance_check.py | 426 ++++++++++++++++++ tools/startup/gfx2hlsl.py | 197 ++++++-- tools/startup/shader_cache_rekey.py | 18 +- 5 files changed, 615 insertions(+), 35 deletions(-) create mode 100644 tests/startup_packed_position_provenance_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index f39c8903a..db89553ca 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -287,6 +287,7 @@ jobs: tests/startup_run_sh_check.py \ tests/startup_flat_param_check.py \ tests/startup_ps_input_scan_check.py \ + tests/startup_packed_position_provenance_check.py \ tests/startup_build_rev_check.py \ tests/startup_gfx2hlsl_bit_alu_check.py \ tests/startup_gfx2hlsl_interp_f16_check.py tests/startup_gfx2hlsl_interp_p2_hi_check.py \ diff --git a/CMakeLists.txt b/CMakeLists.txt index 8d24b1632..6acee0297 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3755,11 +3755,19 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/startup_ps_input_scan_check.py") add_test(NAME startup_ps_input_scan_cli_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_ps_input_scan_cli_check.py") + # The pixel input masks come from the captured stream description of the exact pipeline (#1629): a decoy + # description, stale or missing masks and contradictory enable/address masks; then the #1634 gradient draw. + add_test(NAME startup_packed_screen_position_provenance COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_packed_position_provenance_check.py") foreach(adapter IN ITEMS warp hardware) add_test(NAME startup_packed_screen_position_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_packed_position_check.py" "${DXC_EXECUTABLE}" "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_packed_screen_position_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + add_test(NAME startup_packed_screen_position_provenance_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_packed_position_provenance_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_packed_screen_position_provenance_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) add_test(NAME startup_flat_param_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_flat_param_check.py" draw "${DXC_EXECUTABLE}" "$" ${adapter} $<$:${STARTUP_FXC}>) diff --git a/tests/startup_packed_position_provenance_check.py b/tests/startup_packed_position_provenance_check.py new file mode 100644 index 000000000..5182ac18c --- /dev/null +++ b/tests/startup_packed_position_provenance_check.py @@ -0,0 +1,426 @@ +"""Pixel input masks from the captured stream description of the exact pipeline (#1629). + + (no arguments) association controls, pure Python + draw [fxc] + translate the requests below through translate_request, compile the + pixel stage (DXC ps_6_0, and FXC ps_5_1 when given) and draw it with the + #1634 gradient: every pixel must read back its own packed x | (y << 16); + with fxc, also the compiled-result path of a rewritten description + +Two source-built requests share one cache directory. Each has a stream description, req_.psin: + target exports v4; enable 0x8002 (PERSP_CENTER, POS_FIXED_PT) and address 0x8003 (PERSP_SAMPLE allocated + but not enabled). The address mask lays out v0..v1 PERSP_SAMPLE, v2..v3 PERSP_CENTER, v4 the packed + position. Laying out by the enable mask would put the position in v2. + decoy exports v2; enable = address = 0x8002, so its position is v2. +Both draw correctly only when each translation takes the masks of its own description, so no fixed register +and no mask taken from the other description passes. The controls also refuse, by name, a description that +names another pipeline, a stale description whose stage blobs changed, a missing enable or address mask, +contradictory masks (an enabled input not allocated) and a malformed line. + +The masks are part of the request identity (pipeline_key with ps_inputs). In the same cache, pipelines with +the target's exact stage bytes, root signature and input layout but another mask pair are requests of their +own: 0x8003/0x8003 also places the position in v4 and draws the gradient; 0x8002/0x8002 places it in v2, so +the v4 this code reads is not the position and the draw fails at (1,0) as expected. They arrive after the +target's result exists and are translated as new requests, leaving that result untouched. A description +rewritten in place with another pair after its result was published is checked again, refused by name and +its old result withdrawn. The watcher follows the description each translation reads (an RTV variant reads its +source pipeline's): a wrong pair in a base description withdraws the base and its variant, and the corrected +description, newer than their failures, publishes both again without touching the request files. A result +translated with a description records it (.psdep): removing only the base description withdraws the base +and its variant and refuses both by name, while a legacy request that never had a description has no record +and is not checked again. +""" +import os +import re +import struct +import subprocess +import sys +import tempfile +from contextlib import contextmanager +from pathlib import Path + +from startup_image_3d_check import FULLSCREEN_VS, VS_WORDS, G, compile_hlsl, root_blob + +TARGET = (0x8002, 0x8003) # (enable, address): the packed position in v4 +DECOY = (0x8002, 0x8002) # the packed position in v2 +SAME_V4 = (0x8003, 0x8003) # another valid pair with the packed position in v4 (PERSP_SAMPLE also enabled) + + +def ps_words(reg): + # exp mrt0 vN, vN, vN, vN done vm; s_endpgm (the #1634 fixture's pixel stage) + return struct.pack('.a/.b/.root for VS_WORDS and `ps` under pipeline_key() with `masks`, and the stream + description: `line` when given, else the line naming that key and `masks` (none without masks).""" + key = G.pipeline_key(VS_WORDS, ps, root_blob(), ps_inputs=masks) + name = cache / ('req_%016x' % key) + for ext, blob in (('.b', ps), ('.root', root_blob()), ('.a', VS_WORDS)): + name.with_suffix(ext).write_bytes(blob) + description = line if line is not None else describe(key, masks) if masks else None + if description is not None: + name.with_suffix('.psin').write_bytes(description.encode('ascii')) + return key + + +def describe(key, masks): + return 'psin1 %016x ena=0x%04x addr=0x%04x\n' % (key, *masks) + + +@contextmanager +def fxc_setting(fxc=''): + """X2W_FXC for the translator: by default the manifest-only path (''), where a published manifest is a + finished result without bytecode; with an fxc path, the compile path.""" + previous = os.environ.get('X2W_FXC') + os.environ['X2W_FXC'] = fxc + try: + yield + finally: + if previous is None: + del os.environ['X2W_FXC'] + else: + os.environ['X2W_FXC'] = previous + + +def pending(cache, fxc=''): + """The keys a later --watch pass would translate (failures already written are skipped).""" + with fxc_setting(fxc): + return G.pending_keys(str(cache), True) + + +def watch_pass(cache): + """One translate_pending pass as --watch runs it, on the manifest-only path.""" + with fxc_setting(): + G.translate_pending(str(cache), skip_failed=True, jobs=1) + + +def translated_ps(cache, key, through_pending=False): + """translate_request with the manifest-only path: the pixel HLSL, or the refusal. With through_pending, a + translate_pending pass (as --pending and --watch run it) translates whatever it finds pending instead.""" + with fxc_setting(): + if through_pending: + G.translate_pending(str(cache), skip_failed=True, jobs=1) + fail = cache / ('%016x.fail' % key) + result = 'ok' if (cache / ('%016x.txt' % key)).is_file() else ( + 'unsupported: ' + fail.read_text().strip() if fail.is_file() else 'not translated') + else: + result = G.translate_request(str(cache), key) + if result != 'ok': + return None, result + return (cache / ('%016x.ps.hlsl' % key)).read_text(), result + + +def packed_line(text): + found = re.findall(r'\bv(\d+) = \(uint\(i\.pos\.x\) & 0xffffu\)', text) + return [int(n) for n in found] + + +def build_pair(cache, target=TARGET, decoy=DECOY): + return put_request(cache, ps_words(4), target), put_request(cache, ps_words(2), decoy) + + +def controls(): + failures = [] + + def check(label, ok): + print(('ok ' if ok else 'FAIL ') + label) + if not ok: + failures.append(label) + + def refused(label, cache, key, reason): + text, result = translated_ps(cache, key) + rows = G.request_refusals(str(cache), key) + check(label, text is None and reason in result and any(reason in r for r, _ in rows)) + + # The translator lays out by the address mask and loads by the enable mask. + pipe = G.Pipeline(VS_WORDS, ps_words(4), root_blob(), ps_hw_inputs=TARGET) + check('distinct masks: position after the allocated PERSP_SAMPLE and PERSP_CENTER pairs (v4)', + pipe.packed_position_vgpr == 4 and pipe.persp_center_vgpr == 2) + pipe = G.Pipeline(VS_WORDS, ps_words(4), root_blob(), ps_hw_inputs=(0x0002, 0x8002)) + check('position allocated but not enabled is not modelled', pipe.packed_position_vgpr is None) + for masks in ((0x8003, 0x8002), (0x8100, 0x8000)): + try: + G.Pipeline(VS_WORDS, ps_words(4), root_blob(), ps_hw_inputs=masks) + except G.Unsupported as err: + check('contradictory masks %04x/%04x refused by name' % masks, + 'contradictory pixel input enable/address masks' in str(err)) + else: + check('contradictory masks %04x/%04x refused by name' % masks, False) + + with tempfile.TemporaryDirectory() as tmp: + cache = Path(tmp) + t, d = build_pair(cache) + text, _ = translated_ps(cache, t) + check('target takes its own description: packed position in v4', text is not None and packed_line(text) == [4]) + text, _ = translated_ps(cache, d) + check('decoy takes its own description: packed position in v2', text is not None and packed_line(text) == [2]) + check('refusal report sees no refusal for either request', + G.request_refusals(str(cache), t) == [] and G.request_refusals(str(cache), d) == []) + # An RTV variant reads its source pipeline's description. + request = 'rtv1 %d 28' % t + variant = G.fnv(request.encode('ascii')) + (cache / ('req_%016x.rtv' % variant)).write_text(request, encoding='ascii') + text, _ = translated_ps(cache, variant) + check('RTV variant takes its source pipeline description: v4', text is not None and packed_line(text) == [4]) + + with tempfile.TemporaryDirectory() as tmp: + cache = Path(tmp) + t = put_request(cache, ps_words(4)) + text, _ = translated_ps(cache, t) + check('no captured description: no hardware inputs, position not modelled (today)', + text is not None and packed_line(text) == []) + + with tempfile.TemporaryDirectory() as tmp: + cache = Path(tmp) + t, d = build_pair(cache) + # The decoy's description copied over the target's. + (cache / ('req_%016x.psin' % t)).write_bytes((cache / ('req_%016x.psin' % d)).read_bytes()) + refused('decoy description under the target name refused', cache, t, + 'pixel input description names another pipeline') + # A stale description: the line names the key, but the stored pixel stage changed after capture. + (cache / ('req_%016x.psin' % t)).write_bytes(describe(t, TARGET).encode('ascii')) + (cache / ('req_%016x.b' % t)).write_bytes(ps_words(2)) + refused('stale description (stage blob changed) refused', cache, t, + 'pixel input description names another pipeline') + + for label, line, reason in ( + ('missing address mask', 'psin1 {k} ena=0x8002\n', 'pixel input address mask missing from the stream description'), + ('missing enable mask', 'psin1 {k} addr=0x8003\n', 'pixel input enable mask missing from the stream description'), + ('no masks', 'psin1 {k}\n', 'pixel input enable mask missing from the stream description'), + ('contradictory masks', 'psin1 {k} ena=0x8003 addr=0x8002\n', 'contradictory pixel input enable/address masks'), + ('duplicate mask', 'psin1 {k} ena=0x8002 ena=0x8002\n', 'invalid pixel input description'), + ('malformed line', 'psin1 {k} ena=8002 addr=8003\n', 'invalid pixel input description'), + ('unknown version', 'psin2 {k} ena=0x8002 addr=0x8003\n', 'invalid pixel input description'), + ): + with tempfile.TemporaryDirectory() as tmp: + cache = Path(tmp) + masks = tuple(int(m, 16) for m in re.findall(r'(?:ena|addr)=(0x[0-9a-f]+)', line)) + masks = masks if len(masks) == 2 else None + t = G.pipeline_key(VS_WORDS, ps_words(4), root_blob(), ps_inputs=masks) + put_request(cache, ps_words(4), masks, line=line.format(k='%016x' % t)) + refused(label + ' refused by name', cache, t, reason) + + # One cache, pipelines with identical stage bytes, root signature and input layout but different masks. + with tempfile.TemporaryDirectory() as tmp: + cache = Path(tmp) + bare = G.pipeline_key(VS_WORDS, ps_words(4), root_blob()) + check('without a description the key is unchanged', + bare == G.fnv(root_blob(), G.fnv(ps_words(4), G.fnv(VS_WORDS, G.fnv(b'x2w-startup-shader-17'))))) + keys = [put_request(cache, ps_words(4), masks) for masks in (TARGET, SAME_V4, DECOY)] + check('same stages, root and layout with three mask pairs: three request identities', + len(set(keys)) == 3 and bare not in keys + and all(len(list(cache.glob('req_%016x.*' % key))) == 4 for key in keys)) + texts = [translated_ps(cache, key)[0] for key in keys] + # Under the third pair the position is v2, so the v4 this code reads is not the position. + check('same cache: each pipeline takes its own masks (position v4, v4, not v4), each result under its own key', + None not in texts and [packed_line(text) for text in texts] == [[4], [4], []] + and all((cache / ('%016x.txt' % key)).is_file() for key in keys)) + + # A different mask pair for the same stage bytes after a result exists. + with tempfile.TemporaryDirectory() as tmp: + cache = Path(tmp) + t = put_request(cache, ps_words(4), TARGET) + translated_ps(cache, t, through_pending=True) + published = {ext: (cache / ('%016x%s' % (t, ext))).read_bytes() for ext in ('.txt', '.ps.hlsl')} + w = put_request(cache, ps_words(4), DECOY) + check('another mask pair after the result exists is a pending request of its own', pending(cache) == [w]) + text, _ = translated_ps(cache, w, through_pending=True) + check('it is translated with its own masks (position not v4), the existing result untouched', + text is not None and packed_line(text) == [] + and all((cache / ('%016x%s' % (t, ext))).read_bytes() == data for ext, data in published.items())) + # The target's own description rewritten in place with the other pair, its line still naming the target. + manifest = cache / ('%016x.txt' % t) + stamp = manifest.stat().st_mtime - 100 + os.utime(manifest, (stamp, stamp)) + (cache / ('req_%016x.psin' % t)).write_bytes(describe(t, DECOY).encode('ascii')) + check('a description rewritten after the result is published is checked again', pending(cache) == [t]) + text, result = translated_ps(cache, t, through_pending=True) + check('the rewritten mask pair is refused by name and the old result withdrawn, not reused', + text is None and 'pixel input description names another pipeline' in result and not manifest.is_file()) + check('the refusal is not retried while the request stays the same', pending(cache) == []) + # A description rewritten with the same masks is checked once, then the result counts as done again. + manifest = cache / ('%016x.txt' % w) + stamp = manifest.stat().st_mtime - 100 + os.utime(manifest, (stamp, stamp)) + (cache / ('req_%016x.psin' % w)).write_bytes(describe(w, DECOY).encode('ascii')) + first = pending(cache) + text, _ = translated_ps(cache, w, through_pending=True) + check('a description rewritten unchanged is checked once, then done', + first == [w] and text is not None and packed_line(text) == [] and pending(cache) == []) + + # The watcher follows the description each translation reads: an RTV variant depends on its source's. + with tempfile.TemporaryDirectory() as tmp: + cache = Path(tmp) + t = put_request(cache, ps_words(4), TARGET) + request = 'rtv1 %d 28' % t + v = G.fnv(request.encode('ascii')) + (cache / ('req_%016x.rtv' % v)).write_text(request, encoding='ascii') + for path in cache.glob('req_*'): # captured well before anything below + stamp = path.stat().st_mtime - 1000 + os.utime(path, (stamp, stamp)) + sources = {path: (path.read_bytes(), path.stat().st_mtime_ns) + for path in (cache / ('req_%016x.a' % t), cache / ('req_%016x.rtv' % v))} + watch_pass(cache) + manifests = [cache / ('%016x.txt' % key) for key in (t, v)] + description = cache / ('req_%016x.psin' % t) + check('base and RTV variant published, nothing pending', all(m.is_file() for m in manifests) and pending(cache) == []) + # The base description rewritten with the wrong pair (its line still naming the base), newer than both manifests. + for path in manifests: + if path.is_file(): + stamp = path.stat().st_mtime - 100 + os.utime(path, (stamp, stamp)) + description.write_bytes(describe(t, DECOY).encode('ascii')) + check('a wrong pair in the base description queues the base and its RTV variant', pending(cache) == sorted([t, v])) + watch_pass(cache) + fails = [cache / ('%016x.fail' % key) for key in (t, v)] + check('both refused by name and both published results withdrawn', + not any(m.is_file() for m in manifests) and all(f.is_file() for f in fails) + and 'pixel input description names another pipeline' in fails[0].read_text() + and 'RTV variant source key mismatch' in fails[1].read_text()) + check('the refusals are not retried while the description stays the same', pending(cache) == []) + # The valid description restored, newer than both failures. + for path in fails: + if path.is_file(): + stamp = path.stat().st_mtime - 100 + os.utime(path, (stamp, stamp)) + description.write_bytes(describe(t, TARGET).encode('ascii')) + check('the restored description, newer than the failures, queues both again', pending(cache) == sorted([t, v])) + watch_pass(cache) + texts = [(cache / ('%016x.ps.hlsl' % key)).read_text() if m.is_file() else '' for key, m in zip((t, v), manifests)] + check('both republished from the restored description (position v4), .a and .rtv untouched', + all(m.is_file() for m in manifests) and [packed_line(text) for text in texts] == [[4], [4]] + and all((path.read_bytes(), path.stat().st_mtime_ns) == state for path, state in sources.items()) + and pending(cache) == []) + # Only the base description removed: both results were translated with it, so both are withdrawn. + records = [cache / ('%016x.psdep' % key) for key in (t, v)] + check('both results record the description line they were translated with', + all(r.is_file() and r.read_text() == describe(t, TARGET) for r in records)) + # The failures of the wrong-pair cycle stay: on the manifest-only path a success does not remove them. + description.unlink() + check('a removed description queues the base and its RTV variant', pending(cache) == sorted([t, v])) + watch_pass(cache) + check('both refused by name as missing their description and both published results withdrawn', + not any(m.is_file() for m in manifests) and all(f.is_file() for f in fails) + and all('pixel input description missing for a request translated with one' in f.read_text() + for f in fails)) + check('the refusals are not retried while the description stays missing', pending(cache) == []) + for path in fails: + if path.is_file(): + stamp = path.stat().st_mtime - 100 + os.utime(path, (stamp, stamp)) + description.write_bytes(describe(t, TARGET).encode('ascii')) + check('the description restored again queues both', pending(cache) == sorted([t, v])) + watch_pass(cache) + check('both republished from the restored description', + all(m.is_file() for m in manifests) and pending(cache) == []) + + # A legacy request that never had a description: no dependency record, and its result stays done. + with tempfile.TemporaryDirectory() as tmp: + cache = Path(tmp) + legacy = put_request(cache, ps_words(4)) + watch_pass(cache) + check('a legacy request publishes without a dependency record and is not checked again', + (cache / ('%016x.txt' % legacy)).is_file() and not (cache / ('%016x.psdep' % legacy)).exists() + and pending(cache) == []) + + # Re-keying a cache keeps both pipelines and their descriptions, each naming its own key. + with tempfile.TemporaryDirectory() as tmp: + old, new = Path(tmp) / 'old', Path(tmp) / 'new' + old.mkdir() + keys = [put_request(old, ps_words(4), masks) for masks in (TARGET, DECOY)] + import io + import shader_cache_rekey + status = shader_cache_rekey.rekey(str(old), str(new), jobs=1, out=io.StringIO()) + check('re-keying keeps both mask pairs as requests with their own descriptions', + status == 0 and all((new / ('req_%016x.psin' % key)).read_bytes() == describe(key, masks).encode('ascii') + for key, masks in zip(keys, (TARGET, DECOY))) + and sorted(p.name for p in new.glob('req_*.psin')) == sorted('req_%016x.psin' % key for key in keys)) + + if failures: + print('%d control(s) failed' % len(failures)) + return 1 + print('controls: masks from the exact pipeline description; decoy, stale, missing and contradictory refused; ' + 'masks in the request identity') + return 0 + + +def draw(dxc, renderer, adapter, fxc=None): + compilers = [('dxc', dxc, '6_0')] + if fxc: + compilers.append(('fxc', fxc, '5_1')) + with tempfile.TemporaryDirectory() as tmp: + folder = Path(tmp) + cache = folder / 'cache' + cache.mkdir() + t, d = build_pair(cache) + sources = {} + for label, key in (('target', t), ('decoy', d)): + text, result = translated_ps(cache, key) + assert text is not None, (label, result) + sources[label] = text + # After those results exist, two more pipelines with the target's exact stage bytes, root signature and + # input layout arrive in the same cache: one whose masks also place the position in v4, and one whose + # masks place it in v2 (wrong register for this code). Each is a request of its own and is translated. + same = put_request(cache, ps_words(4), SAME_V4) + wrong = put_request(cache, ps_words(4), DECOY) + assert len({t, d, same, wrong}) == 4 and pending(cache) == sorted([same, wrong]), 'identities' + for label, key in (('same bytes, other masks (v4)', same), ('same bytes, other masks (v2)', wrong)): + text, result = translated_ps(cache, key, through_pending=True) + assert text is not None, (label, result) + sources[label] = text + for kind, compiler, profile in compilers: + vs = compile_hlsl(compiler, kind, FULLSCREEN_VS, 'vs', 'vs_' + profile, folder) + for label, good in (('target', True), ('decoy', True), ('same bytes, other masks (v4)', True), + ('same bytes, other masks (v2)', False)): + ps = compile_hlsl(compiler, kind, sources[label], 'ps', 'ps_' + profile, folder) + run = subprocess.run([renderer, adapter, '--startup-packed-position', vs, ps], + capture_output=True, text=True) + if run.returncode == 77: + print(run.stdout + run.stderr) + return 77 + if good: + assert run.returncode == 0 and 'all 91 packed positions matched' in run.stdout, (label, run.stdout, run.stderr) + else: + assert run.returncode != 0 and 'position mismatch (1,0): expected 00000001 actual 00000000' in run.stderr, (label, run.stderr) + device = [line for line in run.stdout.splitlines() if line.startswith(('backend=', 'adapter=', 'debug_'))] + print(f'{kind} {adapter} {label}: ' + ('91 pixels matched' if good else 'expected mismatch at (1,0)') + + ' [%s]' % '; '.join(device)) + if fxc: + compiled_results(folder / 'compiled', fxc) + return 0 + + +def compiled_results(cache, fxc): + """With bytecode (FXC), an unchanged manifest is not rewritten. A description rewritten unchanged is still + checked once and then done, and one rewritten with another mask pair withdraws the published result.""" + cache.mkdir() + t = put_request(cache, ps_words(4), TARGET) + with fxc_setting(fxc): + G.translate_pending(str(cache), skip_failed=True, jobs=1) + manifest = cache / ('%016x.txt' % t) + assert manifest.is_file() and (cache / ('%016x.ps.cso' % t)).is_file() and pending(cache, fxc) == [], 'compiled' + for masks, done in ((TARGET, True), (DECOY, False)): + stamp = manifest.stat().st_mtime - 100 + os.utime(manifest, (stamp, stamp)) + (cache / ('req_%016x.psin' % t)).write_bytes(describe(t, masks).encode('ascii')) + assert pending(cache, fxc) == [t], ('checked again', masks) + with fxc_setting(fxc): + G.translate_pending(str(cache), skip_failed=True, jobs=1) + assert pending(cache, fxc) == [] and manifest.is_file() == done, ('checked once', masks) + assert 'pixel input description names another pipeline' in (cache / ('%016x.fail' % t)).read_text() + print('fxc compiled result: rewritten description checked once; another mask pair withdraws the result') + + +def main(argv): + if not argv: + return controls() + mode, *args = argv + if mode == 'draw': + status = controls() + return status or draw(*args) + raise SystemExit(__doc__) + + +if __name__ == '__main__': + sys.exit(main(sys.argv[1:])) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 1bc2770ea..0a537d1f8 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -7327,10 +7327,17 @@ def __init__(self, vs_code, ps_code, root_blob, sampler_heap=None, rtv_formats=( # one is enabled). Without hardware inputs the model assumes the center pair alone: v0, v1. self.persp_center_vgpr = 0 if ps_hw_inputs is not None: + # SPI_PS_INPUT_ADDR allocates the entry VGPRs in bit order; SPI_PS_INPUT_ENA chooses which of the + # allocated inputs are loaded. Every enabled input is also allocated (LLVM AMDGPUAsmPrinter + # getSIProgramInfo: "all enabled inputs are tagged in InputAddr as well"; SIISelLowering + # processPSInputArgs marks an input allocated, then enabled only when it is used). ena, addr = ps_hw_inputs - if ena != addr or not 0 <= ena <= 0xffff: + if not (0 <= ena <= 0xffff and 0 <= addr <= 0xffff): raise Unsupported('unverified pixel input enable/address combination') - self.persp_center_vgpr = (2 if addr & 1 else 0) if addr & 2 else None + if ena & ~addr: + raise Unsupported('contradictory pixel input enable/address masks: an enabled input is not allocated') + # Layout from the address mask; an input allocated but not enabled holds no loaded value. + self.persp_center_vgpr = (2 if addr & 1 else 0) if ena & 2 else None if ena & (1 << 15): # SPI PS inputs 0..6 supply IJ pairs (the pull model supplies three); # line stipple through sample coverage each occupy one VGPR. @@ -7978,10 +7985,16 @@ def fnv(data, h=1469598103934665603): return h -def pipeline_key(vs_code, ps_code, root_blob, layout=b''): - """Hash the startup translation revision and the three blobs in runtime order, then a stream's input layout.""" +def pipeline_key(vs_code, ps_code, root_blob, layout=b'', ps_inputs=None): + """Hash the startup translation revision and the three blobs in runtime order, then a stream's input layout. + + A pipeline with a stream description (req_.psin) also hashes its pixel input masks: b'psin1' and then + SPI_PS_INPUT_ENA and SPI_PS_INPUT_ADDR as little-endian u32. Two pipelines with the same stages, root + signature and input layout but different masks are then two requests with their own results. Without a + description the key is unchanged.""" key = fnv(root_blob, fnv(ps_code, fnv(vs_code, fnv(b'x2w-startup-shader-17')))) - return fnv(layout, key) if layout else key + key = fnv(layout, key) if layout else key + return key if ps_inputs is None else fnv(b'psin1' + struct.pack('.vs.hlsl, .ps.hlsl and .txt (last), or .fail with the reason. With check, the pair is compiled to .vs.cso and .ps.cso first and a missing fxc is a failure. check=False, or X2W_FXC set to the empty string, publishes the manifest without bytecode.""" name = os.path.join(out_dir, '%016x' % key) try: - pipe = Pipeline(vs_code, ps_code, root_blob, rtv_formats=rtv_formats, vs_fetch=vs_fetch, ps_attr_map=ps_attr_map) + pipe = Pipeline(vs_code, ps_code, root_blob, rtv_formats=rtv_formats, vs_fetch=vs_fetch, ps_attr_map=ps_attr_map, + ps_hw_inputs=ps_hw_inputs) vs, ps, manifest = pipe.hlsl_vs(), pipe.hlsl_ps(), pipe.manifest() if rtv_request: manifest += rtv_request + '\n' @@ -8267,27 +8281,21 @@ def classify_stage(blob): decoded[kind] = ins return kind - name = os.path.join(out_dir, 'req_%016x' % key) - request = '' - formats = () - base = key - if os.path.isfile(name + '.rtv'): - with open(name + '.rtv', encoding='ascii') as file: - request = file.read(256) - if not re.fullmatch(r'rtv1 [0-9]{1,20}(?: [0-9]{1,10}){1,8}', request) or fnv(request.encode('ascii')) != key: - raise Unsupported('invalid RTV variant request') - base, *formats = map(int, request.split()[1:]) - if base > 0xffffffffffffffff or any(fmt > 0xffffffff for fmt in formats): - raise Unsupported('invalid RTV variant values') - name = os.path.join(out_dir, 'req_%016x' % base) + request, base, formats, description = request_source(out_dir, key) + name = os.path.join(out_dir, 'req_%016x' % base) a, b, root = (open(name + ext, 'rb').read() for ext in ('.a', '.b', '.root')) if pair_info is not None and not request: import hashlib pair_info.append((hashlib.sha256(struct.pack('.rtv) names its source pipeline and is translated + from that pipeline's blobs and stream description, req_.psin. This is the one place that names the + description a request depends on: the translation reads its masks from that path, and pending_keys checks + the same path to withdraw a published result or retry a failure after the description changes or, for a + result recorded as translated with it (dependency_record), is removed. The path is returned whether or not the + file exists. An invalid variant line is refused by name.""" + name = os.path.join(out_dir, 'req_%016x' % key) + request = '' + formats = () + base = key + if os.path.isfile(name + '.rtv'): + with open(name + '.rtv', encoding='ascii') as file: + request = file.read(256) + if not re.fullmatch(r'rtv1 [0-9]{1,20}(?: [0-9]{1,10}){1,8}', request) or fnv(request.encode('ascii')) != key: + raise Unsupported('invalid RTV variant request') + base, *formats = map(int, request.split()[1:]) + if base > 0xffffffffffffffff or any(fmt > 0xffffffff for fmt in formats): + raise Unsupported('invalid RTV variant values') + return request, base, formats, os.path.join(out_dir, 'req_%016x.psin' % base) + + +def request_ps_inputs(out_dir, key): + """The pixel input masks (SPI_PS_INPUT_ENA, SPI_PS_INPUT_ADDR) of one graphics request, or None. + + They come from the stream description request_source() names: req_.psin, the separately captured + description of exactly that pipeline (see read_ps_inputs), or for an RTV variant its source pipeline's. The + masks are part of the request's identity: the key must equal pipeline_key() of the stage blobs, root + signature, input layout and these masks, so a description copied from another pipeline, left stale after a + stage change or rewritten with another mask pair is refused, never applied. No file means no captured + description: the translation keeps its model without hardware inputs.""" + _, base, _, description = request_source(out_dir, key) + masks = read_ps_inputs(description, base) + if masks is None: + return None + name = os.path.join(out_dir, 'req_%016x' % base) + a, b, root = (open(name + ext, 'rb').read() for ext in ('.a', '.b', '.root')) + layout = open(name + '.ia', 'rb').read() if os.path.isfile(name + '.ia') else b'' + if pipeline_key(a, b, root, layout, masks) != base: + raise Unsupported('pixel input description names another pipeline') + return masks + + +def dependency_record(out_dir, key): + """.psdep: written when a graphics request is translated with a stream description, before its manifest. + + It marks a result as known to depend on the description request_source() names, so pending_keys can withdraw + that result when the description is removed. A legacy request that never had a description has no record, and + its inputs are not read again. The record holds the description line the result was translated with.""" + return os.path.join(out_dir, '%016x.psdep' % key) + + +def record_dependency(out_dir, key, base, masks): + path = dependency_record(out_dir, key) + line = 'psin1 %016x ena=0x%04x addr=0x%04x\n' % (base, *masks) + with suppress(FileNotFoundError, UnicodeError), open(path) as existing: + if existing.read() == line: + return + temporary = '%s.%d.tmp' % (path, os.getpid()) + try: + with open(temporary, 'w') as record: + record.write(line) + os.replace(temporary, path) + finally: + with suppress(FileNotFoundError): + os.remove(temporary) + + +def read_ps_inputs(path, key): + """The (enable, address) masks in the stream description at `path` (req_.psin), one ASCII line + 'psin1 ena= addr=' (the key as 16 hex digits, the masks as 0x-prefixed 16-bit values), or + None without the file. The line must name `key`; a malformed line or a missing mask is refused by name.""" + if not os.path.isfile(path): + return None + with open(path, 'rb') as file: + line = file.read(128) + fields = line.decode('ascii', 'replace').split() + if not re.fullmatch(rb'psin1 [0-9a-f]{16}(?: (?:ena|addr)=0x[0-9a-f]{1,4}){0,2}\n?', line): + raise Unsupported('invalid pixel input description') + masks = dict(field.split('=') for field in fields[2:]) + if len(masks) != len(fields) - 2: + raise Unsupported('invalid pixel input description') + if int(fields[1], 16) != key: + raise Unsupported('pixel input description names another pipeline') + for field, label in (('ena', 'enable'), ('addr', 'address')): + if field not in masks: + raise Unsupported('pixel input %s mask missing from the stream description' % label) + return int(masks['ena'], 16), int(masks['addr'], 16) + + def mesh57_key(ms, ps, root): value = fnv(b'x2w-startup-mesh-57-2') for part in (ms, ps, root): @@ -8390,15 +8490,32 @@ def translate_request(out_dir, key): open(os.path.join(out_dir, '%016x.fail' % key), 'w').write(str(reason) + '\n') return 'unsupported: %s' % reason try: - kinds, root, formats, request, fetch, _, attr_map = load_request(out_dir, key, validate_base_key=True) + try: + _, base, _, description = request_source(out_dir, key) + if os.path.isfile(dependency_record(out_dir, key)) and not os.path.isfile(description): + raise Unsupported('pixel input description missing for a request translated with one') + kinds, root, formats, request, fetch, _, attr_map = load_request(out_dir, key, validate_base_key=True) + ps_inputs = request_ps_inputs(out_dir, key) + if ps_inputs is not None: + record_dependency(out_dir, key, base, ps_inputs) # before the manifest is published + except Unsupported: + # A result published earlier was translated from sources or masks this request no longer confirms. + with suppress(FileNotFoundError): + os.remove(os.path.join(out_dir, '%016x.txt' % key)) + raise except (Unsupported, OSError, UnicodeError) as reason: open(os.path.join(out_dir, '%016x.fail' % key), 'w').write(str(reason) + '\n') return 'unsupported: %s' % reason if set(kinds) != {'vs', 'ps'}: open(os.path.join(out_dir, '%016x.fail' % key), 'w').write('stages %s\n' % sorted(kinds)) return 'stages %s' % sorted(kinds) - return translate_to(out_dir, key, kinds['vs'], kinds['ps'], root, rtv_formats=formats, rtv_request=request, vs_fetch=fetch, - ps_attr_map=attr_map) + result = translate_to(out_dir, key, kinds['vs'], kinds['ps'], root, rtv_formats=formats, rtv_request=request, + vs_fetch=fetch, ps_attr_map=attr_map, ps_hw_inputs=ps_inputs) + if ps_inputs is not None and result == 'ok': + # An unchanged manifest is not rewritten; mark it as checked against this description (pending_keys). + with suppress(FileNotFoundError): + os.utime(os.path.join(out_dir, '%016x.txt' % key)) + return result REFUSALS_CAVEAT = ('Counts after the first refusal are approximate. Skipped instructions leave later state ' @@ -8449,7 +8566,8 @@ def request_refusals(out_dir, key, pair_info=None): """Collect reached refusal sites for one request without publishing a translation.""" refusals = [] try: - kinds, root, formats, _, fetch, decoded, attr_map = load_request(out_dir, key, refusals, pair_info) + kinds, root, formats, request, fetch, decoded, attr_map = load_request(out_dir, key, refusals, pair_info) + ps_inputs = request_ps_inputs(out_dir, key) except Unsupported as reason: refusals.append((str(reason), 'pipeline')) return refusals @@ -8469,7 +8587,7 @@ def request_refusals(out_dir, key, pair_info=None): if set(kinds) != {'vs', 'ps'}: raise Unsupported('stages %s' % sorted(kinds)) pipe = Pipeline(kinds['vs'], kinds['ps'], root, rtv_formats=formats, vs_fetch=fetch, - refusals=refusals, decoded=decoded, ps_attr_map=attr_map) + refusals=refusals, decoded=decoded, ps_attr_map=attr_map, ps_hw_inputs=ps_inputs) op = 'hlsl_vs' pipe.hlsl_vs() op = 'hlsl_ps' @@ -8720,8 +8838,21 @@ def pending_keys(out_dir, skip_failed): stages = ('.cs.cso',) if m.group(2) == 'c67' else ('.ms57.cso', '.ps57.cso') if mesh else ('.vs.cso', '.ps.cso') ready_bytecode = has_complete_mesh57_bytecode if mesh else has_bytecode manifest = result + ('.ms57.txt' if mesh else '.txt') - # A published manifest with bytecode (or manifest-only mode) is done; otherwise resume (#2008). - if os.path.isfile(manifest): + # A published manifest with bytecode (or manifest-only mode) is done; otherwise resume (#2008). The stream + # description the translation reads (request_source: the request's own, or an RTV variant's source + # pipeline's) is a dependency like the request file. Rewritten after the result was published, the result + # is checked again, so one translated with other masks is not kept in silence; rewritten after a refusal, + # the request is retried. + described = None + lost = False + if m.group(2) in ('a', 'rtv'): + with suppress(Unsupported, OSError, UnicodeError): # no description, or a variant line refused later + described = os.path.getmtime(request_source(out_dir, key)[3]) + # A result translated with a description recorded it (dependency_record). With that description gone, + # the result is checked again and withdrawn; a legacy request without a record is not read again. + lost = described is None and os.path.isfile(result + '.psdep') + if os.path.isfile(manifest) and not lost and not ( + described is not None and described > os.path.getmtime(manifest)): if manifest_only or all(ready_bytecode(result + s) for s in stages): continue if mesh and has_complete_mesh57_bytecode(result + '.ms57.cso'): @@ -8729,8 +8860,12 @@ def pending_keys(out_dir, skip_failed): if b'ps none' in published.read().splitlines(): continue fail = os.path.join(out_dir, '%016x.fail' % key) - # A repeated pass retries a failure only once its request is rewritten. - if skip_failed and os.path.exists(fail) and os.path.getmtime(fail) >= os.path.getmtime(os.path.join(out_dir, name)): + # A repeated pass retries a failure only once its request or its stream description is rewritten. A result + # still published without its recorded description is checked even with an older .fail, which a success on + # the manifest-only path leaves in place. + recheck = lost and os.path.isfile(manifest) + if skip_failed and not recheck and os.path.exists(fail) and os.path.getmtime(fail) >= max( + os.path.getmtime(os.path.join(out_dir, name)), described or 0): continue keys.append(key) return keys diff --git a/tools/startup/shader_cache_rekey.py b/tools/startup/shader_cache_rekey.py index 64db2d903..a1baf9394 100644 --- a/tools/startup/shader_cache_rekey.py +++ b/tools/startup/shader_cache_rekey.py @@ -12,7 +12,9 @@ The old cache is only read. Only request files (req_*) are written; results and .fail files are not, and a file that already exists in is left as it is. Each file is written to a temporary name and renamed; -the ready marker (.a, .c67, .m57) goes last, as the runtime writes it. Slot 86 mesh requests are only counted. +the ready marker (.a, .c67, .m57) goes last, as the runtime writes it. A stream description (.psin) is written +again under the new key with the same masks, since its line names the key and its masks are part of the key. +Slot 86 mesh requests are only counted. All requests are read before anything is written. When a request part is missing or unreadable, or an RTV variant is malformed, does not match its own name or names a base request that is not in the cache, the tool @@ -29,9 +31,9 @@ REQUEST = re.compile(r'req_([0-9a-f]{16})\.(a|rtv|c67|m57|m86)') # Request files of each kind; the ready marker is last. -PARTS = {'g': ('.b', '.root', '.ia', '.a'), 'c': ('.desc', '.sa', '.sb', '.data', '.root', '.c67'), +PARTS = {'g': ('.b', '.root', '.ia', '.psin', '.a'), 'c': ('.desc', '.sa', '.sb', '.data', '.root', '.c67'), 'm57': ('.ps57', '.root', '.m57')} -OPTIONAL = {'.ia'} # a graphics request without an input layout has no .ia +OPTIONAL = {'.ia', '.psin'} # a graphics request may have no input layout (.ia) and no stream description (.psin) class Incomplete(Exception): @@ -61,7 +63,12 @@ def current_key(job): except OSError as error: return kind, key, None, 'unreadable %s: %s' % (os.path.basename(error.filename or ''), error.strerror) if kind == 'g': - return kind, key, g.pipeline_key(p['.a'], p['.b'], p['.root'], p.get('.ia', b'')), None + # The pixel input masks of a stream description are part of the key; the description names its key. + try: + masks = g.read_ps_inputs(request_name(src, key, '.psin'), key) + except g.Unsupported as reason: + return kind, key, None, str(reason) + return kind, key, g.pipeline_key(p['.a'], p['.b'], p['.root'], p.get('.ia', b''), masks), None if kind == 'm57': return kind, key, g.mesh57_key(p['.m57'], p['.ps57'], p['.root']), None return kind, key, g.compute_key(p['.c67'], p['.data'], p['.root'], p['.desc'], p['.sa'], p['.sb']), None @@ -177,6 +184,9 @@ def rekey(src, dst, jobs=None, out=None): done.add(key) # Read again, not checked against the hashing pass: nothing may write the old cache meanwhile. for ext, data in read_parts(src, kind, old).items(): + if ext == '.psin': # the line names the new key + data = ('psin1 %016x ena=0x%04x addr=0x%04x\n' % ( + key, *g.read_ps_inputs(request_name(src, old, '.psin'), old))).encode('ascii') publish(request_name(dst, key, ext), data, stats) current = sum(old == key for old, key in new[kind].items()) print('%s: %d requests, %d already current -> %d keys' % (label, len(new[kind]), current, len(done)), file=out) From 53be9e2d74a68f9efa1df1cd495c260cfb93fbb5 Mon Sep 17 00:00:00 2001 From: tedin7 <110300616+tedin7@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:05:11 +0100 Subject: [PATCH 056/240] tests: wide VGPR tuple spelling for image_sample_d fixtures (follow-up to #2082, Part of #1723) (#2646) * test: use the wide tuple spelling for image_sample_d fixtures that LLVM 15 assembles Follow-up to #2082. The assembler needs the full 8 VGPR (16 for a volume) tuple; the decoder lists the active registers. * ci: run the image_sample_d fixture check against llvm-mc-15 --- .github/workflows/windows.yml | 2 ++ tests/startup_image_sample_d_check.py | 15 ++++++++------- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index db89553ca..b7a494dda 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -97,6 +97,7 @@ jobs: (["tests/startup_image_sample_l_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_image_sample_b_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_image_sample_lod_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_image_sample_d_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_image_gather_lz_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_compute_gather_lz_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_compute_image_store_check.py", "--llvm-mc", "llvm-mc-15"], {}), @@ -226,6 +227,7 @@ jobs: tests/startup_image_sample_l_check.py \ tests/startup_image_sample_b_check.py \ tests/startup_image_sample_lod_check.py \ + tests/startup_image_sample_d_check.py \ tests/startup_image_gather_lz_check.py \ tests/startup_compute_gather_lz_check.py \ tests/startup_compute_image_store_check.py \ diff --git a/tests/startup_image_sample_d_check.py b/tests/startup_image_sample_d_check.py index 5e7ac7d48..719903e18 100644 --- a/tests/startup_image_sample_d_check.py +++ b/tests/startup_image_sample_d_check.py @@ -21,15 +21,15 @@ TAIL = 's[16:23], s[24:27] dmask:0xf dim:' IMAGE = { - 'd2': 'image_sample_d v[4:7], v[0:5], ' + TAIL + 'SQ_RSRC_IMG_2D', + 'd2': 'image_sample_d v[4:7], v[0:7], ' + TAIL + 'SQ_RSRC_IMG_2D', 'd2nsa': 'image_sample_d v[4:7], [v0, v1, v2, v3, v1, v0], ' + TAIL + 'SQ_RSRC_IMG_2D', - 'd3': 'image_sample_d v[4:7], v[0:8], ' + TAIL + 'SQ_RSRC_IMG_3D', - 'd2a': 'image_sample_d v[4:7], v[0:6], ' + TAIL + 'SQ_RSRC_IMG_2D_ARRAY', + 'd3': 'image_sample_d v[4:7], v[0:15], ' + TAIL + 'SQ_RSRC_IMG_3D', + 'd2a': 'image_sample_d v[4:7], v[0:7], ' + TAIL + 'SQ_RSRC_IMG_2D_ARRAY', 'd1': 'image_sample_d v[4:7], [v0, v1, v2], ' + TAIL + 'SQ_RSRC_IMG_1D', - 'cd': 'image_sample_c_d v[4:7], v[0:6], ' + TAIL + 'SQ_RSRC_IMG_2D', - 'do': 'image_sample_d_o v[4:7], v[0:6], ' + TAIL + 'SQ_RSRC_IMG_2D', - 'dtfe': 'image_sample_d v[4:5], v[0:5], s[16:23], s[24:27] dmask:0x1 dim:SQ_RSRC_IMG_2D tfe', - 'dglc': 'image_sample_d v[4:7], v[0:5], ' + TAIL + 'SQ_RSRC_IMG_2D glc', + 'cd': 'image_sample_c_d v[4:7], v[0:7], ' + TAIL + 'SQ_RSRC_IMG_2D', + 'do': 'image_sample_d_o v[4:7], v[0:7], ' + TAIL + 'SQ_RSRC_IMG_2D', + 'dtfe': 'image_sample_d v[4:5], v[0:7], s[16:23], s[24:27] dmask:0x1 dim:SQ_RSRC_IMG_2D tfe', + 'dglc': 'image_sample_d v[4:7], v[0:7], ' + TAIL + 'SQ_RSRC_IMG_2D glc', } WORDS = { 'd2': bytes.fromhex('04040cf4000000fa800398be800399be80039abe80039bbef002007eff02027e0000803ef202047ef402067e7fc08cbf080f88f00004c400703f8cbf0f1800f804050607000081bf'), @@ -117,6 +117,7 @@ def controls(): def check_binary(llvm_mc): + # The assembler takes the wide tuple spelling (8 VGPRs, 16 for a volume); the decoder lists the active ones. for name, line in IMAGE.items(): built = assemble(llvm_mc, PRE + line + '\n' + POST) if built != WORDS[name]: From f02ebd66913a81caa702b59c4bd103489ebf7d52 Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Thu, 26 Nov 2026 04:05:24 +0200 Subject: [PATCH 057/240] ci: harden form_reference CLI with atomic writes and add CLI suite (#2675) --- CMakeLists.txt | 3 + tests/form_reference_cli_check.py | 410 ++++++++++++++++++++++++++++++ tools/form_reference.py | 112 +++++++- 3 files changed, 512 insertions(+), 13 deletions(-) create mode 100644 tests/form_reference_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 6acee0297..2f22ae5ec 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -10617,6 +10617,9 @@ if(EXISTS "${INTAKE_PYTHON}") # not run them locally while the CI Python job did. add_test(NAME bidi_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/bidi_controls_check.py") + add_test(NAME ci_form_reference_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/form_reference_cli_check.py") + set_tests_properties(ci_form_reference_cli_check PROPERTIES TIMEOUT 60) add_test(NAME compat_report COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/compat_report_check.py") add_test(NAME pe_compat_report_cli_check COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/form_reference_cli_check.py b/tests/form_reference_cli_check.py new file mode 100644 index 000000000..fdcd38fed --- /dev/null +++ b/tests/form_reference_cli_check.py @@ -0,0 +1,410 @@ +"""Pure-Python CLI, atomic-write, path-guard, and mutation suite for tools/form_reference.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +import os +from pathlib import Path +import runpy +import subprocess +import sys +from tempfile import TemporaryDirectory +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOLS_DIR = ROOT / "tools" +TOOL = TOOLS_DIR / "form_reference.py" +sys.path.insert(0, str(TOOLS_DIR)) + +import form_reference # noqa: E402 + + +SYNTHETIC_RST = { + "AMDGPUAsmGFX10.rst": ( + "SOPP\n----\n\n.. parsed-literal::\n\n s_endpgm\n\n" + "EXP\n---\n\n exp\n" + ), + "AMDGPUAsmGFX1011.rst": ( + "SOPK\n----\n\n s_addk_i32 sdst, simm16\n" + ), + "AMDGPUAsmGFX1013.rst": ( + "SMEM\n----\n\n s_atomic_add sdata, sbase, offset\n\n" + "VOP1\n----\n\n v_mov_b32_e32 vdst, src0\n" + ), + "AMDGPUAsmGFX1030.rst": ( + "SOPP\n----\n\n s_endpgm\n\n" + "VOP3\n----\n\n v_fmac_f32_e64 vdst, src0, src1\n\n" + ".. toctree::\n :hidden:\n\n gfx1030_ignored_entry\n" + ), +} + + +def _populate_docs_dir(docs_dir: Path, *, skip: str | None = None) -> None: + docs_dir.mkdir(parents=True, exist_ok=True) + for name, text in SYNTHETIC_RST.items(): + if name == skip: + continue + (docs_dir / name).write_text(text, encoding="utf-8") + + +def _run_main(argv: list[str] | None, *, module=form_reference) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = module.main(argv) + except SystemExit as exc: + code = exc.code if isinstance(exc.code, int) else 2 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str, script: Path = TOOL) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(script), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class FormReferenceCliPositiveTests(unittest.TestCase): + def test_synthetic_rst_and_nested_out_dir_atomic_generation(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + docs = root / "llvm_docs" + _populate_docs_dir(docs) + out_dir = root / "nested" / "coverage" + self.assertFalse(out_dir.exists()) + + replaces: list[tuple[Path, Path]] = [] + real_replace = os.replace + + def tracking_replace(src, dst): + src_p, dst_p = Path(src), Path(dst) + replaces.append((src_p, dst_p)) + self.assertEqual(src_p.parent.resolve(), dst_p.parent.resolve()) + return real_replace(src, dst) + + with mock.patch.object(form_reference.os, "replace", side_effect=tracking_replace): + code, out, err = _run_main([str(docs), "--out-dir", str(out_dir)]) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertEqual(len(replaces), 3) + self.assertIn("gfx1013.tsv 5", out) + self.assertIn("rdna2.tsv 2", out) + self.assertIn("x64_zen2.tsv", out) + self.assertEqual( + sorted(p.name for p in out_dir.iterdir()), + ["gfx1013.tsv", "rdna2.tsv", "x64_zen2.tsv"], + ) + + gfx_lines = (out_dir / "gfx1013.tsv").read_text(encoding="utf-8").splitlines() + self.assertTrue(gfx_lines[0].startswith("# 5 forms. Source: "), gfx_lines[0]) + self.assertEqual( + gfx_lines[1:], + [ + "EXP\texp", + "SMEM\ts_atomic_add", + "SOPK\ts_addk_i32", + "SOPP\ts_endpgm", + "VOP1\tv_mov_b32_e32", + ], + ) + rdna_lines = (out_dir / "rdna2.tsv").read_text(encoding="utf-8").splitlines() + self.assertTrue(rdna_lines[0].startswith("# 2 forms. Source: "), rdna_lines[0]) + self.assertEqual(rdna_lines[1:], ["SOPP\ts_endpgm", "VOP3\tv_fmac_f32_e64"]) + x64_lines = (out_dir / "x64_zen2.tsv").read_text(encoding="utf-8").splitlines() + expected_x64 = form_reference.x64_forms() + self.assertTrue(x64_lines[0].startswith(f"# {len(expected_x64)} forms. Source: ")) + self.assertEqual(len(x64_lines) - 1, len(expected_x64)) + + def test_atomic_overwrite_sys_argv_and_main_entrypoint(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + docs = root / "docs" + _populate_docs_dir(docs) + out_dir = root / "out" + out_dir.mkdir() + for name in form_reference.OUTPUT_TSV_NAMES: + (out_dir / name).write_text("stale\n", encoding="utf-8") + + proc = _run_subprocess(str(docs), "--out-dir", str(out_dir)) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stderr, "") + self.assertEqual( + sorted(p.name for p in out_dir.iterdir()), + ["gfx1013.tsv", "rdna2.tsv", "x64_zen2.tsv"], + ) + self.assertTrue( + (out_dir / "rdna2.tsv").read_text(encoding="utf-8").startswith("# 2 forms.") + ) + + # Verify argv=None forwarding and __main__ entrypoint. + out_entry = root / "entry_out" + cli_argv = [str(TOOL), str(docs), "--out-dir", str(out_entry)] + with mock.patch.object(sys, "argv", cli_argv): + code, _, err = _run_main(None) + self.assertEqual(code, 0, err) + self.assertTrue((out_entry / "gfx1013.tsv").is_file()) + + out_runpy = root / "runpy_out" + stdout, stderr = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", [str(TOOL), str(docs), "--out-dir", str(out_runpy)]), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 0) + self.assertEqual(stderr.getvalue(), "") + self.assertEqual( + sorted(p.name for p in out_runpy.iterdir()), + ["gfx1013.tsv", "rdna2.tsv", "x64_zen2.tsv"], + ) + + +class FormReferenceCliNegativeTests(unittest.TestCase): + def _assert_exit_1_clean(self, argv: list[str], *, fragment: str, check_subproc: bool = True) -> None: + code, out, err = _run_main(argv) + self.assertEqual(code, 1, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertIn("form_reference:", err) + self.assertIn(fragment, err) + + if check_subproc: + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, 1, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertIn("form_reference:", proc.stderr) + self.assertIn(fragment, proc.stderr) + + def test_missing_and_non_directory_docs_dir_rejected_upfront(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + out_dir = root / "never_created" + reg_file = root / "not_a_dir.txt" + reg_file.write_text("file", encoding="utf-8") + + with ( + mock.patch.object(form_reference, "llvm_forms", side_effect=AssertionError("parsed")), + mock.patch.object(form_reference, "x64_forms", side_effect=AssertionError("x64")), + ): + for bad_docs, frag in ( + (str(root / "missing_docs"), "not a directory"), + (str(reg_file), "not a directory"), + ("", "must not be empty"), + (" ", "must not be empty"), + ): + with self.subTest(bad_docs=bad_docs): + self._assert_exit_1_clean( + [bad_docs, "--out-dir", str(out_dir)], + fragment=frag, + check_subproc=False, + ) + self.assertFalse(out_dir.exists()) + + proc = _run_subprocess(str(root / "missing_docs"), "--out-dir", str(out_dir)) + self.assertEqual(proc.returncode, 1) + self.assertNotIn("Traceback", proc.stderr) + self.assertIn("not a directory", proc.stderr) + self.assertFalse(out_dir.exists()) + + def test_missing_or_directory_rst_rejected_upfront(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + out_dir = root / "never_created" + + for missing_name in SYNTHETIC_RST: + docs = root / f"missing_{missing_name}" + _populate_docs_dir(docs, skip=missing_name) + with ( + mock.patch.object(form_reference, "llvm_forms", side_effect=AssertionError("parsed")), + mock.patch.object(form_reference, "x64_forms", side_effect=AssertionError("x64")), + ): + self._assert_exit_1_clean( + [str(docs), "--out-dir", str(out_dir)], + fragment=missing_name, + check_subproc=False, + ) + self.assertFalse(out_dir.exists()) + + dir_rst_docs = root / "dir_rst_docs" + _populate_docs_dir(dir_rst_docs, skip="AMDGPUAsmGFX1030.rst") + (dir_rst_docs / "AMDGPUAsmGFX1030.rst").mkdir() + with mock.patch.object(form_reference, "llvm_forms", side_effect=AssertionError("parsed")): + self._assert_exit_1_clean( + [str(dir_rst_docs), "--out-dir", str(out_dir)], + fragment="AMDGPUAsmGFX1030.rst", + check_subproc=True, + ) + self.assertFalse(out_dir.exists()) + + def test_output_dir_file_parent_and_empty_out_dir_rejected_upfront(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + docs = root / "docs" + _populate_docs_dir(docs) + + # 1) Output file path is an existing directory. + out_with_dir = root / "out_with_dir" + out_with_dir.mkdir() + (out_with_dir / "gfx1013.tsv").mkdir() + with mock.patch.object(form_reference, "llvm_forms", side_effect=AssertionError("parsed")): + self._assert_exit_1_clean( + [str(docs), "--out-dir", str(out_with_dir)], + fragment="must not be a directory", + ) + self.assertEqual([p.name for p in out_with_dir.iterdir()], ["gfx1013.tsv"]) + + # 2) --out-dir itself is an existing regular file. + out_is_file = root / "file_out" + out_is_file.write_text("keep-me", encoding="utf-8") + with mock.patch.object(form_reference, "llvm_forms", side_effect=AssertionError("parsed")): + self._assert_exit_1_clean( + [str(docs), "--out-dir", str(out_is_file)], + fragment="not a directory", + ) + self.assertEqual(out_is_file.read_text(encoding="utf-8"), "keep-me") + + # 3) Parent ancestor of --out-dir is a regular file. + nested_under_file = out_is_file / "sub" + with mock.patch.object(form_reference, "llvm_forms", side_effect=AssertionError("parsed")): + self._assert_exit_1_clean( + [str(docs), "--out-dir", str(nested_under_file)], + fragment="output parent is not a directory", + ) + self.assertEqual(out_is_file.read_text(encoding="utf-8"), "keep-me") + + # 4) Empty --out-dir. + self._assert_exit_1_clean([str(docs), "--out-dir", " "], fragment="--out-dir must not be empty") + + def test_output_symlink_rejected_upfront(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + docs = root / "docs" + _populate_docs_dir(docs) + out_dir = root / "out" + out_dir.mkdir() + real_target = root / "real_target.tsv" + real_target.write_text("untouched\n", encoding="utf-8") + link_target = out_dir / "x64_zen2.tsv" + try: + link_target.symlink_to(real_target) + except OSError as exc: + if getattr(exc, "winerror", None) != 1314: + raise + self.skipTest("this Windows account cannot create symlinks (WinError 1314)") + + with mock.patch.object(form_reference, "llvm_forms", side_effect=AssertionError("parsed")): + self._assert_exit_1_clean( + [str(docs), "--out-dir", str(out_dir)], + fragment="symlink", + ) + self.assertEqual(real_target.read_text(encoding="utf-8"), "untouched\n") + self.assertEqual([p.name for p in out_dir.iterdir()], ["x64_zen2.tsv"]) + + def test_os_replace_failure_leaves_zero_tmp_and_preserves_existing_tsv(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + docs = root / "docs" + _populate_docs_dir(docs) + out_dir = root / "out" + out_dir.mkdir() + for name in form_reference.OUTPUT_TSV_NAMES: + (out_dir / name).write_text(f"prior-{name}\n", encoding="utf-8") + + with mock.patch.object(form_reference.os, "replace", side_effect=OSError("simulated replace fail")): + self._assert_exit_1_clean( + [str(docs), "--out-dir", str(out_dir)], + fragment="simulated replace fail", + check_subproc=False, + ) + + self.assertEqual( + sorted(p.name for p in out_dir.iterdir()), + ["gfx1013.tsv", "rdna2.tsv", "x64_zen2.tsv"], + ) + for name in form_reference.OUTPUT_TSV_NAMES: + self.assertEqual((out_dir / name).read_text(encoding="utf-8"), f"prior-{name}\n") + + def test_argparse_errors_py314_safe(self) -> None: + with TemporaryDirectory() as tmp: + docs = Path(tmp) / "docs" + _populate_docs_dir(docs) + for argv, frag in ( + ([], "required"), + ([str(docs), "--bogus-flag"], "unrecognized"), + ([str(docs), "--out-dir"], "expected one argument"), + ): + with self.subTest(argv=argv): + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, 2) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertIn("usage:", proc.stderr.lower()) + self.assertIn(frag, proc.stderr) + + def test_fast_temp_mutations_killed(self) -> None: + """Verify mutated copies of form_reference.py fail targeted guard assertions.""" + original_src = TOOL.read_text(encoding="utf-8") + mutations = ( + ( + "drop_docs_is_dir", + " if not docs.is_dir():", + " if False:", + lambda m_docs, m_out: [str(m_docs / "not_a_dir"), "--out-dir", str(m_out)], + "not a directory", + ), + ( + "drop_rst_is_file", + " if not rst.is_file():", + " if False:", + lambda m_docs, m_out: [str(m_docs / "missing_rst"), "--out-dir", str(m_out)], + "missing or non-regular", + ), + ( + "drop_out_dir_check", + " if path.exists() and path.is_dir():", + " if False:", + lambda m_docs, m_out: [str(m_docs / "valid"), "--out-dir", str(m_out / "dir_collision")], + "output path must not be a directory", + ), + ) + with TemporaryDirectory() as tmp: + root = Path(tmp) + valid_docs = root / "valid" + _populate_docs_dir(valid_docs) + (root / "not_a_dir").write_text("file", encoding="utf-8") + _populate_docs_dir(root / "missing_rst", skip="AMDGPUAsmGFX1030.rst") + out_base = root / "out" + out_base.mkdir() + (out_base / "dir_collision").mkdir() + (out_base / "dir_collision" / "gfx1013.tsv").mkdir() + + for label, old, new, argv_fn, expected_msg in mutations: + mutated_src = original_src.replace(old, new, 1) + self.assertNotEqual(mutated_src, original_src, label) + mutated_tool = root / f"mut_{label}.py" + mutated_tool.write_text(mutated_src, encoding="utf-8") + argv = argv_fn(root, out_base) + proc = _run_subprocess(*argv, script=mutated_tool) + self.assertNotIn(expected_msg, proc.stderr, label) + + # Mutating temp-file cleanup must leak a .tmp file on replace failure. + no_cleanup_src = original_src.replace("tmp_path.unlink(missing_ok=True)", "pass", 1) + self.assertNotEqual(no_cleanup_src, original_src) + mut_ns: dict[str, object] = {"__file__": str(TOOL)} + exec(compile(no_cleanup_src, str(root / "mut_cleanup.py"), "exec"), mut_ns) + leak_dir = root / "leak_out" + leak_dir.mkdir() + with mock.patch.object(mut_ns["os"], "replace", side_effect=OSError("boom")): + with self.assertRaises(OSError): + mut_ns["_write_atomic"](leak_dir / "gfx1013.tsv", "content") + self.assertTrue(any(p.suffix == ".tmp" for p in leak_dir.iterdir())) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/form_reference.py b/tools/form_reference.py index 9ca34952d..f834c03b7 100644 --- a/tools/form_reference.py +++ b/tools/form_reference.py @@ -1,18 +1,24 @@ """Regenerate the instruction reference lists in docs/coverage/ (rarely needed). -Usage: out/pe-env/Scripts/python.exe tools/form_reference.py +Usage: out/pe-env/Scripts/python.exe tools/form_reference.py [--out-dir DIR] holds AMDGPUAsmGFX10.rst, AMDGPUAsmGFX1011.rst, AMDGPUAsmGFX1013.rst and AMDGPUAsmGFX1030.rst from llvm-project tag llvmorg-15.0.7, llvm/docs/AMDGPU/ (Apache-2.0 WITH LLVM-exception). These are generated from LLVM's instruction tables. The x64 list comes from the iced-x86 package already in requirements-dev.txt. Output lines are "groupform". """ +import argparse +import os +from pathlib import Path import re import sys -from pathlib import Path +import tempfile OUT = Path(__file__).resolve().parents[1] / "docs" / "coverage" LLVM_SOURCE = "llvm-project llvmorg-15.0.7 llvm/docs/AMDGPU/" +REQUIRED_GFX1013_RST = ("AMDGPUAsmGFX10.rst", "AMDGPUAsmGFX1011.rst", "AMDGPUAsmGFX1013.rst") +REQUIRED_RDNA2_RST = ("AMDGPUAsmGFX1030.rst",) +OUTPUT_TSV_NAMES = ("gfx1013.tsv", "rdna2.tsv", "x64_zen2.tsv") # Xbox Series CPUs are AMD Zen 2. These iced CPUID groups are what Zen 2 runs in user mode; the group # names are what the dashboard shows. AVX-512, XOP/FMA4/TBM, 3DNow!, AMX and vendor extras are left out. @@ -73,19 +79,99 @@ def names(module): return {(group, mnemonic) for mnemonic, group in forms.items()} -def write(name, source, forms): - OUT.mkdir(parents=True, exist_ok=True) +def _validate_docs_dir(docs): + """Validate that docs is a directory containing all required AMDGPUAsmGFX*.rst regular files.""" + if not docs.is_dir(): + raise ValueError(f"LLVM docs path is not a directory: {docs}") + gfx1013_files = [docs / name for name in REQUIRED_GFX1013_RST] + rdna2_files = [docs / name for name in REQUIRED_RDNA2_RST] + for rst in (*gfx1013_files, *rdna2_files): + if not rst.is_file(): + raise ValueError(f"missing or non-regular LLVM doc file: {rst}") + return gfx1013_files, rdna2_files + + +def _validate_output_file(path): + """Reject symlink, directory, or file-parent output paths before writing.""" + if path.is_symlink(): + raise ValueError(f"output path must not be a symlink: {path}") + if path.exists() and path.is_dir(): + raise ValueError(f"output path must not be a directory: {path}") + for ancestor in path.parents: + if ancestor.exists() and not ancestor.is_dir(): + raise ValueError(f"output parent is not a directory: {ancestor}") + + +def _validate_out_dir_and_targets(out_dir): + """Validate --out-dir and each target .tsv path upfront before parsing inputs.""" + if out_dir.is_symlink(): + raise ValueError(f"output directory must not be a symlink: {out_dir}") + if out_dir.exists() and not out_dir.is_dir(): + raise ValueError(f"output directory path is not a directory: {out_dir}") + for ancestor in out_dir.parents: + if ancestor.exists() and not ancestor.is_dir(): + raise ValueError(f"output parent is not a directory: {ancestor}") + for name in OUTPUT_TSV_NAMES: + _validate_output_file(out_dir / name) + + +def _write_atomic(path, content): + """Write content via a sibling temp file and os.replace, unlinking temp files on error.""" + _validate_output_file(path) + path.parent.mkdir(parents=True, exist_ok=True) + tmp_path = None + try: + with tempfile.NamedTemporaryFile( + mode="w", + encoding="utf-8", + newline="\n", + dir=path.parent, + prefix=f".{path.stem}.", + suffix=".tmp", + delete=False, + ) as handle: + tmp_path = Path(handle.name) + handle.write(content) + os.replace(tmp_path, path) + except BaseException: + if tmp_path is not None: + tmp_path.unlink(missing_ok=True) + raise + + +def write(name, source, forms, out_dir=OUT): body = "".join(f"{g}\t{f}\n" for g, f in sorted(forms)) - (OUT / name).write_text(f"# {len(forms)} forms. Source: {source}. Regenerate: tools/form_reference.py\n" - + body, encoding="utf-8") + content = (f"# {len(forms)} forms. Source: {source}. Regenerate: tools/form_reference.py\n" + + body) + _write_atomic(Path(out_dir) / name, content) print(name, len(forms)) +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("llvm_docs_dir", help="directory containing AMDGPUAsmGFX*.rst docs") + parser.add_argument("--out-dir", default=None, help="output directory for generated .tsv files") + args = parser.parse_args(argv) + try: + if not args.llvm_docs_dir.strip(): + raise ValueError("llvm_docs_dir must not be empty") + if args.out_dir is not None and not args.out_dir.strip(): + raise ValueError("--out-dir must not be empty") + docs = Path(args.llvm_docs_dir) + out_dir = OUT if args.out_dir is None else Path(args.out_dir) + gfx1013_files, rdna2_files = _validate_docs_dir(docs) + _validate_out_dir_and_targets(out_dir) + gfx1013 = llvm_forms(*gfx1013_files) + rdna2 = llvm_forms(*rdna2_files) + x64 = x64_forms() + write("gfx1013.tsv", LLVM_SOURCE + "AMDGPUAsmGFX10/1011/1013.rst", gfx1013, out_dir=out_dir) + write("rdna2.tsv", LLVM_SOURCE + "AMDGPUAsmGFX1030.rst", rdna2, out_dir=out_dir) + write("x64_zen2.tsv", "iced-x86 1.21.0 mnemonics, Zen 2 user-mode CPUID groups", x64, out_dir=out_dir) + except (OSError, ValueError) as error: + sys.stderr.write(f"form_reference: {error}\n") + return 1 + return 0 + + if __name__ == "__main__": - if len(sys.argv) != 2: - raise SystemExit(__doc__) - docs = Path(sys.argv[1]) - write("gfx1013.tsv", LLVM_SOURCE + "AMDGPUAsmGFX10/1011/1013.rst", - llvm_forms(*(docs / f"AMDGPUAsmGFX{v}.rst" for v in ("10", "1011", "1013")))) - write("rdna2.tsv", LLVM_SOURCE + "AMDGPUAsmGFX1030.rst", llvm_forms(docs / "AMDGPUAsmGFX1030.rst")) - write("x64_zen2.tsv", "iced-x86 1.21.0 mnemonics, Zen 2 user-mode CPUID groups", x64_forms()) + raise SystemExit(main()) From 8ed238cad7feea21ea0a4d95ee6c5c9930cd09c1 Mon Sep 17 00:00:00 2001 From: Roan System Date: Thu, 26 Nov 2026 03:10:20 +0100 Subject: [PATCH 058/240] tests: draw a slot 57 depth-only pair into D32 and compare depth with the CPU (Part of #2413) (#2680) * startup: write nothing for the null export target in gfx2hlsl The null target carries no channel; its only effect is the vm discard emitted before it. Same change as the open #2026, so a rebase onto it drops this commit. Co-Authored-By: Claude Opus 5.5 * startup: translate slot 57 mesh requests with a depth-only pixel stage (Part of #2413) A pixel stage whose only export is the null target was refused with 'slot 57 mesh with a depth-only pixel stage is not covered'. It now translates with the pair: the pixel stage has no SV_Target, keeps the vm discard of an alpha test, and the manifest has an empty targets line. Co-Authored-By: Claude Opus 5.5 * startup: refuse a slot 57 null export mixed with another export (Part of #2413) The slot 57 depth-only profile is a pixel stage whose only export target is null. A null export before or after an mrt0, mrtz or param0 export passed the role check and was published; it is now refused in translate_mesh57 before any source or manifest is written. The general pixel path keeps its mixed forms. Co-Authored-By: Claude Opus 5.5 * tests: draw a slot 57 depth-only pair and compare depth with the CPU A source-built gfx1013 pixel stage narrows EXEC with v_cmpx and exports only to the null target. The pair is drawn twice into a D32 target cleared to the sentinel 1.0 (depth test LESS) on WARP and hardware; colour must stay cleared and depth must match the CPU rasteriser, so covered and discarded pixels are told apart. A reference without the depth writes and the same mesh without the discard must each fail. Offline controls refuse the drawn stage with a colour export before its null export (the slot 57 mixed-export refusal) and a mismatched pair in both directions, and check that pending_keys needs both bytecodes. Part of #2413 --------- Co-authored-by: NiiRoZz Co-authored-by: Claude Opus 5.5 Co-authored-by: Royoo <3230853833@qq.com> --- CMakeLists.txt | 5 + docs/experiments.md | 19 ++- tests/startup_mesh57_skeleton_check.py | 163 +++++++++++++++++++++++++ 3 files changed, 184 insertions(+), 3 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 2f22ae5ec..3c0883da7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -9343,6 +9343,11 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/startup_mesh57_skeleton_check.py" shift "${DXC_EXECUTABLE}" "$" ${adapter}) set_tests_properties(startup_mesh57_skeleton_wave_shift_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + # A slot 57 pair whose pixel stage exports only to the null target, drawn depth-only (#2413 T5). + add_test(NAME startup_mesh57_skeleton_depth_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_mesh57_skeleton_check.py" depth "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_mesh57_skeleton_depth_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) add_test(NAME startup_mesh57_formatted_load_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_mesh57_skeleton_check.py" formatted "${DXC_EXECUTABLE}" "$" ${adapter}) diff --git a/docs/experiments.md b/docs/experiments.md index 7e69d617f..97c7fad37 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9703,9 +9703,22 @@ the empty `targets` line, a control without the EXEC narrowing (no discard) and a null export followed by a position export (still refused). A slot 57 pixel stage that has the null export next to an `mrt0`, `mrtz` or `param0` export, in either order, is refused before any source or manifest is written; -the general pixel path keeps those mixed forms. Nothing is -drawn. The runtime does not load slot 57 results yet, so these draws are not -submitted. +the general pixel path keeps those mixed forms. The +`startup_mesh57_skeleton_depth_{warp,hardware}` CTest checks draw a +source-built depth-only pair (`v_interp_mov_f32`, `v_cmpx_lt_f32 0.5, v0`, +`exp null off, off, off, off done vm`, `s_endpgm`) twice with +`offscreen_check --mesh-depth-pair` into a D32 target cleared to the sentinel +1.0, depth test LESS. Colour must stay cleared and depth must match the CPU +rasteriser: of 259 covered pixels, 181 keep a written depth and 78 keep the +sentinel only because of the discard. A reference without the depth writes +(181 mismatches) and the same mesh with a null export that does not discard +(134 mismatches) must each fail. The offline check also refuses the drawn +stage with a colour export before its null export, a pair whose pixel stage +does not match its key, and the mesh shapes the paired path refuses next to +the depth-only pixel stage; it checks that `pending_keys` keeps +the pair pending until both `.ms57.cso` and `.ps57.cso` are complete. The +runtime does not load slot 57 results yet, so these draws are not submitted +through the guest path. The pending scan checks the DXContainer header and file length for every required slot 57 bytecode artifact. A `ps none` result needs the mesh artifact diff --git a/tests/startup_mesh57_skeleton_check.py b/tests/startup_mesh57_skeleton_check.py index b3814fc88..4024f7579 100644 --- a/tests/startup_mesh57_skeleton_check.py +++ b/tests/startup_mesh57_skeleton_check.py @@ -3,6 +3,7 @@ usage: startup_mesh57_skeleton_check.py startup_mesh57_skeleton_check.py binary startup_mesh57_skeleton_check.py draw + startup_mesh57_skeleton_check.py depth startup_mesh57_skeleton_check.py formatted startup_mesh57_skeleton_check.py shift startup_mesh57_skeleton_check.py exchange @@ -17,6 +18,10 @@ refused with its own message. `binary` compares the embedded words with llvm-mc. `draw` compiles the request path's output (ms_6_5, ps_6_0), draws it and compares the read-back target with a CPU rasteriser written here; a reference with one wrong pixel must fail. +`depth` compiles the pair with a pixel stage that exports only to the null target (a depth-only pass), draws it +twice into a depth buffer cleared to the sentinel 1.0 with depth test LESS, and compares colour (left cleared) and +depth with the CPU rasteriser; a reference without the depth writes, and the same mesh with a null-export stage +that does not discard, must each fail. The exchange mode uses the runtime-published request and the same pixel comparison. """ import os @@ -45,6 +50,21 @@ PIXEL_ASM = ('v_interp_mov_f32 v0, p0, attr0.x\nv_interp_mov_f32 v1, p0, attr0.y\nv_interp_mov_f32 v2, p0, attr0.z\n' 'v_interp_mov_f32 v3, p0, attr0.w\nexp mrt0 v0, v1, v2, v3 done vm\ns_endpgm\n') PIXEL = 'c8020002 c8060102 c80a0202 c80e0302 f800180f 03020100 bf810000'.split() +# A depth-only pixel stage: no colour output, only the null-target export (done, vm, no channel). Lanes whose flat +# attribute 0 red is not above 0.5 leave EXEC, so the vm export kills them and they write no depth. +DEPTH_PIXEL_ASM = ('v_interp_mov_f32 v0, p0, attr0.x\nv_cmpx_lt_f32_e32 0.5, v0\n' + 'exp null off, off, off, off done vm\ns_endpgm\n') +DEPTH_PIXEL = 'c8020002 7c2200f0 f8001890 00000000 bf810000'.split() +NULL_EXPORT = DEPTH_PIXEL.index('f8001890') +# The drawn stage with exp mrt0 v0, v0, v0, v0 inserted before its null export (after the v_cmpx), then the drawn +# stage reading attribute 1, which the mesh does not export. The other mixed forms (mrtz, param0, pos0, both orders, +# no EXEC narrowing) are covered by startup_mesh57_depth_only_check.py. +DEPTH_PIXEL_MUTANTS = ( + ('a colour write next to the drawn null export', DEPTH_PIXEL[:NULL_EXPORT] + ['f800000f', '00000000'] + DEPTH_PIXEL[NULL_EXPORT:], + 'slot 57 pixel stage mixes the null export with another export'), + ('a depth-only pixel stage reading an attribute the mesh does not export', ['c8020402'] + DEPTH_PIXEL[1:], + 'pixel stage reads attributes [1] the vertex stage does not export'), +) # Overwrite red after the raw colour load; green, blue and alpha still come from its other three words. COLOUR_LOAD = 'buffer_load_dwordx4 v[20:23], v4, s[16:19], 0 offen offset:192' @@ -407,6 +427,58 @@ def expect(what, got, want): ) +def depth_only_controls(): + """A pixel stage that exports only to the null target is published as a depth-only pair.""" + with tempfile.TemporaryDirectory() as tmp: + key, result = request(tmp, MESH, DEPTH_PIXEL) + expect('the depth-only pair translates', result, 'ok') + if result == 'ok': + names = sorted(p.name[16:] for p in Path(tmp).iterdir() if not p.name.startswith('req_')) + expect('depth-only pair source and manifest', names, ['.ms57.hlsl', '.ms57.txt', '.ps57.hlsl']) + manifest = (Path(tmp) / ('%016x.ms57.txt' % key)).read_text().splitlines() + # The pixel stage is bound but names no render target: an empty targets line, never 'ps none'. + expect('depth-only manifest stage information', + [line for line in manifest if line.startswith(('params ', 'targets', 'wmask ', 'ps '))], + ['params 1', 'targets ']) + pixel = (Path(tmp) / ('%016x.ps57.hlsl' % key)).read_text() + expect('depth-only pixel stage has no output', ('void main(PSIn i)' in pixel, 'SV_Target' in pixel, + 'SV_Depth' in pixel), (True, False, False)) + expect('depth-only pixel stage keeps the vm discard', pixel.count('discard;'), 1) + # The existing manifest reader (pending_keys): the pair is complete only with both bytecodes. + expect('depth-only manifest is enough in source-only mode', G.pending_keys(tmp, False), []) + part = struct.pack('<4sI4s', b'DXIL', 4, b'test') + bytecode = struct.pack('<4s16sHHIII', b'DXBC', bytes(16), 1, 0, 36 + len(part), 1, 36) + part + os.environ.pop('X2W_FXC') + (Path(tmp) / ('%016x.ms57.cso' % key)).write_bytes(bytecode) + expect('a depth-only pair without its pixel bytecode is pending (unlike ps none)', G.pending_keys(tmp, False), [key]) + pixel_bytecode = Path(tmp) / ('%016x.ps57.cso' % key) + pixel_bytecode.write_bytes(bytecode) + expect('a depth-only pair with both bytecodes is done', G.pending_keys(tmp, False), []) + pixel_bytecode.write_bytes(bytecode[:-1]) + expect('a depth-only pair with truncated pixel bytecode is pending', G.pending_keys(tmp, False), [key]) + os.environ['X2W_FXC'] = '' + for what, pixel, reason in DEPTH_PIXEL_MUTANTS: + with tempfile.TemporaryDirectory() as tmp: + key, result = request(tmp, MESH, pixel) + expect(what, result, 'unsupported: ' + reason) + expect(what + ': only the refusal is published', + sorted(p.name for p in Path(tmp).iterdir() if not p.name.startswith('req_')), ['%016x.fail' % key]) + # A pair whose pixel stage is not the one the key was computed over, in both directions. + for what, keyed, stored in (('a colour stage stored under a depth-only key', DEPTH_PIXEL, PIXEL), + ('a depth-only stage stored under a colour key', PIXEL, DEPTH_PIXEL)): + with tempfile.TemporaryDirectory() as tmp: + key = G.mesh57_key(code(MESH), code(keyed), root()) + for ext, data in (('.root', root()), ('.ps57', code(stored)), ('.m57', code(MESH))): + (Path(tmp) / ('req_%016x%s' % (key, ext))).write_bytes(data) + expect(what, G.translate_request(tmp, key), 'unsupported: slot 57 mesh request key mismatch') + expect(what + ': only the refusal is published', + sorted(p.name for p in Path(tmp).iterdir() if not p.name.startswith('req_')), ['%016x.fail' % key]) + # The mesh shapes the paired path refuses stay refused, with the same message, next to a depth-only pixel stage. + for what, mesh, reason in REFUSALS: + with tempfile.TemporaryDirectory() as tmp: + expect(what + ' (depth-only pair)', request(tmp, mesh, DEPTH_PIXEL)[1], 'unsupported: ' + reason) + + def controls(): os.environ['X2W_FXC'] = '' # sources and manifest only; the draw mode compiles with tempfile.TemporaryDirectory() as tmp: @@ -511,6 +583,7 @@ def controls(): # exp null off, off, off, off done vm; s_endpgm: a pixel stage without a colour output. with tempfile.TemporaryDirectory() as tmp: expect('a depth-only pixel stage', request(tmp, MESH, 'f8001890 00000000 bf810000'.split())[1], 'ok') + depth_only_controls() # The request path refuses a missing s_endpgm earlier; the walk takes the last instruction as the terminator # unread, so the pipeline refuses it too (s_nop in its place). try: @@ -776,6 +849,94 @@ def draw(dxc, renderer, adapter, publisher=None): return 0 +# ---- depth: the depth-only pair drawn twice into a D32 target cleared to 1.0, depth test LESS ------------------ +# Per triangle and draw: (depth, kept). A kept triangle has attribute 0 red 1.0 at its three vertices, a killed one +# 0.25, so the depth-only pixel stage keeps or discards all of its pixels. The four triangles cover: the second draw +# behind the first, the second in front, a first draw killed, both killed. +DEPTH_DRAWS = (((0.25, True), (0.75, True), (0.125, False), (0.5, False)), + ((0.75, True), (0.375, True), (0.625, True), (0.875, False))) + + +def depth_scene(points, indices, draws, honour_kill=True): + """The upload of each draw and the expected colour and depth images (cleared to black and 1.0).""" + uploads, depth = [], [1.0] * (SIDE * SIDE) + words = [a | b << 10 | c << 20 for a, b, c in indices] + for draw in draws: + data = bytearray(buffer(points, [(0, 0, 0, 0)] * 12, words)) + for t, (z, kept) in enumerate(draw): + for slot in indices[t]: + struct.pack_into(' 100 and killed > 50, (written, killed) + # Depth is cleared to the sentinel 1.0 and every drawn depth is below it, so a discarded pixel keeps the sentinel. + covered = pixels(unkilled, cleared) + print('covered %d pixels: %d keep a written depth, %d keep the sentinel only because of the discard, ' + '%d differ from a draw without the discard' % (covered, written, covered - written, killed)) + with tempfile.TemporaryDirectory() as tmp: + key, result = request(tmp, MESH, DEPTH_PIXEL) + expect('the depth-only pair translates and compiles', result, 'ok') + # The same mesh with a null export and no discard: what a pass without the pixel stage would draw. + bare, bare_result = request(tmp, MESH, 'f8001890 00000000 bf810000'.split()) + expect('the pixel stage without discard translates and compiles', bare_result, 'ok') + if result != 'ok' or bare_result != 'ok': + return 0 + names = sorted(p.name[16:] for p in Path(tmp).iterdir() if p.name.startswith('%016x' % key)) + expect('depth-only compiled files', names, ['.ms57.cso', '.ms57.hlsl', '.ms57.txt', '.ps57.cso', '.ps57.hlsl']) + manifest = (Path(tmp) / ('%016x.ms57.txt' % key)).read_text().splitlines() + uds = {tuple(fields[2:]): int(fields[1]) for fields in map(str.split, manifest) if fields and fields[0] == 'udsrc'} + constants = bytearray(1024) + struct.pack_into(' %s' % (label, pair, depth_errors, run.returncode, + 'as expected' if ok else 'UNEXPECTED')) + if not ok or label == 'baseline': + print(run.stdout + run.stderr) + expect('depth draw: ' + label, ok, True) + return 0 + + def draw_formatted(dxc, renderer, adapter): os.environ['X2W_DXC'] = dxc os.environ.pop('X2W_FXC', None) @@ -879,6 +1040,8 @@ def main(argv): binary(argv[2]) elif argv[1:2] == ['draw'] and len(argv) == 5: status = draw(*argv[2:]) + elif argv[1:2] == ['depth'] and len(argv) == 5: + status = draw_depth(*argv[2:]) elif argv[1:2] == ['formatted'] and len(argv) == 5: status = draw_formatted(*argv[2:]) elif argv[1:2] == ['shift'] and len(argv) == 5: From f213cf6373aaada48cffe70da4de7deca0335ebf Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Thu, 26 Nov 2026 03:10:31 +0100 Subject: [PATCH 059/240] gfx2hlsl: prove a compute buffer load with a uniform address uniform for v_readfirstlane_b32 (#2446) * gfx2hlsl: prove a compute buffer load with a uniform address uniform v_readfirstlane_b32 needs a vector source with the same value in every active lane. A buffer_load_dword or buffer_load_format_x in a compute program reads a read-only descriptor (a descriptor used for a load and a store is already refused), so with a uniform VGPR index or offset, a uniform scalar offset and exec known in the entry block, every lane reads the same dword. Mark the destination uniform there. The value has no recomputable expression, so reads past the entry block still refuse. Tests: positive cases plus negative controls for a varying VGPR offset, a varying scalar offset, a graphics stage, no stage kind, unknown exec, a read after the entry block and a varying overwrite. Co-Authored-By: Claude Sonnet 5.5 * test: WARP readback for readfirstlane of a uniform buffer load Compute case N: v_readfirstlane_b32 of a buffer load at a uniform address, xored into each lane's own word, dispatched on D3D12 and compared with a CPU reference. A per-lane address is refused. Control n-dropped-broadcast must mismatch. --------- Co-authored-by: Claude Sonnet 5.5 Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> Co-authored-by: tedin7 --- CMakeLists.txt | 2 +- tests/startup_gfx2hlsl_compute_check.py | 34 +++++++++++++++++++ ...up_gfx2hlsl_readfirstlane_uniform_check.py | 32 ++++++++++++++++- tools/startup/gfx2hlsl.py | 18 +++++++++- 4 files changed, 83 insertions(+), 3 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 3c0883da7..5b9ba4896 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3990,7 +3990,7 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(startup_gfx2hlsl_compute_mbcnt_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) foreach(control IN ITEMS swapped-axes dropped-store b-offset c-unpredicated f-peer f-broadcast g-swapped-offsets g-overlap - j-scalar-dropped h-inner-unpredicated k-block-entered m-else-unswitched) + j-scalar-dropped h-inner-unpredicated k-block-entered m-else-unswitched n-dropped-broadcast) add_test(NAME startup_gfx2hlsl_compute_${control}_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_compute_check.py" control ${control} "${DXC_EXECUTABLE}" "$" ${adapter}) diff --git a/tests/startup_gfx2hlsl_compute_check.py b/tests/startup_gfx2hlsl_compute_check.py index 1d7b56d17..c7befcbb8 100644 --- a/tests/startup_gfx2hlsl_compute_check.py +++ b/tests/startup_gfx2hlsl_compute_check.py @@ -397,6 +397,32 @@ def saveexec_fixture(): 'L-unorm': (1 << 12) | 1 | (4 << 3) | (7 << 6) | (5 << 9), # one, X, W, Y } +# Case N: v_readfirstlane_b32 of a buffer load whose address is the same for every lane (offset 0, no VGPR), xored +# into each lane's own read-buffer word. Lane i stores word0 ^ word[i]. SOURCE_N_VARYING loads the readfirstlane +# source at a per-lane offset (v0), which is not provably uniform and must be refused. +SOURCE_N = """\ +s_mov_b32 s10, s6 +s_mov_b32 s11, 0 +s_load_dwordx8 s[12:19], s[10:11], 0x0 +s_waitcnt lgkmcnt(0) +buffer_load_dword v1, off, s[12:15], 0 +s_waitcnt vmcnt(0) +v_readfirstlane_b32 s20, v1 +v_lshlrev_b32 v4, 2, v0 +buffer_load_dword v2, v4, s[12:15], 0 offen +s_waitcnt vmcnt(0) +v_xor_b32 v3, s20, v2 +buffer_store_dword v3, v4, s[16:19], 0 offen +s_endpgm +""" +WORDS_N = bytes.fromhex( + '06038abe' '80038bbe' '05030cf4000000fa' '7fc08cbf' '000030e000010380' + '703f8cbf' '0105287e' '82000834' '001030e004020380' + '703f8cbf' '1404063a' '001070e004030480' '000081bf') +N_LOAD = bytes.fromhex('000030e000010380') +N_LOAD_VARYING = bytes.fromhex('001030e000010380') +WORDS_N_VARYING = WORDS_N.replace(N_LOAD, N_LOAD_VARYING, 1) + # Each group uses its ID as a low addend, overwrites that SGPR, and stores the # low word, high word and SCC left by the high add. The fourth word stays untouched. SOURCE_CARRY = """\ @@ -436,6 +462,7 @@ def saveexec_fixture(): 'K': (SOURCE_K, WORDS_K, USER7 | TGID_X | tidig(1), (8, 1, 1), (4, 1, 1)), 'G': (SOURCE_G, WORDS_G, USER7 | TGID_X | (1 << 15), (64, 1, 1), (2, 1, 1)), **{name: (SOURCE_L, WORDS_L, USER7, (16, 1, 1), (1, 1, 1)) for name in L_WORD3}, + 'N': (SOURCE_N, WORDS_N, USER7 | tidig(1), (16, 1, 1), (1, 1, 1)), } # Single instructions the controls splice into case A before its store, recorded from llvm-mc 15. @@ -639,6 +666,9 @@ def expected(name): result = (one, one if data[at] == 255 else 0, one, 0) out[4 * lane:4 * lane + 4] = result return out + if name == 'N': + out[:16] = [input_word(0) ^ input_word(lane) for lane in range(16)] + return out producer_offsets = {'G': (1, 32), 'G-offset0-only': (31, 0), 'G-offset1-only': (0, 31)} if name in producer_offsets: # The original fill begins at dword 4, the single-field variants at dword 0. @@ -1426,6 +1456,9 @@ def phi(zero, write, read, between=(), inside=()): refused('compute d16 image load requires validated SRV formats', lambda: pipeline.cs.image(['v12', 'v[0:1]', 's[24:31]'], ['dim:SQ_RSRC_IMG_2D', 'dmask:0x3', 'd16'], 'load')) + # A readfirstlane of a buffer load at a uniform address translates; at a per-lane address it is refused. + assert 's20 = v1;' in translate('N').hlsl_cs() + refused('v_readfirstlane_b32 requires a proven uniform source', lambda: translate('N', code=WORDS_N_VARYING).hlsl_cs()) print('compute entry, numthreads, masked bit counts, manifest, offen store forms and the store, descriptor, execz and sample ' 'refusals pass') @@ -1470,6 +1503,7 @@ def check_binary(llvm_mc): 'g-swapped-offsets': ('G', 'v6 = lds[(a + 20u) >> 2];\n v7 = lds[(a + 144u) >> 2];', 'v6 = lds[(a + 144u) >> 2];\n v7 = lds[(a + 20u) >> 2];'), 'g-overlap': ('G', 'v7 = lds[(a + 144u)', 'v7 = lds[(v6 + 144u)'), + 'n-dropped-broadcast': ('N', 'v3 = s20 ^ v2;', 'v3 = v2;'), # lane i stores word[i], not word0 ^ word[i] 'l-byte-offset': ('L-uint', 'a = v0 * ud2 + v1 + 2;', 'a = v0 * ud2 + 2;'), 'l-swizzle': ('L-unorm', 'v6 = ((ud3 >> 3)', 'v6 = ((0u >> 3)'), 'l-integer-one': ('L-uint', 'c1 = w >> 16; c2 = 0u; c3 = 1u; one = 1u;', 'c1 = w >> 16; c2 = 0u; c3 = 1u;'), diff --git a/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py b/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py index f8369ce7f..b52af84b2 100644 --- a/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py +++ b/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py @@ -28,7 +28,7 @@ def resource(self, key, kind): ALIAS_LOAD = 's_buffer_load_dwordx2 s[2:3], s[4:7], s2' -def run(*instructions, exec_known=True): +def run(*instructions, exec_known=True, kind=None): """Translate disassembly text using the same dispatch and branch scan as a real stage.""" s = G.Stage.__new__(G.Stage) s.pipe, s.lines = Pipe(), [] @@ -37,6 +37,8 @@ def run(*instructions, exec_known=True): s.sym[3] = ('fixed_buffer_word',) s.used_s, s.used_v, s.masks = set(), set(), set() s.exec_known = exec_known + if kind: + s.kind = kind s.ins = [(4 * i, 4, asm.split()[0], asm) for i, asm in enumerate(instructions)] try: s.translate() @@ -209,6 +211,34 @@ def run(*instructions, exec_known=True): got = run('v_mov_b32_e32 v7, s2', READ, exec_known=False) check('unknown exec refused', got == REFUSAL, repr(got)) +# A compute load through a read-only descriptor with a uniform address is uniform; the value has no recomputable +# expression, so only the entry block reads it. +LOAD_OFF = 'buffer_load_dword v7, off, s[4:7], s2' +LOAD_OFFEN = 'buffer_load_dword v8, v7, s[4:7], 0 offen' +got = run(LOAD_OFF, READ, kind='cs') +check('uniform scalar offset load accepted', got[-2:] == ['v7 = r0.Load(a + 0);', 's9 = v7;'], repr(got)) +got = run(MOVE, LOAD_OFFEN, 'v_readfirstlane_b32 s9, v8', kind='cs') +check('uniform vgpr offset load accepted', got[-1] == 's9 = v8;' and len(got) == 4, repr(got)) +got = run(MOVE, 'buffer_load_dword v7, v7, s[4:7], 0 offen', READ, kind='cs') +check('load overwriting its uniform address accepted', got[-1] == 's9 = v7;', repr(got)) +for label, instructions, kind, known in ( + ('load with a varying vgpr offset', ('buffer_load_dword v8, v0, s[4:7], 0 offen', 'v_readfirstlane_b32 s9, v8'), 'cs', True), + ('load with a varying scalar offset', (COMPARE, 'buffer_load_dword v7, off, s[4:7], s2', READ), 'cs', True), + ('load in a graphics stage', (LOAD_OFF, READ), 'ps', True), + ('load without a stage kind', (LOAD_OFF, READ), None, True), + ('load with unknown exec', (LOAD_OFF, READ), 'cs', False), + ('load after the entry block', (LOAD_OFF, 's_cbranch_scc0 label_0010', READ, 's_endpgm', 's_endpgm'), 'cs', True), + ('load then a varying overwrite', (LOAD_OFF, 'v_mov_b32_e32 v7, v0', READ), 'cs', True)): + got = run(*instructions, kind=kind, exec_known=known) + check(f'{label} refused', got == REFUSAL, repr(got)) +original = G.UNIFORM_LOADS +G.UNIFORM_LOADS = frozenset() +try: + got = run(LOAD_OFF, READ, kind='cs') + check('control: load refused without tracking', got == REFUSAL, repr(got)) +finally: + G.UNIFORM_LOADS = original + # Older probes may provide either no tracker or only part of the tracking state. for present in ((), ('uniform_v',), ('uniform_v', 'varying_s')): s = G.Stage.__new__(G.Stage) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 0a537d1f8..b5e5a18d7 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -914,6 +914,8 @@ def smem_mods(mods): 'v_mul_f32', 'v_fma_f32', 'v_fmaak_f32', 'v_rcp_f32', 'v_med3_f32', 'v_mov_b32', )) +UNIFORM_LOADS = frozenset(('buffer_load_dword', 'buffer_load_format_x')) + # DPP quad_perm selections that exchange lanes of a 2x2 pixel quad (lane = 2 * y + x), with the SM 6.0 intrinsic. QUAD_SWAPS = {(1, 0, 3, 2): 'QuadReadAcrossX', (2, 3, 0, 1): 'QuadReadAcrossY', (3, 2, 1, 0): 'QuadReadAcrossDiagonal'} @@ -3026,6 +3028,20 @@ def one(self, name, asm): sources = [re.sub(r'^-(?=[^\d.])', '', tok).strip('|') for tok in sources] if sources and all(self.uniform_source(tok) for tok in sources): dst = candidate[1] + # A compute load through a read-only descriptor (a descriptor is never both loaded and stored) with a uniform + # address reads the same dword in every lane. Entry block only: the value has no recomputable expression. + loaded = (dst is None and base in UNIFORM_LOADS and len(ops) == 4 and self.tracks_uniformity() and + getattr(self, 'kind', None) == 'cs' and not getattr(self, 'past_entry', True) and + getattr(self, 'exec_known', False) and + all(m in ('idxen', 'offen', 'glc', 'slc', 'dlc') or m.startswith('offset:') for m in mods) and + not ('idxen' in mods and 'offen' in mods) and (ops[1] == 'off') == ('idxen' not in mods and 'offen' not in mods) and + (ops[1] == 'off' or self.uniform_source(ops[1])) and self.uniform_source(ops[3])) + if loaded: + candidate = reg_range(ops[0]) + if candidate and candidate[0] == 'v' and candidate[1] == candidate[2]: + dst = candidate[1] + else: + loaded = False self.last_v = None term = self.lower(base, asm, ops, mods) uniform_written = self._uniform_written @@ -3046,7 +3062,7 @@ def one(self, name, asm): # Proven sources are scalars, constants and VGPRs; each VGPR needs its own current expression. expr = self.last_v[1] if self.last_v and self.last_v[0] == dst else None vs = [int(n) for n in re.findall(r'\bv(\d+)\b', expr or '')] - if expr is None or any(n not in self.uniform_expr for n in vs): + if expr is None or loaded or any(n not in self.uniform_expr for n in vs): self.uniform_expr.pop(dst, None) else: self.uniform_expr[dst] = re.sub(r'\bv(\d+)\b', lambda m: '(%s)' % self.uniform_expr[int(m[1])], From f27737c366cd32ab927363c933c7d9493d1d2ace Mon Sep 17 00:00:00 2001 From: SimSalabimse <83839581+SimSalabimse@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:12:07 +0100 Subject: [PATCH 060/240] shader: lower s_ff1_i32 on a general scalar in gfx2hlsl (#2022 Item F) (#2639) * shader: lower s_ff1 of a general scalar (#2022 Item F) Keep the compute-entry exec_lo fold to lane 0, and add firstbitlow / lo-then-hi scan for ordinary SGPR and immediate sources. Lane masks and descriptor words stay refused. CPU fixture with a negative control. Co-authored-by: SimSalabimse * shader: keep s_ff1 b32 general; leave b64 SGPR pair to #2072 Refuse live s_ff1_i32_b64 SGPR pairs (owned by open #2072). Keep zero-extended b64 immediates and add a D3D12 UAV dispatch fixture for the b32 edge words (including firstbitlow(0) == 0xffffffff). Co-authored-by: SimSalabimse * shader: keep s_ff1_i32_b64 out of SCALAR_BITS after rebase Main's SCALAR_BITS install was overwriting Stage.op_s_ff1_i32_b64. Leave the dedicated handler for zero-extended immediates (#2022 F / #2072). Co-authored-by: SimSalabimse * shader: lower s_ff1_i32_b64 SGPR pairs after #2072 merge Keep the Stage handler for zero-extended immediates and emit the same 64-bit firstbitlow scan for register pairs so bit_scan CI stays green. Co-authored-by: SimSalabimse * test: read back s_ff1_i32_b64 of a live SGPR pair on D3D12 (lo/hi cases against a CPU reference) --------- Co-authored-by: Cursor Agent Co-authored-by: SimSalabimse Co-authored-by: tedin7 --- .github/workflows/windows.yml | 1 + AGENTS.md | 1 + CMakeLists.txt | 11 + docs/experiments.md | 14 + tests/startup_gfx2hlsl_compute_check.py | 3 +- tests/startup_gfx2hlsl_s_bit_scan_check.py | 4 +- tests/startup_gfx2hlsl_s_ff1_check.py | 401 +++++++++++++++++++++ tools/startup/gfx2hlsl.py | 83 ++++- 8 files changed, 507 insertions(+), 11 deletions(-) create mode 100644 tests/startup_gfx2hlsl_s_ff1_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index b7a494dda..7e383a04e 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -304,6 +304,7 @@ jobs: tests/startup_gfx2hlsl_s_abs_check.py \ tests/startup_gfx2hlsl_s_bitset_check.py \ tests/startup_gfx2hlsl_s_flbit_check.py \ + tests/startup_gfx2hlsl_s_ff1_check.py \ tests/startup_gfx2hlsl_fma_mix_check.py \ tests/startup_gfx2hlsl_shift64_check.py \ tests/startup_gfx2hlsl_mul_mad_i24_check.py \ diff --git a/AGENTS.md b/AGENTS.md index 11f41b9b5..1c9d01c42 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -176,6 +176,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_s_abs_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_s_bitset_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_s_flbit_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_s_ff1_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_fma_mix_check.py ./out/pe-env/bin/python -B tests/startup_image_2d_array_check.py ./out/pe-env/bin/python -B tests/startup_image_sample_a16_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 5b9ba4896..77d3029a7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3355,6 +3355,17 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(startup_gfx2hlsl_s_flbit_dispatch_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl lowers s_ff1_i32_b32 of a general scalar and s_ff1_i32_b64 of a zero-extended + # immediate (#2022 Item F); live SGPR-pair b64 is owned by open #2072. CPU evaluation, then + # a D3D12 UAV readback on WARP/hardware (same dispatch pattern as pack_absdiff). + add_test(NAME startup_gfx2hlsl_s_ff1 COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_ff1_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_s_ff1_dispatch_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_ff1_check.py" dispatch "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_gfx2hlsl_s_ff1_dispatch_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl lowers v_cube{id,sc,tc,ma}_f32: device-free translation controls. add_test(NAME startup_gfx2hlsl_cube_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_cube_check.py") diff --git a/docs/experiments.md b/docs/experiments.md index 97c7fad37..8c9b7049a 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -8115,6 +8115,20 @@ destination with a known bit index folds. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_s_bitset$' -V` (or `python3 -B tests/startup_gfx2hlsl_s_bitset_check.py`). The fixture is CPU-only; Windows WARP/hardware draws are left for an independent retest. +**Scalar find-first-one.** Startup translation lowers `s_ff1_i32_b32` of a +general scalar to `firstbitlow` (0xffffffff when the word is zero), matching +`pixel_aot` / Mesa. The compute-entry special case on `exec_lo` still folds to +lane 0. SCC is unchanged. Lane masks and descriptor-bearing sources are +refused. `s_ff1_i32_b64` accepts a 32-bit SOP1 literal/inline (ISA zero-extends +the high word to 0) and folds it, and also lowers a live SGPR pair with the same +64-bit firstbitlow scan as the scalar bit-scan forms. Run +`ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_s_ff1$' -V` +(or `python3 -B tests/startup_gfx2hlsl_s_ff1_check.py`). The `_dispatch_warp` +/ `_dispatch_hardware` variants compile the translated `firstbitlow` into a +compute shader and compare UAV readback for inputs 0, 1, 0x80000000 and +0x00010000 (and the zero-extended b64 immediates) against the same reference: +`ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_s_ff1_dispatch_warp$' -V`. +[Refs #2022](https://github.com/R0Y00/Xbox2Windows/issues/2022) Item F. **Scalar find-first-bit-high.** Startup translation lowers `s_flbit_i32_b32` to `S0 == 0 ? 0xffffffff : 31 - firstbithigh(S0)`, matching `pixel_aot` / diff --git a/tests/startup_gfx2hlsl_compute_check.py b/tests/startup_gfx2hlsl_compute_check.py index c7befcbb8..4f45f0b74 100644 --- a/tests/startup_gfx2hlsl_compute_check.py +++ b/tests/startup_gfx2hlsl_compute_check.py @@ -1057,7 +1057,8 @@ def check_controls(): for code in (bytes.fromhex('8003febe') + ff1 + end, ff1 + bytes.fromhex('feff82bf') + end): refused('compute entry EXEC mask', lambda: translate('A', code=code)) - refused('requires compute exec_lo', lambda: translate('A', code=bytes.fromhex('6a1385be') + end)) + # vcc_lo is a lane mask; general-scalar ff1 (#2022 Item F) still refuses it. + refused('lane mask', lambda: translate('A', code=bytes.fromhex('6a1385be') + end)) assert 's5 = 0u;' in translate('A-ff1').hlsl_cs() assert expected('A-ff1') != expected('A') check_lds() diff --git a/tests/startup_gfx2hlsl_s_bit_scan_check.py b/tests/startup_gfx2hlsl_s_bit_scan_check.py index 0b97327eb..34cc810d7 100644 --- a/tests/startup_gfx2hlsl_s_bit_scan_check.py +++ b/tests/startup_gfx2hlsl_s_bit_scan_check.py @@ -131,7 +131,9 @@ def ref(name, value): repr(lines)) # Refusals that must not widen: a 64-bit scan needs a register pair, 32-bit one register, and no lane-mask data. -check('b64 refuses an inline constant source', refused('s_ff1_i32_b64', 3, 0x80)) +# s_ff0 keeps the pair-only SCALAR_BITS path (inline constants refused). s_ff1_i32_b64 also accepts a +# zero-extended 32-bit immediate (#2022 Item F), so the pair-only refusal is checked on s_ff0. +check('b64 refuses an inline constant source', refused('s_ff0_i32_b64', 3, 0x80)) check('b32 refuses exec destination', refused('s_bcnt1_i32_b32', EXEC_LO, 2)) check('b32 refuses m0 destination', refused('s_bcnt1_i32_b32', M0, 2)) check('b32 refuses exec source', refused('s_bcnt1_i32_b32', 3, EXEC_LO)) diff --git a/tests/startup_gfx2hlsl_s_ff1_check.py b/tests/startup_gfx2hlsl_s_ff1_check.py new file mode 100644 index 000000000..365a21521 --- /dev/null +++ b/tests/startup_gfx2hlsl_s_ff1_check.py @@ -0,0 +1,401 @@ +"""s_ff1_i32_b32 of a general scalar and s_ff1_i32_b64 immediates + SGPR pairs (#2022 Item F). + +usage: startup_gfx2hlsl_s_ff1_check.py + startup_gfx2hlsl_s_ff1_check.py dispatch + +RDNA 2 ISA SOP1: S_FF1_I32_B32 finds the lowest set bit of a 32-bit word (0xffffffff if zero); +SCC is unchanged. The compute-entry special case on exec_lo still folds to lane 0. Lane masks +and descriptor sources are refused. + +S_FF1_I32_B64 accepts a 32-bit SOP1 literal/inline (ISA zero-extends the high word to 0) and +folds it, and also lowers a live SGPR pair with the same 64-bit firstbitlow scan as the scalar +bit-scan forms. + +With `dispatch`, the b32 lowering runs as a compute shader on the adapter (D3D12 UAV +readback via offscreen_check, same pattern as startup_gfx2hlsl_pack_absdiff_check). The +reference is plain Python; the translated text is evaluated on the CPU without `dispatch`. +""" +import re +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import disasm_rdna2 as D # noqa: E402 +import gfx2hlsl as G # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import Expr # noqa: E402 + +MASK = 0xffffffff +SOP1 = {name: op for op, (name, _) in D.SOP1_OPS.items()} +WORDS = (0x00000000, 0xffffffff, 0x80000001, 0x00010020, 0x55555555, 0xaaaaaaaa, 0x12345678, 0x10) +# GPU cases from review: prove firstbitlow(0) == 0xffffffff and the named edge bits. +DRAW_B32 = (0x00000000, 0x00000001, 0x80000000, 0x00010000) +# b64 immediates only (hi forced to 0 by zero-extension). hi-nonzero is #2072. +IMMEDIATE_B64 = (0x00000000, 0x00000001, 0x00010000, 0x80000000) +# Live SGPR pair s4:s5 as (lo, hi): both zero, lo only, hi only, both set (lo wins), edge bits in each half. +PAIR_B64 = ((0, 0), (1, 0), (0, 1), (0, 0x80000000), (0, 0x10), (0x80000000, 0xffffffff), (0x00010000, 0x1), + (0xffffffff, 0xffffffff)) +SCC_UNSET = 2 +VCC_LO, EXEC_LO = 106, 126 + +failures = [] + + +def check(label, ok, detail=''): + print('%s: %s' % (label, 'ok' if ok else 'MISMATCH'), flush=True) + if not ok: + failures.append(label) + if detail: + print(' ' + detail) + + +def sop1(name, sdst, ssrc, lit=None): + word = struct.pack(' 105: + raise Unsupported('s_ff1_i32_b32 destination %s' % ops[0]) + if ops[1] == 'exec_lo': + if self.kind != 'cs': + raise Unsupported('s_ff1_i32_b32 of exec_lo outside compute') + if getattr(self, 'past_entry', False) or not getattr(self, 'exec_known', False): + raise Unsupported('s_ff1_i32_b32 requires the compute entry EXEC mask') + # At dispatch entry even the last partial wave starts at lane zero. + self.set_s(dst[1], '0u', ('const', 0)) + return None + if self.is_lane_mask(ops[0]) or self.is_lane_mask(ops[1]) or dst[1] in self.masks: + raise Unsupported('s_ff1_i32_b32 on a lane mask') + imm = re.fullmatch(r'-?(0x[0-9a-fA-F]+|\d+)', ops[1]) + if imm: + value = int(ops[1], 0) & 0xffffffff + # firstbitlow of zero is -1; otherwise the lowest set bit index. + folded = 0xffffffff if value == 0 else (value & -value).bit_length() - 1 + self.set_s(dst[1], '0x%08xu' % folded, ('const', folded)) + return None + src = reg_range(ops[1]) + if not src or src[0] != 's' or src[1] != src[2] or src[1] > 105: + raise Unsupported('s_ff1_i32_b32 source %s' % ops[1]) + if src[1] in self.masks: + raise Unsupported('s_ff1_i32_b32 on a lane mask') + sym = self.sym.get(src[1]) + if sym and sym[0] not in ('const', 'ud', 'fixed_buffer_word'): + raise Unsupported('s_ff1_i32_b32 on %s data' % sym[0]) + if sym and sym[0] == 'const': + value = sym[1] & 0xffffffff + folded = 0xffffffff if value == 0 else (value & -value).bit_length() - 1 + self.set_s(dst[1], '0x%08xu' % folded, ('const', folded)) + return None + self.set_s(dst[1], 'firstbitlow(%s)' % self.u(ops[1])) + return None + + def op_s_ff1_i32_b64(self, ops, mods): + """Find first set bit of a 64-bit source; SCC unchanged (#2022 Item F). + + A 32-bit SOP1 literal or inline constant zero-extends to 64 bits (high word 0) + and folds. An SGPR pair uses the same 64-bit firstbitlow scan as SCALAR_BITS + (`_ctz64` / #2072). Kept as a Stage method so immediates are not refused by the + pair-only SCALAR_BITS template. + """ + if mods or len(ops) != 2: + raise Unsupported('s_ff1_i32_b64 with %d operands, expected 2 unmodified' % len(ops)) dst = reg_range(ops[0]) if not dst or dst[0] != 's' or dst[1] != dst[2] or dst[1] > 105: - raise Unsupported('s_ff1_i32_b32 requires one SGPR destination') - if self.past_entry or not self.exec_known: - raise Unsupported('s_ff1_i32_b32 requires the compute entry EXEC mask') - # At dispatch entry even the last partial wave starts at lane zero. - # FF1 reports its index and leaves SCC unchanged. - self.set_s(dst[1], '0u', ('const', 0)) + raise Unsupported('s_ff1_i32_b64 destination %s' % ops[0]) + if self.is_lane_mask(ops[0]) or dst[1] in self.masks: + raise Unsupported('s_ff1_i32_b64 on a lane mask') + imm = re.fullmatch(r'-?(0x[0-9a-fA-F]+|\d+)', ops[1]) + if imm: + # Encoding: one 32-bit literal/inline; the ISA zero-extends it (hi = 0). + value = int(ops[1], 0) & 0xffffffff + folded = 0xffffffff if value == 0 else (value & -value).bit_length() - 1 + self.set_s(dst[1], '0x%08xu' % folded, ('const', folded)) + return None + src = reg_range(ops[1]) + if src is None or src[0] != 's' or src[2] > 105 or src[2] - src[1] != 1: + raise Unsupported('s_ff1_i32_b64 source %s' % ops[1]) + if any(r in self.masks for r in range(src[1], src[2] + 1)): + raise Unsupported('s_ff1_i32_b64 on a lane mask') + lo, hi = self.S(src[1]), self.S(src[2]) + self.masks.discard(dst[1]) + self.set_s(dst[1], _ctz64(lo, hi)) + return None def op_s_abs_i32(self, ops, mods): """Signed absolute value; SCC = result != 0 (#1723). @@ -7213,7 +7277,8 @@ def _flbit_i64(lo, hi): 's_bcnt0_i32_b64': (True, lambda lo, hi: '(64u - countbits(%s) - countbits(%s))' % (lo, hi), '$ != 0'), 's_bcnt1_i32_b64': (True, lambda lo, hi: '(countbits(%s) + countbits(%s))' % (lo, hi), '$ != 0'), 's_ff0_i32_b64': (True, lambda lo, hi: _ctz64('(~%s)' % lo, '(~%s)' % hi), None), - 's_ff1_i32_b64': (True, _ctz64, None), + # s_ff1_i32_b64 stays on Stage.op_s_ff1_i32_b64 (immediates + SGPR pairs) so SCALAR_BITS + # does not overwrite the zero-extended immediate fold from #2022 Item F. 's_flbit_i32_b64': (True, _clz64, None), 's_flbit_i32_i64': (True, _flbit_i64, None), } From 6d92f2a8fb931272036762d79e0871ffedbb9aae Mon Sep 17 00:00:00 2001 From: rdx <123564405+R0D4X@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:13:45 +0100 Subject: [PATCH 061/240] startup: lower v_mul_hi_i32 and s_mul_hi_i32 in gfx2hlsl (#2405) Co-authored-by: R0D4X Co-authored-by: tedin7 --- .github/workflows/windows.yml | 2 + CMakeLists.txt | 9 + tests/startup_gfx2hlsl_mul_hi_i32_check.py | 303 +++++++++++++++++++++ tools/startup/gfx2hlsl.py | 18 +- 4 files changed, 326 insertions(+), 6 deletions(-) create mode 100644 tests/startup_gfx2hlsl_mul_hi_i32_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 7e383a04e..3e4bf90d4 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -131,6 +131,7 @@ jobs: (["tests/startup_gfx2hlsl_swap_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_dpp_quad_swap_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_shift64_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_gfx2hlsl_mul_hi_i32_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_mul_mad_i24_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_cube_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_vopc_sdwa_check.py", "binary", "llvm-mc-15"], {}), @@ -307,6 +308,7 @@ jobs: tests/startup_gfx2hlsl_s_ff1_check.py \ tests/startup_gfx2hlsl_fma_mix_check.py \ tests/startup_gfx2hlsl_shift64_check.py \ + tests/startup_gfx2hlsl_mul_hi_i32_check.py \ tests/startup_gfx2hlsl_mul_mad_i24_check.py \ tests/startup_gfx2hlsl_vopc_sdwa_check.py \ tests/startup_gfx2hlsl_cmp16_check.py \ diff --git a/CMakeLists.txt b/CMakeLists.txt index 77d3029a7..48501b903 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4050,6 +4050,15 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_gfx2hlsl_shift64_${adapter} PROPERTIES TIMEOUT 180 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl signed multiply-high (v_mul_hi_i32, s_mul_hi_i32): helper math, refusals, mutations and draws. + add_test(NAME startup_gfx2hlsl_mul_hi_i32_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_mul_hi_i32_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_mul_hi_i32_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_mul_hi_i32_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_mul_hi_i32_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl v_fract_f32 goes through the clamped fract32 helper, never a bare D3D frac (#1741). add_test(NAME startup_gfx2hlsl_fract COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_fract_check.py") diff --git a/tests/startup_gfx2hlsl_mul_hi_i32_check.py b/tests/startup_gfx2hlsl_mul_hi_i32_check.py new file mode 100644 index 000000000..596557684 --- /dev/null +++ b/tests/startup_gfx2hlsl_mul_hi_i32_check.py @@ -0,0 +1,303 @@ +"""Signed 32x32->high-32 multiply (v_mul_hi_i32, s_mul_hi_i32) in tools/startup/gfx2hlsl.py. + + (no arguments) translation, helper-math, refusal and mutation controls, pure Python + binary reassemble the fixture sources and compare them with the words below + draw [fxc] + compile the translated pair with FXC ps_5_1 when given and with DXC ps_6_0, + draw one pixel per four input pairs and compare the four result words + +The pixel fixture reads two flat parameters (v0..v3 and v4..v7), computes v_mul_hi_i32 across all four lanes into +v12..v15, and exports v12..v15 to mrt0. The vertex stage supplies the input words through flat parameters so the +pixel stage cannot constant-fold them. + +Every result is compared with an independent Python signed 64-bit reference ((s32(a) * s32(b)) >> 32) & 0xffffffff. +The emitted mul_hi_i32 helper (built on the existing mul_hi_u32 helper in Pipeline.common()) is parsed and evaluated +in 32-bit unsigned arithmetic over a 361-pair edge grid including INT_MIN * INT_MIN, INT_MIN * -1, -1 * -1, and mixed +signs. Controls verify s_mul_hi_i32 decoding/lowering (SCC unchanged, lane-mask/descriptor/bounds refusals), exec-masked +emission, modifier/arity refusals, and mutations replacing mul_hi_i32 with mul_hi_u32 (unsigned high product) or +dropping one sign-correction term on both CPU evaluation and desktop GPU draws. +""" +import re +import struct +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import assemble, compile_hlsl, draw, root_blob # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import ( # noqa: E402 + Expr, + MASK, + POST_SOURCE, + POST_WORDS, + PRE_SOURCE, + PRE_WORDS, + Probe, + check, + refused, + vs_source, + vs_words, + words_text, +) + +BODY_SOURCE = ''.join('v_mul_hi_i32 v%d, v%d, v%d\n' % (12 + lane, lane, 4 + lane) for lane in range(4)) +BODY_WORDS = bytes.fromhex( + '0c006cd500090200' + '0d006cd5010b0200' + '0e006cd5020d0200' + '0f006cd5030f0200' +) +PS_WORDS = PRE_WORDS + BODY_WORDS + POST_WORDS + +SCALAR_SOURCE = 's_mul_hi_i32 s12, s10, s11\n' +SCALAR_WORDS = struct.pack(' hi 0x00000000 (unsigned: 0xfffffffe) + (0x80000000, 0x80000000, 0), # INT_MIN * INT_MIN -> hi 0x40000000 (unsigned: 0x40000000, 1-term drop: 0xc0000000) + (0x80000000, 0x00000002, 0), # INT_MIN * 2 -> hi 0xffffffff (unsigned: 0x00000001) + (0xdeadbeef, 0x7fffffff, 0), # neg * INT_MAX -> hi 0xef56df77 (unsigned: 0x6f56df77) + (0x80000000, 0xffffffff, 0), # INT_MIN * -1 -> hi 0x00000000 + (0x00000000, 0xffffffff, 0), # 0 * -1 -> hi 0x00000000 + (0x7fffffff, 0x7fffffff, 0), # INT_MAX * INT_MAX -> hi 0x3fffffff + (0x00000001, 0x80000000, 0), # 1 * INT_MIN -> hi 0xffffffff + (0xdeadbeef, 0xcafebabe, 0), # neg * neg -> hi 0x0b164486 + (0x9e3779b9, 0x85ebca6b, 0), # neg * neg -> hi 0x2ec3a0c2 + (0xffff0000, 0x00010001, 0), # -65536 * 65537 -> hi 0xffffffff + (0x00010001, 0x00010001, 0), # pos * pos -> hi 0x00000001 +] + + +def s32(v): + v &= MASK + return v - (1 << 32) if v & 0x80000000 else v + + +def ref_mul_hi_i32(a, b): + return ((s32(a) * s32(b)) >> 32) & MASK + + +def ref_mul_hi_u32(a, b): + return ((a & MASK) * (b & MASK)) >> 32 + + +def translate(mutate=False): + pipe = G.Pipeline(vs_words([(0, 0, 0)] * 4), PS_WORDS, root_blob()) + text = pipe.hlsl_ps() + if mutate: + mutated = re.sub(r'mul_hi_i32\((v\d+), (v\d+)\)', r'mul_hi_u32(\1, \2)', text) + assert mutated != text, text + text = mutated + return pipe, text + + +def eval_emitted_helpers(ps_text): + """Parse the emitted mul_hi_u32 and mul_hi_i32 helpers and return a 32-bit evaluator for mul_hi_i32.""" + mu = re.search(r'uint mul_hi_u32\(uint a, uint b\) \{ (.*?) \}', ps_text) + assert mu, 'mul_hi_u32 helper missing from generated HLSL' + u_stmts = [part.strip() for part in mu.group(1).split(';') if part.strip()] + u_decls = [] + for stmt in u_stmts[:-1]: + assert stmt.startswith('uint '), stmt + for item in stmt[5:].split(','): + name, rhs = [x.strip() for x in item.split('=', 1)] + u_decls.append((name, Expr(rhs))) + assert u_stmts[-1].startswith('return '), u_stmts[-1] + u_ret = Expr(u_stmts[-1][7:]) + + def run_u(a, b): + env = {'a': a & MASK, 'b': b & MASK} + for name, expr in u_decls: + env[name] = expr.run(env)[0] + return u_ret.run(env)[0] + + mi = re.search(r'uint mul_hi_i32\(uint a, uint b\) \{ return ([^;]+); \}', ps_text) + assert mi, 'mul_hi_i32 helper missing from generated HLSL' + i_expr_text = mi.group(1) + assert 'mul_hi_u32(a, b)' in i_expr_text, i_expr_text + i_expr = Expr(i_expr_text.replace('mul_hi_u32(a, b)', 'u')) + + def run_i(a, b): + return i_expr.run({'a': a & MASK, 'b': b & MASK, 'u': run_u(a, b)})[0] + + return run_i + + +class ScalarProbe(Probe): + def __init__(self): + super().__init__() + self.masks = set() + self.scc_effect = None + + +def scalar_refused(line): + try: + ScalarProbe().one(line.split(' ', 1)[0], line) + except G.Unsupported: + return True + return False + + +def controls(): + _, text = translate() + found = re.findall(r'^\s*v(1[2-5]) = mul_hi_i32\(v(\d+), v(\d+)\);$', text, re.M) + check('v_mul_hi_i32: four lane calls emitted', + found == [('12', '0', '4'), ('13', '1', '5'), ('14', '2', '6'), ('15', '3', '7')]) + + helper = eval_emitted_helpers(text) + mismatch = next(((a, b, helper(a, b), ref_mul_hi_i32(a, b)) for a, b in GRID + if helper(a, b) != ref_mul_hi_i32(a, b)), None) + check('v_mul_hi_i32: emitted helper matches reference on %d edge pairs' % len(GRID), mismatch is None) + + # Sign-correction negative controls: dropping either sign term must mismatch. + drop_a = text.replace('((a >> 31) != 0u ? b : 0u)', '0u') + drop_b = text.replace('((b >> 31) != 0u ? a : 0u)', '0u') + assert drop_a != text and drop_b != text + check('mul_hi_i32: dropping a-sign correction mismatches INT_MIN * 2', + eval_emitted_helpers(drop_a)(0x80000000, 2) != ref_mul_hi_i32(0x80000000, 2)) + check('mul_hi_i32: dropping b-sign correction mismatches 2 * INT_MIN', + eval_emitted_helpers(drop_b)(2, 0x80000000) != ref_mul_hi_i32(2, 0x80000000)) + + # Draw set 0 mutation: substituting mul_hi_u32 for mul_hi_i32 produces distinct words. + mutated = translate(mutate=True)[1] + check('v_mul_hi_i32: mutated text calls mul_hi_u32 on all four lanes', + re.findall(r'^\s*v(1[2-5]) = mul_hi_u32\(v(\d+), v(\d+)\);$', mutated, re.M) + == [('12', '0', '4'), ('13', '1', '5'), ('14', '2', '6'), ('15', '3', '7')]) + first = DRAW[:4] + ref_first = [ref_mul_hi_i32(a, b) for a, b, _ in first] + mut_first = [ref_mul_hi_u32(a, b) for a, b, _ in first] + check('v_mul_hi_i32: draw set 0 unsigned mutation reads %s (differs from %s)' + % (words_text(mut_first), words_text(ref_first)), mut_first != ref_first) + + # Accepted vector operand forms (VGPR, SGPR, inline constant, literal) and exec-masked emission. + check('v_mul_hi_i32: accepted operand forms translate', not any(refused(a) for a in ( + 'v_mul_hi_i32 v1, v2, v3', 'v_mul_hi_i32 v1, s0, v3', + 'v_mul_hi_i32 v1, v2, -1', 'v_mul_hi_i32 v1, v2, 0x80000000'))) + masked = Probe() + masked.exec_known = False + masked.one('v_mul_hi_i32', 'v_mul_hi_i32 v1, v2, v3') + check('exec-masked v_mul_hi_i32 guards assignment', + masked.lines == ['if (exec & 1) v1 = mul_hi_i32(v2, v3);']) + + # Vector refusals: modifiers and wrong operand counts. + check('v_mul_hi_i32: modifiers and operand modifiers refused', all(refused(a) for a in ( + 'v_mul_hi_i32 v1, v2, v3 clamp', 'v_mul_hi_i32 v1, v2, v3 mul:2', + 'v_mul_hi_i32 v1, v2, v3 div:2', 'v_mul_hi_i32 v1, v2, v3 op_sel:[1,0,0,0]', + 'v_mul_hi_i32 v1, -v2, v3', 'v_mul_hi_i32 v1, |v2|, v3', + 'v_mul_hi_i32 v1, v2, -v3', 'v_mul_hi_i32 v1, v2, |v3|'))) + check('v_mul_hi_i32: wrong operand counts refused', all(refused(a) for a in ( + 'v_mul_hi_i32 v1', 'v_mul_hi_i32 v1, v2', 'v_mul_hi_i32 v1, v2, v3, v4'))) + + # Scalar s_mul_hi_i32: decode, lowering (SCC unchanged), SGPR-over-mask overwrite, and refusals. + decoded = G.decode(SCALAR_WORDS) + check('s_mul_hi_i32: SOP2 encoding decodes', + len(decoded) == 1 and decoded[0][2] == 's_mul_hi_i32' and decoded[0][3] == 's_mul_hi_i32 s12, s10, s11') + sp = ScalarProbe() + sp.one('s_mul_hi_i32', 's_mul_hi_i32 s12, s10, s11') + check('s_mul_hi_i32: lowers to mul_hi_i32 without touching scc', + sp.lines == ['s12 = mul_hi_i32(s10, s11);']) + sp_lit = ScalarProbe() + sp_lit.one('s_mul_hi_i32', 's_mul_hi_i32 s12, s10, 0x80000001') + check('s_mul_hi_i32: literal source translates', + sp_lit.lines == ['s12 = mul_hi_i32(s10, 0x80000001u);']) + # Overwriting an SGPR that previously held a compare mask succeeds and drops its mask mark. + sp_over = ScalarProbe() + sp_over.masks.add(12) + sp_over.one('s_mul_hi_i32', 's_mul_hi_i32 s12, s10, s11') + check('s_mul_hi_i32: overwriting mask-marked SGPR drops mask mark', 12 not in sp_over.masks) + # Reading a mask-marked SGPR as source must be refused. + sp_mask_src = ScalarProbe() + sp_mask_src.masks.add(10) + mask_src_refused = False + try: + sp_mask_src.one('s_mul_hi_i32', 's_mul_hi_i32 s12, s10, s11') + except G.Unsupported: + mask_src_refused = True + check('s_mul_hi_i32: mask-marked SGPR source refused', mask_src_refused) + check('s_mul_hi_i32: lane-mask, vcc/exec, out-of-range and wrong-count forms refused', all(scalar_refused(a) for a in ( + 's_mul_hi_i32 vcc_lo, s10, s11', 's_mul_hi_i32 exec_lo, s10, s11', + 's_mul_hi_i32 s12, vcc_lo, s11', 's_mul_hi_i32 s12, s10, exec_lo', + 's_mul_hi_i32 s106, s10, s11', 's_mul_hi_i32 s12, s106, s11', + 's_mul_hi_i32 s12, s10', 's_mul_hi_i32 s12, s10, s11, s13'))) + sym_p = ScalarProbe() + sym_p.sym[10] = ('ptr', ('vbtab',)) + sym_refused = False + try: + sym_p.one('s_mul_hi_i32', 's_mul_hi_i32 s12, s10, s11') + except G.Unsupported: + sym_refused = True + check('s_mul_hi_i32: symbolic pointer source refused', sym_refused) + + +def check_binary(llvm_mc): + for label, source, words in ( + ('v_mul_hi_i32 body', BODY_SOURCE, BODY_WORDS), + ('s_mul_hi_i32', SCALAR_SOURCE, SCALAR_WORDS), + ('prologue', PRE_SOURCE, PRE_WORDS), + ('export', POST_SOURCE, POST_WORDS), + ): + built = assemble(llvm_mc, source) + if built != words: + raise AssertionError('%s: assembled %s, recorded %s' % (label, built.hex(), words.hex())) + for index in range(0, len(DRAW), 4): + chunk = DRAW[index:index + 4] + if assemble(llvm_mc, vs_source(chunk)) != vs_words(chunk): + raise AssertionError('vertex fixture for %s differs from llvm-mc' % (chunk,)) + print('fixture words match llvm-mc') + + +def check_draw(dxc, renderer, adapter, fxc=None): + controls() + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + good_ps = compile_hlsl(compiler, kind, translate()[1], 'ps_mul_hi_i32_%s' % kind, ps_profile, directory) + for index in range(0, len(DRAW), 4): + chunk = DRAW[index:index + 4] + vs = compile_hlsl(compiler, kind, G.Pipeline(vs_words(chunk), PS_WORDS, root_blob()).hlsl_vs(), + 'vs_mul_hi_i32_%d_%s' % (index, kind), vs_profile, directory) + expected = words_text(ref_mul_hi_i32(a, b) for a, b, _ in chunk) + run = draw(renderer, adapter, vs, good_ps, expected) + if run.returncode: + raise AssertionError('%s v_mul_hi_i32 inputs %s\n%s\n%s' % (kind, chunk, run.stdout, run.stderr)) + print('%s v_mul_hi_i32 %s: %s' % (kind, [('%x' % a, '%x' % b) for a, b, _ in chunk], expected), + flush=True) + if index: + continue + wrong = words_text(ref_mul_hi_u32(a, b) for a, b, _ in chunk) + bad_ps = compile_hlsl(compiler, kind, translate(mutate=True)[1], + 'mutated_mul_hi_i32_%s' % kind, ps_profile, directory) + run = draw(renderer, adapter, vs, bad_ps, expected) + if run.returncode == 0 or 'actual=%s' % wrong not in run.stderr: + raise AssertionError('%s v_mul_hi_i32 mutation did not read %s\n%s\n%s' + % (kind, wrong, run.stdout, run.stderr)) + print('%s v_mul_hi_i32 mutation: fails as expected, reads %s' % (kind, wrong), flush=True) + + +def main(): + if len(sys.argv) == 1: + controls() + return + mode, *args = sys.argv[1:] + if mode == 'binary': + check_binary(*args) + elif mode == 'draw': + check_draw(*args) + else: + raise SystemExit(__doc__) + + +if __name__ == '__main__': + main() diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 97f6bc825..9c3d579e5 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -3714,13 +3714,14 @@ def low(tok): shift_add = base in SHIFT_ADD word_complement = base in ('s_nand_b32', 's_nor_b32', 's_xnor_b32') lane_complement = False - # s_mul_hi_u32 needs the whole 32-bit word of each source, like the halfword pack. - word_pack = base in PACK_B16 or base in ('s_sext_i32_i8', 's_sext_i32_i16', 's_mul_hi_u32') + # s_mul_hi_{u,i}32 need the whole 32-bit word of each source, like the halfword pack. + word_pack = base in PACK_B16 or base in ('s_sext_i32_i8', 's_sext_i32_i16', 's_mul_hi_u32', 's_mul_hi_i32') word_absdiff = base == 's_absdiff_i32' if shift_add or word_complement or word_pack or word_absdiff: - # The per-lane mask cannot supply the full word needed by these operations. s_mul_hi_u32 into an + # The per-lane mask cannot supply the full word needed by these operations. s_mul_hi_{u,i}32 into an # SGPR that held a mask replaces it with a plain word (set_s drops the mark), so only vcc/exec count. - mask_dest = (dname in ('exec', 'exec_lo', 'exec_hi', 'vcc', 'vcc_lo', 'vcc_hi') if base == 's_mul_hi_u32' + mask_dest = (dname in ('exec', 'exec_lo', 'exec_hi', 'vcc', 'vcc_lo', 'vcc_hi') + if base in ('s_mul_hi_u32', 's_mul_hi_i32') else self.is_lane_mask(dname)) # Bit i of ~(S0 op S1) depends only on bit i of each source, so with every source a lane mask the lane's # bit of the result is exact. Only an SGPR destination is taken; a mixed mask and plain word is not. @@ -3738,6 +3739,8 @@ def mask_source(tok): if shift_add and dname != 'm0' and (not dst or dst[0] != 's' or dst[1] != dst[2] or dst[1] > 105): raise Unsupported('%s destination %s' % (base, dname)) if word_pack: + if base in ('s_mul_hi_u32', 's_mul_hi_i32') and len(srcs) != 2: + raise Unsupported('%s with %d operands, expected 3' % (base, len(ops))) if dname != 'm0' and (dst is None or dst[0] != 's' or dst[1] > 105): raise Unsupported('%s destination %s' % (base, dname)) for source in srcs: @@ -7108,7 +7111,7 @@ def declarations(self): # operands are uints; the result is a uint expression VEC_U = { 'v_add_nc_u32': (2, '{0} + {1}'), 'v_sub_nc_u32': (2, '{0} - {1}'), 'v_subrev_nc_u32': (2, '{1} - {0}'), - 'v_mul_lo_u32': (2, '{0} * {1}'), 'v_mul_hi_u32': (2, 'mul_hi_u32({0}, {1})'), 'v_and_b32': (2, '{0} & {1}'), 'v_or_b32': (2, '{0} | {1}'), 'v_xor_b32': (2, '{0} ^ {1}'), + 'v_mul_lo_u32': (2, '{0} * {1}'), 'v_mul_hi_u32': (2, 'mul_hi_u32({0}, {1})'), 'v_mul_hi_i32': (2, 'mul_hi_i32({0}, {1})'), 'v_and_b32': (2, '{0} & {1}'), 'v_or_b32': (2, '{0} | {1}'), 'v_xor_b32': (2, '{0} ^ {1}'), 'v_not_b32': (1, '~{0}'), 'v_lshlrev_b32': (2, '{1} << ({0} & 31)'), 'v_lshrrev_b32': (2, '{1} >> ({0} & 31)'), 'v_ashrrev_i32': (2, 'uint(int({1}) >> ({0} & 31))'), 'v_min_u32': (2, 'min({0}, {1})'), 'v_max_u32': (2, 'max({0}, {1})'), 'v_min_i32': (2, 'uint(min(int({0}), int({1})))'), 'v_max_i32': (2, 'uint(max(int({0}), int({1})))'), @@ -7207,8 +7210,9 @@ def low(n): 's_min_i32': ('uint(min(int({0}), int({1})))', None), 's_max_i32': ('uint(max(int({0}), int({1})))', None), 's_bfe_u32': ('({0} >> ({1} & 31)) & ((({1} >> 16) & 127) >= 32 ? 0xffffffffu : ((1u << (({1} >> 16) & 31)) - 1))', '$ != 0'), 's_brev_b32': ('reversebits({0})', None), - # s_mul_hi_u32: high 32 bits of the unsigned 64-bit product; SCC unchanged. + # s_mul_hi_{u,i}32: high 32 bits of the unsigned/signed 64-bit product; SCC unchanged. 's_mul_hi_u32': ('mul_hi_u32({0}, {1})', None), + 's_mul_hi_i32': ('mul_hi_i32({0}, {1})', None), # s_sext_i32_iN: sign-extend the low N bits of S0; SCC unchanged. 's_sext_i32_i8': ('uint(int({0} << 24) >> 24)', None), 's_sext_i32_i16': ('uint(int({0} << 16) >> 16)', None), @@ -7569,6 +7573,8 @@ def common(self): 'uint mul_hi_u32(uint a, uint b) { uint la = a & 0xffffu, lb = b & 0xffffu;' ' uint middle = (a >> 16) * lb + ((la * lb) >> 16);' ' return (a >> 16) * (b >> 16) + (middle >> 16) + (((middle & 0xffffu) + la * (b >> 16)) >> 16); }', + 'uint mul_hi_i32(uint a, uint b) { return mul_hi_u32(a, b) - ((a >> 31) != 0u ? b : 0u)' + ' - ((b >> 31) != 0u ? a : 0u); }', # a * b + c for binary16 inputs with one rounding (#2073). The first form recovered the binary32 sum error # with a floating-point TwoSum; an NVIDIA driver (RTX 3070 Ti, 32.0.16.2101) simplified that error term to # zero despite `precise`, so ties rounded the wrong way. fma16_rne works on the encodings in 32-bit integer From 7fa3866ed81ca2909eca235257bee8b375dcf70b Mon Sep 17 00:00:00 2001 From: triggered02 <153171514+triggered02@users.noreply.github.com> Date: Thu, 26 Nov 2026 07:45:28 +0530 Subject: [PATCH 062/240] shader: lower single-wave TG_SIZE_EN wave-ID mask in startup compute translator (#2432) Co-authored-by: tedin7 --- CMakeLists.txt | 16 + docs/experiments.md | 10 + tests/startup_compute_tg_size_check.py | 423 ++++++++++++++++++++++++ tests/startup_gfx2hlsl_compute_check.py | 2 +- tools/startup/gfx2hlsl.py | 39 ++- 5 files changed, 483 insertions(+), 7 deletions(-) create mode 100644 tests/startup_compute_tg_size_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 48501b903..df8dfceae 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4025,6 +4025,22 @@ if(EXISTS "${INTAKE_PYTHON}") PASS_REGULAR_EXPRESSION "control ${control}: rejected at word=[0-9]+ ") endforeach() endforeach() + # gfx2hlsl COMPUTE_PGM_RSRC2.TG_SIZE_EN wave-ID masking for single-wave groups <= 32 threads (Refs #2274). + add_test(NAME startup_compute_tg_size_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_compute_tg_size_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_compute_tg_size_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_compute_tg_size_check.py" dispatch "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_compute_tg_size_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + foreach(control IN ITEMS dropped-base swapped-mask) + add_test(NAME startup_compute_tg_size_${control}_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_compute_tg_size_check.py" control ${control} "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_compute_tg_size_${control}_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77 + PASS_REGULAR_EXPRESSION "control ${control}: rejected at word=[0-9]+ ") + endforeach() + endforeach() # gfx2hlsl bounded 128-bit LDS exchanges (ds_write_b128, ds_read_b128) and mixed 32/64/128-bit ops (Refs #1541). add_test(NAME startup_compute_lds_b128_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_compute_lds_b128_check.py") diff --git a/docs/experiments.md b/docs/experiments.md index 8c9b7049a..47f2bd5eb 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -16155,6 +16155,16 @@ Building on #2443 (Slice 1), `X2W_D3D12_RELEASE_RETIRED=1` extends desktop objec ```powershell ctest --preset dev --no-tests=error -R '^startup_resource_(retire|budget)' -V + +## Single-wave `TG_SIZE_EN` wave-ID folding in the startup compute translator + +[The startup translator](../tools/startup/gfx2hlsl.py) accepts `COMPUTE_PGM_RSRC2.TG_SIZE_EN` (bit 10) in `ComputePipeline` when the thread-group size is at most 32 threads (`x * y * z <= 32`, one wave per workgroup). The `TG_SIZE` entry SGPR sits immediately after `USER_SGPR` and any enabled `TGID_X/Y/Z` SGPRs (`user + len(groups)`) and is tagged `('tg_size',)`. Only `s_and_b32 R, TG, 0xfc0` (or `0xfc0, TG`) into an SGPR `R <= 105` is accepted for an untouched `TG_SIZE` register: because a single-wave group has wave index `TG_SIZE[11:6] == 0`, it lowers to `R = 0u; scc = false;` with `R` tracked as `('const', 0)` (feeding `v_mbcnt_lo_u32_b32` as a known zero base). Every other read of an untouched `('tg_size',)` register (other masks, moves, arithmetic, vector instructions, or direct `v_mbcnt_lo_u32_b32`) is refused, while overwriting `TG` restores ordinary scalar behavior. Larger groups (`> 32` threads) with `TG_SIZE_EN` remain refused in `ComputePipeline`, and `tools/compute_store_aot.py` continues to refuse `TG_SIZE_EN` unconditionally. + +[The `TG_SIZE_EN` check](../tests/startup_compute_tg_size_check.py) verifies SGPR placement, `s_and_b32` folding, `v_mbcnt_lo_u32_b32` lowering, overwrite/branch/refusal controls, and a two-group `4x2x2` WARP dispatch (`320` words compared, `0` mismatches on Microsoft Basic Render Driver `10.0.26100.9818`, with `dropped-base` rejected at word 5 and `swapped-mask` rejected at word 8). + +```powershell +.\out\pe-env\Scripts\python.exe -B tests/startup_compute_tg_size_check.py +ctest --preset dev --no-tests=error -R '^startup_compute_tg_size_' -V ``` ## Refusing unmodelled modifiers in the startup translator diff --git a/tests/startup_compute_tg_size_check.py b/tests/startup_compute_tg_size_check.py new file mode 100644 index 000000000..916d9cecf --- /dev/null +++ b/tests/startup_compute_tg_size_check.py @@ -0,0 +1,423 @@ +#!/usr/bin/env python3 +"""Verify COMPUTE_PGM_RSRC2.TG_SIZE_EN (#2274 Part A) in tools/startup/gfx2hlsl.py. + + (no arguments) pure-Python translation, uniformity and refusal controls + dispatch + translate, compile with DXC cs_6_0, dispatch and compare all 320 words + control + mutated translation must mismatch on readback + +For groups of at most 32 threads (one wave), TG_SIZE[11:6] (wave ID, mask 0xfc0) is identically 0. +TG_SIZE sits in the SGPR immediately following USER_SGPR and any enabled TGID_X/Y/Z SGPRs. +Only `s_and_b32 R, TG, 0xfc0` (or `0xfc0, TG`) into a plain SGPR <= 105 is accepted, lowering to +`R = 0u; scc = false;` with `R` tracked as `('const', 0)`; every other read of the untouched +TG_SIZE SGPR is refused. +""" + +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parent +sys.path.insert(0, str(ROOT / 'tools')) +sys.path.insert(0, str(ROOT / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) + +import gfx2hlsl as G # noqa: E402 +from startup_gfx2hlsl_compute_check import ( # noqa: E402 + SENTINEL, + TGID_X, + TGID_Y, + TGID_Z, + TG_SIZE_EN, + USER7, + WORDS, + refused, + root_blob, + tidig, +) + + +def le32(word): + return struct.pack(' s7..s10). + for rsrc2, tg_reg in ( + (USER7 | TG_SIZE_EN, 7), + (USER7 | TGID_X | TG_SIZE_EN, 8), + (USER7 | TGID_X | TGID_Z | TG_SIZE_EN, 9), + (USER7 | TGID_X | TGID_Y | TGID_Z | TG_SIZE_EN, 10), + ): + pipe = translate(code=S_ENDPGM, rsrc2=rsrc2, group=(8, 4, 1)) + assert pipe.tg_size_sgpr == tg_reg, (hex(rsrc2), pipe.tg_size_sgpr, tg_reg) + assert pipe.cs.sym.get(tg_reg) == ('tg_size',), (hex(rsrc2), pipe.cs.sym) + assert not pipe.cs.uniform_source('s%d' % tg_reg) + assert pipe.cs.is_const(tg_reg) is None + assert pipe.cs.const_u32('s%d' % tg_reg) is None + + # 2. Standalone s_and_b32 R, TG, 0xfc0 (both operand orders and in-place R == TG). + for and_insn in ( + sop2(S_AND_B32, 20, 8, LIT, 0xfc0), + sop2(S_AND_B32, 20, LIT, 8, 0xfc0), + ): + pipe = translate(code=and_insn + S_ENDPGM) + hlsl = pipe.hlsl_cs() + assert ' s20 = 0u;\n scc = false;' in hlsl, hlsl + assert 'uint s8' not in hlsl, hlsl + assert pipe.cs.sym.get(20) == ('const', 0) + assert pipe.cs.sym.get(8) == ('tg_size',) + assert pipe.cs.scc_uniform is True + + # In-place overwrite `s_and_b32 s8, s8, 0xfc0` lowers to 0u and turns s8 into ('const', 0). + inplace = translate(code=sop2(S_AND_B32, 8, 8, LIT, 0xfc0) + sop1(S_MOV_B32, 20, 8) + S_ENDPGM) + inplace_hlsl = inplace.hlsl_cs() + assert ' s8 = 0u;\n scc = false;\n s20 = 0x00000000u;' in inplace_hlsl, inplace_hlsl + assert inplace.cs.sym.get(8) == ('const', 0) + + # 3. Full program: s_and_b32 R, TG, 0xfc0 feeds R into v_mbcnt_lo_u32_b32, plus standalone v_mbcnt_lo/hi. + main_hlsl = translate().hlsl_cs() + assert ' s20 = 0u;\n scc = false;' in main_hlsl, main_hlsl + assert 'countbits(0x85241249u & ((1u << (tid.x + 4u * (tid.y + 2u * tid.z))) - 1u)) + 0x00000000u' in main_hlsl, main_hlsl + assert 'countbits(0x0f0f0f0fu & ((1u << (tid.x + 4u * (tid.y + 2u * tid.z))) - 1u)) + v8' in main_hlsl, main_hlsl + + hi_prog = b''.join([ + sop2(S_AND_B32, 20, 8, LIT, 0xfc0), + vop3(V_MBCNT_HI_U32_B32, 8, INLINE_NEG1, 20), + S_ENDPGM, + ]) + hi_hlsl = translate(code=hi_prog).hlsl_cs() + assert ' v8 = 0x00000000u;' in hi_hlsl, hi_hlsl + + # 4. >32 threads per group with TG_SIZE_EN is refused. + for bad_group in ((8, 4, 2), (33, 1, 1), (64, 1, 1)): + refused('TG_SIZE_EN requires at most 32 threads per group', + lambda g=bad_group: translate(code=S_ENDPGM, group=g)) + + # 5. Disallowed reads of TG_SIZE are refused. + bad_tg_reads = [ + ('TG_SIZE register s8 read outside s_and_b32 with 0xfc0', sop2(S_AND_B32, 20, 8, LIT, 0x3f)), + ('TG_SIZE register s8 read outside s_and_b32 with 0xfc0', sop2(S_AND_B32, 20, 8, LIT, 0)), + ('TG_SIZE register s8 read outside s_and_b32 with 0xfc0', sop2(S_AND_B32, 20, 8, 8)), + ('TG_SIZE register s8 read outside s_and_b32 with 0xfc0', sop2(S_AND_B32, M0, 8, LIT, 0xfc0)), + ('TG_SIZE register s8 read outside s_and_b32 with 0xfc0', sop2(S_AND_B32, EXEC_LO, 8, LIT, 0xfc0)), + ('TG_SIZE register s8 read outside s_and_b32 with 0xfc0', sop2(S_AND_B32, VCC_LO, 8, LIT, 0xfc0)), + ('TG_SIZE register s8 read outside s_and_b32 with 0xfc0', sop2(S_AND_B32, 106, 8, LIT, 0xfc0)), + ('TG_SIZE register s8 read outside s_and_b32 with 0xfc0', sop1(S_MOV_B32, 20, 8)), + ('TG_SIZE register s8 read outside s_and_b32 with 0xfc0', sop2(S_OR_B32, 20, 8, INLINE_0)), + ('TG_SIZE register s8 read outside s_and_b32 with 0xfc0', sop2(S_LSHR_B32, 20, 8, INLINE_6)), + ('TG_SIZE register s8 read outside s_and_b32 with 0xfc0', sop2(S_LSHL_B32, 20, 8, INLINE_2)), + ('TG_SIZE register s8 read outside s_and_b32 with 0xfc0', sop1(S_MOV_B64, 20, 8)), + ('TG_SIZE register s8 read outside s_and_b32 with 0xfc0', sopc(S_CMP_EQ_U32, 8, INLINE_0)), + ('s_addk_i32 on tg_size data', sopk(S_ADDK_I32, 8, 1)), + ('TG_SIZE register s8 read outside s_and_b32 with 0xfc0', vop2(V_ADD_NC_U32, 3, 8, 0)), + ('TG_SIZE register s8 read outside s_and_b32 with 0xfc0', vop1(V_MOV_B32, 3, 8)), + ('v_mbcnt_lo_u32_b32 requires a VGPR or known base', vop3(V_MBCNT_LO_U32_B32, 8, INLINE_NEG1, 8)), + ('v_mbcnt_lo_u32_b32 requires a known mask', vop3(V_MBCNT_LO_U32_B32, 8, 8, INLINE_0)), + ] + for msg, insn in bad_tg_reads: + refused(msg, lambda c=insn + S_ENDPGM: translate(code=c).hlsl_cs()) + + # Modified s_and_b32 (e.g. non-empty mods on unit probe) is also refused. + probe = G.Stage.__new__(G.Stage) + probe.sym = {8: ('tg_size',)} + probe.used_s = set() + probe.lines = [] + probe.exec_known = True + refused('TG_SIZE register s8 read outside s_and_b32 with 0xfc0', + lambda: probe.scalar('s_and_b32', ['s20', 's8', '0xfc0'], ['clamp'])) + + # Descriptor-path protection: mixing descriptor and tg_size in s_add_u32 refuses tg_size instead of silently dropping it. + desc_mix = b''.join([ + sop1(S_MOV_B32, 10, 6), + sop1(S_MOV_B32, 11, INLINE_0), + S_LOAD_X8_S12_S10, + sop2(S_ADD_U32, 12, 12, 8), + S_ENDPGM, + ]) + refused('TG_SIZE register s8 read outside s_and_b32 with 0xfc0', lambda: translate(code=desc_mix).hlsl_cs()) + + # 6. Overwriting TG first restores ordinary scalar behavior. + overwrite_const = b''.join([ + sop1(S_MOV_B32, 8, 128 + 5), + sop2(S_AND_B32, 20, 8, LIT, 0x3f), + vop2(V_ADD_NC_U32, 3, 8, 0), + S_ENDPGM, + ]) + ov_const_hlsl = translate(code=overwrite_const).hlsl_cs() + assert ' s8 = 0x00000005u;\n s20 = 0x00000005u & 0x0000003fu;' in ov_const_hlsl, ov_const_hlsl + assert ' v3 = 0x00000005u + v0;' in ov_const_hlsl, ov_const_hlsl + + overwrite_runtime = b''.join([ + sop1(S_MOV_B32, 8, 7), + sop2(S_AND_B32, 20, 8, LIT, 0x3f), + vop2(V_ADD_NC_U32, 3, 8, 0), + S_ENDPGM, + ]) + ov_rt_hlsl = translate(code=overwrite_runtime).hlsl_cs() + assert ' s8 = s7;\n s20 = s8 & 0x0000003fu;' in ov_rt_hlsl, ov_rt_hlsl + assert ' v3 = s8 + v0;' in ov_rt_hlsl, ov_rt_hlsl + + # 7. Branch / execz interactions: s_and_b32 inside s_cbranch_execz live-out is refused; dead-out is accepted. + execz_live = b''.join([ + sopp(0x08, 2), # s_cbranch_execz +2 dwords (skips 8-byte s_and_b32 with literal 0xfc0) + sop2(S_AND_B32, 20, 8, LIT, 0xfc0), + vop1(V_MOV_B32, 3, 20), + S_ENDPGM, + ]) + refused('definition of s20, live where the block joins', lambda: translate(code=execz_live).hlsl_cs()) + + execz_dead = b''.join([ + sopp(0x08, 2), # s_cbranch_execz +2 dwords + sop2(S_AND_B32, 20, 8, LIT, 0xfc0), + S_ENDPGM, + ]) + translate(code=execz_dead).hlsl_cs() + + # Overwriting TG on one branch arm and reading it at join refuses (never leaks ('tg_size',) across a join). + join_leak = b''.join([ + sopc(S_CMP_EQ_U32, 7, INLINE_0), + sopp(0x04, 2), # s_cbranch_scc0 +2 dwords + sop2(S_AND_B32, 8, 8, LIT, 0xfc0), + sop1(S_MOV_B32, 20, 8), + S_ENDPGM, + ]) + refused('holding joined at a branch target', lambda: translate(code=join_leak).hlsl_cs()) + + print('tg_size_en: entry layout, s_and_b32 0xfc0 folding, v_mbcnt_lo base, overwrite and refusals pass') + + +CONTROLS = { + 'dropped-base': (' + v8', ''), + 'swapped-mask': ('v8 = (countbits(0x85241249u', 'v8 = (countbits(0x0f0f0f0fu'), +} + +CONTROL_MISMATCH = { + 'dropped-base': 'word=5 expected=00000002 actual=00000001', + 'swapped-mask': 'word=8 expected=00000001 actual=00000002', +} + + +def mutate(hlsl, control): + old, new = CONTROLS[control] + assert hlsl.count(old) == 1, (control, hlsl) + return hlsl.replace(old, new) + + +def check_dispatch(dxc, runner, adapter, control=None): + runner = str(Path(runner).resolve()) + out = ROOT / 'out' + out.mkdir(exist_ok=True) + hlsl = translate().hlsl_cs() + if control: + if control not in CONTROLS: + raise SystemExit(f'unknown control {control!r}') + hlsl = mutate(hlsl, control) + with tempfile.TemporaryDirectory(dir=out) as tmp: + d = Path(tmp) + src, cso, case = d / 'tg_size.hlsl', d / 'tg_size.cso', d / 'tg_size.case' + src.write_text(hlsl, encoding='ascii') + subprocess.run([dxc, '-T', 'cs_6_0', '-E', 'main', '-Fo', str(cso), str(src)], check=True) + gx, gy, gz = DISPATCH_GROUPS + constants = [0] * 16 + case.write_bytes( + struct.pack(' user: raise Unsupported('root signature needs s4-s%d, COMPUTE_PGM_RSRC2 gives %d user SGPRs' % (root_end - 1, user)) @@ -1949,6 +1950,9 @@ def setup_compute_entry(self, root_end): self.used_s.add(n) self.entry_uniform_s.add(n) self.entry.append('s%d = gid.%s;' % (n, 'xyz'[axis])) + tg_size = getattr(self.pipe, 'tg_size_sgpr', None) + if tg_size is not None: + self.sym[tg_size] = ('tg_size',) for i in range(threads): self.used_v.add(i) self.entry.append('v%d = tid.%s;' % (i, 'xyz'[i])) @@ -1965,6 +1969,8 @@ def S(self, n): if s[0] in ('execcopy', 'fixed_buffer_word'): self.used_s.add(n) return 's%d' % n + if s[0] == 'tg_size': + raise Unsupported('TG_SIZE register s%d read outside s_and_b32 with 0xfc0' % n) raise Unsupported('numeric use of s%d holding %s' % (n, s[0])) self.used_s.add(n) return 's%d' % n @@ -3346,7 +3352,7 @@ def lower(self, base, asm, ops, mods): pipe.uses_sad.add(base) return self.set_v(reg_range(ops[0])[1], text.format(*args)) if base in SCA: - return self.scalar(base, ops) + return self.scalar(base, ops, mods) if mods else self.scalar(base, ops) if base == 's_addc_u32': # Only the high word of an advanced descriptor pointer; the carry is not modelled. hi = reg_range(ops[1]) if len(ops) == 3 else None @@ -3684,7 +3690,7 @@ def exec_absorbed_source(self, base, srcs): return i return None - def scalar(self, base, ops): + def scalar(self, base, ops, mods=()): # Every SALU form in SCA is dst, src (the two templates below use {0} and {1}); a short list would # index past the end and leave `translator crash in : IndexError` in the census instead of a # refusal. s_movk_i32 keeps its own exact check for the immediate it folds. @@ -3755,6 +3761,21 @@ def src_sym(t): r = reg_range(t) return self.sym.get(r[1]) if r and r[0] == 's' else None syms = [src_sym(t) for t in srcs] + tg_srcs = [ + reg for tok in ops[1:] for r in (reg_range(tok),) if r and r[0] == 's' + for reg in range(r[1], r[2] + 1) if self.sym.get(reg) == ('tg_size',) + ] + if tg_srcs: + # Wave-ID bits TG_SIZE[11:6] (mask 0xfc0) are identically 0 for <= 32 threads per group (1 wave). + if (base == 's_and_b32' and not mods and len(srcs) == 2 + and dst and dst[0] == 's' and dst[1] == dst[2] and dst[1] <= 105): + other = (srcs[1] if syms[0] == ('tg_size',) and syms[1] != ('tg_size',) + else srcs[0] if syms[1] == ('tg_size',) and syms[0] != ('tg_size',) + else None) + if other is not None and self.const_u32(other) == 0xfc0: + self.set_s(dst[1], '0u', ('const', 0), scc='false') + return None + raise Unsupported('TG_SIZE register s%d read outside s_and_b32 with 0xfc0' % tg_srcs[0]) if any(s and s[0] in ('desc', 'descnum', 'ptr', 'ptrhi') for s in syms): if scc or base in SCC_UNMODELLED: self.scc_effect = 'descriptor' @@ -7971,10 +7992,16 @@ class ComputePipeline(Pipeline): def __init__(self, cs_code, root_blob, rsrc2, group, sampler_heap=None, refusals=None, decoded=None): from compute_store_aot import checked_group, entry_registers try: - self.entry = entry_registers(rsrc2) # (user SGPRs, {axis: group-ID SGPR}, thread-ID VGPRs) + tg_size_en = (isinstance(rsrc2, int) and not isinstance(rsrc2, bool) + and 0 <= rsrc2 < (1 << 32) and bool((rsrc2 >> 10) & 1)) + self.entry = entry_registers(rsrc2 & ~(1 << 10) if tg_size_en else rsrc2) self.group = checked_group(group) except ValueError as reason: raise Unsupported(str(reason)) from None + if tg_size_en and self.group[0] * self.group[1] * self.group[2] > 32: + raise Unsupported('COMPUTE_PGM_RSRC2 TG_SIZE_EN requires at most 32 threads per group') + user, groups, _ = self.entry + self.tg_size_sgpr = (user + len(groups)) if tg_size_en else None self.root = parse_root(root_blob) self.vs_fetch, self.packed_position_vgpr, self.rtv_formats = None, None, () self.sampler_heap = os.environ.get('X2W_SAMPLER_HEAP') == '1' if sampler_heap is None else sampler_heap From 4f7dd6cee45391545b725c8d04a3a79fe5d25062 Mon Sep 17 00:00:00 2001 From: triggered02 <153171514+triggered02@users.noreply.github.com> Date: Thu, 26 Nov 2026 07:45:50 +0530 Subject: [PATCH 063/240] startup/gfx2hlsl: lower v_mad_u32_u16 (#2433) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> Co-authored-by: tedin7 --- CMakeLists.txt | 9 + docs/experiments.md | 11 + tests/startup_gfx2hlsl_mad_u32_u16_check.py | 374 ++++++++++++++++++++ tools/startup/gfx2hlsl.py | 6 + 4 files changed, 400 insertions(+) create mode 100644 tests/startup_gfx2hlsl_mad_u32_u16_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index df8dfceae..8f2a1a322 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3939,6 +3939,15 @@ if(EXISTS "${INTAKE_PYTHON}") set_tests_properties(startup_gfx2hlsl_mad_dispatch_${adapter} startup_gfx2hlsl_mad_preserve_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl v_mad_u32_u16: low-16 unsigned multiply-add with 32-bit addend and wraparound. + add_test(NAME startup_gfx2hlsl_mad_u32_u16_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_mad_u32_u16_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_mad_u32_u16_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_mad_u32_u16_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_mad_u32_u16_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl v_fma_mix*: every translated form dispatched against a CPU reference that decodes the VOP3P # word itself, plus a control that drops the high-half shift. foreach(adapter IN ITEMS warp hardware) diff --git a/docs/experiments.md b/docs/experiments.md index 47f2bd5eb..4f458311d 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -16167,6 +16167,17 @@ ctest --preset dev --no-tests=error -R '^startup_resource_(retire|budget)' -V ctest --preset dev --no-tests=error -R '^startup_compute_tg_size_' -V ``` +## Startup translator: v_mad_u32_u16 + +[`tools/startup/gfx2hlsl.py`](../tools/startup/gfx2hlsl.py) now lowers the unmodified gfx1013 VOP3A instruction `v_mad_u32_u16` (`0x373` in [`tools/disasm_rdna2.py`](../tools/disasm_rdna2.py)) via `VEC_U` as `({0} & 0xffffu) * ({1} & 0xffffu) + {2}` (unsigned 32-bit wraparound). In `Stage.lower`, `S0` and `S1` are read with `low16_only=True` because only bits `[15:0]` of those operands are consumed (allowing odd-dmask `d16` `image_load` results in `S0`/`S1` and clearing `low16_only_v` on the 32-bit destination), while `S2` is read with `low16_only=False` (refusing `low16_only_v` sources) so all 32 bits of the addend are preserved. Modifiers (`op_sel`, `clamp`, `omod`, `abs`, `neg`) and wrong operand counts remain refused. + +[`tests/startup_gfx2hlsl_mad_u32_u16_check.py`](../tests/startup_gfx2hlsl_mad_u32_u16_check.py) decodes synthetic gfx1013 VOP3A bytes for 4-lane VGPR forms as well as literal/inline-constant/SGPR forms (`v_mad_u32_u16 v1, 0x1f0, v15, 0`, `v_mad_u32_u16 v3, s4, -1, v9`, `v_mad_u32_u16 v2, v5, 7, 0x12345678`), evaluates the emitted HLSL expressions over 1,800 32-bit input triples (including upper-16 garbage bits `0xffff0000` in `S0`/`S1`, `0xffff * 0xffff`, 32-bit wraparound with `S2 = 0xffffffff`, and upper-bit preservation on `S2`) against `((s0 & 0xffff) * (s1 & 0xffff) + s2) & 0xffffffff`, checks the `low16_only` read/clear/refusal rules, checks `op_sel`/`clamp`/`omod`/`abs`/`neg`/arity refusals and the unlowered-table negative control, and verifies three HLSL mutations (`drop_s0_mask`, `drop_s1_mask`, `mask_s2`). In `draw` mode, both FXC (`vs_5_1`/`ps_5_1`, Windows SDK 10.0.26100) and DXC (`vs_6_0`/`ps_6_0`, Windows SDK 10.0.26100) passed 3 four-lane chunks and all 3 mutated draws on Microsoft WARP (`10.0.26100.9818`). Tests: `startup_gfx2hlsl_mad_u32_u16_controls`, `startup_gfx2hlsl_mad_u32_u16_warp`, `startup_gfx2hlsl_mad_u32_u16_hardware` (not run on physical hardware here). + +```powershell +python -B tests/startup_gfx2hlsl_mad_u32_u16_check.py +ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_mad_u32_u16_' -V +``` + ## Refusing unmodelled modifiers in the startup translator Several `Stage` instruction handlers accepted a `mods` list without reading it, so an encoding modifier such as diff --git a/tests/startup_gfx2hlsl_mad_u32_u16_check.py b/tests/startup_gfx2hlsl_mad_u32_u16_check.py new file mode 100644 index 000000000..98ca9a61c --- /dev/null +++ b/tests/startup_gfx2hlsl_mad_u32_u16_check.py @@ -0,0 +1,374 @@ +"""Lower v_mad_u32_u16 in tools/startup/gfx2hlsl.py. + + (no arguments) translation controls, pure Python + binary reassemble the fixture sources and compare them with the encoded words + draw [fxc] + compile the translated pair with FXC ps_5_1 when given and with DXC ps_6_0, + draw one pixel per four input sets and compare the four result words + +RDNA 2 ISA semantics for v_mad_u32_u16 (when op_sel:[0,0,0] and no clamp/omod/abs/neg): + D.u32 = (S0.u32 & 0xffffu) * (S1.u32 & 0xffffu) + S2.u32 (32-bit unsigned wraparound). + +S0 and S1 read only bits [15:0] (allowed on low16-only odd-dmask d16 image_load results), while S2 reads all +32 bits (refused on low16-only registers). Any modifier (op_sel, clamp, omod, abs, neg) or wrong operand count +is refused. +""" +import re +import struct +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import assemble, compile_hlsl, draw, root_blob # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import (Expr, POST_SOURCE, POST_WORDS, PRE_SOURCE, PRE_WORDS, # noqa: E402 + lane_expressions, lane_results, vs_source, vs_words, words_text) + +MASK = 0xffffffff +VOP3_MAD_U32_U16 = 0x373 + + +def ref_mad_u32_u16(s0, s1, s2): + return ((s0 & 0xffff) * (s1 & 0xffff) + s2) & MASK + + +def encode_mad_u32_u16(vdst, src0, src1, src2, *, literal=None, op_sel=(0, 0, 0, 0), + abs_bits=(0, 0, 0), neg=(0, 0, 0), clamp=0, omod=0): + """Encode synthetic gfx1013 VOP3A bytes for v_mad_u32_u16 (opcode 0x373).""" + w0 = (0b110101 << 26) | (VOP3_MAD_U32_U16 << 16) | ((clamp & 1) << 15) | (vdst & 0xff) + for i, bit in enumerate(op_sel): + w0 |= (bit & 1) << (11 + i) + for i, bit in enumerate(abs_bits): + w0 |= (bit & 1) << (8 + i) + w1 = ((src0 & 0x1ff) | ((src1 & 0x1ff) << 9) | ((src2 & 0x1ff) << 18) | + ((omod & 0x3) << 27) | ((neg[0] & 1) << 29) | ((neg[1] & 1) << 30) | ((neg[2] & 1) << 31)) + if 255 in (src0, src1, src2): + assert literal is not None + return struct.pack('<3I', w0, w1, literal & MASK) + assert literal is None + return struct.pack('<2I', w0, w1) + + +BODY_WORDS = b''.join(encode_mad_u32_u16(12 + lane, 256 + lane, 256 + 4 + lane, 256 + 8 + lane) + for lane in range(4)) +PS_WORDS = PRE_WORDS + BODY_WORDS + POST_WORDS +BODY_SOURCE = ''.join('v_mad_u32_u16 v%d, v%d, v%d, v%d\n' % (12 + lane, lane, 4 + lane, 8 + lane) + for lane in range(4)) + +# Synthetic non-register forms decoded through G.decode() and translated via Stage. +SYNTHETIC_CASES = [ + ( + 'literal src0 + vgpr src1 + inline 0 src2', + encode_mad_u32_u16(1, 255, 256 + 15, 128 + 0, literal=0x1f0), + 'v_mad_u32_u16 v1, 0x1f0, v15, 0', + 'v1 = (0x000001f0u & 0xffffu) * (v15 & 0xffffu) + 0x00000000u;', + lambda v: ref_mad_u32_u16(0x1f0, v['v15'], 0), + ), + ( + 'sgpr src0 + inline -1 src1 + vgpr src2', + encode_mad_u32_u16(3, 4, 193, 256 + 9), + 'v_mad_u32_u16 v3, s4, -1, v9', + 'v3 = (s4 & 0xffffu) * (0xffffffffu & 0xffffu) + v9;', + lambda v: ref_mad_u32_u16(v['s4'], 0xffffffff, v['v9']), + ), + ( + 'vgpr src0 + inline 7 src1 + literal src2', + encode_mad_u32_u16(2, 256 + 5, 128 + 7, 255, literal=0x12345678), + 'v_mad_u32_u16 v2, v5, 7, 0x12345678', + 'v2 = (v5 & 0xffffu) * (0x00000007u & 0xffffu) + 0x12345678u;', + lambda v: ref_mad_u32_u16(v['v5'], 7, 0x12345678), + ), +] + +S01_EDGES = [ + 0, 1, 2, 0x7fff, 0x8000, 0xffff, + 0x00010000, 0xdead0000, 0xffff0000, + 0xffff0001, 0xdeadbeef, 0x7fffffff, 0x80000000, 0x8000ffff, MASK, +] +S2_EDGES = [0, 1, 0x12345678, 0x7fffffff, 0x80000000, 0xfffe0000, 0xffff0000, MASK] +GRID = [(s0, s1, s2) for s0 in S01_EDGES for s1 in S01_EDGES for s2 in S2_EDGES] + +# 4 input sets per chunk; chunk 0 simultaneously distinguishes all three mutations below. +DRAW_SETS = [ + # Chunk 0: non-zero upper-16 bits on S0, S1, and S2; all distinct from mutations. + (0xdead0003, 0xbeef0005, 0x12345678), + (0xffff0007, 0x80000009, 0xabcd0000), + (0x0001ffff, 0x0002ffff, 0x00020000), + (0x12340002, 0x56780003, 0x89abcdef), + # Chunk 1: max product 0xffff * 0xffff = 0xfffe0001, wraparound with 0xffffffff, zero product + upper S2. + (0x0000ffff, 0x0000ffff, 0x00000000), + (0x0000ffff, 0x0000ffff, MASK), + (0xdead0000, 0xbeef0000, 0x76543210), + (0xffff0003, 0xffff0005, MASK), + # Chunk 2: boundary bits 0x8000 * 0x8000, 0xffff * 1 + 0xffff0000, wraparound to 0, large addend. + (0x00008000, 0x00008000, 0x00000000), + (0xabcdffff, 0x12340001, 0xffff0000), + (0x00010001, 0x0001ffff, 0xffff0000), + (0xffffffff, 0xffffffff, 0x0001ffff), +] + +MUTATIONS = { + 'drop_s0_mask': ( + r'\((v[0-3]) & 0xffffu\) \* \((v[4-7]) & 0xffffu\) \+ (v(?:[89]|1[01]))', + r'\1 * (\2 & 0xffffu) + \3', + lambda s0, s1, s2: (s0 * (s1 & 0xffff) + s2) & MASK, + ), + 'drop_s1_mask': ( + r'\((v[0-3]) & 0xffffu\) \* \((v[4-7]) & 0xffffu\) \+ (v(?:[89]|1[01]))', + r'(\1 & 0xffffu) * \2 + \3', + lambda s0, s1, s2: ((s0 & 0xffff) * s1 + s2) & MASK, + ), + 'mask_s2': ( + r'\((v[0-3]) & 0xffffu\) \* \((v[4-7]) & 0xffffu\) \+ (v(?:[89]|1[01]))', + r'(\1 & 0xffffu) * (\2 & 0xffffu) + (\3 & 0xffffu)', + lambda s0, s1, s2: ((s0 & 0xffff) * (s1 & 0xffff) + (s2 & 0xffff)) & MASK, + ), +} + + +class Probe(G.Stage): + """Minimal Stage for single-instruction / decoded-byte translation probes.""" + + def __init__(self): + self.lines, self.sym = [], {} + self.used_s, self.used_v, self.uniform_v = set(), set(), set() + self.exec_known = True + self.low16_only_v = set() + self.pinned_low16_v = set() + self.whole_read_v = set() + + +def check(label, ok, detail=''): + print('%s: %s%s' % (label, 'ok' if ok else 'MISMATCH', ' ' + detail if detail and not ok else '')) + if not ok: + raise AssertionError(label) + + +def translate_ps(mutate=None): + pipe = G.Pipeline(vs_words([(0, 0, 0)] * 4), PS_WORDS, root_blob()) + text = pipe.hlsl_ps() + if mutate is not None: + pattern, replacement, _ = MUTATIONS[mutate] + mutated, count = re.subn(pattern, replacement, text) + assert count == 4 and mutated != text, (mutate, count, text) + text = mutated + return pipe, text + + +def decode_one(word_bytes): + decoded = G.decode(word_bytes) + assert len(decoded) == 1, decoded + _, size, name, asm = decoded[0] + assert size == len(word_bytes), (size, len(word_bytes), decoded) + return name, asm + + +def translate_bytes(word_bytes): + name, asm = decode_one(word_bytes) + stage = Probe() + stage.one(name, asm) + return name, asm, stage + + +def refused_bytes(word_bytes): + try: + translate_bytes(word_bytes) + except G.Unsupported as exc: + return str(exc) + return None + + +def refused_asm(asm): + try: + stage = Probe() + stage.one(asm.split(' ', 1)[0], asm) + except G.Unsupported as exc: + return str(exc) + return None + + +def controls(): + # 1. Decode check on the 4-lane pixel body bytes. + body_decoded = G.decode(BODY_WORDS) + expected_body = ['v_mad_u32_u16 v%d, v%d, v%d, v%d' % (12 + i, i, 4 + i, 8 + i) for i in range(4)] + check('synthetic BODY_WORDS decode', + [asm for _, _, _, asm in body_decoded] == expected_body + and all(name == 'v_mad_u32_u16' for _, _, name, _ in body_decoded)) + + # 2. Value-level verification over all 4 lanes across the 1800-case grid. + _, ps_text = translate_ps() + exprs = lane_expressions(ps_text) + mismatch = None + for index, (s0, s1, s2) in enumerate(GRID): + lane = index % 4 + env = {'v%d' % lane: s0, 'v%d' % (4 + lane): s1, 'v%d' % (8 + lane): s2} + got = exprs[lane].run(env)[0] + want = ref_mad_u32_u16(s0, s1, s2) + if got != want: + mismatch = (lane, (s0, s1, s2), got, want) + break + check('pixel lowering: %d 32-bit inputs match reference' % len(GRID), mismatch is None, repr(mismatch)) + + # 3. Synthetic non-register forms: literal, inline integer, SGPR. + sample_vals = { + 'v5': 0xdead0011, 'v9': 0x87654321, 'v15': 0xbeef0005, 's4': 0xcafe0009, + } + for label, word_bytes, want_asm, want_line, ref_fn in SYNTHETIC_CASES: + name, asm, stage = translate_bytes(word_bytes) + check('decode %s' % label, name == 'v_mad_u32_u16' and asm == want_asm, asm) + check('lower %s' % label, stage.lines == [want_line], repr(stage.lines)) + parsed = Expr(stage.lines[0].split(' = ', 1)[1].rstrip(';')) + for hi_s in (0x00000000, 0xdead0000, 0xffff0000): + for lo_s in (0x0000, 0x0001, 0xffff): + env = dict(sample_vals) + val = hi_s | lo_s + env['v5'] = val + env['v15'] = val + env['s4'] = val + env['v9'] = (hi_s ^ 0x12345678) | lo_s + got = parsed.run(env)[0] + want = ref_fn(env) + assert got == want, (label, env, got, want) + check('evaluate %s' % label, True) + + # 4. low16_only contract: S0 and S1 allow odd-dmask d16 low16_only_v; S2 must refuse whole-word read; + # writing dst clears low16_only_v on dst. + stage = Probe() + stage.low16_only_v.update({4, 5}) + stage.one('v_mad_u32_u16', 'v_mad_u32_u16 v4, v4, v5, v7') + check('low16_only allowed on S0/S1 and cleared on dst', + 4 not in stage.low16_only_v and 4 not in stage.whole_read_v and 5 not in stage.whole_read_v + and 7 in stage.whole_read_v) + + stage_s2 = Probe() + stage_s2.low16_only_v.add(7) + try: + stage_s2.one('v_mad_u32_u16', 'v_mad_u32_u16 v6, v4, v5, v7') + except G.Unsupported as exc: + s2_reason = str(exc) + else: + s2_reason = None + check('low16_only refused on S2', s2_reason == 'whole-word read of v7 after odd d16 image_load', repr(s2_reason)) + + # 5. Refusal controls from synthetic VOP3A bytes and malformed operand counts. + byte_refusals = [ + ('op_sel:[1,0,0]', encode_mad_u32_u16(1, 256 + 2, 256 + 3, 256 + 4, op_sel=(1, 0, 0, 0)), 'v_mad_u32_u16 with'), + ('op_sel:[0,1,0]', encode_mad_u32_u16(1, 256 + 2, 256 + 3, 256 + 4, op_sel=(0, 1, 0, 0)), 'v_mad_u32_u16 with'), + ('op_sel:[0,0,1]', encode_mad_u32_u16(1, 256 + 2, 256 + 3, 256 + 4, op_sel=(0, 0, 1, 0)), 'v_mad_u32_u16 with'), + ('op_sel:[0,0,0,1]', encode_mad_u32_u16(1, 256 + 2, 256 + 3, 256 + 4, op_sel=(0, 0, 0, 1)), 'v_mad_u32_u16 with'), + ('clamp', encode_mad_u32_u16(1, 256 + 2, 256 + 3, 256 + 4, clamp=1), 'v_mad_u32_u16 with'), + ('omod mul:2', encode_mad_u32_u16(1, 256 + 2, 256 + 3, 256 + 4, omod=1), 'v_mad_u32_u16 with'), + ('abs', encode_mad_u32_u16(1, 256 + 2, 256 + 3, 256 + 4, abs_bits=(1, 0, 0)), 'operand'), + ('neg', encode_mad_u32_u16(1, 256 + 2, 256 + 3, 256 + 4, neg=(1, 0, 0)), 'operand'), + ] + for label, word_bytes, needle in byte_refusals: + reason = refused_bytes(word_bytes) + check('refused bytes (%s)' % label, reason is not None and needle in reason, repr(reason)) + + for bad_asm in ('v_mad_u32_u16 v1, v2, v3', 'v_mad_u32_u16 v1, v2, v3, v4, v5'): + reason = refused_asm(bad_asm) + check('refused arity (%s)' % bad_asm, + reason is not None and 'operands, expected 4' in reason, repr(reason)) + + # 6. Mutation controls: each mutated HLSL must disagree on GRID and match its own MUTATIONS reference on DRAW_SETS. + first_chunk = DRAW_SETS[:4] + first_ref = [ref_mad_u32_u16(*row) for row in first_chunk] + for mut_name, (_, _, mut_ref) in MUTATIONS.items(): + _, mut_text = translate_ps(mut_name) + mut_exprs = lane_expressions(mut_text) + found = None + for index, (s0, s1, s2) in enumerate(GRID): + lane = index % 4 + env = {'v%d' % lane: s0, 'v%d' % (4 + lane): s1, 'v%d' % (8 + lane): s2} + got = mut_exprs[lane].run(env)[0] + if got != ref_mad_u32_u16(s0, s1, s2): + found = (lane, (s0, s1, s2), got) + break + check('mutation %s breaks GRID' % mut_name, found is not None) + all_match_mut = all( + mut_exprs[i % 4].run({'v%d' % (i % 4): s0, 'v%d' % (4 + i % 4): s1, 'v%d' % (8 + i % 4): s2})[0] + == mut_ref(s0, s1, s2) + for i, (s0, s1, s2) in enumerate(GRID) + ) + check('mutation %s matches its own reference across %d inputs' % (mut_name, len(GRID)), all_match_mut) + wrong_words = [mut_ref(*row) for row in first_chunk] + check('mutation %s differs from reference on draw chunk 0' % mut_name, wrong_words != first_ref) + check('mutation %s evaluator matches draw chunk 0' % mut_name, + lane_results(mut_exprs, first_chunk) == wrong_words) + + # 7. Unlowered negative control: removing v_mad_u32_u16 from VEC_U must refuse. + saved = G.VEC_U.pop('v_mad_u32_u16') + try: + reason = refused_bytes(BODY_WORDS[:8]) + check('unlowered control refuses v_mad_u32_u16', reason == 'v_mad_u32_u16', repr(reason)) + finally: + G.VEC_U['v_mad_u32_u16'] = saved + + +def check_binary(llvm_mc): + built = assemble(llvm_mc, BODY_SOURCE) + if built != BODY_WORDS: + raise AssertionError('body: assembled %s, recorded %s' % (built.hex(), BODY_WORDS.hex())) + for name, source, words in (('prologue', PRE_SOURCE, PRE_WORDS), ('export', POST_SOURCE, POST_WORDS)): + if assemble(llvm_mc, source) != words: + raise AssertionError('%s fixture differs from llvm-mc' % name) + for _, word_bytes, want_asm, _, _ in SYNTHETIC_CASES: + built = assemble(llvm_mc, want_asm + '\n') + if built != word_bytes: + raise AssertionError('%s: assembled %s, recorded %s' % (want_asm, built.hex(), word_bytes.hex())) + for i in range(0, len(DRAW_SETS), 4): + chunk = DRAW_SETS[i:i + 4] + if assemble(llvm_mc, vs_source(chunk)) != vs_words(chunk): + raise AssertionError('vertex fixture for %s differs from llvm-mc' % (chunk,)) + print('fixture words match llvm-mc') + + +def check_draw(dxc, renderer, adapter, fxc=None): + controls() + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + good_ps = compile_hlsl(compiler, kind, translate_ps()[1], 'ps_mad_u32_u16_%s' % kind, ps_profile, directory) + for index in range(0, len(DRAW_SETS), 4): + chunk = DRAW_SETS[index:index + 4] + vs = compile_hlsl(compiler, kind, G.Pipeline(vs_words(chunk), PS_WORDS, root_blob()).hlsl_vs(), + 'vs_mad_u32_u16_%d_%s' % (index, kind), vs_profile, directory) + expected = words_text(ref_mad_u32_u16(*x) for x in chunk) + run = draw(renderer, adapter, vs, good_ps, expected) + if run.returncode: + raise AssertionError('%s chunk %d inputs %s\n%s\n%s' + % (kind, index // 4, chunk, run.stdout, run.stderr)) + print('%s chunk %d %s: %s' % (kind, index // 4, + [tuple('%08x' % v for v in x) for x in chunk], expected), flush=True) + if index: + continue + for mut_name, (_, _, mut_ref) in MUTATIONS.items(): + wrong = words_text(mut_ref(*x) for x in chunk) + bad_ps = compile_hlsl(compiler, kind, translate_ps(mut_name)[1], + 'mutated_%s_%s' % (mut_name, kind), ps_profile, directory) + run = draw(renderer, adapter, vs, bad_ps, expected) + if run.returncode == 0 or 'actual=%s' % wrong not in run.stderr: + raise AssertionError('%s mutation %s did not read %s\n%s\n%s' + % (kind, mut_name, wrong, run.stdout, run.stderr)) + print('%s mutation %s: fails as expected, reads %s' % (kind, mut_name, wrong), flush=True) + + +def main(): + if len(sys.argv) == 1: + controls() + return + mode, *args = sys.argv[1:] + if mode == 'binary': + check_binary(*args) + elif mode == 'draw': + check_draw(*args) + else: + raise SystemExit(__doc__) + + +if __name__ == '__main__': + main() diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 5a3d344dc..52a35b79d 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -3344,6 +3344,11 @@ def lower(self, base, asm, ops, mods): c0, c1 = self.const_u32(ops[1]), self.const_u32(ops[2]) args = [self.u(ops[1], low16_only=c1 is not None and (c1 & 0xffff0000) == 0), self.u(ops[2], low16_only=c0 is not None and (c0 & 0xffff0000) == 0)] + elif base == 'v_mad_u32_u16': + # S0 and S1 read only bits [15:0]; S2 reads all 32 bits. + args = [self.u(ops[1], low16_only=True), + self.u(ops[2], low16_only=True), + self.u(ops[3])] else: args = [self.u(o) for o in ops[1:1 + arity]] if base in ('v_sad_u8', 'v_sad_u16', 'v_sad_u32'): @@ -7146,6 +7151,7 @@ def declarations(self): 'v_cvt_f16_f32': (1, 'f32tof16(F({0}))'), 'v_bfe_u32': (3, '({0} >> ({1} & 31)) & ((1u << ({2} & 31)) - 1)'), 'v_mad_u32_u24': (3, '({0} & 0xffffffu) * ({1} & 0xffffffu) + {2}'), 'v_mad_i32_i24': (3, 'asuint(asint({0} << 8) >> 8) * asuint(asint({1} << 8) >> 8) + {2}'), + 'v_mad_u32_u16': (3, '({0} & 0xffffu) * ({1} & 0xffffu) + {2}'), 'v_lshl_add_u32': (3, '({0} << ({1} & 31)) + {2}'), 'v_add_lshl_u32': (3, '({0} + {1}) << ({2} & 31)'), 'v_add3_u32': (3, '{0} + {1} + {2}'), 'v_or3_b32': (3, '{0} | {1} | {2}'), 'v_xor3_b32': (3, '{0} ^ {1} ^ {2}'), 'v_and_or_b32': (3, '({0} & {1}) | {2}'), 'v_lshl_or_b32': (3, '({0} << ({1} & 31)) | {2}'), 'v_xad_u32': (3, '({0} ^ {1}) + {2}'), 'v_bfi_b32': (3, '({0} & {1}) | (~{0} & {2})'), From d837f75e75207a398e5ac469a3f04642d6cee0d5 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 26 Nov 2026 01:03:01 +0000 Subject: [PATCH 064/240] startup: pixel image_store sparse DMASK via read-modify-write Typed UAV stores write all four channels, so a partial DMASK needs an RMW. Accept non-empty pixel-stage masks and overwrite selected channels in VDATA order (M200-01 I). Compute and D16 still require dmask 0xf. Fixture: dmask 0x5 leaves y/w at the UAV clear; full-write control must mismatch. Refs #2618 Co-authored-by: SimSalabimse --- docs/experiments.md | 16 ++--- tests/startup_pixel_image_store_check.py | 79 ++++++++++++++++++++---- tools/startup/gfx2hlsl.py | 47 ++++++++++---- 3 files changed, 111 insertions(+), 31 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 8c9b7049a..9ba3e59d8 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14718,18 +14718,20 @@ VGPRs and the eight image descriptor words come from an unmodified fixed table offset. The translator emits `asfloat(uint4(...))` into a `RWTexture2D` under the lane's EXEC bit and records `uav N tex2d float table P O channels 4` in the version 2 compute manifest. Pixel-stage 2D `image_store` also accepts -`unorm`. +`unorm` and a sparse DMASK: channels selected by the mask are written in order +from consecutive VDATA registers via a float4 read-modify-write of the typed +UAV (M200-01 I). Compute still requires DMASK `0xf`. -The standalone dispatch reuses the source and CPU reference from the -[gfx1013 2D float store fixture](#gfx1013-2d-float-image-stores-and-mip-loads). -Two groups write 16 texels to mip zero of an `R32G32B32A32_FLOAT` UAV while -comparing all 1,344 words across three mips. A second program masks out the -second row. Omitting the store, swapping R/B, swapping RG/BA and dropping the -EXEC guard produce 64, 32, 64 and 32 mismatches respectively. +`tests/startup_pixel_image_store_check.py` covers the full-mask store and a +`dmask:0x5` (x and z) program whose UAV starts at -1 in every channel; after the +store the named texel is `(1, -1, 2, -1)` and every other texel stays -1. Replacing +the RMW with a full four-channel write must mismatch. Empty and out-of-range +masks stay refused. ```powershell cmake --build --preset release --target offscreen_check ctest --preset release --no-tests=error -R '^startup_compute_image_store(_warp|_hardware)?$' -V +ctest --preset dev --no-tests=error -R '^startup_pixel_image_store' -V ``` ### Explicit-LOD 2D gather diff --git a/tests/startup_pixel_image_store_check.py b/tests/startup_pixel_image_store_check.py index 7c1c0c4ac..ce771eba7 100644 --- a/tests/startup_pixel_image_store_check.py +++ b/tests/startup_pixel_image_store_check.py @@ -1,10 +1,14 @@ -"""Check gfx2hlsl's pixel-stage image_store on a hand-assembled gfx1013 program (#1996 item F). +"""Check gfx2hlsl's pixel-stage image_store on a hand-assembled gfx1013 program (#1996 item F; M200-01 I). The pixel program loads an image descriptor from descriptor table 0, sets the texel address (1, 2) and four distinct binary32 values, stores them with image_store ... dmask:0xf dim:SQ_RSRC_IMG_2D, and exports the same values to mrt0. The words were assembled by hand from the MIMG layout and are decoded back by tools/disasm_rdna2.py here; --llvm-mc reassembles the source and compares the words. +A second program uses dmask:0x5 (x and z) so VDATA is two registers: the UAV starts at -1 in every +channel, the store writes 1.0 and 2.0 into x and z, and y/w stay -1. That is the sparse-mask RMW the +M200-01 I starter asks for. + Without arguments: translation controls and refusals. With draw: also compile the translation with DXC and draw it through offscreen_check --startup-image-store, which reads every texel of a 4x4 image back. Negative controls: the translator refuses the program when the lowering is removed, and the translated shader with @@ -45,12 +49,19 @@ s_endpgm """ STORE = bytes.fromhex('080f20f000040400') +# dmask:0x5 → VDATA v[4:5] written to channels x then z (same PREFIX: v4=1.0, v5=2.0). +STORE_XZ = bytes.fromhex('080520f000040400') PREFIX = bytes.fromhex('04040cf4000000fa' '8102007e' '8202027e' 'f202087e' 'f4020a7e' 'ff020c7e00004040' 'f6020e7e' '7fc08cbf') SUFFIX = bytes.fromhex('703f8cbf' '0f1800f804050607' '000081bf') WORDS = PREFIX + STORE + SUFFIX +WORDS_XZ = PREFIX + STORE_XZ + SUFFIX STORE_LINE = 'w0[uint2(v0, v1)] = asfloat(uint4(v4, v5, v6, v7));' +# Init -1: after xz store, texel is (1.0, -1.0, 2.0, -1.0). +SPARSE_LINE = ('t = w0[uint2(v0, v1)]; t.x = asfloat(v4); t.z = asfloat(v5); ' + 'w0[uint2(v0, v1)] = t;') GUARDED_LINE = 'if (exec & 1) ' + STORE_LINE +SPARSE_BITS = ['3f800000', 'bf800000', '40000000', 'bf800000'] # 1.0, -1.0, 2.0, -1.0 def cmpx_eq(constant): @@ -107,7 +118,7 @@ def controls(): print('glc, slc, dlc and unorm accepted') # Refusals, each by name: packed data or addresses, fault-status returns, a 128-bit descriptor, - # a partial channel mask and other image dimensions. + # and other image dimensions. cases = (('d16', patched(7, 0x80)), ('a16', patched(7, 0x40)), ('tfe', patched(2, 0x01)), ('lwe', patched(2, 0x02)), ('r128', patched(1, 0x80)), ('reserved', patched(1, 0x40)), ('SQ_RSRC_IMG_3D', bytes.fromhex('100f20f000040400')), @@ -118,22 +129,38 @@ def controls(): message = refused(with_store(store), 'image_store') print('refused %-20s %s' % (name + ':', message)) assert decoded.startswith('image_store'), decoded - # A partial channel mask, encoded: the decoder sizes VDATA from the mask (v[4:6], v4), so each must be - # refused for the mask itself, which the translator checks before the data registers. - for mask, data in ((0x7, 'v[4:6]'), (0x1, 'v4')): + # Sparse DMASK: channels selected by the mask are written in order from consecutive VDATA registers. + # The UAV starts at -1; dmask:0x5 with v[4:5] = (1.0, 2.0) yields (1, -1, 2, -1). + decoded_xz = D.decode_instruction(STORE_XZ, 0)[2] + assert decoded_xz == 'image_store v[4:5], v[0:1], s[16:23] dmask:0x5 dim:SQ_RSRC_IMG_2D', decoded_xz + sparse_ps = translate(WORDS_XZ).hlsl_ps() + assert ' ' + SPARSE_LINE in sparse_ps, sparse_ps + print('sparse dmask 0x5: %s' % SPARSE_LINE) + for mask, data, count in ((0x7, 'v[4:6]', 3), (0x1, 'v4', 1), (0x3, 'v[4:5]', 2)): store = patched(1, 0, mask) decoded = D.decode_instruction(store, 0)[2] assert decoded.startswith('image_store %s, ' % data) and 'dmask:%#x' % mask in decoded, decoded - message = refused(with_store(store), 'dmask %#x' % mask, 'writes all four channels') - print('refused %-20s %s' % ('dmask %#x:' % mask, message)) - # The same partial mask with four data registers, through the handler: only the mask guard can refuse it. + text = translate(with_store(store)).hlsl_ps() + store_line = next(line for line in text.splitlines() if 't = w0[uint2(v0, v1)];' in line) + assert store_line.count('t.') == count, (mask, store_line) + print('sparse dmask %#x accepted (%d channel(s))' % (mask, count)) + # Wrong VGPR count for a sparse mask is refused for the data, not the mask. try: - pipe.ps.op_image_store(['v[4:7]', 'v[0:1]', 's[16:23]'], ['dmask:0x7', 'dim:SQ_RSRC_IMG_2D']) + pipe.ps.op_image_store(['v[4:7]', 'v[0:1]', 's[16:23]'], ['dmask:0x5', 'dim:SQ_RSRC_IMG_2D']) except G.Unsupported as error: - assert 'dmask 0x7' in str(error) and 'writes all four channels' in str(error), error + assert '2 VGPRs expected' in str(error), error else: - raise AssertionError('a partial dmask with four data registers was accepted') - print('refused dmask 0x7 with four data registers (v[4:7])') + raise AssertionError('dmask 0x5 with four data registers was accepted') + print('refused dmask 0x5 with four data registers (v[4:7])') + # Empty and out-of-range masks still refuse like a full-channel typed store. + for bad in (0x0, 0x10): + try: + pipe.ps.op_image_store(['v4', 'v[0:1]', 's[16:23]'], ['dmask:%#x' % bad, 'dim:SQ_RSRC_IMG_2D']) + except G.Unsupported as error: + assert 'writes all four channels' in str(error), error + else: + raise AssertionError('dmask %#x was accepted' % bad) + print('refused dmask 0x0 and 0x10') # Four data registers are required for the full mask: three are refused for the data, not the mask. try: pipe.ps.op_image_store(['v[4:6]', 'v[0:1]', 's[16:23]'], ['dmask:0xf', 'dim:SQ_RSRC_IMG_2D']) @@ -142,6 +169,17 @@ def controls(): else: raise AssertionError('dmask 0xf with three data registers was accepted') print('refused dmask 0xf with three data registers (v[4:6])') + # Compute still requires the full mask (shared handler; pixel-only sparse). + try: + pipe.ps.kind = 'cs' + pipe.ps.op_image_store(['v[4:5]', 'v[0:1]', 's[16:23]'], ['dmask:0x5', 'dim:SQ_RSRC_IMG_2D']) + except G.Unsupported as error: + assert 'writes all four channels' in str(error), error + else: + raise AssertionError('compute sparse dmask was accepted') + finally: + pipe.ps.kind = 'ps' + print('refused compute-stage sparse dmask 0x5') # Mask text that is not an integer is a named refusal, not a ValueError. try: pipe.ps.op_image_store(['v[4:7]', 'v[0:1]', 's[16:23]'], ['dmask:0xz', 'dim:SQ_RSRC_IMG_2D']) @@ -247,6 +285,23 @@ def draw(text, label, want=expected): raise AssertionError('control exec guard removed was not detected\n%s\n%s' % (run.stdout, run.stderr)) print('control exec guard removed: fails as expected (%s)' % mismatch_line(run.stderr)) + # Sparse dmask 0x5: only x and z change; y and w stay at the UAV clear (-1.0). + sparse_want = ','.join(SPARSE_BITS) + sparse_source = translate(WORDS_XZ).hlsl_ps() + assert SPARSE_LINE in sparse_source, sparse_source + run = draw(sparse_source, 'store_xz', sparse_want) + if run.returncode: + raise AssertionError('sparse store draw failed\n%s\n%s' % (run.stdout, run.stderr)) + print('draw sparse dmask 0x5: texel (1, 2) = %s' % sparse_want) + # Control: writing all four channels instead of the RMW must mismatch on y and w. + full_instead = sparse_source.replace(SPARSE_LINE, STORE_LINE) + assert full_instead != sparse_source + run = draw(full_instead, 'sparse_as_full', sparse_want) + needle = 'texel_mismatch x=1 y=2 expected=%s actual=%s' % (sparse_want, expected) + if run.returncode == 0 or needle not in run.stderr: + raise AssertionError('control sparse-as-full was not detected\n%s\n%s' % (run.stdout, run.stderr)) + print('control sparse-as-full: fails as expected (%s)' % mismatch_line(run.stderr)) + def main(): controls() diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 9c3d579e5..590eccbdf 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -5531,13 +5531,14 @@ def fixed_table_image(self, operand, name): return self.descriptor(operand) def op_image_store(self, ops, mods): - """Write one four-channel 2D texel from pixel FP32 or compute packed FP16 data. + """Write selected 2D texel channels from pixel FP32 or compute packed FP16 data. MIMG opcode 0x08 (LLVM AMDGPU MIMGInstructions.td, IMAGE_STORE via MIMG_Store): VDATA is the source, VADDR the integer texel address (x, y for dim 2D) and SRSRC the image descriptor; the channels selected by DMASK are written in order from consecutive VDATA registers. HLSL's typed UAV - store writes every channel of the view, so only DMASK 0xf is exact here; a partial mask would need a - read-modify-write and is refused. The data is stored as float4, so the bound view must be of a + store writes every channel of the view, so a full DMASK 0xf is a direct assignment. A partial mask + on a pixel stage is a read-modify-write of the float4 texel (M200-01 I / #2618 starter). Compute + and D16 stores still require DMASK 0xf. The data is stored as float4, so the bound view must be of a float or normalized format (the runtime side is not part of this lowering). The store runs under the lane's exec bit, like the other per-lane writes, and D3D drops UAV writes from helper lanes as the hardware drops them for lanes outside exec. @@ -5564,12 +5565,18 @@ def op_image_store(self, ops, mods): mask = int(masks[0], 0) except ValueError: raise Unsupported('%s with dmask %s: not an integer' % (name, masks[0])) from None - if mask != 0xf: - raise Unsupported('%s with dmask %s: a typed UAV store writes all four channels' % (name, masks[0])) + sparse = self.kind == 'ps' and not d16 and mask and not (mask & ~0xf) and mask != 0xf + if d16 or self.kind == 'cs' or not sparse: + if mask != 0xf: + raise Unsupported('%s with dmask %s: a typed UAV store writes all four channels' % ( + name, masks[0])) + count = 2 if d16 else 4 + else: + count = bin(mask).count('1') data = reg_range(ops[0]) - count = 2 if d16 else 4 if not data or data[0] != 'v' or data[2] - data[1] + 1 != count or data[2] > 255: - raise Unsupported('%s data %s: %s VGPRs expected' % (name, ops[0], 'two' if d16 else 'four')) + raise Unsupported('%s data %s: %s VGPRs expected' % ( + name, ops[0], 'two' if d16 else ('four' if count == 4 else str(count)))) coords = ops[1] if coords.startswith('['): cs = [c.strip() for c in coords[1:-1].split(',')] @@ -5585,15 +5592,31 @@ def op_image_store(self, ops, mods): key = self.fixed_table_image(ops[2], name) else: key = self.descriptor(ops[2]) + image = self.pipe.uav(key, 'tex2d') + index = 'uint2(%s, %s)' % (self.u(cs[0]), self.u(cs[1])) if d16: # RDNA 2 ISA §8.2.5: RG occupy VDATA, BA occupy VDATA+1, low half first. rgba = ['f16tof32(%s & 0xffffu), f16tof32(%s >> 16)' % (word, word) for word in words] - value = 'float4(%s)' % ', '.join(rgba) + body = '%s[%s] = float4(%s);' % (image, index, ', '.join(rgba)) + elif sparse: + # Typed UAV writes all four channels: read the texel, overwrite DMASK channels in VDATA order. + # Reuse the stage's scratch float4 `t` (declared in every pixel entry) so the RMW stays one emit. + parts = ['t = %s[%s]' % (image, index)] + src = 0 + for bit, channel in enumerate('xyzw'): + if mask & (1 << bit): + parts.append('t.%s = asfloat(%s)' % (channel, words[src])) + src += 1 + parts.append('%s[%s] = t' % (image, index)) + body = '; '.join(parts) + ';' else: - value = 'asfloat(uint4(%s))' % ', '.join(words) - image = self.pipe.uav(key, 'tex2d') - body = '%s[uint2(%s, %s)] = %s;' % (image, self.u(cs[0]), self.u(cs[1]), value) - self.emit(body if self.exec_known else 'if (exec & 1) ' + body) + body = '%s[%s] = asfloat(uint4(%s));' % (image, index, ', '.join(words)) + if self.exec_known: + self.emit(body) + elif sparse: + self.emit('if (exec & 1) { %s }' % body) + else: + self.emit('if (exec & 1) ' + body) def gather_2d_setup(self, name, ops, mods, addr_count, addr_label, *, mip_preclamp): if self.kind not in ('ps', 'cs') or len(ops) != 4: From de75613fb24270b1b1553573c01e9bd771f38836 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Thu, 26 Nov 2026 03:16:04 +0100 Subject: [PATCH 065/240] startup: compute input named by a resource heap record a root constant indexes (#2532) * feat: record the compute root signature and descriptor tables (slots 33 and 35) Header-only state in list_compute_root.h with a Linux-testable check. Dispatch (slot 14) is not handled here; the state is exposed through ready() and table() for it. Refs #870. * feat: record compute descriptor tables (slot 35) and clear them on a root or heap change * startup: record SetComputeRoot32BitConstant(s) (list slots 37, 39) Compute root constants are kept per list next to the graphics ones, in a shared 16 x 8 word store that refuses parameter >= 16 and offset >= 8. A new compute root signature clears them. * feat: record command-list slot 14 Dispatch on the desktop list Part of #870. Forward Dispatch only with a desktop compute pipeline and root bound and group counts within 65535 per axis; refuse otherwise. * startup: refuse Dispatch under a compute root with unforwarded arguments, document slot 14 * startup: gate Dispatch on bound compute root SRVs and a pipeline built against the bound root Slot 43 clears a parameter's binding when a replacement is rejected, slot 33 clears all bindings, and the compute pipeline records its root so a mismatched pair is refused. * startup: record SetComputeRoot32BitConstant(s) (list slots 37, 39) Compute root constants are kept per list next to the graphics ones, in a shared 16 x 8 word store that refuses parameter >= 16 and offset >= 8. A new compute root signature clears them. * feat: record command-list slot 14 Dispatch on the desktop list Part of #870. Forward Dispatch only with a desktop compute pipeline and root bound and group counts within 65535 per axis; refuse otherwise. * startup: refuse Dispatch under a compute root with unforwarded arguments, document slot 14 * startup: gate Dispatch on bound compute root SRVs and a pipeline built against the bound root Slot 43 clears a parameter's binding when a replacement is rejected, slot 33 clears all bindings, and the compute pipeline records its root so a mismatched pair is refused. * fix: pass pipeline root out-param in slot86 mesh cached pipeline build * fix: track which compute root constant words were set; drop slot 40 claim * Dispatch translated compute programs with raw table buffers A device slot 67 placeholder keeps the key of its published request. At list slot 14 the stand-in loads the stage cs manifest and compiled program for that key and records the dispatch: raw buffer inputs and outputs from hardware descriptors in the recorded compute tables, entry values from the recorded compute root constants. Other manifest lines leave the pipeline untranslated; a dispatch that cannot be bound completely is refused with one logged reason and records nothing. startup_compute_dispatch_{warp,hardware} drives a source-built program through the stand-in list and reads the output back, with controls before translation, without a Dispatch and for a refused output. Co-Authored-By: Claude Fable 5.2 * Log untranslated compute dispatches on their own line budget Dispatches that arrive before the offline translation no longer use up the lines kept for refusals at bind time. Co-Authored-By: Claude Fable 5.2 * Count compute dispatches per key with their first refusal The per-call refusal lines share one small budget, so a run cannot rank keys by dispatch count. Each key now keeps its Dispatch count, the calls recorded and the reason and table descriptor of its first refusal; the periodic totals are followed by the refused dispatches per reason and the 40 keys with the most dispatches. A manifest that exists but cannot be bound is counted apart from an absent one ("not modelled"). Co-Authored-By: Claude Fable 5.2 * Dispatch translated compute programs that store to 2D textures A `uav tex2d float table channels 4` manifest line is bound from the token of the unordered access view the title created in its descriptor memory. Everything else is refused with its own reason: an entry that is no such token, a view the desktop did not create, a view that is not 2D, a format a float4 store cannot target, and a texture bound to two slots of one dispatch. Programs without entry values, inputs or outputs load too: the translated root no longer emits an empty range or drops the table when only outputs exist. The fixture stores through the stand-in's own list into a 32x8 RGBA16_FLOAT texture and reads it back with CopyTextureRegion. Co-Authored-By: Claude Fable 5.2 * Dispatch translated compute programs that read 2D textures A `srv tex2d table ` manifest line is bound from the token of the shader resource view the title created, through the texture the draw path samples for that resource, uploaded first when the title filled it in memory. `smp` lines become static samplers of the translated root. A dispatch is refused, never bound to a null view, when the entry is no such token, the resource has no desktop texture, the view is not 2D or names a packed format, or the upload fails. Sampler heaps, comparison samplers and other texture kinds keep the translation unavailable. The fixture samples a 1x1 texture into the stored words of the raw buffer case; without a view the dispatch is refused and the output is untouched. Co-Authored-By: Claude Fable 5.2 * Check a compute manifest without entry values at Dispatch Co-Authored-By: Claude Fable 5.2 * Document texture views and the census of translated compute Dispatch Co-Authored-By: Claude Fable 5.2 * Check the device on every 64th translated Dispatch and drop a liveness test The device check drains the debug layer; a draw runs it on every 64th call and the queue's execute drains the rest. A view token whose resource the caller released is the caller's misuse, as on the draw path. Co-Authored-By: Claude Fable 5.2 * Compute dispatch: allow two outputs of one texture, refuse packed outputs, print every census key A texture is refused only when the same call reads and writes it; two outputs of one texture share the unordered access state. A packed output view format gets its own refusal reason. The census prints every dispatched key instead of the first 40, and the wording on refused calls says what may already be recorded (an input texture upload). Co-Authored-By: Claude Fable 5.2 * startup: compute input named by a resource heap record a root constant indexes gfx2hlsl.py lowers one form of a register-offset load through the directly indexed resource heap pointer of a compute root signature: s_lshl_b32 R, , 5 s_load_dwordx4 D, s[H:H+1], R ; s[H+1] a constant zero, no offset: with no write of R and no branch target in between. D is a buffer descriptor and the manifest names it `srv buf heap rootconst `. Every other form keeps a refusal that names it, including an index read from a buffer. The stand-in records the title memory of the list's view heap on every slot 32 call (it kept only the sampler heap and, for oversized heaps, the wrapper) and a Dispatch reads the 16-byte descriptor at byte `word << 5` of that memory, then binds it through the path a table record takes. A record outside the heap refuses the dispatch and binds nothing. Checks: tests/startup_gfx2hlsl_heap_record_check.py (manifest and HLSL exact, 19 refused controls, one translator mutation, LLVM 15 reassembly) and tests/startup_compute_dispatch_heap_check.py on WARP and a physical adapter. Refs #2274 Co-Authored-By: Claude Fable 5.2 * startup: drop a heap record control whose branch target was inside an instruction The second positive case of startup_gfx2hlsl_heap_record_check.py branched to the second dword of the two-dword heap load. The case with a branch target before the shift already covers the form outside the entry block. The experiments entry now says that WARP's descriptor increment is not 32 bytes. Refs #2274 Co-Authored-By: Claude Fable 5.2 * startup: read the stage kind as the other handlers do in the heap load A check added on main calls op_s_load_dwordx8 on a stage built without a kind; the heap record branch read self.kind directly. Co-Authored-By: Claude Fable 5.2 * startup: avoid calling the compute driver after process termination begins The slot 67 cache owns desktop COM objects until module teardown. During process termination, the driver can already be shut down when static destructors run. Keep normal reference release on explicit unload and skip driver calls only during process termination. AI-assisted with Codex (GPT-6.2 Astra, xhigh). * Repair a broken line in the dispatch check Co-Authored-By: Claude Fable 5.2 * Pin four existing texture dispatch refusals: integer view format, manifest version, stage, output also an input Co-Authored-By: Claude Fable 5.2 * Drop the repeated compute root reset left by merging two slot 14 snapshots list_compute_root cleared compute_srv_bound and recomputed compute_root_has_arguments twice; the second copy came from the second #1974 snapshot merge and changed nothing. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: tedin7 Co-authored-by: tedin7 Co-authored-by: Claude Fable 5.2 Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> Co-authored-by: RavenCurseBurg <360931527+RavenCurseBurg@users.noreply.github.com> --- .github/workflows/windows.yml | 2 + AGENTS.md | 1 + CMakeLists.txt | 13 + docs/experiments.md | 42 ++ src/startup_stubs/d3d12_compute_dispatch.inl | 399 ++++++++++++++++++ src/startup_stubs/d3d12_draw.inl | 17 +- src/startup_stubs/d3d12_xs_device.cpp | 22 +- .../translated_sampler_bindings.h | 11 +- tests/startup_compute_dispatch_check.py | 132 ++++++ tests/startup_compute_dispatch_heap_check.py | 87 ++++ .../startup_compute_dispatch_texture_check.py | 203 +++++++++ tests/startup_gfx2hlsl_heap_record_check.py | 236 +++++++++++ tests/startup_stream_consumer.cpp | 229 +++++++++- tools/startup/gfx2hlsl.py | 46 ++ 14 files changed, 1429 insertions(+), 11 deletions(-) create mode 100644 src/startup_stubs/d3d12_compute_dispatch.inl create mode 100644 tests/startup_compute_dispatch_check.py create mode 100644 tests/startup_compute_dispatch_heap_check.py create mode 100644 tests/startup_compute_dispatch_texture_check.py create mode 100644 tests/startup_gfx2hlsl_heap_record_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 3e4bf90d4..3ff1ffbdc 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -103,6 +103,7 @@ jobs: (["tests/startup_compute_image_store_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_compute_image_store_d16_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_compute_readfirstlane_check.py", "--llvm-mc", "llvm-mc-15"], {}), + (["tests/startup_gfx2hlsl_heap_record_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_compute_gather_l_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_compute_buffer_atomics_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_compute_store_d16_x_check.py", "binary", "llvm-mc-15"], {}), @@ -284,6 +285,7 @@ jobs: tests/startup_joined_table_pointer_check.py \ tests/startup_gfx2hlsl_readfirstlane_recompute_check.py \ tests/startup_compute_readfirstlane_check.py \ + tests/startup_gfx2hlsl_heap_record_check.py \ tests/startup_gfx2hlsl_calculated_target_check.py \ tests/startup_triage_run_check.py \ tests/startup_run_ps1_check.py \ diff --git a/AGENTS.md b/AGENTS.md index 1c9d01c42..543bdb057 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -170,6 +170,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_compute_check.py ./out/pe-env/bin/python -B tests/startup_compute_image_store_check.py ./out/pe-env/bin/python -B tests/startup_compute_image_store_d16_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_heap_record_check.py ./out/pe-env/bin/python -B tests/startup_compute_store_format_xyzw_check.py ./out/pe-env/bin/python -B tests/startup_compute_translate_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_swap_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 8f2a1a322..d52759dd9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3267,6 +3267,8 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_image_store_check.py") add_test(NAME startup_compute_image_store_d16 COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_image_store_d16_check.py") + add_test(NAME startup_gfx2hlsl_heap_record COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_heap_record_check.py") add_test(NAME startup_compute_readfirstlane COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_readfirstlane_check.py") add_test(NAME startup_compute_gather_l COMMAND "${INTAKE_PYTHON}" -B @@ -4244,6 +4246,17 @@ if(EXISTS "${INTAKE_PYTHON}") PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) set_tests_properties(startup_compute_translate_e2e_wrong_group_${adapter} PROPERTIES PASS_REGULAR_EXPRESSION "control wrong-group: rejected at word=[0-9]+ ") + add_test(NAME startup_compute_dispatch_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_dispatch_check.py" "$" + "${DXC_EXECUTABLE}" ${adapter}) + add_test(NAME startup_compute_dispatch_texture_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_dispatch_texture_check.py" "$" + "${DXC_EXECUTABLE}" ${adapter}) + add_test(NAME startup_compute_dispatch_heap_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_dispatch_heap_check.py" "$" + "${DXC_EXECUTABLE}" ${adapter}) + set_tests_properties(startup_compute_dispatch_${adapter} startup_compute_dispatch_texture_${adapter} + startup_compute_dispatch_heap_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() add_test(NAME startup_stream_adapter_filter COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stream_rasterizer_check.py" diff --git a/docs/experiments.md b/docs/experiments.md index 4f458311d..92d6a0745 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -16038,6 +16038,17 @@ ctest --preset dev --no-tests=error -R "^startup_image_sample_d_draw_(warp|hardw `tests/startup_gfx2hlsl_mul24_align_check.py` translates each instruction, evaluates the emitted text on the CPU against a reference written with unbounded integers, and checks that `v_mul_hi_u32_u24` is refused. Run with `python3 -B tests/startup_gfx2hlsl_mul24_align_check.py` (`ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_mul24_align$' -V`). `tests/startup_gfx2hlsl_mul24_align_draw_check.py` draws the six translated instructions through FXC `ps_5_1` and DXC `ps_6_0` and compares the GPU readback with the same reference (`startup_gfx2hlsl_mul24_align_warp` and `_hardware`); both compilers run before the test fails, so one compiler's failure does not hide the other's result. The draw covers the six translated instructions only. +## Startup list Dispatch + +Command-list slot 14 (`Dispatch`) is recorded on the desktop list only when the list is open and direct or compute, a desktop compute pipeline and a desktop compute root signature are bound, the compute root declares no static samplers and only root SRV parameters (slot 43), the compute pipeline was built against that same root signature, every root SRV the root declares was set since the root was bound (a rejected or unaligned replacement clears its binding), and every group count is at most 65535. Zero groups on an axis is forwarded and runs nothing. A root with other parameters is refused with `compute root arguments are not forwarded`, a pipeline from another root with `compute pipeline was built against another root signature`, an unset or rejected root SRV with `a compute root SRV is not bound`, because this path forwards none of the compute root-argument slots (35, 37, 39, 41, 45) to the desktop list and the dispatch would run with them unset. Other refusals are logged as `x2w-render Dispatch(x, y, z) refused: `. + +Only the decision is checked: `tests/startup_list_dispatch_check.cpp` runs without a device and its five mutated runs must fail. Executing a dispatch on a GPU, with real results read back, is not verified yet. + +```powershell +cmake --build --preset dev --target startup_list_dispatch_check +ctest --preset dev --no-tests=error -R "^startup_list_dispatch" -V +``` + ## Non-constant scalar symbols at branch targets in the startup translator Follow-up to #2279, which drops scalar constants at a join that another path writes, over the textual range between @@ -16060,6 +16071,37 @@ is 0, so bit 0 of the result is 0 (1 for `s_orn2_b64`) whatever S holds. This re a lane whose exec bit is 0 takes the branch; it is pure Python only, not run on a GPU, and its words are built from the field layouts rather than assembled. +## Translated compute Dispatch + +With a device slot 67 placeholder bound, command-list slot 14 looks up the translation of the pipeline's published request (`.txt` with `stage cs`, and `.cs.cso`) and records it on the desktop list. It binds, from the compute descriptor tables of slot 35: raw buffers named by 16-byte hardware buffer descriptors, and 2D textures named by the token of a view the caller created (device slot 18 for an input, slot 19 for an output the program stores `float4` to). `smp` manifest lines become static samplers, and entry values come from the compute root constants of slots 37 and 39. A buffer input must resolve to a complete GPU-backed range; a buffer output must be a placed buffer that aliases the caller's memory and allows unordered access; a texture view must be 2D, created on the desktop, and for an output have a float or normalized format that is not packed, on a texture that is not also an input of the call. Any other manifest line (other texture kinds, sampler heaps, comparison samplers, root views, `stride` and `descword3` entry values) leaves the pipeline untranslated, and a Dispatch that cannot be bound completely is refused with one logged reason: no Dispatch is recorded and nothing is bound (the upload of an input texture the caller filled in memory may already be recorded; it only syncs content). No view is ever bound null. The entry values live in the compute root-constant store of #1975: a word no slot 37 or 39 call wrote since the compute root was set (slot 33 with another root, or a list reset) has no value and is refused with `an entry value was not set since the compute root`; setting the same root again keeps the words, and the graphics words of slot 40 are separate. + +`tests/startup_compute_dispatch_check.py` drives a source-built gfx1013 program through the stand-in's list on WARP and on a physical adapter (exit 77 without one) and reads the 320 output words back from the aliased memory. Controls in the same run: before the offline translation, without a Dispatch, and with the two descriptors exchanged, every output word must keep its sentinel. The two entry values arrive through slot 37 and slot 39, with other values written through slot 40 in between; `dispatch-same-root` must still give the expected words, and five refused modes must log their reason and keep the sentinels: a missing word, another compute root set and the first set again, a list reset, a compute root that is not the pipeline's, and one buffer named as input and output. `tests/startup_compute_dispatch_texture_check.py` does the same for a program that stores to a 32x8 RGBA16_FLOAT texture (1024 halves read back through CopyTextureRegion; controls: before translation, without a Dispatch, a texture without unordered access) and for the raw buffer program with a level-zero sample of a 1x1 texture XORed into each stored word (control: no view at the table entry). The texture output program is also bound under a manifest edited to declare no entry values. + +The log line `x2w-render compute dispatches: translated , refused , no translation , not modelled ` follows the render totals; "not modelled" counts calls whose manifest exists but holds a line the runtime does not bind. It is followed by a census: the refused calls per first refusal reason of their key, and every dispatched key by call count, each with its count, the calls recorded and the first refused table descriptor. + +Measured on three fixture programs. The sampling fixture uses a 1x1 texture, so it does not tell sampler filter or address modes apart. Programs with other texture kinds, sampler heaps, the same texture as input and output, or buffer outputs in memory that is not aliased are not dispatched. + +```powershell +cmake --build --preset dev --target startup_stream_consumer +ctest --preset dev --no-tests=error -R "^startup_compute_dispatch_" -V +``` + +### An input named by a resource heap record + +A compute root signature that indexes the resource heap directly (root flag 0x400) passes the heap pointer in one SGPR after the root parameters. `gfx2hlsl.py` lowers one form of a load through that pointer: `s_lshl_b32 R, , 5`, then, with no write of `R` and no branch target in between, `s_load_dwordx4 D, s[H:H+1], R` with a constant zero in `s[H+1]` and no `offset:` modifier. `D` is then a buffer descriptor, and the manifest names it `srv buf heap rootconst `. Slot 32 now records the title memory of the list's view heap on every call; at Dispatch the stand-in reads the 16-byte descriptor at byte `word << 5` (32-bit arithmetic, as the program computes it) of that memory and binds the buffer through the path a `table` record takes. A record outside the heap refuses the dispatch (`a heap record is outside the list's view heap`) and binds nothing. + +Every other form keeps a refusal that names it: another shift or index, an index register written again, a branch target between the shift and the load, a high word that is not a constant zero, an `offset:` modifier, eight dwords (an image record), and an index read from a buffer (`s_load of a resource heap record whose index is read from a buffer`). A formatted load or a store through such a record, and the graphics stages, are refused as before. + +`tests/startup_gfx2hlsl_heap_record_check.py` compares the manifest and the HLSL of a source-built gfx1013 program whole, runs 19 refused controls and one translator mutation (without the write tracking, a refused control translates), and with `--llvm-mc` reassembles every instruction. `tests/startup_compute_dispatch_heap_check.py` dispatches that program through the stand-in's list on WARP and on a physical adapter (exit 77 without one): the input descriptor is only in heap record 2, records 0 and 1 hold the output's descriptor, and all 320 output words must match; before translation and for a record outside the heap every word keeps its sentinel. Changing the runtime's shift to 4, or ignoring the index, makes the dispatch test fail (`an output buffer is also an input`). + +Measured on one synthetic program. The offset is a literal byte offset into the title's heap memory, as a table offset is; a heap whose descriptor increment on the desktop adapter is not 32 bytes (WARP is such an adapter, so its run covers the literal offset only) is not checked against a caller that addresses records by that increment. In a local set of 184 compute programs with a register-offset load through the heap pointer, every such load lowers in 4 programs and none of the 184 translates yet: 151 hold a load whose index is read from a buffer, and the 4 stop at other instructions. + +```powershell +python -B tests/startup_gfx2hlsl_heap_record_check.py --llvm-mc llvm-mc-15 +cmake --build --preset dev --target startup_stream_consumer +ctest --preset dev --no-tests=error -R "^startup_compute_dispatch_heap_" -V +``` + ## Startup compute dual-offset/stride-64 LDS ops and 32-bit LDS atomics [`tools/startup/gfx2hlsl.py`](../tools/startup/gfx2hlsl.py) (`lds_dual`, `lds_atomic`, `_lds_general_barrier_ok`, refs `#1541`, `#2274`) lowers the remaining 32-bit RDNA 2 DS dual-offset/stride-64 and unsigned/bitwise atomic instructions onto `groupshared uint lds[N]` (`COMPUTE_PGM_RSRC2.GRANULATED_LDS_SIZE`, nonzero and `<= 32 KiB` / 8192 dwords): diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl new file mode 100644 index 000000000..dffee3996 --- /dev/null +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -0,0 +1,399 @@ +// Translated compute programs at Dispatch (list slot 14). A device slot 67 pipeline is a placeholder that keeps +// the key of its published request; gfx2hlsl.py --pending answers the request with .txt (`stage cs`) and +// .cs.cso. Bound from the compute tables recorded by slot 35: raw buffers (`srv buf table ` +// inputs, `uav table ` outputs) named by hardware buffer descriptors, and 2D textures +// (`srv tex2d table ` inputs, `uav tex2d float table channels 4` outputs) named +// by the token of a view the title created (device slots 18 and 19). `smp` lines become static samplers. Entry +// values come from the compute root constants of slots 37 and 39. Any other manifest line makes the translation +// unavailable; a dispatch that cannot be bound completely is refused with one reason and records no Dispatch and +// binds nothing (the upload of an input texture the title filled in memory may already be recorded: it only +// syncs content). + +struct ComputeTranslation { + // Root parameter and byte offset (views), or parameter and word (entry values). A heap view names the root + // constant (parameter and word) that indexes its 32-byte record in the list's view heap. + struct Slot { int a, b; bool texture, heap; }; + u64 key = 0; + int state = 0; // 0 not loaded, 1 ready, 2 unavailable + ULONGLONG retry_manifest_at = 0; // only an absent manifest can become ready later + std::vector uds, srvs, uavs; + x2w_startup::TranslatedSamplers samplers; // static ones only + x2w_startup::ComPtr root; + x2w_startup::ComPtr pipeline; + const char* unmodelled = nullptr; // why a manifest that exists cannot be used + u64 dispatches = 0, translated = 0; // census: Dispatch calls with this key bound, and those recorded + const char* first_refusal = nullptr; // reason of the first refused call + std::uint32_t refusal_words[4] = {}; // the table descriptor that reason was about, if any; a view token's + // last word is replaced by its view format | dimension << 16 + ~ComputeTranslation() + { + // The per-process cache is destroyed during DLL detach. A driver may already have shut + // down when the process is terminating. Explicit unload still releases both references. + if (x2w_startup::d3d12_process_terminating) { + pipeline.Detach(); + root.Detach(); + } + } +}; + +// Formats a `float` typed output may be viewed with: the program stores float4. +bool float_output_format(DXGI_FORMAT format) +{ + switch (format) { + case DXGI_FORMAT_R32G32B32A32_FLOAT: case DXGI_FORMAT_R16G16B16A16_FLOAT: case DXGI_FORMAT_R16G16B16A16_UNORM: + case DXGI_FORMAT_R16G16B16A16_SNORM: case DXGI_FORMAT_R32G32_FLOAT: case DXGI_FORMAT_R10G10B10A2_UNORM: + case DXGI_FORMAT_R11G11B10_FLOAT: case DXGI_FORMAT_R8G8B8A8_UNORM: case DXGI_FORMAT_R8G8B8A8_SNORM: + case DXGI_FORMAT_R16G16_FLOAT: case DXGI_FORMAT_R16G16_UNORM: case DXGI_FORMAT_R16G16_SNORM: case DXGI_FORMAT_R32_FLOAT: + case DXGI_FORMAT_R8G8_UNORM: case DXGI_FORMAT_R8G8_SNORM: case DXGI_FORMAT_R16_FLOAT: case DXGI_FORMAT_R16_UNORM: + case DXGI_FORMAT_R16_SNORM: case DXGI_FORMAT_R8_UNORM: case DXGI_FORMAT_R8_SNORM: case DXGI_FORMAT_B8G8R8A8_UNORM: + return true; + default: + return false; + } +} +std::unordered_map& compute_translations() { static std::unordered_map m; return m; } +LONG compute_dispatches_translated, compute_dispatches_refused, compute_dispatches_untranslated, compute_dispatches_unmodelled; + +// draw_lock held. Returns the reason the translation is unavailable, or null when it is ready or still absent. +const char* load_compute_translation(ComputeTranslation& tr) +{ + tr.state = 2; + wchar_t path[MAX_PATH]; + std::string manifest; + if (!cache_path(path, L"", tr.key, L".txt") || !read_text(path, manifest)) { + tr.retry_manifest_at = GetTickCount64() + 1000; + return nullptr; + } + tr.retry_manifest_at = 0; + unsigned declared_uds = 0, line_number = 0; + for (std::size_t at = 0; at < manifest.size(); ++line_number) { + std::size_t end = manifest.find('\n', at); + if (end == std::string::npos) end = manifest.size(); + std::string line = manifest.substr(at, end - at); + at = end + 1; + if (!line.empty() && line.back() == '\r') line.pop_back(); + if (line_number == 0) { + if (line != "x2w-manifest 2") return "manifest version"; + continue; + } + if (line_number == 1) { + if (line != "stage cs") return "not a compute manifest"; + continue; + } + unsigned i = 0, x = 0, y = 0, z = 0, w = 0; + int a = 0, b = 0, used = 0; + const auto whole = [&] { return used == static_cast(line.size()); }; + if (line.empty() || (std::sscanf(line.c_str(), "group %u %u %u%n", &x, &y, &z, &used) == 3 && whole())) continue; + if (std::sscanf(line.c_str(), "ud %u%n", &declared_uds, &used) == 1 && whole()) continue; + if (std::sscanf(line.c_str(), "udsrc %u rootconst %d %d%n", &i, &a, &b, &used) == 3 && whole() && i == tr.uds.size()) + tr.uds.push_back({a, b}); + else if (std::sscanf(line.c_str(), "srv %u buf table %d %d%n", &i, &a, &b, &used) == 3 && whole() && i == tr.srvs.size()) + tr.srvs.push_back({a, b}); + else if (std::sscanf(line.c_str(), "srv %u buf heap rootconst %d %d%n", &i, &a, &b, &used) == 3 && whole() && + i == tr.srvs.size()) + tr.srvs.push_back({a, b, false, true}); + else if (std::sscanf(line.c_str(), "uav %u table %d %d%n", &i, &a, &b, &used) == 3 && whole() && i == tr.uavs.size()) + tr.uavs.push_back({a, b}); + else if (std::sscanf(line.c_str(), "uav %u tex2d float table %d %d channels 4%n", &i, &a, &b, &used) == 3 && whole() && + i == tr.uavs.size()) + tr.uavs.push_back({a, b, true}); + else if (std::sscanf(line.c_str(), "srv %u tex2d table %d %d%n", &i, &a, &b, &used) == 3 && whole() && i == tr.srvs.size()) + tr.srvs.push_back({a, b, true}); + else if (std::sscanf(line.c_str(), "smp %u %x %x %x %x%n", &i, &x, &y, &z, &w, &used) == 5 && whole() && + i == tr.samplers.statics.size()) + tr.samplers.read_manifest_line(line.c_str()); + else return line.rfind("srv", 0) == 0 ? "a resource that is not a raw table buffer or a 2D texture" + : line.rfind("uav", 0) == 0 ? "an output that is not a raw table buffer or a 2D float texture" + : line.rfind("udsrc", 0) == 0 ? "an entry value that is not a root constant" + : line.rfind("smp", 0) == 0 ? "a sampler that is not a plain static one" : "an unknown manifest line"; + } + if (tr.uds.size() != declared_uds || tr.uds.size() > 32 || tr.srvs.size() > 32 || tr.uavs.size() > 8) + return "entry value, input or output count"; + x2w_startup::ComPtr code; + if (!cache_path(path, L"", tr.key, L".cs.cso") || FAILED(D3DReadFileToBlob(path, &code))) return "no compiled program"; + // Parameter 0 keeps one constant for a program without entry values: a constants parameter cannot be empty. + if (FAILED(x2w_startup::create_translated_root(device_of(the_device), static_cast(tr.uds.empty() ? 1 : tr.uds.size()), + static_cast(tr.srvs.size()), tr.samplers, &tr.root, static_cast(tr.uavs.size())))) + return "root signature creation failed"; + D3D12_COMPUTE_PIPELINE_STATE_DESC desc{}; + desc.pRootSignature = tr.root.Get(); + desc.CS = {code->GetBufferPointer(), code->GetBufferSize()}; + if (FAILED(device_of(the_device)->CreateComputePipelineState(&desc, IID_PPV_ARGS(&tr.pipeline)))) + return "pipeline creation failed"; + tr.state = 1; + log("x2w-draw compute pipeline %016llx translated: %zu entry values, %zu inputs, %zu outputs", tr.key, tr.uds.size(), + tr.srvs.size(), tr.uavs.size()); + return nullptr; +} + +// True when the bound pipeline is a slot 67 placeholder with a request key: the call is then settled here +// (dispatched, or refused and logged). False leaves it to the desktop-pipeline decision of list_dispatch. +bool dispatch_translated(Wrapper* self, UINT x, UINT y, UINT z) +{ + auto* list = recording(self); + Pass& pass = pass_of(self); + const u64 key = list && pass.pipeline ? pass.pipeline->own().compute_request_key : 0; + if (!key) return false; + const char* reason = nullptr; + LONG* counter = &compute_dispatches_refused; + struct View { + ID3D12Resource* resource; + u64 offset, bytes; + bool transition, texture, described; + unsigned char desc[40]; // a texture view's description, as the title gave it with a desktop format + Wrapper* wrapper; + } views[40]{}; + static_assert(sizeof(D3D12_SHADER_RESOURCE_VIEW_DESC) == 40 && sizeof(D3D12_UNORDERED_ACCESS_VIEW_DESC) == 40); + const auto type = list->GetType(); + AcquireSRWLockExclusive(&draw_lock); + ComputeTranslation* const tr = &compute_translations()[key]; + tr->key = key; + ++tr->dispatches; + std::uint32_t words[8] = {}; + if (type != D3D12_COMMAND_LIST_TYPE_DIRECT && type != D3D12_COMMAND_LIST_TYPE_COMPUTE) reason = "the list type has no Dispatch"; + else if (x > x2w_startup::max_dispatch_groups || y > x2w_startup::max_dispatch_groups || z > x2w_startup::max_dispatch_groups) + reason = "a group count is over the limit"; + else if (pass.compute_root_wrapper != pass.pipeline->own().compute_request_root) + reason = "the compute root set is not the one the pipeline was created with"; + else if (!ensure_draw_heap(self->own().list_device)) reason = "no descriptor heap on this device"; + else { + if (!tr->state || (tr->retry_manifest_at && GetTickCount64() >= tr->retry_manifest_at)) { + tr->unmodelled = load_compute_translation(*tr); + if (tr->unmodelled) log("x2w-draw compute pipeline %016llx not translated: %s", key, tr->unmodelled); + } + if (tr->state != 1) { + // A manifest the runtime cannot bind is the dispatch side's work; an absent one is the translator's. + reason = tr->unmodelled ? tr->unmodelled : "no translation"; + counter = tr->unmodelled ? &compute_dispatches_unmodelled : &compute_dispatches_untranslated; + } + } + // A word no slot 37 or 39 call wrote since the compute root was set has no value to pass (it is not 0). + for (std::size_t i = 0; !reason && i < tr->uds.size(); ++i) + if (!pass.compute_constants.is_bound(tr->uds[i].a, tr->uds[i].b, 1)) reason = "an entry value was not set since the compute root"; + const std::size_t inputs = reason ? 0 : tr->srvs.size(), count = reason ? 0 : inputs + tr->uavs.size(); + for (std::size_t i = 0; i < count && !reason; ++i) { + const bool output = i >= inputs; + const ComputeTranslation::Slot slot = output ? tr->uavs[i - inputs] : tr->srvs[i]; + // A heap record sits at the 32-bit byte offset the program computes, the root constant word shifted left by + // 5, in the title memory of the list's view heap: a literal byte offset, as a table's is. + const u64 entry = slot.a < 0 || slot.b < 0 ? 0 + : slot.heap ? pass.title_view_heap.record(std::uint32_t{pass.compute_constants.word(slot.a, slot.b)} << 5, 16) + : pass.compute_tables.table(slot.a).record(static_cast(slot.b), slot.texture ? 32 : 16); + std::memset(words, 0, sizeof(words)); + const std::size_t entry_bytes = slot.texture ? 32 : 16; + if (!entry || !x2w_local::readable(reinterpret_cast(entry), entry_bytes)) { + reason = slot.heap ? "a heap record is outside the list's view heap" : "a table descriptor is not bound"; + break; + } + std::memcpy(words, reinterpret_cast(entry), entry_bytes); + if (slot.texture) { + // The title's descriptor memory carries the id of the view it created there. Nothing else is bound: + // a null view would read zeros or drop the program's stores without a trace. + ViewRecord record{}; + bool known = false, created = false; + if (words[0] == view_token_magic) { + AcquireSRWLockShared(¬e_lock); + known = words[1] < view_records().size(); + if (known) { + record = view_records()[words[1]]; + created = view_materialized()[words[1]] != 0; + } + ReleaseSRWLockShared(¬e_lock); + } + Wrapper* const wrapper = known ? as_wrapper(reinterpret_cast(record.resource)) : nullptr; + ID3D12Resource* const texture = !wrapper || wrapper->own().kind != resource_kind ? nullptr + : output ? static_cast(wrapper->own().real) : sampled_address_texture(wrapper); + const D3D12_RESOURCE_DESC resource = texture ? texture->GetDesc() : D3D12_RESOURCE_DESC{}; + if (!output) { + D3D12_SHADER_RESOURCE_VIEW_DESC desc{}; + const bool described = record.desc_bytes >= sizeof(desc); + if (described) std::memcpy(&desc, record.desc, sizeof(desc)); + if (desc.Format) desc.Format = desktop_format(desc.Format); + words[3] = static_cast(desc.Format ? desc.Format : resource.Format) | static_cast(desc.ViewDimension) << 16; + if (!known || record.slot != 18) reason = "an input texture entry is not the token of a shader resource view"; + else if (!texture || (resource.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE)) + reason = "an input texture has no desktop texture to sample"; + else if (described ? desc.ViewDimension != D3D12_SRV_DIMENSION_TEXTURE2D + : resource.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || resource.DepthOrArraySize != 1) + reason = "an input texture view is not 2D"; + // shortcut: a packed format needs the stand-in rules of the draw path; add them with its first user. + else if (x2w_startup::packed_target_format(desc.Format)) reason = "an input texture view has a packed format"; + views[i] = {texture, 0, 0, true, true, described}; + std::memcpy(views[i].desc, &desc, sizeof(desc)); + views[i].wrapper = wrapper; + continue; + } + D3D12_UNORDERED_ACCESS_VIEW_DESC desc{}; + const bool described = record.desc_bytes >= sizeof(desc); + if (described) std::memcpy(&desc, record.desc, sizeof(desc)); + if (desc.Format) desc.Format = desktop_format(desc.Format); + const DXGI_FORMAT format = desc.Format ? desc.Format : resource.Format; + words[3] = static_cast(format) | static_cast(desc.ViewDimension) << 16; + if (!known || record.slot != 19) reason = "an output texture entry is not the token of an unordered access view"; + else if (!created || !texture || !(resource.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) + reason = "an output texture view was not created on the desktop"; + else if (described ? desc.ViewDimension != D3D12_UAV_DIMENSION_TEXTURE2D || desc.Texture2D.PlaneSlice + : resource.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || resource.DepthOrArraySize != 1) + reason = "an output texture view is not 2D"; + else if (x2w_startup::packed_target_format(format)) reason = "an output texture view has a packed format"; + else if (!float_output_format(format)) reason = "an output texture format is not a float or normalized one"; + // One state per resource here: a texture read and written by the same call is refused. Two outputs + // of one texture (two mips) share the unordered access state. + for (std::size_t input = 0; input < inputs && !reason; ++input) + if (views[input].wrapper == wrapper) reason = "an output texture is also an input of the dispatch"; + views[i] = {texture, 0, 0, true, true, described}; + std::memcpy(views[i].desc, &desc, sizeof(desc)); + views[i].wrapper = wrapper; + continue; + } + if (!output) { + const IndirectBufferView view = indirect_table_buffer(self, words); + if (!view.resource || view.offset % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT) reason = "an input is not a complete GPU-backed buffer range"; + views[i] = {view.resource, view.offset, view.bytes, !view.upload}; + continue; + } + // An output is written by the GPU: only a placed buffer that aliases the title's memory shows the result + // to the title. shortcut: view tokens and copied placements are refused, add them with their first user. + const u64 address = words[0] | (u64{words[1] & 0xffff} << 32); + const UINT stride = (words[1] >> 16) & 0x3fff; + const u64 bytes = u64{stride ? stride : 1} * words[2]; + const auto placed = words[0] == view_token_magic || !bytes || bytes % 4 || bytes > (16u << 20) + ? PlacedVertexView{} : placed_buffer_range(self->own().list_device, address, bytes); + const ResourceInfo* info = placed.alias ? resource_info(placed.owner) : nullptr; + const u64 offset = placed.alias ? address - reinterpret_cast(placed.owner->own().title_memory) : 0; + if (!info || info->initial_state != D3D12_RESOURCE_STATE_COMMON || offset % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT || + !(placed.alias->GetDesc().Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) + reason = "an output is not an aliased placed buffer range with unordered access"; + for (std::size_t input = 0; input < inputs && !reason; ++input) + if (views[input].resource == placed.alias) reason = "an output buffer is also an input"; + views[i] = {placed.alias, offset, bytes, true}; + } + // A texture the title filled in memory is brought up to date first. An upload recorded before a later one + // fails only syncs content, as a draw sampling that texture would. + for (std::size_t i = 0; i < inputs && !reason; ++i) + if (views[i].texture && !upload_texture(self, views[i].wrapper, views[i].resource)) { + reason = "an input texture could not be uploaded"; + std::memset(words, 0, sizeof(words)); + } + if (reason) { + if (!tr->first_refusal) { + tr->first_refusal = reason; + std::memcpy(tr->refusal_words, words, sizeof(tr->refusal_words)); + } + ReleaseSRWLockExclusive(&draw_lock); + InterlockedIncrement(counter); + // Dispatches that arrive before the offline translation must not use up the lines for bind refusals. + static LONG untranslated, refusals; + if (first_calls(counter == &compute_dispatches_refused ? refusals : untranslated, 16)) log("x2w-draw compute %016llx Dispatch(%u, %u, %u) refused: %s", key, x, y, z, reason); + return true; + } + const UINT n = static_cast(count); + UINT first = static_cast(InterlockedExchangeAdd(&draw_heap_cursor, static_cast(n))) % draw_heap_size; + if (first + n > draw_heap_size) { + first = 0; + InterlockedExchange(&draw_heap_cursor, static_cast(n)); + } + D3D12_CPU_DESCRIPTOR_HANDLE dest{draw_heap->GetCPUDescriptorHandleForHeapStart().ptr + std::size_t{first} * draw_heap_increment}; + for (std::size_t i = 0; i < count; ++i, dest.ptr += draw_heap_increment) { + const View& view = views[i]; + if (i < inputs && view.texture) { + // A compute list accepts no pixel-shader or depth state in a transition. + require_state(self, view.resource, type == D3D12_COMMAND_LIST_TYPE_COMPUTE ? D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE + : sampled_state(self, view.resource) | D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + device_of(the_device)->CreateShaderResourceView(view.resource, + view.described ? reinterpret_cast(view.desc) : nullptr, dest); + continue; + } + if (i < inputs) { + if (view.transition) require_state(self, view.resource, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + buffer_view(dest, view.resource, view.offset, static_cast(view.bytes)); + continue; + } + require_state(self, view.resource, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + if (view.texture) { + device_of(the_device)->CreateUnorderedAccessView(view.resource, nullptr, + view.described ? reinterpret_cast(view.desc) : nullptr, dest); + continue; + } + D3D12_UNORDERED_ACCESS_VIEW_DESC desc{}; + desc.Format = DXGI_FORMAT_R32_TYPELESS; + desc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + desc.Buffer.FirstElement = view.offset / 4; + desc.Buffer.NumElements = static_cast(view.bytes / 4); + desc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + device_of(the_device)->CreateUnorderedAccessView(view.resource, nullptr, &desc, dest); + } + std::uint32_t values[32] = {}; + for (std::size_t i = 0; i < tr->uds.size(); ++i) values[i] = pass.compute_constants.word(tr->uds[i].a, tr->uds[i].b); + if (!pass.heap_set) { + x2w_startup::bind_translated_heaps(list, draw_heap, nullptr); + pass.heap_set = true; + pass.bound_sampler_heap = nullptr; + } + list->SetPipelineState(tr->pipeline.Get()); + list->SetComputeRootSignature(tr->root.Get()); + if (!tr->uds.empty()) list->SetComputeRoot32BitConstants(0, static_cast(tr->uds.size()), values, 0); + if (n) list->SetComputeRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE{draw_heap->GetGPUDescriptorHandleForHeapStart().ptr + u64{first} * draw_heap_increment}); + list->Dispatch(x, y, z); + for (std::size_t i = inputs; i < count; ++i) { // a later dispatch on this list reads what this one wrote + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + barrier.UAV.pResource = views[i].resource; + list->ResourceBarrier(1, &barrier); + } + // The translated root replaced the desktop compute root of the title and its arguments. + if (pass.desktop_compute_root) { + list->SetComputeRootSignature(pass.desktop_compute_root.Get()); + for (UINT parameter = 0; parameter < pass.desktop_compute_upload_srvs.size(); ++parameter) + if (const auto address = pass.desktop_compute_upload_srvs[parameter]) list->SetComputeRootShaderResourceView(parameter, address); + } + ++tr->translated; + ReleaseSRWLockExclusive(&draw_lock); + static LONG checks; // as translated draws do: the queue's execute drains the rest + if ((InterlockedIncrement(&checks) & 63) == 1) check_device("translated dispatch", 14); + InterlockedIncrement(&compute_dispatches_translated); + static LONG logged; + if (first_calls(logged, 8)) + log("x2w-draw compute %016llx Dispatch(%u, %u, %u) translated: entry [%x %x %x %x], %zu inputs, %zu outputs", key, x, y, z, + values[0], values[1], values[2], values[3], inputs, count - inputs); + return true; +} + +// With the periodic totals: refused dispatches by the first refusal reason of their key, then every key by +// dispatch count. The per-call log lines above share one small budget, so they cannot rank keys. +void log_compute_census() +{ + struct Reason { const char* text; u64 keys, dispatches; }; + std::vector reasons; + std::vector keys; + AcquireSRWLockShared(&draw_lock); + for (const auto& item : compute_translations()) { + const ComputeTranslation& tr = item.second; + ComputeTranslation copy; + copy.key = tr.key; + copy.dispatches = tr.dispatches; + copy.translated = tr.translated; + copy.first_refusal = tr.first_refusal; + std::memcpy(copy.refusal_words, tr.refusal_words, sizeof(copy.refusal_words)); + keys.push_back(copy); + if (!tr.first_refusal) continue; + auto found = std::find_if(reasons.begin(), reasons.end(), [&](const Reason& r) { return !std::strcmp(r.text, tr.first_refusal); }); + if (found == reasons.end()) found = reasons.insert(reasons.end(), Reason{tr.first_refusal, 0, 0}); + ++found->keys; + found->dispatches += tr.dispatches - tr.translated; + } + ReleaseSRWLockShared(&draw_lock); + if (keys.empty()) return; + std::sort(reasons.begin(), reasons.end(), [](const Reason& a, const Reason& b) { return a.dispatches > b.dispatches; }); + std::sort(keys.begin(), keys.end(), [](const ComputeTranslation& a, const ComputeTranslation& b) { return a.dispatches > b.dispatches; }); + log("x2w-render compute census: %zu keys dispatched", keys.size()); + for (const Reason& r : reasons) + log("x2w-render compute census reason \"%s\": %llu keys, %llu dispatches", r.text, r.keys, r.dispatches); + for (std::size_t i = 0; i < keys.size(); ++i) + log("x2w-render compute census key %016llx: %llu dispatches, %llu translated, first refusal: %s [%08x %08x %08x %08x]", + keys[i].key, keys[i].dispatches, keys[i].translated, keys[i].first_refusal ? keys[i].first_refusal : "none", + keys[i].refusal_words[0], keys[i].refusal_words[1], keys[i].refusal_words[2], keys[i].refusal_words[3]); +} + +// Fixtures: the census without waiting for the frame that logs it. +extern "C" __declspec(dllexport) void x2w_d3d12_compute_census() { log_compute_census(); } diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 209c82255..04830e6c1 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -314,10 +314,11 @@ LONG pointer_like_qwords(const std::vector& blob) SRWLOCK compute_request_lock = SRWLOCK_INIT; std::unordered_set& compute_keys_seen() { static std::unordered_set s; return s; } -void publish_compute_request(const void* desc) +// Returns the request key, or 0 when publishing is disabled or the description is refused. +u64 publish_compute_request(const void* desc) { wchar_t marker[MAX_PATH]; - if (!render_mode() || !cache_path(marker, L"req_", 0, L".c67")) return; // publishing disabled + if (!render_mode() || !cache_path(marker, L"req_", 0, L".c67")) return 0; // publishing disabled static LONG logged; const char* refusal = nullptr; u64 words[12]{}; @@ -356,7 +357,7 @@ void publish_compute_request(const void* desc) if (refusal) { InterlockedIncrement(&compute_requests_failed); if (first_calls(logged, 12)) log("x2w-draw compute request not written: %s", refusal); - return; + return 0; } const auto& [code, data, state_a, state_b] = copies; // Pointer words never reach .desc or the key; 9 and 10 are not followed (shortcut: two descriptions that @@ -392,6 +393,7 @@ void publish_compute_request(const void* desc) log("x2w-draw compute request %016llx %s (code %llu bytes, data %llu bytes, state blocks %llu + %llu bytes, " "pointer-like blob qwords %ld)", key, present ? "already present" : written ? "published" : "not written", words[6], words[8], words[2], words[4], pointers); + return key; } // Slot 57 fixed descriptors consumed by a decoded DispatchMesh signature. @@ -2387,10 +2389,12 @@ const char* draw_translated_indirect(Wrapper* self, ID3D12CommandSignature* sign } // List slot 32, SetDescriptorHeaps. Track the title's shader-visible sampler -// source while translated draws use their own physical descriptor heaps. +// source while translated draws use their own physical descriptor heaps, and the +// title memory of the view heap for a program that indexes the heap itself. void __stdcall list_set_descriptor_heaps(Wrapper* self, UINT count, void* const* heaps) { x2w_startup::SamplerSource source; + x2w_startup::ViewTable heap_records; x2w_startup::ViewHeapSelection view_heaps; if (count && count <= 4 && x2w_local::readable(heaps, std::size_t{count} * sizeof(*heaps))) { AcquireSRWLockShared(¬e_lock); @@ -2399,6 +2403,10 @@ void __stdcall list_set_descriptor_heaps(Wrapper* self, UINT count, void* const* if (heap.wrapper == reinterpret_cast(heaps[i]) && heap.type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) view_heaps.note(heap.wrapper, heap.desktop_gpu != 0, heap.logical_count, heap.count); + if (heap.wrapper == reinterpret_cast(heaps[i]) && + heap.type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) + heap_records = x2w_startup::resolve_view_table(heap.desktop_gpu, heap.title_cpu, heap.logical_count, + heap.increment, heap.desktop_gpu); if (heap.wrapper == reinterpret_cast(heaps[i]) && heap.type == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER && heap.desktop_gpu) source = {static_cast(heap.title_sampler_cpu), heap.count}; @@ -2413,6 +2421,7 @@ void __stdcall list_set_descriptor_heaps(Wrapper* self, UINT count, void* const* pass.compute_tables.set_view_heap(view_heaps.compute); pass.source_view_heap = view_heaps.graphics; pass.title_samplers = source; + pass.title_view_heap = heap_records; } // The table at a title GPU handle, looked up in the title's view heap (the one set by slot 32 when known). diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 92b6f2ff9..ff4dc8978 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -188,6 +188,8 @@ struct alignas(16) WrapperOwn { LONG compute_trace_dispatches; bool root_without_bindings; // RootSignature: decoded and has no parameters or static samplers ID3D12RootSignature* pipeline_root; // PipelineState: desktop root signature its compute stream declared + u64 compute_request_key; // PipelineState: key of the slot 67 request it published, or 0 + const void* compute_request_root; // PipelineState: root signature wrapper named by that slot 67 description bool root_srv_only; // RootSignature: decoded, no static samplers, every parameter a root SRV (those are forwarded) volatile LONG queue_wait_seen; // CommandQueue: publish later signals only after GPU completion. void* pass; // CommandList (render mode): recording state (Pass) @@ -2483,6 +2485,7 @@ struct Pass { x2w_startup::ViewTable view_tables[16]{}; x2w_startup::ComputeTables compute_tables; // slot 35, read by a Dispatch handler u64 source_view_heap = 0; + x2w_startup::ViewTable title_view_heap; // slot 32: the title memory of the list's view heap (heap records) u64 root_address[16] = {}; // title address of each root descriptor std::uint32_t constants[16][8] = {}; unsigned char constant_words_bound[16] = {}; @@ -2693,6 +2696,9 @@ void __stdcall list_compute_root(Wrapper* self, void* root) pass.compute_root = real ? static_cast(w->own().real) : nullptr; pass.compute_tables.set_signature(w ? root_info(w) : nullptr); // a different signature leaves no table bound pass.compute_params = real ? root_info(w) : nullptr; + pass.compute_srv_bound = 0; + // Root SRV parameters are forwarded by their own slot; anything else the root declares is not. + pass.compute_root_has_arguments = real && !w->own().root_without_bindings && !w->own().root_srv_only; if (compute_binding_trace_enabled() && (!pass.compute_trace || pass.compute_trace->root != w)) { pass.compute_trace = std::make_unique(); pass.compute_trace->root = w; @@ -3680,8 +3686,10 @@ void __stdcall list_root_cbv(Wrapper* self, UINT parameter, u64 address) pass.root_address[parameter] = (address && readable_window(address, 1)) ? address : 0; } // List slot 14, Dispatch. Forwarded only with a desktop compute pipeline and root bound and group counts within the limit. +bool dispatch_translated(Wrapper* self, UINT x, UINT y, UINT z); void __stdcall list_dispatch(Wrapper* self, UINT x, UINT y, UINT z) { + if (dispatch_translated(self, x, y, z)) return; // a slot 67 placeholder never reaches the desktop decision auto* list = recording(self); x2w_startup::ListDispatch request; request.list_open = list != nullptr; @@ -3756,6 +3764,7 @@ std::unordered_map& written_textures(); ID3D12Resource* sampled_address_texture(Wrapper* resource); bool console_layout_srv(const D3D12_RESOURCE_DESC& desc); #include "startup_stubs/d3d12_draw.inl" +#include "startup_stubs/d3d12_compute_dispatch.inl" #include "startup_stubs/mesh86_cache.inl" #include "startup_stubs/d3d12_compute_binding_trace.inl" #include "startup_stubs/list_copy_texture.inl" @@ -6093,9 +6102,15 @@ HRESULT __stdcall device_create_pipeline_placeholder(Wrapper*, const void* desc, hex_text(desc, 96, bytes, sizeof(bytes)); log("x2w-d3d12 Device::slot%d(pipeline?) desc=[%s] riid=%s -> placeholder", N, bytes, text); } - if constexpr (N == 67) publish_compute_request(desc); *out = wrap(nullptr, pipeline_kind); if (!*out) return E_OUTOFMEMORY; + if constexpr (N == 67) { + // A translated Dispatch finds its program by this key (d3d12_compute_dispatch.inl). + if (const u64 key = publish_compute_request(desc)) { + static_cast(*out)->own().compute_request_key = key; + static_cast(*out)->own().compute_request_root = as_wrapper(*static_cast(desc)); + } + } note_pipeline(static_cast(*out), N, nullptr, desc, 0x300); return S_OK; } @@ -6581,6 +6596,11 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa heap_root_refusals[static_cast(x2w_startup::RealRootDecision::both_heaps_missing)], heap_root_refusals[static_cast(x2w_startup::RealRootDecision::state_not_restorable)], indirect_first_lookups, compute_requests_published, compute_requests_present, compute_requests_failed, compute_blob_pointer_words); + if (render_mode() && frame % 300 == 0) { + log("x2w-render compute dispatches: translated %ld, refused %ld, no translation %ld, not modelled %ld", + compute_dispatches_translated, compute_dispatches_refused, compute_dispatches_untranslated, compute_dispatches_unmodelled); + log_compute_census(); + } if (render_mode() && frame % 300 == 0) { // Slot-61 calls since the start, by outcome, then by signature kind (zero kinds left out). static const char* const outcomes[] = {"forwarded", "refused graphics-pipeline", "compute-pipeline", diff --git a/src/startup_stubs/translated_sampler_bindings.h b/src/startup_stubs/translated_sampler_bindings.h index a4aca72dd..8d06fa71a 100644 --- a/src/startup_stubs/translated_sampler_bindings.h +++ b/src/startup_stubs/translated_sampler_bindings.h @@ -113,17 +113,20 @@ inline std::vector decode_statics(const TranslatedSam inline UINT sampler_root_parameter(UINT srvs) { return srvs ? 2u : 1u; } inline HRESULT create_translated_root(ID3D12Device* device, UINT constants, UINT srvs, - const TranslatedSamplers& samplers, ID3D12RootSignature** out) + const TranslatedSamplers& samplers, ID3D12RootSignature** out, UINT uavs = 0) { D3D12_ROOT_PARAMETER parameters[3]{}; parameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; parameters[0].Constants.Num32BitValues = constants; - const D3D12_DESCRIPTOR_RANGE srv_range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, srvs, 0, 0, 0}; + // A compute program's outputs (u0..) follow its resources in the same table. + const D3D12_DESCRIPTOR_RANGE view_ranges[2]{{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, srvs, 0, 0, 0}, + {D3D12_DESCRIPTOR_RANGE_TYPE_UAV, uavs, 0, 0, srvs}}; parameters[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; - parameters[1].DescriptorTable = {1, &srv_range}; + // A range of no descriptors does not serialize: a program without resources starts the table at its outputs. + parameters[1].DescriptorTable = {(srvs ? 1u : 0u) + (uavs ? 1u : 0u), srvs ? view_ranges : view_ranges + 1}; const D3D12_DESCRIPTOR_RANGE sampler_range{ D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, translated_sampler_count, 0, translated_sampler_space, 0}; - UINT count = sampler_root_parameter(srvs); + UINT count = sampler_root_parameter(srvs + uavs); if (samplers.heap) { parameters[count].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; parameters[count].DescriptorTable = {1, &sampler_range}; diff --git a/tests/startup_compute_dispatch_check.py b/tests/startup_compute_dispatch_check.py new file mode 100644 index 000000000..018d4a4b7 --- /dev/null +++ b/tests/startup_compute_dispatch_check.py @@ -0,0 +1,132 @@ +"""A translated compute program dispatched through the stand-in's command list (list slot 14). + +usage: startup_compute_dispatch_check.py + +The consumer creates case A of startup_gfx2hlsl_compute_check.py as a device slot 67 pipeline and records, on a +stand-in list, the descriptor heap, the pipeline, its root signature, two root constants (word 0 by slot 37, word 1 +by slot 39, with a slot 40 call of other words in between), one table of two +hardware buffer descriptors and Dispatch(3, 2, 2). Input and output are placed buffers that alias the consumer's +memory; the output words are read from that memory after the queue's fence. Four runs share one cache: + +1. before translation: the request is published, the Dispatch is refused with "no translation" and every output + word keeps the sentinel (the check fails when nothing translated is dispatched); +2. after gfx2hlsl.py --pending with DXC: all 320 words equal the case's expectation; +3. dispatch-none (no Dispatch recorded): every word keeps the sentinel; +4. dispatch-swapped (the two descriptors exchanged, so the output names the buffer without unordered access): + refused with one logged reason, every word keeps the sentinel and the input is unchanged; +5. dispatch-same-root (the same compute root set again after the constants): all 320 words still match; +6. five more refusals, each with its one logged reason and an untouched output: dispatch-missing-word (no slot 37 + call), dispatch-root-changed (another compute root and back after the constants), dispatch-reset (list closed + and reset after the constants), dispatch-wrong-root (recorded under a root the pipeline was not created with) + and dispatch-same-buffer (the output buffer is also the input). +Exit 77 when the adapter is not available. +""" +import os +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +import startup_gfx2hlsl_compute_check as C +from startup_compute_request_check import DATA, prepare +from startup_compute_translate_check import state_a +from startup_stream_check import gfx2hlsl as G + + +def dispatch(directory, consumer, env, mode): + out = directory / 'out.bin' + out.unlink(missing_ok=True) + args = [consumer, directory / 'vertex', directory / 'pixel', directory / 'root', 'slot67', + directory / 'program', directory / 'data', directory / 'state', mode] + result = subprocess.run(args, env=dict(env, X2W_TEST_DISPATCH_OUT=str(out)), capture_output=True, text=True) + if result.returncode == 77: + print(result.stdout, end='') + sys.exit(77) + assert result.returncode == 0, f'{mode}: consumer exit {result.returncode}\n{result.stderr[-3000:]}' + return list(struct.unpack('<%dI' % C.WORDS, out.read_bytes())), result + + +def lines(result, text): + return [line for line in result.stderr.splitlines() if text in line] + + +def main(consumer, dxc, adapter): + with tempfile.TemporaryDirectory() as temporary: + directory = Path(temporary) + cache, env = prepare(directory) + env.update(X2W_D3D12_LIST_NOOP='1', X2W_D3D12_DEBUG='1') # guest lists; debug-layer messages go to the log + if adapter == 'hardware': + env['X2W_TEST_DISPATCH_HARDWARE'] = '1' + (directory / 'compute_root').write_bytes(C.root_blob(table_range=True)) + env['X2W_TEST_COMPUTE_ROOT'] = str(directory / 'compute_root') + _, words, rsrc2, group, groups = C.CASES['A'] + assert groups == (3, 2, 2) and (C.KEY, C.STRIDE) == (0x01234567, 0x9e3779b9), 'the consumer hard-codes case A' + (directory / 'program').write_bytes(words) + (directory / 'data').write_bytes(DATA) + (directory / 'state').write_bytes(state_a(group, rsrc2)) + untouched, expected = [C.SENTINEL] * C.WORDS, C.expected('A') + assert expected != untouched + + got, result = dispatch(directory, consumer, env, 'dispatch') + print(result.stdout, end='') + assert got == untouched, 'a Dispatch without a translation wrote the output' + assert len(lines(result, 'Dispatch(3, 2, 2) refused: no translation')) == 1, result.stderr[-3000:] + published = lines(result, 'x2w-draw compute request') + assert published and ' published ' in published[0], result.stderr[-3000:] + key = int(published[0].split()[3], 16) + census = lines(result, 'x2w-render compute census') + assert census == ['x2w-render compute census: 1 keys dispatched', + 'x2w-render compute census reason "no translation": 1 keys, 1 dispatches', + f'x2w-render compute census key {key:016x}: 1 dispatches, 0 translated, first refusal: ' + 'no translation [00000000 00000000 00000000 00000000]'], census + + out = subprocess.run([sys.executable, '-B', G.__file__, '--pending', cache], check=True, capture_output=True, + text=True, env=dict(os.environ, X2W_DXC=dxc)).stdout + assert f'{key:016x}: ok' in out, out + + got, result = dispatch(directory, consumer, env, 'dispatch') + wrong = [i for i in range(C.WORDS) if got[i] != expected[i]] + assert not wrong, 'word=%d got=%08x expected=%08x (%d words differ)\n%s' % ( + wrong[0], got[wrong[0]], expected[wrong[0]], len(wrong), result.stderr[-3000:]) + assert len(lines(result, 'Dispatch(3, 2, 2) translated')) == 1 and not lines(result, 'refused'), result.stderr[-3000:] + census = lines(result, 'x2w-render compute census') + assert len(census) == 2 and census[1].endswith(': 1 dispatches, 1 translated, first refusal: none ' + '[00000000 00000000 00000000 00000000]'), census + layer = lines(result, 'x2w-d3d12 debug layer: ') + errors = [line for line in lines(result, 'x2w-d3d12-debug ') if ' sev=0 ' in line or ' sev=1 ' in line] + assert not errors, errors[0] + print('debug layer: ' + ('enabled, no error message' if layer and '0x00000000' in layer[0] else 'unavailable')) + + got, result = dispatch(directory, consumer, env, 'dispatch-none') + assert got == untouched and not lines(result, 'Dispatch('), 'the output changed without a Dispatch' + assert not lines(result, 'x2w-render compute census'), 'a census without a Dispatch' + + got, result = dispatch(directory, consumer, env, 'dispatch-swapped') + assert got == untouched, 'a refused Dispatch wrote the output' + refused = lines(result, 'refused: ') + census = lines(result, 'x2w-render compute census') + assert len(census) == 3 and census[1].endswith( + 'reason "an output is not an aliased placed buffer range with unordered access": 1 keys, 1 dispatches') \ + and '[00000000 00000000 ' not in census[2], census + assert len(refused) == 1 and 'an output is not an aliased placed buffer range with unordered access' in refused[0], \ + result.stderr[-3000:] + got, result = dispatch(directory, consumer, env, 'dispatch-same-root') + assert got == expected and not lines(result, 'refused'), 'setting the same compute root again lost the constants' + + unset = 'an entry value was not set since the compute root' + for mode, reason in (('dispatch-missing-word', unset), ('dispatch-root-changed', unset), ('dispatch-reset', unset), + ('dispatch-wrong-root', 'the compute root set is not the one the pipeline was created with'), + ('dispatch-same-buffer', 'an output buffer is also an input')): + got, result = dispatch(directory, consumer, env, mode) + assert got == untouched, f'{mode}: a refused Dispatch wrote the output' + refused = lines(result, 'refused: ') + assert len(refused) == 1 and refused[0].endswith('refused: ' + reason), f'{mode}: {refused}\n{result.stderr[-3000:]}' + print(f'startup_compute_dispatch: PASS on {adapter} (all {C.WORDS} words match after translation and with the ' + 'same root set again; untouched before translation, without a Dispatch and for 6 refusals)') + + +if __name__ == '__main__': + if len(sys.argv) != 4 or sys.argv[3] not in ('warp', 'hardware'): + sys.exit(__doc__) + main(*sys.argv[1:]) diff --git a/tests/startup_compute_dispatch_heap_check.py b/tests/startup_compute_dispatch_heap_check.py new file mode 100644 index 000000000..c5addfad7 --- /dev/null +++ b/tests/startup_compute_dispatch_heap_check.py @@ -0,0 +1,87 @@ +"""A translated compute program whose input is the resource heap record a root constant indexes (list slot 14). + +usage: startup_compute_dispatch_heap_check.py + +The consumer creates the program of startup_gfx2hlsl_heap_record_check.py as a device slot 67 pipeline, with a +root signature that indexes the resource heap directly, and records the descriptor heap, the pipeline, the root +signature, three root constants, one table and Dispatch(3, 2, 2). The output descriptor is at table byte 16 as in +startup_compute_dispatch_check.py. The input descriptor is only in heap record 2 (heap byte 64), which the third +root constant indexes; heap bytes 0 and 32 hold the output's descriptor, so a dispatch that ignores the index or +scales it by 16 is refused instead of passing. Three runs share one cache: + +1. before translation: the request is published and the Dispatch is refused with "no translation"; +2. after gfx2hlsl.py --pending with DXC: the manifest names the heap record and all 320 words equal the + expectation of case A of startup_gfx2hlsl_compute_check.py (the program computes the same words); +3. dispatch-heap-outside (the constant is 0x07ffffff, a record past the heap): refused with one + logged reason, every word keeps the sentinel and the input is unchanged. +Exit 77 when the adapter is not available. +""" +import os +from pathlib import Path +import subprocess +import sys +import tempfile + +import startup_gfx2hlsl_compute_check as C +import startup_gfx2hlsl_heap_record_check as H +from startup_compute_dispatch_check import dispatch, lines +from startup_compute_request_check import DATA, prepare +from startup_compute_translate_check import state_a +from startup_stream_check import gfx2hlsl as G + +OUTSIDE = "a heap record is outside the list's view heap" + + +def main(consumer, dxc, adapter): + with tempfile.TemporaryDirectory() as temporary: + directory = Path(temporary) + cache, env = prepare(directory) + env.update(X2W_D3D12_LIST_NOOP='1', X2W_D3D12_DEBUG='1') # guest lists; debug-layer messages go to the log + if adapter == 'hardware': + env['X2W_TEST_DISPATCH_HARDWARE'] = '1' + (directory / 'compute_root').write_bytes(H.root_blob(table_range=True)) + env['X2W_TEST_COMPUTE_ROOT'] = str(directory / 'compute_root') + assert H.GROUPS == (3, 2, 2) and H.INDEX_WORD == 2, 'the consumer hard-codes the dispatch and the index word' + (directory / 'program').write_bytes(H.WORDS) + (directory / 'data').write_bytes(DATA) + (directory / 'state').write_bytes(state_a(H.GROUP, H.RSRC2)) + untouched, expected = [C.SENTINEL] * C.WORDS, C.expected('A') + assert expected != untouched + + got, result = dispatch(directory, consumer, env, 'dispatch-heap') + print(result.stdout, end='') + assert got == untouched, 'a Dispatch without a translation wrote the output' + assert len(lines(result, 'Dispatch(3, 2, 2) refused: no translation')) == 1, result.stderr[-3000:] + published = lines(result, 'x2w-draw compute request') + assert published and ' published ' in published[0], result.stderr[-3000:] + key = int(published[0].split()[3], 16) + + out = subprocess.run([sys.executable, '-B', G.__file__, '--pending', cache], check=True, capture_output=True, + text=True, env=dict(os.environ, X2W_DXC=dxc)).stdout + assert f'{key:016x}: ok' in out, out + assert (cache / f'{key:016x}.txt').read_text() == H.MANIFEST + + got, result = dispatch(directory, consumer, env, 'dispatch-heap') + wrong = [i for i in range(C.WORDS) if got[i] != expected[i]] + assert not wrong, 'word=%d got=%08x expected=%08x (%d words differ)\n%s' % ( + wrong[0], got[wrong[0]], expected[wrong[0]], len(wrong), result.stderr[-3000:]) + assert len(lines(result, 'Dispatch(3, 2, 2) translated')) == 1 and not lines(result, 'refused'), result.stderr[-3000:] + layer = lines(result, 'x2w-d3d12 debug layer: ') + errors = [line for line in lines(result, 'x2w-d3d12-debug ') if ' sev=0 ' in line or ' sev=1 ' in line] + assert not errors, errors[0] + print('debug layer: ' + ('enabled, no error message' if layer and '0x00000000' in layer[0] else 'unavailable')) + + got, result = dispatch(directory, consumer, env, 'dispatch-heap-outside') + assert got == untouched, 'a refused Dispatch wrote the output' + refused = lines(result, 'refused: ') + census = lines(result, 'x2w-render compute census') + assert len(refused) == 1 and OUTSIDE in refused[0], result.stderr[-3000:] + assert len(census) == 3 and census[1].endswith(f'reason "{OUTSIDE}": 1 keys, 1 dispatches'), census + print(f'startup_compute_dispatch_heap: PASS on {adapter} (all {C.WORDS} words match through heap record 2; ' + 'untouched before translation and for a record outside the heap)') + + +if __name__ == '__main__': + if len(sys.argv) != 4 or sys.argv[3] not in ('warp', 'hardware'): + sys.exit(__doc__) + main(*sys.argv[1:]) diff --git a/tests/startup_compute_dispatch_texture_check.py b/tests/startup_compute_dispatch_texture_check.py new file mode 100644 index 000000000..4ec3eb508 --- /dev/null +++ b/tests/startup_compute_dispatch_texture_check.py @@ -0,0 +1,203 @@ +"""Translated compute programs with 2D texture views, dispatched through the stand-in's command list (slot 14). + +usage: startup_compute_dispatch_texture_check.py + +Texture output: the consumer creates the image store program of startup_compute_image_store_d16_check.py as a +device slot 67 pipeline, fills a 32x8 RGBA16_FLOAT texture with sentinel halves, creates an unordered access view of +it at table byte 64 (device slot 19), records Dispatch(2, 1, 1) and copies the texture to a readback buffer. Four +runs share one cache: + +1. before translation: refused with "no translation", every half keeps its sentinel; +2. after gfx2hlsl.py --pending with DXC: the 1024 halves equal mip 0 of the fixture's CPU reference (64 changed); +3. texture-store-none (no Dispatch recorded): every half keeps its sentinel; +4. texture-store-denied (a texture without unordered access, whose view the stand-in does not create): refused + with one logged reason, every half keeps its sentinel. +A fifth run binds the same program under a manifest edited to declare no entry values. + +Texture input: case A of startup_gfx2hlsl_compute_check.py with a level-zero sample of a 2D texture XORed into the +stored word (a static sampler, a texture view at table byte 64). The consumer adds a 1x1 RGBA8 texture whose red +is 1.0 and a shader resource view of it (device slot 18). After translation all 320 words equal the case's +expectation XOR the bits of 1.0f; dispatch-sampled-unbound (no view created) is refused with one logged reason and +every word keeps the sentinel. +Exit 77 when the adapter is not available. +""" +import os +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +import startup_compute_image_store_d16_check as S +import startup_gfx2hlsl_compute_check as C +from startup_compute_dispatch_check import lines +from startup_compute_request_check import DATA, prepare +from startup_compute_translate_check import state_a +from startup_stream_check import gfx2hlsl as G + + +def run(directory, consumer, env, mode, layout): + out = directory / 'out.bin' + out.unlink(missing_ok=True) + args = [consumer, directory / 'vertex', directory / 'pixel', directory / 'root', 'slot67', + directory / 'program', directory / 'data', directory / 'state', mode] + result = subprocess.run(args, env=dict(env, X2W_TEST_DISPATCH_OUT=str(out)), capture_output=True, text=True) + if result.returncode == 77: + print(result.stdout, end='') + sys.exit(77) + assert result.returncode == 0, f'{mode}: consumer exit {result.returncode}\n{result.stderr[-3000:]}' + return list(struct.unpack(layout, out.read_bytes())), result + + +def translate(cache, dxc, key): + out = subprocess.run([sys.executable, '-B', G.__file__, '--pending', cache], check=True, capture_output=True, + text=True, env=dict(os.environ, X2W_DXC=dxc)).stdout + assert f'{key:016x}: ok' in out, out + + +def clean(result): + assert not lines(result, 'refused'), result.stderr[-3000:] + errors = [line for line in lines(result, 'x2w-d3d12-debug ') if ' sev=0 ' in line or ' sev=1 ' in line] + assert not errors, errors[0] + layer = lines(result, 'x2w-d3d12 debug layer: ') + return 'enabled, no error message' if layer and '0x00000000' in layer[0] else 'unavailable' + + +def store(directory, consumer, dxc, env): + cache, base = prepare(directory) + env = dict(base, **env) + (directory / 'compute_root').write_bytes(C.root_blob(3, table_range=True)) + env['X2W_TEST_COMPUTE_ROOT'] = str(directory / 'compute_root') + assert S.fixture.GROUP == (4, 2, 1) and S.fixture.GROUPS == 2, 'the consumer hard-codes Dispatch(2, 1, 1)' + (directory / 'program').write_bytes(S.fixture.WORDS) + (directory / 'data').write_bytes(DATA) + (directory / 'state').write_bytes(state_a(S.fixture.GROUP, S.RSRC2)) + reference = S.fixture.reference() + halves = 32 * 8 * 4 # mip 0 comes first in both halves of the reference + untouched, expected = reference[:halves], reference[len(reference) // 2:][:halves] + assert sum(a != b for a, b in zip(untouched, expected)) == 64 + layout = '<%dH' % halves + + got, result = run(directory, consumer, env, 'texture-store', layout) + print(result.stdout, end='') + assert got == untouched, 'a Dispatch without a translation wrote the texture' + assert len(lines(result, 'Dispatch(2, 1, 1) refused: no translation')) == 1, result.stderr[-3000:] + key = int(lines(result, 'x2w-draw compute request')[0].split()[3], 16) + translate(cache, dxc, key) + + got, result = run(directory, consumer, env, 'texture-store', layout) + wrong = [i for i in range(halves) if got[i] != expected[i]] + assert not wrong, 'half=%d got=%04x expected=%04x (%d halves differ)\n%s' % ( + wrong[0], got[wrong[0]], expected[wrong[0]], len(wrong), result.stderr[-3000:]) + assert len(lines(result, 'Dispatch(2, 1, 1) translated')) == 1, result.stderr[-3000:] + layer = clean(result) + + got, result = run(directory, consumer, env, 'texture-store-none', layout) + assert got == untouched and not lines(result, 'Dispatch('), 'the texture changed without a Dispatch' + + got, result = run(directory, consumer, env, 'texture-store-denied', layout) + assert got == untouched, 'a refused Dispatch wrote the texture' + refused = lines(result, 'refused: ') + assert len(refused) == 1 and 'an output texture view was not created on the desktop' in refused[0], result.stderr[-3000:] + + # Refusals the runtime already had, each with its one logged reason and an untouched texture: an integer view + # format, another manifest version, another stage, and (with a manifest line added here for a view the consumer + # creates) the output texture named as an input too. + manifest = cache / f'{key:016x}.txt' + original = manifest.read_text() + for mode, old, new, reason in ( + ('texture-store-uint', '', '', 'an output texture format is not a float or normalized one'), + ('texture-store', 'x2w-manifest 2', 'x2w-manifest 3', 'manifest version'), + ('texture-store', 'stage cs', 'stage ps', 'not a compute manifest'), + ('texture-store-self', 'uav 0 tex2d', 'srv 0 tex2d table 1 0' + chr(10) + 'uav 0 tex2d', + 'an output texture is also an input of the dispatch')): + assert not old or original.count(old) == 1, original + manifest.write_bytes(original.replace(old, new).encode() if old else original.encode()) + got, result = run(directory, consumer, env, mode, layout) + refused = lines(result, 'refused: ') + assert got == untouched and len(refused) == 1 and refused[0].endswith('refused: ' + reason), ( + mode, reason, refused, result.stderr[-3000:]) + manifest.write_bytes(original.encode()) + + # The same compiled program under a manifest without entry values (the program reads none of its three): the + # runtime binds no constants. The manifest is edited here; the translator writes `ud 0` for a root without them. + manifest = cache / f'{key:016x}.txt' + kept = [line for line in manifest.read_text().splitlines() if not line.startswith('udsrc ')] + assert len(kept) == 5 and kept[3] == 'ud 3', kept + manifest.write_bytes(('\n'.join(kept).replace('ud 3', 'ud 0') + '\n').encode()) + got, result = run(directory, consumer, env, 'texture-store', layout) + assert got == expected and lines(result, 'translated: 0 entry values, 0 inputs, 1 outputs'), result.stderr[-3000:] + clean(result) + print(f'texture output: all {halves} halves match after translation (64 changed) and without entry values; ' + f'untouched before translation, without a Dispatch and for a refused view; debug layer: {layer}') + + +# v_xor_b32 v5, v5, v12: the assembled `v_xor_b32 v5, v5, v6` of case A with its second source register changed +# (not assembled by llvm-mc here; the translation below is checked to read it as written). +XOR = 'v_xor_b32 v5, v5, v12' +SAMPLED = ('s_mov_b64 s[20:21], 0', 's_mov_b64 s[22:23], 0', 's_load_dwordx8 s[24:31], s[10:11], 0x40', + 'image_sample_lz v[12:15], v[0:1], s[24:31], s[20:23] dmask:0xf dim:SQ_RSRC_IMG_2D', XOR) + + +def sample(directory, consumer, dxc, env): + cache, base = prepare(directory) + env = dict(base, **env) + (directory / 'compute_root').write_bytes(C.root_blob(table_range=True)) + env['X2W_TEST_COMPUTE_ROOT'] = str(directory / 'compute_root') + _, words, rsrc2, group, groups = C.CASES['A'] + assert groups == (3, 2, 2) and (C.KEY, C.STRIDE) == (0x01234567, 0x9e3779b9), 'the consumer hard-codes case A' + assert words[96:100].hex() == '050d0a3a', 'case A no longer holds v_xor_b32 v5, v5, v6 at byte 96' + C.SPLICE[XOR] = '05190a3a' + code = C.splice(*SAMPLED) + pipeline = C.translate('A', code=code) + assert 'v5 = v5 ^ v12;' in pipeline.hlsl_cs() and pipeline.manifest().endswith( + 'srv 0 buf table 1 0\nsrv 1 tex2d table 1 64\nuav 0 table 1 16\nsmp 0 0x0 0x0 0x0 0x0\n'), pipeline.manifest() + (directory / 'program').write_bytes(code) + (directory / 'data').write_bytes(DATA) + (directory / 'state').write_bytes(state_a(group, rsrc2)) + one = struct.unpack('] + +The root signature has three root constants (s4-s6), one descriptor table (s7) and the directly indexed +resource heap (root flag 0x400, pointer in s8). The program is case A of startup_gfx2hlsl_compute_check.py +with its input descriptor loaded as + + s_lshl_b32 s6, s6, 5 + s_load_dwordx4 s[16:19], s[8:9], s6 + +after s9 is set to zero. gfx2hlsl.py names that input `srv 0 buf heap rootconst 0 2` in the manifest: the +dispatch reads the 32-byte heap record that root constant word 2 indexes. The HLSL and the manifest are +compared whole. Every other form keeps a refusal: another shift, another index, an index register written +again, a branch target between the shift and the load, a high word that is not a constant zero, an offset +modifier, eight dwords, an index read from a buffer (named as such), a formatted load or a store through the +record, and the graphics stages. --llvm-mc reassembles every instruction used here and compares the words. +""" +import argparse +import struct + +from startup_gfx2hlsl_compute_check import G, TGID_X, TGID_Y, TGID_Z, assemble, refused, tidig + +GROUP, GROUPS = (2, 3, 4), (3, 2, 2) +RSRC2 = (9 << 1) | TGID_X | TGID_Y | TGID_Z | tidig(3) # s0-s3, three constants, the table, the heap pointer +INDEX_WORD = 2 # the root constant word the program shifts + +SHIFT, CLEAR, LOAD = 's_lshl_b32 s6, s6, 5', 's_mov_b32 s9, 0', 's_load_dwordx4 s[16:19], s[8:9], s6' +READ = 'buffer_load_dword v5, v4, s[16:19], 0 offen' +WRITE = 'buffer_store_dword v5, v4, s[20:23], 0 offen' +PROGRAM = ( + 's_mov_b32 s12, s7', 's_mov_b32 s13, 0', 's_load_dwordx4 s[20:23], s[12:13], 0x10', + 's_mov_b32 s14, s9', CLEAR, SHIFT, LOAD, 's_waitcnt lgkmcnt(0)', + 'v_mad_u32_u24 v3, v1, 2, v0', 'v_mad_u32_u24 v3, v2, 6, v3', 's_mul_i32 s24, s10, 3', 's_add_u32 s24, s24, s14', + 's_mul_i32 s25, s11, 6', 's_add_u32 s24, s24, s25', 's_mul_i32 s24, s24, 24', 'v_add_nc_u32 v3, s24, v3', + 'v_lshlrev_b32 v4, 2, v3', READ, 'v_mul_lo_u32 v6, v3, s5', 'v_add_nc_u32 v6, s4, v6', 's_waitcnt vmcnt(0)', + 'v_mul_lo_u32 v5, v5, 33', 'v_xor_b32 v5, v5, v6', WRITE, 's_endpgm') +# Every instruction of the program and of the controls, recorded from llvm-mc 15. +ENCODED = { + 's_mov_b32 s12, s7': '07038cbe', 's_mov_b32 s13, 0': '80038dbe', + 's_load_dwordx4 s[20:23], s[12:13], 0x10': '060508f4100000fa', 's_mov_b32 s14, s9': '09038ebe', + CLEAR: '800389be', SHIFT: '0685068f', LOAD: '040408f40000000c', 's_waitcnt lgkmcnt(0)': '7fc08cbf', + 'v_mad_u32_u24 v3, v1, 2, v0': '030043d501050104', 'v_mad_u32_u24 v3, v2, 6, v3': '030043d5020d0d04', + 's_mul_i32 s24, s10, 3': '0a831893', 's_add_u32 s24, s24, s14': '180e1880', 's_mul_i32 s25, s11, 6': '0b861993', + 's_add_u32 s24, s24, s25': '18191880', 's_mul_i32 s24, s24, 24': '18981893', 'v_add_nc_u32 v3, s24, v3': '1806064a', + 'v_lshlrev_b32 v4, 2, v3': '82060834', READ: '001030e004050480', 'v_mul_lo_u32 v6, v3, s5': '060069d5030b0000', + 'v_add_nc_u32 v6, s4, v6': '040c0c4a', 's_waitcnt vmcnt(0)': '703f8cbf', 'v_mul_lo_u32 v5, v5, 33': '050069d505430100', + 'v_xor_b32 v5, v5, v6': '050d0a3a', WRITE: '001070e004050580', 's_endpgm': '000081bf', + 's_lshl_b32 s6, s6, 4': '0684068f', 's_lshl_b32 s6, s6, 6': '0686068f', 's_lshl_b32 s6, s6, s5': '0605068f', + 's_lshl_b32 s6, s14, 5': '0e85068f', 's_mov_b32 s9, 1': '810389be', 's_mov_b32 s9, s5': '050389be', + 's_load_dwordx4 s[16:19], s[8:9], s6 offset:0x20': '040408f42000000c', + 's_load_dwordx8 s[16:23], s[8:9], s6': '04040cf40000000c', 's_load_dwordx4 s[16:19], s[8:9], s5': '040408f40000000a', + 's_load_dwordx4 s[16:19], s[8:9], m0': '040408f4000000f8', 's_add_u32 s6, s6, 0': '06800680', + 's_load_dwordx4 s[28:31], s[12:13], 0x20': '060708f4200000fa', + 's_buffer_load_dword s6, s[28:31], 0x0': '8e0120f4000000fa', 's_buffer_load_dword s26, s[28:31], 0x0': '8e0620f4000000fa', + 's_lshl_b32 s6, s26, 5': '1a85068f', 's_cmp_eq_u32 s4, 0': '048006bf', 's_cbranch_scc0 1': '010084bf', 's_nop 0': '000080bf', + 'buffer_load_format_xyzw v[5:8], v4, s[16:19], 0 offen': '00100ce004050480', + 'buffer_store_dword v5, v4, s[16:19], 0 offen': '001070e004050480', +} +TABLE_LOAD = 's_load_dwordx4 s[28:31], s[12:13], 0x20' +JUMP = ('s_cmp_eq_u32 s4, 0', 's_cbranch_scc0 1', 's_nop 0') # the instruction after the s_nop is a branch target + +MANIFEST = """\ +x2w-manifest 2 +stage cs +group 2 3 4 +ud 3 +udsrc 0 rootconst 0 0 +udsrc 1 rootconst 0 1 +udsrc 2 rootconst 0 2 +srv 0 buf heap rootconst 0 2 +uav 0 table 1 16 +""" +BINDINGS = """\ +cbuffer entry : register(b0) { uint ud0; uint ud1; uint ud2; }; +ByteAddressBuffer r0 : register(t0); +RWByteAddressBuffer u0 : register(u0); +""" +MAIN = """\ +[numthreads(2, 3, 4)] +void main(uint3 gid : SV_GroupID, uint3 tid : SV_GroupThreadID) { + uint s6 = 0, s9 = 0, s10 = 0, s11 = 0, s13 = 0, s14 = 0, s24 = 0, s25 = 0; + uint v0 = 0, v1 = 0, v2 = 0, v3 = 0, v4 = 0, v5 = 0, v6 = 0; + uint vcc = 0, exec = 1, m0 = 0, a = 0, w = 0; bool scc = false; float4 t = 0; + s9 = gid.x; + s10 = gid.y; + s11 = gid.z; + v0 = tid.x; + v1 = tid.y; + v2 = tid.z; + s13 = 0x00000000u; + s14 = s9; + s9 = 0x00000000u; + s6 = ud2 << (0x00000005u & 31); + scc = s6 != 0; + v3 = (v1 & 0xffffffu) * (0x00000002u & 0xffffffu) + v0; + v3 = (v2 & 0xffffffu) * (0x00000006u & 0xffffffu) + v3; + s24 = s10 * 0x00000003u; + s24 = s24 + s14; + s25 = s11 * 0x00000006u; + s24 = s24 + s25; + s24 = s24 * 0x00000018u; + v3 = s24 + v3; + v4 = v3 << (0x00000002u & 31); + a = v4 + 0; + v5 = r0.Load(a + 0); + v6 = v3 * ud1; + v6 = ud0 + v6; + v5 = v5 * 0x00000021u; + v5 = v5 ^ v6; + a = (v4 + 0) & 0xfffffffcu; + u0.Store(a, v5); +} +""" + + +def root_blob(table_range=False, flags=0x400): + """RTS0: param 0 = three root constants (b0), param 1 = a descriptor table, the resource heap directly indexed. + table_range gives the table one SRV range, as startup_gfx2hlsl_compute_check.root_blob does for a device.""" + params_at, constants_at = 24, 24 + 2 * 12 + table_at = constants_at + 12 + ranges = struct.pack('<6I', 0, 1, 0, 0, 0, 0xffffffff) if table_range else b'' + rts0 = (struct.pack('<6I', 2, 2, params_at, 0, table_at + 8 + len(ranges), flags) + + struct.pack('<3I', 1, 0, constants_at) + struct.pack('<3I', 0, 0, table_at) + + struct.pack('<3I', 0, 0, 3) + struct.pack('<2I', len(ranges) // 24, table_at + 8) + ranges) + part = b'RTS0' + struct.pack('((*static_cast(device))[127])( + device, &heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, nullptr, 0, nullptr, &__uuidof(ID3D12Resource), &resource); + return SUCCEEDED(hr) ? resource : nullptr; +} + +// Case A of startup_gfx2hlsl_compute_check.py through the stand-in's own list: two root constants (word 0 by slot +// 37, word 1 by slot 39; a slot 40 call with other words in between must not reach them), a +// table (slot 35) of two 16-byte hardware buffer descriptors written into the title heap's memory, and Dispatch +// (slot 14) of 3x2x2 groups with the slot 67 placeholder bound. Input and output are placed buffers 64 KiB apart +// in one allocation, so both alias this process's memory and the result is read from that memory after the queue's +// fence. dispatch-swapped exchanges the two descriptors (the output then names the buffer without unordered +// access); dispatch-none records everything but the Dispatch. The 320 output words go to X2W_TEST_DISPATCH_OUT. +// dispatch-sampled adds what the sampling variant of the case reads: a committed 1x1 RGBA8 texture filled by +// CopyTextureRegion (list slot 16) and a shader resource view of it (device slot 18) whose token the stand-in +// writes at table byte 64. dispatch-sampled-unbound creates no view, so that entry holds no token. +// dispatch-heap runs the program of startup_gfx2hlsl_heap_record_check.py: a third root constant, 2, indexes the +// 32-byte heap record that holds the input descriptor (heap byte 64). Heap bytes 0 and 32 hold the output's +// descriptor, so an index that is ignored or scaled by 16 names a buffer the dispatch refuses as an input. +// dispatch-heap-outside sets the constant to 0x07ffffff, whose record is past any heap. +// Controls on the recorded state: dispatch-missing-word leaves out the slot 37 call; dispatch-root-changed sets +// another compute root and the first one again after the constants, dispatch-same-root sets the same root again; +// dispatch-reset closes and resets the list after the constants; dispatch-wrong-root records under the other +// root; dispatch-same-buffer names the output buffer as the input too. +static int dispatch_slot67(void* device, const std::string& mode) +{ + constexpr UINT words = 320; + auto* memory = static_cast(VirtualAlloc(nullptr, 0x20000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + if (!memory) return 70; + UINT* const buffers[2] = {memory, memory + 0x10000 / sizeof(UINT)}; + for (UINT i = 0; i < words; ++i) { + buffers[0][i] = 0x8b02a7f1u + i * 0x413b1u; + buffers[1][i] = 0xc5c5c5c5u; + } + const auto word = [](const void* value) { return reinterpret_cast(value); }; + void* placed[2]{}; + UINT descriptors[2][4]{}; + for (int i = 0; i < 2; ++i) { + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, words * sizeof(UINT), 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR, i ? D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS : D3D12_RESOURCE_FLAG_NONE}; + if (FAILED(static_cast(invoke(device, 133, word(buffers[i]), word(&desc), D3D12_RESOURCE_STATE_COMMON, 0, + word(&__uuidof(ID3D12Resource)), word(&placed[i]))))) return 71; + const UINT64 address = reinterpret_cast(buffers[mode == "dispatch-same-buffer" ? 1 : i]); + const UINT view[4] = {static_cast(address), static_cast(address >> 32) | 4u << 16, words, 0}; + std::memcpy(descriptors[mode == "dispatch-swapped" ? 1 - i : i], view, sizeof(view)); + } + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 backing, bytes; + } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 4, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, 0, 0}; + void *heap = nullptr, *queue = nullptr, *allocator = nullptr, *list = nullptr, *fence = nullptr; + // dispatch-sampled-compute records the same calls on a compute list and queue. + const D3D12_COMMAND_LIST_TYPE list_type = mode == "dispatch-sampled-compute" ? D3D12_COMMAND_LIST_TYPE_COMPUTE : D3D12_COMMAND_LIST_TYPE_DIRECT; + const D3D12_COMMAND_QUEUE_DESC queue_desc{list_type}; + const UINT list_desc[]{static_cast(list_type), 2, 1, 0}; + if (FAILED(static_cast(invoke(device, 14, word(&heap_desc), word(&__uuidof(ID3D12DescriptorHeap)), word(&heap)))) || + FAILED(static_cast(invoke(device, 8, word(&queue_desc), word(&__uuidof(ID3D12CommandQueue)), word(&queue)))) || + FAILED(static_cast(invoke(device, 9, list_type, word(&__uuidof(ID3D12CommandAllocator)), word(&allocator)))) || + FAILED(static_cast(invoke(device, 73, word(list_desc), word(allocator), 0, word(&__uuidof(ID3D12GraphicsCommandList)), word(&list)))) || + FAILED(static_cast(invoke(device, 36, 0, 0, word(&__uuidof(ID3D12Fence)), word(&fence))))) return 72; + const StreamWord cpu = invoke(heap, 9), gpu = invoke(heap, 10); + if (!cpu || !gpu) return 73; + std::memcpy(reinterpret_cast(cpu), descriptors, sizeof(descriptors)); + const bool heap_record = mode.rfind("dispatch-heap", 0) == 0; + if (heap_record) + for (const UINT at : {0u, 32u, 64u}) + std::memcpy(reinterpret_cast(cpu + at), descriptors[at != 64], sizeof(descriptors[0])); + const UINT constants[3] = {0x01234567, 0x9e3779b9, mode == "dispatch-heap-outside" ? 0x07ffffffu : 2u}; + const UINT graphics[2] = {0xdeadbeef, 0xfeedface}; + const auto bind = [&] { + invoke(list, 32, 1, word(&heap)); + invoke(list, 25, word(slot67_pipeline)); + invoke(list, 33, word(mode == "dispatch-wrong-root" ? slot67_other_root : slot67_root)); + }; + if (FAILED(static_cast(invoke(list, 139, word(allocator))))) return 74; + bind(); + if (mode.rfind("dispatch-sampled", 0) == 0) { + const D3D12_RESOURCE_DESC texture_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, 1, 1, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, {1, 0}}; + const D3D12_RESOURCE_DESC upload_desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, 256, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR}; + void* const texture = make_committed(device, D3D12_HEAP_TYPE_DEFAULT, texture_desc, D3D12_RESOURCE_STATE_COMMON); + void* const upload = make_committed(device, D3D12_HEAP_TYPE_UPLOAD, upload_desc, D3D12_RESOURCE_STATE_GENERIC_READ); + void* texel = nullptr; + if (!texture || !upload || FAILED(static_cast(invoke(upload, 8, 0, 0, word(&texel)))) || !texel) return 80; + const unsigned char rgba[4] = {255, 64, 128, 32}; // the program reads red: 1.0f + std::memcpy(texel, rgba, sizeof(rgba)); + invoke(upload, 9, 0, 0); + D3D12_TEXTURE_COPY_LOCATION image{static_cast(texture), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + D3D12_TEXTURE_COPY_LOCATION source{static_cast(upload), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + source.PlacedFootprint = {0, {DXGI_FORMAT_R8G8B8A8_UNORM, 1, 1, 1, 256}}; + invoke(list, 16, word(&image), 0, 0, 0, word(&source), 0); + D3D12_SHADER_RESOURCE_VIEW_DESC view{DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_SRV_DIMENSION_TEXTURE2D, D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + view.Texture2D.MipLevels = 1; + if (mode != "dispatch-sampled-unbound") invoke(device, 18, word(texture), word(&view), cpu + 64); + } + if (mode != "dispatch-missing-word") invoke(list, 37, 0, constants[0], 0); + invoke(list, 40, 0, 2, word(graphics), 0); + invoke(list, 39, 0, 1, word(&constants[1]), 1); + if (mode == "dispatch-root-changed") invoke(list, 33, word(slot67_other_root)); + if (mode == "dispatch-root-changed" || mode == "dispatch-same-root") invoke(list, 33, word(slot67_root)); + if (mode == "dispatch-reset") { + if (FAILED(static_cast(invoke(list, 9))) || FAILED(static_cast(invoke(list, 139, word(allocator))))) return 74; + bind(); + } + if (heap_record) invoke(list, 39, 0, 1, word(&constants[2]), 2); + invoke(list, 35, 1, gpu); + if (mode != "dispatch-none") invoke(list, 14, 3, 2, 2); + if (FAILED(static_cast(invoke(list, 9)))) return 75; + invoke(queue, 10, 1, word(&list)); + if (FAILED(static_cast(invoke(queue, 14, word(fence), 1)))) return 76; + for (const ULONGLONG deadline = GetTickCount64() + 10000; invoke(fence, 8) < 1;) { + if (GetTickCount64() >= deadline) return 78; + Sleep(1); + } + for (UINT i = 0; i < words; ++i) + if (buffers[0][i] != 0x8b02a7f1u + i * 0x413b1u) return 79; // the input must stay as written + x2w_d3d12_compute_census(); + char path[MAX_PATH]; + const DWORD n = GetEnvironmentVariableA("X2W_TEST_DISPATCH_OUT", path, MAX_PATH); + if (!n || n >= MAX_PATH) return 2; + std::ofstream(path, std::ios::binary).write(reinterpret_cast(buffers[1]), words * sizeof(UINT)); + return 0; +} + +// The image store program of startup_compute_image_store_d16_check.py through the stand-in's own list: a committed +// 32x8 RGBA16_FLOAT texture (device slot 127) filled with sentinel halves by CopyTextureRegion (list slot 16), an +// unordered access view of it (device slot 19) whose token the stand-in writes into the title heap at table byte 64, +// three root constants, Dispatch of 2x1x1 groups, and the texture copied to a readback buffer whose 1024 halves go +// to X2W_TEST_DISPATCH_OUT. texture-store-none records no Dispatch; texture-store-denied creates the texture +// without unordered access, so the stand-in records its view as not created. texture-store-uint makes the texture +// and its view RGBA16_UINT; texture-store-self also creates a shader resource view of the texture at table byte 0. +static int texture_slot67(void* device, const std::string& mode) +{ + constexpr UINT width = 32, height = 8, pitch = width * 8, bytes = pitch * height; + const auto word = [](const void* value) { return reinterpret_cast(value); }; + const auto make = [&](D3D12_HEAP_TYPE type, const D3D12_RESOURCE_DESC& desc, D3D12_RESOURCE_STATES state) { + return make_committed(device, type, desc, state); + }; + const DXGI_FORMAT format = mode == "texture-store-uint" ? DXGI_FORMAT_R16G16B16A16_UINT : DXGI_FORMAT_R16G16B16A16_FLOAT; + const D3D12_RESOURCE_DESC texture_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, width, height, 1, 1, format, + {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, + mode == "texture-store-denied" ? D3D12_RESOURCE_FLAG_NONE : D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS}; + const D3D12_RESOURCE_DESC buffer_desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, bytes, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR}; + void* const texture = make(D3D12_HEAP_TYPE_DEFAULT, texture_desc, D3D12_RESOURCE_STATE_COMMON); + void* const upload = make(D3D12_HEAP_TYPE_UPLOAD, buffer_desc, D3D12_RESOURCE_STATE_GENERIC_READ); + void* const readback = make(D3D12_HEAP_TYPE_READBACK, buffer_desc, D3D12_RESOURCE_STATE_COPY_DEST); + void* memory = nullptr; + if (!texture || !upload || !readback || FAILED(static_cast(invoke(upload, 8, 0, 0, word(&memory)))) || !memory) return 71; + for (UINT i = 0; i < bytes / 2; ++i) static_cast(memory)[i] = static_cast(0x5000 + i); + invoke(upload, 9, 0, 0); + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 backing, bytes; + } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 4, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, 0, 0}; + void *heap = nullptr, *queue = nullptr, *allocator = nullptr, *list = nullptr, *fence = nullptr; + const D3D12_COMMAND_QUEUE_DESC queue_desc{}; + const UINT list_desc[]{D3D12_COMMAND_LIST_TYPE_DIRECT, 2, 1, 0}; + if (FAILED(static_cast(invoke(device, 14, word(&heap_desc), word(&__uuidof(ID3D12DescriptorHeap)), word(&heap)))) || + FAILED(static_cast(invoke(device, 8, word(&queue_desc), word(&__uuidof(ID3D12CommandQueue)), word(&queue)))) || + FAILED(static_cast(invoke(device, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, word(&__uuidof(ID3D12CommandAllocator)), word(&allocator)))) || + FAILED(static_cast(invoke(device, 73, word(list_desc), word(allocator), 0, word(&__uuidof(ID3D12GraphicsCommandList)), word(&list)))) || + FAILED(static_cast(invoke(device, 36, 0, 0, word(&__uuidof(ID3D12Fence)), word(&fence))))) return 72; + const StreamWord cpu = invoke(heap, 9), gpu = invoke(heap, 10); + if (!cpu || !gpu) return 73; + const D3D12_UNORDERED_ACCESS_VIEW_DESC view{format, D3D12_UAV_DIMENSION_TEXTURE2D}; + invoke(device, 19, word(texture), 0, word(&view), cpu + 64); + D3D12_SHADER_RESOURCE_VIEW_DESC read{format, D3D12_SRV_DIMENSION_TEXTURE2D, D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + read.Texture2D.MipLevels = 1; + if (mode == "texture-store-self") invoke(device, 18, word(texture), word(&read), cpu); + D3D12_TEXTURE_COPY_LOCATION image{static_cast(texture), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + D3D12_TEXTURE_COPY_LOCATION source{static_cast(upload), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + source.PlacedFootprint = {0, {format, width, height, 1, pitch}}; + D3D12_TEXTURE_COPY_LOCATION result = source; + result.pResource = static_cast(readback); + const UINT constants[3] = {1, 2, 3}; + if (FAILED(static_cast(invoke(list, 139, word(allocator))))) return 74; + invoke(list, 32, 1, word(&heap)); + invoke(list, 16, word(&image), 0, 0, 0, word(&source), 0); + invoke(list, 25, word(slot67_pipeline)); + invoke(list, 33, word(slot67_root)); + invoke(list, 39, 0, 3, word(constants), 0); + invoke(list, 35, 1, gpu); + if (mode != "texture-store-none") invoke(list, 14, 2, 1, 1); + invoke(list, 16, word(&result), 0, 0, 0, word(&image), 0); + if (FAILED(static_cast(invoke(list, 9)))) return 75; + invoke(queue, 10, 1, word(&list)); + if (FAILED(static_cast(invoke(queue, 14, word(fence), 1)))) return 76; + for (const ULONGLONG deadline = GetTickCount64() + 10000; invoke(fence, 8) < 1;) { + if (GetTickCount64() >= deadline) return 78; + Sleep(1); + } + x2w_d3d12_compute_census(); + char path[MAX_PATH]; + const DWORD n = GetEnvironmentVariableA("X2W_TEST_DISPATCH_OUT", path, MAX_PATH); + memory = nullptr; + if (!n || n >= MAX_PATH || FAILED(static_cast(invoke(readback, 8, 0, 0, word(&memory)))) || !memory) return 2; + std::ofstream(path, std::ios::binary).write(static_cast(memory), bytes); + invoke(readback, 9, 0, 0); + return 0; +} + static bool create_slot67(void* device, const char* code_path, const char* data_path, const char* state_path, const char* mode) { std::ifstream code_file(code_path, std::ios::binary), data_file(data_path, std::ios::binary), state_file(state_path, std::ios::binary); @@ -170,6 +386,7 @@ static bool create_slot67(void* device, const char* code_path, const char* data_ std::vector state{std::istreambuf_iterator(state_file), {}}; if (code.empty() || data.empty() || state.empty() || !stream_root_signature()) return false; void* root = stream_root_signature(); + slot67_other_root = root; char root_path[MAX_PATH]; const DWORD n = GetEnvironmentVariableA("X2W_TEST_COMPUTE_ROOT", root_path, MAX_PATH); if (n && n < MAX_PATH) { @@ -218,8 +435,11 @@ static bool create_slot67(void* device, const char* code_path, const char* data_ using Create = HRESULT (WINAPI*)(void*, const void*, REFIID, void**); auto create = [&](const void* d) { void* pipeline = nullptr; - return SUCCEEDED(reinterpret_cast((*static_cast(device))[67])(device, d, __uuidof(ID3D12PipelineState), &pipeline)) && + const bool created = SUCCEEDED(reinterpret_cast((*static_cast(device))[67])(device, d, __uuidof(ID3D12PipelineState), &pipeline)) && pipeline; + slot67_pipeline = pipeline; + slot67_root = root; + return created; }; if (m == "order") { if (!create(desc)) return false; @@ -258,7 +478,8 @@ int main(int argc, char** argv) ComPtr adapter; void* device = nullptr; void* pso = nullptr; - const bool hardware = draw && std::strcmp(argv[4], "hardware") == 0; + const bool hardware = (draw && std::strcmp(argv[4], "hardware") == 0) || + GetEnvironmentVariableW(L"X2W_TEST_DISPATCH_HARDWARE", nullptr, 0) != 0; const bool textured = bc7.blocks != nullptr || GetEnvironmentVariableW(L"X2W_TEST_D16_SRV", nullptr, 0) != 0 || GetEnvironmentVariableW(L"X2W_TEST_FORMATTED_BUFFER", nullptr, 0) != 0 || GetEnvironmentVariableW(L"X2W_TEST_FORMATTED_VIEW", nullptr, 0) != 0 || @@ -266,6 +487,10 @@ int main(int argc, char** argv) if (const int rc = prepare_stream_pipeline(argv[1], argv[2], argv[3], hardware, textured, adapter, device, pso)) return rc; // slot67 [case]: WARP device and root only, then slot-67 creations. + if (argc == 9 && std::strcmp(argv[4], "slot67") == 0 && std::strncmp(argv[8], "dispatch", 8) == 0) + return create_slot67(device, argv[5], argv[6], argv[7], argv[8]) ? dispatch_slot67(device, argv[8]) : 10; + if (argc == 9 && std::strcmp(argv[4], "slot67") == 0 && std::strncmp(argv[8], "texture", 7) == 0) + return create_slot67(device, argv[5], argv[6], argv[7], argv[8]) ? texture_slot67(device, argv[8]) : 10; if ((argc == 8 || argc == 9) && std::strcmp(argv[4], "slot67") == 0) return create_slot67(device, argv[5], argv[6], argv[7], argc == 9 ? argv[8] : "valid") ? 0 : 10; if (GetEnvironmentVariableW(L"X2W_TEST_TRUNCATED_ONLY", nullptr, 0)) return 0; diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 52a35b79d..15b3fa124 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -2716,6 +2716,8 @@ def translate(self): } self.descriptor_block_first = 0 self.uniform_expr = {} # proven VGPR -> uniform HLSL expression over scalars that defined it + self.heap_index = {} # SGPR -> what its word is for a resource-heap s_load (see heap_record) + self.heap_index_was = {} # the marks the current instruction's destinations held before it self.since_join = None # SGPRs proven uniform since the last branch target (None: none reached) self.defined_uniform_s = set(init_entry_uniform) self.bad_sgprs = set() @@ -2744,6 +2746,7 @@ def translate(self): # branch-free program is past it too (dead code). self.past_entry = bool(self.blocks) or 0 in targets if off in targets: + self.heap_index.clear() # another path into the join may hold a different word pre_uniform = { r for r in (self.defined_uniform_s if self.since_join is None else self.since_join) if r not in self.varying_s and r not in self.masks @@ -3049,6 +3052,11 @@ def one(self, name, asm): else: loaded = False self.last_v = None + if hasattr(self, 'heap_index'): # unit probes build a Stage without the tracking state + # Any write ends a register's mark; the lowering below sets the new one, if any. + wrote = scalar_destinations(name, asm) + wrote = set(self.heap_index) if 'any' in wrote else wrote & set(self.heap_index) + self.heap_index_was = {r: self.heap_index.pop(r) for r in wrote} term = self.lower(base, asm, ops, mods) uniform_written = self._uniform_written if self.tracks_uniformity() and getattr(self, 'since_join', None) is not None and wrote_s: @@ -3944,6 +3952,15 @@ def known(tok): self.scc_effect = 'a lane-mask complement' if self.tracks_uniformity(): self.scc_uniform = False + if (base == 's_lshl_b32' and hasattr(self, 'heap_index') and re.fullmatch(r'0x[0-9a-f]+|[0-9]+', srcs[1]) + and int(srcs[1], 0) == 5): + # index << 5 is the byte offset of a 32-byte resource-heap record. The index is named only when it is a + # root constant word (the dispatch knows it) or a word an s_buffer_load wrote (refused by name). + r = reg_range(srcs[0]) + if syms[0] and syms[0][0] == 'ud' and self.pipe.uds[syms[0][1]][0] == 'rootconst': + self.heap_index[d] = self.pipe.uds[syms[0][1]] + elif r and r[0] == 's' and {**self.heap_index, **self.heap_index_was}.get(r[1]) == ('bufword',): + self.heap_index[d] = ('buffer',) if is_mask: self.masks.add(d) if pair and base != 's_mov_b64': @@ -4305,8 +4322,31 @@ def op_s_load_dwordx4(self, ops, mods, count=4): self.sym[dst[1] + i] = ('const', 0, 'unassigned') self.pipe.notes.add('dynamic sampler index replaced by a default sampler') return + if p[1] == ('resheap',) and getattr(self, 'kind', None) == 'cs': + return self.heap_record(dst, base, token, imm, count) raise Unsupported('s_load with a register offset through %s' % (p[1],)) + def heap_record(self, dst, base, token, imm, count): + """s_load_dwordx4 D, , R in a compute program, where R is a root constant word + shifted left by 5 with no later write of R and no branch target in between: D is the buffer descriptor in + the 32-byte heap record that the root constant indexes. The manifest names the root constant; the dispatch + reads the record. Only this exact form is modelled.""" + what = 's_load of a resource heap record' + r = reg_range(token) + index = getattr(self, 'heap_index', {}).get(r[1]) if r and r[0] == 's' and r[1] == r[2] else None + if index == ('buffer',): + raise Unsupported('%s whose index is read from a buffer' % what) + if not index or index[0] != 'rootconst': + raise Unsupported('%s whose offset is not a root constant shifted left by 5 since the last branch target' % what) + if count != 4: + raise Unsupported('%s of %d dwords' % (what, count)) + if imm is not None: + raise Unsupported('%s with offset:%#x' % (what, imm)) + if self.sym.get(base[2]) != ('const', 0): + raise Unsupported('%s through a pointer whose high word is not a constant zero' % what) + for i in range(count): + self.sym[dst[1] + i] = ('desc', ('resheap',) + index[1:], 0, i) + def op_s_bfm_b32(self, ops, mods): """Fold constant bitfield masks: titles build inline sampler words with them.""" if len(ops) != 3: @@ -4467,6 +4507,8 @@ def op_s_buffer_load_dword(self, ops, mods, count=1): self.set_s(dst[1] + i, '%s.Load(%s + %d)' % (buf, offset, extra + 4 * i), uniform=uniform) if is_lit: self.sym[dst[1] + i] = ('fixed_buffer_word',) + if hasattr(self, 'heap_index'): + self.heap_index[dst[1] + i] = ('bufword',) def op_s_buffer_load_dwordx2(self, ops, mods): self.op_s_buffer_load_dword(ops, mods, 2) @@ -8061,10 +8103,14 @@ def manifest(self): where = 'table %d %d' % (source[1], off or 0) elif source[0] == 'root': where = 'root %d' % source[1] + elif source[0] == 'resheap' and len(source) == 3 and r['kind'] == 'buf': + where = 'heap rootconst %d %d' % source[1:] # the 32-byte heap record that root constant word indexes else: raise Unsupported('resource through %s' % (source,)) lines.append('srv %d %s %s' % (r['index'], r['kind'], where)) for (source, off), r in self.uavs.items(): + if source[0] != 'table': + raise Unsupported('store through %s' % (source,)) where = 'table %d %d' % (source[1], off) if r['kind'] == 'raw': lines.append('uav %d %s' % (r['index'], where)) From 303701d8f4867c0f0fee7927d2d1701bd91c8baa Mon Sep 17 00:00:00 2001 From: pigalot Date: Thu, 26 Nov 2026 02:16:45 +0000 Subject: [PATCH 066/240] shader: lower the SDWA form of v_cndmask_b32 in gfx2hlsl (#2391) * shader: lower the SDWA form of v_cndmask_b32 in gfx2hlsl The VOP2 select in SDWA form was refused as "SDWA form of v_cndmask_b32". sdwa() now lowers it as a two-source integer operation: each source takes its src0_sel/src1_sel field (sext() sign-extends), the select reads VCC, its fourth operand, the way the plain v_cndmask_b32 does, and dst_sel/dst_unused place the result. clamp, float modifiers and UNUSED_SEXT stay refused. Test: startup_gfx2hlsl_sdwa_check.py pins the emitted text. startup_gfx2hlsl_sdwa_cndmask_check.py draws a constructed gfx1013 pixel stage with four selects over 16 x 16 pixels on WARP and hardware (FXC ps_5_1 and DXC ps_6_0): all 1,024 words match a bit model, and six mutated selects fail against it and match their own. Its binary mode requires LLVM 15 to assemble the fixture to the same words. With the previous translator the fixture is refused. * tests: keep an SDWA select draw failure across a later capability skip Review follow-up. run_pixel_words exited 77 on a renderer skip even after an earlier check had failed, so ctest reported a skip instead of the failure. It now exits 1 when a check has failed, as #2380 did for the sibling draw fixtures. Test: with a check failed and the renderer returning 77, the old code exits 77 and the new code exits 1; without a failure both exit 77. --------- Co-authored-by: lewisalex86 Co-authored-by: tedin7 --- .github/workflows/windows.yml | 2 + AGENTS.md | 1 + CMakeLists.txt | 8 + docs/experiments.md | 22 ++ docs/startup-runtime.md | 4 +- tests/startup_gfx2hlsl_sdwa_check.py | 12 + tests/startup_gfx2hlsl_sdwa_cndmask_check.py | 291 +++++++++++++++++++ tools/startup/gfx2hlsl.py | 7 +- 8 files changed, 345 insertions(+), 2 deletions(-) create mode 100644 tests/startup_gfx2hlsl_sdwa_cndmask_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 3ff1ffbdc..49dc551a1 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -86,6 +86,7 @@ jobs: (["tests/mesh_shadow_check.py", *COMMON_LLVM], {}), (["tests/startup_sampler_heap_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_scalar_m0_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_gfx2hlsl_sdwa_cndmask_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_waitcnt_depctr_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_mesh57_skeleton_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_mesh57_loop_refusal_check.py", "binary", "llvm-mc-15"], {}), @@ -316,6 +317,7 @@ jobs: tests/startup_gfx2hlsl_cmp16_check.py \ tests/startup_gfx2hlsl_draw_skip_check.py \ tests/startup_gfx2hlsl_sdwa_cvt_check.py \ + tests/startup_gfx2hlsl_sdwa_cndmask_check.py \ tests/startup_gfx2hlsl_sop2_complement_check.py \ tests/startup_gfx2hlsl_pack_absdiff_check.py \ tests/startup_gfx2hlsl_sopk_accum_check.py \ diff --git a/AGENTS.md b/AGENTS.md index 543bdb057..c7bc06e20 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -205,6 +205,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_sop2_complement_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_pack_absdiff_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_sdwa_cvt_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_sdwa_cndmask_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_sopk_accum_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_int_med3_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_cselect_mask_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index d52759dd9..276e73c3c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3430,6 +3430,9 @@ if(EXISTS "${INTAKE_PYTHON}") # SDWA forms of the float-result conversions (#1727). add_test(NAME startup_gfx2hlsl_sdwa_cvt COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_sdwa_cvt_check.py") + # The SDWA form of v_cndmask_b32: fixture and model controls; the draws are registered below. + add_test(NAME startup_gfx2hlsl_sdwa_cndmask COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_sdwa_cndmask_check.py") # VOPC SDWA compares (#1906): every integer compare, select and sext() evaluated against an integer # reference; floating-point SDWA forms and unsupported modifiers are refused. The draws are registered below. add_test(NAME startup_gfx2hlsl_vopc_sdwa COMMAND "${INTAKE_PYTHON}" -B @@ -3904,6 +3907,11 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_sdwa_cvt_check.py" draw "${DXC_EXECUTABLE}" "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_gfx2hlsl_sdwa_cvt_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + # Four SDWA v_cndmask_b32 selects over 16 x 16 pixels against a bit model; six mutated selects must fail. + add_test(NAME startup_gfx2hlsl_sdwa_cndmask_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_sdwa_cndmask_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_sdwa_cndmask_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() # gfx2hlsl v_cmp/v_cmpx lg and nlg f32 over every pair of +-0, denormal, +-1, +-max, +-inf and NaN words decide # 16 x 16 pixels, checked pixel by pixel (#1920); the old != lowering must fail the same draws. diff --git a/docs/experiments.md b/docs/experiments.md index 92d6a0745..652dc6185 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -7878,6 +7878,28 @@ all 2,376 CPU evaluations and all 1,024 exported 32-bit words of the 16 x 16 pix reference, while five mutated HLSL controls fail against the reference and match their own models. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_sdwa_cvt(_warp|_hardware)?$' -V`. +The SDWA form of the VOP2 select, `v_cndmask_b32_sdwa vD, src0, src1, vcc_lo`, was refused as +`SDWA form of v_cndmask_b32`. `sdwa()` now lowers it as a two-source integer operation: each source takes its +`src0_sel`/`src1_sel` field, zero-extended or sign-extended under `sext()`, the select reads VCC the way the plain +`v_cndmask_b32` does and picks `src1` where the lane's bit is set, and `dst_sel`/`dst_unused` place the result by +the same rules as the other integer SDWA forms. The mask is always VCC, printed as the fourth operand; ` clamp`, +float modifiers and `UNUSED_SEXT` stay refused. The semantics are the integer SDWA rules already used for the +other forms with the select as the operation; they are not checked against the ISA document here and not measured +on a console. `startup_gfx2hlsl_sdwa_cndmask` draws a constructed gfx1013 pixel stage with four selects over +16 x 16 pixels: VCC is bit 31 of a per-pixel product clear (set in 160 of 256 pixels), and the selects cover byte +and word sources from two registers, a sign-extended `BYTE_2` widened into `WORD_0`, and `WORD_0`, `BYTE_1` and +`BYTE_2` destinations under `UNUSED_PRESERVE` over 1.0, which keeps every exported word a normal binary32 value +(asserted, since the target is `R32G32B32A32_FLOAT`). All 1,024 exported words match a bit model, and six +mutated selects (swapped operands, the mask ignored, the mask inverted, a dropped `sext()`, the neighbouring source +byte and the wrong destination byte) each fail against the model and match their own; that is 26 draws per adapter +with FXC (`ps_5_1`) and DXC (`ps_6_0`). Translating the fixture with the previous translator stops at the +refusal. `startup_gfx2hlsl_sdwa_cndmask_check.py binary ` requires LLVM 15 to assemble the fixture for +gfx1013 to the same words and to print each select as written. Verified on commit base `0736f67c`, Windows 11 +(build `26200.9974`), D3D12 debug layer enabled (`debug_errors=0 debug_warnings=0`), on Microsoft Basic Render +Driver (`1414:008c`, driver `10.0.26100.9818`) and NVIDIA GeForce RTX 5090 (`10de:2b85`, driver `32.0.16.1088`), +with LLVM 15.0.7. This shows that the translated select computes the stated words on desktop GPUs, not that the +console does. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_sdwa_cndmask(_warp|_hardware)?$' -V`. + **The binary32 class comparison.** `v_cmp_class_f32` and `v_cmpx_class_f32` had no lowering, so both census forms were refused - 2 of the remaining refused shaders in the first main-game loading-screen cache (#870, issue #1797). They now lower to a ten-class helper carried in the shader preamble (ported from diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index cb1659989..87d0417b3 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -2064,7 +2064,9 @@ These are measured on one executable; treat them as hypotheses for others. integer VOP1/VOP2 SDWA forms: a source selection is zero-extended, or sign-extended under `sext()`, and the low bits of the result are placed in the destination field, with `UNUSED_PAD` zeroing the others and `UNUSED_PRESERVE` keeping them. The selection helpers match `tools/pixel_aot.py`, which - already lowers the same forms. Float SDWA forms and a `dst_unused:UNUSED_SEXT` destination still + already lowers the same forms. The VOP2 select `v_cndmask_b32_sdwa` lowers the same way, with VCC as + its mask (`startup_gfx2hlsl_sdwa_cndmask`, drawn on WARP and hardware). Float SDWA forms and a + `dst_unused:UNUSED_SEXT` destination still stop translation rather than translating to something inexact. [#1141](https://github.com/R0Y00/Xbox2Windows/issues/1141) The VOPC SDWA compares (`v_cmp_*_sdwa`, `v_cmpx_*_sdwa`) of the existing 32-bit compare table lower too: i32 and u32 sources take their `src0_sel`/`src1_sel` field, sign-extended under `sext()`, and diff --git a/tests/startup_gfx2hlsl_sdwa_check.py b/tests/startup_gfx2hlsl_sdwa_check.py index 627115c7a..a1c9ae945 100644 --- a/tests/startup_gfx2hlsl_sdwa_check.py +++ b/tests/startup_gfx2hlsl_sdwa_check.py @@ -86,6 +86,18 @@ def translate(assembly): print(' emitted:', emitted) +# 5b. The VOP2 select takes its lane mask from VCC (the fourth operand) and its sources through their selects. +emitted = translate('v_cndmask_b32_sdwa v3, v1, v2, vcc_lo dst_sel:DWORD dst_unused:UNUSED_PAD ' + 'src0_sel:WORD_1 src1_sel:BYTE_0') +check('SDWA select picks src1 under VCC', + emitted.replace(' ', '') == 'v3=(vcc&1)?((v2>>0u)&0xffu):((v1>>16u)&0xffffu);') +print(' emitted:', emitted) +emitted = translate('v_cndmask_b32_sdwa v3, v1, v2, vcc_lo dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE ' + 'src0_sel:DWORD src1_sel:DWORD') +check('SDWA select grouped before a word destination', '((vcc & 1) ? v2 : v1)' in emitted and 'v3' in emitted) +print(' emitted:', emitted) + + # 6. Forms with no lowering are refused rather than mistranslated. def refused(assembly): try: diff --git a/tests/startup_gfx2hlsl_sdwa_cndmask_check.py b/tests/startup_gfx2hlsl_sdwa_cndmask_check.py new file mode 100644 index 000000000..82209cb5f --- /dev/null +++ b/tests/startup_gfx2hlsl_sdwa_cndmask_check.py @@ -0,0 +1,291 @@ +"""The SDWA form of v_cndmask_b32 in tools/startup/gfx2hlsl.py, drawn on a GPU. + + (no arguments) fixture and model controls, pure Python + binary assemble the fixture with LLVM 15 (-mcpu=gfx1013) and require its words + draw [fxc] + compile the 16 x 16 pixel fixture (FXC ps_5_1 when given, and DXC ps_6_0), + draw and compare all 1,024 exported words with the model, then require + each mutated shader to fail against the model and match its own + +The VOP2 select in SDWA form reads its lane mask from VCC, printed as the fourth operand. Each source takes its +src0_sel/src1_sel field, zero-extended or sign-extended under sext(), the select picks src1 where the lane's VCC +bit is set and src0 elsewhere, and dst_sel/dst_unused place the low bits of the result. These are the integer SDWA +rules the other forms already use (sdwa_source/sdwa_dest); the draw shows a desktop GPU computing the translated +select, not that the console does. + +The render target is R32G32B32A32_FLOAT, so every exported word must be a normal binary32 value: each select writes +a byte or word of a register that holds 1.0 (0x3f800000) under UNUSED_PRESERVE, which keeps the exponent normal. +The test asserts this, and that both VCC states occur. +""" +import re +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_image_3d_check import FULLSCREEN_VS, VS_WORDS, compile_hlsl, root_blob # noqa: E402 + +failures = [] + +WIDTH = HEIGHT = 16 +MULTIPLIER = 0x9B5D +ONE = 0x3F800000 +PACKED_INPUT = (0x8000, 0x8000) # SPI_PS_INPUT_ENA/ADDR: packed screen position x | (y << 16) in v0 + +SEL = {'BYTE_0': 0, 'BYTE_1': 1, 'BYTE_2': 2, 'BYTE_3': 3, 'WORD_0': 4, 'WORD_1': 5, 'DWORD': 6} +UNUSED = {'UNUSED_PAD': 0, 'UNUSED_SEXT': 1, 'UNUSED_PRESERVE': 2} +VOP2_CNDMASK_B32 = 1 + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH'}") + if not condition: + failures.append(label) + if detail: + print(detail) + + +def encode_cndmask_sdwa(vdst, src0, src1, *, src0_sel, src1_sel, dst_sel, dst_unused='UNUSED_PRESERVE', + src0_sext=0, src1_sext=0): + """VOP2 SDWA (GFX10 VOP_SDWA9Ae): w0 [30:25] opcode, [24:17] vdst, [16:9] VGPR src1, [8:0] = 249; + w1 [7:0] VGPR src0, [10:8] dst_sel, [12:11] dst_unused, [18:16] src0_sel, [19] src0_sext, + [26:24] src1_sel, [27] src1_sext.""" + w0 = (VOP2_CNDMASK_B32 << 25) | (vdst << 17) | (src1 << 9) | 249 + w1 = (src0 | (SEL[dst_sel] << 8) | (UNUSED[dst_unused] << 11) | (SEL[src0_sel] << 16) | (src0_sext << 19) + | (SEL[src1_sel] << 24) | (src1_sext << 27)) + return struct.pack('> shift) & ((1 << width) - 1) + if sext and width < 32 and part >> (width - 1): + part |= (0xFFFFFFFF << width) & 0xFFFFFFFF + return part + + +def place(old, result, sel, preserve): + shift, width = {'BYTE_0': (0, 8), 'BYTE_1': (8, 8), 'BYTE_2': (16, 8), 'BYTE_3': (24, 8), + 'WORD_0': (0, 16), 'WORD_1': (16, 16), 'DWORD': (0, 32)}[sel] + mask = ((1 << width) - 1) << shift + return ((old & ~mask) if preserve else 0) & 0xFFFFFFFF | ((result << shift) & mask) + + +def lanes(): + for y in range(HEIGHT): + for x in range(WIDTH): + v0 = x | (y << 16) + v1 = (v0 & 0xFFFFFF) * MULTIPLIER & 0xFFFFFFFF + yield v0, v1, 0x80000000 > v1 + + +def expected_pixel_words(mode='reference'): + words = [] + for v0, v1, vcc in lanes(): + regs = {0: v0, 1: v1} + for channel, (_, s0, x0, sel0, s1, x1, sel1, dst) in enumerate(SELECTS): + if mode == 'dropped sext' and channel == 1: + x0 = 0 + if mode == 'neighbouring byte' and channel == 3: + sel0 = 'BYTE_2' + if mode == 'wrong destination byte' and channel == 2: + dst = 'BYTE_0' + a, b = field(regs[s0], sel0, x0), field(regs[s1], sel1, x1) + if mode == 'swapped operands' and channel == 0: + a, b = b, a + lane = (not vcc) if (mode == 'mask inverted' and channel == 2) else vcc + picked = a if (mode == 'mask ignored' and channel == 3) else (b if lane else a) + words.append(place(ONE, picked, dst, True)) + return words + + +def normal_or_zero(word): + exponent = (word >> 23) & 0xFF + return word & 0x7FFFFFFF == 0 or 0 < exponent < 0xFF + + +def pixel_hlsl(mode='reference'): + text = G.Pipeline(VS_WORDS, PS_WORDS, root_blob(), ps_hw_inputs=PACKED_INPUT).hlsl_ps() + if mode == 'reference': + return text + # Each mutation edits one select statement of the translated shader. + lines = text.split('\n') + targets = {'swapped operands': 'v2', 'dropped sext': 'v3', 'mask inverted': 'v4', 'wrong destination byte': 'v4', + 'neighbouring byte': 'v5', 'mask ignored': 'v5'} + register = targets[mode] + found = [i for i, line in enumerate(lines) if re.match(r'\s*(uint\s+)?%s\s*=.*\?' % register, line)] + assert len(found) == 1, (mode, found, text) + i = found[0] + line = lines[i] + edited = { + 'swapped operands': lambda s: re.sub(r'\? (\(\(v1 >> 8u\) & 0xffu\)) : (\(\(v0 >> 0u\) & 0xffffu\))', + r'? \2 : \1', s), + 'mask inverted': lambda s: re.sub(r'\((\w+) & 1\) \? ', r'((\1 & 1) ^ 1) ? ', s), + 'dropped sext': lambda s: s.replace('asuint(asint(v1 << 8u) >> 24u)', '((v1 >> 16u) & 0xffu)'), + 'wrong destination byte': lambda s: s.replace('& 0xffff00ffu', '& 0xffffff00u').replace( + '& 0xffu) << 8u)', '& 0xffu) << 0u)'), + 'neighbouring byte': lambda s: s.replace(': ((v1 >> 8u) & 0xffu)', ': ((v1 >> 16u) & 0xffu)'), + 'mask ignored': lambda s: re.sub(r'\(\w+ & 1\) \? ', '(0u & 1) ? ', s), + }[mode](line) + assert edited != line, (mode, line) + lines[i] = edited + return '\n'.join(lines) + + +def controls(): + states = [vcc for _, _, vcc in lanes()] + check('both VCC states occur in at least 64 pixels each', min(states.count(True), states.count(False)) >= 64, + 'set in %d of %d pixels' % (states.count(True), len(states))) + reference = expected_pixel_words() + check('every reference word is a normal binary32 value', all(normal_or_zero(w) for w in reference)) + for mode in MODES: + model = expected_pixel_words(mode) + check(f'model ({mode}) differs from the reference', model != reference) + check(f'model ({mode}) words are normal binary32 values', all(normal_or_zero(w) for w in model)) + # Every channel of every mutated model differs in at least one pixel of its own channel only. + for mode in MODES: + model = expected_pixel_words(mode) + channels = {i % 4 for i, (a, b) in enumerate(zip(reference, model)) if a != b} + check(f'model ({mode}) changes one channel', len(channels) == 1, str(channels)) + try: + text = pixel_hlsl() + except G.Unsupported as error: + check('the fixture translates', False, str(error)) + return + check('the fixture translates', True) + print(text) + for mode in MODES: + try: + pixel_hlsl(mode) + check(f'mutation ({mode}) applies to the translated shader', True) + except AssertionError as error: + check(f'mutation ({mode}) applies to the translated shader', False, repr(error)) + + +def check_binary(llvm_mc): + source = '\n'.join(text for text, _ in PROGRAM) + '\n' + proc = subprocess.run([llvm_mc, '-arch=amdgcn', '-mcpu=gfx1013', '-show-encoding'], + input=source, capture_output=True, text=True, check=True) + built = bytearray() + for line in proc.stdout.splitlines(): + m = re.search(r'encoding: \[([^\]]*)\]', line) + if m: + built += bytes(int(b, 16) for b in m.group(1).split(',')) + check('the fixture words match llvm-mc', bytes(built) == PS_WORDS, + 'llvm-mc %s\nfixture %s' % (bytes(built).hex(), PS_WORDS.hex())) + printed = [line.split(';')[0].strip() for line in proc.stdout.splitlines() if 'v_cndmask_b32_sdwa' in line] + check('llvm-mc prints each select as written', printed == [assembly(s) for s in SELECTS], '\n'.join(printed)) + + +def run_pixel_words(renderer, adapter, vs, ps, expected_path): + run = subprocess.run( + [renderer, adapter, '--startup-pixel-words', str(vs), str(ps), str(WIDTH), str(HEIGHT), str(expected_path)], + capture_output=True, + text=True, + ) + if run.returncode == 77: + print(run.stdout + run.stderr, end='', flush=True) + sys.exit(1 if failures else 77) + if 'debug_layer=enabled' in run.stdout: + assert 'debug_errors=0 debug_warnings=0' in run.stdout, (run.stdout, run.stderr) + return run + + +def check_draw(dxc, renderer, adapter, fxc=None): + ref_words = expected_pixel_words('reference') + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + out_dir = HERE.parent / 'out' + out_dir.mkdir(exist_ok=True) + with tempfile.TemporaryDirectory(prefix='sdwa-cndmask-', dir=out_dir) as tmp: + directory = Path(tmp) + ref_bin = directory / 'reference.bin' + ref_bin.write_bytes(struct.pack('<%dI' % len(ref_words), *ref_words)) + for kind, compiler, vs_profile, ps_profile in compilers: + vs = compile_hlsl(compiler, kind, FULLSCREEN_VS, f'vs_{kind}', vs_profile, directory) + ps = compile_hlsl(compiler, kind, pixel_hlsl('reference'), f'ps_ref_{kind}', ps_profile, directory) + run = run_pixel_words(renderer, adapter, vs, ps, ref_bin) + check(f'{kind} ({adapter}): 16x16 pixel draw matches all 1,024 model words', + run.returncode == 0, run.stdout + run.stderr) + print(run.stdout, end='', flush=True) + for idx, mode in enumerate(MODES): + mut_ps = compile_hlsl(compiler, kind, pixel_hlsl(mode), f'ps_mut_{idx}_{kind}', ps_profile, directory) + fail_run = run_pixel_words(renderer, adapter, vs, mut_ps, ref_bin) + check(f'{kind} ({adapter}) mutation ({mode}) fails against the model', + fail_run.returncode != 0, fail_run.stdout + fail_run.stderr) + mut_words = expected_pixel_words(mode) + mut_bin = directory / f'mut_{idx}.bin' + mut_bin.write_bytes(struct.pack('<%dI' % len(mut_words), *mut_words)) + own_run = run_pixel_words(renderer, adapter, vs, mut_ps, mut_bin) + check(f'{kind} ({adapter}) mutation ({mode}) matches its own model', + own_run.returncode == 0, own_run.stdout + own_run.stderr) + + +def main(): + if len(sys.argv) == 1: + controls() + elif len(sys.argv) == 3 and sys.argv[1] == 'binary': + check_binary(sys.argv[2]) + elif len(sys.argv) in (5, 6) and sys.argv[1] == 'draw': + controls() + check_draw(*sys.argv[2:]) + else: + raise SystemExit(__doc__) + + if failures: + print('FAIL') + for text in failures: + print(' ' + text) + sys.exit(1) + print('PASS') + + +if __name__ == '__main__': + main() diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 15b3fa124..7737c0333 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -3571,7 +3571,7 @@ def half_alu(self, base, ops, mods): # VOP1/VOP2 with sub-dword addressing: select the source fields, run the same operation, then place # the low bits of the result in the destination field. The integer forms reuse VEC_U unchanged, - # v_mov_b32 is the same path with the selected source as its result, + # v_mov_b32 is the same path with the selected source as its result, v_cndmask_b32 selects with VCC, # VEC_U_TO_F conversions apply output modifiers before dst_sel, VEC_F forms stay refused, and # dst_unused UNUSED_SEXT has no lowering. def sdwa(self, base, ops, mods): @@ -3600,6 +3600,11 @@ def sdwa(self, base, ops, mods): self.reject_lane_mask_data(base, ops[1]) elif self.is_lane_mask(ops[1].removeprefix('sext(').removesuffix(')')): raise Unsupported('v_mov_b32 SDWA %s of lane mask %s' % (fields.get('src0_sel'), ops[1])) + elif base == 'v_cndmask_b32' and len(ops) == 4 and ops[3] == 'vcc_lo': + # The VOP2 select: its lane mask is always VCC, printed as the fourth operand, and read like the + # plain select's mask (op_v_cndmask_b32). + mask = self.u(ops[3]).replace('{', '{{').replace('}', '}}') + arity, text = 2, '(%s & 1) ? {1} : {0}' % mask else: raise Unsupported('SDWA form of %s' % base) sources = [] From 2ab3c9e8c5ef6af52f877c022cef5697bb2b86b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?As=C4=B1m=20Mirza=20=C3=87iftler?= <113895866+Asimmimx@users.noreply.github.com> Date: Thu, 26 Nov 2026 05:17:34 +0300 Subject: [PATCH 067/240] startup: draw the gfx2hlsl three-source integer vector operations (#1706) The VEC_U table lowers v_bfe_u32, v_mad_u32_u24, v_lshl_add_u32, v_add_lshl_u32, v_add3_u32, v_or3_b32, v_and_or_b32, v_lshl_or_b32, v_xad_u32 and v_bfi_b32, and no check ran any of them. tests/startup_gfx2hlsl_int3_alu_check.py draws them with the shared per-lane runner (tests/startup_gfx2hlsl_lane_alu.py, byte-identical to the copy in the two-source family PR): one operation per lane on flat inputs, exact result words, against references written from the RDNA 2 ISA (field extract with S1[4:0]/S2[4:0], 24-bit products, shift counts from bits 4:0, wrapping sums, bitfield insert), with widths and counts above 31, bits above bit 23 and wrapping sums. Each operation has one mutated lowering whose first draw must read its own mutated words. All 40 draws match on WARP and an RX 6600 through FXC ps_5_1 and DXC ps_6_0; the 20 mutated draws read their mutated words. Co-authored-by: x2w-worker --- .github/workflows/windows.yml | 2 + CMakeLists.txt | 10 +++ docs/experiments.md | 28 +++++++++ tests/startup_gfx2hlsl_int3_alu_check.py | 79 ++++++++++++++++++++++++ 4 files changed, 119 insertions(+) create mode 100644 tests/startup_gfx2hlsl_int3_alu_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 49dc551a1..af30cda6e 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -112,6 +112,7 @@ jobs: (["tests/startup_image_gather_c_lz_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_image_sample_c_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_image_3d_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_gfx2hlsl_int3_alu_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_image_load_mip_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_image_2d_array_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_image_sample_a16_check.py", "binary", "llvm-mc-15"], {}), @@ -267,6 +268,7 @@ jobs: tests/startup_gfx2hlsl_capture_check.py \ tests/startup_gfx2hlsl_watch_check.py \ tests/startup_translator_check.py \ + tests/startup_gfx2hlsl_int3_alu_check.py \ tests/startup_gfx2hlsl_smem_offset_check.py \ tests/startup_gfx2hlsl_sload_const_offset_check.py \ tests/startup_archive_requests_check.py \ diff --git a/CMakeLists.txt b/CMakeLists.txt index 276e73c3c..c1589b1a8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3802,6 +3802,16 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_gfx2hlsl_s_bit_scan_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl three-source integer vector operations (VEC_U): translation controls, then a draw of the translated + # pairs with reference words and one mutated lowering per operation. + add_test(NAME startup_gfx2hlsl_int3_alu_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_int3_alu_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_int3_alu_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_int3_alu_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_int3_alu_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl per-lane bit operations: CPU evaluation of the translated text against an independent # reference with mutation controls, then a desktop draw of the translated pairs (FXC 5_1 and DXC 6_0). add_test(NAME startup_gfx2hlsl_bit_alu_controls COMMAND "${INTAKE_PYTHON}" -B diff --git a/docs/experiments.md b/docs/experiments.md index 652dc6185..0f3eb2e1f 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14890,6 +14890,34 @@ ctest --preset dev --no-tests=error -R '^startup_image_gather_c_lz(_warp|_hardwa python3 -B tests/startup_image_gather_c_lz_check.py --llvm-mc llvm-mc-15 ``` +## Startup translator: three-source integer operations + +No check ran the three-source integer operations of the `VEC_U` table in `tools/startup/gfx2hlsl.py` before: `v_bfe_u32`, `v_mad_u32_u24`, `v_lshl_add_u32`, `v_add_lshl_u32`, `v_add3_u32`, `v_or3_b32`, `v_and_or_b32`, `v_lshl_or_b32`, `v_xad_u32` and `v_bfi_b32`. All ten are VOP3 only. `tests/startup_gfx2hlsl_int3_alu_check.py` draws them with the shared runner `tests/startup_gfx2hlsl_lane_alu.py`. Each draw applies one operation to each of four pixels' flat inputs and compares the four result words exactly. + +The references follow the AMD RDNA 2 ISA reference with plain integer arithmetic: +- `v_bfe_u32` takes an unsigned field of width S2[4:0] at offset S1[4:0]; +- `v_mad_u32_u24` multiplies the low 24 bits of S0 and S1; +- shift counts come from bits 4:0; +- sums wrap at 32 bits; +- `v_bfi_b32` is the insert `(S0 & S1) | (~S0 & S2)`. + +The inputs include shift counts and widths above 31, sources with bits above bit 23, and sums that wrap. + +Each operation also has a wrong lowering whose first draw must read its own mutated words: +- the bfe mask without `- 1`; +- a full-width first factor; +- add and OR exchanged in the shift-add pair; +- a 4-bit shift count; +- `a + b - c` for `v_add3_u32`; +- XOR for `v_or3_b32`; +- XOR for the OR in `v_and_or_b32`; +- OR for the XOR in `v_xad_u32`; +- an insert without the complement. + +An earlier mutation masked the bfe width to 4 bits. FXC `ps_5_1` compiled that mutated shader to one that read all zeros on WARP, so the mutation no longer tests only the lowering, and it was replaced. The correct lowering matched through both compilers. + +On WARP 10.0.26100.9818 and on an AMD Radeon RX 6600 (driver 32.0.21045.29003), all 40 draws matched through FXC `ps_5_1` and DXC `ps_6_0`, and all 20 mutated draws read their mutated words. Tests: `startup_gfx2hlsl_int3_alu_controls`, `startup_gfx2hlsl_int3_alu_warp` and `startup_gfx2hlsl_int3_alu_hardware`. + ## Startup translator: per-lane bit operations The startup scalar lowering also covers `s_lshl1_add_u32` through diff --git a/tests/startup_gfx2hlsl_int3_alu_check.py b/tests/startup_gfx2hlsl_int3_alu_check.py new file mode 100644 index 000000000..f5c3906dc --- /dev/null +++ b/tests/startup_gfx2hlsl_int3_alu_check.py @@ -0,0 +1,79 @@ +"""Three-source integer vector operations of tools/startup/gfx2hlsl.py (its VEC_U table). + + (no arguments) translation controls, pure Python + binary reassemble the pixel bodies and compare them with the recorded words + draw [fxc] + draw one pixel per four input sets and compare the four result words + +Covers v_bfe_u32, v_mad_u32_u24, v_lshl_add_u32, v_add_lshl_u32, v_add3_u32, v_or3_b32, v_and_or_b32, +v_lshl_or_b32, v_xad_u32 and v_bfi_b32, which no check ran before. All ten are VOP3 only. The fixture and runner +are startup_gfx2hlsl_lane_alu.py: one operation per lane on flat parameters the compilers cannot fold. The references +follow the AMD RDNA 2 ISA reference with plain integer arithmetic: an unsigned field of width S2[4:0] at offset +S1[4:0] for v_bfe_u32, the low 24 bits of S0 and S1 for v_mad_u32_u24, shift counts taken from bits 4:0, 32-bit +wrapping sums and the bitfield insert (S0 & S1) | (~S0 & S2). +""" +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from startup_gfx2hlsl_lane_alu import MASK, main, words # noqa: E402 + +M24 = 0xffffff +OPS = { + 'v_bfe_u32': (3, lambda a, b, c: (a >> (b & 31)) & ((1 << (c & 31)) - 1), False), + 'v_mad_u32_u24': (3, lambda a, b, c: (a & M24) * (b & M24) + c, False), + 'v_lshl_add_u32': (3, lambda a, b, c: (a << (b & 31)) + c, False), + 'v_add_lshl_u32': (3, lambda a, b, c: ((a + b) & MASK) << (c & 31), False), + 'v_add3_u32': (3, lambda a, b, c: a + b + c, False), + 'v_or3_b32': (3, lambda a, b, c: a | b | c, False), + 'v_and_or_b32': (3, lambda a, b, c: (a & b) | c, False), + 'v_lshl_or_b32': (3, lambda a, b, c: (a << (b & 31)) | c, False), + 'v_xad_u32': (3, lambda a, b, c: (a ^ b) + c, False), + 'v_bfi_b32': (3, lambda a, b, c: (a & b) | (~a & c), False), +} +# Input sets (src0, src1, src2), eight per operation: two draws of four pixels. Shift counts and widths above 31, +# sources with bits above bit 23, sums that wrap and masks with every bit pattern. +SETS = [(0x12345678, 4, 8), (0xdeadbeef, 31, 1), (0x80000000, 0, 0), (MASK, 33, 31), + (0xf0f0f0f0, 16, 0x0f0f0f0f), (0x01000003, 0x02000005, 7), (0xaaaaaaaa, 0x55555555, 0xffff0000), + (0x7fffffff, 1, 0x80000001)] +BFE = [(0x12345678, 4, 8), (0xdeadbeef, 31, 1), (0x80000000, 0, 0), (MASK, 33, 31), + (0xf0f0f0f0, 4, 8), (0x89abcdef, 28, 4), (0x0000ff00, 8, 40), (0x80000001, 0, 31)] +DRAW = {op: SETS for op in OPS} +DRAW['v_bfe_u32'] = BFE +# A wrong lowering of each operation: (pattern in the translated text, replacement, reference of the mutation). +MUTATIONS = { + 'v_bfe_u32': (r'\(\(1u << \((v\d+) & 31\)\) - 1\)', r'(1u << (\1 & 31))', + lambda a, b, c: (a >> (b & 31)) & (1 << (c & 31))), + 'v_mad_u32_u24': (r'= \((v\d+) & 0xffffffu\) \* ', r'= \1 * ', lambda a, b, c: a * (b & M24) + c), + 'v_lshl_add_u32': (r'(\(v\d+ << \(v\d+ & 31\)\)) \+ ', r'\1 | ', lambda a, b, c: (a << (b & 31)) | c), + 'v_add_lshl_u32': (r'<< \((v\d+) & 31\)', r'<< (\1 & 15)', lambda a, b, c: ((a + b) & MASK) << (c & 15)), + 'v_add3_u32': (r'(v\d+) \+ (v\d+) \+ (v\d+)', r'\1 + \2 - \3', lambda a, b, c: a + b - c), + 'v_or3_b32': (r'(v\d+) \| (v\d+) \| (v\d+)', r'\1 ^ \2 ^ \3', lambda a, b, c: a ^ b ^ c), + 'v_and_or_b32': (r'\) \| (v\d+)', r') ^ \1', lambda a, b, c: (a & b) ^ c), + 'v_lshl_or_b32': (r'(\(v\d+ << \(v\d+ & 31\)\)) \| ', r'\1 + ', lambda a, b, c: (a << (b & 31)) + c), + 'v_xad_u32': (r'\((v\d+) \^ (v\d+)\)', r'(\1 | \2)', lambda a, b, c: (a | b) + c), + 'v_bfi_b32': (r'\(~(v\d+) & (v\d+)\)', r'(\1 & \2)', lambda a, b, c: (a & b) | (a & c)), +} +BODY = { + 'v_bfe_u32': words('0c0048d5000922040d0048d5010b26040e0048d5020d2a040f0048d5030f2e04'), + 'v_mad_u32_u24': words('0c0043d5000922040d0043d5010b26040e0043d5020d2a040f0043d5030f2e04'), + 'v_lshl_add_u32': words('0c0046d7000922040d0046d7010b26040e0046d7020d2a040f0046d7030f2e04'), + 'v_add_lshl_u32': words('0c0047d7000922040d0047d7010b26040e0047d7020d2a040f0047d7030f2e04'), + 'v_add3_u32': words('0c006dd7000922040d006dd7010b26040e006dd7020d2a040f006dd7030f2e04'), + 'v_or3_b32': words('0c0072d7000922040d0072d7010b26040e0072d7020d2a040f0072d7030f2e04'), + 'v_and_or_b32': words('0c0071d7000922040d0071d7010b26040e0071d7020d2a040f0071d7030f2e04'), + 'v_lshl_or_b32': words('0c006fd7000922040d006fd7010b26040e006fd7020d2a040f006fd7030f2e04'), + 'v_xad_u32': words('0c0045d7000922040d0045d7010b26040e0045d7020d2a040f0045d7030f2e04'), + 'v_bfi_b32': words('0c004ad5000922040d004ad5010b26040e004ad5020d2a040f004ad5030f2e04'), +} +FAMILY = { + 'ops': OPS, 'draw': DRAW, 'mutations': MUTATIONS, 'body': BODY, + 'accepted': ['v_bfe_u32 v1, v2, 8, 4', 'v_mad_u32_u24 v1, v2, v3, v4', 'v_add3_u32 v1, v2, s3, 1', + 'v_bfi_b32 v1, v2, v3, v4', 'v_lshl_or_b32 v1, v2, 16, v3'], + 'refused': ['v_bfe_u32 v1, v2, v3', 'v_add3_u32 v1, v2, v3, v4, v5', 'v_or3_b32 v1, v2', + 'v_mad_u32_u24 v1, v2, v3, v4 clamp', 'v_xad_u32 v1, -v2, v3, v4', 'v_bfi_b32 v1, |v2|, v3, v4', + 'v_and_or_b32 v1, v2, v3, v4 op_sel:[1,0,0,0]'], +} + +if __name__ == '__main__': + main(FAMILY, __doc__) From 686915ea010b6eb22114c480ac46ea7391bb6047 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?As=C4=B1m=20Mirza=20=C3=87iftler?= <113895866+Asimmimx@users.noreply.github.com> Date: Thu, 26 Nov 2026 05:17:50 +0300 Subject: [PATCH 068/240] startup: draw the gfx2hlsl reciprocal, root, exp2 and log2 operations (#1745) The VEC_F table lowers v_rcp_f32, v_rcp_iflag_f32, v_sqrt_f32, v_rsq_f32, v_exp_f32 and v_log_f32 to 1.0 / x, sqrt, rsqrt, exp2 and log2, and no check ran any of them. tests/startup_gfx2hlsl_float_transcendental_check.py draws them with the shared per-lane runner (byte-identical copy of tests/startup_gfx2hlsl_lane_alu.py) on powers of two (and 0 and 9 for the square root), so every result is exact and the draw checks which function and which base each operation is lowered to, not its precision. Each operation has a mutated lowering whose first draw must read its own words. All 24 draws match on WARP and an RX 6600 through FXC ps_5_1 and DXC ps_6_0, and the 12 mutated draws read their mutated words. Co-authored-by: tedin7 --- .github/workflows/windows.yml | 2 + CMakeLists.txt | 11 +++ docs/experiments.md | 13 +++ ...tup_gfx2hlsl_float_transcendental_check.py | 84 +++++++++++++++++++ 4 files changed, 110 insertions(+) create mode 100644 tests/startup_gfx2hlsl_float_transcendental_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index af30cda6e..12cf17f2b 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -120,6 +120,7 @@ jobs: (["tests/startup_image_load_d16_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_image_load_d16_check.py", "decode", "libLLVM-15.so.1"], {}), (["tests/startup_flat_param_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_gfx2hlsl_float_transcendental_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_bit_alu_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_interp_f16_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_interp_p2_hi_check.py", "binary", "llvm-mc-15"], {}), @@ -294,6 +295,7 @@ jobs: tests/startup_run_ps1_check.py \ tests/startup_run_sh_check.py \ tests/startup_flat_param_check.py \ + tests/startup_gfx2hlsl_float_transcendental_check.py \ tests/startup_ps_input_scan_check.py \ tests/startup_packed_position_provenance_check.py \ tests/startup_build_rev_check.py \ diff --git a/CMakeLists.txt b/CMakeLists.txt index c1589b1a8..8c0899266 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4196,6 +4196,17 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_inline_sampler_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl binary32 reciprocal, roots, exp2 and log2 (VEC_F) on exact inputs: translation controls, then a + # draw of the translated pairs with reference words and one mutated lowering per operation. + add_test(NAME startup_gfx2hlsl_float_transcendental_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_float_transcendental_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_float_transcendental_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_float_transcendental_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_float_transcendental_${adapter} PROPERTIES TIMEOUT 300 + SKIP_RETURN_CODE 77) + endforeach() add_test(NAME startup_gfx2hlsl_scalar_shift64_bfe_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_scalar_shift64_bfe_check.py") add_test(NAME startup_gfx2hlsl_scalar_m0_controls COMMAND "${INTAKE_PYTHON}" -B diff --git a/docs/experiments.md b/docs/experiments.md index 0f3eb2e1f..aaf886b70 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15821,6 +15821,19 @@ The [MASM fixture](../tests/cpu/vex_parity.asm) and [differential check](../test ctest --preset release --no-tests=error -R '^cpu_aot_vex_parity$' -V ``` +## Startup translator: reciprocal, roots, exp2 and log2 + +The `VEC_F` table of `tools/startup/gfx2hlsl.py` lowers six operations to HLSL with no check that ran them before: `v_rcp_f32` and `v_rcp_iflag_f32` to `1.0 / x`, `v_sqrt_f32` to `sqrt`, `v_rsq_f32` to `rsqrt`, `v_exp_f32` to `exp2` and `v_log_f32` to `log2`. `tests/startup_gfx2hlsl_float_transcendental_check.py` draws them with the shared runner `tests/startup_gfx2hlsl_lane_alu.py`. Each draw applies one operation per lane on flat inputs, alternates the `_e32` and `_e64` spellings, and compares the four result words exactly. + +Every input is a power of two, or 0 and 9 for the square root, so every result is exact. The check therefore tests which function each operation is lowered to and the base 2 of `v_exp_f32` and `v_log_f32`. It does not test how many ulps an adapter's approximation may be off. + +Each operation has a wrong lowering whose first draw must read its own mutated words: +- `2.0 / x` for the reciprocals; +- sqrt and rsqrt exchanged; +- the exponent off by one; +- the logarithm plus one. + +On WARP 10.0.26100.9818 and on an AMD Radeon RX 6600 (driver 32.0.21045.29003), all 24 draws matched through FXC `ps_5_1` and DXC `ps_6_0`, and all 12 mutated draws read their mutated words. `v_sin_f32` and `v_cos_f32` are not covered: their results at the few exact points depend on the approximation. Tests: `startup_gfx2hlsl_float_transcendental_controls`, `startup_gfx2hlsl_float_transcendental_warp` and `startup_gfx2hlsl_float_transcendental_hardware`. ### gfx1013 pixel DPP16 quad broadcast The pixel translator lowers `quad_perm:[k,k,k,k]` (k = 0 to 3) with full `row_mask` and `bank_mask` on `v_mov_b32` and the VOP1/VOP2 float, integer and integer-to-float forms to `QuadReadLaneAt(value, k)`. The four lanes of a pixel quad are one 2 x 2 block (lane = x & 1 | (y & 1) << 1). It is accepted in the entry straight-line prefix of a pixel stage that ran `s_wqm_b64 exec, exec` (or `s_wqm_b32 exec_lo, exec_lo`) with EXEC unchanged since: the entry EXEC can leave out lanes of a partly covered quad, and the guest would then read an inactive source lane while `QuadReadLaneAt` returns a helper lane's value. A later uniform loop or forward branch elsewhere in the same stage does not drop that proof (the M200-01/003 shape). Without the proof the instruction is refused, as are a broadcast after a branch target, after EXEC changed, or with divergent EXEC before the broadcast, swaps, pair broadcasts, row shifts, mirrors, DPP8, partial masks, `bound_ctrl:0`, non-VGPR sources and vertex stages. `fi:1` is accepted with the proof and changes nothing, since no source lane is disabled. A stage that holds a quad read compiles as `ps_6_0` with DXC (`X2W_DXC`, the Windows Kits `bin` folder or `PATH`), and its vertex stage as `vs_6_0`. diff --git a/tests/startup_gfx2hlsl_float_transcendental_check.py b/tests/startup_gfx2hlsl_float_transcendental_check.py new file mode 100644 index 000000000..adc1b5bc2 --- /dev/null +++ b/tests/startup_gfx2hlsl_float_transcendental_check.py @@ -0,0 +1,84 @@ +"""Binary32 reciprocal, root, exponential and logarithm of tools/startup/gfx2hlsl.py (its VEC_F table). + + (no arguments) translation controls, pure Python + binary reassemble the pixel bodies and compare them with the recorded words + draw [fxc] + draw one pixel per four input sets and compare the four result words + +Covers v_rcp_f32, v_rcp_iflag_f32, v_sqrt_f32, v_rsq_f32, v_exp_f32 and v_log_f32, which no check ran before. They +lower to 1.0 / x, sqrt, rsqrt, exp2 and log2. The fixture and runner are startup_gfx2hlsl_lane_alu.py: one operation +per lane, alternating the e32 and e64 spellings, on flat parameters the compilers cannot fold. The references follow +the AMD RDNA 2 ISA reference (v_exp_f32 and v_log_f32 are base 2). Every input is a power of two, or 0 and 9 for the +square root, so every result is exact and the comparison does not depend on how many ulps an adapter's +approximation may be off: it checks which function each operation is lowered to, not its precision. +""" +import math +import struct +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from startup_gfx2hlsl_lane_alu import main, words # noqa: E402 + + +def f(value): + return struct.unpack(' Date: Thu, 26 Nov 2026 03:19:16 +0100 Subject: [PATCH 069/240] startup: Tracy memory pools for XMemAlloc and the stand-ins' C++ heaps (X2W_TRACY) (#2573) * startup: Tracy memory pools for XMemAlloc and the stand-ins' C++ heaps (X2W_TRACY) X2W_ALLOC, X2W_FREE and X2W_PLOT join the zone macros. XMemAlloc/XMemFree feed the pool "XMemAlloc", each instrumented DLL reports its operator new/delete as " C++ heap", and XMemVirtualAlloc commits are a cumulative plot (the title frees those ranges with Win32 calls). Without the option the macros are no-ops. Co-Authored-By: Claude Fable 5.2 * test: guard the X2W_TRACY operator new/delete replacement --------- Co-authored-by: Claude Fable 5.2 Co-authored-by: tedin7 --- CMakeLists.txt | 14 +++-- docs/startup-runtime.md | 3 +- src/startup_stubs/profile_zone.h | 11 +++- src/startup_stubs/tracy_new.cpp | 35 +++++++++++++ src/xmem_mapped_pages.cpp | 8 +++ src/xmem_shim.cpp | 7 ++- tests/fixtures/tracy_fake/tracy/Tracy.hpp | 28 ++++++++++ tests/tracy_new_check.cpp | 62 +++++++++++++++++++++++ 8 files changed, 160 insertions(+), 8 deletions(-) create mode 100644 src/startup_stubs/tracy_new.cpp create mode 100644 tests/fixtures/tracy_fake/tracy/Tracy.hpp create mode 100644 tests/tracy_new_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 8c0899266..d75c9a2de 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -102,6 +102,13 @@ target_compile_features(memory_query_check PRIVATE cxx_std_17) target_link_libraries(memory_query_check PRIVATE psapi) add_test(NAME desktop_memory_query COMMAND memory_query_check) +# tracy_new.cpp against a recording stand-in for Tracy's memory macros (no Tracy fetched, runs in every build). +add_executable(tracy_new_check tests/tracy_new_check.cpp) +target_compile_features(tracy_new_check PRIVATE cxx_std_17) +target_include_directories(tracy_new_check PRIVATE tests/fixtures/tracy_fake) +target_compile_definitions(tracy_new_check PRIVATE X2W_TRACY=1 X2W_TRACY_HEAP="test C++ heap") +add_test(NAME tracy_new COMMAND tracy_new_check) + add_executable(xmem_committed_memory_check tests/xmem_committed_memory_check.cpp) target_compile_features(xmem_committed_memory_check PRIVATE cxx_std_17) target_link_libraries(xmem_committed_memory_check PRIVATE OneCore) @@ -551,11 +558,11 @@ target_link_libraries(d3d12_xs_shim PRIVATE user32 gdi32 d3dcompiler dxgi x2w_bu target_compile_options(d3d12_xs_shim PRIVATE /bigobj) set_target_properties(xmem_shim d3d12_xs_shim ${startup_stub_targets} PROPERTIES MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") -# Developer-only measurement build: Tracy zones in the stand-ins (src/startup_stubs/profile_zone.h). +# Developer-only measurement build: Tracy zones and memory pools in the stand-ins (src/startup_stubs/profile_zone.h). # One shared TracyClient.dll serves every instrumented DLL. Off (the default), nothing is fetched, defined or linked. # On, Tracy (BSD-3-Clause, see docs/startup-runtime.md) is fetched at the pinned commit below, or taken from an existing # checkout with -DFETCHCONTENT_SOURCE_DIR_TRACY=. The client opens a local socket; see docs/startup-runtime.md. -option(X2W_TRACY "Instrument the startup stand-ins with Tracy zones (fetches Tracy v0.15.0)" OFF) +option(X2W_TRACY "Instrument the startup stand-ins with Tracy zones and memory pools (fetches Tracy v0.15.0)" OFF) if(X2W_TRACY) include(FetchContent) set(CMAKE_POLICY_DEFAULT_CMP0091 NEW) # Tracy's 3.13 minimum would otherwise ignore MSVC_RUNTIME_LIBRARY @@ -576,7 +583,8 @@ if(X2W_TRACY) RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}") foreach(target IN ITEMS d3d12_xs_shim startup_stub_xcrdapi xmem_shim) target_link_libraries(${target} PRIVATE Tracy::TracyClient) - target_compile_definitions(${target} PRIVATE X2W_TRACY=1) + target_compile_definitions(${target} PRIVATE X2W_TRACY=1 X2W_TRACY_HEAP="${target} C++ heap") + target_sources(${target} PRIVATE src/startup_stubs/tracy_new.cpp) endforeach() endif() add_executable(startup_null_views_check tests/startup_null_views_check.cpp) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 87d0417b3..8bc22cfdf 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1258,7 +1258,8 @@ For a timeline instead of the counters, configure a separate build tree with `-D - **Client settings.** On-demand (nothing is recorded until a profiler connects), localhost only, no broadcast, no call stacks, no system tracing and no crash handler. - **Output.** One shared `TracyClient.dll` is linked into `d3d12_xs.dll`, `XCRDAPI.dll` and `xmem.dll`; copy it beside them. - **Zones.** `ExecuteCommandLists`, `Present` (with a frame mark), the frame-wait sleep, window present, desktop pipeline creation, `device_memory_srv` with its resource scans, each DirectStorage request, and the xmem page map and physical write. `src/startup_stubs/profile_zone.h` defines the macros. -- **Off.** Without the option nothing is fetched, defined or linked, and the macros expand to nothing. +- **Memory.** Three kinds of data for Tracy's Memory view, by name: the pool `XMemAlloc` (every block `XMemAlloc` returns until its `XMemFree`), one pool per instrumented DLL for its C++ heap (` C++ heap`, `operator new`/`delete` replaced in `src/startup_stubs/tracy_new.cpp`), and the plot `XMemVirtualAlloc commits (bytes, cumulative)`. That last one is a plot because the title releases those ranges with Win32 calls the stand-in does not see. Memory the title takes straight from Win32 (`VirtualAlloc`, its own heaps) and what the graphics driver commits are not tracked; compare the pools with the `commit peak=` heartbeat to size that remainder. A profiler that connects late misses earlier allocations (on-demand client). +- **Off.** Without the option nothing is fetched, defined or linked, and the macros expand to nothing or a no-op. To capture without a GUI, build Tracy's `capture` tool from the same checkout (`cmake -S /capture -B `; that project fetches its own dependencies), start `capture -o run.tracy -a 127.0.0.1 -s ` and then the instrumented run. Open the file with the Tracy profiler, or export zone statistics with `csvexport`. diff --git a/src/startup_stubs/profile_zone.h b/src/startup_stubs/profile_zone.h index 4981dc672..e94d7e2f6 100644 --- a/src/startup_stubs/profile_zone.h +++ b/src/startup_stubs/profile_zone.h @@ -1,12 +1,19 @@ -// Opt-in Tracy zones for the stand-ins (CMake option X2W_TRACY, a local measurement build). -// Without the option every macro expands to nothing and no Tracy header is included. +// Opt-in Tracy zones, memory pools and plots for the stand-ins (CMake option X2W_TRACY, a local measurement build). +// Without the option every macro expands to nothing or a no-op and no Tracy header is included. #pragma once #if X2W_TRACY #include #define X2W_ZONE(name) ZoneScopedN(name) #define X2W_FRAME_MARK FrameMark +// A named memory pool: every X2W_ALLOC needs its X2W_FREE with the same pool name. +#define X2W_ALLOC(pointer, bytes, pool) TracyAllocN(pointer, bytes, pool) +#define X2W_FREE(pointer, pool) TracyFreeN(pointer, pool) +#define X2W_PLOT(name, value) TracyPlot(name, value) #else #define X2W_ZONE(name) #define X2W_FRAME_MARK +#define X2W_ALLOC(pointer, bytes, pool) ((void)0) +#define X2W_FREE(pointer, pool) ((void)0) +#define X2W_PLOT(name, value) ((void)0) #endif diff --git a/src/startup_stubs/tracy_new.cpp b/src/startup_stubs/tracy_new.cpp new file mode 100644 index 000000000..046ea0d03 --- /dev/null +++ b/src/startup_stubs/tracy_new.cpp @@ -0,0 +1,35 @@ +// X2W_TRACY builds only (CMakeLists.txt adds this file to each instrumented DLL): the C++ heap of the DLL as a +// Tracy memory pool. The array, sized and nothrow forms of the runtime forward to these four. +#include "profile_zone.h" + +#include +#include +#include + +void* operator new(std::size_t bytes) +{ + void* block = std::malloc(bytes ? bytes : 1); + if (!block) throw std::bad_alloc(); + X2W_ALLOC(block, bytes, X2W_TRACY_HEAP); + return block; +} + +void* operator new(std::size_t bytes, std::align_val_t alignment) +{ + void* block = _aligned_malloc(bytes ? bytes : 1, static_cast(alignment)); + if (!block) throw std::bad_alloc(); + X2W_ALLOC(block, bytes, X2W_TRACY_HEAP); + return block; +} + +void operator delete(void* block) noexcept +{ + if (block) X2W_FREE(block, X2W_TRACY_HEAP); + std::free(block); +} + +void operator delete(void* block, std::align_val_t) noexcept +{ + if (block) X2W_FREE(block, X2W_TRACY_HEAP); + _aligned_free(block); +} diff --git a/src/xmem_mapped_pages.cpp b/src/xmem_mapped_pages.cpp index 756741898..324e23253 100644 --- a/src/xmem_mapped_pages.cpp +++ b/src/xmem_mapped_pages.cpp @@ -17,6 +17,7 @@ #include #include +#include #include #include #include @@ -862,6 +863,13 @@ void* local_virtual_alloc(void* address, SIZE_T bytes, DWORD type, ULONGLONG att if (result && !(type & MEM_RESERVE_PLACEHOLDER)) record_reservation(result, bytes); how = "placeholder reserve"; } +#if X2W_TRACY + if (result && (type & MEM_COMMIT)) { + // A plot, not a pool: the title releases these ranges with Win32 calls that are not seen here. + static std::atomic committed; + X2W_PLOT("XMemVirtualAlloc commits (bytes, cumulative)", static_cast(committed += bytes)); + } +#endif const DWORD error = result ? 0 : GetLastError(); x2w_local::logf("x2w-xmem XMemVirtualAlloc addr=%p size=0x%llx type=0x%lx attr=0x%llx prot=0x%lx -> %p (%s, err %lu)", address, static_cast(bytes), static_cast(type), diff --git a/src/xmem_shim.cpp b/src/xmem_shim.cpp index a5b43f0f1..50272449c 100644 --- a/src/xmem_shim.cpp +++ b/src/xmem_shim.cpp @@ -15,6 +15,7 @@ #include "era_title_gpu.h" #include "xmem_gpu_usage.h" #include "startup_stubs/local_log.h" +#include "startup_stubs/profile_zone.h" #include @@ -83,17 +84,19 @@ bool local_free(void* block) extern "C" void* XMemAlloc(SIZE_T bytes, ULONGLONG attributes) { void* allocation = era_heap::allocate(bytes, attributes); - if (!allocation && bytes && x2w_local::env_on("X2W_XMEM_PERMISSIVE")) return local_alloc(bytes, attributes); // Desktop policy: graphics memory types count as GPU-intended for XMemVirtualQuery. - if (allocation && is_graphics(attributes) && !era_title_gpu::track(allocation, bytes)) { + if (!allocation && bytes && x2w_local::env_on("X2W_XMEM_PERMISSIVE")) allocation = local_alloc(bytes, attributes); + else if (allocation && is_graphics(attributes) && !era_title_gpu::track(allocation, bytes)) { era_heap::release_with_attributes(allocation, attributes); return nullptr; } + if (allocation) X2W_ALLOC(allocation, bytes, "XMemAlloc"); return allocation; } extern "C" void XMemFree(void* allocation, ULONGLONG attributes) { + if (allocation) X2W_FREE(allocation, "XMemAlloc"); if (allocation && local_free(allocation)) return; if (allocation && is_graphics(attributes)) { era_title_gpu::untrack(allocation); diff --git a/tests/fixtures/tracy_fake/tracy/Tracy.hpp b/tests/fixtures/tracy_fake/tracy/Tracy.hpp new file mode 100644 index 000000000..fb8c4c4f2 --- /dev/null +++ b/tests/fixtures/tracy_fake/tracy/Tracy.hpp @@ -0,0 +1,28 @@ +// Test double for Tracy's memory macros: records every pool event so tracy_new_check can assert on them. +// Used only by tracy_new_check; the real Tracy is never fetched for it. +#pragma once + +#include + +struct TracyFakeEvent { + bool alloc; + const void* pointer; + std::size_t bytes; + const char* pool; +}; + +constexpr std::size_t kTracyFakeMax = 16; +inline TracyFakeEvent g_tracy_events[kTracyFakeMax]; +inline std::size_t g_tracy_event_count = 0; + +inline void tracy_fake_record(bool alloc, const void* pointer, std::size_t bytes, const char* pool) +{ + if (g_tracy_event_count < kTracyFakeMax) + g_tracy_events[g_tracy_event_count++] = {alloc, pointer, bytes, pool}; +} + +#define TracyAllocN(pointer, bytes, pool) tracy_fake_record(true, (pointer), (bytes), (pool)) +#define TracyFreeN(pointer, pool) tracy_fake_record(false, (pointer), 0, (pool)) +#define TracyPlot(name, value) ((void)0) +#define ZoneScopedN(name) ((void)0) +#define FrameMark ((void)0) diff --git a/tests/tracy_new_check.cpp b/tests/tracy_new_check.cpp new file mode 100644 index 000000000..83cad82e1 --- /dev/null +++ b/tests/tracy_new_check.cpp @@ -0,0 +1,62 @@ +// src/startup_stubs/tracy_new.cpp replaces the DLL's operator new/delete in X2W_TRACY builds. This fixture compiles it +// against a recording stand-in for Tracy's memory macros and checks what a caller of the C++ heap relies on. +#include "../src/startup_stubs/tracy_new.cpp" + +#include +#include +#include + +namespace { +int failures = 0; + +void expect(bool condition, const char* what) +{ + if (condition) return; + std::fprintf(stderr, "FAIL: %s\n", what); + ++failures; +} + +bool pool_is_heap(const char* pool) { return pool && std::strcmp(pool, X2W_TRACY_HEAP) == 0; } +} + +int main() +{ + // An empty allocation is legal C++: it must return a usable pointer, and be reported with the requested size. + void* empty = operator new(0); + expect(empty != nullptr, "operator new(0) returns a block"); + expect(g_tracy_event_count == 1 && g_tracy_events[0].alloc && g_tracy_events[0].pointer == empty && + g_tracy_events[0].bytes == 0 && pool_is_heap(g_tracy_events[0].pool), + "operator new(0) is reported once to the C++ heap pool with 0 bytes"); + + operator delete(empty); + expect(g_tracy_event_count == 2 && !g_tracy_events[1].alloc && g_tracy_events[1].pointer == empty && + pool_is_heap(g_tracy_events[1].pool), + "operator delete reports the same pointer and pool"); + + // Over-aligned blocks come from _aligned_malloc, so they must go back through _aligned_free (a plain free() + // here corrupts the heap). + g_tracy_event_count = 0; + const std::align_val_t alignment{4096}; + void* aligned = operator new(100, alignment); + expect(aligned != nullptr, "aligned operator new returns a block"); + expect(reinterpret_cast(aligned) % 4096 == 0, "aligned operator new honours the alignment"); + std::memset(aligned, 0xA5, 100); + expect(g_tracy_event_count == 1 && g_tracy_events[0].bytes == 100, "aligned allocation reports its size"); + operator delete(aligned, alignment); + expect(g_tracy_event_count == 2 && !g_tracy_events[1].alloc && g_tracy_events[1].pointer == aligned, + "aligned delete reports the same pointer"); + + void* aligned_empty = operator new(0, alignment); + expect(aligned_empty != nullptr, "aligned operator new(0) returns a block"); + operator delete(aligned_empty, alignment); + + // Deleting a null pointer is a no-op and must not reach the profiler. + g_tracy_event_count = 0; + operator delete(nullptr); + operator delete(nullptr, alignment); + expect(g_tracy_event_count == 0, "operator delete(nullptr) reports nothing"); + + if (failures) return 1; + std::puts("tracy_new_check: ok"); + return 0; +} From 203cce148f69628714e92bdee61c3916510a489a Mon Sep 17 00:00:00 2001 From: RenzoWit35 <168984533+RenzoWit35@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:19:33 +0100 Subject: [PATCH 070/240] shader: lower negated and absolute f32 source operands in compute (#1673) Refs #1546. The four binary32 forms of the compute store profile (v_add_f32, v_sub_f32, v_subrev_f32, v_mul_f32) also lower in their VOP3 _e64 spelling when a source carries a modifier as LLVM 15 prints it on a register: -v, |v| or -|v|. The modifiers are sign-bit operations on the word, abs first and then neg, as pixel_aot does for v_cvt_f64_f32_e64 and the binary64 compare sources, so a signed zero or NaN payload keeps its other bits and no float abs() or negation is emitted. No opcode is added. The unmodified _e64 spelling and modifiers on the _e32 spelling stay refused at the instruction. clamp and mul:2, mul:4, div:2 are refused with "Unsupported float output modifier"; abs(), neg(), unbalanced bars and modifiers on constants with "Unsupported float source modifier". The fixture in tests/compute_alu_negabs_check.py puts each modifier on two operations, over values of both signs and signed zeros. On WARP the three read dispatches pass with all 320 words compared; 12 wrong references (each modifier dropped or exchanged) and 12 mutated HLSL sources (each abs mask or sign flip dropped, or a flip made an abs) each fail. A binary mode for the Ubuntu LLVM 15 job checks that the disassembly prints the five modified lines and translates identically. Run: ctest --preset dev --no-tests=error -R '^compute_store_aot_f32_negabs_(warp|hardware)$' -V Co-authored-by: tedin7 --- .github/workflows/windows.yml | 1 + CMakeLists.txt | 4 + docs/experiments.md | 12 +- tests/compute_alu_negabs_check.py | 273 ++++++++++++++++++++++++++++++ tools/compute_store_aot.py | 38 +++++ 5 files changed, 327 insertions(+), 1 deletion(-) create mode 100644 tests/compute_alu_negabs_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 12cf17f2b..94e853cb0 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -41,6 +41,7 @@ jobs: SPIRV = ["spirv-as", "spirv-val", "spirv-cross"] CHECKS = [ (["tests/compute_store_check.py", *COMMON_LLVM], {}), + (["tests/compute_alu_negabs_check.py", *COMMON_LLVM], {}), (["tests/compute_buffer_atomics_check.py", "--binary", "llvm-mc-15", "llvm-objcopy-15", "--llvm", "libLLVM-15.so.1"], {}), (["tests/compute_load_format_check.py", *COMMON_LLVM], {}), (["tests/compute_heap_view_check.py", *COMMON_LLVM], {}), diff --git a/CMakeLists.txt b/CMakeLists.txt index d75c9a2de..c859228bd 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -9755,6 +9755,10 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(compute_store_aot_alu_xor3_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/compute_store_aot_alu_xor3_${adapter}.txt") + add_test(NAME compute_store_aot_f32_negabs_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/compute_alu_negabs_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(compute_store_aot_f32_negabs_${adapter} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) add_test(NAME compute_store_aot_alu_bcnt_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/compute_alu_bcnt_check.py" draw "${DXC_EXECUTABLE}" "$" ${adapter}) diff --git a/docs/experiments.md b/docs/experiments.md index aaf886b70..2d58d0f0b 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -6564,7 +6564,7 @@ Four VOP2 forms lower to one rounded binary32 operation each, on the bit pattern A source is a VGPR, an SGPR that holds a known word, a 32-bit literal, the integer zero or one of the inline float constants LLVM prints (`0.5`, `1.0`, `2.0`, `4.0`, their negatives and `0.15915494`). The second source is a VGPR. Each operation is a small HLSL helper whose result is `precise`, so a multiply followed by an add is not contracted into one fused operation. The helpers are emitted only when the program uses them. -Fused multiply-add is not in this subset. `v_fma_f32`, `v_fmac_f32_e32` and `v_mac_f32_e32` stop the lowering at that instruction, because DXIL has no binary32 form whose single rounding is guaranteed. The `_e64` spellings, `clamp`, `abs` and negation modifiers, an SGPR as the second source, `v_max_f32`, `v_min_f32` and `v_mul_legacy_f32` are refused too. +Fused multiply-add is not in this subset. `v_fma_f32`, `v_fmac_f32_e32` and `v_mac_f32_e32` stop the lowering at that instruction, because DXIL has no binary32 form whose single rounding is guaranteed. The unmodified `_e64` spellings, `clamp`, `abs` and negation modifiers on the `_e32` spellings, an SGPR as the second source, `v_max_f32`, `v_min_f32` and `v_mul_legacy_f32` are refused too. The `_e64` spellings with source modifiers are described under [Negated and absolute binary32 sources](#negated-and-absolute-binary32-sources). NaN, infinity and denormals are not claimed. A literal, an inline integer or a scalar move that is one of them is refused with `Unverified float operand`. A word read from memory is not known statically, so its value is not checked: a caller that binds such a word must keep every operand and result finite and normal. The fixture below builds its operands with integer operations so that they always are. @@ -6586,6 +6586,16 @@ The source-built 32-thread fixture stores four words per thread (`128` words act The fixture replaces the `umin` of the read-compute-write fixture with two `v_xor3_b32`, hand-edited in LLVM 15 spelling: `out = (p ^ key ^ gid) ^ 0x2c5a96e1 ^ -16`, where `p` is the product above and `key = params[0].y = 0xa5c30f96`. Its sources are a result, the dispatch index, an SGPR constant word, a literal and a negative inline constant. The expected words come from a Python model of the instruction definition; lane 0 is also worked by hand (`0x2d574c65`). The readback uses the read harness and its three dispatches and compares all 320 words. On five groups with `n = 150`, each of these references must fail at the first word where it differs: one word off, lane 150 also writing, OR, AND or an add instead of XOR, each source dropped, and `+16` for `-16`. So must recompiled HLSL with an OR for either XOR, the key read from `params[0].z`, the dispatch index dropped, the literal off by one bit, or the inline constant dropped. Run `ctest --preset dev --no-tests=error -R '^compute_store_aot_alu_xor3_(warp|hardware)$' -V`. The translation controls alone are `python -B tests/compute_alu_xor3_check.py controls`. +#### Negated and absolute binary32 sources + +Issue #1546 lists the `-|v|` operand form among the gaps of the measured compute programs. The four binary32 forms above also lower in their VOP3 spelling, `v_add_f32_e64`, `v_sub_f32_e64`, `v_subrev_f32_e64` and `v_mul_f32_e64`, when at least one source carries a source modifier as LLVM 15 prints it on a register: `-v`, `|v|` or `-|v|` (likewise for an SGPR). The modifiers act on the sign bit of the 32-bit word, abs first and then neg, as the pixel translator does for `v_cvt_f64_f32_e64` and the binary64 compare sources: `|v|` is `(w & 0x7fffffffu)`, `-v` is `(w ^ 0x80000000u)` and `-|v|` is `((w & 0x7fffffffu) ^ 0x80000000u)`. They are integer operations on the word, so a signed zero or a NaN payload keeps its other bits; no float `abs()` or unary minus is emitted. In this spelling either source may be a VGPR, an SGPR that holds a known word, a literal, the integer zero or an inline float constant. The operation, its rounding and its finite-and-normal caller contract are those of the `_e32` forms. + +The unmodified `_e64` spelling stays refused at the instruction. `clamp` and the output modifiers `mul:2`, `mul:4` and `div:2` are refused with `Unsupported float output modifier`. The `abs()` and `neg()` spellings, unbalanced bars, a nested modifier and a modifier on a constant (`|1.0|`, `neg(0x3f800000)`, `-0x3f800000`) are refused with `Unsupported float source modifier`. A modified source that is not a known word, or a constant that is NaN, infinite or denormal, is refused with `Unverified float operand`. Modifiers on the `_e32` spellings, other binary32 and binary16 opcodes and `v_fma_f32` stop the lowering at the instruction. + +The fixture in `tests/compute_alu_negabs_check.py` is the read-compute-write kernel with the read bindings and `cap = params[0].y`, the float -0.75. From the source word it builds `x` in [1.5, 2) and `y` in [3, 4) as in the fixture above, then `d = x - 1.75`, which is negative on some lanes and positive on others, `z = 0 * d`, a signed zero, and `a = |d| + y`, `b = -d * a`, `c = b - (-|d|)`, `e = (-c) - |cap|`, `f = -|z| * y` (-0.0 on every lane) and `out = e ^ f` with the integer XOR, so bit 31 of `f` reaches the readback. Each modifier appears on two operations, and the SGPR and a second source carry one. The expected words come from a Python model that applies the modifiers to the bits and rounds each step to binary32. The translation controls pin the exact store, evaluate the three modifier expressions on +0, -0, quiet and signalling NaN payloads, -infinity, a negative value and a denormal word against the bit model, and refuse each form listed above. Dropping the abs or the neg in the lowering, emitting the negation as a float negation, or accepting an output modifier, unbalanced bars or a modified constant each fails them. + +The readback uses the read harness and its three dispatches and compares all 320 words. For each modified source, a reference with the negation dropped, the abs dropped, or abs and negation exchanged (12 references) must fail at its first differing word. So must recompiled HLSL with any one of the four abs masks dropped, or any one of the four sign flips dropped or replaced by an abs (12 mutations). The `binary` mode assembles the fixture with LLVM 15, requires the disassembly to print the five modified lines unchanged and to translate identically; it runs in the Ubuntu job. Run `ctest --preset dev --no-tests=error -R '^compute_store_aot_f32_negabs_(warp|hardware)$' -V`. The translation controls alone are `python -B tests/compute_alu_negabs_check.py controls`. + #### Bit count plus addend (`v_bcnt_u32_b32`) `v_bcnt_u32_b32 vD, a, b` is `D = CountOneBits(a) + b`, the addend wrapping modulo 2^32 (RDNA2 instruction set; diff --git a/tests/compute_alu_negabs_check.py b/tests/compute_alu_negabs_check.py new file mode 100644 index 000000000..ebb3d72c4 --- /dev/null +++ b/tests/compute_alu_negabs_check.py @@ -0,0 +1,273 @@ +"""Check -v, |v| and -|v| sources of the VOP3 binary32 forms in the compute store profile: exact lowering, refusals, +an LLVM 15 round trip and a WARP or GPU readback.""" +from pathlib import Path +import re +import struct +import subprocess +import sys +import tempfile + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import compute_store_check as base # noqa: E402 + +aot = base.aot +NAME = "read_f32_negabs" +# cap = params[0].y is the float -0.75, so -|s0| differs from -s0 and from |s0| on every lane. +CAP = 0xbf400000 +HALF_WAY = 0x3fe00000 # the float 1.75, a literal: it is not an inline constant +# Binary32 with VOP3 source modifiers, hand-edited in LLVM 15 spelling into the read-compute-write fixture. As in +# compute_store_check.READ_F32, the source word w gives x = 1.5 + (w & 0x3fffff) / 2^23 in [1.5, 2) and +# y = 3.0 + (w >> 10) / 2^22 in [3, 4). Then +# d = x - 1.75 in [-0.25, 0.25), negative on some lanes and positive on others +# z = 0 * d +0.0 where d > 0 and -0.0 where d < 0 +# a = |d| + y |v| on add, src0 +# b = -d * a -v on mul, src0 +# c = b - (-|d|) -|v| on sub, src1 +# e = (-c) - (-|cap|) -|v| on an SGPR and -v on src1 of subrev +# f = |z| * y |v| on a signed zero: +0.0 on every lane +# out = e ^ f bitwise, so a sign bit left on f reaches the readback +# Each modifier appears on two operations. Dropping an abs changes the lanes with d < 0 (and the cap); exchanging an +# abs for a negation changes the lanes with d > 0; dropping a negation changes every lane. The cap is negative, so its abs\n# and its negation each change every lane. +MODIFIED = ("v_add_f32_e64 v6, |v4|, v3", "v_mul_f32_e64 v7, -v4, v6", "v_sub_f32_e64 v8, v7, -|v4|", + "v_subrev_f32_e64 v9, -|s0|, -v8", "v_mul_f32_e64 v10, |v5|, v3") +LINES = base.variant( + base.READ_COMPUTE, + ("v_and_b32_e32 v2, 0xffff, v1", "v_and_b32_e32 v2, 0x3fffff, v1\nv_or_b32_e32 v2, 0x3fc00000, v2\n" + "v_lshrrev_b32_e32 v3, 10, v1\nv_or_b32_e32 v3, 0x40400000, v3"), + ("v_lshrrev_b32_e32 v1, 16, v1", f"v_subrev_f32_e32 v4, 0x{HALF_WAY:08x}, v2\nv_mul_f32_e32 v5, 0, v4\n" + + "\n".join(MODIFIED)), + ("v_mad_u32_u24 v1, v2, v1, v0", "v_xor_b32_e32 v1, v10, v9"), + ("v_min_u32_e32 v1, s0, v1", ""), +) +BINDING = base.READ_BINDING +# The modifier of each modified source, by name: a0 is src0 of a, c1 src1 of c, and so on. +SITES = {"a0": "|", "b0": "-", "c1": "-|", "e0": "-|", "e1": "-", "f0": "|"} +ABS, NEG = "& 0x7fffffffu)", " ^ 0x80000000u)" +# The expected store, built from the step names above: a modified source is its word with bit 31 cleared or flipped. +LOAD = base.READ_LOADS["read_copy"] +X = f"(0x3fc00000u | (0x003fffffu & {LOAD}))" +Y = f"(0x40400000u | ({LOAD} >> (0x0000000au & 31u)))" +D = f"f32_sub({X}, 0x{HALF_WAY:08x}u)" +Z = f"f32_mul(0x00000000u, {D})" +A = f"f32_add(({D} & 0x7fffffffu), {Y})" +B = f"f32_mul(({D} ^ 0x80000000u), {A})" +C = f"f32_sub({B}, (({D} & 0x7fffffffu) ^ 0x80000000u))" +E = f"f32_sub(({C} ^ 0x80000000u), ((params[0].y & 0x7fffffffu) ^ 0x80000000u))" +F = f"f32_mul(({Z} & 0x7fffffffu), {Y})" +STORE = f" outputData.Store(tid.x * 4u + 0u, ({F} ^ {E}));" + + +def modify(bits, modifier): + """VOP3 source modifiers on the 32-bit word: abs clears bit 31, then neg flips it.""" + if "|" in modifier: + bits &= 0x7fffffff + if "-" in modifier: + bits ^= 0x80000000 + return bits + + +def steps(gid, sites=SITES): + """Independent CPU model of one lane as binary32 bit patterns, every intermediate value; sites may change one.""" + value, bits = base.f32_value, base.f32_bits + + def op(fn, a, b): + return bits(base.f32_round(fn(value(a), value(b)))) + + word = base.source_word(gid) + x, y = 0x3fc00000 | word & 0x3fffff, 0x40400000 | word >> 10 + d = op(lambda p, q: p - q, x, HALF_WAY) + z = op(lambda p, q: p * q, 0, d) + a = op(lambda p, q: p + q, modify(d, sites["a0"]), y) + b = op(lambda p, q: p * q, modify(d, sites["b0"]), a) + c = op(lambda p, q: p - q, b, modify(d, sites["c1"])) + e = op(lambda p, q: p - q, modify(c, sites["e1"]), modify(CAP, sites["e0"])) + f = op(lambda p, q: p * q, modify(z, sites["f0"]), y) + return x, y, d, z, a, b, c, e, f, e ^ f + + +def negabs_words(groups, bound, **reference): + words = [base.SENTINEL] * 320 + for gid in range(min(32 * groups, bound)): + words[gid] = steps(gid, **reference)[-1] + return words + + +def wrong_sites(): + """One reference per modified source with its negation dropped, its abs dropped, or abs and negation exchanged.""" + for site, modifier in SITES.items(): + changes = {"-": ("neg dropped", "", "abs for neg", "|"), "|": ("abs dropped", "", "neg for abs", "-"), + "-|": ("neg dropped", "|", "abs dropped", "-")}[modifier] + for label, new in (changes[:2], changes[2:]): + yield f"{site} {label}", SITES | {site: new} + + +def lower(*changes, **binding): + return aot.lower(base.variant(LINES, *changes), 32, **(BINDING | binding)).splitlines() + + +def controls(): + """Exact modifier words, the sign-bit form on zeros and NaNs, then one rejection per form outside the subset.""" + lines = lower() + store = lines[-3] + assert lines[-4:] == [base.GUARD_IF, STORE, " }", "}"], lines + # Each modifier is an integer operation on the word, once per modified source, and never a float abs or negation. + assert store.count(ABS) == 4 and store.count(NEG) == 4, store + assert "abs(" not in "\n".join(lines) and "-asfloat" not in "\n".join(lines), lines + + # The sign-bit form keeps every other bit, also for signed zeros, infinities and NaN payloads, which the float + # forms abs() and unary minus need not do. The expression is evaluated here on the word. + vector = {2: ("alu", "W")} + forms = {token: aot.float_e64_source(token, {}, vector, set()) for token in ("-v2", "|v2|", "-|v2|")} + assert forms == {"-v2": "(W ^ 0x80000000u)", "|v2|": "(W & 0x7fffffffu)", "-|v2|": "((W & 0x7fffffffu) ^ 0x80000000u)"} + for word in (0x00000000, 0x80000000, 0x7fc12345, 0xffc00001, 0x7f800001, 0xff800000, 0xbf400000, 0x00000001): + for token, expression in forms.items(): + got = eval(re.sub(r"(0x[0-9a-f]+)u", r"\1", expression).replace("W", str(word))) + assert got == modify(word, token.replace("v2", "")), (token, hex(word), hex(got)) + + # A spelling of the same program: a source without modifier may stay plain in a modified _e64 form. + plain = "v_add_f32_e64 v6, |v4|, v3" + assert lower((plain, "v_add_f32_e64 v6, v3, |v4|"))[-3] != store + assert lower((plain, "v_add_f32_e64 v6, |v4|, s0"))[-3].count("params[0].y") == 2 + # A source modifier changes the program: each one dropped (as the _e32 form where that is all) differs. + assert lower(("v_mul_f32_e64 v7, -v4, v6", "v_mul_f32_e32 v7, v4, v6"))[-3] != store + assert lower(("v_sub_f32_e64 v8, v7, -|v4|", "v_sub_f32_e64 v8, v7, |v4|"))[-3] != store + assert lower(("v_sub_f32_e64 v8, v7, -|v4|", "v_sub_f32_e64 v8, v7, -v4"))[-3] != store + assert lower(("v_subrev_f32_e64 v9, -|s0|, -v8", "v_subrev_f32_e64 v9, |s0|, -v8"))[-3] != store + + unsupported, modifier = "Unsupported compute instruction: ", "Unsupported float source modifier" + output, operand = "Unsupported float output modifier", "Unverified float operand" + add = "v_add_f32_e64 v6, |v4|, v3" + for message, changes in ( + # The unmodified _e64 spelling stays refused, as does every opcode outside the four binary32 forms. + (unsupported + "v_add_f32_e64", ((add, "v_add_f32_e64 v6, v4, v3"),)), + (unsupported + "v_max_f32_e64", ((add, "v_max_f32_e64 v6, |v4|, v3"),)), + (unsupported + "v_fma_f32", ((add, "v_fma_f32 v6, |v4|, v3, v2"),)), + (unsupported + "v_add_f16_e64", ((add, "v_add_f16_e64 v6, |v4|, v3"),)), + # Modifiers on the VOP2 spelling, which has no modifier field. + (unsupported + "v_add_f32_e32", ((add, "v_add_f32_e32 v6, |v4|, v3"),)), + (unsupported + "v_add_f32_e32", ((add, "v_add_f32_e32 v6, -v4, v3"),)), + (unsupported + "v_add_f32_e32", ((add, "v_add_f32_e32 v6, -|v4|, v3"),)), + # Output modifiers, a third source and a register range. + (output, ((add, add + " clamp"),)), + (output, ((add, add + " mul:2"),)), + (output, ((add, add + " mul:4"),)), + (output, ((add, add + " div:2"),)), + (unsupported + "v_add_f32_e64", ((add, add + ", v2"),)), + (modifier, ((add, "v_add_f32_e64 v6, |v[4:5]|, v3"),)), + # Spellings LLVM 15 does not print for a register, unbalanced bars, and modifiers on constants. + (modifier, ((add, "v_add_f32_e64 v6, abs(v4), v3"),)), + (modifier, ((add, "v_add_f32_e64 v6, neg(v4), v3"),)), + (modifier, ((add, "v_add_f32_e64 v6, --v4, v3"),)), + (modifier, ((add, "v_add_f32_e64 v6, |-v4|, v3"),)), + (modifier, ((add, "v_add_f32_e64 v6, |v4, v3"),)), + (modifier, ((add, "v_add_f32_e64 v6, -|v4, v3"),)), + (modifier, ((add, "v_add_f32_e64 v6, -v4|, v3"),)), + (modifier, ((add, "v_add_f32_e64 v6, |v4|, |1.0|"),)), + (modifier, ((add, "v_add_f32_e64 v6, |v4|, -|0.5|"),)), + (modifier, ((add, "v_add_f32_e64 v6, |v4|, neg(0x3f800000)"),)), + (modifier, ((add, "v_add_f32_e64 v6, |v4|, -0x3f800000"),)), + (modifier, ((add, "v_add_f32_e64 v6, |v4|, |0x3f800000|"),)), + # Sources that are not known words or not finite normal constants, with and without a modifier. + (operand, ((add, "v_add_f32_e64 v6, |v40|, v3"),)), + (operand, ((add, "v_add_f32_e64 v6, |v4|, v40"),)), + (operand, ((add, "v_add_f32_e64 v6, -|s20|, v3"),)), + (operand, ((add, "v_add_f32_e64 v6, -|s8|, v3"),)), + (operand, ((add, "s_mov_b32 s20, 0x7fc00000\nv_add_f32_e64 v6, |s20|, v3"),)), + (operand, ((add, "s_mov_b32 s20, 0x80000001\nv_add_f32_e64 v6, -s20, v3"),)), + (operand, ((add, "v_add_f32_e64 v6, |v4|, 0x7f800000"),)), + (operand, ((add, "v_add_f32_e64 v6, |v4|, -1"),)), + (operand, ((add, "v_add_f32_e64 v256, |v4|, v3"),)), + # A result is data only: not a store address and not a lane-guard operand, and a long chain is refused. + ("Unsupported store address", (("v1, v0, s[8:11]", "v0, v1, s[8:11]"),)), + ("Unverified lane guard compare", (("v_xor_b32_e32 v1, v10, v9", + "v_xor_b32_e32 v1, v10, v9\nv_cmp_gt_u32_e32 vcc_lo, s3, v6"),)), + ("ALU expression too large", (("v_xor_b32_e32 v1, v10, v9", + "v_mul_f32_e64 v9, -v9, v9\n" * 3 + "v_xor_b32_e32 v1, v10, v9"),)), + ): + base.rejects(message, lower, *changes) + + +def binary(directory, assembler, objcopy, library): + """Assemble the fixture with LLVM 15, disassemble it and require the same spelling and the same translation.""" + src, obj, raw = [directory / x for x in ("negabs.s", "negabs.o", "negabs.bin")] + src.write_text("\n".join(LINES) + "\n", encoding="ascii") + subprocess.run([assembler, "-triple=amdgcn--amdpal", "-mcpu=gfx1013", "-filetype=obj", src, "-o", obj], check=True) + subprocess.run([objcopy, "-O", "binary", "--only-section=.text", obj, raw], check=True) + decoded = base.disassemble(raw.read_bytes(), library, offsets=True) + printed = [line for _, line in decoded] + missing = [line for line in MODIFIED if line not in printed] + assert not missing, (missing, printed) + assert aot.lower(aot.labelled(decoded), 32, **BINDING) == aot.lower(LINES, 32, **BINDING) + print(f"{NAME}: LLVM round trip prints the {len(MODIFIED)} modified forms and translates identically") + return 0 + + +def draw(directory, compiler, renderer, backend): + """Translate, compile and dispatch the fixture, then require wrong references and mutated sources to fail.""" + src, cso, case = [directory / x for x in ("store.hlsl", "store.cso", "store.case")] + source = aot.lower(LINES, 32, **BINDING) + src.write_text(source, encoding="ascii") + subprocess.run([compiler, "-T", "cs_6_0", "-E", "main", "-Fo", cso, src], check=True) + cmd = [renderer, backend, "--compute-store-case", cso, case] + constants = [0x5eed0000 + i for i in range(16)] + constants[1] = CAP + groups, bound = base.READ_RUNS[-1] + + def write(run_groups, run_bound, words): + case.write_bytes(struct.pack("<337I", run_groups, *words, run_bound, *constants[1:])) + + # Every operand and result of an active lane is finite and normal, except z and f, which are signed zeros, and d + # takes both signs, so each modifier is observed. f is +0.0 on every lane, z is -0.0 on some lanes. + lanes = [steps(gid) for gid in range(bound)] + for gid, lane in enumerate(lanes): + x, y, d, z, a, b, c, e, f, _ = lane + for value in (x, y, d, a, b, c, e): + assert 0x00800000 <= value & 0x7fffffff < 0x7f800000, (gid, hex(value)) + assert z == d & 0x80000000 and f == 0, (gid, hex(z), hex(f)) + assert {lane[2] >> 31 for lane in lanes} == {0, 1}, "d has one sign on every lane" + for run_groups, run_bound in base.READ_RUNS: + write(run_groups, run_bound, negabs_words(run_groups, run_bound)) + result = subprocess.run(cmd) + if result.returncode: + return result.returncode + expected = negabs_words(groups, bound) + wrong = list(wrong_sites()) + for label, sites in wrong: + reference = negabs_words(groups, bound, sites=sites) + word = next(i for i, (a, b) in enumerate(zip(expected, reference)) if a != b) + write(groups, bound, reference) + bad = subprocess.run(cmd, capture_output=True, text=True) + if bad.returncode != 1 or f"word={word} expected={reference[word]:08x}" not in bad.stderr: + raise AssertionError(f"{NAME}: reference '{label}' escaped detection\n{bad.stderr}") + write(groups, bound, expected) + # Each modifier occurrence in the HLSL, dropped alone or exchanged for the other modifier, must fail. + mutations = [] + for old, labels in ((ABS, (("abs dropped", "& 0xffffffffu)"),)), + (NEG, (("neg dropped", " ^ 0x00000000u)"), ("neg as abs", " & 0x7fffffffu)")))): + starts = [m.start() for m in re.finditer(re.escape(old), source)] + assert len(starts) == 4, (old, len(starts)) + for n, start in enumerate(starts): + for label, new in labels: + mutations.append((f"{label} at occurrence {n}", source[:start] + new + source[start + len(old):])) + for label, mutated in mutations: + bad_src, bad_cso = directory / "mutated.hlsl", directory / "mutated.cso" + bad_src.write_text(mutated, encoding="ascii") + subprocess.run([compiler, "-T", "cs_6_0", "-E", "main", "-Fo", bad_cso, bad_src], check=True) + bad = subprocess.run([*cmd[:3], bad_cso, case], capture_output=True, text=True) + if bad.returncode != 1 or "Compute readback differs" not in bad.stderr: + raise AssertionError(f"{NAME}: mutation '{label}' escaped detection\n{bad.stderr}") + print(f"{NAME}: {len(base.READ_RUNS)} dispatches, {len(wrong)} wrong references and " + f"{len(mutations)} mutated sources checked") + return 0 + + +if __name__ == "__main__": + mode, *args = sys.argv[1:] + controls() + if mode == "controls": + sys.exit(0) + if mode not in ("draw", "binary") or len(args) != 3: + sys.exit("usage: compute_alu_negabs_check.py controls | draw " + " | binary ") + with tempfile.TemporaryDirectory() as tmp: + sys.exit((draw if mode == "draw" else binary)(Path(tmp), *args)) diff --git a/tools/compute_store_aot.py b/tools/compute_store_aot.py index 037267560..eb22a3faf 100644 --- a/tools/compute_store_aot.py +++ b/tools/compute_store_aot.py @@ -368,6 +368,29 @@ def float_word(token, scalar, vector, pending, sizes=None): return word +def float_e64_source(token, scalar, vector, pending): + """The HLSL word of a VOP3 binary32 source after its source modifiers, or None for an unknown word. + + LLVM prints the VOP3 source modifiers on a register as -v, |v| and -|v|. They act on the sign bit of the word: + abs clears bit 31, then neg flips it, as pixel_aot does for v_cvt_f64_f32_e64 and binary64 compare sources, so a + zero or NaN keeps its other bits. Modifiers on a constant (neg(0x...), |1.0|) and the abs() spelling are refused. + """ + m = re.fullmatch(r"(-?)(\|?)(s\d+|v\d+)(\|?)", token) + if not m and not re.fullmatch(FLOAT_SOURCE, token): + raise ValueError(f"Unsupported float source modifier: {token}") + if m and m[2] != m[4]: + raise ValueError(f"Unsupported float source modifier: {token}") + word = float_word(m[3] if m else token, scalar, vector, pending) + if word is None: + return None + expression = hlsl_word(word) + if m and m[2]: + expression = f"({expression} & 0x7fffffffu)" + if m and m[1]: + expression = f"({expression} ^ 0x80000000u)" + return expression + + def vector_operands(line): """VGPR numbers named by an instruction, single or as a range.""" regs = set() @@ -2104,6 +2127,21 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N if dst > 255: raise ValueError("Invalid vector destination") vector[dst] = ("alu", f"(inputData.Load({partial[1]}) & 0xffffu)") + elif ((m := re.fullmatch(r"(v_(?:add|sub|subrev|mul)_f32)_e64 v(\d+), ([^,\s]+), ([^,\s]+)( .+)?", line)) + and any(token.startswith(("-", "|", "neg(", "abs(")) and not re.fullmatch(FLOAT_SOURCE, token) + for token in m.groups()[2:4])): + # The VOP3 spelling with a source modifier on at least one source; either source is any binary32 source. + # The unmodified _e64 form is left to the fall-through. clamp and omod (mul:2, mul:4, div:2) are refused. + op, dst = m[1] + "_e32", int(m[2]) + if m[5]: + raise ValueError(f"Unsupported float output modifier: {line}") + sources = [float_e64_source(token, scalar, vector, pending) for token in m.groups()[2:4]] + if dst > 255 or None in sources: + raise ValueError("Unverified float operand") + expression = FALU[op].format(*sources) + if len(expression) > ALU_EXPRESSION_LIMIT: + raise ValueError("ALU expression too large") + vector[dst] = ("alu", expression) elif m := re.fullmatch(rf"(v_(?:add|sub|subrev|mul)_f32_e32) v(\d+), {FLOAT_SOURCE}, (v\d+)", line): op, dst = m[1], int(m[2]) words = [float_word(token, scalar, vector, pending, sizes) for token in m.groups()[2:]] From e76f8acd5a269bfec48ea65203f2b7868fb14df3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?As=C4=B1m=20Mirza=20=C3=87iftler?= <113895866+Asimmimx@users.noreply.github.com> Date: Thu, 26 Nov 2026 05:20:18 +0300 Subject: [PATCH 071/240] startup: draw the gfx2hlsl binary32 rounding operations (#1741) The VEC_F table lowers v_floor_f32, v_ceil_f32, v_trunc_f32, v_fract_f32 and v_rndne_f32 to HLSL floor, ceil, trunc, frac and round, and no check ran any of them. tests/startup_gfx2hlsl_float_round_check.py draws them with the shared per-lane runner (byte-identical copy of tests/startup_gfx2hlsl_lane_alu.py) against references written from the RDNA 2 ISA: signed zero results, round half to even, and fract capped at 0x3f7fffff, on exact halves and quarters, 1000000.5, the binary32 just below 0.5, 8388607.5 and -2^-30. Each operation has a mutated lowering whose first draw must read its own words. All 20 draws match on WARP and an RX 6600 through FXC ps_5_1 and DXC ps_6_0, the 10 mutated draws read their mutated words, and frac(-2^-30) reads 0x3f7fffff on both adapters. Co-authored-by: tedin7 --- .github/workflows/windows.yml | 2 + CMakeLists.txt | 10 +++ docs/experiments.md | 14 ++++ tests/startup_gfx2hlsl_float_round_check.py | 81 +++++++++++++++++++++ 4 files changed, 107 insertions(+) create mode 100644 tests/startup_gfx2hlsl_float_round_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 94e853cb0..6ca992861 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -115,6 +115,7 @@ jobs: (["tests/startup_image_3d_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_int3_alu_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_image_load_mip_check.py", "--llvm-mc", "llvm-mc-15"], {}), + (["tests/startup_gfx2hlsl_float_round_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_image_2d_array_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_image_sample_a16_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_image_sample_a16_check.py", "decode", "libLLVM-15.so.1"], {}), @@ -247,6 +248,7 @@ jobs: tests/startup_image_3d_check.py \ tests/startup_image_load_mip_check.py \ tests/startup_gfx2hlsl_operand_count_check.py \ + tests/startup_gfx2hlsl_float_round_check.py \ tests/startup_gfx2hlsl_scalar_arity_check.py \ tests/startup_gfx2hlsl_scalar_table_arity_check.py \ tests/startup_image_2d_array_check.py \ diff --git a/CMakeLists.txt b/CMakeLists.txt index c859228bd..1d3ee56d1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3329,6 +3329,16 @@ if(EXISTS "${INTAKE_PYTHON}") # gfx2hlsl refuses a binary32 or integer vector operation with a source too few or too many. add_test(NAME startup_gfx2hlsl_operand_count COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_operand_count_check.py") + # gfx2hlsl binary32 rounding (VEC_F floor, ceil, trunc, fract, rndne): translation controls, then a draw of + # the translated pairs with reference words and one mutated lowering per operation. + add_test(NAME startup_gfx2hlsl_float_round_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_float_round_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_float_round_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_float_round_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_float_round_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl refuses a scalar ALU operation whose operand list is too short. add_test(NAME startup_gfx2hlsl_scalar_arity COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_scalar_arity_check.py") diff --git a/docs/experiments.md b/docs/experiments.md index 2d58d0f0b..6cb1d1459 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14951,6 +14951,20 @@ The startup pixel stage lowers constant-lane SGPR spills (#2125 item E): `v_writ The binary32 table (`VEC_F`) applies the same operand-count rule. Before this change, a form one source short (`v_add_f32 v1, v2`) raised `IndexError` in `Stage.one` instead of `Unsupported`. A form with one source too many (`v_med3_f32 v1, v2, v3, v4, v5`) translated with the extra source dropped. `tests/startup_gfx2hlsl_operand_count_check.py` (`startup_gfx2hlsl_operand_count`) checks every operation of both tables: one source fewer and one source more are refused, and the exact count translates. It also checks that the constant and accumulator forms (`v_fmac_f32`, `v_mac_f32`, `v_fmamk_f32`, `v_fmaak_f32`, `v_madmk_f32`, `v_madak_f32`) keep translating with their usual operands. As a control, it loads the translator with the new `VEC_F` guard removed and requires both old failures to come back. +## Startup translator: binary32 rounding + +No check ran the rounding operations of the `VEC_F` table in `tools/startup/gfx2hlsl.py` before: `v_floor_f32`, `v_ceil_f32`, `v_trunc_f32`, `v_fract_f32` and `v_rndne_f32`. They lower to HLSL `floor`, `ceil`, `trunc`, `frac` and `round`. `tests/startup_gfx2hlsl_float_round_check.py` draws them with the shared runner `tests/startup_gfx2hlsl_lane_alu.py`, one operation per lane on flat inputs, alternating the `_e32` and `_e64` spellings, and compares the four result words exactly. + +The references follow the AMD RDNA 2 ISA reference: +- A zero result keeps the sign of the source: `ceil(-0.75)`, `trunc(-0.75)` and `rndne(-2^-30)` are -0. +- `v_rndne_f32` rounds halves to even: 2.5 → 2, 3.5 → 4, -2.5 → -2, 1000000.5 → 1000000. +- `v_fract_f32` is `x - floor(x)`, capped at the largest binary32 below 1.0. With -2^-30 the exact difference rounds to 1.0, and the instruction gives `0x3f7fffff`. + +The inputs also include the binary32 just below 0.5 and 8388607.5. + +Each operation has a wrong lowering whose first draw must read its own mutated words: floor and ceil exchanged, floor for trunc, `x - trunc(x)` for frac, and trunc for round. + +On WARP 10.0.26100.9818 and on an AMD Radeon RX 6600 (driver 32.0.21045.29003), all 20 draws matched through FXC `ps_5_1` and DXC `ps_6_0`, and all 10 mutated draws read their mutated words. On both adapters, HLSL `frac` of -2^-30 read `0x3f7fffff`, so the lowering kept the cap on these two adapters without an explicit comparison. Tests: `startup_gfx2hlsl_float_round_controls`, `startup_gfx2hlsl_float_round_warp` and `startup_gfx2hlsl_float_round_hardware`. ## Startup translator: v_swap_b32 `tools/startup/gfx2hlsl.py` now lowers `v_swap_b32` (VOP1, opcode 101), which it used to refuse. Both VGPRs exchange their old values, so the lowering reads the destination into a temporary before either register is written: `{ uint t = v1; v1 = v2; v2 = t; }`. The RDNA 2 ISA allows no input or output modifier on it, and LLVM 15 assembles only the 32-bit VOP1 spelling for gfx1013 (the `_e64`, `_dpp` and `_sdwa` forms and a scalar, constant, negated or 64-bit operand are rejected), so the translator refuses all of those and a modifier. A register-to-itself swap assembles and keeps its value. A proven-uniform register keeps that proof across the swap only while the exec mask is known. diff --git a/tests/startup_gfx2hlsl_float_round_check.py b/tests/startup_gfx2hlsl_float_round_check.py new file mode 100644 index 000000000..6ca36fb9b --- /dev/null +++ b/tests/startup_gfx2hlsl_float_round_check.py @@ -0,0 +1,81 @@ +"""Binary32 rounding operations of tools/startup/gfx2hlsl.py (its VEC_F table). + + (no arguments) translation controls, pure Python + binary reassemble the pixel bodies and compare them with the recorded words + draw [fxc] + draw one pixel per four input sets and compare the four result words + +Covers v_floor_f32, v_ceil_f32, v_trunc_f32, v_fract_f32 and v_rndne_f32, which no check ran before. The fixture and +runner are startup_gfx2hlsl_lane_alu.py: one operation per lane, alternating the e32 and e64 spellings, on flat +parameters the compilers cannot fold. The references follow the AMD RDNA 2 ISA reference: a zero result keeps the sign +of the source (ceil(-0.75) and trunc(-0.75) are -0), v_rndne_f32 rounds halves to even, and v_fract_f32 is +x - floor(x) capped at the largest binary32 below 1.0 (0x3f7fffff), so a tiny negative source does not give 1.0. +The inputs are exact halves and quarters, 1000000.5, the binary32 just below 0.5, 8388607.5 and -2^-30. +""" +import math +import struct +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from startup_gfx2hlsl_lane_alu import main, words # noqa: E402 + + +def f(value): + return struct.unpack(' Date: Thu, 26 Nov 2026 02:22:23 +0000 Subject: [PATCH 072/240] test: allow s_mul_hi_* own-arity templates in scalar table check #2405 added s_mul_hi_i32 (and an early arity refuse for both mul_hi forms). The negative control still expected only one non-IndexError survivor. Co-authored-by: SimSalabimse --- ...startup_gfx2hlsl_scalar_table_arity_check.py | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/tests/startup_gfx2hlsl_scalar_table_arity_check.py b/tests/startup_gfx2hlsl_scalar_table_arity_check.py index 7a2d86ebc..f33cff0f5 100644 --- a/tests/startup_gfx2hlsl_scalar_table_arity_check.py +++ b/tests/startup_gfx2hlsl_scalar_table_arity_check.py @@ -16,6 +16,9 @@ HERE = Path(__file__).resolve().parent SOURCE = HERE.parent / 'tools' / 'startup' / 'gfx2hlsl.py' +# Templates that refuse a short form in their own body (before the shared SCA arity guard). +OWN_ARITY = frozenset(('s_bfm_b32', 's_mul_hi_u32', 's_mul_hi_i32')) + def load(text=None): spec = importlib.util.spec_from_loader('gfx2hlsl_table', loader=None) @@ -91,17 +94,19 @@ def refusal(module, op, sources): changed.append(op) check('a complete form is never refused for its operand count', not changed, repr(changed[:4])) -# Negative control: with the guard removed the short form raises IndexError again. One template keeps its own -# arity check (s_bfm_b32 spells "expected 3" in its body), so it refuses either way and is excluded here rather -# than counted as a survivor. +# Negative control: with the guard removed the short form raises IndexError again. Templates that keep +# their own arity check refuse either way and are excluded here rather than counted as survivors. stripped = load(SOURCE.read_text(encoding='utf-8').replace(' if len(srcs) < needed:', ' if False:')) control = [op for op in TWO_SOURCE if refusal(stripped, op, needed_sources(stripped, op) - 1) == 'IndexError'] -check('control: without the guard the short form raises IndexError', len(control) >= len(TWO_SOURCE) - 1, +check('control: without the guard the short form raises IndexError', + len(control) >= len(TWO_SOURCE) - len(OWN_ARITY), '%d of %d' % (len(control), len(TWO_SOURCE))) kept = [op for op in TWO_SOURCE if op not in control] -check('the one template with its own arity check still refuses without the guard', - all(refusal(stripped, op, needed_sources(stripped, op) - 1).startswith(op) for op in kept), repr(kept)) +check('templates with their own arity check still refuse without the guard', + set(kept) <= OWN_ARITY and all( + refusal(stripped, op, needed_sources(stripped, op) - 1).startswith(op) for op in kept), + repr(kept)) print('scalar table arity checks: %d failed' % len(failures)) sys.exit(1 if failures else 0) From ad1ad194a642f327ecf1f3ca001aefb21270365b Mon Sep 17 00:00:00 2001 From: SimSalabimse <83839581+SimSalabimse@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:26:16 +0100 Subject: [PATCH 073/240] startup: accept sample_b and get_lod under entry EXEC after a join (#2659) * startup: accept sample_b and get_lod under entry EXEC after a join image_sample_b and image_get_lod refused any prior branch target even when EXEC was still the entry mask (M200-01 B/L: outside straight-line with every lane active). Drop the blocks gate; keep the pixel + exec_known proof. Fixtures: uniform join before the op accepted; divergent EXEC refused; WARP draw of join-before sample_b bias -1. Refs #2618 Co-authored-by: SimSalabimse * startup: require wave-uniform CF for sample_b and get_lod Review on #2659: dropping only the blocks gate accepted vcc/exec branches before SampleBias / CalculateLevelOfDetail. Track uniform_cf (cleared by divergent s_cbranch_*), keep scc-uniform joins, and refuse vccz/vccnz/execz/execnz before the op in both fixtures. Refs #2618 Co-authored-by: SimSalabimse * startup: refuse sample_b and get_lod inside a loop with a divergent back edge A divergent backward branch after the read still lets lanes of one quad leave the loop at different passes, so the read runs again with uneven quads although no divergent branch precedes it in program order. Record the read sites and the divergent back edges and refuse a read that one of them spans. Tests: synthetic words with s_cbranch_vccnz/execnz right after the read, back to it (fail before, pass after). * test: allow s_mul_hi_* own-arity templates in scalar table check #2405 added s_mul_hi_i32 (and an early arity refuse for both mul_hi forms). The negative control still expected only one non-IndexError survivor. Co-authored-by: SimSalabimse --------- Co-authored-by: Cursor Agent Co-authored-by: SimSalabimse Co-authored-by: tedin7 --- docs/experiments.md | 4 +- tests/startup_gfx2hlsl_image_get_lod_check.py | 51 ++++++++--- ...artup_gfx2hlsl_scalar_table_arity_check.py | 17 ++-- tests/startup_image_sample_b_check.py | 87 +++++++++++++++++-- tools/startup/gfx2hlsl.py | 37 ++++++-- 5 files changed, 165 insertions(+), 31 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 6cb1d1459..0822a4387 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14526,9 +14526,9 @@ For binary32 arithmetic and compare sources, the translator reads the inline int ## Startup translator: biased image sampling -`tools/startup/gfx2hlsl.py` lowers the gfx1013 `image_sample_b` form in a pixel stage to `tex.SampleBias(smp, uv, bias)` for 2D, 2D-array and 3D textures. The RDNA 2 ISA (section 8.2.4, Table 43: "_B LOD BIAS, 1: lod bias, Add this BIAS to the LOD computed"; section 8.2.5: the address is `{ offset } { bias } { z-compare } { derivative } { body }` and the bias is "One Dword float") puts the bias in the FIRST address register, so `v[0:2]` is bias, u, v and the NSA list `[v3, v1, v2]` takes the bias from `v3`. LLVM 15 agrees: `IntrinsicsAMDGPU.td` gives `AMDGPUSample_b` the extra argument `llvm_anyfloat_ty "bias"` and `MIMGInstructions.td` the gfx10 opcode `0x25`. `llvm-mc` (LLVM 15, gfx1013) assembles the contiguous 2D, 2D-array, 3D and NSA forms, and the check compares every fixture against it. HLSL `SampleBias` adds the bias to the implicit mip level and documents the range -16.0 to 15.99; the ISA text states no hardware clamp, so a bias outside that range is an unverified difference. The form is refused outside a pixel stage, after the exec mask was modified and after a branch (there the plain sample is lowered to level 0, which would drop the bias), and so are `image_sample_b_cl`, `image_sample_c_b*`, `image_sample_b_o`, `image_gather4_b`, 1D, cube and multisample dimensions, an empty `dmask`, the `unorm`, `r128`, `tfe`, `lwe`, `a16` and `d16` modifiers, set reserved MIMG bits, and a constant sampler whose LOD bias fields (word 2 bits 19:0, s6.8 and s2.4, scaled by `T#.perf_modulation` in the ISA) are not zero or whose mip filter is 0 (mipmapping disabled), or whose MIN_LOD is above its MAX_LOD. The guest clamp is kept: MIN_LOD (word 1 bits 11:0) and MAX_LOD (bits 23:12) are unsigned 4.8 fixed point (Mesa 24.0.0 `src/amd/registers/gfx10-rsrc.json`, `SQ_IMG_SAMP_WORD1`; `radeonsi/si_state.c` lines 5169-5170 encode them with `S_FIXED(x, 8)`), and the sampler of an `image_sample_b` is written as an `smpl` manifest line that the runtime decodes to `MinLOD = MIN_LOD / 256` and `MaxLOD = MAX_LOD / 256` (`src/startup_stubs/translated_sampler_bindings.h`); `smp` and `smpc` lines still leave MinLOD at 0 and MaxLOD unbounded (the next section moves `image_sample`, `_l` and `_lz` with a constant sampler to `smpl`). A sampler read from the sampler heap, including the default-sampler shortcut for a run-time heap load, or built from a register is refused for `image_sample_b`, because its LOD limits and bias cannot be shown to be irrelevant. +`tools/startup/gfx2hlsl.py` lowers the gfx1013 `image_sample_b` form in a pixel stage to `tex.SampleBias(smp, uv, bias)` for 2D, 2D-array and 3D textures. The RDNA 2 ISA (section 8.2.4, Table 43: "_B LOD BIAS, 1: lod bias, Add this BIAS to the LOD computed"; section 8.2.5: the address is `{ offset } { bias } { z-compare } { derivative } { body }` and the bias is "One Dword float") puts the bias in the FIRST address register, so `v[0:2]` is bias, u, v and the NSA list `[v3, v1, v2]` takes the bias from `v3`. LLVM 15 agrees: `IntrinsicsAMDGPU.td` gives `AMDGPUSample_b` the extra argument `llvm_anyfloat_ty "bias"` and `MIMGInstructions.td` the gfx10 opcode `0x25`. `llvm-mc` (LLVM 15, gfx1013) assembles the contiguous 2D, 2D-array, 3D and NSA forms, and the check compares every fixture against it. HLSL `SampleBias` adds the bias to the implicit mip level and documents the range -16.0 to 15.99; the ISA text states no hardware clamp, so a bias outside that range is an unverified difference. The form needs a pixel stage whose EXEC is still the entry mask with wave-uniform control flow (implicit derivatives); a uniform (scc) join or later loop does not drop that proof, while divergent EXEC or a vcc/exec-conditioned branch before the sample does (there the plain sample is lowered to level 0, which would drop the bias). It is also refused outside a pixel stage, and so are `image_sample_b_cl`, `image_sample_c_b*`, `image_sample_b_o`, `image_gather4_b`, 1D, cube and multisample dimensions, an empty `dmask`, the `unorm`, `r128`, `tfe`, `lwe`, `a16` and `d16` modifiers, set reserved MIMG bits, and a constant sampler whose LOD bias fields (word 2 bits 19:0, s6.8 and s2.4, scaled by `T#.perf_modulation` in the ISA) are not zero or whose mip filter is 0 (mipmapping disabled), or whose MIN_LOD is above its MAX_LOD. The guest clamp is kept: MIN_LOD (word 1 bits 11:0) and MAX_LOD (bits 23:12) are unsigned 4.8 fixed point (Mesa 24.0.0 `src/amd/registers/gfx10-rsrc.json`, `SQ_IMG_SAMP_WORD1`; `radeonsi/si_state.c` lines 5169-5170 encode them with `S_FIXED(x, 8)`), and the sampler of an `image_sample_b` is written as an `smpl` manifest line that the runtime decodes to `MinLOD = MIN_LOD / 256` and `MaxLOD = MAX_LOD / 256` (`src/startup_stubs/translated_sampler_bindings.h`); `smp` and `smpc` lines still leave MinLOD at 0 and MaxLOD unbounded (the next section moves `image_sample`, `_l` and `_lz` with a constant sampler to `smpl`). A sampler read from the sampler heap, including the default-sampler shortcut for a run-time heap load, or built from a register is refused for `image_sample_b`, because its LOD limits and bias cannot be shown to be irrelevant. -`tests/startup_image_sample_b_check.py` translates source-built fixtures and, with `draw`, draws the 2D array through `offscreen_check --startup-image-2d-array-mips` (4x4, two slices, three mips whose cells all differ, point sampler with mip filter point; MAX_LOD 2 for the bias cases). Constant coordinates have no derivatives, so the draw rewrites only the `u` initialiser of the translated HLSL to `0.75 + 0.5 * (SV_Position.x - 0.5)`, an implicit LOD of 1 at the sampled pixel; the `SampleBias` call is untouched. Bias -1, 0 and +1 read mip 0, 1 and 2 on WARP with DXC and FXC. Negative controls: the same program with `image_sample` reads mip 1 for every case, and edited calls (bias replaced by 0, bias negated, bias and `u` exchanged, `Sample` for `SampleBias`) each read another cell. The sampler limits are discriminated by cases whose limit lies below a mip that exists: MAX_LOD 1 with bias +1 stays on mip 1 (unclamped: mip 2), MAX_LOD 0 with bias +1 stays on mip 0, MIN_LOD 2 with bias -1 reads mip 2 (unclamped: mip 0) and MIN_LOD 1 = MAX_LOD 1 with bias -1 reads mip 1; the MAX_LOD 2 bias cases cannot tell, because mip 2 is the last level. Each limit case is drawn again with an `smp` line instead of `smpl` (limits not carried) and must read the unclamped mip. `startup_sampler_comparison` checks the decoded MinLOD and MaxLOD. Replacing the bias by 0 or exchanging the bias with the first coordinate in `gfx2hlsl.py`, dropping the MaxLOD assignment in the runtime decoder, accepting a heap sampler, and the previous `gfx2hlsl.py`, each make a check fail. Not covered: a physical-adapter run (`startup_image_sample_b_hardware` is registered), a plain 2D or 3D draw (those forms are checked on the generated HLSL), fractional bias with a linear mip filter, bias outside -16 to 15.99, a fractional MIN_LOD or MAX_LOD (only whole mips are drawn; the 4.8 decode is checked without a device), a non-zero descriptor LOD bias (refused, not carried) and the limits of the other sample forms (see the next section). +`tests/startup_image_sample_b_check.py` translates source-built fixtures and, with `draw`, draws the 2D array through `offscreen_check --startup-image-2d-array-mips` (4x4, two slices, three mips whose cells all differ, point sampler with mip filter point; MAX_LOD 2 for the bias cases). Constant coordinates have no derivatives, so the draw rewrites only the `u` initialiser of the translated HLSL to `0.75 + 0.5 * (SV_Position.x - 0.5)`, an implicit LOD of 1 at the sampled pixel; the `SampleBias` call is untouched. Bias -1, 0 and +1 read mip 0, 1 and 2 on WARP with DXC and FXC. A uniform (scc) join before the sample is accepted and drawn (same mip as the plain bias -1 case); divergent EXEC or a vcc/exec-conditioned branch before the sample is refused. Negative controls: the same program with `image_sample` reads mip 1 for every case, and edited calls (bias replaced by 0, bias negated, bias and `u` exchanged, `Sample` for `SampleBias`) each read another cell. The sampler limits are discriminated by cases whose limit lies below a mip that exists: MAX_LOD 1 with bias +1 stays on mip 1 (unclamped: mip 2), MAX_LOD 0 with bias +1 stays on mip 0, MIN_LOD 2 with bias -1 reads mip 2 (unclamped: mip 0) and MIN_LOD 1 = MAX_LOD 1 with bias -1 reads mip 1; the MAX_LOD 2 bias cases cannot tell, because mip 2 is the last level. Each limit case is drawn again with an `smp` line instead of `smpl` (limits not carried) and must read the unclamped mip. `startup_sampler_comparison` checks the decoded MinLOD and MaxLOD. Replacing the bias by 0 or exchanging the bias with the first coordinate in `gfx2hlsl.py`, dropping the MaxLOD assignment in the runtime decoder, accepting a heap sampler, and the previous `gfx2hlsl.py`, each make a check fail. Not covered: a physical-adapter run (`startup_image_sample_b_hardware` is registered), a plain 2D or 3D draw (those forms are checked on the generated HLSL), fractional bias with a linear mip filter, bias outside -16 to 15.99, a fractional MIN_LOD or MAX_LOD (only whole mips are drawn; the 4.8 decode is checked without a device), a non-zero descriptor LOD bias (refused, not carried) and the limits of the other sample forms (see the next section). ```powershell cmake --build --preset dev --target offscreen_check diff --git a/tests/startup_gfx2hlsl_image_get_lod_check.py b/tests/startup_gfx2hlsl_image_get_lod_check.py index e9443d9ca..70475ee59 100644 --- a/tests/startup_gfx2hlsl_image_get_lod_check.py +++ b/tests/startup_gfx2hlsl_image_get_lod_check.py @@ -1,17 +1,20 @@ -"""image_get_lod on a 2D texture in tools/startup/gfx2hlsl.py. +"""image_get_lod on a 2D texture in tools/startup/gfx2hlsl.py (M200-01 L). image_get_lod returns [0] the LOD a sample would use, clamped, and [1] the computed LOD before the clamp (Mesa nir_texop_lod, emitted by ACO as image_get_lod; GLSL textureQueryLod x/y). It is lowered to HLSL CalculateLevelOfDetail / CalculateLevelOfDetailUnclamped, which take implicit derivatives like Sample, so the stage -must be a pixel stage, straight-line, with every lane active. The clamped value depends on the sampler's LOD limits -and bias, so the sampler must be a constant descriptor under the validation of image_sample_b. +must be a pixel stage whose EXEC is still the entry mask (every lane active) with wave-uniform control flow. A +uniform (scc) join or later loop does not drop that proof; divergent EXEC or a vcc/exec-conditioned branch before +the read does. The clamped value depends on the sampler's LOD limits and bias, so the sampler must be a constant +descriptor under the validation of image_sample_b. Fixture (synthetic): the recorded c_lz stage of startup_image_sample_c_check with the MIMG opcode set to 0x60 (image_get_lod; the decoder reads it back with a 2-register address), sampler word 2 loaded from a literal (mip filter point), and for the second form dmask 0x3. -Checks: dmask 0x1, 0x2 and 0x3 lower to the two calls on the sampler, which carries its LOD limits. Controls (refused): -dmask 0x4, a 2D array, a branch before the read, a sampler LOD bias, a sampler with mipmapping disabled, and the -stage without op_image_get_lod (negative control: refused as on main). +Checks: dmask 0x1, 0x2 and 0x3 lower to the two calls on the sampler, which carries its LOD limits. A uniform join +before the read is accepted. Controls (refused): dmask 0x4, a 2D array, divergent EXEC, s_cbranch_vccz/execz before +the read, a sampler LOD bias, a sampler with mipmapping disabled, and the stage without op_image_get_lod +(negative control: refused as on main). draw [fxc]: also compile the dmask 0x3 stage with dxc ps_6_0 (and fxc ps_5_1). """ import struct @@ -34,7 +37,11 @@ MIP_POINT = 1 << 26 # SQ_IMG_SAMP_WORD2 bits 27:26 MIP_FILTER -def stage(dmask=1, dim=1, branch=False, word2=MIP_POINT): +def sopp(op, simm): + return struct.pack(' right after the read, back to it (a divergent back edge spanning the read) + code = code[:AT + 8] + sopp(back_op, -3) + code[AT + 8:] + insert = b'' + if branch: # s_cbranch_scc0 to the next instruction: uniform control flow before the read + insert += sopp(4, 0) + if join: # uniform forward join; every lane still has the entry EXEC at the read + insert += (bytes.fromhex('800380be') + bytes.fromhex('008006bf') + sopp(5, 1) + bytes.fromhex('810381be')) + if divergent: # s_mov_b32 exec_lo, 0: the entry-mask proof is gone + insert += bytes.fromhex('8003febe') + if cf_op is not None: # s_mov; s_cbranch_ +1; s_mov (vcc/exec: divergent CF) + insert += bytes.fromhex('800380be') + sopp(cf_op, 1) + bytes.fromhex('810381be') + if insert: + code = code[:AT] + insert + code[AT:] return code @@ -74,9 +92,17 @@ def controls(): assert call in text and 'v4 = U(t.x);' in text and 'v5 = U(t.y);' in text, text _, text = ps(stage(dmask=2)) # the unclamped LOD alone lands in the first destination register assert call in text and 'v4 = U(t.y);' in text and 'U(t.x)' not in text, text + _, text = ps(stage(branch=True)) + assert call in text and 'v4 = U(t.x);' in text, text + _, text = ps(stage(join=True)) + assert call in text and 'v4 = U(t.x);' in text, text refused(stage(dmask=4), 'image_get_lod form') refused(stage(dim=5), 'image_get_lod form') # SQ_RSRC_IMG_2D_ARRAY - refused(stage(branch=True), 'image_get_lod needs implicit derivatives') + refused(stage(divergent=True), 'image_get_lod needs implicit derivatives') + for op in (7, 9): # vccnz, execnz back edge after the read + refused(stage(back_op=op), 'image_get_lod needs implicit derivatives') + for op in (6, 7, 8, 9): # vccz, vccnz, execz, execnz + refused(stage(cf_op=op), 'image_get_lod needs implicit derivatives') refused(stage(word2=MIP_POINT | 1), 'image_get_lod with a sampler LOD bias') refused(stage(word2=0), 'image_get_lod with mipmapping disabled') saved = G.Stage.op_image_get_lod @@ -85,8 +111,9 @@ def controls(): refused(stage(), 'image_get_lod') finally: G.Stage.op_image_get_lod = saved - print('image_get_lod: CalculateLevelOfDetail / Unclamped for dmask 0x1, 0x2 and 0x3; dmask 0x4, a 2D array, a branch, ' - 'a sampler bias and a sampler without mipmapping refused; refused without the handler') + print('image_get_lod: CalculateLevelOfDetail / Unclamped for dmask 0x1, 0x2 and 0x3; uniform join/branch before ' + 'the read accepted; dmask 0x4, a 2D array, divergent EXEC, vcc/exec branches, a sampler bias and a ' + 'sampler without mipmapping refused; refused without the handler') return pipe diff --git a/tests/startup_gfx2hlsl_scalar_table_arity_check.py b/tests/startup_gfx2hlsl_scalar_table_arity_check.py index 7a2d86ebc..f33cff0f5 100644 --- a/tests/startup_gfx2hlsl_scalar_table_arity_check.py +++ b/tests/startup_gfx2hlsl_scalar_table_arity_check.py @@ -16,6 +16,9 @@ HERE = Path(__file__).resolve().parent SOURCE = HERE.parent / 'tools' / 'startup' / 'gfx2hlsl.py' +# Templates that refuse a short form in their own body (before the shared SCA arity guard). +OWN_ARITY = frozenset(('s_bfm_b32', 's_mul_hi_u32', 's_mul_hi_i32')) + def load(text=None): spec = importlib.util.spec_from_loader('gfx2hlsl_table', loader=None) @@ -91,17 +94,19 @@ def refusal(module, op, sources): changed.append(op) check('a complete form is never refused for its operand count', not changed, repr(changed[:4])) -# Negative control: with the guard removed the short form raises IndexError again. One template keeps its own -# arity check (s_bfm_b32 spells "expected 3" in its body), so it refuses either way and is excluded here rather -# than counted as a survivor. +# Negative control: with the guard removed the short form raises IndexError again. Templates that keep +# their own arity check refuse either way and are excluded here rather than counted as survivors. stripped = load(SOURCE.read_text(encoding='utf-8').replace(' if len(srcs) < needed:', ' if False:')) control = [op for op in TWO_SOURCE if refusal(stripped, op, needed_sources(stripped, op) - 1) == 'IndexError'] -check('control: without the guard the short form raises IndexError', len(control) >= len(TWO_SOURCE) - 1, +check('control: without the guard the short form raises IndexError', + len(control) >= len(TWO_SOURCE) - len(OWN_ARITY), '%d of %d' % (len(control), len(TWO_SOURCE))) kept = [op for op in TWO_SOURCE if op not in control] -check('the one template with its own arity check still refuses without the guard', - all(refusal(stripped, op, needed_sources(stripped, op) - 1).startswith(op) for op in kept), repr(kept)) +check('templates with their own arity check still refuse without the guard', + set(kept) <= OWN_ARITY and all( + refusal(stripped, op, needed_sources(stripped, op) - 1).startswith(op) for op in kept), + repr(kept)) print('scalar table arity checks: %d failed' % len(failures)) sys.exit(1 if failures else 0) diff --git a/tests/startup_image_sample_b_check.py b/tests/startup_image_sample_b_check.py index f72cc4242..356010aa7 100644 --- a/tests/startup_image_sample_b_check.py +++ b/tests/startup_image_sample_b_check.py @@ -1,4 +1,4 @@ -"""Biased implicit-LOD image_sample_b in tools/startup/gfx2hlsl.py (pixel stage only). +"""Biased implicit-LOD image_sample_b in tools/startup/gfx2hlsl.py (pixel stage only; M200-01 B). (no arguments) translation controls, pure Python binary reassemble every fixture source and compare it with the recorded words @@ -12,7 +12,9 @@ IntrinsicsAMDGPU.td lists the extra argument of AMDGPUSample_b as llvm_anyfloat_ty "bias" and MIMGInstructions.td gives IMAGE_SAMPLE_B the gfx10 opcode 0x25. HLSL Texture.SampleBias(sampler, location, bias) adds the bias to the implicit mip level, so the lowering is tex.SampleBias(smp, uv, bias). D3D documents the bias range as -16.0 to 15.99; -the ISA text states no hardware clamp, so values outside that range are an unverified difference. +the ISA text states no hardware clamp, so values outside that range are an unverified difference. Accepted under the +entry EXEC mask and wave-uniform control flow even after a uniform (scc) join or later loop; divergent EXEC or a +vcc/exec-conditioned branch before the sample stays refused. Each fixture is a source-built gfx1013 pixel stage: v0 = bias, v1 = u = 0.75, v2 = v = 0.25 and v3 = the slice (root constant 1, s9). Constant coordinates have no derivatives (the implicit LOD would be log2(0) and the bias is lost), so @@ -386,9 +388,10 @@ def texel_cell(mip, slice_index): def check_guards(): """The stage guard and the address-count guard are decided before any state is read, so a bare stage reaches them.""" - def call(coords, kind='ps', exec_known=True, blocks=()): + def call(coords, kind='ps', exec_known=True, blocks=(), uniform_cf=True): bare = G.Stage.__new__(G.Stage) bare.kind, bare.exec_known, bare.blocks = kind, exec_known, list(blocks) + bare.uniform_cf = uniform_cf bare.image(['v5', coords, 's0'], ['dim:SQ_RSRC_IMG_2D', 'dmask:0x1'], 'b') for coords, count in (('[v1, v2]', 2), ('[v1, v2, v3, v4]', 4)): @@ -399,13 +402,23 @@ def call(coords, kind='ps', exec_known=True, blocks=()): else: raise AssertionError('image_sample_b accepted %d address registers' % count) for label, kwargs in (('vertex stage', {'kind': 'vs'}), ('compute stage', {'kind': 'cs'}), - ('exec modified', {'exec_known': False}), ('after a branch', {'blocks': [object()]})): + ('exec modified', {'exec_known': False}), + ('divergent CF', {'uniform_cf': False})): try: call('[v1, v2, v3]', **kwargs) except G.Unsupported as error: assert 'image_sample_b needs implicit derivatives' in str(error), (label, error) else: raise AssertionError('image_sample_b accepted: %s' % label) + # A prior join (non-empty blocks) is fine while EXEC and wave-uniform CF hold (M200-01 B). + try: + call('[v1, v2, v3]', blocks=[object()], uniform_cf=True) + except G.Unsupported as error: + raise AssertionError('image_sample_b refused with entry EXEC after a uniform join: %s' % error) + except AttributeError: + pass + else: + raise AssertionError('image_sample_b after a join returned without needing a pipeline') # The legal case gets past both guards: the bare stage then stops where it needs a pipeline. try: call('[v1, v2, v3]') @@ -413,7 +426,41 @@ def call(coords, kind='ps', exec_known=True, blocks=()): raise AssertionError('legal image_sample_b refused: %s' % error) except AttributeError: pass - print('refused: wrong address count, vertex and compute stages, modified exec, code after a branch') + else: + raise AssertionError('legal image_sample_b returned without needing a pipeline') + print('refused: wrong address count, vertex and compute stages, modified exec, divergent CF; ' + 'join with entry EXEC and uniform CF accepted') + + +def sopp(op, simm): + return struct.pack(' +1; s_mov immediately before the sample_b (review probe).""" + off = next(o for o, _s, _n, a in G.decode(data) if 'image_sample_b' in a) + insert = bytes.fromhex('800380be') + sopp(sopp_op, 1) + bytes.fromhex('810381be') + return data[:off] + insert + data[off:] + + +def with_divergent_back_edge_after_sample(data, sopp_op): + """Insert s_cbranch_ right after the sample_b, jumping back to it: the branch comes later in program order, but + the sample runs again on the next pass, with lanes that left the loop at different passes.""" + off, size = next((o, s) for o, s, _n, a in G.decode(data) if 'image_sample_b' in a) + return data[:off + size] + sopp(sopp_op, -(size // 4 + 1)) + data[off + size:] def controls(): @@ -421,6 +468,24 @@ def controls(): locate() stage('array 1').hlsl_ps() # the plain translation first: a translator without the lowering stops here check_guards() + plain = bytes.fromhex(WORDS['plain']) + join_ps = G.Pipeline(VS_WORDS, with_join_before_sample(plain), root_blob()).hlsl_ps() + assert 'SampleBias' in join_ps and bias_call(join_ps, 'float2') == (['v1', 'v2'], 'v0'), join_ps + for label, mutate in ( + ('divergent EXEC', with_divergent_exec_before_sample), + ('s_cbranch_vccz', lambda d: with_branch_before_sample(d, 6)), + ('s_cbranch_vccnz', lambda d: with_branch_before_sample(d, 7)), + ('s_cbranch_execz', lambda d: with_branch_before_sample(d, 8)), + ('s_cbranch_execnz', lambda d: with_branch_before_sample(d, 9)), + ('s_cbranch_vccnz back edge after the sample', lambda d: with_divergent_back_edge_after_sample(d, 7)), + ('s_cbranch_execnz back edge after the sample', lambda d: with_divergent_back_edge_after_sample(d, 9))): + try: + G.Pipeline(VS_WORDS, mutate(plain), root_blob()).hlsl_ps() + except G.Unsupported as error: + assert 'image_sample_b needs implicit derivatives' in str(error), (label, error) + else: + raise AssertionError('image_sample_b accepted after %s' % label) + print('uniform join before sample_b accepted; divergent EXEC and vcc/exec branches before sample_b refused') # Address order: the bias register comes first and is the third SampleBias argument. expected = { 'array 1': (['v1', 'v2', 'v3'], 'v0', 'float3', 'Texture2DArray r0'), @@ -588,6 +653,18 @@ def sampler_line(pipe): if run.returncode: raise AssertionError('%s %s slice=%d\n%s\n%s' % (kind, name, slice_index, run.stdout, run.stderr)) print('%s sample_b %s slice=%d: %s' % (kind, name, slice_index, expected), flush=True) + # M200-01 B: the same bias-1 array sample after a uniform join must still read mip 0. + join_words = with_join_before_sample(bytes.fromhex(WORDS['array -1'])) + join_pipe = G.Pipeline(VS_WORDS, join_words, root_blob()) + join_shader = compile_hlsl(compiler, kind, drawable(join_pipe.hlsl_ps()), 'ps_join_m1_%s' % kind, + ps_profile, directory) + join_line = sampler_line(join_pipe) + for slice_index in (0, 1): + expected = texel_cell(mip_for(-1), slice_index) + run = draw_once(vs, join_shader, slice_index, expected, join_line) + if run.returncode: + raise AssertionError('%s join sample_b slice=%d\n%s\n%s' % (kind, slice_index, run.stdout, run.stderr)) + print('%s sample_b join-before bias=-1 slice=%d: %s' % (kind, slice_index, expected), flush=True) # Negative control: without a bias the draw reads mip 1, so the bias -1 and bias +1 expectations must fail. line = sampler_line(stage('array nobias')) nobias = compile_hlsl(compiler, kind, drawable(translated['array nobias']), 'ps_nobias_%s' % kind, ps_profile, directory) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 7737c0333..99b56a8d9 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -2689,6 +2689,10 @@ def translate(self): self.sym = dict(init_sym) self.exec_known = init_exec_known self.wqm_exec = init_wqm_exec + # True until a wave-divergent branch: SampleBias / CalculateLevelOfDetail need uniform CF. + self.uniform_cf = True + self.derivative_sites = [] # (offset, name) of image_sample_b / image_get_lod, for the back-edge proof + self.divergent_back_edges = [] # (target, branch offset) of divergent backward branches self.masks = set(init_masks) self.join_masks = set() # marked SGPRs whose mark is not proven on every path (unjoined) last_write = {} # SGPR -> offset of its last write in program order @@ -2866,10 +2870,13 @@ def translate(self): raise Unsupported('slot 57 mesh: %s on a wave-wide condition is not covered' % name) cond_uniform = True if not cond_uniform: + # Divergent CF: later SampleBias / CalculateLevelOfDetail would see uneven quads. + self.uniform_cf = False b_target = int(parse(asm)[1][0].split('_')[1], 16) regs, affected = div_targets.get(off, (set(), set())) regs = {r for r in regs if isinstance(r, int)} if b_target <= off: + self.divergent_back_edges.append((b_target, off)) regs.update(r for r in joined.get(b_target, ()) if isinstance(r, int)) for tgt_off in affected: bad_at_target.setdefault(tgt_off, set()).update(regs) @@ -2927,6 +2934,15 @@ def translate(self): if refusals is None: raise Unsupported(reason) refusals.append((reason, self.kind)) + for at, name in self.derivative_sites: + # A divergent back edge that spans the call lets lanes of one quad leave the loop at different passes, so + # the call runs again with uneven quads even though no divergent branch precedes it in program order. + if any(target <= at <= branch for target, branch in self.divergent_back_edges): + reason = ('%s needs implicit derivatives: pixel stage with the entry EXEC mask and wave-uniform ' + 'control flow' % name) + if refusals is None: + raise Unsupported(reason) + refusals.append((reason, self.kind)) self.pinned_low16_v.update(self.low16_only_v) try: self.check_vcc_paths() @@ -5313,10 +5329,16 @@ def image(self, ops, mods, how): lod, cs = cs[-1], cs[:-1] else: # The bias is added to the LOD derived from the coordinate derivatives of the pixel quad: only a - # pixel stage that still runs with its entry mask has them. Elsewhere the plain sample is lowered - # to level 0, which would drop the bias, so the bias form is refused instead. - if self.kind != 'ps' or not self.exec_known or len(self.blocks) > 0: - raise Unsupported('image_sample_b needs implicit derivatives: pixel stage, entry mask, no branches') + # pixel stage that still runs with its entry mask and wave-uniform control flow has them. + # Elsewhere the plain sample is lowered to level 0, which would drop the bias, so the bias form is + # refused instead. A uniform join (scc with scc_uniform) or later loop does not drop the proof + # (M200-01 B/L). Divergent EXEC or a vcc/exec-conditioned branch before the sample stays refused. + if (self.kind != 'ps' or not self.exec_known or + not getattr(self, 'uniform_cf', True)): + raise Unsupported('image_sample_b needs implicit derivatives: pixel stage with the entry EXEC ' + 'mask and wave-uniform control flow') + if hasattr(self, 'derivative_sites'): + self.derivative_sites.append((self.pc, 'image_sample_b')) bias, cs = cs[0], cs[1:] if how == 'get_lod': # image_get_lod returns [0] the LOD a sample would use, clamped, and [1] the computed LOD before the clamp @@ -5328,8 +5350,11 @@ def image(self, ops, mods, how): if self.kind != 'ps' or dim != 'SQ_RSRC_IMG_2D' or not dmask or dmask & ~3 or len(cs) != 2: raise Unsupported('image_get_lod form %s %s' % (', '.join(ops), ' '.join(mods))) # Both HLSL calls take implicit derivatives, so the rule of image_sample_b applies. - if not self.exec_known or len(self.blocks) > 0: - raise Unsupported('image_get_lod needs implicit derivatives: pixel stage, entry mask, no branches') + if not self.exec_known or not getattr(self, 'uniform_cf', True): + raise Unsupported('image_get_lod needs implicit derivatives: pixel stage with the entry EXEC ' + 'mask and wave-uniform control flow') + if hasattr(self, 'derivative_sites'): + self.derivative_sites.append((self.pc, 'image_get_lod')) desc_key = self.descriptor(ops[2]) tex = self.pipe.resource(desc_key, kinds[dim]) if how in ('load', 'load_mip'): From 8ad488afc80b61794426f01de3895dbb0791b756 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?As=C4=B1m=20Mirza=20=C3=87iftler?= <113895866+Asimmimx@users.noreply.github.com> Date: Thu, 26 Nov 2026 05:27:30 +0300 Subject: [PATCH 074/240] startup: draw the gfx2hlsl two-source integer vector operations (#1703) * startup: draw the gfx2hlsl two-source integer vector operations The VEC_U table lowers v_add_nc_u32, v_sub_nc_u32, v_subrev_nc_u32, v_mul_lo_u32, v_and_b32, v_or_b32, v_xor_b32, v_not_b32, v_lshlrev_b32, v_lshrrev_b32, v_ashrrev_i32, v_min/max_u32, v_min/max_i32 and v_mul_u32_u24 to single HLSL expressions; no check ran any of them. tests/startup_gfx2hlsl_lane_alu.py turns the pixel fixture of startup_gfx2hlsl_bit_alu_check.py into a runner for table families: one operation per lane on flat inputs, alternating _e32 and _e64, exact result words, recorded llvm-mc bodies with a binary mode, controls for modifiers and operand counts, and one mutated lowering per operation whose draw must read its own mutated words. tests/startup_gfx2hlsl_int_alu_check.py is the first family. Its references follow the RDNA 2 ISA (wrapping arithmetic, rev shifts by S0[4:0], arithmetic shift, signed/unsigned order, 24-bit products) over inputs with shift counts above 31, sign-bit values, wrapping products and bits above bit 23. All 64 draws match on WARP and an RX 6600 through FXC ps_5_1 and DXC ps_6_0, and the 32 mutated draws read their mutated words. * build: close the foreach of the int_alu tests after merging main --------- Co-authored-by: tedin7 --- .github/workflows/windows.yml | 2 + CMakeLists.txt | 10 +++ docs/experiments.md | 17 ++++ tests/startup_gfx2hlsl_int_alu_check.py | 105 ++++++++++++++++++++++++ 4 files changed, 134 insertions(+) create mode 100644 tests/startup_gfx2hlsl_int_alu_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 6ca992861..e112d97fa 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -124,6 +124,7 @@ jobs: (["tests/startup_flat_param_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_float_transcendental_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_bit_alu_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_gfx2hlsl_int_alu_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_interp_f16_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_interp_p2_hi_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_sgpr_spill_check.py", "binary", "llvm-mc-15"], {}), @@ -303,6 +304,7 @@ jobs: tests/startup_packed_position_provenance_check.py \ tests/startup_build_rev_check.py \ tests/startup_gfx2hlsl_bit_alu_check.py \ + tests/startup_gfx2hlsl_int_alu_check.py \ tests/startup_gfx2hlsl_interp_f16_check.py tests/startup_gfx2hlsl_interp_p2_hi_check.py \ tests/startup_gfx2hlsl_sgpr_spill_check.py \ tests/startup_gfx2hlsl_mad_check.py \ diff --git a/CMakeLists.txt b/CMakeLists.txt index 1d3ee56d1..c53f0a5b8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3840,6 +3840,16 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_gfx2hlsl_bit_alu_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl two- and one-source integer vector operations (VEC_U): translation controls, then the same draw + # of the translated pairs with reference words and one mutated lowering per operation. + add_test(NAME startup_gfx2hlsl_int_alu_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_int_alu_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_int_alu_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_int_alu_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_int_alu_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl abs (`|src|` and `-|src|`) on v_cndmask_b32_e64 data sources: CPU evaluation of the translated # text over 32-bit bit patterns, then a desktop draw of the translated pair (FXC ps_5_1 and DXC ps_6_0) # with order-reversed and abs-dropped mutation controls. diff --git a/docs/experiments.md b/docs/experiments.md index 0822a4387..2583c9227 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15424,6 +15424,23 @@ python -B tools/startup/gfx2hlsl.py --refusals out/startup/shader_cache `off` names no offset at all, so it is translated exactly as the literal 0: the same emitted HLSL, the same descriptor offset for a table load, and the same fixed-word marking of an `s_buffer_load` result. Before this change, `s_buffer_load_dword s0, s[4:7], off` was refused with `operand 'off'`, and the `s_load` form with the misleading register-offset message. `tests/startup_gfx2hlsl_smem_offset_check.py` drives each load handler on a scalar symbol state with no machine code. It compares the `off` form of `s_buffer_load_dword`, `_dwordx2` and `_dwordx4`, of `s_load_dword` and `_dwordx2` from a root buffer and of `s_load_dwordx8` from a descriptor table with the literal 0, keeps the literal and `m0` behaviour above, and requires five other operand spellings to be refused by both kinds of load. With the `off` handling removed in-process, both `off` forms must be refused again. Test: `startup_gfx2hlsl_smem_offset`. Not covered here: whether the full set of locally refused shaders now translates, which needs local inputs. +## Startup translator: integer vector operations + +The `VEC_U` table of `tools/startup/gfx2hlsl.py` lowers these two- and one-source integer operations to single HLSL expressions, and no check ran them before: `v_add_nc_u32`, `v_sub_nc_u32`, `v_subrev_nc_u32`, `v_mul_lo_u32`, `v_and_b32`, `v_or_b32`, `v_xor_b32`, `v_not_b32`, `v_lshlrev_b32`, `v_lshrrev_b32`, `v_ashrrev_i32`, `v_min_u32`, `v_max_u32`, `v_min_i32`, `v_max_i32` and `v_mul_u32_u24`. + +`tests/startup_gfx2hlsl_int_alu_check.py` draws them with the pixel fixture of the bit-operation check above. The shared runner is `tests/startup_gfx2hlsl_lane_alu.py`. Each draw applies one operation to each of four pixels' flat inputs. The lanes alternate the `_e32` and `_e64` spellings (`v_mul_lo_u32` exists only as VOP3), and the four result words are compared exactly. + +The references follow the AMD RDNA 2 ISA reference: 32-bit wrapping arithmetic, `rev` shifts of S1 by S0[4:0], an arithmetic shift for `v_ashrrev_i32`, signed or unsigned comparisons by name, and the product of the low 24 bits for `v_mul_u32_u24`. Every operation has eight input sets (two draws). They include shift counts above 31, sign-bit values for the signed and unsigned pairs, wrapping products, and sources with bits above bit 23. + +Each operation also has a wrong lowering that must read its own mutated words in the first draw: +- add as subtract, the two subtract orders exchanged; +- a 24-bit multiply for `v_mul_lo_u32`, a full multiply for `v_mul_u32_u24`; +- OR, XOR and AND exchanged, NOT dropped; +- shift operands exchanged, the shift count masked to 4 bits, a logical shift for the arithmetic one; +- min and max exchanged, unsigned comparisons for the signed pair. + +On WARP 10.0.26100.9818 and on an AMD Radeon RX 6600 (driver 32.0.21045.29003), all 64 draws matched through FXC `ps_5_1` and DXC `ps_6_0`, and all 32 mutated draws read their mutated words. The controls also keep modifiers (`clamp`, `-v`, `|v|`, `mul:2`) and wrong operand counts refused. `binary ` reassembles the pixel bodies (llvm-mc 19 here; the CI job passes llvm-mc 15). Tests: `startup_gfx2hlsl_int_alu_controls`, `startup_gfx2hlsl_int_alu_warp` and `startup_gfx2hlsl_int_alu_hardware`. + **Constant register offsets for `s_load_dword*`.** An SGPR that holds a known constant (`s_movk_i32 s9, 0x40` before the load) is translated as the literal offset, which reaches descriptors in a bindless heap. Limits: the proof is used only in shaders without branches, because symbols are not merged at control-flow joins; `s_movk_i32` sign-extends its 16-bit immediate, so `0x8000` and above become negative and stay refused; the run-time sampler heap index is unchanged; an SGPR with an unknown value, `m0`, and a total above 0xfffff stay refused. Measured on CPU only (translation checks); D3D12 and GPU behavior are not measured. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_sload_const_offset$' -V` or `python3 -B tests/startup_gfx2hlsl_sload_const_offset_check.py`. [Part of #1723](https://github.com/R0Y00/Xbox2Windows/issues/1723) ### Scalar writes to and symbolic tracking of `m0` diff --git a/tests/startup_gfx2hlsl_int_alu_check.py b/tests/startup_gfx2hlsl_int_alu_check.py new file mode 100644 index 000000000..093ae49ed --- /dev/null +++ b/tests/startup_gfx2hlsl_int_alu_check.py @@ -0,0 +1,105 @@ +"""Two- and one-source integer vector operations of tools/startup/gfx2hlsl.py (its VEC_U table). + + (no arguments) translation controls, pure Python + binary reassemble the pixel bodies and compare them with the recorded words + draw [fxc] + draw one pixel per four input sets and compare the four result words + +Covers v_add_nc_u32, v_sub_nc_u32, v_subrev_nc_u32, v_mul_lo_u32, v_and_b32, v_or_b32, v_xor_b32, v_not_b32, +v_lshlrev_b32, v_lshrrev_b32, v_ashrrev_i32, v_min_u32, v_max_u32, v_min_i32, v_max_i32 and v_mul_u32_u24, which +no check ran before. The fixture and runner are startup_gfx2hlsl_lane_alu.py: one operation per lane, alternating +the e32 and e64 spellings where both exist (v_mul_lo_u32 is VOP3 only), on flat parameters the compilers cannot fold. +The references follow the AMD RDNA 2 ISA reference: 32-bit wrapping arithmetic, shifts by S0[4:0] of S1 (the +"rev" forms), an arithmetic shift for v_ashrrev_i32, signed or unsigned comparisons by name, and the 24-bit +multiply of the low 24 bits of each source. The inputs include shift counts above 31, values with the sign bit +set for the signed and unsigned pairs, products that wrap and sources with bits above bit 23. +""" +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from startup_gfx2hlsl_lane_alu import MASK, main, signed, words # noqa: E402 + +M24 = 0xffffff +OPS = { + 'v_add_nc_u32': (2, lambda a, b: a + b, True), + 'v_sub_nc_u32': (2, lambda a, b: a - b, True), + 'v_subrev_nc_u32': (2, lambda a, b: b - a, True), + 'v_mul_lo_u32': (2, lambda a, b: a * b, False), + 'v_and_b32': (2, lambda a, b: a & b, True), + 'v_or_b32': (2, lambda a, b: a | b, True), + 'v_xor_b32': (2, lambda a, b: a ^ b, True), + 'v_not_b32': (1, lambda a: ~a, True), + 'v_lshlrev_b32': (2, lambda a, b: b << (a & 31), True), + 'v_lshrrev_b32': (2, lambda a, b: b >> (a & 31), True), + 'v_ashrrev_i32': (2, lambda a, b: signed(b) >> (a & 31), True), + 'v_min_u32': (2, min, True), + 'v_max_u32': (2, max, True), + 'v_min_i32': (2, lambda a, b: min(signed(a), signed(b)), True), + 'v_max_i32': (2, lambda a, b: max(signed(a), signed(b)), True), + 'v_mul_u32_u24': (2, lambda a, b: (a & M24) * (b & M24), True), +} +# Input sets (src0, src1, unused), eight per operation: two draws of four pixels. +ARITH = [(1, MASK, 0), (0x80000000, 0x80000000, 0), (0x12345678, 0x9abcdef0, 0), (0, 1, 0), + (0x7fffffff, 1, 0), (0xdeadbeef, 0xfeedface, 0), (5, 3, 0), (MASK, MASK, 0)] +LOGIC = [(0xf0f0f0f0, 0x0ff00ff0, 0), (0, MASK, 0), (0x12345678, 0x9abcdef0, 0), (MASK, 0x80000001, 0), + (0xaaaaaaaa, 0x55555555, 0), (0xdeadbeef, 0, 0), (1, 3, 0), (0x00ff0000, 0x0f0f0f0f, 0)] +SHIFT = [(4, 0x80000001, 0), (31, 0xc0000000, 0), (33, 0x80000010, 0), (0, 0xdeadbeef, 0), + (16, 0x12345678, 0), (0xffffffe1, 0xf0000000, 0), (32, 0x7fffffff, 0), (7, 0xffffff80, 0)] +ORDER = [(1, 0x80000000, 0), (MASK, 0, 0), (0x7fffffff, 0x80000000, 0), (5, 5, 0), + (0xfffffffe, 0xffffffff, 0), (100, 0x80000001, 0), (0, 0x7fffffff, 0), (0x80000000, 0x7fffffff, 0)] +MUL24 = [(0x01000003, 0x02000005, 0), (M24, M24, 0), (0x12345678, 0x9abcdef0, 0), (0x00800000, 2, 0), + (MASK, 1, 0), (0x00010000, 0x00010000, 0), (0xff000000, 0xff123456, 0), (7, 0x00ffffff, 0)] +DRAW = {op: ARITH for op in ('v_add_nc_u32', 'v_sub_nc_u32', 'v_subrev_nc_u32', 'v_mul_lo_u32')} +DRAW.update({op: LOGIC for op in ('v_and_b32', 'v_or_b32', 'v_xor_b32', 'v_not_b32')}) +DRAW.update({op: SHIFT for op in ('v_lshlrev_b32', 'v_lshrrev_b32', 'v_ashrrev_i32')}) +DRAW.update({op: ORDER for op in ('v_min_u32', 'v_max_u32', 'v_min_i32', 'v_max_i32')}) +DRAW['v_mul_u32_u24'] = MUL24 +# A wrong lowering of each operation: (pattern in the translated text, replacement, reference of the mutation). +MUTATIONS = { + 'v_add_nc_u32': (r'= (v\d+) \+ (v\d+);', r'= \1 - \2;', lambda a, b: a - b), + 'v_sub_nc_u32': (r'= (v\d+) - (v\d+);', r'= \2 - \1;', lambda a, b: b - a), + 'v_subrev_nc_u32': (r'= (v\d+) - (v\d+);', r'= \2 - \1;', lambda a, b: a - b), + 'v_mul_lo_u32': (r'= (v\d+) \* (v\d+);', r'= \1 * (\2 & 0xffffffu);', lambda a, b: a * (b & M24)), + 'v_and_b32': (r'= (v\d+) & (v\d+);', r'= \1 | \2;', lambda a, b: a | b), + 'v_or_b32': (r'= (v\d+) \| (v\d+);', r'= \1 ^ \2;', lambda a, b: a ^ b), + 'v_xor_b32': (r'= (v\d+) \^ (v\d+);', r'= \1 | \2;', lambda a, b: a | b), + 'v_not_b32': (r'= ~(v\d+);', r'= \1;', lambda a: a), + 'v_lshlrev_b32': (r'= (v\d+) << \((v\d+) & 31\);', r'= \2 << (\1 & 31);', lambda a, b: a << (b & 31)), + 'v_lshrrev_b32': (r'>> \((v\d+) & 31\)', r'>> (\1 & 15)', lambda a, b: b >> (a & 15)), + 'v_ashrrev_i32': (r'uint\(int\((v\d+)\) >> ', r'(\1 >> ', lambda a, b: b >> (a & 31)), + 'v_min_u32': (r'min\((v\d+), (v\d+)\)', r'max(\1, \2)', max), + 'v_max_u32': (r'max\((v\d+), (v\d+)\)', r'min(\1, \2)', min), + 'v_min_i32': (r'uint\(min\(int\((v\d+)\), int\((v\d+)\)\)\)', r'min(\1, \2)', min), + 'v_max_i32': (r'uint\(max\(int\((v\d+)\), int\((v\d+)\)\)\)', r'max(\1, \2)', max), + 'v_mul_u32_u24': (r'\((v\d+) & 0xffffffu\) \* \((v\d+) & 0xffffffu\)', r'\1 * \2', lambda a, b: a * b), +} +BODY = { + 'v_add_nc_u32': words('0009184a0d0025d5010b0200020d1c4a0f0025d5030f0200'), + 'v_sub_nc_u32': words('0009184c0d0026d5010b0200020d1c4c0f0026d5030f0200'), + 'v_subrev_nc_u32': words('0009184e0d0027d5010b0200020d1c4e0f0027d5030f0200'), + 'v_mul_lo_u32': words('0c0069d5000902000d0069d5010b02000e0069d5020d02000f0069d5030f0200'), + 'v_and_b32': words('000918360d001bd5010b0200020d1c360f001bd5030f0200'), + 'v_or_b32': words('000918380d001cd5010b0200020d1c380f001cd5030f0200'), + 'v_xor_b32': words('0009183a0d001dd5010b0200020d1c3a0f001dd5030f0200'), + 'v_not_b32': words('006f187e0d00b7d501010000026f1c7e0f00b7d503010000'), + 'v_lshlrev_b32': words('000918340d001ad5010b0200020d1c340f001ad5030f0200'), + 'v_lshrrev_b32': words('0009182c0d0016d5010b0200020d1c2c0f0016d5030f0200'), + 'v_ashrrev_i32': words('000918300d0018d5010b0200020d1c300f0018d5030f0200'), + 'v_min_u32': words('000918260d0013d5010b0200020d1c260f0013d5030f0200'), + 'v_max_u32': words('000918280d0014d5010b0200020d1c280f0014d5030f0200'), + 'v_min_i32': words('000918220d0011d5010b0200020d1c220f0011d5030f0200'), + 'v_max_i32': words('000918240d0012d5010b0200020d1c240f0012d5030f0200'), + 'v_mul_u32_u24': words('000918160d000bd5010b0200020d1c160f000bd5030f0200'), +} +FAMILY = { + 'ops': OPS, 'draw': DRAW, 'mutations': MUTATIONS, 'body': BODY, + 'accepted': ['v_add_nc_u32 v1, v2, v3', 'v_mul_lo_u32 v1, v2, v3', 'v_not_b32_e64 v1, v2', + 'v_ashrrev_i32_e64 v1, v2, v3', 'v_min_i32 v1, 5, v3', 'v_mul_u32_u24_e64 v1, v2, v3'], + 'refused': ['v_add_nc_u32 v1, v2', 'v_mul_lo_u32 v1, v2, v3, v4', 'v_not_b32 v1, v2, v3', + 'v_add_nc_u32_e64 v1, v2, v3 clamp', 'v_and_b32_e64 v1, -v2, v3', 'v_max_i32_e64 v1, |v2|, v3', + 'v_lshlrev_b32_e64 v1, v2, v3 mul:2', 'v_xor_b32 v1, v2'], +} + +if __name__ == '__main__': + main(FAMILY, __doc__) From 9b5c5180974574f9ddc1555ed43324c5e8d61f5c Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Thu, 26 Nov 2026 03:29:44 +0100 Subject: [PATCH 075/240] shader: prove spill-slot reads across branches in the startup translator (#2524) * startup: prove spill-slot reads across branches in gfx2hlsl (#2125) v_writelane_b32 / v_readlane_b32 spill slots were refused in any pixel stage with branches. A forward must-dataflow over the basic blocks (intersection at joins, fixed point through loops) now gives the writes that can supply each read. A single reaching write is accepted unless it lies in the region of a branch not proven uniform that the read is outside; several reaching writes are accepted only when none lies in such a region, and the reload then keeps a constant only if every write stored it and is not claimed uniform. Every other shape keeps a named refusal: no write on some path, a loop-carried write, a write in a non-uniform region, a refused reaching write. Refs #2125 Co-Authored-By: Claude Opus 5.5 * test: draw the spill slot across uniform branches on D3D12 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: tedin7 --- .github/workflows/windows.yml | 1 + AGENTS.md | 1 + CMakeLists.txt | 11 + docs/experiments.md | 4 +- .../startup_gfx2hlsl_spill_branches_check.py | 390 ++++++++++++++++++ tools/startup/gfx2hlsl.py | 109 ++++- 6 files changed, 505 insertions(+), 11 deletions(-) create mode 100644 tests/startup_gfx2hlsl_spill_branches_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index e112d97fa..9b3c95f89 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -307,6 +307,7 @@ jobs: tests/startup_gfx2hlsl_int_alu_check.py \ tests/startup_gfx2hlsl_interp_f16_check.py tests/startup_gfx2hlsl_interp_p2_hi_check.py \ tests/startup_gfx2hlsl_sgpr_spill_check.py \ + tests/startup_gfx2hlsl_spill_branches_check.py \ tests/startup_gfx2hlsl_mad_check.py \ tests/startup_gfx2hlsl_neg_check.py \ tests/startup_gfx2hlsl_compute_check.py \ diff --git a/AGENTS.md b/AGENTS.md index c7bc06e20..bc3d72607 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -251,6 +251,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_run_sh_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_bit_alu_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_sgpr_spill_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_spill_branches_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_shift64_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_vopc_sdwa_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_cmp16_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index c53f0a5b8..23110dc47 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3920,6 +3920,17 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_gfx2hlsl_mul24_align_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) endforeach() + # The same spill slots across branches: a write must reach the read on every path, outside non-uniform regions. + add_test(NAME startup_gfx2hlsl_spill_branches COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_spill_branches_check.py") + # The same branches drawn on D3D12 (FXC 5_1 and DXC 6_0): two uniform choices write different words to one slot, + # GPU readback of the reload after the join against each arm's reference, the opposite arm as a negative control. + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_spill_branches_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_spill_branches_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_spill_branches_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl 16-bit vector ALU (#1723): the translated pairs drawn on WARP and hardware (FXC 5_1 and DXC 6_0), # four result words per draw against an exact binary16 reference. add_test(NAME startup_gfx2hlsl_f16_alu_draw_controls COMMAND "${INTAKE_PYTHON}" -B diff --git a/docs/experiments.md b/docs/experiments.md index 2583c9227..d8eca29e6 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14947,7 +14947,9 @@ lane masks and the discard destination. Run The startup pixel stage lowers DPP16 quad swaps (#2125 item B): `v_mov_b32_dpp` and the VOP2 forms in the integer and binary32 operation tables with `quad_perm:[1,0,3,2]`, `[2,3,0,1]` or `[3,2,1,0]` and full `row_mask`/`bank_mask` read the source from the neighbouring pixel of the 2x2 quad (X, Y or diagonal), written as `QuadReadAcrossX`, `QuadReadAcrossY` and `QuadReadAcrossDiagonal` (SM 6.0, helper lanes included). The second source of a VOP2 keeps the lane's own register. The form needs a straight-line pixel stage at entry EXEC, proven whole-quad by an earlier `s_wqm_b64 exec, exec` (a partly covered quad has inactive source lanes that the hardware masks and `QuadReadAcross*` does not; a later write to EXEC or a restored older copy drops the proof), and plain VGPR operands. A binary32 source may carry the `neg`/`abs` modifier (`-vN`, `|vN|`, `-|vN|`): the permuted word is read from the neighbour first and the modifier applies to that value (RDNA 2 ISA 12.19, LLVM 15 prints them on the `_dpp` spelling), while integer sources, SGPR sources and every other modifier stay refused. Vertex stages, broadcast and pair selections (items A and C), row shifts, mirrors, DPP8, partial masks and operations without a table entry are refused. `fi:1` (fetch inactive) is accepted under the same whole-quad proof, where no source lane is disabled, and gives the same translation. FXC ps_5_1 has no quad intrinsic, so `translate_to` compiles a pair that uses one with DXC as vs_6_0/ps_6_0 (`X2W_DXC`, then PATH) and refuses it when no DXC exists. `tests/startup_gfx2hlsl_dpp_quad_swap_check.py` builds three pixel programs from the lane rule (OR and move forms, plus `v_min_u32_dpp` of the exchanged and own positions, #2023 item H, whose reference is the integer unsigned minimum and which also rejects a maximum) (the packed position in v0, the neighbour at x^1, y^1 or both, an own-lane control), draws 16 x 16 pixels and compares every word with an integer reference; three wrong exchanges, a missing exchange and (for the minimum) a maximum must read a different image, and a reference with one swap dropped must be rejected. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_dpp_quad_swap_' -V`. The Python controls run on Linux; the draws need DXC and `offscreen_check` on Windows. `startup_gfx2hlsl_dpp_quad_swap_controls` checks `-v0` and `|v0|` against the emitted `QuadReadAcrossX` text and keeps an integer `-v0` refused; the draw mode also checks all 256 pixels of a binary32 multiply-by-one fixture. Its three channels use NEG, ABS and NEG+ABS on different neighbours, and each dropped modifier produces a mismatch. The binary mode reassembles the modified DPP source words. [Refs #1723](https://github.com/R0Y00/Xbox2Windows/issues/1723) -The startup pixel stage lowers constant-lane SGPR spills (#2125 item E): `v_writelane_b32 vN, sM, k` followed by `v_readlane_b32 sD, vN, k` with an inline constant lane `k` (0..31) becomes one scalar slot per (VGPR, lane), written and read back as plain assignments. Both instructions ignore EXEC and touch only lane `k`, so with a constant `k` and a VGPR that no other instruction names, no cross-lane read exists to model. Refused, each with a reason: a lane chosen by an SGPR, lanes outside 0..31, a VGPR that any other instruction also names (vector use or register range), a read of a slot nothing wrote, branches (write-before-read needs straight-line order), a lane mask, `m0` or modifier on the value, a destination that is not a plain SGPR, and vertex stages. A constant value reloads as a constant. `tests/startup_gfx2hlsl_sgpr_spill_check.py` builds a pixel program with four slots in three VGPRs, clobbers the source SGPRs, reloads them (one slot after a second write) and ORs each word into the packed screen position; it draws 16 x 16 pixels and compares every word with an integer reference computed from the slot rule. Four wrong lowerings (overwrite ignored, lane 31 read as lane 0, a second VGPR read as the first, no reload) must read a different image. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_sgpr_spill_' -V`. The Python controls and the `binary` assembler check run on Linux; the draws need DXC and `offscreen_check` on Windows. +The startup pixel stage lowers constant-lane SGPR spills (#2125 item E): `v_writelane_b32 vN, sM, k` followed by `v_readlane_b32 sD, vN, k` with an inline constant lane `k` (0..31) becomes one scalar slot per (VGPR, lane), written and read back as plain assignments. Both instructions ignore EXEC and touch only lane `k`, so with a constant `k` and a VGPR that no other instruction names, no cross-lane read exists to model. Refused, each with a reason: a lane chosen by an SGPR, lanes outside 0..31, a VGPR that any other instruction also names (vector use or register range), a read of a slot nothing wrote, a read in a program with branches that the proof below does not cover, a lane mask, `m0` or modifier on the value, a destination that is not a plain SGPR, and vertex stages. A constant value reloads as a constant. `tests/startup_gfx2hlsl_sgpr_spill_check.py` builds a pixel program with four slots in three VGPRs, clobbers the source SGPRs, reloads them (one slot after a second write) and ORs each word into the packed screen position; it draws 16 x 16 pixels and compares every word with an integer reference computed from the slot rule. Four wrong lowerings (overwrite ignored, lane 31 read as lane 0, a second VGPR read as the first, no reload) must read a different image. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_sgpr_spill_' -V`. The Python controls and the `binary` assembler check run on Linux; the draws need DXC and `offscreen_check` on Windows. + +The same slots are lowered in pixel stages with branches. The slot variable is assigned on the pixel's own path, while the hardware lane holds the last write on the wave's path; the two differ only inside the region of a branch not proven uniform (`s_cbranch_execz`/`_vccz` and their `nz` forms, or an SCC branch on varying data: the blocks between the branch and its immediate post-dominator, or the loop range of a backward branch), where the wave also runs blocks the pixel skips. A forward must-dataflow over the basic blocks (intersection at joins, fixed point through loops) gives, for each `v_readlane_b32`, the writes of its (VGPR, lane) that can supply it. One write: every path into the read ran it, so it is accepted unless the write lies in such a region and the read is outside it (a loop or arm the wave can run after the pixel left it). Several writes: accepted only when none lies in such a region; the reload keeps a constant only if every write stored it and is not claimed uniform. Refused, each by name: no write on some path (including another lane on another path), a write later in a loop that reaches the read through the back edge, a single write in a non-uniform region the read is outside, joined writes with one in a non-uniform region, and a reaching write that was itself refused. The lane-mask, descriptor, lane-range and vector-use refusals above are unchanged; the lane-mask test still follows program order, not the joins. On a local set of 79 vertex/pixel requests whose first refusal was the straight-line requirement under a development translator, 32 reach that refusal on main; with this change all 32 pass it and stop next at a lane-mask or descriptor spill source (30) or a spill VGPR also used as a vector (2). The other 47 stop earlier on main (`v_fma_mix_f32` 39, a joined symbol 8). `tests/startup_gfx2hlsl_spill_branches_check.py` (`startup_gfx2hlsl_spill_branches`) translates synthetic programs through `Stage.translate()`: six accepted shapes with their exact emitted lines, seven refusals with their exact reasons, and six translator mutations (union at joins, one pass instead of the fixed point, lanes keyed by their spelling, each region rule removed, every branch counted uniform) that must each turn a control red. One whole pixel stage is also generated: the slot is declared once and assigned on both arms of a uniform branch before the read after the join. The same file also draws it (`startup_gfx2hlsl_spill_branches_warp`/`_hardware`, FXC 5_1 and DXC 6_0): two uniform SCC choices write different binary32 words to one slot, the join reloads it and exports it OR-ed with the packed screen position, and the readback of all 16x16 pixels must equal the selected arm; the opposite arm's reference must mismatch. The binary32 table (`VEC_F`) applies the same operand-count rule. Before this change, a form one source short (`v_add_f32 v1, v2`) raised `IndexError` in `Stage.one` instead of `Unsupported`. A form with one source too many (`v_med3_f32 v1, v2, v3, v4, v5`) translated with the extra source dropped. `tests/startup_gfx2hlsl_operand_count_check.py` (`startup_gfx2hlsl_operand_count`) checks every operation of both tables: one source fewer and one source more are refused, and the exact count translates. It also checks that the constant and accumulator forms (`v_fmac_f32`, `v_mac_f32`, `v_fmamk_f32`, `v_fmaak_f32`, `v_madmk_f32`, `v_madak_f32`) keep translating with their usual operands. As a control, it loads the translator with the new `VEC_F` guard removed and requires both old failures to come back. diff --git a/tests/startup_gfx2hlsl_spill_branches_check.py b/tests/startup_gfx2hlsl_spill_branches_check.py new file mode 100644 index 000000000..5ae651d3a --- /dev/null +++ b/tests/startup_gfx2hlsl_spill_branches_check.py @@ -0,0 +1,390 @@ +"""SGPR spill to VGPR lanes across branches in the pixel stage of tools/startup/gfx2hlsl.py (#2125). + +`v_writelane_b32 vN, sM, k` parks a scalar in lane k of vN and `v_readlane_b32 sD, vN, k` reads it back; both ignore +EXEC (AMD RDNA 2 ISA reference, VOP3 lane operations). The translator keeps one scalar per (vN, k). In a program with +branches that scalar is assigned on the pixel's own path, while the hardware slot holds the last write on the wave's +path. A read is accepted when a write of its (VGPR, lane) reaches it on every path (forward must-dataflow: +intersection at joins, fixed point through loops) and no write that can supply it lies where the wave can run it +while this pixel skips it: inside the region of a branch not proven uniform that the read is outside, or, when several +writes can supply the read, inside any such region. + +Synthetic programs only, translated through Stage.translate(). Every refusal has a negative control, and the +translator mutations at the end (union instead of intersection, one pass instead of the fixed point, each region rule +removed) must each turn a control red. + + (no arguments) pure Python + binary the draw fixtures assemble to their words + draw [fxc] both uniform choices drawn, read back, opposite arm refused +""" +import re +import struct +import subprocess +import sys +import tempfile +import types +from pathlib import Path +from types import SimpleNamespace + +HERE = Path(__file__).resolve().parent +TOOLS = HERE.parent / 'tools' +sys.path.insert(0, str(TOOLS)) +sys.path.insert(0, str(TOOLS / 'startup')) +import gfx2hlsl as G # noqa: E402 +sys.path.insert(0, str(HERE)) +from startup_flat_param_check import assemble # noqa: E402 +from startup_image_3d_check import FULLSCREEN_VS, VS_WORDS, compile_hlsl, root_blob # noqa: E402 + +failures = [] + + +def check(label, ok, detail=''): + print('%s: %s' % (label, 'ok' if ok else 'MISMATCH')) + if not ok: + failures.append(label) + if detail: + print(' ' + detail) + + +def program(text): + """Assembly text with `Name:` labels -> decoded (offset, size, name, text) tuples, four bytes each.""" + lines = [line.strip() for line in text.strip().splitlines()] + labels, offset = {}, 0 + for line in lines: + if line.endswith(':'): + labels[line[:-1]] = offset + else: + offset += 4 + decoded, offset = [], 0 + for line in lines: + if not line.endswith(':'): + line = re.sub(r'\bL\w+\b', lambda m: 'label_%x' % labels[m[0]], line) + decoded.append((offset, 4, line.split(' ', 1)[0], line)) + offset += 4 + return decoded + + +def translate(text, module=G): + """-> (refusal reasons, emitted lines in block order).""" + refusals = [] + stage = module.Stage(SimpleNamespace(root={'params': [], 'flags': 0}), 'ps', b'', refusals=refusals, + decoded=program(text)) + return [reason for reason, _ in refusals], [line for _, lines, _ in stage.blocks for line in lines] + + +# s3 is an entry scalar, so `s_cmp_eq_u32 s2, s3` is a uniform SCC branch; s_cbranch_execz is never proven uniform. +ACCEPTED = { + 'two arms of a uniform branch, each writing a different constant': (''' + s_mov_b32 s2, 5 + s_cmp_eq_u32 s2, s3 + s_cbranch_scc0 Lelse + v_writelane_b32 v10, 7, 3 + s_branch Ljoin + Lelse: + v_writelane_b32 v10, 9, 3 + Ljoin: + v_readlane_b32 s1, v10, 3 + v_mov_b32 v1, s1 + s_endpgm''', ['sp10_3 = 0x00000007u;', 'sp10_3 = 0x00000009u;', 's1 = sp10_3;', 'v1 = s1;']), + 'two arms of a uniform branch writing the same constant keep it': (''' + s_mov_b32 s2, 5 + s_cmp_eq_u32 s2, s3 + s_cbranch_scc0 Lelse + v_writelane_b32 v10, 7, 3 + s_branch Ljoin + Lelse: + v_writelane_b32 v10, 7, 3 + Ljoin: + v_readlane_b32 s1, v10, 3 + v_mov_b32 v1, s1 + s_endpgm''', ['sp10_3 = 0x00000007u;', 'sp10_3 = 0x00000007u;', 's1 = sp10_3;', 'v1 = 0x00000007u;']), + 'write before a non-uniform branch, read inside its region and after the join': (''' + v_writelane_b32 v10, s3, 3 + s_and_saveexec_b32 s4, vcc_lo + s_cbranch_execz Ljoin + v_readlane_b32 s1, v10, 3 + v_mov_b32 v1, s1 + Ljoin: + s_or_b32 exec_lo, exec_lo, s4 + v_readlane_b32 s5, v10, 3 + v_mov_b32 v2, s5 + s_endpgm''', ['sp10_3 = s3;', 's1 = sp10_3;', 'if (exec & 1) v1 = s1;', 's5 = sp10_3;', + 'if (exec & 1) v2 = s5;']), + 'write and read inside the same non-uniform region': (''' + s_and_saveexec_b32 s4, vcc_lo + s_cbranch_execz Ljoin + v_writelane_b32 v10, s3, 3 + s_mov_b32 s3, 0 + v_readlane_b32 s1, v10, 3 + v_mov_b32 v1, s1 + Ljoin: + s_or_b32 exec_lo, exec_lo, s4 + s_endpgm''', ['sp10_3 = s3;', 's1 = sp10_3;', 'if (exec & 1) v1 = s1;']), + 'a lane spelled 0x3 overwrites lane 3': (''' + s_mov_b32 s2, 5 + s_cmp_eq_u32 s2, s3 + s_cbranch_scc0 Ljoin + Ljoin: + v_writelane_b32 v10, 7, 3 + v_writelane_b32 v10, 9, 0x3 + v_readlane_b32 s1, v10, 3 + v_mov_b32 v1, s1 + s_endpgm''', ['sp10_3 = 0x00000007u;', 'sp10_3 = 0x00000009u;', 's1 = sp10_3;', 'v1 = 0x00000009u;']), + 'write before a uniform loop, read in the body and after it': (''' + v_writelane_b32 v10, s3, 3 + s_mov_b32 s2, 0 + Lloop: + v_readlane_b32 s1, v10, 3 + s_add_u32 s2, s2, 1 + s_cmp_lt_u32 s2, 4 + s_cbranch_scc1 Lloop + v_readlane_b32 s5, v10, 3 + v_mov_b32 v1, s5 + s_endpgm''', ['sp10_3 = s3;', 's1 = sp10_3;', 's5 = sp10_3;', 'v1 = s5;']), +} + +REFUSED = { + 'a write on one arm only (no write on some path)': (''' + s_mov_b32 s2, 5 + s_cmp_eq_u32 s2, s3 + s_cbranch_scc0 Ljoin + v_writelane_b32 v10, 7, 3 + Ljoin: + v_readlane_b32 s1, v10, 3 + s_endpgm''', 'v_readlane_b32 reads v10 lane 3 with no v_writelane_b32 of it on some path'), + 'another lane on the other arm': (''' + s_mov_b32 s2, 5 + s_cmp_eq_u32 s2, s3 + s_cbranch_scc0 Lelse + v_writelane_b32 v10, 7, 3 + s_branch Ljoin + Lelse: + v_writelane_b32 v10, 7, 4 + Ljoin: + v_readlane_b32 s1, v10, 3 + s_endpgm''', 'v_readlane_b32 reads v10 lane 3 with no v_writelane_b32 of it on some path'), + 'a later write in a uniform loop reaches the loop head (loop-carried)': (''' + v_writelane_b32 v10, 7, 3 + s_mov_b32 s2, 0 + Lloop: + v_readlane_b32 s1, v10, 3 + v_mov_b32 v1, s1 + v_writelane_b32 v10, 9, 3 + s_add_u32 s2, s2, 1 + s_cmp_lt_u32 s2, 4 + s_cbranch_scc1 Lloop + s_endpgm''', 'v_readlane_b32 reads v10 lane 3 written later in a loop (loop-carried)'), + 'the only write inside a non-uniform loop, read after it': (''' + s_mov_b32 s2, 0 + Lloop: + v_writelane_b32 v10, s2, 3 + s_add_u32 s2, s2, 1 + v_cmp_gt_u32 vcc_lo, s2, v0 + s_cbranch_vccnz Lloop + v_readlane_b32 s1, v10, 3 + s_endpgm''', 'v_readlane_b32 reads v10 lane 3 outside the region of the branch at 0x10 that writes it, ' + 'which is not proven uniform'), + 'a write before and a write inside a non-uniform region, read after the join': (''' + v_writelane_b32 v10, s3, 3 + s_and_saveexec_b32 s4, vcc_lo + s_cbranch_execz Ljoin + v_writelane_b32 v10, 9, 3 + Ljoin: + s_or_b32 exec_lo, exec_lo, s4 + v_readlane_b32 s1, v10, 3 + s_endpgm''', 'v_readlane_b32 joins 2 writes of v10 lane 3, one inside the region of the branch at 0x8, which ' + 'is not proven uniform'), + 'two arms of a non-uniform branch rejoining inside an outer non-uniform region': (''' + s_and_saveexec_b32 s4, vcc_lo + s_cbranch_execz Lend + v_writelane_b32 v10, 7, 3 + s_cbranch_vccz Lelse + v_writelane_b32 v10, 9, 3 + Lelse: + v_readlane_b32 s1, v10, 3 + Lend: + s_or_b32 exec_lo, exec_lo, s4 + s_endpgm''', 'v_readlane_b32 joins 2 writes of v10 lane 3, one inside the region of the branch at 0x4, which ' + 'is not proven uniform'), + 'the reaching write was refused': (''' + s_mov_b32 s2, 5 + s_cmp_eq_u32 s2, s3 + s_cbranch_scc0 Ljoin + Ljoin: + v_writelane_b32 v10, vcc_lo, 3 + v_readlane_b32 s1, v10, 3 + s_endpgm''', 'v_readlane_b32 reads v10 lane 3 from a v_writelane_b32 that was not translated'), +} + + +def controls(module=G, quiet=False): + """-> labels of the controls that failed against `module`.""" + failed = [] + for label, (text, want) in ACCEPTED.items(): + reasons, lines = translate(text, module) + ok = not reasons and [line for line in lines if re.match(r'(if \(exec & 1\) )?(sp\d|s1 |s5 |v[12] )', line)] == want + failed += [] if ok else ['accepted: ' + label] + if not quiet: + check('accepted: %s' % label, ok, '%s %s' % (reasons, lines)) + for label, (text, want) in REFUSED.items(): + reasons, _ = translate(text, module) + ok = want in reasons + failed += [] if ok else ['refused: ' + label] + if not quiet: + check('refused: %s' % label, ok, str(reasons)) + return failed + + +MUTATIONS = { + 'union instead of intersection at joins': ( + '{k: into[t][k] | state[k] for k in into[t].keys() & state.keys()}', + '{k: into[t].get(k, frozenset()) | state.get(k, frozenset()) for k in into[t].keys() | state.keys()}'), + 'one pass instead of the fixed point': ( + ' while changed:\n changed = False\n for b, (lo, hi) in enumerate(bounds):\n', + ' for changed in [False]:\n for b, (lo, hi) in enumerate(bounds):\n'), + 'lanes keyed by their spelling': ('lane = int(ops[2], 0) # 3 and 0x3', 'lane = ops[2] # 3 and 0x3'), + 'no region rule for a single write': (' if here not in blocks:\n', ' if False:\n'), + 'no region rule for joined writes': (' if len(writes) > 1:\n', ' if False:\n'), + 'every conditional branch counted as uniform': (' if off in self.uniform_branches or', + ' if True or'), +} + + +def mutated(old, new): + source = (TOOLS / 'startup' / 'gfx2hlsl.py').read_text(encoding='utf-8').replace('\r\n', '\n') + assert source.count(old) == 1, old + module = types.ModuleType('gfx2hlsl_mutant') + module.__file__ = str(TOOLS / 'startup' / 'gfx2hlsl.py') + exec(compile(source.replace(old, new), module.__file__, 'exec'), module.__dict__) + return module + + +# The same slot drawn on D3D12: two uniform branch choices write different words to v10 lane 3, the join reloads it and +# exports it OR-ed with the packed screen position. s3 is 5 (the compare s2 == s3 holds: first arm) or 6 (second arm). +WIDTH = HEIGHT = 16 +PACKED = (0x8000, 0x8000) # SPI_PS_INPUT_ENA/ADDR: the packed screen position only, in v0 +ARM_WORDS = (0x40200000, 0x40400000) # binary32 words with no bit below 21, clear of x | y << 16 +FIXTURE_TEXT = '''s_mov_b32 s0, 0x40200000 +s_mov_b32 s1, 0x40400000 +s_mov_b32 s2, 5 +s_mov_b32 s3, %d +s_cmp_eq_u32 s2, s3 +s_cbranch_scc0 3 +v_writelane_b32 v10, s0, 3 +s_branch 2 +v_writelane_b32 v10, s1, 3 +v_readlane_b32 s5, v10, 3 +v_or_b32_e32 v1, s5, v0 +exp mrt0 v1, v1, v1, v1 done vm +s_endpgm +''' +_COMMON = (0xbe8003ff, 0x40200000, 0xbe8103ff, 0x40400000, 0xbe820385) +_TAIL = (0xbf060302, 0xbf840003, 0xd761000a, 0x00010600, 0xbf820002, 0xd761000a, 0x00010601, 0xd7600005, + 0x0001070a, 0x38020005, 0xf800180f, 0x01010101, 0xbf810000) +CHOICES = {5: ARM_WORDS[0], 6: ARM_WORDS[1]} +CHOICE_WORDS = {s3: struct.pack('<19I', *_COMMON, 0xbe830380 | s3, *_TAIL) for s3 in CHOICES} + + +def pixel_image(arm): + return [(x | y << 16) | arm for y in range(HEIGHT) for x in range(WIDTH) for _ in range(4)] + + +def check_binary(llvm_mc): + for s3 in CHOICES: + check('llvm-mc assembles the s3 == %d fixture to the same words' % s3, + assemble(llvm_mc, FIXTURE_TEXT % s3) == CHOICE_WORDS[s3]) + + +def words_file(directory, name, words): + path = directory / ('%s.bin' % name) + path.write_bytes(struct.pack('<%dI' % len(words), *words)) + return path + + +def draw(renderer, adapter, vs, ps, expected): + run = subprocess.run([renderer, adapter, '--startup-pixel-words', str(vs), str(ps), str(WIDTH), str(HEIGHT), + str(expected)], capture_output=True, text=True) + if run.returncode == 77: + print(run.stdout + run.stderr) + sys.exit(1 if failures else 77) + return run + + +def check_draw(dxc, renderer, adapter, fxc=None): + texts = {} + for s3, words in CHOICE_WORDS.items(): + refusals = [] + texts[s3] = G.Pipeline(VS_WORDS, words, root_blob(), ps_hw_inputs=PACKED, refusals=refusals).hlsl_ps() + check('s3 == %d: the pixel stage translates with no refusal' % s3, not refusals, str(refusals)) + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + images = {s3: words_file(directory, 'image%d' % s3, pixel_image(arm)) for s3, arm in CHOICES.items()} + for name, compiler, profile_vs, profile_ps in ( + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else [])): + vs = compile_hlsl(compiler, name, FULLSCREEN_VS, 'vs_' + name, profile_vs, directory) + for s3, text in texts.items(): + ps = compile_hlsl(compiler, name, text, 'ps_%s_%d' % (name, s3), profile_ps, directory) + run = draw(renderer, adapter, vs, ps, images[s3]) + check('%s %s s3 == %d: all %d pixels equal the selected arm' % (adapter, name, s3, WIDTH * HEIGHT), + run.returncode == 0 and 'all %d pixels matched' % (WIDTH * HEIGHT) in run.stdout, + run.stdout + run.stderr) + # Negative control: the opposite arm's reference must differ from what this choice draws. + run = draw(renderer, adapter, vs, ps, images[11 - s3]) + check('%s %s s3 == %d: the opposite arm as reference fails' % (adapter, name, s3), + run.returncode != 0 and 'pixel mismatch' in run.stderr, run.stdout + run.stderr) + + +def main(): + if len(sys.argv) != 1: + mode, *args = sys.argv[1:] + if mode == 'binary': + check_binary(*args) + elif mode == 'draw': + controls() + check_draw(*args) + else: + raise SystemExit(__doc__) + if failures: + print('FAIL') + for text in failures: + print(' ' + text) + sys.exit(1) + print('PASS') + return + controls() + # The straight-line requirement stays for a stage with no block graph (a unit probe that skips translate()). + probe = G.Stage.__new__(G.Stage) + probe.kind, probe.lines, probe.sym, probe.masks = 'ps', [], {}, set() + probe.used_s, probe.used_v, probe.uniform_v, probe.varying_s = set(), set(), set(), set() + probe.scc_uniform, probe.has_branches, probe.ins = True, True, [] + try: + probe.one('v_writelane_b32', 'v_writelane_b32 v10, s0, 3') + reason = None + except G.Unsupported as error: + reason = str(error) + check('a stage with branches and no block graph keeps the straight-line refusal (%s)' % reason, + reason == 'v_writelane_b32 needs straight-line code to prove write-before-read') + # The whole pixel stage: the slot is declared once before the blocks and assigned on each arm. + from startup_image_3d_check import VS_WORDS, root_blob + text = ACCEPTED['two arms of a uniform branch, each writing a different constant'][0].replace( + 'v_mov_b32 v1, s1', 'v_mov_b32 v1, s1\nexp mrt0 v1, v1, v1, v1 done vm') + refusals = [] + ps = G.Pipeline(VS_WORDS, b'', root_blob(), refusals=refusals, decoded={'ps': program(text)}).hlsl_ps() + want = [' uint sp10_3 = 0;', ' if (pc == 1) {', ' sp10_3 = 0x00000007u;', ' if (pc == 2) {', + ' sp10_3 = 0x00000009u;', ' if (pc == 3) {', ' s1 = sp10_3;'] + lines = ps.splitlines() + at = [lines.index(line) if line in lines else -1 for line in want] + check('pixel stage: slot declared once, assigned on both arms, read after the join', + not refusals and -1 not in at and at == sorted(at) and ps.count('uint sp10_3') == 1, '%s\n%s' % (refusals, ps)) + for label, (old, new) in MUTATIONS.items(): + red = controls(mutated(old, new), quiet=True) + check('mutation "%s" turns %d control(s) red: %s' % (label, len(red), red), bool(red)) + if failures: + print('FAIL') + for text in failures: + print(' ' + text) + sys.exit(1) + print('PASS') + + +if __name__ == '__main__': + main() diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 99b56a8d9..925ca2ffb 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -2468,10 +2468,12 @@ def joined_registers(self, with_cfg=False): With ``with_cfg=True``, returns ``(joined, forward_splits, div_targets)`` where ``forward_splits`` keeps only writes on non-dominating forward arms between a target's dominators and the target (excluding loop back edges) and ``div_targets`` maps each ``s_cbranch_*`` offset to ``(writes, affected_targets)`` inside its divergent - CFG region (between the branch and its immediate post-dominator, or over the loop range for a backward edge).""" + CFG region (between the branch and its immediate post-dominator, or over the loop range for a backward edge). + A fourth item, ``(bounds, block_of, succ, div_blocks)``, is the block graph and that region's blocks per + ``s_cbranch_*`` offset, for the spill-slot proof (spill_reaching).""" ins = self.ins if not ins: - return ({}, {}, {}) if with_cfg else {} + return ({}, {}, {}, ([], {}, [], {})) if with_cfg else {} index = {off: i for i, (off, *_) in enumerate(ins)} calculated = getattr(self, 'calculated_pc', {}) # unit probes build a Stage without translate() branch = lambda name: name.startswith('s_cbranch') or name in ('s_branch', 's_setpc_b64') @@ -2557,7 +2559,7 @@ def joined_registers(self, with_cfg=False): new = {b} | set.intersection(*(pdom[s] for s in succ[b])) if new != pdom[b]: pdom[b], changed = new, True - div_targets = {} + div_targets, div_blocks = {}, {} for b, (lo, hi) in enumerate(bounds): off, _n, name, asm = ins[hi - 1] if not name.startswith('s_cbranch'): @@ -2570,6 +2572,7 @@ def joined_registers(self, with_cfg=False): loop_blks = range(min(t_blk, b), b + 1) regs = set().union(*(writes[w] for w in loop_blks)) affected = {off_of[w] for w in loop_blks} & all_targets + div_blocks[off] = set(loop_blks) else: stop = pdom[b] - {b} ipd = max(stop, key=lambda x: len(pdom[x])) if stop else None @@ -2582,9 +2585,10 @@ def joined_registers(self, with_cfg=False): dtodo += succ[w] regs = set().union(*(writes[w] for w in div)) if div else set() affected = ({off_of[w] for w in div} | ({off_of[ipd]} if ipd is not None else set())) & all_targets + div_blocks[off] = div div_targets[off] = (regs, affected) self.flow = (index, block_of, succ, dom, writes, {}) - return joined, forward_splits, div_targets + return joined, forward_splits, div_targets, (bounds, block_of, succ, div_blocks) def unjoined(self, target, last_write, regs): """The registers of regs whose program-order state is not proven at a branch target. A lane-mask mark or a @@ -2657,7 +2661,8 @@ def translate(self): splits.update((self.mesh_allocation_block, self.ins[at + 2][0])) join_writes = self.join_writes(branches) refused = self.execz_refusals() if getattr(self, 'kind', None) == 'cs' else {} # probes skip __init__ - joined, forward_splits, div_targets = self.joined_registers(with_cfg=True) + joined, forward_splits, div_targets, self.spill_cfg = self.joined_registers(with_cfg=True) + self.spill_reach = self.spill_reaching(self.spill_cfg) init_sym = dict(self.sym) init_exec_known = getattr(self, 'exec_known', True) init_wqm_exec = getattr(self, 'wqm_exec', False) @@ -2720,6 +2725,8 @@ def translate(self): } self.descriptor_block_first = 0 self.uniform_expr = {} # proven VGPR -> uniform HLSL expression over scalars that defined it + self.uniform_branches = set() # s_cbranch_* offsets proven uniform in this pass (spill-slot proof) + self.spill_writes = {} # instruction index of a v_writelane_b32 translated in this pass -> (sym, uniform) self.heap_index = {} # SGPR -> what its word is for a resource-heap s_load (see heap_record) self.heap_index_was = {} # the marks the current instruction's destinations held before it self.since_join = None # SGPRs proven uniform since the last branch target (None: none reached) @@ -2869,6 +2876,8 @@ def translate(self): if not vcc_branches[off] <= uniform_vcc_compares: raise Unsupported('slot 57 mesh: %s on a wave-wide condition is not covered' % name) cond_uniform = True + if cond_uniform: + self.uniform_branches.add(off) if not cond_uniform: # Divergent CF: later SampleBias / CalculateLevelOfDetail would see uneven quads. self.uniform_cf = False @@ -6136,8 +6145,82 @@ def op_v_readfirstlane_b32(self, ops, mods): # AMDGPU spill lowering). Both ignore EXEC. With a constant k and a VGPR that no other instruction # touches, vN is only a table of scalar slots, so one scalar variable per (vN, k) is an exact model # and no other lane is ever read. Anything else keeps the one-lane model out of reach and is refused. + # + # With branches the slot variable is assigned on the pixel's own path, while the hardware slot holds the last + # write on the wave's path. The two paths differ only inside the region of a branch not proven uniform (an + # s_cbranch_execz or _vccz the pixel takes alone, or an SCC branch on varying data), where the wave also runs + # the blocks this pixel skips. spill_reaching gives the writes that can supply a read, written on every path. + # One write: every path into the read ran it, so the slot is one more scalar register; it is accepted unless + # the write lies in such a region that the read is outside (a loop or arm the wave can run after this pixel + # left it). Several writes: the value is chosen by the path, so every write must lie outside every such region; + # the reload then keeps a constant only if all of them stored it, and is not claimed uniform. SPILL_LANES = 32 + def spill_reaching(self, cfg): + """Instruction index of each v_readlane_b32 -> the v_writelane_b32 indices that can supply its (VGPR, lane), or + None when some path from the entry reaches it with none. Forward must-dataflow over the blocks: a slot is + written at a join only if it is written on every incoming edge (intersection) and the writes that can supply + it are the union over those edges, iterated to a fixed point so a later write in a loop body reaches the loop + head through the back edge.""" + bounds, _, succ, _ = cfg + lane_ops = {} + for i, (_, _, name, asm) in enumerate(self.ins): + base = re.sub(r'_e(32|64)$', '', name) + ops = parse(asm)[1] if base in ('v_writelane_b32', 'v_readlane_b32') else () + if len(ops) == 3: + try: + lane = int(ops[2], 0) # 3 and 0x3 are one slot + except ValueError: + lane = ops[2] # an SGPR lane, refused by spill_operands + lane_ops[i] = (base == 'v_writelane_b32', ops[0 if base == 'v_writelane_b32' else 1], lane) + into = [{}] + [None] * (len(bounds) - 1) # None: no path reaches the block yet + reach = {} + changed = True + while changed: + changed = False + for b, (lo, hi) in enumerate(bounds): + if into[b] is None: + continue + state = dict(into[b]) + for i in range(lo, hi): + if i in lane_ops: + write, vreg, lane = lane_ops[i] + if write: + state[vreg, lane] = frozenset([i]) + else: + reach[i] = state.get((vreg, lane)) + for t in succ[b]: + new = state if into[t] is None else {k: into[t][k] | state[k] for k in into[t].keys() & state.keys()} + if new != into[t]: + into[t], changed = new, True + return reach + + def spill_join(self, n, lane): + """(sym, uniform) of the slot a v_readlane_b32 reads in a program with branches, or a refusal naming what + failed (see the comment above SPILL_LANES).""" + i = self.descriptor_instruction_index + writes = self.spill_reach.get(i) + if writes is None: + raise Unsupported('v_readlane_b32 reads v%d lane %d with no v_writelane_b32 of it on some path' % (n, lane)) + if max(writes) > i: + raise Unsupported('v_readlane_b32 reads v%d lane %d written later in a loop (loop-carried)' % (n, lane)) + if any(w not in self.spill_writes for w in writes): + raise Unsupported('v_readlane_b32 reads v%d lane %d from a v_writelane_b32 that was not translated' % (n, lane)) + _, block_of, _, div_blocks = self.spill_cfg + here = block_of[i] + for off, blocks in sorted(div_blocks.items()): + if off in self.uniform_branches or not any(block_of[w] in blocks for w in writes): + continue + if len(writes) > 1: + raise Unsupported('v_readlane_b32 joins %d writes of v%d lane %d, one inside the region of the branch at ' + '%#x, which is not proven uniform' % (len(writes), n, lane, off)) + if here not in blocks: + raise Unsupported('v_readlane_b32 reads v%d lane %d outside the region of the branch at %#x that writes ' + 'it, which is not proven uniform' % (n, lane, off)) + stored = [self.spill_writes[w] for w in sorted(writes)] + sym = stored[0][0] if all(s == stored[0][0] for s, _ in stored) else None + return sym, len(stored) == 1 and stored[0][1] + def spill_operands(self, name, ops, mods): if mods or len(ops) != 3: raise Unsupported('%s with modifiers or %d operands' % (name, len(ops))) @@ -6154,7 +6237,8 @@ def spill_operands(self, name, ops, mods): raise Unsupported('%s lane %d outside 0..%d' % (name, lane, self.SPILL_LANES - 1)) if getattr(self, 'kind', None) != 'ps': raise Unsupported('%s is lowered in pixel stages only' % name) - if getattr(self, 'has_branches', True) or not self.tracks_uniformity(): + if not self.tracks_uniformity() or (getattr(self, 'has_branches', True) and + getattr(self, 'spill_reach', None) is None): raise Unsupported('%s needs straight-line code to prove write-before-read' % name) self.require_spill_only(vreg[1], name) return vreg[1], sreg, lane @@ -6185,6 +6269,8 @@ def op_v_writelane_b32(self, ops, mods): uniform = self.uniform_source(ops[1]) slots = self.__dict__.setdefault('spill_slots', {}) slots[(n, lane)] = (sym, uniform) + if getattr(self, 'spill_reach', None) is not None: + self.spill_writes[self.descriptor_instruction_index] = (sym, uniform) self.emit('sp%d_%d = %s;' % (n, lane, value)) def op_v_readlane_b32(self, ops, mods): @@ -6193,10 +6279,13 @@ def op_v_readlane_b32(self, ops, mods): n, dst, lane = self.spill_operands('v_readlane_b32', ops, mods) if dst is None: raise Unsupported('v_readlane_b32 requires an SGPR destination') - slot = getattr(self, 'spill_slots', {}).get((n, lane)) - if slot is None: - raise Unsupported('v_readlane_b32 reads v%d lane %d before any v_writelane_b32 wrote it' % (n, lane)) - sym, uniform = slot + if getattr(self, 'has_branches', False): + sym, uniform = self.spill_join(n, lane) + else: + slot = getattr(self, 'spill_slots', {}).get((n, lane)) + if slot is None: + raise Unsupported('v_readlane_b32 reads v%d lane %d before any v_writelane_b32 wrote it' % (n, lane)) + sym, uniform = slot self.set_s(dst[1], 'sp%d_%d' % (n, lane), sym=sym, uniform=uniform) def op_v_mov_b32(self, ops, mods): From fa189d2efb1c856c9aec589ac74a4e09269f0278 Mon Sep 17 00:00:00 2001 From: archielcqp-a11y <307535386+archielcqp-a11y@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:29:50 -0500 Subject: [PATCH 076/240] compute: lower the d16 descriptor-format buffer loads (#2165) buffer_load_format_d16_{x,xy,xyz,xyzw} now use the descriptor-format decoder, with the same validity rule and refusal. Two 16-bit channels pack per word, x low. The format's type decides the value. FLOAT16 formats give their stored halves. UNORM and SNORM16 give binary16, rounded to nearest even by long division with denormals kept. 16-bit UINT and SINT give the 16-bit integer, not a float. 32-bit formats have no d16 rule here and are invalid. An odd count leaves the last word low-16 only: it reaches a store or an ALU operand through v_and_b32 0xffff, as for the caller-format D16 reads. A second fixture makes ten d16 loads over the same t0 words. It compares all 320 words for one and two groups on WARP and hardware. Three invalid-format runs must leave u0 unwritten. Seven wrong references and nine mutated sources must fail, among them integer-as-float, truncated or flushed binary16, and swapped packing. LLVM 15 assembles both fixtures and the round trip matches. Refs #2022 (item A, d16 follow-up to the format decoder) AI-assisted (Claude Code); reviewed and run locally. Co-authored-by: Claude Opus 5.5 Co-authored-by: tedin7 --- CMakeLists.txt | 5 + README.md | 2 +- docs/experiments.md | 30 ++- tests/compute_load_format_check.py | 361 +++++++++++++++++++++-------- tools/compute_store_aot.py | 84 +++++-- 5 files changed, 362 insertions(+), 120 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 23110dc47..ea4632950 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -10000,6 +10000,11 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(compute_store_aot_descriptor_load_format_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + add_test(NAME compute_store_aot_descriptor_load_format_d16_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/compute_load_format_check.py" draw-d16 "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(compute_store_aot_descriptor_load_format_d16_${adapter} PROPERTIES TIMEOUT 120 + SKIP_RETURN_CODE 77) add_test(NAME compute_store_aot_heap_view_load_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/compute_heap_view_check.py" draw "${DXC_EXECUTABLE}" "$" ${adapter}) diff --git a/README.md b/README.md index a82343fc1..b0e70f346 100644 --- a/README.md +++ b/README.md @@ -168,7 +168,7 @@ The control-flow CPU translator supports [source-built string memory transfers]( | gfx1030 formatted UINT buffer reads | Lower [indexed `buffer_load_format_*` with caller-declared RGBA32 UINT](docs/experiments.md#indexed-gfx1030-formatted-uint-buffer-reads) and verify one to four channels in the UAV readback. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_format_'` | | gfx1030 formatted D16 UINT writes | Lower [indexed packed `buffer_store_format_d16_x/xy/xyzw`](docs/experiments.md#indexed-gfx1030-formatted-d16-uint-buffer-writes) and verify the untouched halfword and record padding. The experimental `xyz` form requires a caller-verified W-preservation contract. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_store_format_'` | | gfx1030 formatted UINT buffer writes | Lower [indexed `buffer_store_format_*` with matching caller-declared UINT texels](docs/experiments.md#indexed-gfx1030-formatted-uint-buffer-writes) and compare full UAV readback with a CPU reference. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_store_format_'` | -| Descriptor-format buffer loads | Lower [gfx1013 indexed `buffer_load_format_x/xy/xyz/xyzw`](docs/experiments.md#descriptor-format-buffer-loads), reading the GFX10 or legacy format from V# word 3 at run time with integer-exact conversions. An unsupported format or opcode width leaves the output unwritten. The descriptor itself is still static. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_descriptor_load_format_'` | +| Descriptor-format buffer loads | Lower [gfx1013 indexed `buffer_load_format_x/xy/xyz/xyzw` and the d16 forms](docs/experiments.md#descriptor-format-buffer-loads), reading the GFX10 or legacy format from V# word 3 at run time with integer-exact conversions. An unsupported format or opcode width leaves the output unwritten. The descriptor itself is still static. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_descriptor_load_format_'` | | Heap-view buffer loads | Lower [gfx1013 indexed `buffer_load_format_xy/xyzw` from a run-time view record](docs/experiments.md#heap-view-buffer-loads): base, stride, `num_records` and format come from the record at a chosen slot. An index past `num_records` reads zero; a view that is not live, a bad slot or a bad format leaves the output unwritten. The record table is a side table inside t0; the SM 6.6 heap lookup is not wired yet. | `ctest --preset dev --no-tests=error -R '^compute_(store_aot_heap_view_load_\|heap_view_controls$)'` | | Descriptor-format buffer stores | Lower [indexed `buffer_store_format_x/xy/xyz/xyzw` and the d16 forms](docs/experiments.md#descriptor-format-buffer-stores), reading the GFX10 or legacy format from V# word 3. Unknown formats are refused. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_descriptor_store_format_'` | | gfx1030 depth-comparison sampling | Lower [2D comparison samples with and without offsets](docs/experiments.md#gfx1030-2d-comparison-sampling). | `ctest --preset dev --no-tests=error -R '^pixel_aot_compare_sample_' -V` | diff --git a/docs/experiments.md b/docs/experiments.md index d8eca29e6..458a94d47 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -6226,7 +6226,6 @@ The gfx1013 compute store profile lowers `buffer_load_format_x`, `_xy`, `_xyz` a This is the format decoder of item A of #2022. The descriptor still comes from the static table offset (`--source-descriptor`, `--source-stride`). Taking the descriptor from a run-time view record is the [next slice](#heap-view-buffer-loads), so this alone does not count as coverage of any application dispatch. The address is `idxen` only and 4-byte aligned, and four bytes per opcode channel must fit inside the stated stride. These stay refused with this flag: -- the `d16_` forms; - `offen`; - gfx1030; - `--source-format`. @@ -6299,6 +6298,35 @@ one D3D12 device, root signature and pipeline. Each case gets fresh buffers, sub compares all 320 words after the fence. The renderer reports `pass`, `mismatch` or `error` for each case and exits with status 1 if any case fails. The eleven shader mutations still compile and dispatch separately. +#### d16 forms + +`buffer_load_format_d16_x`, `_xy`, `_xyz` and `_xyzw` use the same format word, validity rule and refusal, and pack two 16-bit channels per result word, x in the low half. The format's type decides the 16-bit value: +- **FLOAT16 formats:** the stored halves, unchanged. +- **UNORM and SNORM16:** binary16 of the value above (`x / (2^n - 1)` or `max(x / 32767, -1)`), rounded to nearest even by long division. Binary16 denormals are kept, so `1/65535` is `0x0100`. +- **16-bit UINT and SINT:** the 16-bit integer, not a float. +- **32-bit formats:** no d16 rule is established here, so `32_UINT` and `32_FLOAT` in one to four channels are invalid under d16 and publish nothing. + +Whether the RDNA format unit rounds the same way, or keeps binary16 denormals, is not verified. + +An odd channel count leaves the high half of the last result word undefined. That word is low-16 only: it reaches a whole-word store or an ALU operand only through `v_and_b32 0xffff`, as for the existing caller-format D16 reads. + +The d16 fixture makes ten loads over the same t0 words, one per format with a d16 rule, and stores them in a 64-byte u0 record. The checks: +- **Readback:** WARP and the hardware adapter compare all 320 words for one group and for two. +- **Invalid formats:** three runs each make one load invalid, and each must leave u0 unwritten. They use `32_32_FLOAT` under `d16_xy`, `16_16_UNORM` under `d16_x`, and `8_SNORM`. +- **Wrong references:** on the two-group run, each of these must fail at its first differing word: + - truncated binary16, and flushed binary16 denormals; + - 16-bit UINT converted like 16-bit UNORM, and 16-bit SINT converted like 16-bit SNORM; + - halves packed high first; + - the legacy word ignored; + - the neighbouring thread's element. +- **Mutated HLSL:** each of these must also fail: + - a binary16 ratio that never rounds up, and flushed binary16 denormals; + - the two integer formats converted; + - halves packed high first, and the SNORM16 half sign dropped; + - the binary32 conversion used under d16; + - on the invalid runs, a 32-bit format accepted under d16, and the refusal removed. +- **Translation controls:** they reject the odd half when the mask is missing, when an ALU operation uses it, and when the destination range is too wide. With the d16 flag dropped, the low-half marking removed, or 32-bit formats given a d16 arm, they fail. + ```powershell cmake --build --preset dev --target offscreen_check ctest --preset dev --no-tests=error -R '^compute_(store_aot_descriptor_load_format_|load_format_controls$)' -V diff --git a/tests/compute_load_format_check.py b/tests/compute_load_format_check.py index 90ba550ee..ddc297c86 100644 --- a/tests/compute_load_format_check.py +++ b/tests/compute_load_format_check.py @@ -2,6 +2,7 @@ The t0 format is V# word 3, read from a constant word at run time (--load-format-constant), as the descriptor-format stores read theirs. The case file supplies the t0 words, so each format sees chosen edge values. +Two suites share the t0 layout: binary32 results (draw) and d16 results packed two per word (draw-d16). """ from concurrent.futures import ThreadPoolExecutor from fractions import Fraction @@ -21,6 +22,7 @@ GROUP = (4, 1, 1) SOURCE_STRIDE = 80 OUTPUT_STRIDE = 120 +D16_STRIDE = 64 THREADS = 8 # opcode suffix, t0 byte offset, GFX10 format code, legacy word 3, u0 byte offset of the results. LOADS = ( @@ -39,7 +41,20 @@ ("x", 68, 20, False, 108), # 32_UINT ("xy", 72, 64, False, 112), # 32_32_FLOAT ) -# Format words that make one load invalid: load index, V# word 3. Each must leave every u0 word unwritten. +# The same t0 fields through the d16 opcodes. Every format with a d16 rule appears once. +D16_LOADS = ( + ("d16_xyzw", 0, 56, False, 0), # 8_8_8_8_UNORM + ("d16_xy", 4, 23, False, 8), # 16_16_UNORM + ("d16_xyzw", 8, 50, False, 12), # 2_10_10_10_UNORM + ("d16_xy", 12, 29, True, 20), # 16_16_FLOAT, legacy + ("d16_xyzw", 16, 71, False, 24), # 16_16_16_16_FLOAT + ("d16_x", 24, 7, False, 32), # 16_UNORM + ("d16_x", 28, 8, False, 36), # 16_SNORM + ("d16_x", 32, 11, False, 40), # 16_UINT + ("d16_x", 36, 12, False, 44), # 16_SINT + ("d16_x", 40, 13, False, 48), # 16_FLOAT +) +# Format words that make one load invalid: label, load index, V# word 3. Each must leave every u0 word unwritten. IDENTITY_32_UINT = aot.descriptor_format_word(20) INVALID = ( ("unknown format 8_SNORM", 0, aot.DESCRIPTOR_GFX10_FIXED | (2 << 12)), @@ -49,6 +64,11 @@ # 10_10_10_2_UNORM has a 2-bit x in bits 1:0; only the 2_10_10_10 layout is handled. ("10_10_10_2_UNORM", 2, aot.DESCRIPTOR_GFX10_FIXED | (44 << 12)), ) +D16_INVALID = ( + ("d16_xy on 32_32_FLOAT", 1, aot.descriptor_format_word(64)), + ("d16_x on 16_16_UNORM", 5, aot.descriptor_format_word(23)), + ("unknown format 8_SNORM", 0, aot.DESCRIPTOR_GFX10_FIXED | (2 << 12)), +) # Thread 0-3 t0 words: edge values per field. Threads 4-7 are pseudo-random. CURATED = ( (0x8001ff00, 0x0001ffff, 0xa00007ff, 0x80000001, 0xfc007c00, 0x7bff7e01, 0xdeadffff, 0x12348000, 0xabcdffff, @@ -79,6 +99,15 @@ def source_words(): return words + [base.SENTINEL] * (320 - len(words)) +def _exponent(value): + exponent = value.numerator.bit_length() - value.denominator.bit_length() + while value >= Fraction(2) ** exponent * 2: + exponent += 1 + while value < Fraction(2) ** exponent: + exponent -= 1 + return exponent + + def f32_bits(value): """binary32 bits of a Fraction or exact value, rounded to nearest even (no double rounding).""" value = Fraction(value) @@ -86,11 +115,7 @@ def f32_bits(value): return 0 sign = 0x80000000 if value < 0 else 0 value = abs(value) - exponent = value.numerator.bit_length() - value.denominator.bit_length() - while value >= Fraction(2) ** exponent * 2: - exponent += 1 - while value < Fraction(2) ** exponent: - exponent -= 1 + exponent = _exponent(value) assert -126 <= exponent < 128, value mantissa = round(value / Fraction(2) ** (exponent - 23)) if mantissa == 1 << 24: @@ -98,6 +123,25 @@ def f32_bits(value): return sign | ((exponent + 127) << 23) | (mantissa - (1 << 23)) +def f16_bits(value, *, truncate=False, flush=False): + """binary16 bits of a Fraction in [-1, 1], rounded to nearest even, denormals kept (IEEE 754 rounding).""" + value = Fraction(value) + if value == 0: + return 0 + sign = 0x8000 if value < 0 else 0 + value = abs(value) + exponent = _exponent(value) + rounding = (lambda q: int(q)) if truncate else round + if exponent < -14: + if flush: + return sign + return sign | rounding(value / Fraction(2) ** -24) # a carry to 0x400 is the smallest normal + mantissa = rounding(value / Fraction(2) ** (exponent - 10)) + if mantissa == 1 << 11: + mantissa, exponent = 1 << 10, exponent + 1 + return sign | ((exponent + 15) << 10) | (mantissa - (1 << 10)) + + def half_to_f32(half): """IEEE 754 widening of binary16: exact for numbers; a NaN keeps its payload (IEEE 754-2008 6.2.3).""" sign, exponent, mantissa = (half >> 15) & 1, (half >> 10) & 31, half & 0x3ff @@ -126,7 +170,7 @@ def snorm16(half, *, clamp=True): def load(code, words, channels, *, wrong=()): - """Independent reference for one load: the definition of each format, from the t0 words at its offset. + """Independent reference for one binary32 load: the definition of each format, from the t0 words at its offset. The profile handles an opcode that reads exactly the format's channels; anything else is a refusal. """ @@ -162,31 +206,82 @@ def load(code, words, channels, *, wrong=()): return result[:channels] -def expected_words(groups, *, wrong=(), source=None, placeholder=None): - """u0 after a valid dispatch. placeholder=(load index, words) publishes those words for that load instead.""" - source = source or source_words() - words = [base.SENTINEL] * 320 - for thread in range(GROUP[0] * groups): - index = thread + 1 if "neighbour element" in wrong else thread - element = source[index * SOURCE_STRIDE // 4:(index + 1) * SOURCE_STRIDE // 4] - for number, (suffix, src, code, legacy, dst) in enumerate(LOADS): - if placeholder and placeholder[0] == number: - values = placeholder[1](element[src // 4:]) - elif legacy and "legacy ignored" in wrong: - values = [0] * len(suffix) - else: - values = load(code, element[src // 4:], len(suffix), wrong=wrong) - start = (thread * OUTPUT_STRIDE + dst) // 4 - words[start:start + len(values)] = values - return words - +def load_d16(code, words, channels, *, wrong=()): + """Independent reference for one d16 load: binary16 for float-type formats, the 16-bit integer for UINT and + SINT, packed two per word with x low. An odd final half is stored masked to its low 16 bits.""" + _code, kind, format_channels = aot.decode_buffer_descriptor_format(aot.descriptor_format_word(code)) + assert channels == format_channels and kind != "raw32", (code, channels) + w = words[0] + rounding = dict(truncate="half truncated" in wrong, flush="flush halves" in wrong) -def constants(): - words = [aot.descriptor_format_word(code, legacy=legacy) for _s, _o, code, legacy, _d in LOADS] - return words + [0] * (16 - len(words)) + def ratio(x, d): + return f16_bits(Fraction(x, d), **rounding) + def snorm(h): + value = h - 0x10000 if h & 0x8000 else h + return 0xbc00 if value <= -32767 else f16_bits(Fraction(value, 32767), **rounding) -def program(): + if kind == "unorm8": + halves = [ratio((w >> (8 * i)) & 0xff, 255) for i in range(4)] + elif kind == "unorm16x2": + halves = [ratio(w & 0xffff, 65535), ratio(w >> 16, 65535)] + elif kind == "unorm10": + halves = [ratio((w >> (10 * i)) & 0x3ff, 1023) for i in range(3)] + [ratio(w >> 30, 3)] + elif kind == "f16x2": + halves = [w & 0xffff, w >> 16] + elif kind == "f16x4": + halves = [w & 0xffff, w >> 16, words[1] & 0xffff, words[1] >> 16] + elif kind == "unorm16": + halves = [ratio(w & 0xffff, 65535)] + elif kind == "snorm16": + halves = [snorm(w & 0xffff)] + elif kind == "uint16": + halves = [ratio(w & 0xffff, 65535) if "integer as unorm" in wrong else w & 0xffff] + elif kind == "sint16": + halves = [snorm(w & 0xffff) if "integer as snorm" in wrong else w & 0xffff] + else: + halves = [w & 0xffff] + if "pack high first" in wrong: + halves = [h for pair in zip(halves[1::2], halves[0::2]) for h in pair] + halves[len(halves) & ~1:] + return [halves[i] | ((halves[i + 1] if i + 1 < len(halves) else 0) << 16) for i in range(0, len(halves), 2)] + + +class Suite: + def __init__(self, name, loads, stride, model, invalid, wrong, mutations): + self.name, self.loads, self.stride, self.model = name, loads, stride, model + self.invalid, self.wrong, self.mutations = invalid, wrong, mutations + self.lines, self.binding = program(loads, stride) + + def expected(self, groups, *, wrong=(), placeholder=None): + """u0 after a valid dispatch. placeholder=(load index, function) publishes other words for that load.""" + source = source_words() + words = [base.SENTINEL] * 320 + for thread in range(GROUP[0] * groups): + index = thread + 1 if "neighbour element" in wrong else thread + element = source[index * SOURCE_STRIDE // 4:(index + 1) * SOURCE_STRIDE // 4] + for number, (suffix, src, code, legacy, dst) in enumerate(self.loads): + channels = len(suffix.removeprefix("d16_")) + if placeholder and placeholder[0] == number: + values = placeholder[1](element[src // 4:]) + elif legacy and "legacy ignored" in wrong: + values = [0] * registers(suffix) + else: + values = self.model(code, element[src // 4:], channels, wrong=wrong) + start = (thread * self.stride + dst) // 4 + words[start:start + len(values)] = values + return words + + def constants(self): + words = [aot.descriptor_format_word(code, legacy=legacy) for _s, _o, code, legacy, _d in self.loads] + return words + [0] * (16 - len(words)) + + +def registers(suffix): + channels = len(suffix.removeprefix("d16_")) + return (channels + 1) // 2 if suffix.startswith("d16_") else channels + + +def program(loads, stride): lines = [ "s_mov_b32 s12, s7", "s_mov_b32 s13, 0", "s_load_dwordx4 s[20:23], s[12:13], 0x30", @@ -200,36 +295,35 @@ def program(): "s_buffer_load_dwordx2 s[36:37], s[16:19], 0x30", "s_waitcnt lgkmcnt(0)", ] - reg, stores = 10, [] - for suffix, src, _code, _legacy, dst in LOADS: - n = len(suffix) + reg, masks, stores = 10, [], [] + for suffix, src, _code, _legacy, dst in loads: + n = registers(suffix) regs = f"v{reg}" if n == 1 else f"v[{reg}:{reg + n - 1}]" lines.append(f"buffer_load_format_{suffix} {regs}, v8, s[40:43], 0 idxen" + (f" offset:{src}" if src else "")) + if suffix.startswith("d16_") and len(suffix) % 2: + # An odd d16 count leaves the high half of the last word undefined; keep only the low half. + last = reg + n - 1 + masks.append(f"v_and_b32_e32 v{last}, 0xffff, v{last}") width = "" if n == 1 else f"x{n}" stores.append(f"buffer_store_dword{width} {regs}, v8, s[20:23], 0 idxen" + (f" offset:{dst}" if dst else "")) reg += n - lines += ["s_waitcnt vmcnt(0)", *stores, "s_endpgm"] + lines += ["s_waitcnt vmcnt(0)", *masks, *stores, "s_endpgm"] binding = dict(table_reg=7, descriptor_offset=0x30, constant_descriptor=0x40, source_descriptor=0x50, - source_stride=SOURCE_STRIDE, group_reg=11, stride=OUTPUT_STRIDE, cpu="gfx1013", - load_format_constant=tuple(range(len(LOADS)))) + source_stride=SOURCE_STRIDE, group_reg=11, stride=stride, cpu="gfx1013", + load_format_constant=tuple(range(len(loads)))) return lines, binding -LINES, BINDING = program() -FIRST_LOAD = (" bool format_valid_0;\n" - " uint4 format_load_0 = load_descriptor_format(params[0].x, tid.x * 80u + 0u, 4u, format_valid_0);") -FIRST_STORE = (" outputData.Store4(tid.x * 120u + 0u, uint4(format_load_0.x, format_load_0.y, format_load_0.z, " - "format_load_0.w));") -LAST_LOAD = " uint4 format_load_13 = load_descriptor_format(params[3].y, tid.x * 80u + 72u, 2u, format_valid_13);" -REFUSE = " if (!(" + " && ".join(f"format_valid_{i}" for i in range(len(LOADS))) + ")) return;" -WRONG = (("UNORM divided by 2^n", ("unorm divisor",)), ("UNORM truncated", ("unorm truncated",)), - ("SNORM without the clamp", ("snorm unclamped",)), ("SINT16 zero-extended", ("sint zero-extended",)), - ("FLOAT16 halves swapped", ("swap halves",)), ("FLOAT16 denormals flushed", ("flush halves",)), - ("legacy format ignored", ("legacy ignored",)), ("neighbouring element", ("neighbour element",))) # Independent launches (the mutation ones also compile a mutated source); the Win2025 slots have 11 vCPUs. LAUNCH_THREADS = 6 FIXED = f"{aot.DESCRIPTOR_LEGACY_FIXED:#x}u" -# label, old, new, and the run it must fail: None for the valid two-group run, else an INVALID index. + + +def refuse_line(count): + return " if (!(" + " && ".join(f"format_valid_{i}" for i in range(count)) + ")) return;" + + +# label, old, new, and the run it must fail: None for the valid two-group run, else an invalid-run index. MUTATIONS = ( ("ratio never rounds up", " if ((bits & 1u) != 0u && (r != 0u || (result & 1u) != 0u)) ++result;\n", "", None), ("denormal halves flushed", " if (m == 0u) return sign;\n", " return sign;\n", None), @@ -239,76 +333,139 @@ def program(): ("SINT16 zero-extended", "(uint)((int)(raw.x << 16u) >> 16u)", "(raw.x & 0xffffu)", None), ("legacy fixed bits ignored", f"}} else if (fixedBits == {FIXED}) {{", "} else if (false) {", None), ("format word from params[0].y", "load_descriptor_format(params[0].x,", "load_descriptor_format(params[0].y,", None), - ("invalid loads still store", REFUSE, "", 0), + ("invalid loads still store", refuse_line(len(LOADS)), "", 0), ("narrower opcode accepted", "format == 77u) && channels == 4u)", "format == 77u) && channels <= 4u)", 1), ("wider opcode accepted", "format == 22u) && channels == 1u)", "format == 22u) && channels >= 1u)", 2), ("selectors ignored", f"uint fixedBits = formatWord & {aot.DESCRIPTOR_FIXED_MASK:#x}u;", f"uint fixedBits = formatWord & {aot.DESCRIPTOR_FIXED_MASK & ~0xfff:#x}u | 0xfacu;", 3), ) +D16_MUTATIONS = ( + ("binary16 ratio never rounds up", + " if (roundBit != 0u && (sticky || (result & 1u) != 0u)) ++result;\n", "", None), + ("binary16 denormals flushed", " : (f >> shift);\n", " : 0u;\n", None), + ("16_UINT converted like 16_UNORM", "(format == 11u) && channels == 1u) { h.x = raw.x & 0xffffu;", + "(format == 11u) && channels == 1u) { h.x = descriptor_ratio16(raw.x & 0xffffu, 65535u);", None), + ("16_SINT converted like 16_SNORM", "(format == 12u) && channels == 1u) { h.x = raw.x & 0xffffu;", + "(format == 12u) && channels == 1u) { h.x = descriptor_snorm16_half(raw.x & 0xffffu);", None), + ("halves packed high first", "r = uint4(h.x | (h.y << 16u), h.z | (h.w << 16u), 0u, 0u);", + "r = uint4(h.y | (h.x << 16u), h.w | (h.z << 16u), 0u, 0u);", None), + ("SNORM16 half sign dropped", "0x8000u | descriptor_ratio16(", "descriptor_ratio16(", None), + ("binary32 conversion under d16", "(d16 != 0u && (format == 23u)", "(d16 == 0u && (format == 23u)", None), + ("32-bit format accepted under d16", "(d16 == 0u && (format == 62u || format == 64u) && channels == 2u)", + "(true && (format == 62u || format == 64u) && channels == 2u)", 0), + ("invalid loads still store", refuse_line(len(D16_LOADS)), "", 2), +) +SUITES = { + "draw": Suite(NAME, LOADS, OUTPUT_STRIDE, load, INVALID, ( + ("UNORM divided by 2^n", ("unorm divisor",)), ("UNORM truncated", ("unorm truncated",)), + ("SNORM without the clamp", ("snorm unclamped",)), ("SINT16 zero-extended", ("sint zero-extended",)), + ("FLOAT16 halves swapped", ("swap halves",)), ("FLOAT16 denormals flushed", ("flush halves",)), + ("legacy format ignored", ("legacy ignored",)), ("neighbouring element", ("neighbour element",))), + MUTATIONS), + "draw-d16": Suite(NAME + "_d16", D16_LOADS, D16_STRIDE, load_d16, D16_INVALID, ( + ("binary16 truncated", ("half truncated",)), ("binary16 denormals flushed", ("flush halves",)), + ("16_UINT converted like 16_UNORM", ("integer as unorm",)), + ("16_SINT converted like 16_SNORM", ("integer as snorm",)), + ("halves packed high first", ("pack high first",)), ("legacy format ignored", ("legacy ignored",)), + ("neighbouring element", ("neighbour element",))), + D16_MUTATIONS), +} +LINES, BINDING = SUITES["draw"].lines, SUITES["draw"].binding +D16_LINES, D16_BINDING = SUITES["draw-d16"].lines, SUITES["draw-d16"].binding +FIRST_LOAD = (" bool format_valid_0;\n" + " uint4 format_load_0 = load_descriptor_format(params[0].x, tid.x * 80u + 0u, 4u, 0u, format_valid_0);") +FIRST_STORE = (" outputData.Store4(tid.x * 120u + 0u, uint4(format_load_0.x, format_load_0.y, format_load_0.z, " + "format_load_0.w));") +LAST_LOAD = (" uint4 format_load_13 = load_descriptor_format(params[3].y, tid.x * 80u + 72u, 2u, 0u, " + "format_valid_13);") +D16_FIRST_LOAD = " uint4 format_load_0 = load_descriptor_format(params[0].x, tid.x * 80u + 0u, 4u, 1u, format_valid_0);" +D16_ODD_STORE = " outputData.Store(tid.x * 64u + 32u, (format_load_5.x & 0xffffu));" def lower(lines=None, **binding): return aot.lower(LINES if lines is None else lines, GROUP, **(BINDING | binding)) +def lower_d16(lines=None, **binding): + return aot.lower(D16_LINES if lines is None else lines, GROUP, **(D16_BINDING | binding)) + + def controls(): """Exact staged loads and stores, model checks, then one rejection per form outside the profile.""" assert f32_bits(Fraction(1, 255)) == 0x3b808081 and f32_bits(Fraction(128, 255)) == 0x3f008081 assert unorm(1, 16) == 0x37800080 and unorm(2, 2) == 0x3f2aaaab and snorm16(0x8000) == 0xbf800000 assert snorm16(0x8000, clamp=False) == 0xbf800100 and snorm16(0xffff) == 0xb8000100 assert half_to_f32(0x0001) == 0x33800000 and half_to_f32(0x03ff) == 0x387fc000 and half_to_f32(0x7e01) == 0x7fc02000 + # binary16: 100/1023 rounds up, 1/65535 and -1/32767 are denormals, and 1/3 rounds down. + assert f16_bits(Fraction(1, 255)) == 0x1c04 and f16_bits(Fraction(128, 255)) == 0x3804 + assert f16_bits(Fraction(1, 65535)) == 0x0100 and f16_bits(Fraction(1, 3)) == 0x3555 + assert f16_bits(Fraction(100, 1023)) == 0x2e42 and f16_bits(Fraction(100, 1023), truncate=True) == 0x2e41 + assert f16_bits(Fraction(-1, 32767)) == 0x8200 and f16_bits(Fraction(1, 65535), flush=True) == 0 source = lower() lines = source.splitlines() + refuse = refuse_line(len(LOADS)) assert source.count("= load_descriptor_format(") == len(LOADS) - assert FIRST_LOAD in source and LAST_LOAD in lines and FIRST_STORE in lines and REFUSE in lines, source + assert FIRST_LOAD in source and LAST_LOAD in lines and FIRST_STORE in lines and refuse in lines, source assert "outputData.Store(tid.x * 120u + 108u, format_load_12.x);" in source assert "outputData.Store2(tid.x * 120u + 112u, uint2(format_load_13.x, format_load_13.y));" in source # Every load and the refusal come before the first store. - assert lines.index(LAST_LOAD) < lines.index(REFUSE) < lines.index(FIRST_STORE) + assert lines.index(LAST_LOAD) < lines.index(refuse) < lines.index(FIRST_STORE) assert "&& channels == 4u) {" in source and "channels <=" not in source and "valid = false;" in source # Without the load constants the profile keeps the gfx1030 caller-format path and refuses gfx1013. base.rejects("Unsupported formatted buffer read target or address mode", lower, load_format_constant=None) for _name, old_lines, old_binding in base.mubuf_format_cases(): old = aot.lower(old_lines, 32, **old_binding) assert "load_descriptor_format(" not in old and "inputData.Load" in old and " return;" not in old + # d16: the flag reaches the helper, the odd final half is masked before a whole-word store, and no 32-bit + # format has a d16 arm. + d16 = lower_d16() + assert D16_FIRST_LOAD in d16 and D16_ODD_STORE in d16 and refuse_line(len(D16_LOADS)) in d16, d16 + assert "outputData.Store2(tid.x * 64u + 0u, uint2(format_load_0.x, format_load_0.y));" in d16 + assert "(d16 != 0u && (format == 20u" not in d16 and "(d16 != 0u && (format == 56u)" in d16 xyzw = LINES[12] assert xyzw == "buffer_load_format_xyzw v[10:13], v8, s[40:43], 0 idxen", xyzw + d16x = D16_LINES[17] + assert d16x == "buffer_load_format_d16_x v18, v8, s[40:43], 0 idxen offset:24", d16x + mask = "v_and_b32_e32 v18, 0xffff, v18" wait = LINES.index("s_waitcnt lgkmcnt(0)", 7) - for message, lines_, binding in ( - ("Descriptor-format d16 loads are not lowered", - base.variant(LINES, (xyzw, "buffer_load_format_d16_xyzw v[10:11], v8, s[40:43], 0 idxen")), {}), - ("Descriptor-format d16 loads are not lowered", - base.variant(LINES, (xyzw, "buffer_load_format_d16_x v10, v8, s[40:43], 0 idxen")), {}), - ("Unsupported formatted buffer read target or address mode", + for message, function, lines_, binding in ( + # The odd d16 half is low-16 only: stored or used without the mask, it is not a known word. + ("Store data is not a known word", lower_d16, base.variant(D16_LINES, (mask, "")), {}), + ("Unverified ALU operand", lower_d16, base.variant(D16_LINES, (mask, "v_xor_b32_e32 v18, 1, v18")), {}), + ("Unverified buffer read destination", lower_d16, base.variant(D16_LINES, (d16x, d16x.replace("v18,", "v[18:19],"))), {}), + ("Unsupported formatted buffer read target or address mode", lower, base.variant(LINES, (xyzw, xyzw.replace(" idxen", " offen"))), {}), - ("Unsupported formatted buffer read target or address mode", + ("Unsupported formatted buffer read target or address mode", lower, base.variant(LINES, (xyzw, xyzw.replace(" idxen", ""))), {}), - ("Unverified read offset", base.variant(LINES, (xyzw, xyzw + " offset:2")), {}), - ("Read leaves its source element", base.variant(LINES, (xyzw, xyzw + " offset:68")), {}), - ("Unsupported compute instruction", base.variant(LINES, (xyzw, xyzw + " glc")), {}), - ("Formatted buffer load is missing a format constant", None, dict(load_format_constant=(0,))), - ("Unused buffer load format constant", None, dict(load_format_constant=tuple(range(len(LOADS) + 1)))), - ("Formatted buffer load format constant is not ready", None, + ("Unverified read offset", lower, base.variant(LINES, (xyzw, xyzw + " offset:2")), {}), + ("Read leaves its source element", lower, base.variant(LINES, (xyzw, xyzw + " offset:68")), {}), + ("Unsupported compute instruction", lower, base.variant(LINES, (xyzw, xyzw + " glc")), {}), + ("Formatted buffer load is missing a format constant", lower, None, dict(load_format_constant=(0,))), + ("Unused buffer load format constant", lower, None, dict(load_format_constant=tuple(range(len(LOADS) + 1)))), + ("Formatted buffer load format constant is not ready", lower, None, dict(load_format_constant=(15,) + BINDING["load_format_constant"][1:])), - ("Formatted buffer load format constant is not ready", LINES[:wait] + LINES[wait + 1:], {}), - ("Invalid buffer load format constant", None, dict(cpu="gfx1030")), - ("Unsupported formatted source binding", None, dict(source_format="BUF_FMT_32_32_32_32_UINT")), - ("Invalid buffer load format constant", None, dict(cpu="gfx1030", source_format="BUF_FMT_32_32_32_32_UINT")), - ("Invalid buffer load format constant", None, dict(load_format_constant=(16,))), - ("Invalid buffer load format constant", None, dict(load_format_constant=())), - ("Invalid buffer load format constant", None, dict(constant_descriptor=None)), - ("Invalid buffer load format constant", None, dict(source_stride=None)), + ("Formatted buffer load format constant is not ready", lower, LINES[:wait] + LINES[wait + 1:], {}), + ("Invalid buffer load format constant", lower, None, dict(cpu="gfx1030")), + ("Unsupported formatted source binding", lower, None, dict(source_format="BUF_FMT_32_32_32_32_UINT")), + ("Invalid buffer load format constant", lower, None, + dict(cpu="gfx1030", source_format="BUF_FMT_32_32_32_32_UINT")), + ("Invalid buffer load format constant", lower, None, dict(load_format_constant=(16,))), + ("Invalid buffer load format constant", lower, None, dict(load_format_constant=())), + ("Invalid buffer load format constant", lower, None, dict(constant_descriptor=None)), + ("Invalid buffer load format constant", lower, None, dict(source_stride=None)), # A load result is data only. - ("Unsupported store address", base.variant(LINES, (", v8, s[20:23], 0 idxen offset:16", ", v10, s[20:23], 0 idxen offset:16")), {}), + ("Unsupported store address", lower, + base.variant(LINES, (", v8, s[20:23], 0 idxen offset:16", ", v10, s[20:23], 0 idxen offset:16")), {}), ): - base.rejects(message, lower, lines_, **binding) + base.rejects(message, function, lines_, **binding) def binary(directory, assembler, objcopy, library): - """LLVM 15 assembles the fixture; lower of the disassembly and the CLI both match lower of the source.""" + """LLVM 15 assembles both fixtures; lower of the disassembly and the CLI both match lower of the source.""" controls() - base.descriptor_store_round_trip(directory, LINES, BINDING, "mc", assembler, objcopy, library) - print(f"{NAME}: llvm15_round_trip=match") + for suite in SUITES.values(): + base.descriptor_store_round_trip(directory, suite.lines, suite.binding, "mc", assembler, objcopy, library) + print(f"{NAME}: llvm15_round_trip=match ({len(SUITES)} fixtures)") return 0 @@ -342,14 +499,14 @@ def check_references(name, renderer, backend, shader, cases, *, allow_hardware_s return 0 -def draw(directory, compiler, renderer, backend): +def draw(directory, compiler, renderer, backend, suite): """Dispatch with chosen t0 words; wrong references and mutated sources must fail. The reference cases share one device and compute pipeline. Each independently compiled mutation keeps its own renderer process so compilation and readback can overlap with the reference checks. """ src, cso = directory / "load.hlsl", directory / "load.cso" - source = lower() + source = aot.lower(suite.lines, GROUP, **suite.binding) src.write_text(source, encoding="ascii") subprocess.run([compiler, "-T", "cs_6_0", "-E", "main", "-Fo", cso, src], check=True) words = source_words() @@ -358,7 +515,7 @@ def draw(directory, compiler, renderer, backend): def write_case(number, groups, reference, formats): case = directory / f"case{number}.bin" - data = (struct.pack("<321I", groups, *reference) + struct.pack("<16I", *(formats or constants())) + data = (struct.pack("<321I", groups, *reference) + struct.pack("<16I", *(formats or suite.constants())) + struct.pack("<320I", *words)) case.write_bytes(data) return case @@ -375,54 +532,54 @@ def run_mutation(number, label, case, mutated): result = subprocess.run([renderer, backend, "--compute-store-case", shader, case], capture_output=True, text=True) if result.returncode != 1 or "Compute readback differs" not in result.stderr: - raise AssertionError(f"{NAME}: mutation '{label}' escaped detection\n{result.stderr}") + raise AssertionError(f"{suite.name}: mutation '{label}' escaped detection\n{result.stderr}") for groups in (1, 2): - add_reference("dispatch", groups, expected_words(groups)) + add_reference("dispatch", groups, suite.expected(groups)) def invalid_formats(number): - formats = constants() - formats[INVALID[number][1]] = INVALID[number][2] + formats = suite.constants() + formats[suite.invalid[number][1]] = suite.invalid[number][2] return formats # Each invalid format must leave all of u0 at the sentinel, and so fail a reference that publishes - # placeholder words for that load: zeros, or the D3D (0, 0, 0, 1) fill for the wider opcode. + # placeholder words for that load. unwritten = [base.SENTINEL] * 320 - zeros = (lambda channels: (lambda words: [0] * channels)) - for number, (label, index, _word) in enumerate(INVALID): + for number, (label, index, _word) in enumerate(suite.invalid): add_reference(f"refused {label}", 2, unwritten, invalid_formats(number)) - channels = len(LOADS[index][0]) - placeholders = [("published as zeros", zeros(channels))] - if number == 2: + count = registers(suite.loads[index][0]) + placeholders = [("published as zeros", lambda words, count=count: [0] * count)] + if suite.loads is LOADS and number == 2: placeholders.append(("published with the (0, 0, 0, 1) fill", lambda words: [words[0], 0])) for what, values in placeholders: - published = expected_words(2, placeholder=(index, values)) + published = suite.expected(2, placeholder=(index, values)) add_reference(f"{label} {what}", 2, published, invalid_formats(number), diagnostic=f"word=0 expected={published[0]:08x} actual=c5c5c5c5") - expected = expected_words(2) - for label, wrong in WRONG: - reference = expected_words(2, wrong=wrong) + expected = suite.expected(2) + for label, wrong in suite.wrong: + reference = suite.expected(2, wrong=wrong) word = next((i for i, (a, b) in enumerate(zip(expected, reference)) if a != b), None) if word is None: - raise AssertionError(f"{NAME}: reference '{label}' matches the expected words") + raise AssertionError(f"{suite.name}: reference '{label}' matches the expected words") add_reference(f"reference '{label}'", 2, reference, diagnostic=f"word={word} expected=") - for label, old, new, run_index in MUTATIONS: + for label, old, new, run_index in suite.mutations: mutated = source.replace(old, new, 1) if mutated == source: - raise AssertionError(f"{NAME}: mutation '{label}' did not change the source") + raise AssertionError(f"{suite.name}: mutation '{label}' did not change the source") number = len(references) + len(mutations) reference, formats = (expected, None) if run_index is None else (unwritten, invalid_formats(run_index)) case = write_case(number, 2, reference, formats) mutations.append((number, label, case, mutated)) with ThreadPoolExecutor(max_workers=min(LAUNCH_THREADS, os.cpu_count() or 1)) as pool: - batch = pool.submit(check_references, NAME, renderer, backend, cso, references) + batch = pool.submit(check_references, suite.name, renderer, backend, cso, references) mutants = [pool.submit(run_mutation, *mutation) for mutation in mutations] batch.result() for future in mutants: future.result() - print(f"{NAME}: {2 + len(INVALID)} dispatches, {len(WRONG) + len(INVALID) + 1} wrong references and " - f"{len(MUTATIONS)} mutated sources checked") + count = len(suite.wrong) + len(suite.invalid) + (1 if suite.loads is LOADS else 0) + print(f"{suite.name}: {2 + len(suite.invalid)} dispatches, {count} wrong references and " + f"{len(suite.mutations)} mutated sources checked") return 0 @@ -434,7 +591,7 @@ def invalid_formats(number): with tempfile.TemporaryDirectory() as tmp: if mode == "binary" and len(args) == 3: sys.exit(binary(Path(tmp), *args)) - if mode == "draw" and len(args) == 3: - sys.exit(draw(Path(tmp), *args)) + if mode in SUITES and len(args) == 3: + sys.exit(draw(Path(tmp), *args, SUITES[mode])) sys.exit("usage: compute_load_format_check.py controls | binary " - "| draw ") + "| draw | draw-d16 ") diff --git a/tools/compute_store_aot.py b/tools/compute_store_aot.py index eb22a3faf..fdb550aa1 100644 --- a/tools/compute_store_aot.py +++ b/tools/compute_store_aot.py @@ -641,6 +641,11 @@ def descriptor_load_hlsl(): Every conversion is integer arithmetic, so the result does not depend on the GPU's float division. UNORM is x / (2^n - 1) and SNORM16 is max(x / 32767, -1), rounded to nearest even binary32 by long division. FLOAT16 widens exactly, keeping NaN payloads. 16-bit UINT and SINT zero- and sign-extend the low halfword. + + With d16 the channels pack two per result word, x in the low half. Float-type formats give binary16: the + FLOAT16 halves as stored, and UNORM and SNORM16 rounded to nearest even binary16 (denormals kept) by long + division. 16-bit UINT and SINT give the 16-bit integer, not a float. A 32-bit format has no d16 rule here and + is invalid. """ legacy = [] for field, code in sorted(LEGACY_DESCRIPTOR_FORMATS.items()): @@ -665,14 +670,32 @@ def descriptor_load_hlsl(): grouped = {} for code, (kind, channels) in DESCRIPTOR_STORE_FORMATS.items(): grouped.setdefault((kind, channels), []).append(code) + halves = { + "unorm8": ("h = uint4(descriptor_ratio16(raw.x & 0xffu, 255u), descriptor_ratio16((raw.x >> 8u) & 0xffu, 255u), " + "descriptor_ratio16((raw.x >> 16u) & 0xffu, 255u), descriptor_ratio16(raw.x >> 24u, 255u));"), + "unorm16x2": ("h.xy = uint2(descriptor_ratio16(raw.x & 0xffffu, 65535u), " + "descriptor_ratio16(raw.x >> 16u, 65535u));"), + "unorm10": ("h = uint4(descriptor_ratio16(raw.x & 0x3ffu, 1023u), " + "descriptor_ratio16((raw.x >> 10u) & 0x3ffu, 1023u), " + "descriptor_ratio16((raw.x >> 20u) & 0x3ffu, 1023u), descriptor_ratio16(raw.x >> 30u, 3u));"), + "f16x2": "h.xy = uint2(raw.x & 0xffffu, raw.x >> 16u);", + "f16x4": "h = uint4(raw.x & 0xffffu, raw.x >> 16u, raw.y & 0xffffu, raw.y >> 16u);", + "unorm16": "h.x = descriptor_ratio16(raw.x & 0xffffu, 65535u);", + "snorm16": "h.x = descriptor_snorm16_half(raw.x & 0xffffu);", + "uint16": "h.x = raw.x & 0xffffu;", + "sint16": "h.x = raw.x & 0xffffu;", + "f16": "h.x = raw.x & 0xffffu;", + } arms = [] - for kind in _DESCRIPTOR_KIND_ORDER: - for channels in range(1, 5): - codes = grouped.get((kind, channels)) - if codes: - test = " || ".join(f"format == {code}u" for code in sorted(codes)) - keyword = "if" if not arms else "else if" - arms.append(f" {keyword} (({test}) && channels == {channels}u) {{ {bodies[kind]} valid = true; }}") + for d16, table in ((False, bodies), (True, halves)): + for kind in _DESCRIPTOR_KIND_ORDER: + for channels in range(1, 5): + codes = grouped.get((kind, channels)) + if codes and kind in table: + test = " || ".join(f"format == {code}u" for code in sorted(codes)) + keyword = "if" if not arms else "else if" + arms.append(f" {keyword} (d16 {'!=' if d16 else '=='} 0u && ({test}) && channels == {channels}u) " + f"{{ {table[kind]} valid = true; }}") return ( "uint descriptor_ratio(uint x, uint d) {\n" " // binary32 bits of x / d for 0 <= x <= d < 2^16, rounded to nearest even by long division.\n" @@ -691,6 +714,31 @@ def descriptor_load_hlsl(): " if ((bits & 1u) != 0u && (r != 0u || (result & 1u) != 0u)) ++result;\n" " return result;\n" "}\n" + "uint descriptor_ratio16(uint x, uint d) {\n" + " // binary16 bits of x / d for 0 <= x <= d < 2^16, rounded to nearest even, denormals kept.\n" + " if (x == 0u) return 0u;\n" + " if (x == d) return 0x3c00u;\n" + " uint r = x, f = 0u;\n" + " for (uint i = 0u; i < 26u; ++i) {\n" + " r <<= 1u;\n" + " uint bit = r >= d ? 1u : 0u;\n" + " r -= bit * d;\n" + " f = (f << 1u) | bit;\n" + " }\n" + " // x / d = f / 2^26 plus a remainder. A normal result keeps 11 bits; a denormal counts units of 2^-24.\n" + " uint lead = firstbithigh(f);\n" + " uint shift = lead >= 12u ? lead - 10u : 2u;\n" + " uint result = lead >= 12u ? (((lead - 11u) << 10u) | ((f >> shift) & 0x3ffu)) : (f >> shift);\n" + " uint roundBit = (f >> (shift - 1u)) & 1u;\n" + " bool sticky = (f & ((1u << (shift - 1u)) - 1u)) != 0u || r != 0u;\n" + " if (roundBit != 0u && (sticky || (result & 1u) != 0u)) ++result;\n" + " return result;\n" + "}\n" + "uint descriptor_snorm16_half(uint bits16) {\n" + " int value = (int)(bits16 << 16u) >> 16;\n" + " if (value <= -32767) return 0xbc00u;\n" + " return value < 0 ? 0x8000u | descriptor_ratio16((uint)(-value), 32767u) : descriptor_ratio16((uint)value, 32767u);\n" + "}\n" "uint descriptor_snorm16_load(uint bits16) {\n" " int value = (int)(bits16 << 16u) >> 16;\n" " if (value <= -32767) return 0xbf800000u;\n" @@ -704,7 +752,7 @@ def descriptor_load_hlsl(): " uint top = firstbithigh(m);\n" " return sign | ((top + 103u) << 23u) | ((m << (23u - top)) & 0x7fffffu);\n" "}\n" - "uint4 load_descriptor_format(uint formatWord, uint addr, uint channels, out bool valid) {\n" + "uint4 load_descriptor_format(uint formatWord, uint addr, uint channels, uint d16, out bool valid) {\n" " valid = false;\n" f" uint fixedBits = formatWord & {DESCRIPTOR_FIXED_MASK:#x}u;\n" f" uint field = (formatWord >> {DESCRIPTOR_FORMAT_SHIFT}u) & {DESCRIPTOR_FORMAT_MASK:#x}u;\n" @@ -715,8 +763,9 @@ def descriptor_load_hlsl(): + "\n".join(legacy) + "\n" " }\n" " uint4 raw = inputData.Load4(addr);\n" - " uint4 r = uint4(0u, 0u, 0u, 0u);\n" + " uint4 r = uint4(0u, 0u, 0u, 0u), h = uint4(0u, 0u, 0u, 0u);\n" + "\n".join(arms) + "\n" + " if (d16 != 0u) r = uint4(h.x | (h.y << 16u), h.z | (h.w << 16u), 0u, 0u);\n" " return r;\n" "}\n" ) @@ -761,7 +810,7 @@ def heap_view_hlsl(table_offset, view_count, buffer_bytes): " inRange = inRange && instOffset + 4u * channels <= left - start;\n" " addr = v.x + start + instOffset;\n" " }\n" - " uint4 r = load_descriptor_format(v.w, inRange ? addr : 0u, channels, valid);\n" + " uint4 r = load_descriptor_format(v.w, inRange ? addr : 0u, channels, 0u, valid);\n" " return inRange ? r : zero;\n" "}\n" ) @@ -2122,11 +2171,12 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N raise ValueError("Unverified plane byte offset") vector[dst] = ("plane_bytes", row_tag[1], shift, *column_tag[1:]) elif ((m := re.fullmatch(r"v_and_b32_e32 v(\d+), (?:0xffff|65535), v(\d+)", line)) - and isinstance(partial := vector.get(int(m[2])), tuple) and partial[0] == "source_low16"): + and isinstance(partial := vector.get(int(m[2])), tuple) and partial[0] in ("source_low16", "alu_low16")): dst = int(m[1]) if dst > 255: raise ValueError("Invalid vector destination") - vector[dst] = ("alu", f"(inputData.Load({partial[1]}) & 0xffffu)") + word = f"inputData.Load({partial[1]})" if partial[0] == "source_low16" else partial[1] + vector[dst] = ("alu", f"({word} & 0xffffu)") elif ((m := re.fullmatch(r"(v_(?:add|sub|subrev|mul)_f32)_e64 v(\d+), ([^,\s]+), ([^,\s]+)( .+)?", line)) and any(token.startswith(("-", "|", "neg(", "abs(")) and not re.fullmatch(FLOAT_SOURCE, token) for token in m.groups()[2:4])): @@ -2396,8 +2446,6 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N descriptor_load = None if resource_channels and load_format_words is not None: # The format is V# word 3 from a constant word, decoded in the shader (descriptor_load_hlsl). - if packed: - raise ValueError("Descriptor-format d16 loads are not lowered") if not idxen or offen: raise ValueError("Unsupported formatted buffer read target or address mode") if format_load_index >= len(load_format_words): @@ -2475,15 +2523,19 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N if descriptor_load is not None: result = f"format_load_{format_load_index - 1}" slot = hlsl_word(('constant_word', descriptor_load)) + if heap_view is not None and packed: + raise ValueError("D16 descriptor-format loads are not lowered through a heap view") call = (f"load_heap_view_format({slot}, tid.{AXES[tag[1]]}, {aligned}u, {components}u, " f"format_valid_{format_load_index - 1})" if heap_view is not None else - f"load_descriptor_format({slot}, {addresses[0]}, {components}u, " + f"load_descriptor_format({slot}, {addresses[0]}, {components}u, {int(packed)}u, " f"format_valid_{format_load_index - 1})") staged_steps.append((None, f" bool format_valid_{format_load_index - 1};\n" f" uint4 {result} = {call};")) for reg in range(dst, dst + count): vector.pop(reg, None) - loading[reg] = ("alu", f"{result}.{'xyzw'[reg - dst]}") + # An odd d16 count leaves the high half of the last word undefined, as for source_low16. + low16 = packed and components % 2 and reg == dst + count - 1 + loading[reg] = ("alu_low16" if low16 else "alu", f"{result}.{'xyzw'[reg - dst]}") continue # The address has been captured, so the index can alias a destination. for reg, address in enumerate(addresses, dst): From 0c8f5dabe16b6285b4a5adcc497c226fd7f989c3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?As=C4=B1m=20Mirza=20=C3=87iftler?= <113895866+Asimmimx@users.noreply.github.com> Date: Thu, 26 Nov 2026 05:32:18 +0300 Subject: [PATCH 077/240] startup: draw the gfx2hlsl binary32 arithmetic operations (#1712) * startup: draw the gfx2hlsl binary32 arithmetic operations The VEC_F table lowers v_add_f32, v_sub_f32, v_subrev_f32, v_mul_f32, v_mul_legacy_f32, v_min_f32, v_max_f32, v_fma_f32, v_mad_f32, v_mad_legacy_f32, v_med3_f32, v_min3_f32 and v_max3_f32, and no check ran any of them. tests/startup_gfx2hlsl_float_alu_check.py draws them with the shared per-lane runner (byte-identical copy of tests/startup_gfx2hlsl_lane_alu.py) on inputs with exact results, against references written from the RDNA 2 ISA (S1 - S0 for subrev, the legacy multiply's 0 against inf and NaN, the middle of three). Each operation has one mutated lowering whose first draw must read its own mutated words. All 52 draws match on WARP and an RX 6600 through FXC ps_5_1 and DXC ps_6_0, and the 26 mutated draws read their mutated words. Not covered and recorded in docs/experiments.md: the translation writes v_fma_f32 and v_mad_f32 as a * b + c, which WARP rounds twice and the RX 6600 fuses, so an inexact product reads 0 on one and 2^-24 on the other. * test: follow main's mad32/med3_32 lowerings in the float ALU mutations --------- Co-authored-by: x2w-worker --- .github/workflows/windows.yml | 2 + CMakeLists.txt | 10 ++ docs/experiments.md | 17 +++ tests/startup_gfx2hlsl_float_alu_check.py | 125 ++++++++++++++++++++++ 4 files changed, 154 insertions(+) create mode 100644 tests/startup_gfx2hlsl_float_alu_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 9b3c95f89..ecda84488 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -112,6 +112,7 @@ jobs: (["tests/startup_compute_store_format_xyzw_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_image_gather_c_lz_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_image_sample_c_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_gfx2hlsl_float_alu_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_image_3d_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_int3_alu_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_image_load_mip_check.py", "--llvm-mc", "llvm-mc-15"], {}), @@ -246,6 +247,7 @@ jobs: tests/startup_compute_store_format_xyzw_check.py \ tests/startup_image_gather_c_lz_check.py \ tests/startup_image_sample_c_check.py \ + tests/startup_gfx2hlsl_float_alu_check.py \ tests/startup_image_3d_check.py \ tests/startup_image_load_mip_check.py \ tests/startup_gfx2hlsl_operand_count_check.py \ diff --git a/CMakeLists.txt b/CMakeLists.txt index ea4632950..3dc2ace03 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4531,6 +4531,16 @@ if(EXISTS "${INTAKE_PYTHON}") # Startup shader translator: the SMEM offset 'off' is the literal 0; m0 and other operands keep their handling (#1674). add_test(NAME startup_gfx2hlsl_smem_offset COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_smem_offset_check.py") + # gfx2hlsl binary32 arithmetic (VEC_F): translation controls, then a draw of the translated pairs with exact + # reference words and one mutated lowering per operation. + add_test(NAME startup_gfx2hlsl_float_alu_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_float_alu_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_float_alu_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_float_alu_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_float_alu_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + endforeach() # Startup shader translator: s_load descriptor into s[104:107] (vcc is s106/s107) (#1723). add_test(NAME startup_gfx2hlsl_sload_s104 COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_sload_s104_check.py") diff --git a/docs/experiments.md b/docs/experiments.md index 458a94d47..8fc1fac72 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14552,6 +14552,23 @@ For binary32 arithmetic and compare sources, the translator reads the inline int `tools/startup/gfx2hlsl.py` now lowers the gfx1013 `image_sample_l` form of a 2D or 3D texture sample to `tex.SampleLevel(smp, uv, level)`. The level is the last address register: the third for a contiguous 2D address, the fourth for 3D, and the last element of an NSA list. `tests/startup_image_sample_l_check.py` translates source-built fixtures (the words are checked against `llvm-mc`) and requires the level to come from that register; an address list `[v0, v1, v3]` must use `v3`, not the third consecutive register. Replacing the level with 0, replacing the call with implicit `Sample`, or reading the third register in every form each make the check fail. Offset (`_o`), compare (`_c_l`), gather, 1D, array, cube and multisample dimensions, an empty `dmask`, and the `unorm`, `r128`, `tfe`, `lwe`, `a16` and `d16` modifiers or any set reserved MIMG bit are refused with an `Unsupported` message; only the cache-policy bits `glc`, `slc` and `dlc` are accepted because they do not change the sampled value. The disassembler previously read `lwe` from reserved bit 14 of word 0; `llvm-mc` (19, gfx1013) encodes it in bit 17, and the check now has one `llvm-mc`-built fixture per refused modifier plus patched reserved-bit fixtures. Not measured: no draw samples a mip level on WARP or hardware through this lowering, so the level selection is checked on the generated HLSL text only. [HLSL SampleLevel](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-to-samplelevel) +## Startup translator: binary32 arithmetic + +No check ran these binary32 operations of the `VEC_F` table in `tools/startup/gfx2hlsl.py` before: `v_add_f32`, `v_sub_f32`, `v_subrev_f32`, `v_mul_f32`, `v_mul_legacy_f32`, `v_min_f32`, `v_max_f32`, `v_fma_f32`, `v_mad_f32`, `v_mad_legacy_f32`, `v_med3_f32`, `v_min3_f32` and `v_max3_f32`. `tests/startup_gfx2hlsl_float_alu_check.py` draws them with the shared runner `tests/startup_gfx2hlsl_lane_alu.py`. Each draw applies one operation to each of four pixels' flat inputs, alternating the `_e32` and `_e64` spellings of the VOP2 forms, and compares the four result words exactly. + +The references follow the AMD RDNA 2 ISA reference: `v_subrev` is S1 - S0, the legacy multiply reads 0 when either factor is 0 even against an infinity or a NaN, and `v_med3_f32` is the middle value. Every input set has an exact result, so the check does not depend on rounding or on whether a compiler fuses a multiply and an add. + +Each operation has a wrong lowering whose first draw must read its own mutated words: +- the add, subtract and multiply exchanged or reversed; +- the legacy product doubled; +- min and max exchanged; +- `a * b - c` for the multiply-adds; +- `max3` for `med3`. + +On WARP 10.0.26100.9818 and on an AMD Radeon RX 6600 (driver 32.0.21045.29003), all 52 draws matched through FXC `ps_5_1` and DXC `ps_6_0`, and all 26 mutated draws read their mutated words. Tests: `startup_gfx2hlsl_float_alu_controls`, `startup_gfx2hlsl_float_alu_warp` and `startup_gfx2hlsl_float_alu_hardware`. + +Not covered: inexact products. The translation writes both `v_fma_f32`, which rounds once, and `v_mad_f32`, which rounds the product and then the sum, as `a * b + c`. With `a = b = 1 + 2^-12` and `c = -(1 + 2^-11)`, a single rounding gives 2^-24 (`0x33800000`) and two roundings give 0. Through both FXC and DXC, both operations read 0 on WARP and `0x33800000` on the RX 6600. The result of either operation on an inexact product therefore depends on the adapter. NaN and signed-zero ordering in min, max and med3, and denormals, are not covered either. + ## Startup translator: biased image sampling `tools/startup/gfx2hlsl.py` lowers the gfx1013 `image_sample_b` form in a pixel stage to `tex.SampleBias(smp, uv, bias)` for 2D, 2D-array and 3D textures. The RDNA 2 ISA (section 8.2.4, Table 43: "_B LOD BIAS, 1: lod bias, Add this BIAS to the LOD computed"; section 8.2.5: the address is `{ offset } { bias } { z-compare } { derivative } { body }` and the bias is "One Dword float") puts the bias in the FIRST address register, so `v[0:2]` is bias, u, v and the NSA list `[v3, v1, v2]` takes the bias from `v3`. LLVM 15 agrees: `IntrinsicsAMDGPU.td` gives `AMDGPUSample_b` the extra argument `llvm_anyfloat_ty "bias"` and `MIMGInstructions.td` the gfx10 opcode `0x25`. `llvm-mc` (LLVM 15, gfx1013) assembles the contiguous 2D, 2D-array, 3D and NSA forms, and the check compares every fixture against it. HLSL `SampleBias` adds the bias to the implicit mip level and documents the range -16.0 to 15.99; the ISA text states no hardware clamp, so a bias outside that range is an unverified difference. The form needs a pixel stage whose EXEC is still the entry mask with wave-uniform control flow (implicit derivatives); a uniform (scc) join or later loop does not drop that proof, while divergent EXEC or a vcc/exec-conditioned branch before the sample does (there the plain sample is lowered to level 0, which would drop the bias). It is also refused outside a pixel stage, and so are `image_sample_b_cl`, `image_sample_c_b*`, `image_sample_b_o`, `image_gather4_b`, 1D, cube and multisample dimensions, an empty `dmask`, the `unorm`, `r128`, `tfe`, `lwe`, `a16` and `d16` modifiers, set reserved MIMG bits, and a constant sampler whose LOD bias fields (word 2 bits 19:0, s6.8 and s2.4, scaled by `T#.perf_modulation` in the ISA) are not zero or whose mip filter is 0 (mipmapping disabled), or whose MIN_LOD is above its MAX_LOD. The guest clamp is kept: MIN_LOD (word 1 bits 11:0) and MAX_LOD (bits 23:12) are unsigned 4.8 fixed point (Mesa 24.0.0 `src/amd/registers/gfx10-rsrc.json`, `SQ_IMG_SAMP_WORD1`; `radeonsi/si_state.c` lines 5169-5170 encode them with `S_FIXED(x, 8)`), and the sampler of an `image_sample_b` is written as an `smpl` manifest line that the runtime decodes to `MinLOD = MIN_LOD / 256` and `MaxLOD = MAX_LOD / 256` (`src/startup_stubs/translated_sampler_bindings.h`); `smp` and `smpc` lines still leave MinLOD at 0 and MaxLOD unbounded (the next section moves `image_sample`, `_l` and `_lz` with a constant sampler to `smpl`). A sampler read from the sampler heap, including the default-sampler shortcut for a run-time heap load, or built from a register is refused for `image_sample_b`, because its LOD limits and bias cannot be shown to be irrelevant. diff --git a/tests/startup_gfx2hlsl_float_alu_check.py b/tests/startup_gfx2hlsl_float_alu_check.py new file mode 100644 index 000000000..ae6131850 --- /dev/null +++ b/tests/startup_gfx2hlsl_float_alu_check.py @@ -0,0 +1,125 @@ +"""Binary32 arithmetic of tools/startup/gfx2hlsl.py (its VEC_F table). + + (no arguments) translation controls, pure Python + binary reassemble the pixel bodies and compare them with the recorded words + draw [fxc] + draw one pixel per four input sets and compare the four result words + +Covers v_add_f32, v_sub_f32, v_subrev_f32, v_mul_f32, v_mul_legacy_f32, v_min_f32, v_max_f32, v_fma_f32, v_mad_f32, +v_mad_legacy_f32, v_med3_f32, v_min3_f32 and v_max3_f32, which no check ran before. The fixture and runner are +startup_gfx2hlsl_lane_alu.py: one operation per lane on flat parameters the compilers cannot fold, alternating the +e32 and e64 spellings of the VOP2 forms. The references follow the AMD RDNA 2 ISA reference: v_subrev is S1 - S0; +the legacy multiply reads 0 when either factor is 0, even against an infinity or a NaN; v_med3_f32 is the middle of +three values. + +Every input set has an exact result, so the operations are checked independently of rounding and of whether a +compiler fuses a multiply and an add. Not covered: inexact products (v_fma_f32 rounds once and v_mad_f32 twice, while +the translation writes both as a * b + c and leaves the choice to the compiler), NaN and signed-zero ordering in min, +max and med3, and denormals. +""" +import struct +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from startup_gfx2hlsl_lane_alu import main, words # noqa: E402 + + +def f(value): + return struct.unpack(' Date: Thu, 26 Nov 2026 10:35:53 +0800 Subject: [PATCH 078/240] tests: batch matching and wrong vertex-fetch references by format (#2690) Co-authored-by: RavenCurseBurg <360931527+RavenCurseBurg@users.noreply.github.com> --- tests/compute_heap_store_check.py | 2 +- tests/compute_load_format_check.py | 5 ++- tests/startup_vertex_fetch_formats_check.py | 42 +++++++++++---------- 3 files changed, 26 insertions(+), 23 deletions(-) diff --git a/tests/compute_heap_store_check.py b/tests/compute_heap_store_check.py index 30f6ecffe..a95a87913 100644 --- a/tests/compute_heap_store_check.py +++ b/tests/compute_heap_store_check.py @@ -260,7 +260,7 @@ def add(label, slot, **values): wrong_view = table.copy() wrong_view[TABLE_BYTE // 4 + 5 * 8 + 3] = wrong_format add(f"wrong format {wrong_format:#x}", 5, table_words=wrong_view) - if check_references(f"heap-store {mode}", renderer, backend, cso, references, allow_hardware_skip=True) == 77: + if check_references(f"heap-store {mode}", renderer, backend, cso, references, allow_skip=backend == "hardware") == 77: return 77 width_str = {"d16_x": "4u", "d16_xy": "8u", "d16_xyz": "12u"}.get(mode, "16u") format_guard = {"d16_x": f"{FLOAT1:#x}u", "d16_xy": f"{FLOAT2:#x}u", diff --git a/tests/compute_load_format_check.py b/tests/compute_load_format_check.py index ddc297c86..576b9cf1a 100644 --- a/tests/compute_load_format_check.py +++ b/tests/compute_load_format_check.py @@ -469,11 +469,12 @@ def binary(directory, assembler, objcopy, library): return 0 -def check_references(name, renderer, backend, shader, cases, *, allow_hardware_skip=False): +def check_references(name, renderer, backend, shader, cases, *, allow_skip=False): paths = [path for path, _label, _diagnostic in cases] result = subprocess.run([renderer, backend, "--compute-store-batch", shader, *paths], capture_output=True, text=True) - if allow_hardware_skip and backend == "hardware" and result.returncode == 77: + if allow_skip and result.returncode == 77: + print(result.stdout, result.stderr) return 77 statuses = [line for line in result.stdout.splitlines() if line.startswith("case=")] messages = re.split(r"(?=^case=\d+ path=)", result.stderr, flags=re.MULTILINE)[1:] diff --git a/tests/startup_vertex_fetch_formats_check.py b/tests/startup_vertex_fetch_formats_check.py index 187fa7b56..554209f8a 100644 --- a/tests/startup_vertex_fetch_formats_check.py +++ b/tests/startup_vertex_fetch_formats_check.py @@ -9,7 +9,7 @@ (startup_r8_uint_check.py). This drives each table entry the way that check does: a source-built vertex stage with one tbuffer_load_format_xyzw from vertex buffer 1 is translated, its generated vertex body is called from a compute wrapper, and the four position components of 16 vertices are read back through -offscreen_check --compute-store-case and compared with a reference that decodes the same bytes from the +offscreen_check and compared with a reference that decodes the same bytes from the format definitions (little-endian fields from the lowest byte, UNORM n / (2^bits - 1), binary16 widened to binary32, missing X, Y and Z as 0 and a missing W as 1.0, or 1 for an integer format). @@ -21,8 +21,9 @@ that word as an entry constant and the translation switches on it. Each format is run through a MUBUF xyz load with its own descriptor word, then descriptor words with swizzles and constants 0 and 1 run through the same translated body. -Wrong references (channels swapped, a shift off by one field, a missing W read as 0, UNORM over 2^bits) -and mutated translations must fail the readback. +Each TBUFFER format runs its matching reference and each wrong reference that changes a word in one renderer +batch. The first mismatched word must match the predicted index and values. Mutated translations +compile and dispatch separately. """ import re import struct @@ -31,6 +32,7 @@ import tempfile from pathlib import Path +from compute_load_format_check import check_references from startup_sampler_heap_check import root_blob from startup_stream_check import gfx2hlsl @@ -451,14 +453,17 @@ def compile_fetch(directory, compiler, name, source): return binary -def run_reference(directory, consumer, adapter, binary, name, words, translated=None, word3=None): - case = directory / 'fetch.case' - translated = translated or pipeline(name) +def write_reference(case, name, words, translated, word3=None): constants = [0] * 16 constants[translated.uds.index(('stride', 0))] = FORMATS[name][1] if word3 is not None: constants[translated.uds.index(('descword3', 0))] = word3 case.write_bytes(struct.pack('<337I', 1, *words, *constants)) + + +def run_reference(directory, consumer, adapter, binary, name, words, translated=None, word3=None): + case = directory / 'fetch.case' + write_reference(case, name, words, translated or pipeline(name), word3) return subprocess.run([consumer, adapter, '--compute-store-case', binary, case], capture_output=True, text=True) @@ -469,26 +474,23 @@ def run(directory, compiler, consumer, adapter, name, source, words, translated= def check(directory, compiler, consumer, adapter): for name in FORMATS: - source = pipeline(name).hlsl_vs() - binary = compile_fetch(directory, compiler, name, source) + translated = pipeline(name) + binary = compile_fetch(directory, compiler, name, translated.hlsl_vs()) correct = expected(name) - result = run_reference(directory, consumer, adapter, binary, name, correct) - if result.returncode == 77: - print(result.stdout, result.stderr) - return 77 - if result.returncode: - raise RuntimeError('%s: %s%s' % (name, result.stdout, result.stderr)) - print('%s: 16 vertices, stride %d, offset %d: %s' % ( - name, FORMATS[name][1], FORMATS[name][2], - [line for line in result.stdout.splitlines() if 'mismatches=' in line][0])) + case = directory / 'fetch-correct.case' + write_reference(case, name, correct, translated) + references = [(case, '16 vertices, stride %d, offset %d' % FORMATS[name][1:3], None)] for label, wrong in WRONG: words = expected(name, **wrong) if words == correct: continue first = next(i for i, (a, b) in enumerate(zip(words, correct)) if a != b) - bad = run_reference(directory, consumer, adapter, binary, name, words) - if bad.returncode != 1 or 'word=%d expected=' % first not in bad.stderr: - raise AssertionError('%s: reference %r escaped detection\n%s' % (name, label, bad.stderr)) + case = directory / f'fetch-wrong-{len(references)}.case' + write_reference(case, name, words, translated) + diagnostic = f'word={first} expected={words[first]:08x} actual={correct[first]:08x}' + references.append((case, label, diagnostic)) + if check_references(name, consumer, adapter, binary, references, allow_skip=True) == 77: + return 77 for name, label, old, new in MUTATIONS: source = pipeline(name).hlsl_vs() binary = compile_fetch(directory, compiler, name, source.replace(old, new, 1)) From a3b923e1fa0415d190cad8beec038d3e11763d68 Mon Sep 17 00:00:00 2001 From: Roan System Date: Thu, 26 Nov 2026 03:37:10 +0100 Subject: [PATCH 079/240] startup: bind pixel-stage UAVs from the title's descriptor table (#2448) * startup: bind pixel-stage UAVs from the title's descriptor table Refs #1996 (item F). load_translation reads the 'uav N tex2d table P O' line that gfx2hlsl.py writes for a pixel-stage image_store instead of dropping the translation. The translated root signature gets a UAV range after the SRVs in its view table, and each draw makes the view from the unordered-access view the title created at that table entry, on mip 0 of a 2D texture. Version 2 manifests (the ones with uav lines) are read again; each uav line is bound or refused by name, and the raw buffer line of the vertex-stage stores (#2059) stays refused. Refused by name, nothing bound in place of the view: other line forms (including a view qualifier or a channels field, as in the compute line) when the manifest is loaded; at draw time no table, an entry outside the table, an entry without a view, a view that is not a UAV, a resource without ALLOW_UNORDERED_ACCESS, other resource or view dimensions, mips and planes, integer, sRGB and non-colour formats, no typed UAV store, and a texture that is also an SRV, a render target or the depth texture of the draw. These checks run before any view of the draw is written. Indirect draws refuse a translation with a uav line. tests/startup_pixel_uav_check.py draws the source-built program of #2155 through the runtime and reads back every word of four sentinel textures. AI-assisted. * test: pixel UAV no-ua case expects the empty-entry refusal now that skipped UAVs record no view --------- Co-authored-by: tedin7 --- CMakeLists.txt | 7 + docs/experiments.md | 2 +- docs/startup-runtime.md | 23 +- src/startup_stubs/d3d12_draw.inl | 247 +++++++++++++-- src/startup_stubs/d3d12_xs_device.cpp | 4 + .../translated_sampler_bindings.h | 4 +- tests/startup_pixel_uav.cpp | 299 ++++++++++++++++++ tests/startup_pixel_uav_check.py | 270 ++++++++++++++++ tests/startup_stream_consumer.cpp | 3 +- tests/startup_stream_draw.cpp | 7 + 10 files changed, 842 insertions(+), 24 deletions(-) create mode 100644 tests/startup_pixel_uav.cpp create mode 100644 tests/startup_pixel_uav_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 3dc2ace03..deb088e8f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1263,6 +1263,7 @@ target_link_libraries(startup_stream_consumer PRIVATE d3d12_xs_shim startup_stub target_sources(startup_stream_consumer PRIVATE tests/startup_frame_copy.cpp) target_sources(startup_stream_consumer PRIVATE tests/startup_root_reset.cpp) target_sources(startup_stream_consumer PRIVATE tests/startup_memory_srv_diag.cpp) +target_sources(startup_stream_consumer PRIVATE tests/startup_pixel_uav.cpp) add_executable(startup_stream_depth tests/startup_stream_depth.cpp $) target_compile_features(startup_stream_depth PRIVATE cxx_std_17) @@ -4482,6 +4483,12 @@ if(EXISTS "${INTAKE_PYTHON}") "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_d16_srv_check.py" "$" "${backend}") set_tests_properties(startup_d16_srv_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + # A translated pixel-stage image store bound from the title's table (#1996 item F): the stored texel and + # every other word of four textures read back, each refusal by its reason, and the exec controls. + add_test(NAME startup_pixel_uav_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_pixel_uav_check.py" + "$" "${backend}") + set_tests_properties(startup_pixel_uav_${backend} PROPERTIES TIMEOUT 240 SKIP_RETURN_CODE 77) add_test(NAME startup_frame_copy_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_frame_copy_check.py" "$" ${backend}) diff --git a/docs/experiments.md b/docs/experiments.md index 8fc1fac72..d99e8fff6 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -262,7 +262,7 @@ to check RGBA8 texel and alpha values, rebinding, and a mismatched 2D view on ha ## Offline vertex buffer stores -`tools/startup/gfx2hlsl.py` lowers vertex-stage `buffer_store_dword`, `dwordx2`, `dwordx3` and `dwordx4` in the `off` form to `RWByteAddressBuffer.Store*`. The descriptor must come from a root-table slot, and the manifest becomes version 2 with a `uav table ` line. This is offline only: the shipped runtime refuses version 2 manifests, so no store runs in a game. Refused forms: `glc`, `slc`, `offen`, `idxen`, pixel stage, a descriptor also used for a load, a descriptor whose base was changed, and an immediate or inline offset that is not a multiple of four. A register offset is rounded down to a multiple of four. +`tools/startup/gfx2hlsl.py` lowers vertex-stage `buffer_store_dword`, `dwordx2`, `dwordx3` and `dwordx4` in the `off` form to `RWByteAddressBuffer.Store*`. The descriptor must come from a root-table slot, and the manifest becomes version 2 with a `uav table ` line. This is offline only: the shipped runtime refuses the `raw` uav line by name (it binds only pixel-stage `tex2d` stores), so no buffer store runs in a game. Refused forms: `glc`, `slc`, `offen`, `idxen`, pixel stage, a descriptor also used for a load, a descriptor whose base was changed, and an immediate or inline offset that is not a multiple of four. A register offset is rounded down to a multiple of four. The descriptor modifications that compute buffer stores accept are accepted here too, with the same checks: the stride clear of DW1 and the structured-to-raw conversion (stride DW1[29:16] extracted, optionally clamped to at least 1, DW2 NUM_RECORDS scaled by it, DW3 OOB_SELECT set to 3, stride cleared), all four words from one descriptor load. The store and manifest are those of the unmodified descriptor. In the vertex stage, as in compute, a descriptor load through a pointer other than the untouched pair is tagged with the constant high word of a 32-bit table pointer, or otherwise with its own load, so the conversion cannot mix words of two loads. Any other modification stays refused. As for compute, matching out-of-range behavior would need a UAV view sized to the converted byte count; the runtime binds no vertex-stage UAV yet. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 8bc22cfdf..3c8e79aa9 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -2205,11 +2205,30 @@ These are measured on one executable; treat them as hypotheses for others. `uav tex2d table ` line. The cache-policy bits are accepted. A partial channel mask (a typed store writes all four channels), other dimensions, `d16`, `a16`, `tfe`, `lwe`, `r128`, `image_store_mip`, a store outside a pixel or compute stage, and a program that loads - and stores the same image are refused by name. The runtime does not bind UAVs on the translated - graphics path yet: it logs and does not use a translation whose manifest has a `uav` line. A + and stores the same image are refused by name. A hand-assembled program stores four distinct values at texel (1, 2). The desktop draw reads all 16 texels of a 4x4 image back; deleting the store or exchanging x and y must fail. Run `ctest --preset release --no-tests=error -R '^startup_pixel_image_store_' -V`. +- **Binding pixel-stage image stores.** A translated draw binds each `uav N tex2d table P O` line + as a UAV range `u0..` placed after the SRVs in the translated root signature's view table. The view is made from the unordered-access + view the title created at that table entry (`resolve_pixel_uavs` in `d3d12_draw.inl`), on + mip 0 of a 2D texture, and the texture is in `UNORDERED_ACCESS` for the draw. Refusals are logged + with their reason and nothing is bound in place of the view. When the manifest is loaded, the + translation is not used for another image kind, a buffer line (`uav N raw table P O`, + the vertex-stage store of #2059), a view qualifier (`float`, `uint`, `sint`, as in the compute line), another source, extra fields such as + `channels`, an index out of order or more than eight views. At draw time, + the draw is not translated for no table at the parameter, an entry outside the bound table, an + entry without a view, a view that is not a UAV, a resource without `ALLOW_UNORDERED_ACCESS`, an + array, 3D, 1D or multisampled resource, a view of another dimension, mip or plane, an integer, + sRGB or non-colour format, a format without typed UAV store, and a texture that is also an SRV, + a render target or the depth texture of the draw; these checks run before any view of the draw is + written or any texture changes state. Indirect draws refuse a translation with a `uav` line. Compute UAVs and barriers between + draws that write and read the same texture are not covered. `tests/startup_pixel_uav_check.py` + draws the program above through the runtime with four 4x4 two-mip textures in which every word is + a distinct sentinel. The texel lands only in the texture the table names, and every other word of + the four textures stays unchanged; each refusal leaves every word unchanged. The exec-off variant + leaves the texel, and must fail once recompiled without its guard. Run + `ctest --preset release --no-tests=error -R '^startup_pixel_uav_' -V`. - **Explicit mip loads.** For 2D textures, 2D arrays and 3D textures, `image_load_mip` passes the final address register to `Texture.Load` as the mip level (`int4(x, y, slice, mip)` for an array, whose four registers are x, y, slice and mip). Ordinary `image_load` still reads mip zero. diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 04830e6c1..a8d84d8e0 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -9,6 +9,111 @@ // buffers named by the hardware descriptors in its tables, textures behind view tokens) into an // upload ring / a private descriptor heap. +// A pixel-stage image store (#1996 item F): tools/startup/gfx2hlsl.py writes 'uav N tex2d table P O' for the +// RWTexture2D at u, whose descriptor is at byte O of the title's root table P. Only that form is +// read; a view qualifier or a 'channels' field, as in the compute line, is refused. +struct PixelUav { + unsigned index = 0, parameter = 0, offset = 0; +}; +constexpr unsigned pixel_uav_limit = 8; + +// Returns nullptr and fills out, or the reason the line is refused. +const char* read_pixel_uav_line(const std::string& line, PixelUav& out) +{ + std::vector w; + for (std::size_t at = line.find_first_not_of(' '); at != std::string::npos; at = line.find_first_not_of(' ', at)) { + const std::size_t end = line.find(' ', at); + w.push_back(line.substr(at, end == std::string::npos ? std::string::npos : end - at)); + at = end == std::string::npos ? line.size() : end; + } + const auto number = [](const std::string& text, unsigned& value) { + if (text.empty() || text.size() > 9 || text.find_first_not_of("0123456789") != std::string::npos) return false; + value = static_cast(std::strtoul(text.c_str(), nullptr, 10)); + return true; + }; + if (w.size() < 2 || w[0] != "uav" || !number(w[1], out.index)) return "malformed view index"; + if (w.size() < 3) return "missing view kind"; + if (w[2] == "raw" || w[2] == "table") return "buffer view (raw uav) is not bound"; + if (w[2] != "tex2d") return "only tex2d views are bound"; + if (w.size() > 3 && (w[3] == "float" || w[3] == "uint" || w[3] == "sint")) return "a view qualifier is not read for pixel stores"; + if (w.size() < 4 || w[3] != "table") return "view source is not a table"; + if (w.size() < 6) return "missing table parameter or offset"; + if (w.size() > 6) return "unexpected field after the table offset"; + if (!number(w[4], out.parameter) || out.parameter >= 16) return "table parameter out of range"; + if (!number(w[5], out.offset)) return "malformed table offset"; + return nullptr; +} + +// Formats a RWTexture2D store converts to: float, UNORM and SNORM colour formats. +bool float_uav_format(DXGI_FORMAT format) +{ + switch (format) { + case DXGI_FORMAT_R32G32B32A32_FLOAT: case DXGI_FORMAT_R32G32B32_FLOAT: case DXGI_FORMAT_R16G16B16A16_FLOAT: + case DXGI_FORMAT_R16G16B16A16_UNORM: case DXGI_FORMAT_R16G16B16A16_SNORM: case DXGI_FORMAT_R32G32_FLOAT: + case DXGI_FORMAT_R10G10B10A2_UNORM: case DXGI_FORMAT_R11G11B10_FLOAT: case DXGI_FORMAT_R8G8B8A8_UNORM: + case DXGI_FORMAT_R8G8B8A8_SNORM: case DXGI_FORMAT_R16G16_FLOAT: case DXGI_FORMAT_R16G16_UNORM: + case DXGI_FORMAT_R16G16_SNORM: case DXGI_FORMAT_R32_FLOAT: case DXGI_FORMAT_R8G8_UNORM: case DXGI_FORMAT_R8G8_SNORM: + case DXGI_FORMAT_R16_FLOAT: case DXGI_FORMAT_R16_UNORM: case DXGI_FORMAT_R16_SNORM: case DXGI_FORMAT_R8_UNORM: + case DXGI_FORMAT_R8_SNORM: case DXGI_FORMAT_A8_UNORM: case DXGI_FORMAT_B5G6R5_UNORM: case DXGI_FORMAT_B5G5R5A1_UNORM: + case DXGI_FORMAT_B8G8R8A8_UNORM: case DXGI_FORMAT_B8G8R8X8_UNORM: case DXGI_FORMAT_B4G4R4A4_UNORM: + return true; + default: + return false; + } +} + +bool integer_uav_format(DXGI_FORMAT format) +{ + switch (format) { + case DXGI_FORMAT_R32G32B32A32_UINT: case DXGI_FORMAT_R32G32B32A32_SINT: case DXGI_FORMAT_R32G32B32_UINT: + case DXGI_FORMAT_R32G32B32_SINT: case DXGI_FORMAT_R16G16B16A16_UINT: case DXGI_FORMAT_R16G16B16A16_SINT: + case DXGI_FORMAT_R32G32_UINT: case DXGI_FORMAT_R32G32_SINT: case DXGI_FORMAT_R10G10B10A2_UINT: + case DXGI_FORMAT_R8G8B8A8_UINT: case DXGI_FORMAT_R8G8B8A8_SINT: case DXGI_FORMAT_R16G16_UINT: + case DXGI_FORMAT_R16G16_SINT: case DXGI_FORMAT_R32_UINT: case DXGI_FORMAT_R32_SINT: case DXGI_FORMAT_R8G8_UINT: + case DXGI_FORMAT_R8G8_SINT: case DXGI_FORMAT_R16_UINT: case DXGI_FORMAT_R16_SINT: case DXGI_FORMAT_R8_UINT: + case DXGI_FORMAT_R8_SINT: + return true; + default: + return false; + } +} + +bool srgb_uav_format(DXGI_FORMAT format) +{ + return format == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB || format == DXGI_FORMAT_B8G8R8A8_UNORM_SRGB || + format == DXGI_FORMAT_B8G8R8X8_UNORM_SRGB; +} + +// The view of mip 0 of a 2D texture for a pixel UAV. resource is the desktop description, title_view the title's +// own view (nullptr when it passed none) with console format values already mapped. Returns nullptr and fills +// out, or the reason the binding is refused. +const char* pixel_uav_view(ID3D12Device* device, const D3D12_RESOURCE_DESC& resource, + const D3D12_UNORDERED_ACCESS_VIEW_DESC* title_view, D3D12_UNORDERED_ACCESS_VIEW_DESC& out) +{ + if (resource.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) return "resource is not a 2D texture"; + if (resource.DepthOrArraySize != 1) return "resource is a texture array"; + if (resource.SampleDesc.Count != 1) return "resource is multisampled"; + if (!(resource.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) return "resource lacks ALLOW_UNORDERED_ACCESS"; + DXGI_FORMAT format = resource.Format; + if (title_view) { + if (title_view->ViewDimension != D3D12_UAV_DIMENSION_TEXTURE2D) return "view is not a 2D texture view"; + if (title_view->Texture2D.MipSlice != 0) return "view names a mip other than 0"; + if (title_view->Texture2D.PlaneSlice != 0) return "view names a plane other than 0"; + if (title_view->Format != DXGI_FORMAT_UNKNOWN) format = title_view->Format; + } + if (integer_uav_format(format)) return "integer format for a float view"; + if (srgb_uav_format(format)) return "sRGB format"; + if (!float_uav_format(format)) return "format is not a float colour format"; + D3D12_FEATURE_DATA_FORMAT_SUPPORT support{format}; + if (FAILED(device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &support, sizeof(support))) || + !(support.Support2 & D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE)) + return "format has no typed UAV store on this device"; + out = {}; + out.Format = format; + out.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; + return nullptr; +} + struct Translation { struct Srv { int kind, source, a, b; }; // kind 0 buffer, 1 2D texture, 2 2D array, 3 3D texture, 4 1D texture; source 0 table(param a, byte b), 1 vertex stream a, 2 root parameter a enum UdKind { rect, base_vertex, start_instance, root_constant, stride, mrt_bits, d16_unorm16, desc_word3 }; @@ -16,6 +121,7 @@ struct Translation { int state = 0; // 1 ready, 2 unavailable ULONGLONG retry_manifest_at = 0; // Only an absent manifest can become ready on a later draw. std::vector srvs; + std::vector uavs; // manifest 'uav N tex2d table P O' (#1996 F): u0.. after the SRVs std::vector uds; x2w_startup::TranslatedSamplers samplers; x2w_startup::ExportWriteMasks write_masks; // manifest 'wmask': channels each export leaves unwritten (#1674) @@ -168,14 +274,11 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}) return; } matched_rtv = true; - } else if (line.compare(0, 13, "x2w-manifest ") == 0 && line != "x2w-manifest 1") { - // Version 2 adds `uav` lines for vertex-stage stores. This runtime does not bind them, - // so it must not draw a translation whose stores it would silently skip (#1723). + } else if (line.compare(0, 13, "x2w-manifest ") == 0 && line != "x2w-manifest 1" && line != "x2w-manifest 2") { + // Version 2 adds `uav` lines. Each one is bound (a pixel-stage tex2d store) or refused by name below, + // so a translation whose stores would be silently skipped is never drawn (#1723). log("x2w-draw unsupported manifest version for %016llx", tr.key); return; - } else if (line.compare(0, 4, "uav ") == 0) { - log("x2w-draw unsupported uav line for %016llx", tr.key); - return; } else if (std::sscanf(line.c_str(), "udsrc %d %15s %d %d", &i, source, &x, &y) >= 2) { Translation::Ud ud{-1, x, y}; if (!std::strcmp(source, "rect")) ud.kind = Translation::rect; @@ -203,11 +306,17 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}) return; } } else if (line.compare(0, 4, "uav ") == 0) { - // tools/startup/gfx2hlsl.py lowers a pixel-stage image_store to a u-register store, but the - // translated root signature has no UAV range and no view is made from the title's descriptor yet. - log("x2w-draw pipeline %016llx stores to an image (%s); pixel-stage UAVs are not bound yet, translation not used", - tr.key, line.c_str()); - return; + // A pixel-stage image_store: the view is made at draw time from the title's unordered-access view at + // that table entry (resolve_pixel_uavs). + PixelUav uav; + const char* refusal = read_pixel_uav_line(line, uav); + if (!refusal && uav.index != tr.uavs.size()) refusal = "view index out of order"; + if (!refusal && tr.uavs.size() >= pixel_uav_limit) refusal = "too many views"; + if (refusal) { + log("x2w-draw pipeline %016llx uav line refused (%s): %s; translation not used", tr.key, refusal, line.c_str()); + return; + } + tr.uavs.push_back(uav); } else if (!tr.samplers.read_manifest_line(line.c_str())) { log("x2w-draw invalid sampler heap manifest for %016llx", tr.key); return; @@ -226,7 +335,7 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}) if (!cache_path(path, L"", tr.key, L".vs.cso") || FAILED(D3DReadFileToBlob(path, &tr.vs))) return; if (!cache_path(path, L"", tr.key, L".ps.cso") || FAILED(D3DReadFileToBlob(path, &tr.ps))) return; const HRESULT hr = x2w_startup::create_translated_root(device_of(the_device), static_cast(tr.uds.size()), - static_cast(tr.srvs.size()), tr.samplers, &tr.root); + static_cast(tr.srvs.size()), tr.samplers, &tr.root, static_cast(tr.uavs.size())); if (FAILED(hr)) { log("x2w-draw root signature for %016llx failed 0x%08lx", tr.key, static_cast(hr)); return; @@ -234,8 +343,8 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}) tr.state = 1; if (previously_missing) InterlockedDecrement(&translation_missing); InterlockedIncrement(&translation_ready); - log("x2w-draw pipeline %016llx translated: %zu entry values, %zu resources, %zu static samplers, sampler_heap=%u", - tr.key, tr.uds.size(), tr.srvs.size(), tr.samplers.statics.size(), tr.samplers.heap ? 1u : 0u); + log("x2w-draw pipeline %016llx translated: %zu entry values, %zu resources, %zu writable textures, %zu static samplers, sampler_heap=%u", + tr.key, tr.uds.size(), tr.srvs.size(), tr.uavs.size(), tr.samplers.statics.size(), tr.samplers.heap ? 1u : 0u); } // draw_lock held. Both pipeline forms use the same request writer and shader cache. @@ -1886,6 +1995,85 @@ bool formatted_buffers_ready(const Translation& tr, const Pass& pass, FormattedB return true; } +struct PixelUavBinding { + ID3D12Resource* resource = nullptr; + D3D12_UNORDERED_ACCESS_VIEW_DESC view{}; +}; + +// draw_lock held. The writable textures of tr (#1996 F), from the unordered-access views the title created at +// their table entries (pixel_uav_view). False, with the reason logged, when one cannot be bound as the program +// expects: the draw is then not translated, and no other view is bound in its place. +bool resolve_pixel_uavs(const Translation& tr, const Pass& pass, PixelUavBinding* out) +{ + const auto refuse = [&](std::size_t i, const char* reason, unsigned long long detail) { + static LONG refused; + if (first_calls(refused, 16)) + log("x2w-draw %016llx uav %zu refused: %s (0x%llx); draw not translated", tr.key, i, reason, detail); + return false; + }; + for (std::size_t i = 0; i < tr.uavs.size(); ++i) { + const PixelUav& uav = tr.uavs[i]; + const x2w_startup::ViewTable& table = pass.view_tables[uav.parameter]; + if (!table.address) return refuse(i, "no descriptor table at the parameter", uav.parameter); + const u64 entry = table.record(uav.offset, 32); + if (!entry) return refuse(i, "table entry outside the bound table", uav.offset); + std::uint32_t words[8] = {}; + if (!x2w_local::readable(reinterpret_cast(entry), 32)) return refuse(i, "table entry unreadable", entry); + std::memcpy(words, reinterpret_cast(entry), 32); + if (words[0] != view_token_magic) return refuse(i, "table entry holds no view", words[0]); + ViewRecord record{}; + AcquireSRWLockShared(¬e_lock); + const bool known = words[1] < view_records().size(); + if (known) record = view_records()[words[1]]; + ReleaseSRWLockShared(¬e_lock); + if (!known) return refuse(i, "unknown view token", words[1]); + if (record.slot != 19) return refuse(i, "table entry is not an unordered-access view", record.slot); + Wrapper* resource = as_wrapper(reinterpret_cast(record.resource)); + if (!resource || resource->own().kind != resource_kind || !resource->own().real) return refuse(i, "view has no resource", record.resource); + if (resource->own().tiled_address_srv) return refuse(i, "resource is a texture by title address", record.resource); + auto* texture = static_cast(resource->own().real); + D3D12_UNORDERED_ACCESS_VIEW_DESC title_view{}; + const bool described = record.desc_bytes >= sizeof(title_view); + if (record.desc_bytes && !described) return refuse(i, "truncated view description", record.desc_bytes); + if (described) { + std::memcpy(&title_view, record.desc, sizeof(title_view)); + title_view.Format = desktop_format(title_view.Format); + } + const D3D12_RESOURCE_DESC desc = texture->GetDesc(); + const char* reason = pixel_uav_view(device_of(the_device), desc, described ? &title_view : nullptr, out[i].view); + if (reason) { + static LONG refused_view; + if (first_calls(refused_view, 16)) + log("x2w-draw %016llx uav %zu refused: %s (view %s dimension %d mip %u format %d; resource dimension %d array %u " + "flags 0x%x format %d); draw not translated", tr.key, i, reason, described ? "described" : "default", + title_view.ViewDimension, title_view.Texture2D.MipSlice, title_view.Format, desc.Dimension, + static_cast(desc.DepthOrArraySize), static_cast(desc.Flags), desc.Format); + return false; + } + // A texture the draw also renders to or reads cannot be bound for writing. Checked here, before the + // draw records any view or state change. + const bool target = std::find(pass.bound_targets, pass.bound_targets + pass.target_count, texture) != + pass.bound_targets + pass.target_count; + if (target || (pass.bound_depth && pass.bound_depth == texture)) + return refuse(i, "the texture is also a render or depth target of this draw", reinterpret_cast(texture)); + for (std::size_t s = 0; s < tr.srvs.size(); ++s) { + const Translation::Srv& srv = tr.srvs[s]; + if (srv.kind < 1 || srv.kind > 4 || srv.source != 0 || srv.a < 0 || srv.a >= 16 || srv.b < 0) continue; + const u64 srv_entry = pass.view_tables[srv.a].record(static_cast(srv.b), 32); + std::uint32_t srv_words[8] = {}; + if (!srv_entry || !x2w_local::readable(reinterpret_cast(srv_entry), 32)) continue; + std::memcpy(srv_words, reinterpret_cast(srv_entry), 32); + if (srv_words[0] != view_token_magic) continue; + AcquireSRWLockShared(¬e_lock); + const u64 srv_resource = srv_words[1] < view_records().size() ? view_records()[srv_words[1]].resource : 0; + ReleaseSRWLockShared(¬e_lock); + if (srv_resource && srv_resource == record.resource) return refuse(i, "the texture is also an SRV of this draw", s); + } + out[i].resource = texture; + } + return true; +} + bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UINT start, INT base_vertex, UINT start_instance, TranslatedIndirectDraw* indirect) { @@ -1925,6 +2113,12 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI ReleaseSRWLockExclusive(&draw_lock); return false; } + if (!tr->uavs.empty()) { + indirect->set_refusal("translated draw with a writable texture is not bound for indirect draws", + indirect_refusal_code::unsupported_resource_or_entry); + ReleaseSRWLockExclusive(&draw_lock); + return false; + } auto& entry = indexed ? tr->indexed_indirect_entry : tr->independent_indirect_entry; if (!entry.has_value()) { bool found_base = !indexed; @@ -1960,11 +2154,17 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI ReleaseSRWLockExclusive(&draw_lock); return false; } + PixelUavBinding uav_bindings[pixel_uav_limit]; + if (!resolve_pixel_uavs(*tr, pass, uav_bindings)) { + ReleaseSRWLockExclusive(&draw_lock); + return false; + } const UINT n = static_cast(tr->srvs.size()); - UINT first = static_cast(InterlockedExchangeAdd(&draw_heap_cursor, static_cast(n))) % draw_heap_size; - if (first + n > draw_heap_size) { + const UINT views = n + static_cast(tr->uavs.size()); // the SRVs, then the UAVs, in one table + UINT first = static_cast(InterlockedExchangeAdd(&draw_heap_cursor, static_cast(views))) % draw_heap_size; + if (first + views > draw_heap_size) { first = 0; - InterlockedExchange(&draw_heap_cursor, static_cast(n)); + InterlockedExchange(&draw_heap_cursor, static_cast(views)); } std::uint32_t strides[32] = {}; // Only the vertices this draw can reference are copied: [vertex_first, vertex_first + vertex_count). @@ -2256,6 +2456,15 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI have ? "bound" : "NULL", head); } } + for (UINT j = 0; j < tr->uavs.size(); ++j) { + const D3D12_CPU_DESCRIPTOR_HANDLE dest{draw_heap->GetCPUDescriptorHandleForHeapStart().ptr + SIZE_T{first + n + j} * draw_heap_increment}; + require_state(self, uav_bindings[j].resource, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + device_of(the_device)->CreateUnorderedAccessView(uav_bindings[j].resource, nullptr, &uav_bindings[j].view, dest); + static LONG shown; + if (first_calls(shown, 6)) + log("x2w-draw %016llx uav %u: resource %p format %d mip 0", tr->key, j, static_cast(uav_bindings[j].resource), + uav_bindings[j].view.Format); + } static LONG checks; if ((InterlockedIncrement(&checks) & 63) == 1) check_device("translated draw views", 0); std::uint32_t values[32] = {}; @@ -2311,8 +2520,8 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI pass.bound_sampler_heap = samplers; } list->SetGraphicsRoot32BitConstants(0, static_cast(tr->uds.size()), values, 0); - if (n) list->SetGraphicsRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE{draw_heap->GetGPUDescriptorHandleForHeapStart().ptr + u64{first} * draw_heap_increment}); - if (samplers) list->SetGraphicsRootDescriptorTable(x2w_startup::sampler_root_parameter(n), samplers->GetGPUDescriptorHandleForHeapStart()); + if (views) list->SetGraphicsRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE{draw_heap->GetGPUDescriptorHandleForHeapStart().ptr + u64{first} * draw_heap_increment}); + if (samplers) list->SetGraphicsRootDescriptorTable(x2w_startup::sampler_root_parameter(views), samplers->GetGPUDescriptorHandleForHeapStart()); list->IASetPrimitiveTopology(pass.topology == 5 ? D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP : D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); bool drawn = false; if (indirect) { diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index ff4dc8978..ae3cd6be9 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -2503,6 +2503,8 @@ struct Pass { ID3D12Resource* target0 = nullptr; // desktop resource of render target 0 (for per-draw dumps) ID3D12Resource* trace_targets[8]{}; ID3D12Resource* trace_depth = nullptr; + ID3D12Resource* bound_targets[8]{}; // the last accepted bind: targets [0, target_count) and the depth texture + ID3D12Resource* bound_depth = nullptr; bool heap_set = false; x2w_startup::SamplerSource title_samplers; std::unique_ptr sampler_snapshot; @@ -3578,6 +3580,8 @@ void __stdcall list_targets(Wrapper* self, UINT count, const D3D12_CPU_DESCRIPTO } if (dsv_target) require_state(self, dsv_target, dsv_state); pass.target_count = count; + std::copy_n(targets, 8, pass.bound_targets); + pass.bound_depth = dsv_target; pass.dsv_format = dsv_format; const auto single_sample = [](ID3D12Resource* resource) { const auto samples = resource->GetDesc().SampleDesc; diff --git a/src/startup_stubs/translated_sampler_bindings.h b/src/startup_stubs/translated_sampler_bindings.h index 8d06fa71a..10149b3c1 100644 --- a/src/startup_stubs/translated_sampler_bindings.h +++ b/src/startup_stubs/translated_sampler_bindings.h @@ -110,8 +110,10 @@ inline std::vector decode_statics(const TranslatedSam return statics; } -inline UINT sampler_root_parameter(UINT srvs) { return srvs ? 2u : 1u; } +// views: the SRVs and UAVs of the view table together. +inline UINT sampler_root_parameter(UINT views) { return views ? 2u : 1u; } +// Parameter 1, when there are views, is one table: SRVs t0.. first, then UAVs u0.. right after them. inline HRESULT create_translated_root(ID3D12Device* device, UINT constants, UINT srvs, const TranslatedSamplers& samplers, ID3D12RootSignature** out, UINT uavs = 0) { diff --git a/tests/startup_pixel_uav.cpp b/tests/startup_pixel_uav.cpp new file mode 100644 index 000000000..36a654629 --- /dev/null +++ b/tests/startup_pixel_uav.cpp @@ -0,0 +1,299 @@ +// X2W_TEST_PIXEL_UAV= (tests/startup_pixel_uav_check.py): a translated pixel program that stores to a +// 2D image (#1996 item F) drawn through d3d12_xs.dll, with the image bound from the title's descriptor table. +// +// Four committed 4x4 textures with two mips each, every word of every texel a distinct sentinel: +// A R32G32B32A32_FLOAT with ALLOW_UNORDERED_ACCESS, B the same, C without the flag, D R32G32B32A32_TYPELESS. +// One shader-visible heap of eight entries: +// 0 UAV of A (explicit 2D view, mip 0) 1 UAV of B (no description: the default view) +// 2 UAV of C (the stand-in skips the desktop call and keeps the title's view) +// 3 UAV of D as R32G32B32A32_UINT 4 left unwritten +// 5 SRV of A 6 UAV of A, mip 1 +// 7 UAV of A as a one-slice 2D array 8 UAV of E, a 4x4 R8G8B8A8_UNORM render target with the flag +// The case names the table bound at root parameter 0 (and, for srv-and-uav, parameter 1); one draw follows. +// The target case binds E as the draw's render target first. +// After the fence every subresource of the four textures is written to .uav, and the debug layer's +// errors are counted when it is on. +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +using Word = std::uint64_t; +Word invoke(void*, unsigned, Word = 0, Word = 0, Word = 0, Word = 0, Word = 0, Word = 0, Word = 0, Word = 0); + +namespace { +using Microsoft::WRL::ComPtr; +template Word ptr(T* value) { return reinterpret_cast(value); } + +constexpr UINT side = 4, mips = 2, textures = 4; + +// The sentinel of word c of texel (x, y) of mip m of texture t; tests/startup_pixel_uav_check.py makes the same. +std::uint32_t sentinel(UINT t, UINT m, UINT texel, UINT c) { return 0xc0000000u | (t << 12) | (m << 8) | (texel << 2) | c; } + +struct Fixture { + ID3D12Device* desktop = nullptr; + void* resources[textures]{}; + ComPtr natives[textures]; +} fixture; + +ComPtr native_of(void* guest, void* wrapped) +{ + // The stand-in forwards SetPrivateDataInterface with the desktop object behind its argument. + constexpr GUID key{0x5e1f0b42, 0x2d8c, 0x4f61, {0x9a, 0x37, 0x0c, 0x71, 0x52, 0x88, 0xe4, 0x1d}}; + if (FAILED(static_cast(invoke(guest, 5, ptr(&key), ptr(wrapped))))) return nullptr; + ComPtr stored; + UINT bytes = sizeof(IUnknown*); + const HRESULT read = fixture.desktop->GetPrivateData(key, &bytes, stored.GetAddressOf()); + invoke(guest, 5, ptr(&key), 0); + ComPtr result; + if (FAILED(read) || FAILED(stored.As(&result))) return nullptr; + return result; +} + +D3D12_RESOURCE_DESC texture_desc(UINT t) +{ + return {D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, side, side, 1, mips, + t == 3 ? DXGI_FORMAT_R32G32B32A32_TYPELESS : DXGI_FORMAT_R32G32B32A32_FLOAT, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, t == 2 ? D3D12_RESOURCE_FLAG_NONE : D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS}; +} + +struct Copier { + ComPtr queue; + ComPtr allocator; + ComPtr list; + ComPtr fence; + bool open(ID3D12Device* device) + { + const D3D12_COMMAND_QUEUE_DESC desc{}; + return SUCCEEDED(device->CreateCommandQueue(&desc, IID_PPV_ARGS(&queue))) && + SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator))) && + SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.Get(), nullptr, IID_PPV_ARGS(&list))) && + SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence))); + } + bool run() + { + if (FAILED(list->Close())) return false; + ID3D12CommandList* lists[] = {list.Get()}; + queue->ExecuteCommandLists(1, lists); + if (FAILED(queue->Signal(fence.Get(), 1))) return false; + const ULONGLONG deadline = GetTickCount64() + 10000; + while (fence->GetCompletedValue() < 1 && GetTickCount64() < deadline) Sleep(1); + return fence->GetCompletedValue() == 1; + } +}; + +void barrier(ID3D12GraphicsCommandList* list, ID3D12Resource* resource, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) +{ + D3D12_RESOURCE_BARRIER b{}; + b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + b.Transition = {resource, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, before, after}; + list->ResourceBarrier(1, &b); +} + +ComPtr buffer(ID3D12Device* device, D3D12_HEAP_TYPE type, UINT64 bytes, D3D12_RESOURCE_STATES state) +{ + const D3D12_HEAP_PROPERTIES heap{type}; + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, bytes, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; + ComPtr result; + if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, IID_PPV_ARGS(&result)))) + return nullptr; + return result; +} + +// Fills every subresource of the four textures with its sentinels (to_textures) or copies them all back. +bool copy_all(ID3D12Device* device, bool to_textures, std::vector* words) +{ + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprints[mips]{}; + UINT64 total = 0; + const auto desc = texture_desc(0); + device->GetCopyableFootprints(&desc, 0, mips, 0, footprints, nullptr, nullptr, &total); + if (!total || total == ~UINT64{0}) return false; + auto staging = buffer(device, to_textures ? D3D12_HEAP_TYPE_UPLOAD : D3D12_HEAP_TYPE_READBACK, total * textures, + to_textures ? D3D12_RESOURCE_STATE_GENERIC_READ : D3D12_RESOURCE_STATE_COPY_DEST); + Copier copier; + if (!staging || !copier.open(device)) return false; + unsigned char* memory = nullptr; + if (to_textures) { + if (FAILED(staging->Map(0, nullptr, reinterpret_cast(&memory)))) return false; + for (UINT t = 0; t < textures; ++t) + for (UINT m = 0; m < mips; ++m) { + const UINT n = side >> m; + for (UINT y = 0; y < n; ++y) + for (UINT x = 0; x < n; ++x) + for (UINT c = 0; c < 4; ++c) { + const std::uint32_t value = sentinel(t, m, y * n + x, c); + std::memcpy(memory + t * total + footprints[m].Offset + y * footprints[m].Footprint.RowPitch + (x * 4 + c) * 4, + &value, 4); + } + } + staging->Unmap(0, nullptr); + } + for (UINT t = 0; t < textures; ++t) { + auto* texture = fixture.natives[t].Get(); + const auto state = to_textures ? D3D12_RESOURCE_STATE_COPY_DEST : D3D12_RESOURCE_STATE_COPY_SOURCE; + barrier(copier.list.Get(), texture, D3D12_RESOURCE_STATE_COMMON, state); + for (UINT m = 0; m < mips; ++m) { + D3D12_TEXTURE_COPY_LOCATION placed{staging.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + placed.PlacedFootprint = footprints[m]; + placed.PlacedFootprint.Offset += t * total; + D3D12_TEXTURE_COPY_LOCATION subresource{texture, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + subresource.SubresourceIndex = m; + if (to_textures) copier.list->CopyTextureRegion(&subresource, 0, 0, 0, &placed, nullptr); + else copier.list->CopyTextureRegion(&placed, 0, 0, 0, &subresource, nullptr); + } + barrier(copier.list.Get(), texture, state, D3D12_RESOURCE_STATE_COMMON); + } + if (!copier.run()) return false; + if (to_textures) return true; + if (FAILED(staging->Map(0, nullptr, reinterpret_cast(&memory)))) return false; + for (UINT t = 0; t < textures; ++t) + for (UINT m = 0; m < mips; ++m) { + const UINT n = side >> m; + for (UINT y = 0; y < n; ++y) + for (UINT x = 0; x < n * 4; ++x) { + std::uint32_t value = 0; + std::memcpy(&value, memory + t * total + footprints[m].Offset + y * footprints[m].Footprint.RowPitch + x * 4, 4); + words->push_back(value); + } + } + staging->Unmap(0, nullptr); + return true; +} + +ID3D12InfoQueue* debug_messages() +{ + static ComPtr queue; + if (!queue && fixture.desktop) fixture.desktop->QueryInterface(IID_PPV_ARGS(&queue)); + return queue.Get(); +} +} // namespace + +int draw_pixel_uavs(ID3D12Device* desktop, void* guest, void* list) +{ + char mode[32]{}; + GetEnvironmentVariableA("X2W_TEST_PIXEL_UAV", mode, sizeof(mode)); + const std::string which(mode); + fixture.desktop = desktop; + for (UINT t = 0; t < textures; ++t) { + using Create = HRESULT (WINAPI*)(void*, const D3D12_HEAP_PROPERTIES*, UINT, const D3D12_RESOURCE_DESC*, UINT, const void*, + void*, UINT, const void*, REFIID, void**); + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + const auto desc = texture_desc(t); + const auto create = reinterpret_cast((*static_cast(guest))[127]); + if (FAILED(create(guest, &heap, 0, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr, nullptr, 0, nullptr, + __uuidof(ID3D12Resource), &fixture.resources[t])) || !fixture.resources[t]) + return 70; + fixture.natives[t] = native_of(guest, fixture.resources[t]); + if (!fixture.natives[t]) return 71; + } + if (!copy_all(desktop, true, nullptr)) return 72; + + struct Extended { + D3D12_DESCRIPTOR_HEAP_DESC desc; + Word address, bytes; + } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 9, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, 0, 0}; + void* heap = nullptr; + if (FAILED(static_cast(invoke(guest, 14, ptr(&heap_desc), ptr(&__uuidof(ID3D12DescriptorHeap)), ptr(&heap))))) + return 73; + const Word cpu = invoke(heap, 9), gpu = invoke(heap, 10); + const UINT stride = static_cast(invoke(guest, 15, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV)); + if (!cpu || !gpu || stride < 32) return 73; + + D3D12_UNORDERED_ACCESS_VIEW_DESC view{DXGI_FORMAT_R32G32B32A32_FLOAT, D3D12_UAV_DIMENSION_TEXTURE2D}; + invoke(guest, 19, ptr(fixture.resources[0]), 0, ptr(&view), cpu + 0 * stride); + invoke(guest, 19, ptr(fixture.resources[1]), 0, 0, cpu + 1 * stride); + invoke(guest, 19, ptr(fixture.resources[2]), 0, ptr(&view), cpu + 2 * stride); + D3D12_UNORDERED_ACCESS_VIEW_DESC integer = view; + integer.Format = DXGI_FORMAT_R32G32B32A32_UINT; + invoke(guest, 19, ptr(fixture.resources[3]), 0, ptr(&integer), cpu + 3 * stride); + D3D12_SHADER_RESOURCE_VIEW_DESC srv{DXGI_FORMAT_R32G32B32A32_FLOAT, D3D12_SRV_DIMENSION_TEXTURE2D, + D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + srv.Texture2D.MipLevels = 1; + invoke(guest, 18, ptr(fixture.resources[0]), ptr(&srv), cpu + 5 * stride); + D3D12_UNORDERED_ACCESS_VIEW_DESC mip1 = view; + mip1.Texture2D.MipSlice = 1; + invoke(guest, 19, ptr(fixture.resources[0]), 0, ptr(&mip1), cpu + 6 * stride); + D3D12_UNORDERED_ACCESS_VIEW_DESC array{DXGI_FORMAT_R32G32B32A32_FLOAT, D3D12_UAV_DIMENSION_TEXTURE2DARRAY}; + array.Texture2DArray.ArraySize = 1; + invoke(guest, 19, ptr(fixture.resources[0]), 0, ptr(&array), cpu + 7 * stride); + + // E: a 4x4 R8G8B8A8_UNORM texture that is both a render target and writable; entry 8 is its UAV. The target + // case binds it as the draw's render target and names that entry. + using Create = HRESULT (WINAPI*)(void*, const D3D12_HEAP_PROPERTIES*, UINT, const D3D12_RESOURCE_DESC*, UINT, const void*, + void*, UINT, const void*, REFIID, void**); + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_RESOURCE_DESC target_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, side, side, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS}; + static void* target = nullptr; + if (FAILED(reinterpret_cast((*static_cast(guest))[127])(guest, &default_heap, 0, &target_desc, + D3D12_RESOURCE_STATE_COMMON, nullptr, nullptr, 0, nullptr, __uuidof(ID3D12Resource), &target)) || !target) + return 70; + D3D12_UNORDERED_ACCESS_VIEW_DESC target_view{DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_UAV_DIMENSION_TEXTURE2D}; + invoke(guest, 19, ptr(target), 0, ptr(&target_view), cpu + 8 * stride); + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + Word address, bytes; + } rtv_heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}, 0, 0}; + void* rtv_heap = nullptr; + if (FAILED(static_cast(invoke(guest, 14, ptr(&rtv_heap_desc), ptr(&__uuidof(ID3D12DescriptorHeap)), ptr(&rtv_heap))))) + return 73; + const D3D12_CPU_DESCRIPTOR_HANDLE rtv{static_cast(invoke(rtv_heap, 9))}; + const D3D12_RENDER_TARGET_VIEW_DESC target_rtv{DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RTV_DIMENSION_TEXTURE2D, {}}; + invoke(guest, 20, ptr(target), ptr(&target_rtv), rtv.ptr); + + struct Case { const char* name; int entry; int srv_entry; }; + static const Case cases[] = { + {"a", 0, -1}, {"b", 1, -1}, {"no-ua", 2, -1}, {"uint", 3, -1}, {"missing", 4, -1}, {"srv", 5, -1}, + {"mip1", 6, -1}, {"array", 7, -1}, {"out-of-range", 7, -1}, {"no-table", -1, -1}, {"srv-and-uav", 0, 5}, + {"target", 8, -1}, + }; + const Case* chosen = nullptr; + for (const Case& c : cases) + if (which == c.name) chosen = &c; + if (!chosen) return 74; + std::printf("pixel uav case %s: table entry %d, title descriptor stride %u\n", chosen->name, chosen->entry, stride); + if (which == "target") invoke(list, 50, 1, ptr(&rtv)); + invoke(list, 32, 1, ptr(&heap)); + if (chosen->entry >= 0) invoke(list, 36, 0, gpu + Word(chosen->entry) * stride); + if (chosen->srv_entry >= 0) invoke(list, 36, 1, gpu + Word(chosen->srv_entry) * stride); + invoke(list, 12, 3, 1); + return 0; +} + +// After the fence: every word of every subresource of the four textures, texture by texture, mip by mip, row by +// row, to .uav; then the debug layer's error count. +int report_pixel_uavs(const char* pixels) +{ + std::vector words; + const bool copied = copy_all(fixture.desktop, false, &words); + if (copied) { + std::ofstream out(std::string(pixels) + ".uav", std::ios::binary); + out.write(reinterpret_cast(words.data()), static_cast(words.size() * 4)); + if (!out) return 76; + } + const HRESULT removed = fixture.desktop->GetDeviceRemovedReason(); + std::printf("device removed reason: 0x%08lx\n", static_cast(removed)); + auto* messages = debug_messages(); + if (!messages) { + std::printf("debug layer: absent\n"); + return copied ? 0 : 75; + } + UINT errors = 0; + for (UINT64 i = 0; i < messages->GetNumStoredMessages(); ++i) { + SIZE_T size = 0; + if (FAILED(messages->GetMessage(i, nullptr, &size)) || !size) continue; + std::vector storage(size); + auto* message = reinterpret_cast(storage.data()); + if (FAILED(messages->GetMessage(i, message, &size)) || message->Severity > D3D12_MESSAGE_SEVERITY_ERROR) continue; + if (++errors <= 8) std::printf("debug layer error id %d: %.300s\n", static_cast(message->ID), message->pDescription); + } + std::printf("debug layer: on, errors: %u\n", errors); + return copied ? 0 : 75; +} diff --git a/tests/startup_pixel_uav_check.py b/tests/startup_pixel_uav_check.py new file mode 100644 index 000000000..4d02c50f1 --- /dev/null +++ b/tests/startup_pixel_uav_check.py @@ -0,0 +1,270 @@ +"""Bind a translated pixel-stage image store through the runtime (#1996 item F, runtime slice). + +The pixel program is the hand-assembled gfx1013 one of tests/startup_pixel_image_store_check.py: it loads an +image descriptor from table 0, stores 1.0, 2.0, 3.0 and 4.0 at texel (1, 2) and exports the same values. It is +published by startup_stream_consumer, translated by tools/startup/gfx2hlsl.py --pending (manifest line +'uav 0 tex2d table 0 0') and drawn through d3d12_xs.dll with X2W_TEST_PIXEL_UAV= +(tests/startup_pixel_uav.cpp). Each case is its own process. After the fence the fixture writes every word of +both mips of four 4x4 textures (A and B writable, C without ALLOW_UNORDERED_ACCESS, D typeless), each word a +distinct sentinel, and the debug layer's error count when the layer is on. + +Drawn: the table names A (case a) or B (case b, a view without a description). Texel (1, 2) of mip 0 of that +texture holds the four values; every other word of all four textures, both mips, keeps its sentinel. +Refused, each by its logged reason, with every word unchanged and no translated draw: a table entry with no +view, an SRV, a texture without ALLOW_UNORDERED_ACCESS, an integer view, a view of mip 1, a 2D-array view, an +entry outside the bound table, no table at the parameter, the same texture also bound as an SRV of the draw, and +a texture E that is also the draw's render target (bound through list slot 50). +Manifest lines: a view qualifier (float, uint, and the compute line with 'channels 4'), another image kind, a buffer +line, a 'channels' field and a view index out of order are refused when the manifest is loaded. +Exec: the v_cmpx variants of the program, through the same runtime path: exec on writes the texel, exec off +leaves it. Control: the exec-off shader recompiled with the guard removed from the store must write the texel, +and the check must report it. +""" +import os +from pathlib import Path +import shutil +import struct +import subprocess +import sys +import tempfile + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +from startup_stream_check import container, gfx2hlsl # noqa: E402 +from startup_stream_draw_check import vertex # noqa: E402 +from startup_pixel_image_store_check import BITS, EXEC_OFF, EXEC_ON, GUARDED_LINE, STORE_LINE, WORDS # noqa: E402 + +SIDE, MIPS, TEXTURES = 4, 2, 4 +WRITTEN = [int(b, 16) for b in BITS] +CLEAR, WHITE = bytes((0, 0, 255, 255)), bytes((255, 255, 255, 255)) +DRAWN_LINE = 'x2w-draw draw(3, 1, start 0, base 0) pipeline' + +# case: (table entry the fixture binds, texture written or None, reason logged, manifest edit) +CASES = { + 'a': (0, 0, None, None), + 'b': (1, 1, None, None), + 'missing': (4, None, 'uav 0 refused: table entry holds no view', None), + 'srv': (5, None, 'uav 0 refused: table entry is not an unordered-access view', None), + # The device skips a UAV over a resource without ALLOW_UNORDERED_ACCESS (#2649): no view is recorded, so the draw sees an empty entry. + 'no-ua': (2, None, 'uav 0 refused: table entry holds no view', None), + 'uint': (3, None, 'uav 0 refused: integer format for a float view', None), + 'mip1': (6, None, 'uav 0 refused: view names a mip other than 0', None), + 'array': (7, None, 'uav 0 refused: view is not a 2D texture view', None), + 'out-of-range': (7, None, 'uav 0 refused: table entry outside the bound table', + ('uav 0 tex2d table 0 0', 'uav 0 tex2d table 0 4096')), + 'no-table': (None, None, 'uav 0 refused: no descriptor table at the parameter', None), + 'srv-and-uav': (0, None, 'uav 0 refused: the texture is also an SRV of this draw', + ('uav 0 tex2d table 0 0', 'uav 0 tex2d table 0 0\nsrv 0 tex2d table 1 0')), + 'target': (8, None, 'uav 0 refused: the texture is also a render or depth target of this draw', None), +} + +# case: (replacement of 'uav 0 tex2d table 0 0', texture written or None, reason logged) +LINES = ( + ('a.float-line', 'uav 0 tex2d float table 0 0', None, 'uav line refused (a view qualifier is not read for pixel stores)'), + ('a.compute-line', 'uav 0 tex2d float table 0 0 channels 4', None, + 'uav line refused (a view qualifier is not read for pixel stores)'), + ('a.tex2da-line', 'uav 0 tex2da table 0 0', None, 'uav line refused (only tex2d views are bound)'), + ('a.buffer-line', 'uav 0 raw table 0 0', None, 'uav line refused (buffer view (raw uav) is not bound)'), + ('a.uint-line', 'uav 0 tex2d uint table 0 0', None, 'uav line refused (a view qualifier is not read for pixel stores)'), + ('a.channels-field', 'uav 0 tex2d table 0 0 channels 4', None, + 'uav line refused (unexpected field after the table offset)'), + ('a.second-view', 'uav 1 tex2d table 0 0', None, 'uav line refused (view index out of order)'), +) + + +def sentinel(t, m, texel, c): + return 0xc0000000 | t << 12 | m << 8 | texel << 2 | c + + +def expected_words(written): + words = [] + for t in range(TEXTURES): + for m in range(MIPS): + n = SIDE >> m + for texel in range(n * n): + for c in range(4): + hit = t == written and m == 0 and texel == 2 * n + 1 + words.append(WRITTEN[c] if hit else sentinel(t, m, texel, c)) + return words + + +def describe(index): + """texture, mip, texel and channel of word index of the .uav file.""" + for t in range(TEXTURES): + for m in range(MIPS): + n = SIDE >> m + if index < n * n * 4: + texel, c = divmod(index, 4) + return 'texture %s mip %d texel (%d, %d) word %d' % ('ABCD'[t], m, texel % n, texel // n, c) + index -= n * n * 4 + return 'word past the end' + + +class Program: + """One pixel program published and translated into its own cache.""" + + def __init__(self, directory, consumer, words, env): + self.directory, self.consumer = directory, consumer + directory.mkdir() + self.cache = directory / 'cache' + self.cache.mkdir() + self.vs, self.ps, self.root = (directory / name for name in ('vs', 'ps', 'root')) + self.vs.write_bytes(vertex()) + self.ps.write_bytes(container(0, list(struct.unpack('<%dI' % (len(words) // 4), words)))) + publish = dict(env, X2W_SHADER_CACHE=str(self.cache), X2W_TEST_PIXEL_UAV='a') + publish.pop('X2W_TEST_DEBUG_LAYER', None) + subprocess.run([consumer, self.vs, self.ps, self.root], env=publish, check=True) + subprocess.run([sys.executable, '-B', gfx2hlsl.__file__, '--pending', self.cache], env=publish, check=True) + self.manifest, = self.cache.glob('*.txt') + lines = self.manifest.read_text(encoding='ascii').splitlines() + assert lines[0] == 'x2w-manifest 2' and 'uav 0 tex2d table 0 0' in lines and not any( + line.startswith('srv ') for line in lines), lines + + +def run_case(program, name, env, backend, cache=None): + """Returns (returncode, stdout, trap log, render target bytes, texture words).""" + folder = program.directory / name + folder.mkdir() + output, trap = folder / 'pixels', folder / 'trap.log' + case_env = dict(env, X2W_SHADER_CACHE=str(cache or program.cache), X2W_TEST_PIXEL_UAV=name.split('.')[0], + X2W_TRAP_LOG=str(trap)) + run = subprocess.run([program.consumer, program.vs, program.ps, program.root, backend, output], env=case_env, + capture_output=True, text=True) + if run.returncode == 77 and 'no debug layer: skipped' in run.stdout and 'X2W_TEST_DEBUG_LAYER' in env: + # Rule of the neighbouring fixtures: the debug layer is a condition, not a requirement. + print('%s: no debug layer on this machine, run without it' % name) + shutil.rmtree(folder) + env.pop('X2W_TEST_DEBUG_LAYER') + return run_case(program, name, env, backend, cache) + log = trap.read_text(errors='replace') if trap.exists() else '' + pixels = output.read_bytes() if output.exists() else b'' + uav = Path(str(output) + '.uav') + words = list(struct.unpack('<%dI' % (uav.stat().st_size // 4), uav.read_bytes())) if uav.exists() else [] + return run.returncode, run.stdout + run.stderr, log, pixels, words + + +def verdict(name, result, written, reason, drawn): + """None when the case holds, otherwise the first difference.""" + returncode, out, log, pixels, words = result + if returncode: + return 'consumer exited %d\n%s' % (returncode, out[-3000:]) + if 'device removed reason: 0x00000000' not in out: + return 'device removed or no report\n%s' % out[-3000:] + if 'debug layer: on' in out and 'debug layer: on, errors: 0' not in out: + return 'debug layer errors\n%s' % out[-3000:] + want = expected_words(written) + if len(words) != len(want): + return '%d texture words read back, expected %d' % (len(words), len(want)) + for i, (got, expected) in enumerate(zip(words, want)): + if got != expected: + return 'texel_mismatch %s: got %08x, expected %08x' % (describe(i), got, expected) + if (DRAWN_LINE in log) != drawn: + return 'translated draw %s' % ('missing' if drawn else 'present although refused') + if reason and reason not in log: + return 'reason "%s" not logged\n%s' % (reason, log[-3000:]) + if drawn is not None and name in ('a', 'b'): + rows = [pixels[i:i + 32] for i in range(0, len(pixels), 32)] + want_row = WHITE * 4 + CLEAR * 4 + if len(rows) != 4 or any(row != want_row for row in rows): + return 'render target %s, expected the left half white' % pixels.hex() + if not drawn and pixels != CLEAR * 32: + return 'render target changed by a refused draw: %s' % pixels.hex() + return None + + +def recompile_without_guard(program, folder): + """A copy of the exec-off cache whose pixel shader stores without the exec guard.""" + cache = folder / 'cache_unguarded' + shutil.copytree(program.cache, cache) + hlsl, = cache.glob('*.ps.hlsl') + text = hlsl.read_text() + assert (' ' + GUARDED_LINE) in text, text + hlsl.write_text(text.replace(GUARDED_LINE, STORE_LINE)) + fxc = gfx2hlsl.find_fxc() + if not fxc: + return None + cso = hlsl.with_name(hlsl.name.replace('.hlsl', '.cso')) + subprocess.run([fxc, '/nologo', '/T', 'ps_5_1', '/E', 'main', '/Fo', str(cso), str(hlsl)], check=True, + capture_output=True) + return cache + + +def check(directory, consumer, backend): + env = dict(os.environ, X2W_D3D12_PERMISSIVE='1', X2W_D3D12_LIST_NOOP='1', X2W_D3D12_RENDER='1', + X2W_D3D12_DEBUG='0', X2W_D3D12_DEVICE_NOOP='1', X2W_TEST_DEBUG_LAYER='1') + if os.environ.get('X2W_PIXEL_UAV_NO_DEBUG') == '1': + env.pop('X2W_TEST_DEBUG_LAYER') + store = Program(directory / 'store', consumer, WORDS, env) + failures = [] + + def expect(program, name, written, reason, drawn, cache=None): + result = run_case(program, name, env, backend, cache) + if result[0] == 77: + print(result[1]) + sys.exit(77) + problem = verdict(name, result, written, reason, drawn) + adapter = next((line for line in result[1].splitlines() if line.startswith('adapter=')), '') + layer = next((line for line in result[1].splitlines() if line.startswith('debug layer:')), 'debug layer: ?') + stride = next((line.rsplit(' ', 1)[1] for line in result[1].splitlines() if 'title descriptor stride' in line), '?') + layer += '; descriptor stride ' + stride + if problem: + failures.append('%s: %s' % (name, problem)) + print('FAIL %s: %s' % (name, problem.splitlines()[0])) + for line in result[1].splitlines(): + if line.startswith(('debug layer', 'device removed')): + print(' ' + line) + else: + what = ('texel (1, 2) of texture %s written, every other word unchanged' % 'ABCD'[written] if written is not None + else 'every word unchanged') + print('%-13s %s; %s%s [%s; %s]' % (name + ':', 'drawn' if drawn else 'refused', what, + (' (' + reason + ')') if reason else '', adapter, layer)) + return problem + + for name, (_, written, reason, edit) in CASES.items(): + if edit: + text = store.manifest.read_text(encoding='ascii') + assert edit[0] in text + store.manifest.write_text(text.replace(edit[0], edit[1]), encoding='ascii') + try: + expect(store, name, written, reason, written is not None) + finally: + if edit: + store.manifest.write_text(text, encoding='ascii') + # Other forms of the manifest line, table entry 0: load_translation refuses the translation and nothing is drawn. + text = store.manifest.read_text(encoding='ascii') + for name, replacement, written, reason in LINES: + store.manifest.write_text(text.replace('uav 0 tex2d table 0 0', replacement), encoding='ascii') + try: + expect(store, name, written, reason, written is not None) + finally: + store.manifest.write_text(text, encoding='ascii') + + exec_on = Program(directory / 'exec_on', consumer, EXEC_ON, env) + exec_off = Program(directory / 'exec_off', consumer, EXEC_OFF, env) + for program in (exec_on, exec_off): + assert (' ' + GUARDED_LINE) in next(program.cache.glob('*.ps.hlsl')).read_text() + expect(exec_on, 'a.exec-on', 0, None, True) + expect(exec_off, 'a.exec-off', None, None, True) + # Control: the exec-off shader without the guard writes the texel, and the check above must catch it. + unguarded = recompile_without_guard(exec_off, directory) + if unguarded is None: + print('control exec guard removed: no fxc, not run') + else: + result = run_case(exec_off, 'a.exec-off-unguarded', env, backend, unguarded) + problem = verdict('a', result, None, None, True) + needle = 'texel_mismatch texture A mip 0 texel (1, 2) word 0: got %08x, expected %08x' % (WRITTEN[0], sentinel(0, 0, 9, 0)) + if not problem or not problem.startswith(needle): + failures.append('control exec guard removed was not detected: %s' % problem) + else: + print('control exec guard removed: fails as expected (%s)' % problem) + if failures: + raise SystemExit('\n'.join(failures)) + print('%s: %d cases and the exec guard control' % (backend, len(CASES) + len(LINES) + 2)) + return 0 + + +if __name__ == '__main__': + if len(sys.argv) != 3: + raise SystemExit(__doc__) + with tempfile.TemporaryDirectory() as temporary: + sys.exit(check(Path(temporary), *sys.argv[1:])) diff --git a/tests/startup_stream_consumer.cpp b/tests/startup_stream_consumer.cpp index 6be711e5e..8d672d385 100644 --- a/tests/startup_stream_consumer.cpp +++ b/tests/startup_stream_consumer.cpp @@ -483,7 +483,8 @@ int main(int argc, char** argv) const bool textured = bc7.blocks != nullptr || GetEnvironmentVariableW(L"X2W_TEST_D16_SRV", nullptr, 0) != 0 || GetEnvironmentVariableW(L"X2W_TEST_FORMATTED_BUFFER", nullptr, 0) != 0 || GetEnvironmentVariableW(L"X2W_TEST_FORMATTED_VIEW", nullptr, 0) != 0 || - GetEnvironmentVariableW(L"X2W_TEST_JOINED_TABLE", nullptr, 0) != 0; + GetEnvironmentVariableW(L"X2W_TEST_JOINED_TABLE", nullptr, 0) != 0 || + GetEnvironmentVariableW(L"X2W_TEST_PIXEL_UAV", nullptr, 0) != 0; if (const int rc = prepare_stream_pipeline(argv[1], argv[2], argv[3], hardware, textured, adapter, device, pso)) return rc; // slot67 [case]: WARP device and root only, then slot-67 creations. diff --git a/tests/startup_stream_draw.cpp b/tests/startup_stream_draw.cpp index ed6e4717b..3f2405a97 100644 --- a/tests/startup_stream_draw.cpp +++ b/tests/startup_stream_draw.cpp @@ -347,6 +347,9 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* } else if (GetEnvironmentVariableW(L"X2W_TEST_D16_SRV", nullptr, 0)) { extern int draw_d16_srvs(ID3D12Device*, void*, void*); if (const int result = draw_d16_srvs(desktop.Get(), guest, list)) return result; + } else if (GetEnvironmentVariableW(L"X2W_TEST_PIXEL_UAV", nullptr, 0)) { + extern int draw_pixel_uavs(ID3D12Device*, void*, void*); + if (const int result = draw_pixel_uavs(desktop.Get(), guest, list)) return result; } else if (GetEnvironmentVariableW(L"X2W_TEST_VERTEX_FETCH", nullptr, 0)) { // TEXCOORD float3 in slot 0 and POSITION float3 in slot 1, 12 bytes each; vertices 0-2 are unused. Vertices // 3-8 are drawn from start vertex 3: positions cover pixels [1, 3) x [1, 3) of the 8x4 target, texture @@ -492,6 +495,10 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* last = 2; } if (const int rc = submit(last)) return rc; + if (GetEnvironmentVariableW(L"X2W_TEST_PIXEL_UAV", nullptr, 0)) { + extern int report_pixel_uavs(const char*); + if (const int rc = report_pixel_uavs(pixels)) return rc; + } if (GetEnvironmentVariableW(L"X2W_TEST_ROOT_CBV", nullptr, 0)) { extern int root_heap_report(); if (const int rc = root_heap_report()) return rc; From 53b4b8cc974f0479bcb55e594389d4eb409564ec Mon Sep 17 00:00:00 2001 From: SimSalabimse <83839581+SimSalabimse@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:38:52 +0100 Subject: [PATCH 080/240] shader: lower s_quadmask_b32 in gfx2hlsl (Part of #1723) (#2642) * shader: lower s_quadmask_b32 in gfx2hlsl (#1723) Port the pixel_aot nibble-collapse SOP1 (each 4-bit group to one bit of D). SCC is the nonzero test of the result. Lane masks and descriptor words are refused. CPU fixture with a negative control. Co-authored-by: SimSalabimse * test: add D3D12 WARP dispatch readback for s_quadmask_b32 Co-authored-by: SimSalabimse * docs: note s_quadmask_b32 WARP dispatch ctest Co-authored-by: SimSalabimse * test: allow s_mul_hi_* own-arity templates in scalar table check #2405 added s_mul_hi_i32 (and an early arity refuse for both mul_hi forms). The negative control still expected only one non-IndexError survivor. Co-authored-by: SimSalabimse --------- Co-authored-by: Cursor Agent Co-authored-by: SimSalabimse Co-authored-by: tedin7 --- .github/workflows/windows.yml | 1 + AGENTS.md | 1 + CMakeLists.txt | 10 + docs/experiments.md | 12 + tests/startup_gfx2hlsl_s_quadmask_check.py | 244 +++++++++++++++++++++ tools/startup/gfx2hlsl.py | 43 ++++ 6 files changed, 311 insertions(+) create mode 100644 tests/startup_gfx2hlsl_s_quadmask_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index ecda84488..920e1f3af 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -321,6 +321,7 @@ jobs: tests/startup_gfx2hlsl_s_bitset_check.py \ tests/startup_gfx2hlsl_s_flbit_check.py \ tests/startup_gfx2hlsl_s_ff1_check.py \ + tests/startup_gfx2hlsl_s_quadmask_check.py \ tests/startup_gfx2hlsl_fma_mix_check.py \ tests/startup_gfx2hlsl_shift64_check.py \ tests/startup_gfx2hlsl_mul_hi_i32_check.py \ diff --git a/AGENTS.md b/AGENTS.md index bc3d72607..388a15055 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -178,6 +178,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_s_bitset_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_s_flbit_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_s_ff1_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_s_quadmask_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_fma_mix_check.py ./out/pe-env/bin/python -B tests/startup_image_2d_array_check.py ./out/pe-env/bin/python -B tests/startup_image_sample_a16_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index deb088e8f..1c3c9b356 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3387,6 +3387,16 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(startup_gfx2hlsl_s_ff1_dispatch_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl lowers s_quadmask_b32 (SOP1, #1723): CPU evaluation, then a D3D12 UAV + # readback on WARP/hardware (same dispatch pattern as s_ff1 / s_abs / pack_absdiff). + add_test(NAME startup_gfx2hlsl_s_quadmask COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_quadmask_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_s_quadmask_dispatch_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_quadmask_check.py" dispatch "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_gfx2hlsl_s_quadmask_dispatch_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl lowers v_cube{id,sc,tc,ma}_f32: device-free translation controls. add_test(NAME startup_gfx2hlsl_cube_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_cube_check.py") diff --git a/docs/experiments.md b/docs/experiments.md index d99e8fff6..1636ef535 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -8202,6 +8202,18 @@ against the same reference (including `flbit(0) == 0xffffffff`): `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_s_flbit_dispatch_warp$' -V`. [Refs #1723](https://github.com/R0Y00/Xbox2Windows/issues/1723). +**Scalar quad mask.** Startup translation lowers `s_quadmask_b32` so each +output bit is the OR of one four-bit group of the source (8-bit result), with +`SCC = (D != 0)`, matching `pixel_aot`. Lane masks and descriptor-bearing +sources are refused. The 64-bit form stays refused. Run +`ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_s_quadmask$' -V` +(or `python3 -B tests/startup_gfx2hlsl_s_quadmask_check.py`). The +`_dispatch_warp` / `_dispatch_hardware` variants compile the translated +expression into a compute shader and compare UAV readback for 0, a low +nibble, bit 31 and `0x000f0000` (plus an SCC-dependent branch token): +`ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_s_quadmask_dispatch_warp$' -V`. +[Refs #1723](https://github.com/R0Y00/Xbox2Windows/issues/1723). + **Scalar immediate comparisons.** The startup translator sign-extends the 16-bit field of `s_movk_i32` and `s_cmpk_*_i32`, and zero-extends the field of `s_cmpk_*_u32`. The source-built check covers all six relations against diff --git a/tests/startup_gfx2hlsl_s_quadmask_check.py b/tests/startup_gfx2hlsl_s_quadmask_check.py new file mode 100644 index 000000000..b1c80d6f7 --- /dev/null +++ b/tests/startup_gfx2hlsl_s_quadmask_check.py @@ -0,0 +1,244 @@ +"""s_quadmask_b32 in tools/startup/gfx2hlsl.py (#1723). + +usage: startup_gfx2hlsl_s_quadmask_check.py + startup_gfx2hlsl_s_quadmask_check.py dispatch + +RDNA 2 ISA SOP1: each output bit is the OR of one four-bit group of S0 (8-bit +result). SCC = (D != 0). Matches pixel_aot. Lane masks and descriptor sources +are refused. The reference is plain Python; the translated text is evaluated on +the CPU. + +With `dispatch`, the lowering runs as a compute shader on the adapter (D3D12 UAV +readback via offscreen_check, same pattern as startup_gfx2hlsl_s_ff1_check / +startup_gfx2hlsl_s_abs_check). Each case stores D, SCC, and an SCC-dependent +branch token so the nibble collapse and nonzero SCC test are exercised on device. +""" +import re +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import disasm_rdna2 as D # noqa: E402 +import gfx2hlsl as G # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import Expr # noqa: E402 + +MASK = 0xffffffff +SOP1 = {name: op for op, (name, _) in D.SOP1_OPS.items()} +WORDS = (0x00000000, 0xffffffff, 0x00000001, 0x80000000, 0x11111111, 0x000f0000, 0x12345678, 0xf0f0f0f0) +# GPU cases: zero (SCC clear), low nibble, high bit, mid nibble-only. +DRAW = (0x00000000, 0x0000000f, 0x80000000, 0x000f0000) +SCC_BRANCH_TAKEN = 0x00a11ced +SCC_BRANCH_NOT = 0x00dead00 +VCC_LO, EXEC_LO = 106, 126 + +failures = [] + + +def check(label, ok, detail=''): + print('%s: %s' % (label, 'ok' if ok else 'MISMATCH'), flush=True) + if not ok: + failures.append(label) + if detail: + print(' ' + detail) + + +def sop1(name, sdst, ssrc): + return struct.pack('> (4 * group)) & 0xf) != 0) << group for group in range(8)) + + +class Probe(G.Stage): + def __init__(self): + self.lines, self.sym = [], {} + self.used_s, self.used_v, self.uniform_v = set(), set(), set() + self.masks = set() + self.exec_known = True + + +def translate(words, masks=(), sym=None): + decoded = G.decode(words) + assert len(decoded) == 1 and decoded[0][1] == len(words), decoded + stage = Probe() + stage.masks = set(masks) + if sym: + stage.sym.update(sym) + try: + stage.one(decoded[0][2], decoded[0][3]) + except G.Unsupported as error: + stage.lines = ['refused: %s' % error] + return stage.lines, stage.sym + + +def run(lines, env): + env = dict(env) + for line in lines: + m = re.fullmatch(r'(\w+) = (.*);', line) + assert m, line + env[m.group(1)] = Expr(m.group(2)).run(env)[0] + return env + + +def controls(): + bad = None + lines, _ = translate(sop1('s_quadmask_b32', 3, 1)) + assert lines and not lines[0].startswith('refused'), lines + for word in WORDS: + out = run(lines, {'s1': word, 'scc': 0}) + want = (quadmask32(word), int(quadmask32(word) != 0)) + if (out['s3'], int(bool(out['scc']))) != want: + bad = (hex(word), (out['s3'], out['scc']), want) + break + check('s_quadmask_b32 SGPR source', bad is None, str(bad)) + + bad = None + for word in WORDS: + stage = Probe() + try: + stage.one('s_quadmask_b32', 's_quadmask_b32 s3, %d' % word) + except G.Unsupported as error: + bad = ('refused %s' % error,) + break + out = run(stage.lines, {'scc': 0}) + want = (quadmask32(word), int(quadmask32(word) != 0)) + if (out['s3'], int(bool(out['scc']))) != want: + bad = (hex(word), (out['s3'], out['scc']), want) + break + check('s_quadmask_b32 immediate source', bad is None, str(bad)) + + # 0x000f0000 -> nibble 4 set -> bit 4 -> 0x10 + lines, sym = translate(sop1('s_quadmask_b32', 3, 1), sym={1: ('const', 0x000f0000)}) + check('s_quadmask_b32 folds a constant source', + lines[0].startswith('s3 = 0x00000010u;') and sym.get(3) == ('const', 0x10) + and any(l.startswith('scc = ') for l in lines), + str((lines, sym.get(3)))) + + refused = [translate(sop1('s_quadmask_b32', d, s))[0][0] for d, s in ( + (3, VCC_LO), (3, EXEC_LO), (VCC_LO, 1), (EXEC_LO, 1))] + check('s_quadmask_b32 refuses lane-mask destinations/sources', + all(r.startswith('refused: ') for r in refused), str(refused)) + + stage = Probe() + stage.masks.add(1) + try: + stage.one('s_quadmask_b32', 's_quadmask_b32 s3, s1') + check('s_quadmask_b32 refuses a tracked lane-mask source', False, stage.lines) + except G.Unsupported as error: + check('s_quadmask_b32 refuses a tracked lane-mask source', 'lane mask' in str(error), str(error)) + + stage = Probe() + stage.sym[1] = ('desc', ('root', 0), 0, 0) + try: + stage.one('s_quadmask_b32', 's_quadmask_b32 s3, s1') + check('s_quadmask_b32 refuses a descriptor source', False, stage.lines) + except G.Unsupported as error: + check('s_quadmask_b32 refuses a descriptor source', 'desc' in str(error), str(error)) + + # Negative control: drop the first nibble contribution; must diverge. + stage = Probe() + stage.one('s_quadmask_b32', 's_quadmask_b32 s3, s1') + mutated = [re.sub(r'\(\(s1 & 0xfu\) != 0u \? 1u : 0u\)', '0u', stage.lines[0], count=1)] + assert mutated != stage.lines, stage.lines + out_ok = run(stage.lines, {'s1': 0x0000000f, 'scc': 0}) + out_bad = run([mutated[0]] + stage.lines[1:], {'s1': 0x0000000f, 'scc': 0}) + check('mutation that drops the first nibble bit diverges', + out_ok['s3'] == 1 and out_bad['s3'] == 0, + str((out_ok['s3'], out_bad['s3']))) + + if failures: + print('FAILED: %s' % ', '.join(failures)) + sys.exit(1) + print('all ok') + + +def dispatch_quadmask(dxc, runner, adapter, cases, directory): + """Translate s_quadmask_b32 once; feed each case through a UAV and read D, SCC, and a branch token.""" + lines, _ = translate(sop1('s_quadmask_b32', 3, 1)) + assert lines and not lines[0].startswith('refused'), lines + fill = tuple(((i + 1) * 0x9e3779b1 & MASK) | 1 for i in range(len(cases))) + result_width = 3 + hlsl = ['RWByteAddressBuffer data : register(u0);', '[numthreads(1, 1, 1)]', 'void main() {'] + for i, word in enumerate(cases): + dst_byte = 4 * (len(fill) + result_width * i) + hlsl.extend(( + ' {', + ' uint s1 = data.Load(%d) ^ %s;' % (4 * i, '%#010xu' % (fill[i] ^ word)), + ' uint s3;', + ' bool scc = true;', + )) + hlsl.extend(' ' + line for line in lines) + hlsl.append(' data.Store(%d, s3);' % dst_byte) + hlsl.append(' data.Store(%d, uint(scc));' % (dst_byte + 4)) + hlsl.append(' if (scc) {') + hlsl.append(' data.Store(%d, %#010xu);' % (dst_byte + 8, SCC_BRANCH_TAKEN)) + hlsl.append(' } else {') + hlsl.append(' data.Store(%d, %#010xu);' % (dst_byte + 8, SCC_BRANCH_NOT)) + hlsl.append(' }') + hlsl.append(' }') + hlsl.append('}') + + src, cso, output = (directory / ('s_quadmask_b32' + suffix) for suffix in ('.hlsl', '.cso', '.bin')) + src.write_text('\n'.join(hlsl) + '\n', encoding='ascii') + compile_result = subprocess.run([dxc, '-T', 'cs_6_0', '-E', 'main', '-Fo', str(cso), str(src)], + stderr=subprocess.PIPE, text=True) + if compile_result.returncode or compile_result.stderr: + raise AssertionError(compile_result.stderr or 'DXC exited with %d' % compile_result.returncode) + word_count = len(fill) + result_width * len(cases) + dump_words = (word_count + 3) // 4 * 4 + run_result = subprocess.run( + [runner, adapter, '--raw-uav-dump', str(cso), '1', str(4 * dump_words), str(output)], + capture_output=True, text=True) + print(run_result.stdout, end='') + if run_result.returncode == 77: + sys.exit(77) + if run_result.returncode or run_result.stderr: + raise AssertionError(run_result.stderr or 'raw UAV dump exited with %d' % run_result.returncode) + actual = struct.unpack('<%dI' % dump_words, output.read_bytes()) + assert actual[:len(fill)] == fill, 'operand region changed: %s' % (actual[:len(fill)],) + return actual[len(fill):word_count] + + +def check_dispatch(dxc, runner, adapter): + controls() + runner = str(Path(runner).resolve()) + out = HERE.parent / 'out' + out.mkdir(exist_ok=True) + with tempfile.TemporaryDirectory(dir=out) as tmp: + got = dispatch_quadmask(dxc, runner, adapter, DRAW, Path(tmp)) + for i, word in enumerate(DRAW): + result = quadmask32(word) + scc_v = int(result != 0) + branch = SCC_BRANCH_TAKEN if scc_v else SCC_BRANCH_NOT + base = 3 * i + label = 'dispatch s_quadmask_b32 %#010x' % word + check('%s result' % label, got[base] == result, + 'got %#x want %#x' % (got[base], result)) + check('%s SCC' % label, got[base + 1] == scc_v, + 'got %#x want %#x' % (got[base + 1], scc_v)) + check('%s SCC branch' % label, got[base + 2] == branch, + 'got %#x want %#x' % (got[base + 2], branch)) + check('dispatch quadmask(0) clears SCC', + got[1] == 0 and got[2] == SCC_BRANCH_NOT, + str((got[1], got[2]))) + check('dispatch quadmask(0x000f0000) is 0x10', got[3 * 3] == 0x10, hex(got[3 * 3])) + if failures: + print('FAILED: %s' % ', '.join(failures)) + sys.exit(1) + print('dispatch ok') + + +if __name__ == '__main__': + if len(sys.argv) == 1: + controls() + elif len(sys.argv) == 5 and sys.argv[1] == 'dispatch': + check_dispatch(*sys.argv[2:]) + else: + sys.exit(__doc__) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 925ca2ffb..93b4ac26c 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -6028,6 +6028,49 @@ def op_s_flbit_i32_b32(self, ops, mods): return None + def op_s_quadmask_b32(self, ops, mods): + """Collapse each nibble of S0 to one bit of D; SCC = result != 0 (#1723). + + RDNA 2 ISA SOP1 / pixel_aot: bit g of D is 1 iff nibble g of S0 is nonzero. + Lane masks and descriptor-bearing SGPRs are refused. The 64-bit form stays out of scope. + """ + if mods or len(ops) != 2: + raise Unsupported('s_quadmask_b32 with %d operands, expected 2 unmodified' % len(ops)) + dst = reg_range(ops[0]) + if not dst or dst[0] != 's' or dst[1] != dst[2] or dst[1] > 105: + raise Unsupported('s_quadmask_b32 destination %s' % ops[0]) + if self.is_lane_mask(ops[0]) or dst[1] in self.masks: + raise Unsupported('s_quadmask_b32 on a lane mask') + imm = re.fullmatch(r'-?(0x[0-9a-fA-F]+|\d+)', ops[1]) + if imm: + value = int(ops[1], 0) & 0xffffffff + folded = 0 + for group in range(8): + if value & (0xf << (group * 4)): + folded |= 1 << group + self.set_s(dst[1], '0x%08xu' % folded, ('const', folded), scc='$ != 0') + return None + src = reg_range(ops[1]) + if not src or src[0] != 's' or src[1] != src[2] or src[1] > 105: + raise Unsupported('s_quadmask_b32 source %s' % ops[1]) + if self.is_lane_mask(ops[1]) or src[1] in self.masks: + raise Unsupported('s_quadmask_b32 on a lane mask') + sym = self.sym.get(src[1]) + if sym and sym[0] not in ('const', 'ud', 'fixed_buffer_word'): + raise Unsupported('s_quadmask_b32 on %s data' % sym[0]) + if sym and sym[0] == 'const': + value = sym[1] & 0xffffffff + folded = 0 + for group in range(8): + if value & (0xf << (group * 4)): + folded |= 1 << group + self.set_s(dst[1], '0x%08xu' % folded, ('const', folded), scc='$ != 0') + return None + src_u = self.u(ops[1]) + parts = ['((%s & 0x%xu) != 0u ? %du : 0u)' % (src_u, 0xf << (g * 4), 1 << g) for g in range(8)] + self.set_s(dst[1], '(%s)' % ' | '.join(parts), scc='$ != 0') + return None + # ---- slot 57 mesh stage: instructions mesh_skeleton() puts in place of the group-memory exchanges ---- def op_x2w_mesh_lane0(self, ops, mods): # `s_mov_b64 exec, 1` leaves lane 0 of each wave running. The saved copy of that mask is not modelled. From 0b6bcf161ae25f1cbd50ff3480b59f238e6fcb13 Mon Sep 17 00:00:00 2001 From: RavenCurseBurg Date: Thu, 26 Nov 2026 10:39:23 +0800 Subject: [PATCH 081/240] tests: preserve adapter-selection notices in compute readfirstlane readbacks (#2693) Co-authored-by: RavenCurseBurg <360931527+RavenCurseBurg@users.noreply.github.com> --- tests/startup_compute_readfirstlane_check.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/tests/startup_compute_readfirstlane_check.py b/tests/startup_compute_readfirstlane_check.py index c229be9e2..56cf8f2ab 100644 --- a/tests/startup_compute_readfirstlane_check.py +++ b/tests/startup_compute_readfirstlane_check.py @@ -231,14 +231,20 @@ def dispatch(dxc, runner, adapter): print(proc.stdout, end='') if proc.returncode == 77: return 77 + diagnostics = [] + for line in proc.stderr.splitlines(): + if adapter == 'hardware' and line.startswith('XBOX2WINDOWS_ADAPTER: skipping '): + print(line, file=sys.stderr) + else: + diagnostics.append(line) if mutation: want = CONTROLS[mutation][2] - first = proc.stderr.strip().splitlines()[:1] + first = diagnostics[:1] if proc.returncode != 1 or first != [want]: raise AssertionError('control %s: expected exit 1 with %r, got exit %d %r' % (mutation, want, proc.returncode, proc.stderr)) print('control %s (%s): rejected at %s' % (mutation, adapter, first[0])) - elif proc.returncode or proc.stderr: + elif proc.returncode or diagnostics: raise AssertionError('baseline (%s): %s' % (adapter, proc.stderr or 'exit %d' % proc.returncode)) else: print('baseline (%s): all %d words match' % (adapter, WORDS)) From 3b2453d57a629129dd13e1a39502ff8ae5d378e6 Mon Sep 17 00:00:00 2001 From: Matheus Sergio Date: Wed, 25 Nov 2026 23:39:28 -0300 Subject: [PATCH 082/240] startup: lower scalar null operand and guard non-SGPR SALU destinations in gfx2hlsl (#2698) Lower the RDNA 2 `null` scalar operand (`code 125`) and replace `reg_range(...)[1]` `TypeError` crashes on non-SGPR scalar destinations with explicit `Unsupported` refusals in `tools/startup/gfx2hlsl.py`: - Read `null` (`125`) as wave-uniform `0x00000000u` in `Stage.u`, `Stage.const_u32`, `Stage.uniform_source`, `Stage.scalar_const`, `SCALAR_CONST_FOLD`, `scalar_bitset`, `op_s_bfm_b32`, and `VOP3_ONLY_VEC_U` in `Stage.lower`. - Lower 32-bit plain numeric/constant SALU writes to `null` in `Stage.scalar` and `op_s_bfm_b32`, discarding the register write while still emitting modeled `SCC` updates (`s_and_b32`, `s_or_b32`, `s_xor_b32`, `s_andn2_b32`, `s_orn2_b32`, `s_not_b32`, `s_nand_b32`, `s_nor_b32`, `s_xnor_b32`, `s_lshl_b32`, `s_lshr_b32`, `s_ashr_i32`, `s_bfe_u32`, `s_absdiff_i32`) and preserving `SCC` on non-SCC writes (`s_mov_b32`, `s_movk_i32`, `s_brev_b32`, `s_mul_i32`, `s_bfm_b32`). - Refuse `_b64`, lane-mask (`exec`/`vcc`/mask SGPR), `SCC_UNMODELLED`, and descriptor/pointer writes to `null`, as well as unmodelled scalar destinations (`vcc_hi`, `exec_hi`, `ttmp*`), with explicit `gfx2hlsl.Unsupported` reasons instead of `TypeError`. Add `tests/startup_gfx2hlsl_scalar_null_check.py` covering LLVM 15 `llvm-mc` / `libLLVM` round-trips, boundary `SCC` evaluation across all 14 32-bit SCC-writing SALU ops, destination refusal sweeps across all 48 `SCA` ops plus `s_bfm_b32`, and WARP / hardware D3D12 pixel draws (`FXC ps_5_1` + `DXC ps_6_0`) and root-constant SALU+branch buffer readbacks with negative controls. Refs #2618, #1723, #2463. AI-assisted. --- .github/workflows/windows.yml | 3 + AGENTS.md | 1 + CMakeLists.txt | 11 + docs/experiments.md | 14 + tests/startup_gfx2hlsl_scalar_null_check.py | 654 ++++++++++++++++++++ tools/startup/gfx2hlsl.py | 59 +- 6 files changed, 733 insertions(+), 9 deletions(-) create mode 100644 tests/startup_gfx2hlsl_scalar_null_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 920e1f3af..ac4d983e9 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -95,6 +95,8 @@ jobs: (["tests/startup_gfx2hlsl_cvt_pk_u8_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_cvt_pk_int16_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_cvt_pk_int16_check.py", "decode", "libLLVM-15.so.1"], {}), + (["tests/startup_gfx2hlsl_scalar_null_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_gfx2hlsl_scalar_null_check.py", "decode", "libLLVM-15.so.1"], {}), (["tests/startup_gfx2hlsl_cmp16_check.py", "binary", "llvm-mc-15", "llvm-objcopy-15"], {}), (["tests/startup_image_sample_l_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_image_sample_b_check.py", "binary", "llvm-mc-15"], {}), @@ -262,6 +264,7 @@ jobs: tests/startup_gfx2hlsl_cvt_alu_check.py \ tests/startup_gfx2hlsl_cvt_pk_u8_check.py \ tests/startup_gfx2hlsl_cvt_pk_int16_check.py \ + tests/startup_gfx2hlsl_scalar_null_check.py \ tests/startup_gfx2hlsl_cvt_off_f32_i4_check.py \ tests/startup_gfx2hlsl_int_med3_check.py \ tests/startup_gfx2hlsl_cselect_mask_check.py \ diff --git a/AGENTS.md b/AGENTS.md index 388a15055..47b0ead30 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -267,6 +267,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_image_arity_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_sad_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_cvt_pk_int16_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_scalar_null_check.py ``` `tests/pixel_aot_check.py binary` additionally needs LLVM with gfx1013 support diff --git a/CMakeLists.txt b/CMakeLists.txt index 1c3c9b356..23b9d4844 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3651,6 +3651,17 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_gfx2hlsl_cvt_pk_int16_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl RDNA 2 scalar null operand (code 125) and Stage.scalar destination guards (#2618, #1723, #2463): + # 32-bit null-destination SCC updates, null source (0u), explicit Unsupported refusals replacing TypeError, and + # WARP/hardware draws + root-constant buffer readbacks with negative controls. + add_test(NAME startup_gfx2hlsl_scalar_null_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_scalar_null_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_scalar_null_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_scalar_null_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_scalar_null_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl v_cvt_off_f32_i4 (VOP1 0x0e and VOP3A 0x18e): signed 4-bit nibble conversion with output modifiers, # low16_only provenance, uniformity tracking, refusals, and WARP/hardware draws with mutated controls. add_test(NAME startup_gfx2hlsl_cvt_off_f32_i4_controls COMMAND "${INTAKE_PYTHON}" -B diff --git a/docs/experiments.md b/docs/experiments.md index 1636ef535..ea6458732 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -16590,3 +16590,17 @@ ctest --preset dev --no-tests=error -R '^(pixel_aot_sdwa_cvt_warp|pixel_aot_sdwa ``` Linux controls, `form_coverage_check.check_sdwa_cvt_forms`, and Python reference/mutation checks ran locally; LLVM 15 `pixel_aot_binary` round-trips and Windows WARP/hardware D3D12 draws run in CI. + +## Startup translator: RDNA 2 scalar `null` operand and `Stage.scalar` destination guards + +`tools/startup/gfx2hlsl.py` lowers the RDNA 2 `null` scalar operand (`code 125`) and replaces `reg_range(...)[1]` `TypeError` crashes on non-SGPR scalar destinations with explicit `Unsupported` refusals (#2618, #1723, #2463): + +- **32-bit `null` source (`code 125`)**: `Stage.u`, `Stage.const_u32`, `Stage.uniform_source`, `Stage.scalar_const`, `SCALAR_CONST_FOLD`, `scalar_bitset`, `op_s_bfm_b32`, and `VOP3_ONLY_VEC_U` in `Stage.lower` read `null` as wave-uniform `0x00000000u`. +- **32-bit `null` destination in `Stage.scalar` and `op_s_bfm_b32`**: plain 32-bit numeric/constant SALU writes to `null` discard the destination register write while still emitting modeled `SCC` updates (`s_and_b32`, `s_or_b32`, `s_xor_b32`, `s_andn2_b32`, `s_orn2_b32`, `s_not_b32`, `s_nand_b32`, `s_nor_b32`, `s_xnor_b32`, `s_lshl_b32`, `s_lshr_b32`, `s_ashr_i32`, `s_bfe_u32`, `s_absdiff_i32`) and leaving `SCC` unchanged for non-SCC operations (`s_mov_b32`, `s_movk_i32`, `s_brev_b32`, `s_mul_i32`, `s_bfm_b32`). `s_lshl1..4_add_u32`, `PACK_B16` / `s_sext_*` / `s_mul_hi_*`, and `s_cselect_b32` retain their pinned `null` destination refusals. +- **Explicit `Unsupported` refusals replacing `TypeError`**: `_b64` operations (`s_and_b64 null, exec, s[0:1]`, etc.), lane-mask sources (`exec_lo`, `vcc_lo`, compare-mask SGPRs), `SCC_UNMODELLED` operations (`s_add_u32`, `s_sub_u32`, `s_add_i32`, `s_sub_i32`, `s_min_*`, `s_max_*`), and descriptor/pointer sources written to `null`, as well as unmodelled destinations (`vcc_hi`, `exec_hi`, `ttmp*`), raise specific `gfx2hlsl.Unsupported` reasons instead of `TypeError`. + +[`tests/startup_gfx2hlsl_scalar_null_check.py`](../tests/startup_gfx2hlsl_scalar_null_check.py) constructs synthetic gfx1013 SOP1/SOP2/SOPK/SOPC/VOP2/VOP3A/SMEM words (no game data), verifies all 14 32-bit SCC-writing SALU operations into `null` across boundary pairs, checks LLVM 15 `llvm-mc` / `libLLVM` round-trips, sweeps all 48 `SCA` ops plus `s_bfm_b32` against non-SGPR destinations, and runs D3D12 GPU verification across Microsoft WARP (`1414:008c`, driver `10.0.26100.9818`) and an AMD Radeon RX 9070 XT (`1002:7550`, driver `32.0.32029.2010`) with the D3D12 debug layer enabled (`0` errors, `0` warnings): 4 pixel-stage draws (`FXC ps_5_1` + `DXC ps_6_0`) with 6 pixel mutations plus 4 runtime root-constant SALU+branch buffer runs with 4 HLSL mutations per adapter. + +```powershell +ctest --test-dir out/build/release --no-tests=error -R "^startup_gfx2hlsl_scalar_null_(controls|warp|hardware)$" -V +``` diff --git a/tests/startup_gfx2hlsl_scalar_null_check.py b/tests/startup_gfx2hlsl_scalar_null_check.py new file mode 100644 index 000000000..f074e286f --- /dev/null +++ b/tests/startup_gfx2hlsl_scalar_null_check.py @@ -0,0 +1,654 @@ +"""RDNA 2 scalar null operand (code 125) and Stage.scalar destination guards in tools/startup/gfx2hlsl.py. + + (no arguments) translation, CPU SCC evaluation across 14 32-bit SALU ops, null-source + folding/uniformity, TypeError/Unsupported destination sweep, pure Python + binary reassemble every fixture and instruction spelling and compare with recorded words + decode disassemble the canonical encodings with LLVM's C API and compare with disasm_rdna2.py + draw [fxc] + compile and draw the pixel fixture (FXC ps_5_1 + DXC ps_6_0) and execute the + root-constant SALU null-destination + branch buffer fixture with negative controls + +AMD RDNA 2 ISA reference (scalar/vector source and destination encoding code 125 = null): + - Reading null returns 0 (wave-uniform 32-bit zero). + - Writing null discards the destination register result while still performing modeled 32-bit SCC updates. + - Unmodelled scalar destinations (vcc_hi, exec_hi, ttmp*, _b64/lane-mask/descriptor/unmodelled-SCC writes to null) + raise gfx2hlsl.Unsupported instead of TypeError (#2618, #1723, #2463). +""" +import re +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import disasm_rdna2 as D # noqa: E402 +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import assemble, compile_hlsl, draw, root_blob # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import ( # noqa: E402 + Expr, + MASK, + POST_SOURCE, + POST_WORDS, + PRE_SOURCE, + PRE_WORDS, + check, + signed, + vs_source, + vs_words, + words_text, +) + +NULL = 125 +M0 = 124 +VCC_LO, VCC_HI = 106, 107 +TTMP0 = 108 +EXEC_LO, EXEC_HI = 126, 127 + +SENTINEL = 0xc5c5c5c5 +# Matches offscreen_check --compute-store-case's built-in t0 ByteAddressBuffer pattern. +DATA = b''.join(struct.pack('> 1) & 0x3f) + w1 = ((soffset & 0x7f) << 25) | (imm & 0x1fffff) + return struct.pack('<2I', w0, w1) + + +def root_with_one_constant(): + header = struct.pack('<6I', 2, 1, 24, 0, 0, 0) + param = struct.pack('<3I', 1, 0, 36) + const = struct.pack('<3I', 0, 0, 1) + rts0 = header + param + const + part = b'RTS0' + struct.pack(' llvm-mc <-> libLLVM). +CANONICAL_CASES = ( + ('s_and_b32 null, s8, 4', sop2(0x0e, NULL, 8, 128 + 4)), + ('s_bfe_u32 null, s8, 0x30008', sop2(0x27, NULL, 8, 255, lit=0x30008)), + ('s_mov_b32 null, s8', sop1(0x03, NULL, 8)), + ('s_not_b32 null, s8', sop1(0x07, NULL, 8)), + ('s_movk_i32 null, 0x100', sopk(0x00, NULL, 0x100)), + ('s_cselect_b32 s2, 32, null', sop2(0x0a, 2, 128 + 32, NULL)), + ('s_or_b32 m0, null, s2', sop2(0x10, M0, NULL, 2)), + ('s_cmp_eq_u32 s8, null', sopc(0x06, 8, NULL)), + ('s_bfm_b32 null, s8, 2', sop2(0x24, NULL, 8, 128 + 2)), + ('s_and_b64 null, exec, s[0:1]', sop2(0x0f, NULL, EXEC_LO, 0)), + ('v_subrev_nc_u32_e32 v12, null, v0', vop2(0x27, 12, NULL, 0)), + ('v_xor3_b32 v13, v1, v5, null', vop3a(0x178, 13, 257, 261, NULL)), + ('v_add_f32_e32 v14, null, v2', vop2(0x03, 14, NULL, 2)), + ('v_cvt_pk_u16_u32 v15, null, v3', vop3a(0x36a, 15, NULL, 259)), +) + +# Pixel-stage draw fixture (FXC ps_5_1 + DXC ps_6_0): exercises null as VOP2/VOP3A source and SALU null-dst + null-src. +PS_BODY_SOURCE = """\ +v_subrev_nc_u32_e32 v12, null, v0 +v_xor3_b32 v13, v1, v5, null +v_add_f32_e32 v14, null, v2 +s_mov_b32 s4, 1.0 +s_and_b32 null, s4, 0x7f800000 +s_cselect_b32 s5, 0x55, null +v_xor_b32_e32 v15, s5, v3 +""" +PS_BODY_WORDS = b''.join(( + vop2(0x27, 12, NULL, 0), + vop3a(0x178, 13, 257, 261, NULL), + vop2(0x03, 14, NULL, 2), + sop1(0x03, 4, 242), + sop2(0x0e, NULL, 4, 255, lit=0x7f800000), + sop2(0x0a, 5, 255, NULL, lit=0x55), + vop2(0x1d, 15, 5, 3), +)) +PS_WORDS = PRE_WORDS + PS_BODY_WORDS + POST_WORDS + +PS_DRAW_INPUTS = [ + # Set 0: normal binary32 words in v0..v3, plus v5 (set index 1's second element) for v_xor3_b32. + (0x3f800011, 0, 0), + (0x40200022, 0x0000ff00, 0), + (0x40600000, 0, 0), # 3.5f + (0x41000033, 0, 0), + # Set 1: + (0xbf800044, 0, 0), + (0xc1200055, 0x00aa5500, 0), + (0xc0100000, 0, 0), # -2.25f + (0x3e800066, 0, 0), +] + + +def f32_add_zero(bits, addend_bits=0): + a = struct.unpack('> (b & 31)) & MASK) != 0), + ('s_ashr_i32', 2, lambda a, b: ((signed(a) >> (b & 31)) & MASK) != 0), + ('s_bfe_u32', 2, lambda a, b: ((a >> (b & 31)) & (MASK if ((b >> 16) & 127) >= 32 else ((1 << ((b >> 16) & 31)) - 1))) != 0), + ('s_absdiff_i32', 2, lambda a, b: (abs(signed((a - b) & MASK)) & MASK) != 0), +) + +SCC_PAIRS = ( + (0, 0), (0, MASK), (MASK, 0), (MASK, MASK), (0x55555555, 0xaaaaaaaa), + (0x80000000, 1), (0x80000000, 31), (1, 31), (0x0000ff00, 0x00080008), + (0x0000ff00, 0x00040000), (0x00010000, 0x00200010), (0xdeadbeef, 0xdeadbeef), +) + + +class DummyPipe: + sampler_heap = False + rtv_formats = () + srv_formats = {} + + def __init__(self): + self.resources = {} + self.uavs = {} + self.uds = [] + self.modified = set() + self.other_modified = set() + + def ud(self, tag): + if tag not in self.uds: + self.uds.append(tag) + return self.uds.index(tag) + + def resource(self, key, kind): + entry = self.resources.setdefault(key, {'index': len(self.resources), 'kind': kind}) + return 'r%d' % entry['index'] + + +class ProbeStage(G.Stage): + def __init__(self, kind='ps'): + self.pipe = DummyPipe() + self.kind = kind + self.lines = [] + self.sym = { + 5: ('const', 0x12), + 10: ('ptr', ('root', 1)), + 11: ('ptrhi', ('root', 1)), + **{16 + i: ('desc', ('table', 0), 16, i) for i in range(4)}, + } + self.used_s, self.used_v = set(), set() + self.uniform_v, self.varying_s = set(), set() + self.scc_uniform = True + self.defined_uniform_s = {0, 1, 2, 5} + self.bad_sgprs = set() + self.uniform_expr = {} + self.since_join = None + self.low16_only_v, self.pinned_low16_v, self.whole_read_v = set(), set(), set() + self.exec_known = True + self.exports, self.attrs, self.write_masks, self.masks = {}, {}, {}, set() + + +def eval_scc_line(line, s0, s1): + assert line.startswith('scc = ') and line.endswith(';'), line + return bool(Expr(line[len('scc = '):-1]).run({'s0': s0 & MASK, 's1': s1 & MASK})[0]) + + +def build_root_null_pipeline(): + """VS exercising runtime root-constant s8 through SALU null-destination SCC updates, no-SCC null discards, + null scalar sources, and s_cbranch_scc0 into s_buffer_load_dwordx4.""" + vs = b''.join(( + smem(0x02, 16, 0, soffset=NULL, imm=0x10), # s_load_dwordx4 s[16:19], s[0:1], 0x10 + sop2(0x0e, NULL, 8, 128 + 4), # s_and_b32 null, s8, 4 -> scc = (s8 & 4) != 0 + sop1(0x03, NULL, 8), # s_mov_b32 null, s8 -> no-op, keeps scc + sop2(0x26, NULL, 8, 128 + 7), # s_mul_i32 null, s8, 7 -> no-op, keeps scc + sop2(0x24, NULL, 8, 128 + 2), # s_bfm_b32 null, s8, 2 -> no-op, keeps scc + sop2(0x0a, 2, 128 + 32, NULL), # s_cselect_b32 s2, 32, null -> s2 = scc ? 32 : 0 + sop2(0x27, NULL, 8, 255, lit=0x30008), # s_bfe_u32 null, s8, 0x30008 -> scc = ((s8 >> 8) & 7) != 0 + sopp(0x04, 2), # s_cbranch_scc0 +2 dwords (skips the 8-byte literal add) + sop2(0x00, 2, 2, 255, lit=0x40), # s_add_u32 s2, s2, 0x40 -> s2 += 64 when scc + sop2(0x10, M0, NULL, 2), # s_or_b32 m0, null, s2 -> m0 = 0 | s2 + smem(0x0a, 20, 16, soffset=M0), # s_buffer_load_dwordx4 s[20:23], s[16:19], m0 + vop1(0x01, 4, 20), + vop1(0x01, 5, 21), + vop1(0x01, 6, 22), + vop1(0x01, 7, 23), + struct.pack('<3I', 0xf80008cf, 0x07060504, 0xbf810000), + )) + ps = struct.pack('<3I', 0xf800180f, 0, 0xbf810000) + return G.Pipeline(vs, ps, root_with_one_constant()) + + +def expected_root_null(s8, *, drop_and_scc=False, clobber_mov_scc=False, invert_bfe_scc=False, bad_null_src=False): + scc1 = False if drop_and_scc else ((s8 & 4) != 0) + if clobber_mov_scc: + scc1 = True + null_val = 16 if bad_null_src else 0 + s2 = 32 if scc1 else null_val + bfe_nz = (((s8 >> 8) & 7) != 0) + scc2 = (not bfe_nz) if invert_bfe_scc else bfe_nz + if scc2: + s2 = (s2 + 64) & MASK + addr = (null_val | s2) & MASK + quad = list(struct.unpack_from('<4I', DATA, addr)) + return quad * 16 + [SENTINEL] * (320 - 64) + + +def controls(): + # 1. Canonical encodings round-trip through disasm_rdna2.decode_instruction. + for text, raw in CANONICAL_CASES: + n, _, asm, _ = D.decode_instruction(raw, 0) + check(f'disasm_rdna2 round-trip: {text}', n == len(raw) and asm == text) + off, body_lines = 0, [] + while off < len(PS_BODY_WORDS): + n, _, asm, _ = D.decode_instruction(PS_BODY_WORDS, off) + body_lines.append(asm + '\n') + off += n + check('PS_BODY_WORDS matches PS_BODY_SOURCE', ''.join(body_lines) == PS_BODY_SOURCE) + + # 2. All 14 32-bit SCC-writing SCA ops into null emit only `scc = ...;` and match ISA SCC across boundary pairs. + for op, arity, ref_scc in SCC_32_OPS: + st = ProbeStage() + asm = f'{op} null, s0' if arity == 1 else f'{op} null, s0, s1' + st.one(op, asm) + check(f'{op} null: emits single SCC assignment and leaves SGPRs unwritten', + len(st.lines) == 1 and st.lines[0].startswith('scc = ') and st.scc_uniform) + seen = set() + mismatches = 0 + for a, b in SCC_PAIRS: + got = eval_scc_line(st.lines[0], a, b) + want = ref_scc(a, b) + seen.add(got) + if got != want: + mismatches += 1 + check(f'{op} null: {len(SCC_PAIRS)} boundary pairs match ISA SCC (reaches both True and False)', + mismatches == 0 and seen == {False, True}) + + # 3. 32-bit non-SCC ops into null validate sources, emit no assignment, and leave SCC / scc_uniform untouched. + for op, asm in ( + ('s_mov_b32', 's_mov_b32 null, s0'), + ('s_movk_i32', 's_movk_i32 null, 0x100'), + ('s_brev_b32', 's_brev_b32 null, s0'), + ('s_mul_i32', 's_mul_i32 null, s0, s1'), + ('s_bfm_b32', 's_bfm_b32 null, s0, s1'), + ): + st = ProbeStage() + st.scc_uniform = False + st.one(op, asm) + check(f'{op} into null: emits nothing and preserves scc_uniform', + st.lines == [] and st.scc_uniform is False) + + # 4. null (code 125) as a 32-bit source reads as 0x00000000u, folds constants, and preserves UNIFORM_VALU. + st_fold = ProbeStage() + st_fold.one('s_brev_b32', 's_brev_b32 s2, null') + st_fold.one('s_bfm_b32', 's_bfm_b32 s3, 8, null') + st_fold.one('s_mov_b32', 's_mov_b32 s4, 1') + st_fold.one('s_bitset0_b32', 's_bitset0_b32 s4, null') + st_fold.one('s_bfe_i32', 's_bfe_i32 s6, null, 0x40000') + check('null source folds in s_brev_b32, s_bfm_b32, s_bitset0_b32 and s_bfe_i32', + st_fold.sym.get(2) == ('const', 0) + and st_fold.sym.get(3) == ('const', 0xff) + and st_fold.sym.get(4) == ('const', 0) + and st_fold.sym.get(6) == ('const', 0)) + + def run_stage(*instructions, varying=()): + s = G.Stage.__new__(G.Stage) + s.pipe, s.kind, s.lines = DummyPipe(), 'ps', [] + s.attrs, s.exports, s.write_masks = {}, {}, {} + s.sym, s.used_s, s.used_v, s.masks = {}, set(), set(), set() + s.uniform_v, s.varying_s, s.scc_uniform = set(), set(varying), True + s.entry_uniform_s = {2} + s.exec_known = True + s.ins = [(4 * i, 4, asm.split()[0], asm) for i, asm in enumerate(instructions)] + s.translate() + return [line for _, lines, _ in s.blocks for line in lines] + + u_lines = run_stage( + 's_and_b32 null, s2, 4', + 's_cselect_b32 s3, 10, null', + 'v_cvt_pk_u16_u32 v7, null, s3', + 'v_readfirstlane_b32 s9, v7', + ) + check('uniform s_and_b32 null + null source propagates to v_readfirstlane_b32', + u_lines[-1] == 's9 = v7;') + try: + run_stage( + 'v_cmp_lt_f32_e32 vcc_lo, v0, v1', + 's_and_b32 m0, vcc_lo, -1', + 's_cselect_b32 s8, 4, 0', + 's_cmp_eq_u32 s2, s2', + 's_and_b32 null, s8, 4', + 's_cselect_b32 s3, 10, null', + 'v_mov_b32_e32 v7, s3', + 'v_readfirstlane_b32 s9, v7', + ) + except G.Unsupported as exc: + check('varying s_and_b32 null clears scc_uniform and refuses v_readfirstlane_b32', + 'proven uniform source' in str(exc)) + else: + raise AssertionError('varying s_and_b32 null unexpectedly accepted by v_readfirstlane_b32') + + # ComputePipeline lowering with s_and_b32 null + s_cbranch_scc0 + VALU null source. + cs_blob = ( + sop2(0x0e, NULL, 4, 128 + 4) + + sopp(0x04, 1) + + vop2(0x25, 1, NULL, 0) + + sopp(0x01, 0) + ) + cs_hlsl = G.ComputePipeline(cs_blob, root_blob(), (4 << 1) | (1 << 7), (1, 1, 1)).hlsl_cs() + check('ComputePipeline: s_and_b32 null + s_cbranch_scc0 + v_add_nc_u32 null lowers cleanly', + 'scc = (s4 & 0x00000004u) != 0;' in cs_hlsl and '0x00000000u + v0' in cs_hlsl) + + # 5. Complete TypeError elimination & explicit Unsupported refusal sweep across all SCA ops + s_bfm_b32. + bad_dests = ('vcc_hi', 'exec_hi', 'ttmp0') + for op in sorted(G.SCA): + arity = 1 if op in ('s_mov_b32', 's_mov_b64', 's_movk_i32', 's_not_b32', 's_not_b64', + 's_brev_b32', 's_sext_i32_i8', 's_sext_i32_i16') else 2 + src_a = '0x10' if op == 's_movk_i32' else ('s[0:1]' if op.endswith('_b64') else 's0') + src_b = 's[2:3]' if op.endswith('_b64') else 's1' + rhs = src_a if arity == 1 else f'{src_a}, {src_b}' + for dst in bad_dests: + for use_desc in (False, True): + st = ProbeStage() + if use_desc and not op.endswith('_b64') and op != 's_movk_i32': + st.sym[0] = ('desc', ('table', 0), 16, 0) + try: + st.one(op, f'{op} {dst}, {rhs}') + except G.Unsupported as exc: + assert dst in str(exc) or 'descriptor' in str(exc) or 'lane mask' in str(exc), (op, dst, exc) + except Exception as exc: + raise AssertionError(f'{op} into {dst} (desc={use_desc}) raised {type(exc).__name__}: {exc}') + else: + raise AssertionError(f'{op} into {dst} unexpectedly accepted: {st.lines}') + + for dst in ('vcc_lo', 'vcc_hi', 'exec_lo', 'exec_hi', 'ttmp0'): + st = ProbeStage() + try: + st.one('s_bfm_b32', f's_bfm_b32 {dst}, s0, s1') + except G.Unsupported as exc: + assert f's_bfm_b32 destination {dst}' == str(exc), exc + else: + raise AssertionError(f's_bfm_b32 into {dst} accepted') + check(f'all {len(G.SCA)} SCA ops + s_bfm_b32 refuse unmodelled non-SGPR destinations without TypeError', True) + + # Specific null-destination refusals: _b64, lane-mask sources (#2618 wave64 pattern), SCC_UNMODELLED, descriptors. + specific_refusals = ( + ('s_and_b64', 's_and_b64 null, exec, s[0:1]', 's_and_b64 into null on a lane mask'), + ('s_or_b64', 's_or_b64 null, vcc, s[0:1]', 's_or_b64 into null on a lane mask'), + ('s_and_b64', 's_and_b64 null, s[0:1], s[2:3]', 's_and_b64 into null'), + ('s_mov_b64', 's_mov_b64 null, s[0:1]', 's_mov_b64 into null'), + ('s_and_b32', 's_and_b32 null, exec_lo, s0', 's_and_b32 into null on a lane mask'), + ('s_or_b32', 's_or_b32 null, vcc_lo, s0', 's_or_b32 into null on a lane mask'), + ('s_nand_b32', 's_nand_b32 null, vcc_lo, exec_lo', 's_nand_b32 on a lane mask'), + ('s_bfm_b32', 's_bfm_b32 null, vcc_lo, 4', 's_bfm_b32 into null on a lane mask'), + ('s_add_u32', 's_add_u32 null, s0, s1', 's_add_u32 into null: SCC is not modelled'), + ('s_add_i32', 's_add_i32 null, s0, s1', 's_add_i32 into null: SCC is not modelled'), + ('s_sub_u32', 's_sub_u32 null, s0, s1', 's_sub_u32 into null: SCC is not modelled'), + ('s_sub_i32', 's_sub_i32 null, s0, s1', 's_sub_i32 into null: SCC is not modelled'), + ('s_min_u32', 's_min_u32 null, s0, s1', 's_min_u32 into null: SCC is not modelled'), + ('s_min_i32', 's_min_i32 null, s0, s1', 's_min_i32 into null: SCC is not modelled'), + ('s_max_u32', 's_max_u32 null, s0, s1', 's_max_u32 into null: SCC is not modelled'), + ('s_max_i32', 's_max_i32 null, s0, s1', 's_max_i32 into null: SCC is not modelled'), + ('s_and_b32', 's_and_b32 null, s16, 0xff', 'scc from descriptor data'), + ('s_add_u32', 's_add_u32 null, s10, 4', 'scc from descriptor data'), + ('s_mov_b32', 's_mov_b32 null, s16', 's_mov_b32 into null on descriptor data'), + ) + for op, asm, expected_reason in specific_refusals: + st = ProbeStage() + try: + st.one(op, asm) + except G.Unsupported as exc: + check(f'refuses {asm} ({exc})', str(exc) == expected_reason and not st.lines) + else: + raise AssertionError(f'{asm} unexpectedly accepted: {st.lines}') + + # SGPR holding a compare mask must also be refused when combined into null. + st_mask = ProbeStage() + st_mask.masks.add(0) + try: + st_mask.one('s_and_b32', 's_and_b32 null, s0, s1') + except G.Unsupported as exc: + check('s_and_b32 null with SGPR compare mask refused', str(exc) == 's_and_b32 into null on a lane mask') + else: + raise AssertionError('accepted SGPR compare mask into null') + + # 6. Unlowered negative control: reverting Stage.u('null') restores the pre-change refusal. + real_u = G.Stage.u + + def no_null_u(self, tok, *, low16_only=False): + if tok == 'null': + raise G.Unsupported("operand 'null'") + return real_u(self, tok, low16_only=low16_only) + + G.Stage.u = no_null_u + try: + try: + G.Pipeline(vs_words(PS_DRAW_INPUTS[:4]), PS_WORDS, root_blob()) + except G.Unsupported as exc: + check("unlowered control: removing null from Stage.u restores operand 'null' refusal", + str(exc) == "operand 'null'") + else: + raise AssertionError('PS_WORDS translated with Stage.u null handling disabled') + finally: + G.Stage.u = real_u + + +def check_binary(llvm_mc): + for text, expected in CANONICAL_CASES: + built = assemble(llvm_mc, text + '\n') + assert built == expected, f'{text}: assembled {built.hex()}, recorded {expected.hex()}' + assert assemble(llvm_mc, PS_BODY_SOURCE) == PS_BODY_WORDS, 'PS_BODY_WORDS differs from llvm-mc' + for name, source, raw in (('prologue', PRE_SOURCE, PRE_WORDS), ('export', POST_SOURCE, POST_WORDS)): + assert assemble(llvm_mc, source) == raw, f'{name} fixture differs from llvm-mc' + for idx in range(0, len(PS_DRAW_INPUTS), 4): + chunk = PS_DRAW_INPUTS[idx:idx + 4] + assert assemble(llvm_mc, vs_source(chunk)) == vs_words(chunk), chunk + print('llvm-mc: all scalar/vector null cases and draw fixtures match recorded words') + + +def check_decode(library): + from pixel_aot import disassemble + blob = b''.join(raw for _, raw in CANONICAL_CASES) + llvm_lines = disassemble(blob, library) + ours = [text for text, _ in CANONICAL_CASES] + assert llvm_lines == ours, f'LLVM vs disasm_rdna2 mismatch: {list(zip(llvm_lines, ours))}' + print(f'libLLVM: {len(CANONICAL_CASES)} encodings with null match disasm_rdna2.py verbatim') + + +def run_root_case(directory, dxc, renderer, adapter, pipe, vs_hlsl, ref_words, *, s8=0, fxc=None): + hlsl, binary, case = (directory / n for n in ('root_null.hlsl', 'root_null.cso', 'root_null.case')) + constants = [0] * 16 + if ('rootconst', 0, 0) in pipe.uds: + constants[pipe.uds.index(('rootconst', 0, 0))] = s8 + case.write_bytes(struct.pack('<337I', 1, *ref_words, *constants)) + hlsl.write_text(vs_hlsl, encoding='ascii') + if fxc: + ps_hlsl = directory / 'root_null_ps.hlsl' + ps_hlsl.write_text(pipe.hlsl_ps(), encoding='ascii') + subprocess.run([fxc, '/nologo', '/T', 'vs_5_1', '/E', 'main', '/Fo', str(directory / 'vs51.cso'), str(hlsl)], + check=True, capture_output=True, text=True) + subprocess.run([fxc, '/nologo', '/T', 'ps_5_1', '/E', 'main', '/Fo', str(directory / 'ps51.cso'), str(ps_hlsl)], + check=True, capture_output=True, text=True) + subprocess.run([dxc, '-T', 'vs_6_0', '-E', 'main', '-Fo', str(binary), str(hlsl)], + check=True, capture_output=True, text=True) + wrapper = ( + '\nRWByteAddressBuffer outputWords : register(u0);\n' + '[numthreads(16, 1, 1)]\n' + 'void readback(uint id : SV_GroupIndex) {\n' + ' float4 p = body(id).pos;\n' + ' outputWords.Store4(id * 16, asuint(p));\n' + '}\n' + ) + with hlsl.open('a', encoding='ascii') as handle: + handle.write(wrapper) + subprocess.run([dxc, '-T', 'cs_6_0', '-E', 'readback', '-Fo', str(binary), str(hlsl)], + check=True, capture_output=True, text=True) + return subprocess.run([renderer, adapter, '--compute-store-case', str(binary), str(case)], + capture_output=True, text=True) + + +def check_draw(dxc, renderer, adapter, fxc=None): + controls() + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + ps_draws = ps_muts = 0 + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + ps_text = G.Pipeline(vs_words([(0, 0, 0)] * 4), PS_WORDS, root_blob()).hlsl_ps() + + # Part A: Graphics VS+PS draw across FXC ps_5_1 and DXC ps_6_0 + three pixel-stage mutations. + ps_mutations = ( + ( + 'subrev_null_1', + 'v0 - 0x00000000u', + 'v0 - 0x00000001u', + lambda c: [(c[0][0] - 1) & MASK, (c[1][0] ^ c[1][1]) & MASK, f32_add_zero(c[2][0]), (c[3][0] ^ 0x55) & MASK], + ), + ( + 'f32_null_one', + 'F(0x00000000u) + F(v2)', + '1.0 + F(v2)', + lambda c: [c[0][0] & MASK, (c[1][0] ^ c[1][1]) & MASK, f32_add_zero(c[2][0], 0x3f800000), (c[3][0] ^ 0x55) & MASK], + ), + ( + 'drop_null_scc', + 'scc = (s4 & 0x7f800000u) != 0;', + 'scc = false;', + lambda c: [c[0][0] & MASK, (c[1][0] ^ c[1][1]) & MASK, f32_add_zero(c[2][0]), c[3][0] & MASK], + ), + ) + for kind, compiler, vs_profile, ps_profile in compilers: + good_ps = compile_hlsl(compiler, kind, ps_text, f'ps_null_{kind}', ps_profile, directory) + for idx in range(0, len(PS_DRAW_INPUTS), 4): + chunk = PS_DRAW_INPUTS[idx:idx + 4] + vs = compile_hlsl(compiler, kind, G.Pipeline(vs_words(chunk), PS_WORDS, root_blob()).hlsl_vs(), + f'vs_null_{idx}_{kind}', vs_profile, directory) + expected = words_text(ref_ps_chunk(chunk)) + run = draw(renderer, adapter, vs, good_ps, expected) + if run.returncode == 77: + print(run.stdout, run.stderr) + sys.exit(77) + if run.returncode: + raise AssertionError(f'{kind} PS null draw {idx}\n{run.stdout}\n{run.stderr}') + ps_draws += 1 + print(f'{kind} PS null draw {idx // 4}: {expected}', flush=True) + if idx: + continue + for mut_name, target, repl, mut_fn in ps_mutations: + assert target in ps_text, (mut_name, ps_text) + bad_ps = compile_hlsl(compiler, kind, ps_text.replace(target, repl, 1), + f'mut_ps_{mut_name}_{kind}', ps_profile, directory) + wrong = words_text(mut_fn(chunk)) + mrun = draw(renderer, adapter, vs, bad_ps, expected) + if mrun.returncode == 0 or f'actual={wrong}' not in mrun.stderr: + raise AssertionError(f'{kind} mutation {mut_name} did not read {wrong}\n{mrun.stdout}\n{mrun.stderr}') + ps_muts += 1 + print(f'{kind} PS mutation ({mut_name}): fails as expected, reads {wrong}', flush=True) + + # Part B: Runtime root-constant s8 through SALU null-destination SCC updates + branch + buffer load. + root_pipe = build_root_null_pipeline() + vs_hlsl = root_pipe.hlsl_vs() + for s8 in (0x000, 0x004, 0x300, 0x504): + ref = expected_root_null(s8) + res = run_root_case(directory, dxc, renderer, adapter, root_pipe, vs_hlsl, ref, + s8=s8, fxc=fxc if s8 == 0 else None) + if res.returncode == 77: + print(res.stdout, res.stderr) + sys.exit(77) + if res.returncode: + raise AssertionError(f'root null case s8={s8:#x}\n{res.stdout}\n{res.stderr}') + print(f'root null SALU+branch (s8={s8:#x}):', + [l for l in res.stdout.splitlines() if 'mismatches=' in l][0], flush=True) + + # Four HLSL mutations on the runtime root-constant shader must fail GPU readback. + ref_504 = expected_root_null(0x504) + ref_300 = expected_root_null(0x300) + and_mut, n1 = re.subn(r'scc = \(ud\d+ & 0x00000004u\) != 0;', 'scc = false;', vs_hlsl, count=1) + clob_mut, n2 = re.subn(r's2 = scc \? 0x00000020u : 0x00000000u;', + 'scc = true; s2 = scc ? 0x00000020u : 0x00000000u;', vs_hlsl, count=1) + bfe_mut, n3 = re.subn(r'(scc = \(\(ud\d+ >> \(0x00030008u & 31\)\).*?)\) != 0;', r'\1) == 0;', vs_hlsl, count=1) + src_mut, n4 = re.subn(r'm0 = 0x00000000u \| s2;', 'm0 = 0x00000010u | s2;', vs_hlsl, count=1) + assert (n1, n2, n3, n4) == (1, 1, 1, 1), (n1, n2, n3, n4, vs_hlsl) + root_mutants = ( + ('dropped s_and_b32 null SCC write', and_mut, 0x504, ref_504), + ('no-SCC null discard clobbering SCC', clob_mut, 0x300, ref_300), + ('inverted s_bfe_u32 null SCC write', bfe_mut, 0x504, ref_504), + ('non-zero null source in s_or_b32', src_mut, 0x504, ref_504), + ) + for label, mutant_hlsl, s8_val, good_ref in root_mutants: + assert mutant_hlsl != vs_hlsl, (label, vs_hlsl) + fail = run_root_case(directory, dxc, renderer, adapter, root_pipe, mutant_hlsl, good_ref, s8=s8_val) + if fail.returncode != 1 or 'Compute readback differs' not in fail.stderr: + raise AssertionError(f'root mutation {label!r} escaped detection:\n{fail.stdout}\n{fail.stderr}') + print(f'root mutation ({label}): fails GPU readback as expected', flush=True) + + print(f'{adapter}: {ps_draws} PS draws + 4 root-constant runs matched; {ps_muts} PS + 4 root mutations caught') + + +def main(): + if len(sys.argv) == 1: + controls() + return + mode, *args = sys.argv[1:] + if mode == 'binary' and len(args) == 1: + check_binary(args[0]) + elif mode == 'decode' and len(args) == 1: + check_decode(args[0]) + elif mode == 'draw' and len(args) in (3, 4): + check_draw(*args) + else: + raise SystemExit(__doc__) + + +if __name__ == '__main__': + main() diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 93b4ac26c..0e6a2aab5 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -1993,6 +1993,8 @@ def u(self, tok, *, low16_only=False): if m: raise Unsupported('numeric use of m0 holding %s' % m[0]) return 'm0' + if tok == 'null': + return '0x00000000u' r = reg_range(tok) if r: if r[0] == 'v': @@ -2079,6 +2081,8 @@ def is_const(self, n): return s[1] if s and s[0] == 'const' else None def const_u32(self, tok): + if tok == 'null': + return 0 r = reg_range(tok) if r: if r[0] == 's' and r[1] == r[2]: @@ -3027,7 +3031,7 @@ def uniform_source(self, tok): if sym: return sym[0] in ('const', 'ud', 'fixed_buffer_word') return lo not in self.varying_s - if tok in FLOATS: + if tok == 'null' or tok in FLOATS: return True try: int(tok, 0) @@ -3366,7 +3370,7 @@ def lower(self, base, asm, ops, mods): if sr is not None: if sr[1] != sr[2] or (sr[0] == 'v' and sr[1] > 255) or (sr[0] == 's' and sr[1] > 105): raise Unsupported('%s source %s' % (base, src)) - elif src not in FLOATS and src != 'm0': + elif src not in FLOATS and src not in ('m0', 'null'): try: val = int(src, 0) except ValueError: @@ -3742,14 +3746,16 @@ def scalar(self, base, ops, mods=()): if base == 's_movk_i32' and len(ops) != 2: raise Unsupported('s_movk_i32 with %d operands, expected 2' % len(ops)) text, scc = SCA[base] + dst = reg_range(ops[0]) if base == 's_add_u32' and self.address_carry_reader is not None and self.pc == self.address_carry_reader: + if not dst or dst[0] != 's' or dst[1] != dst[2] or dst[1] > 105: + raise Unsupported('s_add_u32 destination %s' % ops[0]) # The immediately preceding numeric add emitted the carry; no branch can enter here. - self.set_s(reg_range(ops[0])[1], '(scc ? 1u : 0u)') + self.set_s(dst[1], '(scc ? 1u : 0u)') self.set_scc('false') # 0 + a single bit never produces another carry. return None - if base in SCC_UNMODELLED and self.tracks_uniformity(): + if base in SCC_UNMODELLED and self.tracks_uniformity() and ops[0] != 'null': self.scc_uniform = False - dst = reg_range(ops[0]) pair = base.endswith('_b64') srcs = ops[1:] # 64-bit operands name the low register; exec/vcc name themselves. @@ -3837,7 +3843,12 @@ def src_sym(t): return None if dname in ('exec', 'vcc', 'exec_lo', 'vcc_lo'): raise Unsupported('mask from descriptor data') - d = reg_range(dname)[1] + if dname == 'null': + raise Unsupported('scc from descriptor data' if (scc or base in SCC_UNMODELLED) + else '%s into null on descriptor data' % base) + if not dst or dst[0] != 's': + raise Unsupported('%s destination %s' % (base, ops[0])) + d = dst[1] own = self.sym.get(d) raw = (raw_descriptor_alu(base, syms, [self.const_u32(t) for t in srcs]) if getattr(self, 'kind', None) in ('cs', 'vs') and len(syms) == 2 else None) @@ -3883,6 +3894,13 @@ def src_sym(t): needed = max((int(i) for i in re.findall(r'\{(\d+)\}', text)), default=-1) + 1 if len(srcs) < needed: raise Unsupported('%s with %d operands, expected %d' % (base, len(ops), needed + 1)) + if dname == 'null': + if any(self.is_lane_mask(t) for t in srcs): + raise Unsupported('%s into null on a lane mask' % base) + if pair: + raise Unsupported('%s into null' % base) + if base in SCC_UNMODELLED and getattr(self, 'pc', None) not in getattr(self, 'address_carry_pairs', ()): + raise Unsupported('%s into null: SCC is not modelled' % base) absorbed = self.exec_absorbed_source(base, srcs) if absorbed is not None: self.used_s.add(reg_range(srcs[absorbed])[1]) @@ -3924,7 +3942,13 @@ def src_sym(t): if scc: self.set_scc(scc.replace('$', var)) return None - d = reg_range(dname)[1] + if dname == 'null': + if scc: + self.set_scc(scc.replace('$', '(%s)' % expr)) + return None + if not dst or dst[0] != 's': + raise Unsupported('%s destination %s' % (base, ops[0])) + d = dst[1] is_mask = pair or any(t in ('exec', 'exec_lo', 'vcc', 'vcc_lo') or (reg_range(t) and reg_range(t)[0] == 's' and reg_range(t)[1] in self.masks) for t in srcs) and base.split('_')[1] in ('mov', 'and', 'or', 'xor', 'andn2', 'orn2', 'nand', 'nor', 'xnor', 'not', 'cselect') if base in ('s_mov_b32', 's_mov_b64', 's_movk_i32') and re.fullmatch(r'-?(0x[0-9a-f]+|\d+)', srcs[0]) and srcs[0] not in FLOATS: @@ -3942,6 +3966,8 @@ def known(tok): if r and r[0] == 's' and r[1] == r[2]: c = self.is_const(r[1]) return c if c is not None else getattr(self, '_pre_fconst', getattr(self, 'float_const_s', {})).get(r[1]) + if tok == 'null': + return 0 if tok in FLOATS: return fbits(FLOATS[tok]) if re.fullmatch(r'-?(0x[0-9a-f]+|\d+)', tok) and tok not in FLOATS: @@ -4145,7 +4171,9 @@ def scalar_bitset(self, ops, mods, clear): raise Unsupported('%s on a lane mask' % name) imm = re.fullmatch(r'-?(0x[0-9a-fA-F]+|\d+)', ops[1]) bit_sym = None - if imm: + if ops[1] == 'null': + index_imm = 0 + elif imm: index_imm = int(ops[1], 0) & 31 else: src = reg_range(ops[1]) @@ -4386,6 +4414,8 @@ def op_s_bfm_b32(self, ops, mods): r = reg_range(o) if r and r[0] == 's': vals.append(self.is_const(r[1])) + elif o == 'null': + vals.append(0) else: try: vals.append(int(o, 0)) @@ -4400,7 +4430,16 @@ def op_s_bfm_b32(self, ops, mods): self.sym.pop('m0', None) self.emit('m0 = %s;' % expr) return None - d = reg_range(ops[0])[1] + if ops[0] == 'null': + if any(self.is_lane_mask(t) for t in ops[1:3]): + raise Unsupported('s_bfm_b32 into null on a lane mask') + self.u(ops[1]) + self.u(ops[2]) + return None + dst = reg_range(ops[0]) + if not dst: + raise Unsupported('s_bfm_b32 destination %s' % ops[0]) + d = dst[1] if None not in vals: value = (((1 << (vals[0] & 31)) - 1) << (vals[1] & 31)) & 0xffffffff self.set_s(d, '0x%08xu' % value, ('const', value)) @@ -4410,6 +4449,8 @@ def op_s_bfm_b32(self, ops, mods): def scalar_const(self, tok): """Value of a 32-bit scalar source that is known at translation time, else None.""" + if tok == 'null': + return 0 r = reg_range(tok) if r: return self.is_const(r[1]) if r[0] == 's' and r[1] == r[2] else None From 7c6cf907cc45ae932021b886dc1e33594eb13720 Mon Sep 17 00:00:00 2001 From: SimSalabimse <83839581+SimSalabimse@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:40:21 +0100 Subject: [PATCH 083/240] startup: lower constant-trip mesh57 loops outside exchanges (#2413 T6) (#2630) * startup: lower constant-trip mesh57 loops outside exchanges (#2413 T6) Accept one proven constant-trip SCC back-edge in translate_mesh57 by unrolling it; keep data-dependent, EXEC-carrying, and unconditional loops refused by the existing named reason. Source-built fixture draws with a CPU rasteriser oracle; the once-through mutant fails that reference. Co-authored-by: SimSalabimse * tests: spell mesh57 loop branches as numeric SOPP offsets llvm-mc encodes labeled s_cbranch targets differently from the relative SIMM16 words the fixture embeds; match startup_mesh57_skeleton.s style. Co-authored-by: SimSalabimse * startup: tighten mesh57 loop trip signedness and once-through draw oracle Take compare signedness alone, refuse reversed s_sub trip steps, and require a real draw-reference mismatch for the once-through mutant. Refs #2413 Co-authored-by: SimSalabimse * test: allow s_mul_hi_* own-arity templates in scalar table check #2405 added s_mul_hi_i32 (and an early arity refuse for both mul_hi forms). The negative control still expected only one non-IndexError survivor. Co-authored-by: SimSalabimse --------- Co-authored-by: Cursor Agent Co-authored-by: SimSalabimse --- .github/workflows/windows.yml | 2 + AGENTS.md | 1 + CMakeLists.txt | 7 + docs/experiments.md | 14 ++ tests/startup_mesh57_loop.s | 85 +++++++++ tests/startup_mesh57_loop_check.py | 287 +++++++++++++++++++++++++++++ tools/startup/gfx2hlsl.py | 167 ++++++++++++++++- 7 files changed, 560 insertions(+), 3 deletions(-) create mode 100644 tests/startup_mesh57_loop.s create mode 100644 tests/startup_mesh57_loop_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index ac4d983e9..763c15bff 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -91,6 +91,7 @@ jobs: (["tests/startup_gfx2hlsl_waitcnt_depctr_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_mesh57_skeleton_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_mesh57_loop_refusal_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_mesh57_loop_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_cvt_alu_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_cvt_pk_u8_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_cvt_pk_int16_check.py", "binary", "llvm-mc-15"], {}), @@ -291,6 +292,7 @@ jobs: tests/startup_mesh57_skeleton_check.py \ tests/startup_mesh57_depth_only_check.py \ tests/startup_mesh57_loop_refusal_check.py \ + tests/startup_mesh57_loop_check.py \ tests/startup_gfx2hlsl_scalar_shift64_bfe_check.py \ tests/startup_gfx2hlsl_readfirstlane_uniform_check.py \ tests/startup_gfx2hlsl_loop_constants_check.py \ diff --git a/AGENTS.md b/AGENTS.md index 47b0ead30..f16119659 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -199,6 +199,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_mesh57_skeleton_check.py ./out/pe-env/bin/python -B tests/startup_mesh57_depth_only_check.py ./out/pe-env/bin/python -B tests/startup_mesh57_loop_refusal_check.py +./out/pe-env/bin/python -B tests/startup_mesh57_loop_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_readfirstlane_uniform_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_loop_constants_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_join_symbols_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 23b9d4844..51b074e68 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3532,6 +3532,9 @@ if(EXISTS "${INTAKE_PYTHON}") # Slot 57 mesh loop refusal outside the accepted exchanges (#2413 T6); mutant drops the back-edge. add_test(NAME startup_mesh57_loop_refusal COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_mesh57_loop_refusal_check.py") + # Slot 57 mesh constant-trip loop lowering outside the accepted exchanges (#2413 T6). + add_test(NAME startup_mesh57_loop COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_mesh57_loop_check.py") # Scalar SOPK accumulate: s_addk_i32 signed-overflow SCC and s_mulk_i32 against an integer reference. add_test(NAME startup_gfx2hlsl_sopk_accum COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_sopk_accum_check.py") @@ -9503,6 +9506,10 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/startup_mesh57_skeleton_check.py" draw "${DXC_EXECUTABLE}" "$" ${adapter}) set_tests_properties(startup_mesh57_skeleton_draw_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + add_test(NAME startup_mesh57_loop_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_mesh57_loop_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_mesh57_loop_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) add_test(NAME startup_mesh57_skeleton_wave_shift_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_mesh57_skeleton_check.py" shift "${DXC_EXECUTABLE}" "$" ${adapter}) diff --git a/docs/experiments.md b/docs/experiments.md index ea6458732..cae5d444a 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9830,6 +9830,20 @@ loop message. The oracle is an exact string match; a stub that only checks for any `unsupported:` result would accept a wrong reason and is rejected by the check. Host-only (no WARP/hardware draw). Run `python -B tests/startup_mesh57_loop_refusal_check.py`, or the matching CTest. +The `startup_mesh57_loop` check is a source-built program with the same +exchanges plus one constant-trip scalar loop after the count exchange +(`tests/startup_mesh57_loop.s`: `s_mov_b32 s40, 0`, then four iterations of +`s_add_u32` / `s_cmp_lt_u32` / `s_cbranch_scc1`). `translate_mesh57` unrolls +the proven trip count and publishes `ms_6_5`; vertex red is 1.0 when the final +counter equals 4. Unsupported shapes still refuse with +`slot 57 mesh: a loop outside the group-memory exchanges is not covered`: an +unconditional back-edge, a data-dependent compare against a root constant, and +a loop body that writes EXEC. The once-through mutant replaces the back-edge +with `s_nop` so the counter stays 1 and red stays 0; the draw reference for the +constant-trip image must fail on that mutant. Run +`python -B tests/startup_mesh57_loop_check.py` on the host, and +`ctest --preset release --no-tests=error -j 1 -V -R '^startup_mesh57_loop_(warp|hardware)$'` +for WARP and hardware draws against the CPU rasteriser. A forward `s_cbranch_vccz` or `s_cbranch_vccnz` can also branch on the lane's VCC bit when EXEC is full and every incoming path last wrote VCC with diff --git a/tests/startup_mesh57_loop.s b/tests/startup_mesh57_loop.s new file mode 100644 index 000000000..3537b099a --- /dev/null +++ b/tests/startup_mesh57_loop.s @@ -0,0 +1,85 @@ +// Source-built slot 57 mesh fixture for #2413 item T6: the accepted group-memory exchanges plus one +// constant-trip scalar loop after the count exchange. translate_mesh57 unrolls the four iterations; +// unsupported loop shapes still refuse by name (see startup_mesh57_loop_check.py). +// Entry and buffer layout match tests/startup_mesh57_skeleton.s. +// After the loop, s40 == 4 selects vertex red = 1.0 via v7; a mutant that drops the back-edge leaves +// s40 == 1 and red = 0. v20 is overwritten from v7 after the colour load, as in the skeleton branch draws. +s_inst_prefetch 0x3 +s_mov_b64 exec, 1 +s_mov_b64 s[4:5], exec +s_and_b32 s6, s3, 0xf000000 +s_cbranch_scc1 7 // to the reading waves +v_lshrrev_b32 v5, 7, v5 +v_mov_b32 v6, 0 +ds_write_b32 v6, v5 offset:8 +s_waitcnt_depctr 0xffe3 +s_barrier +s_branch 4 // past the reading waves +s_barrier +v_mov_b32 v6, 0 +ds_read_b32 v5, v6 offset:8 +s_mov_b64 exec, -1 +s_bfe_u32 s6, s3, 0x40018 +s_lshl_b32 s7, s6, 6 +v_mbcnt_lo_u32_b32 v0, -1, s7 +v_mbcnt_hi_u32_b32 v0, -1, v0 +s_waitcnt lgkmcnt(0) +v_readfirstlane_b32 s12, v5 +s_load_dwordx4 s[16:19], s[10:11], 0 +s_mov_b32 s13, s8 +s_mov_b32 s14, s9 +s_barrier +s_cmp_eq_i32 s6, 0 +s_cbranch_scc0 16 // to the reading waves +s_mov_b64 exec, s[4:5] +s_cbranch_execz 7 // never taken: the saved mask is 1 +v_mov_b32 v1, s13 +v_mov_b32 v2, 0 +v_mov_b32 v3, s14 +ds_write_b32 v2, v1 +ds_write_b32 v2, v3 offset:4 +s_mov_b64 exec, -1 +s_waitcnt_depctr 0xffe3 +s_barrier +s_lshl_b32 s4, s13, 12 +s_or_b32 m0, s4, s14 +s_sendmsg sendmsg(MSG_GS_ALLOC_REQ) +s_branch 13 // past the reading waves +s_barrier +s_mov_b64 exec, s[4:5] +s_cbranch_execz 9 // never taken: the saved mask is 1 +v_mov_b32 v2, 0 +ds_read_b32 v1, v2 +ds_read_b32 v3, v2 offset:4 +s_waitcnt lgkmcnt(1) +v_readfirstlane_b32 s13, v1 +s_waitcnt lgkmcnt(0) +v_readfirstlane_b32 s14, v3 +s_mov_b64 exec, -1 +// Constant-trip loop (4 iterations). Final s40 == 4 writes vertex red = 1.0 into v7. +// Numeric SOPP offsets (as in startup_mesh57_skeleton.s): -3 retargets the add; +1 skips the red write. +v_mov_b32 v7, 0 +s_mov_b32 s40, 0 +s_add_u32 s40, s40, 1 +s_cmp_lt_u32 s40, 4 +s_cbranch_scc1 -3 +s_cmp_eq_u32 s40, 4 +s_cbranch_scc0 1 +v_mov_b32 v7, 1.0 +v_cmpx_gt_i32 s14, v0 +v_and_b32 v4, 15, v0 +v_lshlrev_b32 v4, 4, v4 +buffer_load_dwordx4 v[16:19], v4, s[16:19], 0 offen +buffer_load_dwordx4 v[20:23], v4, s[16:19], 0 offen offset:192 +s_waitcnt vmcnt(0) +v_mov_b32 v20, v7 +exp pos0 v16, v17, v18, v19 done +exp param0 v20, v21, v22, v23 +s_mov_b64 exec, -1 +v_cmpx_gt_i32 s13, v0 +v_and_b32 v4, 15, v0 +v_lshlrev_b32 v4, 2, v4 +buffer_load_dword v24, v4, s[16:19], 0 offen offset:384 +s_waitcnt vmcnt(0) +exp prim v24, off, off, off done +s_endpgm diff --git a/tests/startup_mesh57_loop_check.py b/tests/startup_mesh57_loop_check.py new file mode 100644 index 000000000..10aab1927 --- /dev/null +++ b/tests/startup_mesh57_loop_check.py @@ -0,0 +1,287 @@ +"""Slot 57 mesh constant-trip loop lowering outside the accepted group-memory exchanges (#2413 T6). + +usage: startup_mesh57_loop_check.py + startup_mesh57_loop_check.py binary + startup_mesh57_loop_check.py draw + +The source-built fixture (tests/startup_mesh57_loop.s) keeps the skeleton exchanges and inserts one +constant-trip scalar loop after the count exchange. translate_mesh57 unrolls it; the request translates +and draws with vertex red = 1.0. Unsupported shapes still refuse with the named loop message: an +unconditional back-edge (the #2622 refusal program), a data-dependent trip count, and a loop whose +body writes EXEC. The once-through mutant replaces the back-edge with s_nop so s40 stays 1 and red +stays 0; a draw reference that expects the constant-trip image must fail on that mutant. +""" +import os +from pathlib import Path +import re +import struct +import subprocess +import sys +import tempfile + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +import gfx2hlsl as G # noqa: E402 + +LOOP_REASON = 'slot 57 mesh: a loop outside the group-memory exchanges is not covered' + +# Constant-trip fixture: four iterations of s_add_u32 s40, s40, 1; s_cmp_lt_u32 s40, 4; then red from s40 == 4. +MESH = ( + 'bfa00003 befe0481 be84047e 8706ff03 0f000000 bf850007 2c0a0a87 7e0c0280 d8340008 00000506' + ' bfa3ffe3 bf8a0000 bf820004 bf8a0000 7e0c0280 d8d80008 05000006 befe04c1 9386ff03 00040018' + ' 8f078606 d7650000 00000ec1 d7660000 000200c1 bf8cc07f 7e180505 f4080405 fa000000 be8d0308' + ' be8e0309 bf8a0000 bf008006 bf840010 befe0404 bf880007 7e02020d 7e040280 7e06020e d8340000' + ' 00000102 d8340004 00000302 befe04c1 bfa3ffe3 bf8a0000 8f048c0d 887c0e04 bf900009 bf82000d' + ' bf8a0000 befe0404 bf880009 7e040280 d8d80000 01000002 d8d80004 03000002 bf8cc17f 7e1a0501' + ' bf8cc07f 7e1c0503 befe04c1 7e0e0280 bea80380 80288128 bf0a8428 bf85fffd bf068428 bf840001' + ' 7e0e02f2 7d28000e 3608008f 34080884 e0381000 80041004 e03810c0 80041404 bf8c3f70 7e280307' + ' f80008cf 13121110 f800020f 17161514 befe04c1 7d28000d 3608008f 34080882 e0301180 80041804' + ' bf8c3f70 f8000941 00000018 bf810000').split() +# Once-through mutant: back-edge replaced by s_nop (body runs once; s40 == 1; red stays 0). +ONCE = MESH[: MESH.index('bf85fffd')] + ['bf800000'] + MESH[MESH.index('bf85fffd') + 1:] +# Unconditional back-edge after the count exchange (#2622 refusal shape). +INFINITE = ( + 'bfa00003 befe0481 be84047e 8706ff03 0f000000 bf850007 2c0a0a87 7e0c0280 d8340008 00000506' + ' bfa3ffe3 bf8a0000 bf820004 bf8a0000 7e0c0280 d8d80008 05000006 befe04c1 9386ff03 00040018' + ' 8f078606 d7650000 00000ec1 d7660000 000200c1 bf8cc07f 7e180505 f4080405 fa000000 be8d0308' + ' be8e0309 bf8a0000 bf008006 bf840010 befe0404 bf880007 7e02020d 7e040280 7e06020e d8340000' + ' 00000102 d8340004 00000302 befe04c1 bfa3ffe3 bf8a0000 8f048c0d 887c0e04 bf900009 bf82000d' + ' bf8a0000 befe0404 bf880009 7e040280 d8d80000 01000002 d8d80004 03000002 bf8cc17f 7e1a0501' + ' bf8cc07f 7e1c0503 befe04c1 bf800000 bf82fffe 7d28000e 3608008f 34080884 e0381000 80041004' + ' e03810c0 80041404 bf8c3f70 f80008cf 13121110 f800020f 17161514 befe04c1 7d28000d 3608008f' + ' 34080882 e0301180 80041804 bf8c3f70 f8000941 00000018 bf810000').split() +# Data-dependent trip: s_cmp_lt_u32 s40, s8 (root constant) instead of an immediate. +DATA_DEP = MESH[: MESH.index('bf0a8428')] + ['bf0a0828'] + MESH[MESH.index('bf0a8428') + 1:] +# EXEC write in the loop body: v_cmpx_gt_u32_e32 0, v0 between the add and the compare (branch -4). +_EXEC_AT = MESH.index('80288128') +EXEC_BODY = MESH[: _EXEC_AT + 1] + ['7da80080', 'bf0a8428', 'bf85fffc'] + MESH[_EXEC_AT + 3:] + +PIXEL = 'c8020002 c8060102 c80a0202 c80e0302 f800180f 03020100 bf810000'.split() + +FAILED = [] +SIDE = 32 +TRIANGLES = (((2, 2), (14, 2), (2, 14)), ((18, 3), (30, 5), (21, 14)), + ((3, 18), (13, 20), (6, 30)), ((18, 18), (30, 18), (30, 30))) +ORDER = (7, 2, 10, 5, 0, 8, 3, 11, 1, 6, 9, 4) + + +def expect(what, got, want): + if got != want: + FAILED.append(what) + print('FAIL %s: got %r, want %r' % (what, got, want)) + + +def code(words): + return b''.join(struct.pack(' 0 or (edge == 0 and (dy < 0 or (dy == 0 and dx > 0))) + if inside: + image[y * SIDE + x] = colour + return image + + +def binary(mc): + text = (HERE / 'startup_mesh57_loop.s').read_text() + expect('constant-trip fixture words match llvm-mc', assemble(mc, text), MESH) + mutant_text = text.replace('s_cbranch_scc1 -3\n', 's_nop 0\n') + expect('once-through mutant words match llvm-mc', assemble(mc, mutant_text), ONCE) + + +def host(): + os.environ['X2W_FXC'] = '' # sources and manifest only; draw mode compiles + want = 'unsupported: ' + LOOP_REASON + + with tempfile.TemporaryDirectory() as tmp: + key, result = request(tmp, MESH) + expect('constant-trip loop translates', result, 'ok') + if result == 'ok': + names = sorted(p.name[16:] for p in Path(tmp).iterdir() if not p.name.startswith('req_')) + expect('constant-trip publishes mesh and pixel sources', names, + ['.ms57.hlsl', '.ms57.txt', '.ps57.hlsl']) + hlsl = (Path(tmp) / ('%016x.ms57.hlsl' % key)).read_text() + expect('constant-trip unrolls four counter updates', + hlsl.count('0x00000001u') >= 4 and 's40' in hlsl, True) + + with tempfile.TemporaryDirectory() as tmp: + key, result = request(tmp, ONCE) + expect('once-through mutant translates', result, 'ok') + + for what, mesh in ( + ('unconditional back-edge', INFINITE), + ('data-dependent trip count', DATA_DEP), + ('EXEC write in the loop body', EXEC_BODY), + ): + with tempfile.TemporaryDirectory() as tmp: + key, result = request(tmp, mesh) + expect(what + ' refuses by name', result, want) + if result == want: + expect(what + ' .fail text', (Path(tmp) / ('%016x.fail' % key)).read_text(), LOOP_REASON + '\n') + + other = 'unsupported: slot 57 mesh: a branch enters or crosses a group-memory exchange' + expect('stubbed comparator would accept a wrong reason', ignores_refusal_string(other, want), True) + expect('exact oracle rejects that wrong reason', other == want, False) + expect('exact oracle matches the named loop refusal', want == 'unsupported: ' + LOOP_REASON, True) + + # Signedness comes from the compare alone: signed update + unsigned compare across bit 31 is not + # a finite unroll within MESH_TRIP_MAX (review on #2630). + expect('signed update / unsigned compare across bit 31 is not a finite trip count', + G.mesh_trip_count(0x7fffffff, 's_add_i32', 1, 's_cmp_gt_u32', 4, 's_cbranch_scc1', True), + None) + expect('unsigned compare after signed update from -3 is one trip', + G.mesh_trip_count((-3) & 0xffffffff, 's_add_i32', 1, 's_cmp_lt_u32', 0, 's_cbranch_scc1', True), + 1) + + if FAILED: + print('startup_mesh57_loop: %d failed' % len(FAILED)) + return 1 + print('startup_mesh57_loop: ok') + return 0 + + +def draw(dxc, renderer, adapter): + os.environ['X2W_DXC'] = dxc + os.environ.pop('X2W_FXC', None) + points, colours, indices = geometry() + words = [a | b << 10 | c << 20 for a, b, c in indices] + # Constant-trip: every vertex red channel is 255. Once-through mutant keeps the buffer reds. + trip_colours = [(255, *colour[1:]) for colour in colours] + with tempfile.TemporaryDirectory() as tmp: + key, result = request(tmp, MESH) + expect('constant-trip translates and compiles', result, 'ok') + if result != 'ok': + return 1 if FAILED else 0 + name = str(Path(tmp) / ('%016x' % key)) + uds = G.MeshPipeline(code(MESH), code(PIXEL), root()).uds + constants = bytearray(1024) + struct.pack_into('= 0 else (value + (1 << 32)) & 0xffffffff + + +def mesh_trip_count(init, step_name, step_imm, cmp_name, limit, latch_name, cmp_counter_left): + """Finite trip count for a scalar counted loop, or None when unbounded / unsupported.""" + counter = init & 0xffffffff + step = step_imm & 0xffffffff + signed = '_i32' in cmp_name # compare opcode alone + take_when_scc = latch_name == 's_cbranch_scc1' + + def as_signed(word): + return word - (1 << 32) if word >= (1 << 31) else word + + for trips in range(1, MESH_TRIP_MAX + 1): + if step_name.startswith('s_add'): + counter = (counter + step) & 0xffffffff + else: + counter = (counter - step) & 0xffffffff + left, right = (counter, limit) if cmp_counter_left else (limit, counter) + if signed: + left, right = as_signed(left), as_signed(right) + if cmp_name.endswith(('_eq_i32', '_eq_u32')): + scc = left == right + elif cmp_name.endswith(('_lg_i32', '_lg_u32')): + scc = left != right + elif cmp_name.endswith(('_gt_i32', '_gt_u32')): + scc = left > right + elif cmp_name.endswith(('_ge_i32', '_ge_u32')): + scc = left >= right + elif cmp_name.endswith(('_lt_i32', '_lt_u32')): + scc = left < right + elif cmp_name.endswith(('_le_i32', '_le_u32')): + scc = left <= right + else: + return None + if take_when_scc != scc: + return trips + return None + + +def mesh_constant_trip(ins, header, latch, offsets): + """Prove one constant-trip SCC back-edge: (trips,) or None. + + Shape (census "constant pattern", with an exact trip count): s_mov_b32 sN, C immediately before the + header; the body changes sN only by s_add/s_sub of a constant; the last body instruction is s_cmp of sN + against a constant; the latch is s_cbranch_scc0/scc1 back to the header. No other branch enters or leaves + the body, and the body does not write EXEC, touch a barrier, LDS, sendmsg, or export. + """ + if header <= 0 or latch <= header or latch >= len(ins): + return None + latch_name = ins[latch][2] + if latch_name not in ('s_cbranch_scc0', 's_cbranch_scc1'): + return None + init_name, init_ops, _ = parse(ins[header - 1][3]) + if init_name != 's_mov_b32' or len(init_ops) != 2 or not re.fullmatch(r's\d+', init_ops[0]): + return None + init_imm = mesh_inline_u32(init_ops[1]) + if init_imm is None: + return None + counter = init_ops[0] + counter_n = int(counter[1:]) + body = ins[header:latch] + if not body or not body[-1][2].startswith('s_cmp_'): + return None + cmp_name, cmp_ops, _ = parse(body[-1][3]) + if len(cmp_ops) != 2: + return None + if cmp_ops[0] == counter: + cmp_counter_left, limit_tok = True, cmp_ops[1] + elif cmp_ops[1] == counter: + cmp_counter_left, limit_tok = False, cmp_ops[0] + else: + return None + limit = mesh_inline_u32(limit_tok) + if limit is None: + return None + step = None + for off, size, name, asm in body[:-1]: + if name.startswith(('s_branch', 's_cbranch', 's_setpc', 's_call', 's_swappc')): + return None + if name.startswith(('ds_', 'exp')) or name in ('s_barrier', 's_sendmsg', 's_sendmsghalt'): + return None + _, ops, _ = parse(asm) + if writes_exec(name, ops) or name.startswith('v_cmpx') or name == 's_and_saveexec_b64': + return None + if name.startswith('s_') and re.search(r'\bvcc(_lo|_hi)?\b', asm): + return None + writes = set() + for tok in destinations(name, ops): + r = reg_range(tok) + if r and r[0] == 's': + writes.update(range(r[1], r[2] + 1)) + if counter_n in writes: + if name not in MESH_TRIP_STEPS or len(ops) != 3 or ops[0] != counter: + return None + if ops[1] == counter and mesh_inline_u32(ops[2]) is not None: + imm = mesh_inline_u32(ops[2]) + elif (ops[2] == counter and mesh_inline_u32(ops[1]) is not None + and name.startswith('s_add')): + # Add is commutative; s_sub with the counter as SRC1 is a different recurrence. + imm = mesh_inline_u32(ops[1]) + else: + return None + if step is not None: + return None + step = (name, imm) + if step is None: + return None + # No other branch may enter the body past the header or leave it before the latch. + for i, (off, _, name, asm) in enumerate(ins): + if not name.startswith(('s_cbranch', 's_branch')): + continue + target = int(parse(asm)[1][0].split('_')[1], 16) + dest = offsets.get(target) + if dest is None: + continue + if i == latch: + continue + if header <= i < latch and not (header <= dest <= latch): + return None + if header < dest <= latch and not (header <= i <= latch): + return None + trips = mesh_trip_count(init_imm, step[0], step[1], cmp_name, limit, latch_name, cmp_counter_left) + return (trips,) if trips is not None else None + + def mesh_skeleton(ins, vcc_branches, wave_limits, wave_loads): """Prove the one accepted group-memory shape of a slot 57 mesh program and replace it by per-thread instructions. @@ -1457,6 +1596,8 @@ def lands(key, index, what): offsets = {item[0]: i for i, item in enumerate(ins)} edges = {} count_entry = count_entry_branch = None + # header index -> (latch index, trip count). Constant-trip loops are unrolled below. + constant_trips = {} no_effect = lambda i: ins[i][2].startswith(('s_nop', 's_waitcnt', 's_clause')) exchange_branch_refusal = 'slot 57 mesh: a branch enters or crosses a group-memory exchange' @@ -1521,12 +1662,18 @@ def dead_count_entry_scalar(i): raise Unsupported(exchange_branch_refusal) count_entry, count_entry_branch = compare, i if target <= off: - raise Unsupported('slot 57 mesh: a loop outside the group-memory exchanges is not covered') + proven = mesh_constant_trip(ins, dest, i, offsets) + if proven is None or dest in constant_trips: + raise Unsupported(MESH_LOOP_REFUSAL) + constant_trips[dest] = (i, proven[0]) + continue if name not in ('s_branch', 's_cbranch_scc0', 's_cbranch_scc1', 's_cbranch_execz') + MESH_VCC_BRANCHES: raise Unsupported('slot 57 mesh: %s on a wave-wide condition is not covered' % name) edges[i] = dest targets = set(edges.values()) + if targets & set(constant_trips): + raise Unsupported(MESH_LOOP_REFUSAL) if count_entry is not None and targets.intersection(range(count_entry, count_at)): raise Unsupported(exchange_branch_refusal) first_post_count_branch = next((i for i in edges if i >= b_end), None) @@ -1615,8 +1762,22 @@ def live_at_join(reg, join): exports = [] incoming = {} falls = True - for index in (list(range(first, start)) + [start] + list(range(a_end, count_at + 1)) - + list(range(b_end, len(ins)))): + def region_walk(lo, hi): + """Instruction indices in [lo, hi), with each proven constant-trip body repeated and its latch dropped.""" + order, i = [], lo + while i < hi: + if i in constant_trips: + latch, trips = constant_trips[i] + for _ in range(trips): + order.extend(range(i, latch)) + i = latch + 1 + continue + order.append(i) + i += 1 + return order + + for index in (region_walk(first, start) + [start] + region_walk(a_end, count_at + 1) + + region_walk(b_end, len(ins))): if index in targets: paths = incoming[index] if falls: From 4c03e07101da6471e4a2edc8f29fafb04c3dad6c Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Thu, 26 Nov 2026 03:40:27 +0100 Subject: [PATCH 084/240] gfx2hlsl: prove a thread-id shift uniform when it clears every thread-id bit (#2455) * gfx2hlsl: prove a compute buffer load with a uniform address uniform v_readfirstlane_b32 needs a vector source with the same value in every active lane. A buffer_load_dword or buffer_load_format_x in a compute program reads a read-only descriptor (a descriptor used for a load and a store is already refused), so with a uniform VGPR index or offset, a uniform scalar offset and exec known in the entry block, every lane reads the same dword. Mark the destination uniform there. The value has no recomputable expression, so reads past the entry block still refuse. Tests: positive cases plus negative controls for a varying VGPR offset, a varying scalar offset, a graphics stage, no stage kind, unknown exec, a read after the entry block and a varying overwrite. Co-Authored-By: Claude Sonnet 5.5 * gfx2hlsl: prove a thread-id shift uniform when it clears every thread-id bit In a compute entry block, v_lshrrev_b32 by n of the X thread id (v0, each local id has its own VGPR) is 0 in every lane when the group's X size is at most 1 << n. The same holds for (uniform << K) + v0 built by v_lshl_add_u32 with n <= K and size <= 1 << K: the low K bits of the base are clear, the sum does not carry, and the shifted value is the uniform part. The nearest earlier writer is the definition (program order is execution order in the entry block), v0 must be unwritten at it and the scalar unwritten after it. The value records a recomputable expression, so a read past the entry block is accepted too, until the scalar changes. Everything else keeps refusing by name: a larger group, a shift larger than the scale, a varying or rewritten scalar, a vector base, a rewritten v0, another stage and any modifier. Co-Authored-By: Claude Sonnet 5.5 --------- Co-authored-by: Claude Sonnet 5.5 Co-authored-by: tedin7 --- ...up_gfx2hlsl_readfirstlane_uniform_check.py | 49 +++++++++++++- tools/startup/gfx2hlsl.py | 64 ++++++++++++++++++- 2 files changed, 111 insertions(+), 2 deletions(-) diff --git a/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py b/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py index b52af84b2..b5b9fa437 100644 --- a/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py +++ b/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py @@ -28,10 +28,12 @@ def resource(self, key, kind): ALIAS_LOAD = 's_buffer_load_dwordx2 s[2:3], s[4:7], s2' -def run(*instructions, exec_known=True, kind=None): +def run(*instructions, exec_known=True, kind=None, group=None): """Translate disassembly text using the same dispatch and branch scan as a real stage.""" s = G.Stage.__new__(G.Stage) s.pipe, s.lines = Pipe(), [] + if group: + s.pipe.group = group s.attrs = {} s.sym = {4 + i: ('desc', ('table', 0), 0, i) for i in range(4)} s.sym[3] = ('fixed_buffer_word',) @@ -239,6 +241,51 @@ def run(*instructions, exec_known=True, kind=None): finally: G.UNIFORM_LOADS = original +# tid.x >> n is 0 in every lane when the group's X size is at most 1 << n (the thread id VGPR is untouched). +WAVE = 'v_lshrrev_b32_e32 v1, 6, v0' +READ1 = 'v_readfirstlane_b32 s9, v1' +for size in (1, 33, 64): + got = run(WAVE, READ1, kind='cs', group=(size, 1, 1)) + check(f'wave index of a group of {size} accepted', got[-1] == 's9 = v1;', repr(got)) +got = run(WAVE, 's_cbranch_scc0 label_0010', READ1, 's_endpgm', 's_endpgm', kind='cs', group=(64, 1, 1)) +check('wave index read past the entry block recomputed as zero', got[-1] == 's9 = 0u;', repr(got)) +for label, instructions, kind, group in ( + ('wave index of a group of 65', (WAVE, READ1), 'cs', (65, 1, 1)), + ('wave index of a group of 128', (WAVE, READ1), 'cs', (128, 1, 1)), + ('wave index of a group with no recorded size', (WAVE, READ1), 'cs', None), + ('shift by 5 of a group of 64', ('v_lshrrev_b32_e32 v1, 5, v0', READ1), 'cs', (64, 1, 1)), + ('wave index in a graphics stage', (WAVE, READ1), 'ps', (64, 1, 1)), + ('wave index without a stage kind', (WAVE, READ1), None, (64, 1, 1)), + ('wave index of v1', ('v_lshrrev_b32_e32 v1, 6, v1', READ1), 'cs', (64, 1, 1)), + ('wave index after v0 is overwritten', ('v_mov_b32_e32 v0, 200', WAVE, READ1), 'cs', (64, 1, 1)), + ('wave index after v0 is loaded', ('buffer_load_dword v[0:1], off, s[4:7], s2', WAVE, READ1), 'cs', (64, 1, 1)), + ('wave index after v0 is swapped', ('v_swap_b32 v2, v0', WAVE, READ1), 'cs', (64, 1, 1)), + ('wave index with an output modifier', ('v_lshrrev_b32_e64 v1, 6, v0 clamp', READ1), 'cs', (64, 1, 1)), + ('wave index of a register shift', ('v_lshrrev_b32_e32 v1, v2, v0', READ1), 'cs', (64, 1, 1))): + got = run(*instructions, kind=kind, group=group) + check(f'{label} refused', got == ("v_lshrrev_b32 with ['clamp']" if 'modifier' in label else REFUSAL), repr(got)) + +# The global thread id of a 64-wide group, (uniform << 6) + tid.x, shifted back by 6 is the uniform part. +GID = 'v_lshl_add_u32 v0, s2, 6, v0' +got = run(GID, WAVE, READ1, kind='cs', group=(64, 1, 1)) +check('global thread id shifted back accepted', got[-1] == 's9 = v1;', repr(got)) +got = run(GID, WAVE, 's_cbranch_scc0 label_0014', READ1, 's_endpgm', 's_endpgm', kind='cs', group=(64, 1, 1)) +check('thread id base shifted back recomputed past the entry block', got[-1] == 's9 = ((s2 << 6u) >> 6u);', repr(got)) +got = run(GID, WAVE, 's_mov_b32 s2, 5', 's_cbranch_scc0 label_0018', READ1, 's_endpgm', 's_endpgm', kind='cs', group=(64, 1, 1)) +check('thread id base shifted back refused past the entry block after the scalar changed', got == REFUSAL, repr(got)) +for label, instructions, group in ( + ('thread id base of a group of 128', (GID, WAVE, READ1), (128, 1, 1)), + ('thread id base shifted by more than the scale', ('v_lshl_add_u32 v0, s2, 6, v0', 'v_lshrrev_b32_e32 v1, 7, v0', READ1), (64, 1, 1)), + ('thread id base from a varying scalar', (COMPARE, 'v_lshl_add_u32 v0, s2, 6, v0', WAVE, READ1), (64, 1, 1)), + ('thread id base with the scalar rewritten', (GID, 's_mov_b32 s2, vcc_lo', WAVE, READ1), (64, 1, 1)), + ('thread id base from a vector', ('v_lshl_add_u32 v0, v5, 6, v0', WAVE, READ1), (64, 1, 1)), + ('thread id base added to another vector', ('v_lshl_add_u32 v0, s2, 6, v4', WAVE, READ1), (64, 1, 1)), + ('thread id base added to a rewritten v0', ('v_mov_b32_e32 v0, 3', GID, WAVE, READ1), (64, 1, 1)), + ('thread id base rewritten after', (GID, 'v_add_nc_u32_e32 v0, s3, v0', WAVE, READ1), (64, 1, 1)), + ('thread id base scaled by 32', ('v_lshl_add_u32 v0, s2, 5, v0', WAVE, READ1), (64, 1, 1))): + got = run(*instructions, kind='cs', group=group) + check(f'{label} refused', got == REFUSAL, repr(got)) + # Older probes may provide either no tracker or only part of the tracking state. for present in ((), ('uniform_v',), ('uniform_v', 'varying_s')): s = G.Stage.__new__(G.Stage) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 36db4fedd..c4fdb7d95 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -3176,6 +3176,55 @@ def join_writes(self, branches): def tracks_uniformity(self): return all(hasattr(self, name) for name in ('uniform_v', 'varying_s', 'scc_uniform')) + def vgpr_writer(self, reg, before, after=-1): + """Index of the last instruction in self.ins[after + 1:before] that may write VGPR reg (the first operand, + and the second of v_swap_b32), or None.""" + for i in range(before - 1, after, -1): + _, _, name, asm = self.ins[i] + ops = parse(asm)[1] + for tok in (ops[:2] if name.startswith('v_swap') else ops[:1]): + r = reg_range(tok) + if r and r[0] == 'v' and r[1] <= reg <= r[2]: + return i + return None + + def tid_shift(self, count, source): + """The uniform expression of `v_lshrrev_b32 vD, count, source` in the entry block of a compute program, or None. + + The X thread id (v0, each local id has its own VGPR) is below the group's X size, so a right shift by n with + size <= 1 << n clears every thread-id bit. That gives 0 for the thread id itself, and for a vector built as + (uniform << K) + v0 with n <= K and size <= 1 << K the low K bits of the base are clear, the sum does not + carry, and the result is the same in every lane. Program order is execution order here, so the nearest + earlier writer is the definition; v0 must be unwritten at the definition and the scalar unwritten after it.""" + src, now = reg_range(source), self.pc_index() + if (not re.fullmatch(r'0x[0-9a-f]+|\d+', count) or int(count, 0) >= 32 or not src or src[0] != 'v' or + src[1] != src[2] or now is None): + return None + n, size = int(count, 0), getattr(self.pipe, 'group', (1 << 31,))[0] + if size > 1 << n: + return None + defined = self.vgpr_writer(src[1], now) + if src[1] == 0 and defined is None: + return '0u' + if defined is None: + return None + _, _, name, asm = self.ins[defined] + _, d, mods = parse(asm) + base = re.sub(r'_e(32|64)$', '', name) + scalar = reg_range(d[1]) if len(d) == 4 else None + if (base != 'v_lshl_add_u32' or mods or not scalar or scalar[0] != 's' or scalar[1] != scalar[2] or + scalar[1] > 105 or d[3] != 'v0' or not re.fullmatch(r'0x[0-9a-f]+|\d+', d[2]) or + n > int(d[2], 0) or int(d[2], 0) >= 32 or size > 1 << int(d[2], 0) or + self.vgpr_writer(0, defined) is not None or not self.uniform_source(d[1])): + return None + for _, _, later, later_asm in self.ins[defined + 1:now]: + if scalar[1] in scalar_destinations(later, later_asm) or 'any' in scalar_destinations(later, later_asm): + return None + return '((s%d << %du) >> %du)' % (scalar[1], int(d[2], 0), n) + + def pc_index(self): + return next((i for i, ins in enumerate(self.ins) if ins[0] == self.pc), None) + def uniform_source(self, tok): r = reg_range(tok) if r: @@ -3241,6 +3290,17 @@ def one(self, name, asm): dst = candidate[1] else: loaded = False + # A shift right of the X thread id, or of (uniform << K) + thread id, that leaves no thread-id bit. + shifted = None + if (dst is None and base == 'v_lshrrev_b32' and not mods and len(ops) == 3 and + self.tracks_uniformity() and hasattr(self, 'uniform_expr') and getattr(self, 'kind', None) == 'cs' and + not getattr(self, 'past_entry', True) and getattr(self, 'exec_known', False)): + candidate = reg_range(ops[0]) + shifted = self.tid_shift(ops[1], ops[2]) + if shifted is not None and candidate and candidate[0] == 'v' and candidate[1] == candidate[2]: + dst = candidate[1] + else: + shifted = None self.last_v = None if hasattr(self, 'heap_index'): # unit probes build a Stage without the tracking state # Any write ends a register's mark; the lowering below sets the new one, if any. @@ -3266,7 +3326,9 @@ def one(self, name, asm): # Proven sources are scalars, constants and VGPRs; each VGPR needs its own current expression. expr = self.last_v[1] if self.last_v and self.last_v[0] == dst else None vs = [int(n) for n in re.findall(r'\bv(\d+)\b', expr or '')] - if expr is None or loaded or any(n not in self.uniform_expr for n in vs): + if shifted is not None: + self.uniform_expr[dst] = shifted + elif expr is None or loaded or any(n not in self.uniform_expr for n in vs): self.uniform_expr.pop(dst, None) else: self.uniform_expr[dst] = re.sub(r'\bv(\d+)\b', lambda m: '(%s)' % self.uniform_expr[int(m[1])], From f4b53e0263a4b3905f3fce979a6da8bed6a00c3d Mon Sep 17 00:00:00 2001 From: triggered02 <153171514+triggered02@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:14:18 +0530 Subject: [PATCH 085/240] startup: lower 1D image sampling with an explicit level (#1722) * startup: lower 1D image sampling with an explicit level * Draw the 1D explicit LOD cases against distinct mip values * Keep the explicit-gradient refusal control aligned with the 1D diagnostic --------- Co-authored-by: Royoo <3230853833@qq.com> --- CMakeLists.txt | 7 + docs/experiments.md | 18 ++ tests/offscreen_check.cpp | 11 +- tests/startup_gfx2hlsl_image_1d_check.py | 211 +++++++++++++++++++++++ tests/startup_image_3d.cpp | 2 +- tests/startup_image_sample_b_check.py | 2 +- tests/startup_image_sample_d_check.py | 2 +- tests/startup_image_sample_l_check.py | 8 +- tools/startup/gfx2hlsl.py | 15 +- 9 files changed, 264 insertions(+), 12 deletions(-) create mode 100644 tests/startup_gfx2hlsl_image_1d_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 51b074e68..570a06722 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3420,6 +3420,9 @@ if(EXISTS "${INTAKE_PYTHON}") # lowering of the same selections. add_test(NAME startup_gfx2hlsl_sdwa COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_sdwa_check.py") + # 1D image sampling with an explicit level (#1721). + add_test(NAME startup_gfx2hlsl_image_1d COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_image_1d_check.py") # Handlers that do not model a modifier they can receive refuse it (#1771). add_test(NAME startup_gfx2hlsl_modifier_free COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_modifier_free_check.py") @@ -3730,6 +3733,10 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/startup_image_3d_check.py" draw "${DXC_EXECUTABLE}" "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_image_3d_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + add_test(NAME startup_gfx2hlsl_image_1d_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_image_1d_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_gfx2hlsl_image_1d_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) add_test(NAME startup_image_load_mip_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_image_load_mip_check.py" --draw "${DXC_EXECUTABLE}" "$" ${adapter}) diff --git a/docs/experiments.md b/docs/experiments.md index cae5d444a..5bb19d36a 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -16386,6 +16386,24 @@ ctest --preset dev --no-tests=error -R '^startup_resource_(retire|budget)' -V ctest --preset dev --no-tests=error -R '^startup_compute_tg_size_' -V ``` +## Explicit-level 1D image sampling in the startup translator + +[The startup translator](../tools/startup/gfx2hlsl.py) now lowers 1D `image_sample_lz` and `image_sample_l` onto `Texture1D.SampleLevel` alongside the existing implicit-level `image_sample` path (#1721): + +- `image_sample_lz` takes one address dword (`u`) and lowers to `tex.SampleLevel(smp, F(u), 0)`. +- `image_sample_l` takes two address dwords (`u`, then the explicit `lod`) and lowers to `tex.SampleLevel(smp, F(u), F(lod))`. +- Both explicit-level forms require a non-empty `dmask` and accept only `dim:SQ_RSRC_IMG_1D`, `dmask:*`, and the cache-policy modifiers (`glc`, `slc`, `dlc`). Plain `image_sample` on 1D keeps its existing rule (still refusing cache-policy bits), and layout or address modifiers (`unorm`, `r128`, `a16`, `d16`, `tfe`, `lwe`, reserved bits), wrong address counts, empty `dmask`, `image_sample_b`, and `image_load` on 1D stay refused. + +[The 1D image check](../tests/startup_gfx2hlsl_image_1d_check.py) builds synthetic MIMG instructions against the decoder layout and verifies `image_sample_lz`, `image_sample_l`, plain `image_sample`, 2D separation, cache-policy equivalence, empty `dmask`, and refused forms. Run: + +```powershell +ctest --preset dev --no-tests=error -j 1 -R '^startup_gfx2hlsl_image_1d($|_)' -V +``` + +The draw fixture binds a three-mip Texture1D with a distinct value per mip. With LOD +inputs 1 and 2, the zero-level form reads level 0 and the explicit form reads the +provided level. Forcing the explicit level to zero changes the level-2 readback. + ## Startup translator: v_mad_u32_u16 [`tools/startup/gfx2hlsl.py`](../tools/startup/gfx2hlsl.py) now lowers the unmodified gfx1013 VOP3A instruction `v_mad_u32_u16` (`0x373` in [`tools/disasm_rdna2.py`](../tools/disasm_rdna2.py)) via `VEC_U` as `({0} & 0xffffu) * ({1} & 0xffffu) + {2}` (unsigned 32-bit wraparound). In `Stage.lower`, `S0` and `S1` are read with `low16_only=True` because only bits `[15:0]` of those operands are consumed (allowing odd-dmask `d16` `image_load` results in `S0`/`S1` and clearing `low16_only_v` on the 32-bit destination), while `S2` is read with `low16_only=False` (refusing `low16_only_v` sources) so all 32 bits of the addend are preserved. Modifiers (`op_sel`, `clamp`, `omod`, `abs`, `neg`) and wrong operand counts remain refused. diff --git a/tests/offscreen_check.cpp b/tests/offscreen_check.cpp index 5c1b653c8..7ed885fd3 100644 --- a/tests/offscreen_check.cpp +++ b/tests/offscreen_check.cpp @@ -1322,8 +1322,10 @@ OperationResult run_startup_sampler_heap(const OperationContext& ctx) // mip levels whose cells all differ (tests/startup_image_3d.cpp). OperationResult run_startup_image_3d(const OperationContext& ctx) { - const bool mips = std::strcmp(ctx.argv[2], "--startup-image-2d-array-mips") == 0; - const bool array = mips || std::strcmp(ctx.argv[2], "--startup-image-2d-array") == 0; + const bool array_mips = std::strcmp(ctx.argv[2], "--startup-image-2d-array-mips") == 0; + const bool one_dimensional_mips = std::strcmp(ctx.argv[2], "--startup-image-1d-mips") == 0; + const bool array = array_mips || std::strcmp(ctx.argv[2], "--startup-image-2d-array") == 0; + const bool one_dimensional = one_dimensional_mips || std::strcmp(ctx.argv[2], "--startup-image-1d") == 0; const bool two_dimensional = std::strcmp(ctx.argv[2], "--startup-image-2d") == 0; float z = 0.0f; if (two_dimensional && ctx.argv[5][0] == '0' && (ctx.argv[5][1] == 'x' || ctx.argv[5][1] == 'X')) { @@ -1340,8 +1342,8 @@ OperationResult run_startup_image_3d(const OperationContext& ctx) return {OutcomeKind::fail, "expected value is not four hex words"}; float color[4]{}; const char* sampler = ctx.argc == 8 ? ctx.argv[7] : "smp 0 0x0 0x0 0x0 0x0"; - check_startup_image_3d(ctx.device, ctx.argv[3], ctx.argv[4], z, color, sampler, array, mips ? 3 : 1, - std::strcmp(ctx.argv[2], "--startup-image-1d") == 0, two_dimensional); + check_startup_image_3d(ctx.device, ctx.argv[3], ctx.argv[4], z, color, sampler, array, + array_mips || one_dimensional_mips ? 3 : 1, one_dimensional, two_dimensional); std::uint32_t bits[4]; std::memcpy(bits, color, sizeof(bits)); if (std::memcmp(bits, expected, sizeof(bits)) != 0) { @@ -1680,6 +1682,7 @@ const OperationSpec kOperations[] = { {"--sampler-index-control", 3, 3, nullptr, kGateSm60SamplerIndexControl, run_sampler_index_control}, {"--startup-sampler-heap", 7, 9, nullptr, kNoGate, run_startup_sampler_heap}, {"--startup-image-1d", 7, 8, nullptr, kNoGate, run_startup_image_3d}, + {"--startup-image-1d-mips", 7, 8, nullptr, kNoGate, run_startup_image_3d}, {"--startup-image-2d", 7, 8, nullptr, kNoGate, run_startup_image_3d}, {"--startup-image-2d-view", 7, 7, nullptr, kNoGate, run_startup_image_2d_view}, {"--startup-image-3d", 7, 8, nullptr, kNoGate, run_startup_image_3d}, diff --git a/tests/startup_gfx2hlsl_image_1d_check.py b/tests/startup_gfx2hlsl_image_1d_check.py new file mode 100644 index 000000000..d24436c81 --- /dev/null +++ b/tests/startup_gfx2hlsl_image_1d_check.py @@ -0,0 +1,211 @@ +"""1D image sampling in tools/startup/gfx2hlsl.py (issue #1721). + +usage: startup_gfx2hlsl_image_1d_check.py [draw ] + +A 1D image has one coordinate, and `image_sample_lz` / `image_sample_l` carry the explicit level in the next +address dword. The translator accepted 1D only for the implicit-level `image_sample`, so the two explicit-level +forms were refused - 2 of the 29 refused shaders in the first loading-screen cache (#870). + +The instruction bytes are **constructed here** from the field layout the checked-in decoder reads +(`tools/disasm_rdna2.py`, MIMG branch): + w0: [31:26] = 0b111100, [24:18] opcode low 7 bits, [0] opcode bit 7, [11:8] dmask, [5:3] dimension, + [2:1] NSA dword count, [12] unorm, [15] r128 + w1: [7:0] vaddr, [15:8] vdata, [20:16] srsrc/4, [25:21] sampler/4 +""" +import os +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +here = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(here, '..', 'tools')) +sys.path.insert(0, os.path.join(here, '..', 'tools', 'startup')) +import gfx2hlsl as G # noqa: E402 + +failures = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH'}") + if not condition: + failures.append(label) + if detail: + print(' ' + detail) + + +IMG_LOAD = 0x00 +IMG_SAMPLE = 0x20 +IMG_SAMPLE_L = 0x24 +IMG_SAMPLE_LZ = 0x27 +DIM_1D = 0 +DIM_2D = 1 + + +def encode_mimg(op, *, dmask=0xF, dim=DIM_1D, vaddr=0, vdata=4, srsrc=8, ssamp=12, nsa=0, + extra_addrs=(), unorm=0, r128=0, glc=0, slc=0, dlc=0): + """Encode one MIMG instruction; returns its bytes (8 + 4 per NSA dword).""" + w0 = ((0b111100 << 26) | ((op & 0x7F) << 18) | (((op >> 7) & 1) << 0) + | ((dmask & 0xF) << 8) | ((dim & 0x7) << 3) | ((nsa & 0x3) << 1) + | ((unorm & 1) << 12) | ((r128 & 1) << 15) | ((dlc & 1) << 7) + | ((glc & 1) << 13) | ((slc & 1) << 25)) + w1 = ((vaddr & 0xFF) | ((vdata & 0xFF) << 8) | (((srsrc // 4) & 0x1F) << 16) + | (((ssamp // 4) & 0x1F) << 21)) + return struct.pack('> level) * 3 // 4 + rgba = ((1 + x + 32 * level) / 128, x, 0, 0.75 if x else 0.5) + return ','.join(f'{struct.unpack(" 1: + if len(sys.argv) != 5 or sys.argv[1] != 'draw': + sys.exit(__doc__) + draw(*sys.argv[2:]) diff --git a/tests/startup_image_3d.cpp b/tests/startup_image_3d.cpp index 6c0070de6..8305017fd 100644 --- a/tests/startup_image_3d.cpp +++ b/tests/startup_image_3d.cpp @@ -70,7 +70,7 @@ void check_startup_image_3d(ID3D12Device* device, const char* vertex_path, const float color[4], const char* sampler_line, bool array, UINT levels, bool one_dimensional, bool two_dimensional, UINT first_mip, UINT view_levels) { - if (levels < 1 || levels > max_levels || (levels > 1 && !array && !two_dimensional)) + if (levels < 1 || levels > max_levels || (levels > 1 && !array && !two_dimensional && !one_dimensional)) throw std::runtime_error("Unsupported image mip level count"); if (view_levels && (!two_dimensional || first_mip >= levels || view_levels > levels - first_mip)) throw std::runtime_error("2D mip window exceeds the resource"); diff --git a/tests/startup_image_sample_b_check.py b/tests/startup_image_sample_b_check.py index 356010aa7..d398e8676 100644 --- a/tests/startup_image_sample_b_check.py +++ b/tests/startup_image_sample_b_check.py @@ -518,7 +518,7 @@ def controls(): refused('gather', 'image_gather4_b') refused('cube', 'image dimension SQ_RSRC_IMG_CUBE') refused('msaa', 'image dimension SQ_RSRC_IMG_') - refused('dim1d', 'unverified 1D image sample address or modifiers') + refused('dim1d', 'unverified 1D image b address or modifiers') refused('unorm', 'image_sample_b modifier unorm') refused('tfe', 'image_sample_b modifier tfe') refused('a16', 'image_sample_b modifier a16') diff --git a/tests/startup_image_sample_d_check.py b/tests/startup_image_sample_d_check.py index 719903e18..d684232c5 100644 --- a/tests/startup_image_sample_d_check.py +++ b/tests/startup_image_sample_d_check.py @@ -108,7 +108,7 @@ def controls(): refused('cd', 'image_sample_c_d') refused('do', 'image_sample_d_o') - refused('d1', 'unverified 1D image sample address or modifiers') + refused('d1', 'unverified 1D image d address or modifiers') refused('dtfe', 'image_sample_d modifier tfe') print('refused: compare, offset, 1D, tfe') diff --git a/tests/startup_image_sample_l_check.py b/tests/startup_image_sample_l_check.py index d406e77dc..72d4a0fff 100644 --- a/tests/startup_image_sample_l_check.py +++ b/tests/startup_image_sample_l_check.py @@ -251,11 +251,15 @@ def controls(): refused('d16', 'image_sample_l modifier d16') # half-precision result layout refused('r128', 'image_sample_l modifier r128') # four-dword resource descriptor refused('dmask0', 'empty dmask') - refused('dim1d', 'unverified 1D image sample address or modifiers') + # A 1D image has one coordinate and the level in the next address dword, so it lowers to Texture1D + # with the same SampleLevel call shape a 2D image uses (issue #1721). + one_d = stage('dim1d') + assert 'Texture1D' in one_d, one_d + assert re.search(r'SampleLevel\(\w+, F\(v0\), F\(v1\)\)', one_d), one_d refused('msaa', 'image dimension SQ_RSRC_IMG_') for name in RESERVED: refused(name, 'image_sample_l modifier reserved') # bits LLVM ignores must not be silently accepted - print('refused: offset, compare, gather, cube, 1D, MSAA, unorm, a16, tfe, lwe, d16, r128, dmask 0, reserved bits') + print('refused: offset, compare, gather, cube, MSAA, unorm, a16, tfe, lwe, d16, r128, dmask 0, reserved bits') # Cache-policy bits do not change the sampled value: same lowering as the plain form. for name in ('glc', 'slc', 'dlc'): diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index c4fdb7d95..6343147b4 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -5558,8 +5558,16 @@ def image(self, ops, mods, how): else: r = reg_range(coords) cs = ['v%d' % n for n in range(r[1], r[2] + 1)] - if one and (how != 'sample' or len(cs) != 1 or not dmask or any(not m.startswith(('dim:', 'dmask:')) for m in mods)): - raise Unsupported('unverified 1D image sample address or modifiers') + # A 1D image has one coordinate. sample_lz and sample_l carry the explicit level in the next + # address dword, so their address is x then level; Texture1D.SampleLevel takes the location as a + # float, which is what the `one` branch below builds. Anything else stays refused by name. + if one: + expected = {'sample': 1, 'lz': 1, 'l': 2}.get(how) + if expected is None or len(cs) != expected or not dmask: + raise Unsupported('unverified 1D image %s address or modifiers' % how) + for m in mods: + if not (m.startswith(('dim:', 'dmask:')) or (how != 'sample' and m in ('dlc', 'glc', 'slc'))): + raise Unsupported('1D image %s modifier %s' % (how, m)) lod = bias = None grads = None if how == 'd': @@ -5596,7 +5604,8 @@ def image(self, ops, mods, how): raise Unsupported('%s modifier %s' % (name, m)) if dmask == 0: raise Unsupported('%s with an empty dmask' % name) - if len(cs) != (4 if three else 3): + expected = 4 if three else (2 if one else 3) + if len(cs) != expected: raise Unsupported('%s with %d address registers' % (name, len(cs))) if how == 'l': lod, cs = cs[-1], cs[:-1] From d382863b04a18356f068616dce4e1086a63463f9 Mon Sep 17 00:00:00 2001 From: RavenCurseBurg Date: Thu, 26 Nov 2026 10:46:01 +0800 Subject: [PATCH 086/240] gfx2hlsl: prove lane-local compute readfirstlane waterfall bodies (#2694) * gfx2hlsl: prove lane-local compute readfirstlane waterfall bodies * tests: preserve adapter-selection notices in compute readfirstlane readbacks --------- Co-authored-by: RavenCurseBurg <360931527+RavenCurseBurg@users.noreply.github.com> --- docs/experiments.md | 8 ++ tests/startup_compute_readfirstlane_check.py | 9 +- tests/startup_compute_waterfall.py | 107 +++++++++++++++++++ tools/startup/gfx2hlsl.py | 97 +++++++++++++++++ 4 files changed, 218 insertions(+), 3 deletions(-) create mode 100644 tests/startup_compute_waterfall.py diff --git a/docs/experiments.md b/docs/experiments.md index 5bb19d36a..021a45447 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15557,6 +15557,14 @@ ctest --preset dev --no-tests=error -R '^(startup_gfx2hlsl_readfirstlane_(unifor python -B tests/startup_compute_readfirstlane_check.py --llvm-mc llvm-mc-15 ``` +The same checks exercise a [four-thread resource-index waterfall](../tests/startup_compute_waterfall.py) for #2644. +`v_readfirstlane_b32` selects a key and the following `v_cmpx_eq_i32` enables the lanes sharing that key. A saved +copy of `exec_lo`, `s_andn2_wrexec_b32` and a backward `s_cbranch_scc1` serve the remaining lanes. Each participating +lane can execute one visit with its own key when the body performs proven lane-local operations and its temporary +scalars are dead at exit. The fixtures vary the active count from zero to four, restore EXEC, and check both an +arithmetic result and a key-dependent byte offset in one fixed raw buffer. A read of the group's active mask, +a store inside the loop, a live scalar or a key-selected descriptor keeps an instruction-specific refusal. + ## Desktop audio render sink `startup_audio_output` drives a small WASAPI shared-mode render sink ([`audio_sink.h`](../src/startup_stubs/audio_sink.h)) with generated PCM blocks. It is the first slice of [issue #1145](https://github.com/R0Y00/Xbox2Windows/issues/1145). The sink takes `submit(format, frames, bytes)`, converts the block to the endpoint mix format (32-bit float or 16-bit PCM only) and records the first accepted block, the submitted format, per-block frame counts and peaks, consumed frames (submitted minus `GetCurrentPadding`), the `IAudioClock` position, the drained interval and the recovery. The fixture runs three cases in one process: no submission; eight 40 ms blocks with distinct amplitudes, one of them intentionally silent; and a producer that withholds the next block until the queue is empty, then resumes. diff --git a/tests/startup_compute_readfirstlane_check.py b/tests/startup_compute_readfirstlane_check.py index 56cf8f2ab..f7326e1f7 100644 --- a/tests/startup_compute_readfirstlane_check.py +++ b/tests/startup_compute_readfirstlane_check.py @@ -8,7 +8,8 @@ reads it through ``v_readfirstlane_b32`` at the join, runs a four-iteration uniform loop whose counter ``s22`` is incremented uniformly and read back via ``v_readfirstlane_b32`` both inside the loop and after loop exit, and stores one combined word per thread across two four-thread groups ``(4, 1, 1) x (2, 1, 1)`` so both arms of the branch -run on the GPU. +run on the GPU. The waterfall fixtures also exercise a lane-varying key. They restore the incoming threads +after selecting zero to four lanes, then read back per-key arithmetic and a load from one fixed raw buffer. """ import argparse from pathlib import Path @@ -23,6 +24,7 @@ sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) import disasm_rdna2 as D # noqa: E402 +import startup_compute_waterfall as waterfall from startup_gfx2hlsl_compute_check import ( # noqa: E402 CASES, G, KEY, MASK, SENTINEL, STRIDE, WORDS, patch, refused, root_blob, ) @@ -194,7 +196,8 @@ def controls(llvm_mc=None): if llvm_mc: check_binary(llvm_mc) - print('Compute readfirstlane one-path, loop-counter and refusal checks passed') + waterfall.controls(llvm_mc) + print('Compute readfirstlane one-path, loop-counter, waterfall and refusal checks passed') CONTROLS = { @@ -248,7 +251,7 @@ def dispatch(dxc, runner, adapter): raise AssertionError('baseline (%s): %s' % (adapter, proc.stderr or 'exit %d' % proc.returncode)) else: print('baseline (%s): all %d words match' % (adapter, WORDS)) - return 0 + return waterfall.dispatch(td, dxc, runner, adapter) def main(argv): diff --git a/tests/startup_compute_waterfall.py b/tests/startup_compute_waterfall.py new file mode 100644 index 000000000..1646999c6 --- /dev/null +++ b/tests/startup_compute_waterfall.py @@ -0,0 +1,107 @@ +"""Source-built four-lane numeric waterfall for the compute readfirstlane fixture (#2644).""" +import struct +import subprocess + +from compute_load_format_check import check_references +from startup_gfx2hlsl_compute_check import G, MASK, SENTINEL, USER7, WORDS, assemble, refused, root_blob + + +# The input buffer contains the keys. Root constant s4 selects how many lanes enter the loop. +# Every lane writes its result after the original EXEC is restored, including the initial 13 for inactive lanes. +PREFIX = ( + ('s_mov_b32 s10, s6', '06038abe'), ('s_mov_b32 s11, 0', '80038bbe'), + ('s_load_dwordx8 s[12:19], s[10:11], 0', '05030cf4000000fa'), ('s_waitcnt lgkmcnt(0)', '7fc08cbf'), + ('v_lshlrev_b32_e32 v4, 2, v0', '82000834'), ('buffer_load_dword v5, v4, s[12:15], 0 offen', '001030e004050380'), + ('s_waitcnt vmcnt(0)', '703f8cbf'), ('v_mov_b32_e32 v7, 13', '8d020e7e'), + ('s_mov_b32 s26, exec_lo', '7e039abe'), ('v_cmpx_gt_u32_e32 s4, v0', '0400a87d'), +) +SAVE = ('s_mov_b32 s21, exec_lo', '7e0395be') +HEAD = ('v_readfirstlane_b32 s22, v5', '05052c7e') +COMPARE = ('v_cmpx_eq_i32_e32 s22, v5', '160a247d') +ADD = ('s_add_u32 s23, s22, 17', '16911780') +XOR = ('v_xor_b32_e32 v7, s23, v0', '17000e3a') +CLOSE = ('s_andn2_wrexec_b32 s21, s21', '154795be') +RESTORE = ('s_mov_b32 exec_lo, s26', '1a03febe') +STORE = ('buffer_store_dword v7, v4, s[16:19], 0 offen', '001070e004070480') +END = ('s_endpgm', '000081bf') +FIXED_LOAD = (('s_load_dwordx4 s[28:31], s[10:11], 0', '050708f4000000fa'), ('s_waitcnt lgkmcnt(0)', '7fc08cbf'), + ('v_mov_b32_e32 v8, s22', '1602107e'), ('buffer_load_dword v7, v8, s[28:31], 0 offen', '001030e008070780'), + ('s_waitcnt vmcnt(0)', '703f8cbf')) + + +def program(*, before_save=(), after_save=(), compare=COMPARE, body=(ADD, XOR), after_restore=()): + loop = (HEAD, compare, *body, CLOSE) + offset = -(sum(len(bytes.fromhex(code)) for _, code in loop) // 4 + 1) + branch = ('s_cbranch_scc1 %d' % offset, struct.pack(' 32: + return 'b32 remaining mask requires at most 32 threads per group' + copy = None + for i in reversed(range(head)): + _, _, op, asm = ins[i] + if op.startswith(('s_branch', 's_cbranch', 's_setpc', 's_endpgm', 's_movrel')): + break + if remaining in effects[i][2] or effects[i][2] & EXEC_KEYS: + if op == 's_mov_b32' and parse(asm)[1] == [remaining, 'exec_lo']: + copy = i + break + if copy is None: + return 'remaining mask is not an unchanged copy of EXEC' + if any(ins[copy][0] < target <= ins[close][0] for branch, target in jumps if branch != close): + return 'another branch enters the saved mask or loop' + # Only ordinary lane-local operations and reads of a bound raw buffer. An instruction + # that observes the other lanes sharing this key cannot use this scalarization (e.g. mbcnt of EXEC). + body_writes = {key, 'scc'} # WREXEC supplies SCC for the next iteration. + numeric_writes = {key} + descriptor_inputs, buffer_descriptors = set(), set() + reads_before_write = set() + defined = {key} + for j in range(head + 2, close - 1): + base, ops, mods = parse(ins[j][3]) + base = re.sub(r'_e(32|64)$', '', base) + if base not in ('s_add_u32', 's_mov_b32', 's_and_b32', 's_or_b32', 's_lshl_b32', 's_waitcnt', + 'v_mov_b32', 'v_xor_b32', 'v_add_nc_u32', 's_load_dwordx4', 'buffer_load_dword'): + return 'body instruction %s is not proven lane-local' % base + if mods and not (base == 'buffer_load_dword' and mods == ['offen']): + return 'body instruction %s has unproved modifiers' % base + reads, writes, may_write = effects[j] + if (reads | may_write) & (EXEC_KEYS | {'vcc', 'vcc_hi', 'm0', remaining}): + return 'body reads or changes a lane mask or special register' + if base == 's_load_dwordx4': + dst = reg_range(ops[0]) if len(ops) == 3 else None + if not dst or dst[0] != 's' or dst[2] > 105: + return 'descriptor load overlaps a special register' + descriptor_inputs.update(reads) + else: + numeric_writes.update(may_write) + if base == 'buffer_load_dword': + if len(ops) < 3: + return 'buffer load has no descriptor' + buffer_descriptors.update(scalar_tokens(ops[2])) + reads_before_write.update(reads - defined) + defined.update(writes) + body_writes.update(may_write) + if reads_before_write & body_writes: + return 'body reads loop-carried scalar state' + # The data byte offset can use the key. Loading or modifying the resource descriptor + # with the key needs a separate proof that the runtime binds the whole range. + if descriptor_inputs & body_writes or buffer_descriptors & numeric_writes: + return 'per-lane descriptor selection requires a proven bound heap range' + # The close leaves EXEC and SCC zero. The last physical pass's other scalar + # values can differ per lane in this model and must be dead on every successor. + if close + 1 < len(ins) and (body_writes - {'scc'}) & live_in[close + 1]: + return 'body scalar is live at the loop exit' + if any(name.startswith('s_movrel') for _, _, name, _ in ins): + return 'relative scalar indexing can observe a loop register' + return None + def phi_mask_ok(self, key, b, t, effects, succ, targets, index): """True when lane mask `key` ('vcc' for vcc_lo, or 'sN'), live at the join t of the s_cbranch_execz at b, is the zeroed-then-set-from-exec shape execz_refusals accepts (see its docstring): every write of it in the @@ -6444,6 +6534,13 @@ def proven_uniform_v(self, n): def op_v_readfirstlane_b32(self, ops, mods): src, dst = reg_range(ops[1]), reg_range(ops[0]) past_entry = getattr(self, 'past_entry', True) + waterfalls = getattr(self, 'waterfall_reads', {}) + if getattr(self, 'pc', None) in waterfalls and not (src and self.proven_uniform_v(src[1])): + reason = waterfalls[self.pc] + if reason: + raise Unsupported('compute readfirstlane waterfall: ' + reason) + self.set_s(dst[1], self.u(ops[1]), uniform=False) # the selected key varies between lanes + return if (mods or not dst or dst[0] != 's' or dst[1] != dst[2] or not src or src[0] != 'v' or src[1] != src[2] or not self.proven_uniform_v(src[1])): raise Unsupported('v_readfirstlane_b32 requires a proven uniform source') From d93cd7007f0c84ec57e24373894ebce384c34ed0 Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Thu, 26 Nov 2026 04:48:12 +0200 Subject: [PATCH 087/240] runtime: harden startup triage_run CLI guards and add CLI suite (#2672) --- CMakeLists.txt | 3 + tests/startup_triage_run_cli_check.py | 393 ++++++++++++++++++++++++++ tools/startup/triage_run.py | 24 +- 3 files changed, 418 insertions(+), 2 deletions(-) create mode 100644 tests/startup_triage_run_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 570a06722..38ae556ae 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4633,6 +4633,9 @@ if(EXISTS "${INTAKE_PYTHON}") set_tests_properties(startup_gfx2hlsl_export_mask_drop_control PROPERTIES WILL_FAIL TRUE) add_test(NAME startup_triage_run COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_triage_run_check.py") + add_test(NAME runtime_startup_triage_run_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_triage_run_cli_check.py") + set_tests_properties(runtime_startup_triage_run_cli_check PROPERTIES TIMEOUT 60) add_test(NAME startup_run_ps1 COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_run_ps1_check.py") # The Linux launcher's check exits 77 on Windows; the Ubuntu job runs it. diff --git a/tests/startup_triage_run_cli_check.py b/tests/startup_triage_run_cli_check.py new file mode 100644 index 000000000..346be0e1b --- /dev/null +++ b/tests/startup_triage_run_cli_check.py @@ -0,0 +1,393 @@ +#!/usr/bin/env python3 +"""Pure-Python synthetic log/cache CLI, validation, and mutation suite for tools/startup/triage_run.py.""" + +from __future__ import annotations + +from contextlib import redirect_stderr, redirect_stdout +import io +from pathlib import Path +import runpy +import subprocess +import sys +import tempfile +import types +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOLS_STARTUP = ROOT / "tools" / "startup" +TOOL = TOOLS_STARTUP / "triage_run.py" +sys.path.insert(0, str(TOOLS_STARTUP)) +import triage_run # noqa: E402 + + +SYNTHETIC_LOG = "\n".join([ + "x2w-d3d12 Device::slot70 unsupported memory SRV arguments: reason=unsupported_description " + "res{dim=1 fmt=0 size=4096x1x1 mips=1 layout=0x1 flags=0x0 align=0 samples=1/0} " + "view{dim=11 fmt=0 map=0x1688} dest=0x1 dest_in_view_heap=1 address=0x2 address_readable=0", + "x2w-dstorage options=0x1 dest=0x1 dest_size=0x1000 source=0x1 offset=0x0 size=0x100 -> zlib failed", + "x2w-dstorage options=0x1 dest=0x1 dest_size=0x1000 source=0x1 offset=0x100 size=0x100 -> read failed", + "x2w-runtime 12345678::slot5(0x1) -> 0x80004005 from +0x100", + "x2w-runtime 12345678::slot6(0x1) -> 0x80070005 from +0x200", + "x2w-runtime 12345678::slot7(0x1) -> 0x80070057 from +0x300", +]) + "\n" + + +def _run_main(module, argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = module.main(argv) + except SystemExit as exc: + code = exc.code + if not isinstance(code, int): + if code is not None: + stderr.write(f"{code}\n") + code = 0 if code is None else 1 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class StartupTriageRunCliPositiveTests(unittest.TestCase): + def test_directory_logdir_with_shader_cache_and_max_items(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + logdir = root / "logs" + (logdir / "nested").mkdir(parents=True) + (logdir / "stderr.txt").write_text(SYNTHETIC_LOG, encoding="utf-8") + # Mirrored trap.log line should be deduplicated against sibling stderr.txt. + (logdir / "trap.log").write_text( + "x2w-dstorage options=0x1 dest=0x1 dest_size=0x1000 source=0x1 offset=0x0 size=0x100 -> zlib failed\n", + encoding="utf-8", + ) + (logdir / "nested" / "extra.out").write_text( + "x2w-dstorage options=0x1 dest=0x1 dest_size=0x1000 source=0x1 offset=0x200 size=0x100 -> bcpack failed\n", + encoding="utf-8", + ) + # Non-log extension must be ignored. + (logdir / "ignored.json").write_text( + "x2w-dstorage options=0x1 dest=0x1 dest_size=0x1000 source=0x1 offset=0x300 size=0x100 -> read failed\n", + encoding="utf-8", + ) + + cache_dir = root / "shader_cache" + cache_dir.mkdir() + (cache_dir / "0000000000000001.fail").write_text("image_load_mip tfe\n", encoding="utf-8") + (cache_dir / "0000000000000002.fail").write_text("image_load_mip tfe\n", encoding="utf-8") + (cache_dir / "0000000000000003.fail").write_text("image_load_mip a16\n", encoding="utf-8") + (cache_dir / "req_0000000000000003.c67").write_bytes(b"\0" * 4) + + argv = [str(logdir), "--shader-cache", str(cache_dir), "--max-items", "2"] + code, out, err = _run_main(triage_run, argv) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertIn("## Startup Run Triage Summary", out) + self.assertIn("- Log files scanned: `3`", out) + self.assertIn("- `X2W_SHADER_CACHE` `.fail` shaders: `3` (2 unique reasons)", out) + self.assertIn("### `X2W_SHADER_CACHE` `.fail` Reasons", out) + self.assertIn("| 2 | `image_load_mip tfe` |", out) + self.assertIn("| 1 | `compute: image_load_mip a16` |", out) + self.assertIn("_Showing top 2 of 3 unique entries (3 total events)._", out) + + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stderr, "") + self.assertEqual(proc.stdout, out) + + def test_single_file_logdir_argv_none_and_main_entrypoint(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + single = root / "single.log" + single.write_text( + "x2w-dstorage options=0x1 dest=0x1 dest_size=0x10 source=0x1 offset=0x0 size=0x10 -> read failed\n", + encoding="utf-8", + ) + + with mock.patch.object(sys, "argv", [str(TOOL), str(single), "--max-items", "1"]): + code, out, err = _run_main(triage_run, None) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertIn("- Log files scanned: `1`", out) + self.assertIn("| 1 | read failed |", out) + self.assertNotIn("X2W_SHADER_CACHE", out) + + stdout_m, stderr_m = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", [str(TOOL), str(single)]), + redirect_stdout(stdout_m), + redirect_stderr(stderr_m), + self.assertRaises(SystemExit) as exited, + ): + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 0) + self.assertEqual(stderr_m.getvalue(), "") + self.assertIn("| 1 | read failed |", stdout_m.getvalue()) + + +class StartupTriageRunCliNegativeTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_code: int | None = 1, + fragments: tuple[str, ...] = (), + check_subprocess: bool = True, + ) -> str: + code, out, err = _run_main(triage_run, argv) + if expected_code is None: + self.assertNotEqual(code, 0) + else: + self.assertEqual(code, expected_code, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertTrue(err.strip()) + for fragment in fragments: + self.assertIn(fragment.lower(), err.lower()) + + if check_subprocess: + proc = _run_subprocess(*argv) + if expected_code is None: + self.assertNotEqual(proc.returncode, 0) + else: + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + for fragment in fragments: + self.assertIn(fragment.lower(), proc.stderr.lower()) + return err + + def test_missing_and_non_regular_logdir_rejected_upfront(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + missing_log = root / "missing_logs" + non_regular = root / "special_entry" + + with mock.patch.object( + triage_run, + "triage_run", + side_effect=AssertionError("triage_run called for invalid logdir"), + ): + self._assert_clean_failure( + [str(missing_log)], + expected_code=1, + fragments=("log path not found",), + ) + + orig_exists = Path.exists + orig_is_file = Path.is_file + orig_is_dir = Path.is_dir + + def fake_exists(p: Path) -> bool: + return True if p == non_regular else orig_exists(p) + + def fake_is_file(p: Path) -> bool: + return False if p == non_regular else orig_is_file(p) + + def fake_is_dir(p: Path) -> bool: + return False if p == non_regular else orig_is_dir(p) + + with ( + mock.patch.object(Path, "exists", fake_exists), + mock.patch.object(Path, "is_file", fake_is_file), + mock.patch.object(Path, "is_dir", fake_is_dir), + ): + self._assert_clean_failure( + [str(non_regular)], + expected_code=1, + fragments=("regular file or directory",), + check_subprocess=False, + ) + + def test_missing_and_file_shader_cache_rejected_upfront(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + logdir = root / "logs" + logdir.mkdir() + (logdir / "stderr.txt").write_text("", encoding="utf-8") + missing_cache = root / "missing_cache" + file_cache = root / "not_a_dir.txt" + file_cache.write_text("file contents", encoding="utf-8") + + with mock.patch.object( + triage_run, + "triage_run", + side_effect=AssertionError("triage_run called for invalid shader_cache"), + ): + self._assert_clean_failure( + [str(logdir), "--shader-cache", str(missing_cache)], + expected_code=1, + fragments=("shader cache directory not found",), + ) + self._assert_clean_failure( + [str(logdir), "--shader-cache", str(file_cache)], + expected_code=1, + fragments=("shader cache path is not a directory",), + ) + + def test_non_positive_max_items_rejected_upfront(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + logdir = root / "logs" + logdir.mkdir() + + with mock.patch.object( + triage_run, + "triage_run", + side_effect=AssertionError("triage_run called for invalid --max-items"), + ): + for bad_value in ("0", "-1", "-100"): + with self.subTest(max_items=bad_value): + self._assert_clean_failure( + [str(logdir), "--max-items", bad_value], + expected_code=1, + fragments=("--max-items must be at least 1", bad_value), + ) + + def test_runtime_oserror_valueerror_and_main_exit_code_1_without_traceback(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + logdir = root / "logs" + logdir.mkdir() + + for exc in (OSError("simulated I/O failure"), ValueError("simulated parse failure")): + with self.subTest(exc=type(exc).__name__): + with mock.patch.object(triage_run, "triage_run", side_effect=exc): + self._assert_clean_failure( + [str(logdir)], + expected_code=1, + fragments=(str(exc),), + check_subprocess=False, + ) + + stdout_m, stderr_m = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", [str(TOOL), str(root / "absent")]), + redirect_stdout(stdout_m), + redirect_stderr(stderr_m), + self.assertRaises(SystemExit) as exited, + ): + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 1) + self.assertEqual(stdout_m.getvalue(), "") + self.assertNotIn("Traceback", stderr_m.getvalue()) + self.assertIn("log path not found", stderr_m.getvalue().lower()) + + def test_argparse_errors_py314_safe(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + logdir = root / "logs" + logdir.mkdir() + + for argv, frags in ( + ([], ("required",)), + ([str(logdir), "--shader-cache"], ("expected one argument",)), + ([str(logdir), "--max-items"], ("expected one argument",)), + ([str(logdir), "--max-items", "abc"], ("invalid",)), + ([str(logdir), "--bogus-flag"], ("unrecognized",)), + ): + with self.subTest(argv=argv): + self._assert_clean_failure( + argv, + expected_code=None, + fragments=frags, + ) + + def test_fast_temp_mutations(self) -> None: + source = TOOL.read_text(encoding="utf-8") + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + valid_logdir = root / "logs" + valid_logdir.mkdir() + (valid_logdir / "stderr.txt").write_text("", encoding="utf-8") + missing_log = root / "missing_logs" + non_regular = root / "special_entry" + missing_cache = root / "missing_cache" + file_cache = root / "file_cache.txt" + file_cache.write_text("not a dir", encoding="utf-8") + + mutations = [ + ( + "drop_logdir_exists_guard", + " if not args.logdir.exists():\n", + " if False:\n", + [str(missing_log)], + False, + "log path not found", + ), + ( + "drop_logdir_regular_or_dir_guard", + " if not (args.logdir.is_file() or args.logdir.is_dir()):\n", + " if False:\n", + [str(non_regular)], + True, + None, + ), + ( + "drop_shader_cache_exists_guard", + " if not args.shader_cache.exists():\n", + " if False:\n", + [str(valid_logdir), "--shader-cache", str(missing_cache)], + False, + "shader cache directory not found", + ), + ( + "drop_shader_cache_is_dir_guard", + " if not args.shader_cache.is_dir():\n", + " if False:\n", + [str(valid_logdir), "--shader-cache", str(file_cache)], + False, + None, + ), + ( + "allow_zero_max_items", + " if args.max_items < 1:\n", + " if args.max_items < 0:\n", + [str(valid_logdir), "--max-items", "0"], + False, + None, + ), + ] + + for label, target, replacement, argv, mock_non_regular, broken_fragment in mutations: + with self.subTest(mutation=label): + self.assertEqual(source.count(target), 1, target) + mutated = types.ModuleType(f"triage_run_mut_{label}") + mutated.__file__ = str(TOOL) + sys.modules[mutated.__name__] = mutated + try: + exec(compile(source.replace(target, replacement, 1), str(TOOL), "exec"), mutated.__dict__) + + if mock_non_regular: + orig_exists = Path.exists + orig_is_file = Path.is_file + orig_is_dir = Path.is_dir + with ( + mock.patch.object(Path, "exists", lambda p: True if p == non_regular else orig_exists(p)), + mock.patch.object(Path, "is_file", lambda p: False if p == non_regular else orig_is_file(p)), + mock.patch.object(Path, "is_dir", lambda p: False if p == non_regular else orig_is_dir(p)), + ): + code, _, err = _run_main(mutated, argv) + else: + code, _, err = _run_main(mutated, argv) + finally: + sys.modules.pop(mutated.__name__, None) + + if broken_fragment is None: + self.assertEqual(code, 0, f"mutation {label} unexpectedly failed: {err}") + else: + self.assertNotIn(broken_fragment, err.lower(), f"mutation {label} still emitted {broken_fragment!r}") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/startup/triage_run.py b/tools/startup/triage_run.py index fee383915..427d54cf7 100644 --- a/tools/startup/triage_run.py +++ b/tools/startup/triage_run.py @@ -833,6 +833,20 @@ def _line_stream() -> Iterable[str]: ) +def _validate_args(args: argparse.Namespace) -> None: + if not args.logdir.exists(): + raise FileNotFoundError(f"log path not found: {args.logdir}") + if not (args.logdir.is_file() or args.logdir.is_dir()): + raise ValueError(f"log path must be a regular file or directory: {args.logdir}") + if args.shader_cache is not None: + if not args.shader_cache.exists(): + raise FileNotFoundError(f"shader cache directory not found: {args.shader_cache}") + if not args.shader_cache.is_dir(): + raise NotADirectoryError(f"shader cache path is not a directory: {args.shader_cache}") + if args.max_items < 1: + raise ValueError(f"--max-items must be at least 1, got {args.max_items}") + + def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser( description="Summarize startup logs and optional shader cache into allowlisted Markdown." @@ -851,9 +865,15 @@ def main(argv: list[str] | None = None) -> int: help="Maximum rows per summary table (default: 16)", ) args = parser.parse_args(argv) - print(triage_run(args.logdir, shader_cache=args.shader_cache, max_items=args.max_items)) + try: + _validate_args(args) + report = triage_run(args.logdir, shader_cache=args.shader_cache, max_items=args.max_items) + except (OSError, ValueError) as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + print(report) return 0 if __name__ == "__main__": - sys.exit(main()) + raise SystemExit(main()) From 13f1e4ce2b39db580dfa25ce50dd795ef1061388 Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Thu, 26 Nov 2026 04:48:57 +0200 Subject: [PATCH 088/240] textures: validate archive inputs and lookup keys upfront in texture_descriptors CLI (#2665) --- CMakeLists.txt | 3 + tests/texture_descriptors_cli_check.py | 417 +++++++++++++++++++++++++ tools/texture_descriptors.py | 15 +- 3 files changed, 433 insertions(+), 2 deletions(-) create mode 100644 tests/texture_descriptors_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 38ae556ae..213729fb0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -9423,6 +9423,9 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/bc7_blocks_cli_check.py") add_test(NAME texture_descriptors_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/texture_descriptors_check.py") + add_test(NAME textures_texture_descriptors_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/texture_descriptors_cli_check.py") + set_tests_properties(textures_texture_descriptors_cli_check PROPERTIES TIMEOUT 60) add_test(NAME resource_range_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/resource_ranges_check.py") add_test(NAME ttpf_batch_export COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/texture_descriptors_cli_check.py b/tests/texture_descriptors_cli_check.py new file mode 100644 index 000000000..daac72a8b --- /dev/null +++ b/tests/texture_descriptors_cli_check.py @@ -0,0 +1,417 @@ +#!/usr/bin/env python3 +"""CLI validation, multi-archive lookup, and error-exit suite for tools/texture_descriptors.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +import json +import os +from pathlib import Path +import runpy +import struct +import subprocess +import sys +import tempfile +import unittest +from unittest import mock +import zlib + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "texture_descriptors.py" +sys.path.insert(0, str(ROOT / "tools")) + +from paged_resource import PagedResource # noqa: E402 +import texture_descriptors as td # noqa: E402 + + +def _pack_boundary(stored: int, logical: int, codec: int = 0, trailing_bytes: int = 0) -> bytes: + assert stored % 256 == 0 and logical % 4096 == 0 + stored_units = stored // 256 + logical_pages = logical // 4096 + low = (stored_units & 0x03ffffff) | ((codec & 15) << 26) | ((logical_pages & 3) << 30) + high = ((logical_pages >> 2) & 0xfffff) | ((trailing_bytes & 0xfff) << 20) + return struct.pack(" int: + return ((height - 1) << 14) | (width - 1) + + +def _flags(dxgi_format: int, mip_marker: int) -> int: + return (mip_marker << 24) | (dxgi_format << 3) + + +def _build_synthetic_archive( + *, + keys: tuple[int, ...] = (0x0123456789abcdef, (1 << 64) - 1), + raw_padding: int = 512, +) -> tuple[bytearray, bytes, bytes]: + """Build a synthetic RDS5/ETPF archive with one padded raw range and one zlib range.""" + raw_payload = bytes((i * 17 + 5) % 256 for i in range(4096)) + zlib_plain = b"ZPAGE0_" + b"X" * 4089 + b"ZPAGE1_" + b"Y" * 4089 + zlib_packed = zlib.compress(zlib_plain) + + raw_start = 4352 + raw_end = raw_start + 4096 + raw_padding + zlib_slot = ((len(zlib_packed) + 255) // 256) * 256 + total_size = raw_end + zlib_slot + + archive = bytearray(total_size) + struct.pack_into("<4sIQ", archive, 0, b"RDS5", 4, 16384) + archive[16:24] = _pack_boundary(256, 0, codec=0, trailing_bytes=0) + archive[24:32] = _pack_boundary(raw_start, 4096, codec=0, trailing_bytes=raw_padding) + archive[32:40] = _pack_boundary(raw_end, 8192, codec=8, trailing_bytes=0) + archive[40:48] = _pack_boundary(total_size, 16384, codec=0, trailing_bytes=0) + + records = len(keys) + struct.pack_into("<4sIII", archive, 256, b"ETPF", 0x27a, records, 0) + struct.pack_into("<4I", archive, 272, _shape(64, 32), _flags(71, 3), 1, 0) + if records > 1: + struct.pack_into("<4I", archive, 288, _shape(128, 16), _flags(98, 1), 3, 0) + struct.pack_into(f"<{records}Q", archive, 272 + records * 16, *keys) + + archive[raw_start:raw_start + 4096] = raw_payload + archive[raw_end:raw_end + len(zlib_packed)] = zlib_packed + return archive, raw_payload, zlib_plain + + +def _run_main(argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = td.main(argv) + except SystemExit as exc: + code = exc.code if isinstance(exc.code, int) else 1 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class TextureDescriptorsCliPositiveTests(unittest.TestCase): + def test_direct_main_all_modes_and_boundary_keys(self) -> None: + max_u64 = (1 << 64) - 1 + key_a = 0x0123456789ABCDEF + arch_bytes_1, raw_payload, zlib_plain = _build_synthetic_archive(keys=(0, key_a)) + arch_bytes_2, _, _ = _build_synthetic_archive(keys=(key_a, max_u64)) + + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + arch1 = root / "first.ttpf" + arch2 = root / "nested" / "second.ttpf" + arch2.parent.mkdir() + arch1.write_bytes(arch_bytes_1) + arch2.write_bytes(arch_bytes_2) + + # 1) Inventory mode. + code, out, err = _run_main([str(arch1)]) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertEqual( + json.loads(out), + { + "descriptor_count": 2, + "groups": [ + {"width": 64, "height": 32, "dxgi_format": 71, "mip_marker": 3, "count": 1}, + {"width": 128, "height": 16, "dxgi_format": 98, "mip_marker": 1, "count": 1}, + ], + }, + ) + + # 2) --descriptor mode (0 and 1). + code, out, err = _run_main([str(arch1), "--descriptor", "0"]) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertEqual( + json.loads(out), + { + "descriptor_index": 0, + "width": 64, + "height": 32, + "dxgi_format": 71, + "mip_marker": 3, + "logical_offset": 4096, + }, + ) + code, out, err = _run_main([str(arch1), "--descriptor", "1"]) + self.assertEqual(code, 0, err) + self.assertEqual(json.loads(out)["logical_offset"], 12288) + + # 3) --raw-page-map mode. + code, out, err = _run_main([str(arch1), "--raw-page-map", "0"]) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + rpm = json.loads(out) + self.assertEqual(rpm, {"logical_offset": 4096, "file_offset": 4352}) + self.assertEqual(arch_bytes_1[rpm["file_offset"]:rpm["file_offset"] + 4096], raw_payload) + + # 4) --zlib-segment mode. + code, out, err = _run_main([str(arch1), "--zlib-segment", "1"]) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + zseg = json.loads(out) + self.assertEqual(zseg["segment_logical_offset"], 8192) + self.assertEqual(zseg["page_offset_in_segment"], 4096) + self.assertEqual(zseg["segment"]["codec"], "zlib") + self.assertEqual(zseg["segment"]["size"], 8192) + with arch1.open("rb") as stream: + seg_obj = td.zlib_segment(stream, 1) + decoded = PagedResource(stream, [seg_obj.segment]).read(seg_obj.page_offset_in_segment, 4096) + self.assertEqual(decoded, zlib_plain[4096:]) + + # 5) --lookup-key decimal, 0x/0X hex, boundary 0 and 2^64-1, and absent key. + for raw_key, expected in ( + (str(key_a), [(arch1, 1), (arch2, 0)]), + (f"0x{key_a:x}", [(arch1, 1), (arch2, 0)]), + (f"0X{key_a:X}", [(arch1, 1), (arch2, 0)]), + ("0", [(arch1, 0)]), + ("0x0", [(arch1, 0)]), + (str(max_u64), [(arch2, 1)]), + (hex(max_u64), [(arch2, 1)]), + ("0xdeadbeefcafebabe", []), + ): + with self.subTest(raw_key=raw_key): + code, out, err = _run_main([str(arch1), str(arch2), "--lookup-key", raw_key]) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertEqual( + json.loads(out), + { + "matches": [ + {"archive": str(path), "descriptor_index": index} + for path, index in expected + ] + }, + ) + + def test_sys_argv_and_script_entrypoint_and_subprocess(self) -> None: + arch_bytes, _, _ = _build_synthetic_archive() + with tempfile.TemporaryDirectory() as tmp: + arch = Path(tmp) / "entry.ttpf" + arch.write_bytes(arch_bytes) + cli_argv = [str(TOOL), str(arch), "--descriptor", "0"] + + with mock.patch.object(sys, "argv", cli_argv): + code, out, err = _run_main(None) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertEqual(json.loads(out)["descriptor_index"], 0) + + stdout, stderr = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", cli_argv), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 0) + self.assertEqual(stderr.getvalue(), "") + self.assertEqual(json.loads(stdout.getvalue())["width"], 64) + + proc = _run_subprocess(str(arch), "--lookup-key", "0x0123456789abcdef") + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stderr, "") + self.assertEqual( + json.loads(proc.stdout), + {"matches": [{"archive": str(arch), "descriptor_index": 0}]}, + ) + + +class TextureDescriptorsCliNegativeAndMutationTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_code: int | None = 1, + fragments: tuple[str, ...] = (), + check_subprocess: bool = True, + ) -> str: + code, out, err = _run_main(argv) + if expected_code is None: + self.assertNotEqual(code, 0, (code, err)) + else: + self.assertEqual(code, expected_code, err) + self.assertEqual(out, "") + self.assertTrue(err.strip(), f"expected stderr for {argv!r}") + self.assertNotIn("Traceback", err) + err_lower = err.lower() + for fragment in fragments: + self.assertIn(fragment.lower(), err_lower) + + if check_subprocess: + proc = _run_subprocess(*argv) + if expected_code is None: + self.assertNotEqual(proc.returncode, 0, proc.stderr) + else: + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertTrue(proc.stderr.strip(), f"expected subprocess stderr for {argv!r}") + self.assertNotIn("Traceback", proc.stderr) + sub_lower = proc.stderr.lower() + for fragment in fragments: + self.assertIn(fragment.lower(), sub_lower) + return err + + def test_upfront_archive_existence_and_is_file_before_opening(self) -> None: + arch_bytes, _, _ = _build_synthetic_archive() + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + valid = root / "valid.ttpf" + valid.write_bytes(arch_bytes) + missing = root / "missing.ttpf" + dir_arch = root / "dir_arch" + dir_arch.mkdir() + + # Single-archive missing & directory checks never open files. + for bad_path, frag in ( + (missing, f"{missing}: archive file not found"), + (dir_arch, f"{dir_arch}: archive path is not a regular file"), + ): + with self.subTest(bad_path=bad_path): + with mock.patch.object(Path, "open") as open_mock: + self._assert_clean_failure( + [str(bad_path)], + expected_code=1, + fragments=(frag,), + check_subprocess=False, + ) + open_mock.assert_not_called() + self._assert_clean_failure([str(bad_path)], expected_code=1, fragments=(frag,)) + + # Multi-archive --lookup-key validates ALL archives before opening the first! + for argv, frag in ( + ([str(valid), str(missing), "--lookup-key", "0"], f"{missing}: archive file not found"), + ([str(valid), str(dir_arch), "--lookup-key", "0"], f"{dir_arch}: archive path is not a regular file"), + ): + with self.subTest(argv=argv): + with mock.patch.object(Path, "open") as open_mock: + self._assert_clean_failure( + argv, + expected_code=1, + fragments=(frag,), + check_subprocess=False, + ) + open_mock.assert_not_called() + self._assert_clean_failure(argv, expected_code=1, fragments=(frag,)) + + def test_lookup_key_range_validated_upfront_before_opening(self) -> None: + arch_bytes, _, _ = _build_synthetic_archive() + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + valid = root / "valid.ttpf" + valid.write_bytes(arch_bytes) + + for argv_tail, frag in ( + (["--lookup-key", "-1"], "unsigned 64-bit integer"), + (["--lookup-key=-0x1"], "invalid literal"), + (["--lookup-key", str(1 << 64)], "unsigned 64-bit integer"), + (["--lookup-key", hex(1 << 64)], "unsigned 64-bit integer"), + (["--lookup-key", "not_a_key"], "invalid literal"), + (["--lookup-key", ""], "invalid literal"), + ): + with self.subTest(argv_tail=argv_tail): + with mock.patch.object(Path, "open") as open_mock: + self._assert_clean_failure( + [str(valid), *argv_tail], + expected_code=1, + fragments=(f"{valid}:", frag), + check_subprocess=False, + ) + open_mock.assert_not_called() + self._assert_clean_failure( + [str(valid), *argv_tail], + expected_code=1, + fragments=(f"{valid}:", frag), + ) + + def test_negative_descriptor_index_validated_before_file_checks(self) -> None: + arch_bytes, _, _ = _build_synthetic_archive() + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + valid = root / "valid.ttpf" + valid.write_bytes(arch_bytes) + missing = root / "missing.ttpf" + + for target in (valid, missing): + for flag in ("--descriptor", "--raw-page-map", "--zlib-segment"): + with self.subTest(target=target.name, flag=flag): + with mock.patch.object(Path, "open") as open_mock: + self._assert_clean_failure( + [str(target), flag, "-1"], + expected_code=1, + fragments=(f"{target}:", "nonnegative"), + check_subprocess=False, + ) + open_mock.assert_not_called() + + def test_truncated_corrupt_zlib_and_duplicate_archive_failures(self) -> None: + arch_bytes, _, _ = _build_synthetic_archive() + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + valid = root / "valid.ttpf" + valid.write_bytes(arch_bytes) + + empty = root / "empty.ttpf" + empty.write_bytes(b"") + self._assert_clean_failure([str(empty)], expected_code=1, fragments=(f"{empty}:", "Truncated RDS5 header")) + + short = root / "short.ttpf" + short.write_bytes(b"RDS5" + bytes(12)) + self._assert_clean_failure([str(short)], expected_code=1, fragments=(f"{short}:", "Truncated RDS5 header")) + + corrupt_zlib = root / "corrupt_zlib.ttpf" + corrupt = bytearray(arch_bytes) + corrupt[4352 + 4096 + 512] ^= 0xFF + corrupt_zlib.write_bytes(corrupt) + self._assert_clean_failure( + [str(corrupt_zlib), "--zlib-segment", "1"], + expected_code=1, + fragments=(f"{corrupt_zlib}:", "Invalid zlib stream"), + ) + + # Duplicate archive input: identical path and hardlink alias. + alias = root / "alias.ttpf" + os.link(valid, alias) + for dup_pair in ([str(valid), str(valid)], [str(valid), str(alias)]): + with self.subTest(dup_pair=dup_pair): + self._assert_clean_failure( + [*dup_pair, "--lookup-key", "0x0123456789abcdef"], + expected_code=1, + fragments=(f"{dup_pair[1]}:", "Duplicate archive input"), + ) + + def test_argparse_errors_py314_safe(self) -> None: + arch_bytes, _, _ = _build_synthetic_archive() + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + arch1 = root / "one.ttpf" + arch2 = root / "two.ttpf" + arch1.write_bytes(arch_bytes) + arch2.write_bytes(arch_bytes) + + for argv, frags in ( + ([], ("required",)), + ([str(arch1), "--bogus-flag"], ("unrecognized",)), + ([str(arch1), "--descriptor", "bad"], ("invalid",)), + ([str(arch1), "--descriptor"], ("expected one argument",)), + ([str(arch1), "--descriptor", "0", "--lookup-key", "0"], ("not allowed with argument",)), + ([str(arch1), str(arch2)], ("--lookup-key",)), + ): + with self.subTest(argv=argv): + self._assert_clean_failure( + argv, + expected_code=None, + fragments=frags, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/texture_descriptors.py b/tools/texture_descriptors.py index e9efb974b..7dcc0ede2 100644 --- a/tools/texture_descriptors.py +++ b/tools/texture_descriptors.py @@ -229,13 +229,26 @@ def main(argv: list[str] | None = None) -> int: mode.add_argument("--lookup-key", metavar="KEY", help="Find all descriptor indices for a decimal or 0x-prefixed 64-bit texture key") args = parser.parse_args(argv) + if args.lookup_key is None and len(args.archives) != 1: + parser.error("Multiple archives require --lookup-key") archive = args.archives[0] try: for index in (args.descriptor, args.raw_page_map, args.zlib_segment): if index is not None and index < 0: raise ValueError("Descriptor index outside the ETPF table (must be nonnegative)") + key: int | None = None if args.lookup_key is not None: key = int(args.lookup_key, 16 if args.lookup_key.lower().startswith("0x") else 10) + if not 0 <= key < 1 << 64: + raise ValueError("Texture key must be an unsigned 64-bit integer") + for candidate in args.archives: + archive = candidate + if not candidate.exists(): + raise FileNotFoundError("Archive file not found") + if not candidate.is_file(): + raise ValueError("Archive path is not a regular file") + archive = args.archives[0] + if key is not None: seen: set[tuple[int, int]] = set() matches: list[dict[str, str | int]] = [] for archive in args.archives: @@ -250,8 +263,6 @@ def main(argv: list[str] | None = None) -> int: json.dump({"matches": matches}, sys.stdout, indent=2) print() else: - if len(args.archives) != 1: - parser.error("Multiple archives require --lookup-key") with archive.open("rb") as file: if args.descriptor is not None: print(json.dumps(describe_descriptor(file, args.descriptor), indent=2)) From 73621923b7e3a6ac1ae03281445320c1217fc23a Mon Sep 17 00:00:00 2001 From: yjs <1245206726@qq.com> Date: Thu, 26 Nov 2026 10:50:17 +0800 Subject: [PATCH 089/240] startup: allow MRT, depth, and depth-only targets in translated ExecuteIndirect (#2417) * startup: allow MRT, depth, and depth-only targets in translated ExecuteIndirect * tests: verify depth-only indirect draw rasterization with occlusion query --- CMakeLists.txt | 2 + docs/experiments.md | 15 +- src/startup_stubs/d3d12_draw.inl | 17 +- src/startup_stubs/d3d12_xs_device.cpp | 19 +- tests/startup_indirect_draw_indexed.cpp | 236 +++++++++++++++++++++++- 5 files changed, 278 insertions(+), 11 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 213729fb0..6f333cbda 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1542,6 +1542,7 @@ foreach(backend IN ITEMS warp hardware) add_test(NAME startup_indirect_draw_${backend} COMMAND startup_indirect_draw_indexed ${backend} draw) add_test(NAME startup_indirect_translated_draw_${backend} COMMAND startup_indirect_draw_indexed ${backend} translated) add_test(NAME startup_indirect_translated_refusal_census_${backend} COMMAND startup_indirect_draw_indexed ${backend} translated-refusal-census) + add_test(NAME startup_indirect_translated_targets_${backend} COMMAND startup_indirect_draw_indexed ${backend} translated-targets) add_test(NAME startup_indirect_other_refusal_census_${backend} COMMAND startup_indirect_draw_indexed ${backend} indirect-other-refusal-census) add_test(NAME startup_indirect_copy_provenance_${backend} COMMAND startup_indirect_draw_indexed ${backend} copy-provenance) add_test(NAME startup_indirect_copy_provenance_off_${backend} COMMAND startup_indirect_draw_indexed ${backend} copy-provenance-off) @@ -1566,6 +1567,7 @@ foreach(backend IN ITEMS warp hardware) startup_indirect_mesh_amplified_${backend} PROPERTIES TIMEOUT 30 SKIP_RETURN_CODE 77) set_tests_properties(startup_indirect_translated_draw_${backend} startup_indirect_translated_refusal_census_${backend} + startup_indirect_translated_targets_${backend} startup_indirect_other_refusal_census_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) set_tests_properties(startup_indirect_copy_provenance_${backend} startup_indirect_copy_provenance_off_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) diff --git a/docs/experiments.md b/docs/experiments.md index 021a45447..09d88a0f4 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -84,8 +84,13 @@ ctest --preset dev --no-tests=error -R '^startup_present_producer_(warp|hardware ### Translated indirect triangles `X2W_TRANSLATED_INDIRECT_DRAW=1` lets a slot 57 cached translation record one non-indexed -`ExecuteIndirect` Draw on a direct list with triangle-list topology, one single-sample colour -target, an explicit viewport and scissor, and the root signature used to create the guest pipeline. +`ExecuteIndirect` Draw on a direct list with triangle-list topology, single-sample bound colour +and/or depth-stencil targets (up to 8 colour targets, colour plus depth-stencil, or depth-only), +an explicit viewport and scissor, and the root signature used to create the guest pipeline. +Sampled texture bindings must not alias any bound colour target or writable depth view, and a +translated pipeline with depth or stencil writes is refused against a read-only depth view +(`read_only_depth_write`). Non-translated desktop graphics pipelines keep the single colour-target +requirement without a depth view. The translated path binds its usual pipeline, root and sampled textures, then forwards the placed desktop argument buffer and offset. Its producer supplies legal D3D12 draw arguments. The shim checks the placed buffer range without reading the draw fields or limiting the GPU-generated vertex count. @@ -101,7 +106,7 @@ same resource that contains the indirect arguments, and copied placements with u the accepted resource directly as a desktop raw SRV and uses its recorded stride for the shader entry. Run `cmake --build --preset release --target startup_indirect_draw_indexed` and -`ctest --preset release -j1 --no-tests=error -R '^startup_indirect_translated_draw_' -V`. +`ctest --preset release -j1 --no-tests=error -R '^startup_indirect_translated_(draw|targets)_' -V`. The fixture compiles source-built desktop shaders and installs their translation-cache manifest. A compute writer records one triangle at a nonzero offset in a placed GPU buffer with separate title backing. A fenced readback compares the argument, guard words and every colour pixel. @@ -110,7 +115,9 @@ binding the wrong root, using a short argument range or using a shader that read leaves the target clear. A second compute writer supplies distinguishing colours to a table buffer. The table's nonzero offset and stride select the second colour, the short view reads zero, and a non-aliased placement is refused. A raw descriptor over a recording-owned upload page reads the -same colour and refuses a view that crosses its allocation. +same colour and refuses a view that crosses its allocation. `startup_indirect_translated_targets_{warp,hardware}` +additionally checks two-target MRT, colour plus depth-stencil, depth-only (zero colour targets with a +depth view), refusal of zero attachments, and refusal of a sampled texture aliasing render target 1. ### Index views backed by a recording upload diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index a8d84d8e0..c45c49b9f 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -1691,6 +1691,7 @@ constexpr const char* sampled_texture_unbindable = "sampled_texture_unbindable"; constexpr const char* incomplete_vertex_stream = "incomplete_vertex_stream"; constexpr const char* incomplete_table_buffer = "incomplete_table_buffer"; constexpr const char* indexed_validation_failed = "indexed_validation_failed"; +constexpr const char* read_only_depth_write = "read_only_depth_write"; } // namespace indirect_refusal_code struct TranslatedIndirectDraw { @@ -2141,6 +2142,14 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI ReleaseSRWLockExclusive(&draw_lock); return false; } + if (bound->has_depth_stencil && pass.dsv_format != DXGI_FORMAT_UNKNOWN && !pass.depth_view_writable && + ((bound->depth_stencil.DepthEnable && bound->depth_stencil.DepthWriteMask != D3D12_DEPTH_WRITE_MASK_ZERO) || + (bound->depth_stencil.StencilEnable && bound->depth_stencil.StencilWriteMask != 0))) { + indirect->set_refusal("translated draw writes depth or stencil to a read-only depth view", + indirect_refusal_code::read_only_depth_write); + ReleaseSRWLockExclusive(&draw_lock); + return false; + } } ID3D12PipelineState* pipeline = ensure_draw_heap(self->own().list_device) ? pipeline_for(*bound, *tr, pass, indexed_rect) : nullptr; if (indirect && indexed_rect && !pipeline) { @@ -2266,7 +2275,13 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI if (srv.kind == 2) desc.Texture2DArray.ArraySize = 1; } } - if (indirect && (!texture || record.slot != 18 || texture == pass.target0)) { + const auto aliases_writable_target = [&](ID3D12Resource* tex) { + if (!tex) return false; + for (UINT t = 0; t < pass.target_count; ++t) + if (pass.bound_targets[t] == tex) return true; + return pass.bound_depth == tex && pass.depth_view_writable; + }; + if (indirect && (!texture || record.slot != 18 || aliases_writable_target(texture))) { indirect->set_refusal("translated draw requires a matching sampled texture distinct from the target", indirect_refusal_code::sampled_texture_mismatch); ReleaseSRWLockExclusive(&draw_lock); diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index ae3cd6be9..a6e66c854 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -2501,6 +2501,8 @@ struct Pass { UINT stencil_reference = 0; // last guest OMSetStencilRef on this recording UINT target_count = 0; ID3D12Resource* target0 = nullptr; // desktop resource of render target 0 (for per-draw dumps) + ID3D12Resource* bound_targets[8]{}; + ID3D12Resource* bound_depth = nullptr; ID3D12Resource* trace_targets[8]{}; ID3D12Resource* trace_depth = nullptr; ID3D12Resource* bound_targets[8]{}; // the last accepted bind: targets [0, target_count) and the depth texture @@ -2997,6 +2999,17 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, if ((pass.constant_words_bound[i] & mask) != mask) return refuse("cached mesh root constants are incomplete", indirect_graphics_pipeline); } + } else if (translated) { + if (!pass.targets_bound || (!pass.target_count && pass.dsv_format == DXGI_FORMAT_UNKNOWN) || + !pass.viewport_set || !pass.scissor_set) { + const char* code = + (!pass.targets_bound || (!pass.target_count && pass.dsv_format == DXGI_FORMAT_UNKNOWN)) + ? indirect_other_refusal_code::no_render_target + : indirect_other_refusal_code::missing_viewport_or_scissor; + return refuse("translated indirect draw requires bound target or depth view, viewport and scissor", indirect_other, code); + } + if (!pass.targets_single_sample) + return refuse("draw requires single-sample targets", indirect_other, indirect_other_refusal_code::multisample_target); } else if (!pass.targets_bound || pass.target_count != 1 || !pass.target0 || (!translated && pass.target_formats[0] != pass.indirect_graphics.target_format) || pass.dsv_format != DXGI_FORMAT_UNKNOWN || !pass.viewport_set || !pass.scissor_set) { @@ -3013,7 +3026,7 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, return refuse("indirect rectangle list requires a non-indexed draw", indirect_other, indirect_other_refusal_code::rect_list_indexed); if (!mesh && !rect_list && pass.topology != D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST) return refuse("indirect draw requires triangle-list or rectangle-list topology", indirect_other, indirect_other_refusal_code::unsupported_topology); - if (!pass.indirect_graphics.cached_mesh) { + if (!pass.indirect_graphics.cached_mesh && !translated) { const auto samples = pass.target0->GetDesc().SampleDesc; if (samples.Count != 1 || samples.Quality) return refuse("draw requires a single-sample render target", indirect_other, indirect_other_refusal_code::multisample_target); @@ -3487,6 +3500,8 @@ void __stdcall list_targets(Wrapper* self, UINT count, const D3D12_CPU_DESCRIPTO pass.depth_view_writable = false; pass.target_count = 0; pass.target0 = nullptr; + std::fill_n(pass.bound_targets, 8, nullptr); + pass.bound_depth = nullptr; pass.dsv_format = DXGI_FORMAT_UNKNOWN; if (!list) return; static LONG refused, unresolved_logged; @@ -3569,6 +3584,8 @@ void __stdcall list_targets(Wrapper* self, UINT count, const D3D12_CPU_DESCRIPTO } } if (!count && !dsv_ptr) return; + std::copy_n(targets, 8, pass.bound_targets); + pass.bound_depth = dsv_target; if (red_producers().enabled()) { std::copy_n(targets, 8, pass.trace_targets); pass.trace_depth = dsv_target; diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index 234eb8c3b..cece4f068 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -602,7 +602,7 @@ ComPtr make_gpu_table_buffer(ID3D12Device* guest, UINT64 bytes) struct TranslatedDrawFixture { TranslatedDrawFixture(ID3D12Device* guest, std::uint32_t colour, ID3D12Device* desktop = nullptr, - bool short_view = false, bool copied = false, bool replay = false) + bool short_view = false, bool copied = false, bool replay = false, bool allow_rt = false) : wrong_root(create_root(guest, {0, nullptr, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE})), backing(VirtualAlloc(nullptr, 65536, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)) { @@ -613,8 +613,8 @@ struct TranslatedDrawFixture { const D3D12_RESOURCE_DESC desc = copied ? D3D12_RESOURCE_DESC{D3D12_RESOURCE_DIMENSION_BUFFER, 0, replay ? replay_copy_bytes : 64u, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS} : - D3D12_RESOURCE_DESC{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, 1, 1, 1, 1, format, {1, 0}, - D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE}; + D3D12_RESOURCE_DESC{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, allow_rt ? width : 1u, allow_rt ? height : 1u, 1, 1, format, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, allow_rt ? D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET : D3D12_RESOURCE_FLAG_NONE}; auto* address = static_cast(backing.get()) + (copied ? 16 : 0); std::memcpy(address + (replay ? 4 : copied ? 32 : 0), &colour, sizeof(colour)); using Place = HRESULT (WINAPI*)(IUnknown*, void*, const D3D12_RESOURCE_DESC*, UINT, const void*, REFIID, void**); @@ -1337,6 +1337,207 @@ bool check_translated_refusal_census(const std::wstring& log_path) return true; } +bool check_translated_targets(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_root, + ID3D12PipelineState* writer, ID3D12RootSignature* title_root, IUnknown* pso, + ID3D12CommandSignature* signature, const TranslatedDrawFixture& red_binding) +{ + const TranslatedDrawFixture alias_binding(guest, red, nullptr, false, false, false, true); + enum class Mode { mrt_two, color_and_dsv, depth_only, no_attachments, alias_rtv1 }; + const auto run_mode = [&](Mode mode, const char* label) -> bool { + const auto& binding = mode == Mode::alias_rtv1 ? alias_binding : red_binding; + PlacedBuffer arguments(device, guest, static_cast(sizeof(initial)), D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + Words initial_words = initial; + initial_words[1 + command_stride(DrawKind::vertices) / sizeof(std::uint32_t)] = 0x3c3c3c3c; + const auto upload = make_buffer(device, sizeof(initial_words), D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + void* memory = nullptr; + const D3D12_RANGE untouched{0, 0}; + check(upload->Map(0, &untouched, &memory), "map targets upload"); + std::memcpy(memory, initial_words.data(), sizeof(initial_words)); + upload->Unmap(0, nullptr); + + const D3D12_RESOURCE_DESC color_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, width, height, 1, 1, format, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET}; + const D3D12_RESOURCE_DESC depth_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, width, height, 1, 1, DXGI_FORMAT_D16_UNORM, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL}; + constexpr float clear[]{0, 0, 0, 1}; + D3D12_CLEAR_VALUE color_clear{format, {0, 0, 0, 1}}; + D3D12_CLEAR_VALUE depth_clear{DXGI_FORMAT_D16_UNORM, {0, 0, 0, 1}}; + depth_clear.DepthStencil = {1.0f, 0}; + + const auto color0 = resource(device, color_desc, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, &color_clear); + const auto color1 = resource(device, color_desc, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, &color_clear); + const auto depth = resource(device, depth_desc, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, &depth_clear); + + const D3D12_DESCRIPTOR_HEAP_DESC rtv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 2, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + ComPtr rtv_heap; + check(device->CreateDescriptorHeap(&rtv_heap_desc, IID_PPV_ARGS(&rtv_heap)), "create targets rtv heap"); + const UINT rtv_inc = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV); + D3D12_CPU_DESCRIPTOR_HANDLE rtvs[2]{ + rtv_heap->GetCPUDescriptorHandleForHeapStart(), + {rtv_heap->GetCPUDescriptorHandleForHeapStart().ptr + rtv_inc}}; + guest->CreateRenderTargetView(color0.Get(), nullptr, rtvs[0]); + ID3D12Resource* rtv1_res = mode == Mode::alias_rtv1 ? binding.sampled.Get() : color1.Get(); + guest->CreateRenderTargetView(rtv1_res, nullptr, rtvs[1]); + + const D3D12_DESCRIPTOR_HEAP_DESC dsv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + ComPtr dsv_heap; + check(guest->CreateDescriptorHeap(&dsv_heap_desc, IID_PPV_ARGS(&dsv_heap)), "create targets dsv heap"); + using GetCpu = UINT64(WINAPI*)(IUnknown*, void*); + D3D12_CPU_DESCRIPTOR_HANDLE guest_dsv{slot(dsv_heap.Get(), 9)(dsv_heap.Get(), nullptr)}; + const D3D12_CPU_DESCRIPTOR_HANDLE native_dsv = + native_object(device, guest, dsv_heap.Get())->GetCPUDescriptorHandleForHeapStart(); + D3D12_DEPTH_STENCIL_VIEW_DESC dsv_desc{}; + dsv_desc.Format = DXGI_FORMAT_D16_UNORM; + dsv_desc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D; + guest->CreateDepthStencilView(depth.Get(), &dsv_desc, guest_dsv); + + ComPtr allocator; + check(guest->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator)), "create targets allocator"); + auto wrapped_list = begin_guest_list(guest, allocator.Get()); + auto* wrapped = wrapped_list.Get(); + const auto native_list = native_object(device, guest, wrapped); + auto* list = native_list.Get(); + + transition(list, arguments.native.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST); + list->CopyBufferRegion(arguments.native.Get(), 0, upload.Get(), 0, sizeof(initial_words)); + transition(list, arguments.native.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + list->SetPipelineState(writer); + list->SetComputeRootSignature(writer_root); + list->SetComputeRootUnorderedAccessView(0, arguments.native->GetGPUVirtualAddress()); + list->Dispatch(1, 1, 1); + transition(list, arguments.native.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COMMON); + + using Bind = void (WINAPI*)(IUnknown*, IUnknown*); + using Clear = void (WINAPI*)(IUnknown*, SIZE_T, const float*, UINT, const D3D12_RECT*); + using Targets = void (WINAPI*)(IUnknown*, UINT, const D3D12_CPU_DESCRIPTOR_HANDLE*, BOOL, const D3D12_CPU_DESCRIPTOR_HANDLE*); + using Topology = void (WINAPI*)(IUnknown*, D3D12_PRIMITIVE_TOPOLOGY); + using Viewport = void (WINAPI*)(IUnknown*, UINT, const D3D12_VIEWPORT*); + using Scissor = void (WINAPI*)(IUnknown*, UINT, const D3D12_RECT*); + using Heaps = void (WINAPI*)(IUnknown*, UINT, ID3D12DescriptorHeap* const*); + using Table = void (WINAPI*)(IUnknown*, UINT, UINT64); + using Execute = void (WINAPI*)(IUnknown*, IUnknown*, UINT, IUnknown*, UINT64, IUnknown*, UINT64); + + slot(wrapped, 52)(wrapped, rtvs[0].ptr, clear, 0, nullptr); + if (mode == Mode::mrt_two) slot(wrapped, 52)(wrapped, rtvs[1].ptr, clear, 0, nullptr); + if (mode == Mode::mrt_two || mode == Mode::alias_rtv1) + slot(wrapped, 50)(wrapped, 2, rtvs, FALSE, nullptr); + else if (mode == Mode::color_and_dsv) { + slot(wrapped, 50)(wrapped, 1, rtvs, FALSE, &guest_dsv); + list->ClearDepthStencilView(native_dsv, D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, nullptr); + } else if (mode == Mode::depth_only) { + slot(wrapped, 50)(wrapped, 0, nullptr, FALSE, &guest_dsv); + list->ClearDepthStencilView(native_dsv, D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, nullptr); + } else { + slot(wrapped, 50)(wrapped, 0, nullptr, FALSE, nullptr); + } + + ComPtr query_heap; + ComPtr query_readback; + if (mode == Mode::depth_only) { + const D3D12_QUERY_HEAP_DESC query_desc{D3D12_QUERY_HEAP_TYPE_OCCLUSION, 1, 0}; + check(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(&query_heap)), "create depth-only occlusion query heap"); + query_readback = make_buffer(device, sizeof(std::uint64_t), D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + } + + const D3D12_VIEWPORT viewport{0, 0, width, height, 0, 1}; + const D3D12_RECT scissor{0, 0, width, height}; + slot(wrapped, 25)(wrapped, pso); + slot(wrapped, 34)(wrapped, title_root); + ID3D12DescriptorHeap* heaps[]{binding.heap.Get()}; + slot(wrapped, 32)(wrapped, 1, heaps); + slot
(wrapped, 36)(wrapped, 0, binding.gpu); + slot(wrapped, 20)(wrapped, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + slot(wrapped, 21)(wrapped, 1, &viewport); + slot(wrapped, 22)(wrapped, 1, &scissor); + if (mode == Mode::depth_only) list->BeginQuery(query_heap.Get(), D3D12_QUERY_TYPE_OCCLUSION, 0); + slot(wrapped, 61)(wrapped, signature, 1, arguments.wrapped.Get(), argument_offset, nullptr, 0); + if (mode == Mode::depth_only) { + list->EndQuery(query_heap.Get(), D3D12_QUERY_TYPE_OCCLUSION, 0); + list->ResolveQueryData(query_heap.Get(), D3D12_QUERY_TYPE_OCCLUSION, 0, 1, query_readback.Get(), 0); + } + check(slot(wrapped, 9)(wrapped), "close targets list"); + + const D3D12_COMMAND_QUEUE_DESC queue_desc{}; + ComPtr guest_queue; + check(guest->CreateCommandQueue(&queue_desc, __uuidof(ID3D12CommandQueue), reinterpret_cast(guest_queue.GetAddressOf())), + "create targets queue"); + IUnknown* lists[]{wrapped}; + slot(guest_queue.Get(), 10)(guest_queue.Get(), 1, lists); + const auto native_queue = native_object(device, guest, guest_queue.Get()); + ComPtr fence; + check(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)), "create targets fence"); + check(native_queue->Signal(fence.Get(), 1), "signal targets fence"); + HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr); + check(fence->SetEventOnCompletion(1, done), "set targets fence event"); + WaitForSingleObject(done, INFINITE); + CloseHandle(done); + + if (mode == Mode::depth_only) { + std::uint64_t samples = 0; + const D3D12_RANGE query_range{0, sizeof(samples)}; + check(query_readback->Map(0, &query_range, &memory), "map depth-only occlusion query"); + std::memcpy(&samples, memory, sizeof(samples)); + query_readback->Unmap(0, &untouched); + const auto expected_samples = static_cast(width) * height; + if (samples != expected_samples) { + std::fprintf(stderr, "%s: expected %llu rasterized samples, got %llu\n", + label, static_cast(expected_samples), + static_cast(samples)); + return false; + } + } + + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; + UINT64 bytes = 0; + device->GetCopyableFootprints(&color_desc, 0, 1, 0, &footprint, nullptr, nullptr, &bytes); + const auto read_pixels = [&](ID3D12Resource* target, std::uint32_t expected_colour, const char* which) -> bool { + const auto readback = make_buffer(device, bytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + ComputeCommands copy(device, nullptr, D3D12_COMMAND_LIST_TYPE_DIRECT); + transition(copy.list.Get(), target, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); + D3D12_TEXTURE_COPY_LOCATION src{target, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {}}; + D3D12_TEXTURE_COPY_LOCATION dst{readback.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, {}}; + dst.PlacedFootprint = footprint; + copy.list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + copy.submit_and_wait(device); + const D3D12_RANGE range{0, static_cast(bytes)}; + check(readback->Map(0, &range, &memory), "map targets readback"); + bool ok = true; + for (UINT y = 0; y < height; ++y) + for (UINT x = 0; x < width; ++x) { + std::uint32_t actual = 0; + std::memcpy(&actual, static_cast(memory) + y * footprint.Footprint.RowPitch + x * sizeof(actual), sizeof(actual)); + if (actual != expected_colour) { + std::fprintf(stderr, "%s (%s) pixel (%u,%u): got 0x%08x, expected 0x%08x\n", + label, which, x, y, actual, expected_colour); + ok = false; + } + } + readback->Unmap(0, &untouched); + return ok; + }; + const bool expect_draw = mode == Mode::mrt_two || mode == Mode::color_and_dsv; + if (!read_pixels(color0.Get(), expect_draw ? red : black, "rtv0")) return false; + if (mode == Mode::mrt_two && !read_pixels(color1.Get(), black, "rtv1")) return false; + std::printf("%s: OK\n", label); + return true; + }; + const bool ok = + run_mode(Mode::mrt_two, "translated indirect MRT (2 color targets)") && + run_mode(Mode::color_and_dsv, "translated indirect color + DSV") && + run_mode(Mode::depth_only, "translated indirect depth-only (0 RTV + DSV)") && + run_mode(Mode::no_attachments, "translated indirect refuses 0 RTV + no DSV") && + run_mode(Mode::alias_rtv1, "translated indirect refuses sampled texture aliasing RTV 1"); + if (!ok) return false; + const std::size_t needed = x2w_d3d12_census_report(nullptr, 0); + std::string report(needed + 1, '\0'); + x2w_d3d12_census_report(report.data(), report.size()); + if (report.find("reason=sampled_texture_mismatch calls=1") == std::string::npos) { + std::fprintf(stderr, "expected sampled_texture_mismatch refusal for RTV 1 alias in census report:\n%s\n", report.c_str()); + return false; + } + return true; +} + bool check_indirect_other_refusal_census(const std::wstring& log_path) { const std::size_t needed = x2w_d3d12_census_report(nullptr, 0); @@ -1408,7 +1609,7 @@ bool check_indirect_other_refusal_census(const std::wstring& log_path) std::string log_line; bool saw_vp_log = false, saw_arg_log = false, saw_multi_log = false; const std::string want_vp = "x2w-render ExecuteIndirect refused, key " + parsed[0].key + - " [missing_viewport_or_scissor]: indirect graphics requires one matching target, viewport and scissor"; + " [missing_viewport_or_scissor]: translated indirect draw requires bound target or depth view, viewport and scissor"; const std::string want_arg = "x2w-render ExecuteIndirect refused, key " + parsed[0].key + " [argument_outside_placed_buffer]: argument record is outside a unique placed buffer"; const std::string want_multi = "x2w-render ExecuteIndirect refused, key " + zero_key + @@ -1526,6 +1727,7 @@ int main(int argc, char** argv) try const bool copy_off = argc == 3 && std::strcmp(argv[2], "copy-provenance-off") == 0; const bool refusal_census_control = argc == 3 && std::strcmp(argv[2], "translated-refusal-census-control") == 0; const bool refusal_census = refusal_census_control || (argc == 3 && std::strcmp(argv[2], "translated-refusal-census") == 0); + const bool translated_targets = argc == 3 && std::strcmp(argv[2], "translated-targets") == 0; const bool other_refusal_census_control = argc == 3 && std::strcmp(argv[2], "indirect-other-refusal-census-control") == 0; const bool other_refusal_census = other_refusal_census_control || (argc == 3 && std::strcmp(argv[2], "indirect-other-refusal-census") == 0); const bool upload_index = argc == 3 && std::strcmp(argv[2], "translated-indexed-upload") == 0; @@ -1533,7 +1735,7 @@ int main(int argc, char** argv) try const bool alias_disabled = argc == 3 && std::strcmp(argv[2], "translated-indexed-alias-off") == 0; const bool alias_index = alias_disabled || (argc == 3 && std::strcmp(argv[2], "translated-indexed-alias") == 0); const bool translated_indexed = alias_index || upload_index || rect || (argc == 3 && std::strcmp(argv[2], "translated-indexed") == 0); - const bool translated = copy_on || copy_off || refusal_census || other_refusal_census || translated_indexed || (argc == 3 && std::strcmp(argv[2], "translated") == 0); + const bool translated = copy_on || copy_off || refusal_census || other_refusal_census || translated_targets || translated_indexed || (argc == 3 && std::strcmp(argv[2], "translated") == 0); // "count-control" is the negative control: it expects one forwarded call too many. const bool count_control = argc == 3 && std::strcmp(argv[2], "count-control") == 0; if ((translated && !translated_indexed) || (argc == 3 && std::strcmp(argv[2], "draw") == 0)) kind = DrawKind::vertices; @@ -2008,6 +2210,30 @@ int main(int argc, char** argv) try DeleteFileW(log_path.c_str()); return ok && (!info || !info->GetNumStoredMessages()) ? 0 : 1; } + if (translated_targets) { + const bool ok = check_translated_targets(device.Get(), guest.Get(), writer.Get(), producer.Get(), + title_root.Get(), pso.Get(), signature.Get(), red_binding); + std::filesystem::remove_all(cache); + bool debug_ok = true; + if (info) { + for (UINT64 i = 0; i < info->GetNumStoredMessages(); ++i) { + SIZE_T bytes = 0; + info->GetMessage(i, nullptr, &bytes); + std::vector storage(bytes); + auto* msg = reinterpret_cast(storage.data()); + info->GetMessage(i, msg, &bytes); + // Message 679 (PS expects RTV0 with NumRenderTargets=0) is an expected benign warning when + // reusing the colour-writing pixel shader for the depth-only pass. + if (msg->Severity <= D3D12_MESSAGE_SEVERITY_ERROR || + (msg->Severity == D3D12_MESSAGE_SEVERITY_WARNING && msg->ID != 679)) { + std::fprintf(stderr, "D3D12 debug message %u (sev %d): %s\n", + static_cast(msg->ID), static_cast(msg->Severity), msg->pDescription); + debug_ok = false; + } + } + } + return ok && debug_ok ? 0 : 1; + } if (other_refusal_census) { bool ok = verify(producer.Get(), false, Refusal::none, "other census warm up translated pipeline key") && verify(producer.Get(), false, Refusal::missing_viewport, "other census key1 missing_viewport_or_scissor #1") && From 05a457aa2913cfd273cc2f17897c29b39d2000c6 Mon Sep 17 00:00:00 2001 From: Louis <59670693+louisdibiasi@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:50:33 -0500 Subject: [PATCH 090/240] runtime: handle save staging allocation failure (#2697) * runtime: handle save staging allocation failure * Report allocation failure while preparing a save action --------- Co-authored-by: Royoo <3230853833@qq.com> --- src/startup_stubs/runtime_proxy.cpp | 29 +++++++++++++++------------ src/startup_stubs/save_store.h | 10 ++++++++-- tests/startup_gamesave_submit.cpp | 31 +++++++++++++++++++++++++++++ 3 files changed, 55 insertions(+), 15 deletions(-) diff --git a/src/startup_stubs/runtime_proxy.cpp b/src/startup_stubs/runtime_proxy.cpp index 1f0e7890a..eac6941c8 100644 --- a/src/startup_stubs/runtime_proxy.cpp +++ b/src/startup_stubs/runtime_proxy.cpp @@ -1202,23 +1202,26 @@ bool save_call(int slot, u64* args, u64* result) // reaches the disk before the update is submitted, and an update closed without a submit // leaves the save as it was. Only an open update is acted on; any other argument is // accepted and dropped as before. - std::string blob; - if (update_container(args[0]).empty() || !read_save_name(args[1], blob)) return true; x2w_save::Action action; - action.remove = slot == 26; - action.blob = blob; - if (!x2w_save::valid_name(blob)) { - *result = e_invalidarg; - return true; - } - if (!action.remove) { - const std::size_t size = static_cast(args[3]); - if (size > x2w_save::max_blob_bytes || (size && x2w_local::probe_readable(static_cast(args[2]), size) != size)) { + try { + if (update_container(args[0]).empty() || !read_save_name(args[1], action.blob)) return true; + action.remove = slot == 26; + if (!x2w_save::valid_name(action.blob)) { *result = e_invalidarg; return true; } - const auto* bytes = reinterpret_cast(args[2]); - if (size) action.data.assign(bytes, bytes + size); + if (!action.remove) { + const std::size_t size = static_cast(args[3]); + if (size > x2w_save::max_blob_bytes || (size && x2w_local::probe_readable(static_cast(args[2]), size) != size)) { + *result = e_invalidarg; + return true; + } + const auto* bytes = reinterpret_cast(args[2]); + if (size) action.data.assign(bytes, bytes + size); + } + } catch (const std::bad_alloc&) { + *result = e_outofmemory; + return true; } AcquireSRWLockExclusive(&save_lock); const bool staged = args[0] >= save_update_handle && save_table.stage(static_cast(args[0] - save_update_handle), std::move(action)); diff --git a/src/startup_stubs/save_store.h b/src/startup_stubs/save_store.h index 9887644fe..26d0ec8c9 100644 --- a/src/startup_stubs/save_store.h +++ b/src/startup_stubs/save_store.h @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -145,8 +146,13 @@ class ContainerTable { { if (update >= capacity || !updates_[update]) return false; if (action.data.size() > max_staged_bytes - staged_bytes_[update]) return false; - staged_bytes_[update] += action.data.size(); - staged_[update].push_back(std::move(action)); + const std::size_t size = action.data.size(); + try { + staged_[update].push_back(std::move(action)); + } catch (const std::bad_alloc&) { + return false; + } + staged_bytes_[update] += size; return true; } // The staged actions in order; the update starts empty again. diff --git a/tests/startup_gamesave_submit.cpp b/tests/startup_gamesave_submit.cpp index 09f83f42a..d17489a9f 100644 --- a/tests/startup_gamesave_submit.cpp +++ b/tests/startup_gamesave_submit.cpp @@ -2,7 +2,23 @@ // XAsync service can reject Begin, delay notification or enter the callback inline. #include "../src/startup_stubs/runtime_proxy.cpp" #include +#include #include +#include +#include + +static std::atomic fail_allocation_size{0}; +void* operator new(std::size_t size) +{ + std::size_t expected = size; + if (size && fail_allocation_size.compare_exchange_strong(expected, 0)) { + throw std::bad_alloc(); + } + if (void* p = std::malloc(size ? size : 1)) return p; + throw std::bad_alloc(); +} +void operator delete(void* p) noexcept { std::free(p); } +void operator delete(void* p, std::size_t) noexcept { std::free(p); } namespace { using Provider = decltype(&submit_provider); @@ -92,6 +108,21 @@ int run(bool system) call(16,provider_handle,ptr("profile"),ptr(&container)) || call(23,container,0,ptr(&good)) || call(23,container,0,ptr(&bad))) return 1; unsigned char byte=0x11; + const std::array large_blob{}; + for (const auto data_size : {std::size_t{1}, large_blob.size()}) { + fail_allocation_size = data_size == 1 ? sizeof(x2w_save::Action) : data_size; + u64 failed_stage{}; + try { + failed_stage = call(25,good,ptr("preference"),ptr(large_blob.data()),data_size); + } catch (const std::bad_alloc&) { + return 20; + } + if (fail_allocation_size || failed_stage != e_outofmemory) { + std::fprintf(stderr, "staging %zu bytes: pending allocation=%zu, HRESULT=0x%08llx\n", + data_size, fail_allocation_size.load(), static_cast(failed_stage)); + return 21; + } + } if (call(25,good,ptr("preference"),ptr(&byte),1) || call(27,good) || value()!=0x11) return 2; byte=0x77; if (call(25,good,ptr("preference"),ptr(&byte),1) || call(26,bad,ptr("absent"))) return 3; From ed8189acd964045d40804833c1b5ae99f73e131b Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Thu, 26 Nov 2026 04:51:05 +0200 Subject: [PATCH 091/240] shader: harden spirv_address_window CLI guards and add CLI suite (#2664) --- CMakeLists.txt | 3 + tests/spirv_address_window_cli_check.py | 433 ++++++++++++++++++++++++ tools/spirv_address_window.py | 34 +- 3 files changed, 464 insertions(+), 6 deletions(-) create mode 100644 tests/spirv_address_window_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 6f333cbda..4ab626d2c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4705,6 +4705,9 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/spirv_sampler_split_check.py") add_test(NAME spirv_address_window_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/spirv_address_window_check.py") + add_test(NAME shader_spirv_address_window_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/spirv_address_window_cli_check.py") + set_tests_properties(shader_spirv_address_window_cli_check PROPERTIES TIMEOUT 60) add_test(NAME shader_section_probe_cli_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/section_probe_cli_check.py") # Outside a Git checkout, such as a source archive, the tracked-path check cannot run. diff --git a/tests/spirv_address_window_cli_check.py b/tests/spirv_address_window_cli_check.py new file mode 100644 index 000000000..cf3e9905e --- /dev/null +++ b/tests/spirv_address_window_cli_check.py @@ -0,0 +1,433 @@ +#!/usr/bin/env python3 +"""Pure-Python mocked-subprocess CLI, atomic-write, path-guard, and cleanup suite for tools/spirv_address_window.py.""" + +from contextlib import redirect_stderr, redirect_stdout +from pathlib import Path +import os +import runpy +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOLS_DIR = ROOT / "tools" +TOOL = TOOLS_DIR / "spirv_address_window.py" +FIXTURES = ROOT / "tests" / "spirv_window" +sys.path.insert(0, str(TOOLS_DIR)) +import spirv_address_window as saw # noqa: E402 + + +SUBTRACT_ASM = (FIXTURES / "subtract.spvasm").read_text(encoding="utf-8") +_REAL_SUBPROCESS_RUN = subprocess.run + + +def _run_main(argv: list[str] | None) -> tuple[int, str, str]: + import io + + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = saw.main(argv) + except SystemExit as exc: + code = exc.code + if not isinstance(code, int): + if code is not None: + stderr.write(f"{code}\n") + code = 0 if code is None else 1 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return _REAL_SUBPROCESS_RUN( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class SpirvAddressWindowCliPositiveTests(unittest.TestCase): + def test_atomic_spv_in_nested_dir_overwrite_and_zero_temp_dirs(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + src = work / "subtract.spvasm" + src.write_text(SUBTRACT_ASM, encoding="utf-8") + nested_out = work / "nested" / "deep" / "window.spv" + + calls: list[list[str]] = [] + seen_asm: dict[str, str] = {} + created_tempdirs: list[Path] = [] + replaced_pairs: list[tuple[Path, Path]] = [] + real_tempdir = tempfile.TemporaryDirectory + real_replace = Path.replace + payload_counter = [0] + + class TrackingTempDir(real_tempdir): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + created_tempdirs.append(Path(self.name)) + + def tracking_replace(self_path: Path, target: Path): + replaced_pairs.append((self_path, Path(target))) + self.assertEqual(self_path.parent.parent.resolve(), Path(target).parent.resolve()) + return real_replace(self_path, target) + + def fake_run(cmd, check=False, **_kwargs): + self.assertTrue(check) + calls.append([str(part) for part in cmd]) + if cmd[0] == "mock-as": + asm_path = Path(cmd[3]) + seen_asm[asm_path.name] = asm_path.read_text(encoding="utf-8") + out_idx = cmd.index("-o") + 1 + payload_counter[0] += 1 + Path(cmd[out_idx]).write_bytes(f"SPV_V{payload_counter[0]}".encode("ascii")) + return subprocess.CompletedProcess(cmd, 0) + + with ( + mock.patch.object(saw.subprocess, "run", side_effect=fake_run), + mock.patch.object(saw.tempfile, "TemporaryDirectory", TrackingTempDir), + mock.patch.object(Path, "replace", tracking_replace), + ): + # 1) Nested missing parent directories, atomic replace, 0 leftover temp dirs. + code, out, err = _run_main([ + str(src), + str(nested_out), + "--assembler", + " mock-as ", + "--validator", + " mock-val ", + ]) + + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(out, "") + self.assertEqual(err, "") + self.assertEqual(nested_out.read_bytes(), b"SPV_V2") + self.assertEqual([p.name for p in nested_out.parent.iterdir()], ["window.spv"]) + self.assertEqual(len(created_tempdirs), 1) + self.assertFalse(created_tempdirs[0].exists()) + self.assertEqual(len(replaced_pairs), 1) + self.assertEqual(replaced_pairs[0][1].resolve(), nested_out.resolve()) + + self.assertEqual(len(calls), 4) + self.assertEqual(calls[0][:3], ["mock-as", "--target-env", "vulkan1.2"]) + self.assertEqual(Path(calls[0][3]).name, "original.spvasm") + self.assertEqual(calls[1][:3], ["mock-val", "--target-env", "vulkan1.2"]) + self.assertEqual(calls[2][:3], ["mock-as", "--target-env", "vulkan1.2"]) + self.assertEqual(Path(calls[2][3]).name, "logical.spvasm") + self.assertEqual(calls[3][:3], ["mock-val", "--target-env", "vulkan1.2"]) + self.assertEqual(seen_asm["original.spvasm"], SUBTRACT_ASM) + self.assertIn("OpMemoryModel Logical GLSL450", seen_asm["logical.spvasm"]) + self.assertNotIn("PhysicalStorageBuffer", seen_asm["logical.spvasm"]) + + # 2) Atomic overwrite on existing file leaves 0 temp dirs. + calls.clear() + code_ow, out_ow, err_ow = _run_main([ + str(src), + str(nested_out), + "--assembler", + "mock-as", + "--validator", + "mock-val", + ]) + self.assertEqual(code_ow, 0, err_ow) + self.assertEqual(out_ow, "") + self.assertEqual(err_ow, "") + self.assertEqual(nested_out.read_bytes(), b"SPV_V4") + self.assertEqual([p.name for p in nested_out.parent.iterdir()], ["window.spv"]) + self.assertEqual(len(created_tempdirs), 2) + self.assertFalse(created_tempdirs[1].exists()) + + # 3) argv=None forwards sys.argv cleanly. + with mock.patch.object( + sys, + "argv", + [str(TOOL), str(src), str(nested_out), "--assembler", "mock-as", "--validator", "mock-val"], + ): + code_none, out_none, err_none = _run_main(None) + self.assertEqual(code_none, 0, err_none) + self.assertEqual(out_none, "") + self.assertEqual(err_none, "") + self.assertEqual(nested_out.read_bytes(), b"SPV_V6") + self.assertEqual([p.name for p in nested_out.parent.iterdir()], ["window.spv"]) + self.assertFalse(created_tempdirs[2].exists()) + + # 4) __main__ entrypoint exits cleanly on invalid source without raw traceback. + import io + + stdout_m, stderr_m = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", [str(TOOL), str(work / "absent.spvasm"), str(work / "out.spv")]), + redirect_stdout(stdout_m), + redirect_stderr(stderr_m), + self.assertRaises(SystemExit) as exited, + ): + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 1) + self.assertEqual(stdout_m.getvalue(), "") + self.assertNotIn("Traceback", stderr_m.getvalue()) + self.assertIn("source file not found", stderr_m.getvalue().lower()) + + +class SpirvAddressWindowCliNegativeTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_code: int | None = 1, + fragments: tuple[str, ...] = (), + check_subprocess: bool = True, + ) -> str: + code, out, err = _run_main(argv) + if expected_code is None: + self.assertNotEqual(code, 0) + else: + self.assertEqual(code, expected_code, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertTrue(err.strip()) + for fragment in fragments: + self.assertIn(fragment.lower(), err.lower()) + + if check_subprocess: + proc = _run_subprocess(*argv) + if expected_code is None: + self.assertNotEqual(proc.returncode, 0) + else: + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + for fragment in fragments: + self.assertIn(fragment.lower(), proc.stderr.lower()) + return err + + def test_missing_dir_and_bad_utf8_source_rejected_without_creating_parent(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + dir_src = work / "dir_source" + dir_src.mkdir() + bad_utf8 = work / "bad_utf8.spvasm" + bad_utf8.write_bytes(b"\xff\xfe\x00\x80") + absent_out = work / "never_created" / "window.spv" + + with mock.patch.object( + saw.subprocess, + "run", + side_effect=AssertionError("subprocess.run called for invalid source"), + ): + for label, src, frags in ( + ("missing_source", work / "missing.spvasm", ("source file not found",)), + ("directory_source", dir_src, ("directory",)), + ("bad_utf8_source", bad_utf8, ("decode",)), + ): + with self.subTest(case=label): + self._assert_clean_failure( + [str(src), str(absent_out), "--assembler", "mock-as", "--validator", "mock-val"], + expected_code=1, + fragments=frags, + ) + self.assertFalse(absent_out.parent.exists()) + + def test_output_guards_dir_file_parent_and_samefile(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + src = work / "subtract.spvasm" + src.write_text(SUBTRACT_ASM, encoding="utf-8") + out_dir = work / "existing_dir.spv" + out_dir.mkdir() + file_parent = work / "file_parent" + file_parent.write_bytes(b"keep-parent-bytes") + hardlink = work / "subtract_hardlink.spv" + hardlink.hardlink_to(src) + missing_src = work / "missing.spvasm" + + with mock.patch.object( + saw.subprocess, + "run", + side_effect=AssertionError("subprocess.run called for invalid output"), + ): + for label, argv, frags in ( + ("output_is_dir", [str(src), str(out_dir)], ("directory",)), + ("parent_is_file", [str(src), str(file_parent / "window.spv")], ("not a directory",)), + ("ancestor_is_file", [str(src), str(file_parent / "sub" / "window.spv")], ("not a directory",)), + ("same_exact_path", [str(src), str(src)], ("separate input assembly and output binary",)), + ( + "same_unnormalized_path", + [str(src), str(work / "nested" / ".." / "subtract.spvasm")], + ("separate input assembly and output binary",), + ), + ( + "same_missing_alias", + [str(missing_src), str(work / "nested" / ".." / "missing.spvasm")], + ("separate input assembly and output binary",), + ), + ("hardlink_samefile", [str(src), str(hardlink)], ("separate input assembly and output binary",)), + ): + with self.subTest(case=label): + self._assert_clean_failure(argv, expected_code=1, fragments=frags) + + self.assertEqual(src.read_text(encoding="utf-8"), SUBTRACT_ASM) + self.assertEqual(list(out_dir.iterdir()), []) + self.assertEqual(file_parent.read_bytes(), b"keep-parent-bytes") + + def test_output_symlink_rejected_before_subprocess(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + src = work / "subtract.spvasm" + src.write_text(SUBTRACT_ASM, encoding="utf-8") + out_dir = work / "out_dir" + out_dir.mkdir() + real_target = out_dir / "real.spv" + real_target.write_bytes(b"UNTOUCHED") + live_link = out_dir / "live_link.spv" + dangling_link = out_dir / "dangling_link.spv" + try: + live_link.symlink_to(real_target) + dangling_link.symlink_to(out_dir / "missing.spv") + except OSError as exc: + if getattr(exc, "winerror", None) != 1314: + raise + self.skipTest("this Windows account cannot create symlinks (WinError 1314)") + + with mock.patch.object( + saw.subprocess, + "run", + side_effect=AssertionError("subprocess.run called for symlink output"), + ): + for label, link in (("live_symlink", live_link), ("dangling_symlink", dangling_link)): + with self.subTest(case=label): + self._assert_clean_failure( + [str(src), str(link), "--assembler", "mock-as", "--validator", "mock-val"], + expected_code=1, + fragments=("symlink",), + ) + + self.assertEqual(real_target.read_bytes(), b"UNTOUCHED") + self.assertEqual( + sorted(p.name for p in out_dir.iterdir()), + ["dangling_link.spv", "live_link.spv", "real.spv"], + ) + + def test_empty_and_whitespace_assembler_and_validator_rejected(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + src = work / "subtract.spvasm" + src.write_text(SUBTRACT_ASM, encoding="utf-8") + absent_out = work / "absent_dir" / "window.spv" + + with mock.patch.object( + saw.subprocess, + "run", + side_effect=AssertionError("subprocess.run called for empty tool flag"), + ): + for label, flag, val in ( + ("empty_assembler", "--assembler", ""), + ("blank_assembler", "--assembler", " \t "), + ("empty_validator", "--validator", ""), + ("blank_validator", "--validator", " \n "), + ): + with self.subTest(case=label): + self._assert_clean_failure( + [str(src), str(absent_out), flag, val], + expected_code=1, + fragments=(flag, "non-empty"), + ) + self.assertFalse(absent_out.parent.exists()) + + def test_subprocess_and_replace_failures_clean_up_temp_dirs_and_preserve_output(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + src = work / "subtract.spvasm" + src.write_text(SUBTRACT_ASM, encoding="utf-8") + target_dir = work / "target_dir" + target_dir.mkdir() + protected = target_dir / "kept.spv" + sentinel = b"SENTINEL_KEEP_BYTES" + protected.write_bytes(sentinel) + + created_tempdirs: list[Path] = [] + real_tempdir = tempfile.TemporaryDirectory + calls: list[list[str]] = [] + fail_on_call: dict[int, BaseException] = {} + + class TrackingTempDir(real_tempdir): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + created_tempdirs.append(Path(self.name)) + + def fake_run(cmd, check=False, **_kwargs): + calls.append([str(part) for part in cmd]) + idx = len(calls) + if idx in fail_on_call: + raise fail_on_call[idx] + if cmd[0] == "mock-as": + out_idx = cmd.index("-o") + 1 + Path(cmd[out_idx]).write_bytes(b"MOCK_SPV") + return subprocess.CompletedProcess(cmd, 0) + + with ( + mock.patch.object(saw.subprocess, "run", side_effect=fake_run), + mock.patch.object(saw.tempfile, "TemporaryDirectory", TrackingTempDir), + ): + failure_cases = ( + ("orig_as_called_process_error", 1, subprocess.CalledProcessError(1, ["mock-as"]), ("returned non-zero",)), + ("orig_val_called_process_error", 2, subprocess.CalledProcessError(1, ["mock-val"]), ("returned non-zero",)), + ("lower_as_called_process_error", 3, subprocess.CalledProcessError(1, ["mock-as"]), ("returned non-zero",)), + ("lower_val_called_process_error", 4, subprocess.CalledProcessError(1, ["mock-val"]), ("returned non-zero",)), + ("missing_tool_file_not_found", 1, FileNotFoundError("no mock-as binary"), ("no mock-as binary",)), + ("validator_timeout", 2, subprocess.TimeoutExpired(["mock-val"], 5), ("timed out",)), + ) + for label, call_idx, exc, frags in failure_cases: + with self.subTest(case=label): + calls.clear() + fail_on_call.clear() + fail_on_call[call_idx] = exc + self._assert_clean_failure( + [str(src), str(protected), "--assembler", "mock-as", "--validator", "mock-val"], + expected_code=1, + fragments=frags, + check_subprocess=False, + ) + self.assertEqual(protected.read_bytes(), sentinel) + self.assertEqual([p.name for p in target_dir.iterdir()], ["kept.spv"]) + self.assertFalse(created_tempdirs[-1].exists()) + + fail_on_call.clear() + with mock.patch.object(Path, "replace", side_effect=OSError("simulated replace failure")): + self._assert_clean_failure( + [str(src), str(protected), "--assembler", "mock-as", "--validator", "mock-val"], + expected_code=1, + fragments=("simulated replace failure",), + check_subprocess=False, + ) + self.assertEqual(protected.read_bytes(), sentinel) + self.assertEqual([p.name for p in target_dir.iterdir()], ["kept.spv"]) + self.assertFalse(created_tempdirs[-1].exists()) + + def test_argparse_errors_py314_safe(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + src = work / "subtract.spvasm" + src.write_text(SUBTRACT_ASM, encoding="utf-8") + out = work / "out.spv" + + for argv, frags in ( + ([], ("required",)), + ([str(src)], ("required",)), + ([str(src), str(out), "--assembler"], ("expected one argument",)), + ([str(src), str(out), "--validator"], ("expected one argument",)), + ([str(src), str(out), "--bogus-flag"], ("unrecognized",)), + ): + with self.subTest(argv=argv): + self._assert_clean_failure( + argv, + expected_code=None, + fragments=frags, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/spirv_address_window.py b/tools/spirv_address_window.py index 304f6cb90..068f1c650 100644 --- a/tools/spirv_address_window.py +++ b/tools/spirv_address_window.py @@ -665,6 +665,31 @@ def _same_path(left: Path, right: Path) -> bool: return False +def _validate_args(args: argparse.Namespace) -> tuple[str, str]: + if _same_path(args.output, args.source): + raise ValueError("use separate input assembly and output binary paths") + if args.source.is_dir(): + raise IsADirectoryError(f"source path must not be a directory: {args.source}") + if not args.source.exists(): + raise FileNotFoundError(f"source file not found: {args.source}") + if not args.source.is_file(): + raise ValueError(f"source path must be a regular file: {args.source}") + if args.output.is_symlink(): + raise ValueError(f"output path must not be a symlink: {args.output}") + if args.output.is_dir(): + raise IsADirectoryError(f"output path must not be a directory: {args.output}") + for parent in args.output.parents: + if parent.is_file() or ((parent.exists() or parent.is_symlink()) and not parent.is_dir()): + raise NotADirectoryError(f"output parent is not a directory: {parent}") + assembler = args.assembler.strip() + if not assembler: + raise ValueError("--assembler must be a non-empty string") + validator = args.validator.strip() + if not validator: + raise ValueError("--validator must be a non-empty string") + return assembler, validator + + def main(argv=None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("source", type=Path) @@ -673,10 +698,7 @@ def main(argv=None) -> int: parser.add_argument("--validator", default="spirv-val") args = parser.parse_args(argv) try: - if _same_path(args.output, args.source): - raise ValueError("use separate input assembly and output binary paths") - if args.output.is_dir(): - raise ValueError(f"output path must not be a directory: {args.output}") + assembler, validator = _validate_args(args) original = args.source.read_text(encoding="utf-8") args.output.parent.mkdir(parents=True, exist_ok=True) with tempfile.TemporaryDirectory(dir=args.output.parent) as directory: @@ -684,8 +706,8 @@ def main(argv=None) -> int: binary = path / "module.spv" def validate(source): - subprocess.run([args.assembler, "--target-env", "vulkan1.2", source, "-o", binary], check=True) - subprocess.run([args.validator, "--target-env", "vulkan1.2", binary], check=True) + subprocess.run([assembler, "--target-env", "vulkan1.2", source, "-o", binary], check=True) + subprocess.run([validator, "--target-env", "vulkan1.2", binary], check=True) snapshot = path / "original.spvasm" snapshot.write_text(original, encoding="utf-8") From ed53c1febbc7cd0dc44cee7f3a4dad9809b62183 Mon Sep 17 00:00:00 2001 From: SimSalabimse <83839581+SimSalabimse@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:51:38 +0100 Subject: [PATCH 092/240] =?UTF-8?q?startup:=20lower=20constant-lane=20writ?= =?UTF-8?q?elane/readlane=20spills=20in=20translate=5Fm=E2=80=A6=20(#2637)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * startup: lower constant-lane writelane/readlane spills in translate_mesh57 Accept the #2127 constant-lane v_writelane_b32 / v_readlane_b32 idiom on the slot 57 mesh request path (Part of #2413 T7). Spill-only VGPRs become scalar slots; ordinary vector use, unwritten lanes and non-constant lanes stay refused. Source-built host checks and WARP/hardware draw fixtures cover the happy path and a mutant that zeroes the spilled colour word. AI-assisted. Co-authored-by: SimSalabimse * startup: fix mesh57 lane-spill WARP mutant and EXEC/exchange refusals Refuse raw EXEC writelane sources under the one-lane model, scan pre-skeleton instructions so exchange VGPRs stay spill-unsafe, park an ordinary scalar in lane 63, and mutate only the colour spill assignment so the multi-decl keeps sp30_63 for DXC. Refs #2413 Co-authored-by: SimSalabimse * test: allow s_mul_hi_* own-arity templates in scalar table check #2405 added s_mul_hi_i32 (and an early arity refuse for both mul_hi forms). The negative control still expected only one non-IndexError survivor. Co-authored-by: SimSalabimse --------- Co-authored-by: Cursor Agent Co-authored-by: SimSalabimse Co-authored-by: Royoo <3230853833@qq.com> --- .github/workflows/windows.yml | 2 + AGENTS.md | 1 + CMakeLists.txt | 7 + docs/experiments.md | 13 ++ tests/startup_mesh57_lane_spill_check.py | 231 +++++++++++++++++++++++ tools/startup/gfx2hlsl.py | 51 +++-- 6 files changed, 291 insertions(+), 14 deletions(-) create mode 100644 tests/startup_mesh57_lane_spill_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 763c15bff..92a27f4bd 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -92,6 +92,7 @@ jobs: (["tests/startup_mesh57_skeleton_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_mesh57_loop_refusal_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_mesh57_loop_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_mesh57_lane_spill_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_cvt_alu_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_cvt_pk_u8_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_cvt_pk_int16_check.py", "binary", "llvm-mc-15"], {}), @@ -293,6 +294,7 @@ jobs: tests/startup_mesh57_depth_only_check.py \ tests/startup_mesh57_loop_refusal_check.py \ tests/startup_mesh57_loop_check.py \ + tests/startup_mesh57_lane_spill_check.py \ tests/startup_gfx2hlsl_scalar_shift64_bfe_check.py \ tests/startup_gfx2hlsl_readfirstlane_uniform_check.py \ tests/startup_gfx2hlsl_loop_constants_check.py \ diff --git a/AGENTS.md b/AGENTS.md index f16119659..d80240aa5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -200,6 +200,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_mesh57_depth_only_check.py ./out/pe-env/bin/python -B tests/startup_mesh57_loop_refusal_check.py ./out/pe-env/bin/python -B tests/startup_mesh57_loop_check.py +./out/pe-env/bin/python -B tests/startup_mesh57_lane_spill_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_readfirstlane_uniform_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_loop_constants_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_join_symbols_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 4ab626d2c..6d8113d46 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3540,6 +3540,9 @@ if(EXISTS "${INTAKE_PYTHON}") # Slot 57 mesh constant-trip loop lowering outside the accepted exchanges (#2413 T6). add_test(NAME startup_mesh57_loop COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_mesh57_loop_check.py") + # Slot 57 constant-lane v_writelane_b32 / v_readlane_b32 spill idiom (#2413 T7). + add_test(NAME startup_mesh57_lane_spill COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_mesh57_lane_spill_check.py") # Scalar SOPK accumulate: s_addk_i32 signed-overflow SCC and s_mulk_i32 against an integer reference. add_test(NAME startup_gfx2hlsl_sopk_accum COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_sopk_accum_check.py") @@ -9528,6 +9531,10 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/startup_mesh57_loop_check.py" draw "${DXC_EXECUTABLE}" "$" ${adapter}) set_tests_properties(startup_mesh57_loop_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + add_test(NAME startup_mesh57_lane_spill_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_mesh57_lane_spill_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_mesh57_lane_spill_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) add_test(NAME startup_mesh57_skeleton_wave_shift_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_mesh57_skeleton_check.py" shift "${DXC_EXECUTABLE}" "$" ${adapter}) diff --git a/docs/experiments.md b/docs/experiments.md index 09d88a0f4..228af5c6b 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9859,6 +9859,19 @@ VGPR source, a different VCC write, or a narrowed EXEC at the branch invalidates the proof. The CPU-reference draws cover both outcomes for each branch polarity and a VCC-zero branch after a join. +The `startup_mesh57_lane_spill_{warp,hardware}` tests cover the constant-lane +`v_writelane_b32` / `v_readlane_b32` spill idiom in `translate_mesh57` (#2413 T7). +A source-built program parks ordinary scalars in fixed wave64 lanes of a spill-only +VGPR (including lane 63), reloads them, and uses the colour reload as vertex red. +Raw `exec_lo` / `exec_hi` sources stay refused under the one-lane model. Host checks +also refuse an unwritten slot, a register-selected lane, lane 64, ordinary vector use +of the spill VGPR, and a spill into an exchange VGPR. The draw compares all 1,024 +pixels with a CPU rasterizer; zeroing the spilled colour assignment in HLSL (not the +multi-decl) must change the image. +Run `python -B tests/startup_mesh57_lane_spill_check.py` for host refusals, or +`ctest --preset release --no-tests=error -R '^startup_mesh57_lane_spill' -V` +for WARP and hardware. + The `startup_mesh57_skeleton_wave_shift_{warp,hardware}` tests cover a single `s_lshl_b32` behind a forward EXEC-zero branch after the count exchange. From full EXEC a compare selects the threads with index below an unsigned constant. diff --git a/tests/startup_mesh57_lane_spill_check.py b/tests/startup_mesh57_lane_spill_check.py new file mode 100644 index 000000000..ea1f94db6 --- /dev/null +++ b/tests/startup_mesh57_lane_spill_check.py @@ -0,0 +1,231 @@ +"""Constant-lane v_writelane_b32 / v_readlane_b32 in translate_mesh57 (#2413 T7). + +usage: startup_mesh57_lane_spill_check.py + startup_mesh57_lane_spill_check.py binary + startup_mesh57_lane_spill_check.py draw + +The fixture extends the accepted slot 57 group-memory shape with the #2127 spill idiom: +park ordinary scalars in fixed wave64 lanes of a spill-only VGPR under EXEC-independent +writelane/readlane, clobber the SGPRs, reload them, and use the colour reload as vertex red. +Raw EXEC sources stay refused. Ordinary VGPR use of the spill register, an exchange VGPR, an +unwritten slot, a register-selected lane, and a mutant that zeroes the spilled colour assignment +(not the multi-decl) must fail by name or change pixels. +""" +import os +from pathlib import Path +import re +import struct +import subprocess +import sys +import tempfile + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +import gfx2hlsl as G # noqa: E402 +from startup_mesh57_skeleton_check import ( # noqa: E402 + MESH, PIXEL, PIXEL_ASM, POST_COUNT, assemble, buffer, code, expect, FAILED, geometry, rasterise, root, +) + +SIDE = 32 + + +def writelane(vd, src, lane): + """Two little-endian words for `v_writelane_b32 vD, src, lane` (src is an SGPR index or special).""" + return ['%08x' % (0xd7610000 | vd), '%08x' % (src | ((128 + lane) << 9))] + + +def readlane(sd, vv, lane): + """Two little-endian words for `v_readlane_b32 sD, vV, lane` (VGPR encoded as 256+V).""" + return ['%08x' % (0xd7600000 | sd), '%08x' % ((256 + vv) | ((128 + lane) << 9))] + + +# s_mov_b32 s40, 1.0; writelane v30 lane 3; clobber; park/reload a second ordinary scalar in lane 63 +# (wave64); v_mov_b32 v7, s40 — vertex red comes from the colour reload. Raw EXEC spills are refused. +SPILL_ASM = """s_mov_b32 s40, 1.0 +v_writelane_b32 v30, s40, 3 +s_mov_b32 s40, 0 +s_mov_b32 s41, 0x11 +v_writelane_b32 v30, s41, 63 +s_mov_b32 s41, 0 +v_readlane_b32 s41, v30, 63 +v_readlane_b32 s40, v30, 3 +v_mov_b32 v7, s40""" +SPILL_WORDS = ( + ['bea803f2'] + writelane(30, 40, 3) + ['bea80380'] + + ['bea90391'] + writelane(30, 41, 63) + ['bea90380'] + readlane(41, 30, 63) + + readlane(40, 30, 3) + ['7e0e0228'] +) +# After the colour load's waitcnt, overwrite v20 (red) with the reloaded spill in v7. +_WAIT = MESH.index('bf8c3f70') +SPILL_MESH = ( + MESH[:POST_COUNT] + SPILL_WORDS + MESH[POST_COUNT:_WAIT + 1] + + ['7e280307'] + MESH[_WAIT + 1:] +) +# Mutant: drop the colour writelane so the reload of lane 3 is unwritten at the host, or after a +# successful translation zero the spill assignment in HLSL so the draw oracle fails. +MUTANT_NO_WRITE = ( + MESH[:POST_COUNT] + ( + ['bea803f2', 'bea80380'] + ['bea90391'] + writelane(30, 41, 63) + ['bea90380'] + + readlane(41, 30, 63) + readlane(40, 30, 3) + ['7e0e0228'] + ) + MESH[POST_COUNT:_WAIT + 1] + ['7e280307'] + MESH[_WAIT + 1:] +) + + +def request(directory, mesh, pixel=PIXEL): + ms, ps, blob = code(mesh), code(pixel), root() + key = G.mesh57_key(ms, ps, blob) + for ext, data in (('.root', blob), ('.ps57', ps), ('.m57', ms)): + (Path(directory) / ('req_%016x%s' % (key, ext))).write_bytes(data) + return key, G.translate_request(str(directory), key) + + +def controls(): + os.environ['X2W_FXC'] = '' + with tempfile.TemporaryDirectory() as tmp: + key, result = request(tmp, SPILL_MESH) + expect('spill fixture translates', result, 'ok') + if result == 'ok': + text = (Path(tmp) / ('%016x.ms57.hlsl' % key)).read_text() + expect('spill slots are declared', 'sp30_3' in text and 'sp30_63' in text, True) + expect('colour spill is assigned', 'sp30_3 =' in text, True) + expect('wave64 lane 63 parks the second scalar', 'sp30_63 =' in text and 's41 = sp30_63' in text, True) + expect('reload feeds the SGPR', 's40 = sp30_3' in text, True) + expect('spill VGPR is not a vector temporary', not re.search(r'\bv30\b', text), True) + + refusals = ( + ('unwritten spill slot', + MESH[:POST_COUNT] + ['bea803f2'] + writelane(30, 40, 3) + ['bea80380'] + + readlane(40, 30, 4) + ['7e0e0228'] + MESH[POST_COUNT:], + 'v_readlane_b32 reads v30 lane 4 before any v_writelane_b32 wrote it'), + ('register-selected lane', + MESH[:POST_COUNT] + ['bea803f2', 'bea80380'] + + ['%08x' % (0xd761001e), '%08x' % (40 | (40 << 9))] # v_writelane v30, s40, s40 + + readlane(40, 30, 3) + ['7e0e0228'] + MESH[POST_COUNT:], + 'v_writelane_b32 requires a constant lane, got s40'), + ('lane 64 outside wave64', + MESH[:POST_COUNT] + ['bea803f2'] + writelane(30, 40, 64) + MESH[POST_COUNT:], + 'v_writelane_b32 lane 64 outside 0..63'), + ('mixed ordinary use of the spill VGPR', + MESH[:POST_COUNT] + ['bea803f2'] + writelane(30, 40, 3) + ['bea80380'] + + ['7e3c0300'] # v_mov_b32 v30, v0 — ordinary vector write of the spill VGPR + + readlane(40, 30, 3) + ['7e0e0228'] + MESH[POST_COUNT:], + 'v_writelane_b32: v30 is also used as a vector (v_mov_b32_e32)'), + ('spill into the group-index exchange VGPR', + MESH[:POST_COUNT] + ['bea803f2'] + writelane(5, 40, 3) + ['bea80380'] + + readlane(40, 5, 3) + ['7e0e0228'] + MESH[POST_COUNT:], + 'v_writelane_b32: v5 is also used as a vector (v_lshrrev_b32_e32)'), + ('raw exec_hi spill', + MESH[:POST_COUNT] + writelane(30, 127, 63) + MESH[POST_COUNT:], + 'v_writelane_b32 source exec_hi is a lane mask or m0'), + ('raw exec_lo spill', + MESH[:POST_COUNT] + writelane(30, 126, 3) + MESH[POST_COUNT:], + 'v_writelane_b32 source exec_lo is a lane mask or m0'), + ('read before any write', + MESH[:POST_COUNT] + readlane(40, 30, 3) + ['7e0e0228'] + MESH[POST_COUNT:], + 'v_readlane_b32 reads v30 lane 3 before any v_writelane_b32 wrote it'), + ('missing colour write refuses at reload', MUTANT_NO_WRITE, + 'v_readlane_b32 reads v30 lane 3 before any v_writelane_b32 wrote it'), + ) + for what, mesh, reason in refusals: + with tempfile.TemporaryDirectory() as tmp: + key, result = request(tmp, mesh) + expect(what, result, 'unsupported: ' + reason) + expect(what + ': only the refusal is published', + sorted(p.name for p in Path(tmp).iterdir() if not p.name.startswith('req_')), + ['%016x.fail' % key]) + + +def binary(mc): + mesh = (HERE / 'startup_mesh57_skeleton.s').read_text() + insert = mesh.replace('v_cmpx_gt_i32 s14, v0', SPILL_ASM + '\nv_cmpx_gt_i32 s14, v0') + insert = insert.replace('exp pos0', 'v_mov_b32 v20, v7\nexp pos0') + expect('spill mesh words match llvm-mc', assemble(mc, insert), SPILL_MESH) + expect('pixel words match llvm-mc', assemble(mc, PIXEL_ASM), PIXEL) + + +def draw(dxc, renderer, adapter): + os.environ['X2W_DXC'] = dxc + os.environ.pop('X2W_FXC', None) + points, colours, indices = geometry() + with tempfile.TemporaryDirectory() as tmp: + key, result = request(tmp, SPILL_MESH) + expect('spill fixture translates and compiles', result, 'ok') + if result != 'ok': + return 0 + name = Path(tmp) / ('%016x' % key) + pipe = G.MeshPipeline(code(SPILL_MESH), code(PIXEL), root()) + constants = bytearray(1024) + for slot, count in enumerate((4, 12)): + struct.pack_into(' 0, True) + path.write_bytes(head + b''.join(map(bytes, image))) + run = subprocess.run( + [renderer, adapter, '--mesh-indexed', str(mutant), str(name) + '.ps57.cso', str(path)], + capture_output=True, text=True) + if run.returncode == 77: + print(run.stdout + run.stderr) + return 77 + expect('mutant fails the correct reference', + (run.returncode != 0 and 'mismatches=' in run.stdout), True) + path.write_bytes(head + b''.join(map(bytes, wrong))) + run = subprocess.run( + [renderer, adapter, '--mesh-indexed', str(mutant), str(name) + '.ps57.cso', str(path)], + capture_output=True, text=True) + if run.returncode == 77: + print(run.stdout + run.stderr) + return 77 + expect('mutant matches the zeroed reference', + (run.returncode, 'pixels=1024 mismatches=0' in run.stdout), (0, True)) + print('spill draw: %d pixels differ when the spilled word is zeroed' % different) + return 0 + + +def main(argv): + status = 0 + if argv[1:2] == ['binary'] and len(argv) == 3: + binary(argv[2]) + elif argv[1:2] == ['draw'] and len(argv) == 5: + status = draw(*argv[2:]) + elif len(argv) == 1: + controls() + else: + print(__doc__) + return 2 + if FAILED: + return 1 + print('skip: no mesh shader tier' if status == 77 else 'ok') + return status + + +if __name__ == '__main__': + sys.exit(main(sys.argv)) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index b78fca6d7..061534962 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -1850,7 +1850,11 @@ def region_walk(lo, hi): continue if name.startswith('ds_') or name in ('s_barrier', 's_sendmsg', 's_sendmsghalt'): raise Unsupported('slot 57 mesh: %s outside the group-memory exchanges' % name) - if name.startswith(('v_readlane', 'v_writelane')): + # Constant-lane v_writelane_b32 / v_readlane_b32 (#2413 T7, #2127): Stage lowers the idiom and + # refuses ordinary VGPR use, unwritten slots and non-constant lanes. The spill VGPR is not a + # per-lane value in this model, so it does not update the stale/pending sets below. + lane_spill = base_name in ('v_writelane_b32', 'v_readlane_b32') + if name.startswith(('v_readlane', 'v_writelane')) and not lane_spill: raise Unsupported('slot 57 mesh: lane spills are not covered') keep = ins[index] if base_name == 'v_readfirstlane_b32': @@ -1867,7 +1871,8 @@ def region_walk(lo, hi): writes_s.update(range(r[1], r[2] + 1)) if 3 in writes_s or writes_s & lane: raise Unsupported('slot 57 mesh: the wave word s3 or the saved lane-0 mask is written') - if writes_s and name.startswith('v_') and keep[2] != 'x2w_mesh_group': + if (writes_s and name.startswith('v_') and keep[2] != 'x2w_mesh_group' + and base_name != 'v_readlane_b32'): raise Unsupported('slot 57 mesh: %s into an SGPR is not covered' % base_name) # Only the wave index of s3 is modelled. if not re.fullmatch(r's_bfe_u32 s\d+, s3, 0x40018', asm) and any( @@ -1916,8 +1921,9 @@ def region_walk(lo, hi): raise Unsupported('slot 57 mesh: an EXEC compare other than output count > thread index under ' 'exec = -1 is not covered') mask = count - elif writes_exec(name, ops) or re.search(r'\b(?:exec(?:_lo|_hi)?|src_execz|src_vccz)\b', asm) or ( - name.startswith('s_') and re.search(r'\bvcc(_lo|_hi)?\b', asm)): + elif (not lane_spill and ( + writes_exec(name, ops) or re.search(r'\b(?:exec(?:_lo|_hi)?|src_execz|src_vccz)\b', asm) or ( + name.startswith('s_') and re.search(r'\bvcc(_lo|_hi)?\b', asm)))): raise Unsupported('slot 57 mesh: %s on a wave mask is not covered' % base_name) # The thread index: v_mbcnt_lo(-1, wave << 6) then v_mbcnt_hi(-1, that) under exec = -1. if asm == 's_bfe_u32 %s, s3, 0x40018' % env['wave']: @@ -1938,6 +1944,8 @@ def region_walk(lo, hi): thread_high = index + 1 elif thread in writes_v and index != thread_high: raise Unsupported('slot 57 mesh: the thread index register is rewritten') + if lane_spill: + reads_v, writes_v = set(), set() if keep[2] != 'x2w_mesh_group' and reads_v & stale: raise Unsupported('slot 57 mesh: v%d is read where it is not defined for every lane (an entry value, or ' 'left different per wave by an exchange)' % min(reads_v & stale)) @@ -2014,7 +2022,11 @@ def __init__(self, pipe, kind, code, refusals=None, decoded=None): self.mesh_vcc_branches = {} self.mesh_wave_limits = {} self.mesh_wave_loads = {} + # Keep the pre-skeleton program so spill-only proofs still see the exchange VGPRs + # (mesh_skeleton rewrites those ops to x2w_mesh_* / s_nop). + self.mesh_source_ins = list(self.ins) self.ins = mesh_skeleton(self.ins, self.mesh_vcc_branches, self.mesh_wave_limits, self.mesh_wave_loads) + # A loop header is translated before the back edges into it, so whether a back edge brings the symbol kept # there is known only afterwards: translate again with that register read at run time or refused there. A # register only moves from kept to 'run' to 'refuse', so this ends. @@ -2973,6 +2985,7 @@ def translate(self): self.whole_read_v = set() # VGPRs read outside a proven low-16-bit consumer self.float_const_s = {} # SGPR -> 32-bit pattern from s_mov_b32 of an inline float constant self.has_branches = bool(targets) + self.spill_slots = {} # (vgpr, lane) -> (sym, uniform) for constant-lane SGPR spills self.vcc_events = {} self.entry_table_pointers = { reg: sym[1] for reg, sym in init_sym.items() @@ -6552,12 +6565,13 @@ def op_v_readfirstlane_b32(self, ops, mods): else: self.set_s(dst[1], self.u(ops[1])) - # ---- SGPR spill to VGPR lanes (#2125, item E) -------------------------------------------- + # ---- SGPR spill to VGPR lanes (#2125 item E; mesh #2413 T7 / #2127) ---------------------- # The compiler parks a scalar in one lane of a VGPR: `v_writelane_b32 vN, sM, k` writes sM into lane k # and `v_readlane_b32 sD, vN, k` reads it back (AMD RDNA 2 ISA reference, VOP3 lane ops; LLVM 15 # AMDGPU spill lowering). Both ignore EXEC. With a constant k and a VGPR that no other instruction # touches, vN is only a table of scalar slots, so one scalar variable per (vN, k) is an exact model # and no other lane is ever read. Anything else keeps the one-lane model out of reach and is refused. + # Pixel stages are wave32 (lanes 0..31). Slot 57 mesh is wave64 (lanes 0..63), matching #2127. # # With branches the slot variable is assigned on the pixel's own path, while the hardware slot holds the last # write on the wave's path. The two paths differ only inside the region of a branch not proven uniform (an @@ -6646,19 +6660,24 @@ def spill_operands(self, name, ops, mods): lane = int(ops[2], 0) except ValueError: raise Unsupported('%s requires a constant lane, got %s' % (name, ops[2])) from None - if not 0 <= lane < self.SPILL_LANES: - raise Unsupported('%s lane %d outside 0..%d' % (name, lane, self.SPILL_LANES - 1)) - if getattr(self, 'kind', None) != 'ps': - raise Unsupported('%s is lowered in pixel stages only' % name) + kind = getattr(self, 'kind', None) + lanes = 64 if kind == 'ms' else self.SPILL_LANES + if not 0 <= lane < lanes: + raise Unsupported('%s lane %d outside 0..%d' % (name, lane, lanes - 1)) + if kind not in ('ps', 'ms'): + raise Unsupported('%s is lowered in pixel and mesh stages only' % name) if not self.tracks_uniformity() or (getattr(self, 'has_branches', True) and - getattr(self, 'spill_reach', None) is None): + (kind != 'ps' or getattr(self, 'spill_reach', None) is None)): raise Unsupported('%s needs straight-line code to prove write-before-read' % name) self.require_spill_only(vreg[1], name) return vreg[1], sreg, lane def require_spill_only(self, n, name): """Refuse unless every instruction naming v is a lane write or read of it.""" - for _, _, op, asm in getattr(self, 'ins', ()): + # Mesh: scan the pre-skeleton program. The accepted group-memory exchanges rewrite to + # x2w_mesh_* / s_nop, which would hide ordinary use of exchange VGPRs (v5 and temps). + source = getattr(self, 'mesh_source_ins', None) or getattr(self, 'ins', ()) + for _, _, op, asm in source: if re.sub(r'_e(32|64)$', '', op) in ('v_writelane_b32', 'v_readlane_b32'): continue for lo, hi, single in re.findall(r'\bv\[(\d+):(\d+)\]|\bv(\d+)\b', asm): @@ -6669,11 +6688,15 @@ def require_spill_only(self, n, name): def op_v_writelane_b32(self, ops, mods): n, src, lane = self.spill_operands('v_writelane_b32', ops, mods) if src is None: + # Slot 57 mesh keeps ordinary scalar spills only (R0Y00 on #2637). Raw EXEC words are not + # proven under the one-lane model (exec_hi would be wrong under full EXEC; exec_lo under + # a lane-0 mask would reload per thread). mesh_entry_aot still models EXEC for #2127. if ops[1] in ('vcc', 'vcc_lo', 'vcc_hi', 'exec', 'exec_lo', 'exec_hi', 'm0'): raise Unsupported('v_writelane_b32 source %s is a lane mask or m0' % ops[1]) - value, sym, uniform = self.u(ops[1]), None, True - if re.fullmatch(r'0x[0-9a-f]{8}u', value): - sym = ('const', int(value[2:-1], 16)) + else: + value, sym, uniform = self.u(ops[1]), None, True + if re.fullmatch(r'0x[0-9a-f]{8}u', value): + sym = ('const', int(value[2:-1], 16)) else: if self.is_lane_mask(ops[1]) or (self.sym.get(src[1]) or ('',))[0] not in ('', 'const', 'ud', 'fixed_buffer_word'): raise Unsupported('v_writelane_b32 source s%d holds a lane mask or descriptor' % src[1]) From c3136f897ba03e91b4a0d3f869a6120e0c11bafd Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Thu, 26 Nov 2026 04:55:26 +0200 Subject: [PATCH 093/240] pe: harden call_evidence CLI input/output guards and atomic writes (#2666) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 3 + tests/call_evidence_cli_check.py | 690 +++++++++++++++++++++++++++++++ tools/call_evidence.py | 77 +++- 3 files changed, 760 insertions(+), 10 deletions(-) create mode 100644 tests/call_evidence_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 6d8113d46..304452379 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -10794,6 +10794,9 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/pe_inventory_cli_check.py") add_test(NAME call_evidence_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/call_evidence_check.py") + add_test(NAME pe_call_evidence_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/call_evidence_cli_check.py") + set_tests_properties(pe_call_evidence_cli_check PROPERTIES TIMEOUT 60) add_test(NAME pe_run_package_invalid_pe COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/pe_run_package_invalid_check.py") add_test(NAME pe_run_package_plan_check COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/call_evidence_cli_check.py b/tests/call_evidence_cli_check.py new file mode 100644 index 000000000..cb606b759 --- /dev/null +++ b/tests/call_evidence_cli_check.py @@ -0,0 +1,690 @@ +#!/usr/bin/env python3 +"""Pure-Python synthetic PE32+ CLI, atomic-write, and path-guard suite for tools/call_evidence.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import hashlib +import io +import json +import os +from pathlib import Path +import runpy +import shutil +import struct +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOLS_DIR = ROOT / "tools" +TOOL = TOOLS_DIR / "call_evidence.py" +sys.path.insert(0, str(TOOLS_DIR)) +import call_evidence # noqa: E402 + + +IMAGE_BASE = 0x180000000 +SECTION_RVA = 0x1000 +RAW_OFFSET = 0x200 +RAW_SIZE = 0x1000 + + +def _make_dxbc_container() -> bytes: + """Build a minimal synthetic DXBC container with DXIL and RTS0 parts.""" + program = struct.pack(" tuple[bytes, dict[tuple[bytes, bytes], int], list[int]]: + """Build a minimal AMD64 PE32+ DLL with optional imports and mapped DXBC containers.""" + payload = bytearray(RAW_SIZE) + cursor = 0 + + def alloc(size: int, align: int) -> int: + nonlocal cursor + cursor = (cursor + align - 1) & ~(align - 1) + rva = SECTION_RVA + cursor + if cursor + size > len(payload): + raise AssertionError("synthetic section overflow") + cursor += size + return rva + + def put(rva: int, blob: bytes) -> None: + offset = rva - SECTION_RVA + payload[offset:offset + len(blob)] = blob + + grouped: dict[bytes, list[bytes]] = {} + for dll_bytes, sym in imports: + grouped.setdefault(dll_bytes, []).append(sym) + + dll_rvas = {} + for dll_bytes in grouped: + raw = dll_bytes + b"\0" + rva = alloc(len(raw), 2) + put(rva, raw) + dll_rvas[dll_bytes] = rva + + hint_rvas = {} + for dll_bytes, syms in grouped.items(): + for sym in syms: + raw = struct.pack(" bytes: + body = "\n".join(f" {IMAGE_BASE + rva:016X}: {text}" for rva, text in lines) + return f"Dump of file fixture.dll\n\nFile Type: DLL\n\n{body}\n".encode("ascii") + + +def _populate_valid_build_dir(build_dir: Path) -> tuple[dict[str, bytes], dict[str, bytes]]: + pe0, iat0, _ = _build_pe32_plus(imports=[(b"xmem.dll", b"XMemAlloc")]) + pe1, iat1, c_rvas1 = _build_pe32_plus( + imports=[(b"d3d12_xs.dll", b"D3D12SerializeVersionedRootSignature")], + containers=[_make_dxbc_container()], + ) + pe2, _, _ = _build_pe32_plus() + images = { + call_evidence.NAMES[0]: pe0, + call_evidence.NAMES[1]: pe1, + call_evidence.NAMES[2]: pe2, + } + disasm = { + call_evidence.NAMES[0]: _format_disasm([ + (0x2100, f"call qword ptr [{IMAGE_BASE + iat0[(b'xmem.dll', b'XMemAlloc')]:016X}h]"), + ]), + call_evidence.NAMES[1]: _format_disasm([ + (0x2200, f"jmp qword ptr [{IMAGE_BASE + iat1[(b'd3d12_xs.dll', b'D3D12SerializeVersionedRootSignature')]:016X}h]"), + (0x2210, f"lea rcx, [{IMAGE_BASE + c_rvas1[0]:016X}h]"), + ]), + call_evidence.NAMES[2]: b"", + } + build_dir.mkdir(parents=True, exist_ok=True) + for name, blob in images.items(): + (build_dir / name).write_bytes(blob) + return images, disasm + + +def _run_main(argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = call_evidence.main(argv) + except SystemExit as exc: + code = exc.code + if not isinstance(code, int): + if code is not None: + stderr.write(f"{code}\n") + code = 0 if code is None else 1 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class CallEvidenceCliPositiveTests(unittest.TestCase): + def test_atomic_write_creates_nested_dirs_replaces_stale_and_leaves_zero_tmp(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + build_dir = base / "build" + images, disasm = _populate_valid_build_dir(build_dir) + fake_tool = base / "repo" / "tools" / "call_evidence.py" + fake_tool.parent.mkdir(parents=True) + expected_out = (base / "repo" / "out" / "calls" / "six-apis.json").resolve() + + def fake_dumpbin(cmd: list[str]) -> bytes: + return disasm[Path(cmd[-1]).name] + + with ( + mock.patch.object(call_evidence, "__file__", str(fake_tool)), + mock.patch("call_evidence.subprocess.check_output", side_effect=fake_dumpbin), + ): + code, out, err = _run_main([str(build_dir)]) + + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertEqual(Path(out.strip()), expected_out) + self.assertEqual(sorted(p.name for p in expected_out.parent.iterdir()), ["six-apis.json"]) + + parsed = json.loads(expected_out.read_text(encoding="utf-8")) + self.assertEqual(list(parsed.keys()), list(call_evidence.NAMES)) + for name, blob in images.items(): + self.assertEqual(parsed[name]["sha256"], hashlib.sha256(blob).hexdigest()) + self.assertEqual(parsed[call_evidence.NAMES[0]]["calls"]["XMemAlloc"]["sites"][0]["rva"], "0x2100") + self.assertEqual(len(parsed[call_evidence.NAMES[1]]["containers"]), 1) + + # Seed stale bytes and verify atomic overwrite leaves 0 .tmp files. + expected_out.write_text("{stale", encoding="utf-8") + with ( + mock.patch.object(call_evidence, "__file__", str(fake_tool)), + mock.patch("call_evidence.subprocess.check_output", side_effect=fake_dumpbin), + ): + code2, out2, err2 = _run_main([str(build_dir)]) + self.assertEqual(code2, 0, err2) + self.assertEqual(err2, "") + self.assertEqual(Path(out2.strip()), expected_out) + self.assertEqual(sorted(p.name for p in expected_out.parent.iterdir()), ["six-apis.json"]) + self.assertEqual(json.loads(expected_out.read_text(encoding="utf-8")), parsed) + + def test_sys_argv_none_and_main_entrypoint_system_exit(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + build_dir = base / "build" + _, disasm = _populate_valid_build_dir(build_dir) + fake_tool = base / "repo" / "tools" / "call_evidence.py" + fake_tool.parent.mkdir(parents=True) + fake_tool.write_text(TOOL.read_text(encoding="utf-8"), encoding="utf-8") + expected_out = (base / "repo" / "out" / "calls" / "six-apis.json").resolve() + + def fake_dumpbin(cmd: list[str]) -> bytes: + return disasm[Path(cmd[-1]).name] + + with ( + mock.patch.object(call_evidence, "__file__", str(fake_tool)), + mock.patch.object(sys, "argv", [str(fake_tool), str(build_dir)]), + mock.patch("call_evidence.subprocess.check_output", side_effect=fake_dumpbin), + ): + code, out, err = _run_main(None) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(Path(out.strip()), expected_out) + self.assertTrue(expected_out.is_file()) + + # Verify __main__ raises SystemExit(0) on success and SystemExit(1) on PE error. + expected_out.unlink() + stdout, stderr = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", [str(fake_tool), str(build_dir)]), + mock.patch("subprocess.check_output", side_effect=fake_dumpbin), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(fake_tool), run_name="__main__") + self.assertIs(type(exited.exception.code), int) + self.assertEqual(exited.exception.code, 0) + self.assertEqual(stderr.getvalue(), "") + self.assertEqual(Path(stdout.getvalue().strip()), expected_out) + self.assertTrue(expected_out.is_file()) + + (build_dir / call_evidence.NAMES[0]).write_bytes(b"corrupt") + stdout2, stderr2 = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", [str(fake_tool), str(build_dir)]), + redirect_stdout(stdout2), + redirect_stderr(stderr2), + ): + with self.assertRaises(SystemExit) as exited_err: + runpy.run_path(str(fake_tool), run_name="__main__") + self.assertEqual(exited_err.exception.code, 1) + self.assertEqual(stdout2.getvalue(), "") + self.assertNotIn("Traceback", stderr2.getvalue()) + self.assertIn("call_evidence:", stderr2.getvalue()) + + +class CallEvidenceCliNegativeTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_code: int | None, + fragments: tuple[str, ...] = (), + check_subprocess: bool = True, + ) -> str: + code, out, err = _run_main(argv) + if expected_code is None: + self.assertNotEqual(code, 0) + else: + self.assertEqual(code, expected_code, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertTrue(err.strip()) + for fragment in fragments: + self.assertIn(fragment.lower(), err.lower()) + + if check_subprocess: + proc = _run_subprocess(*argv) + if expected_code is None: + self.assertNotEqual(proc.returncode, 0) + else: + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertTrue(proc.stderr.strip()) + for fragment in fragments: + self.assertIn(fragment.lower(), proc.stderr.lower()) + return err + + def test_missing_dir_non_dir_and_missing_dll_rejected_before_inspect(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + missing_dir = base / "missing_dir" + file_input = base / "regular.bin" + file_input.write_bytes(b"data") + empty_dir = base / "empty" + empty_dir.mkdir() + partial_dir = base / "partial" + partial_dir.mkdir() + pe, _, _ = _build_pe32_plus() + (partial_dir / call_evidence.NAMES[0]).write_bytes(pe) + (partial_dir / call_evidence.NAMES[1]).write_bytes(pe) + + with ( + mock.patch.object( + call_evidence, + "inspect", + side_effect=AssertionError("inspect called on invalid directory/inputs"), + ), + mock.patch.object( + call_evidence, + "_write_atomic", + side_effect=AssertionError("_write_atomic called on invalid directory/inputs"), + ), + ): + self._assert_clean_failure([str(missing_dir)], expected_code=2) + self._assert_clean_failure([str(file_input)], expected_code=2, fragments=("not a directory",)) + self._assert_clean_failure([str(empty_dir)], expected_code=2, fragments=("missing expected image",)) + self._assert_clean_failure( + [str(partial_dir)], + expected_code=2, + fragments=("missing expected image", call_evidence.NAMES[2]), + ) + + def test_dll_guards_reject_directory_unreadable_and_symlink_before_inspect(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + build_dir = base / "build" + _populate_valid_build_dir(build_dir) + fake_tool = base / "repo" / "tools" / "call_evidence.py" + fake_tool.parent.mkdir(parents=True) + out_dir = base / "repo" / "out" + + # 1) Expected DLL path is a directory. + dll_dir = build_dir / call_evidence.NAMES[1] + dll_dir.unlink() + dll_dir.mkdir() + with ( + mock.patch.object(call_evidence, "__file__", str(fake_tool)), + mock.patch.object(call_evidence, "inspect", side_effect=AssertionError("inspect called")), + mock.patch.object(call_evidence, "_write_atomic", side_effect=AssertionError("write called")), + ): + self._assert_clean_failure( + [str(build_dir)], + expected_code=1, + fragments=("call_evidence:", "directory"), + check_subprocess=False, + ) + self.assertFalse(out_dir.exists()) + + # 2) Expected DLL path is unreadable (os.access false or open PermissionError). + dll_dir.rmdir() + pe_ok, _, _ = _build_pe32_plus() + dll_dir.write_bytes(pe_ok) + with ( + mock.patch.object(call_evidence, "__file__", str(fake_tool)), + mock.patch.object(call_evidence, "inspect", side_effect=AssertionError("inspect called")), + mock.patch.object(call_evidence, "_write_atomic", side_effect=AssertionError("write called")), + ): + with mock.patch("call_evidence.os.access", return_value=False): + self._assert_clean_failure( + [str(build_dir)], + expected_code=1, + fragments=("call_evidence:", "not readable"), + check_subprocess=False, + ) + with mock.patch.object(Path, "open", side_effect=PermissionError("denied")): + self._assert_clean_failure( + [str(build_dir)], + expected_code=1, + fragments=("call_evidence:", "denied"), + check_subprocess=False, + ) + self.assertFalse(out_dir.exists()) + + # 3) Expected DLL path is a live or dangling symlink. + target_dll = base / "real_target.dll" + target_dll.write_bytes(pe_ok) + dll_link = build_dir / call_evidence.NAMES[2] + dll_link.unlink() + try: + dll_link.symlink_to(target_dll) + except OSError as exc: + if getattr(exc, "winerror", None) != 1314: + raise + self.skipTest("this Windows account cannot create symlinks (WinError 1314)") + + with ( + mock.patch.object(call_evidence, "__file__", str(fake_tool)), + mock.patch.object(call_evidence, "inspect", side_effect=AssertionError("inspect called")), + mock.patch.object(call_evidence, "_write_atomic", side_effect=AssertionError("write called")), + ): + self._assert_clean_failure( + [str(build_dir)], + expected_code=1, + fragments=("call_evidence:", "symlink"), + check_subprocess=False, + ) + dll_link.unlink() + dll_link.symlink_to(base / "dangling_target.dll") + self._assert_clean_failure( + [str(build_dir)], + expected_code=1, + fragments=("call_evidence:", "symlink"), + check_subprocess=False, + ) + self.assertFalse(out_dir.exists()) + + def test_output_guards_reject_inside_root_dir_and_file_parent_before_inspect(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + build_dir = base / "build" + _populate_valid_build_dir(build_dir) + repo_dir = base / "repo" + fake_tool = repo_dir / "tools" / "call_evidence.py" + fake_tool.parent.mkdir(parents=True) + out_file = repo_dir / "out" / "calls" / "six-apis.json" + + # 1) Output inside root (repo_dir has valid DLLs, and out/calls has valid DLLs). + _populate_valid_build_dir(repo_dir) + nested_calls = repo_dir / "out" / "calls" + _populate_valid_build_dir(nested_calls) + with ( + mock.patch.object(call_evidence, "__file__", str(fake_tool)), + mock.patch.object(call_evidence, "inspect", side_effect=AssertionError("inspect called")), + mock.patch.object(call_evidence, "_write_atomic", side_effect=AssertionError("write called")), + ): + for overlapping in (repo_dir, nested_calls): + with self.subTest(overlapping=overlapping.name): + self._assert_clean_failure( + [str(overlapping)], + expected_code=2, + fragments=("separate from the report directory",), + check_subprocess=False, + ) + self.assertFalse(out_file.exists()) + shutil.rmtree(repo_dir / "out") + + # 2) Output path is an existing directory. + out_file.mkdir(parents=True) + with ( + mock.patch.object(call_evidence, "__file__", str(fake_tool)), + mock.patch.object(call_evidence, "inspect", side_effect=AssertionError("inspect called")), + mock.patch.object(call_evidence, "_write_atomic", side_effect=AssertionError("write called")), + ): + self._assert_clean_failure( + [str(build_dir)], + expected_code=1, + fragments=("call_evidence:", "directory"), + check_subprocess=False, + ) + out_file.rmdir() + + # 3) Output parent ('calls') is a regular file. + out_file.parent.rmdir() + out_file.parent.write_text("keep-calls", encoding="utf-8") + with ( + mock.patch.object(call_evidence, "__file__", str(fake_tool)), + mock.patch.object(call_evidence, "inspect", side_effect=AssertionError("inspect called")), + mock.patch.object(call_evidence, "_write_atomic", side_effect=AssertionError("write called")), + ): + self._assert_clean_failure( + [str(build_dir)], + expected_code=1, + fragments=("call_evidence:", "not a directory"), + check_subprocess=False, + ) + self.assertEqual(out_file.parent.read_text(encoding="utf-8"), "keep-calls") + + # 4) Output ancestor ('out') is a regular file. + out_file.parent.unlink() + out_file.parent.parent.rmdir() + out_file.parent.parent.write_text("keep-out", encoding="utf-8") + with ( + mock.patch.object(call_evidence, "__file__", str(fake_tool)), + mock.patch.object(call_evidence, "inspect", side_effect=AssertionError("inspect called")), + mock.patch.object(call_evidence, "_write_atomic", side_effect=AssertionError("write called")), + ): + self._assert_clean_failure( + [str(build_dir)], + expected_code=1, + fragments=("call_evidence:", "not a directory"), + check_subprocess=False, + ) + self.assertEqual(out_file.parent.parent.read_text(encoding="utf-8"), "keep-out") + + def test_output_symlink_and_symlink_parent_rejected_before_inspect(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + build_dir = base / "build" + _populate_valid_build_dir(build_dir) + repo_dir = base / "repo" + fake_tool = repo_dir / "tools" / "call_evidence.py" + fake_tool.parent.mkdir(parents=True) + out_file = repo_dir / "out" / "calls" / "six-apis.json" + out_file.parent.mkdir(parents=True) + real_target = base / "real_report.json" + real_target.write_text("untouched", encoding="utf-8") + + try: + out_file.symlink_to(real_target) + except OSError as exc: + if getattr(exc, "winerror", None) != 1314: + raise + self.skipTest("this Windows account cannot create symlinks (WinError 1314)") + + with ( + mock.patch.object(call_evidence, "__file__", str(fake_tool)), + mock.patch.object(call_evidence, "inspect", side_effect=AssertionError("inspect called")), + mock.patch.object(call_evidence, "_write_atomic", side_effect=AssertionError("write called")), + ): + self._assert_clean_failure( + [str(build_dir)], + expected_code=1, + fragments=("call_evidence:", "symlink"), + check_subprocess=False, + ) + out_file.unlink() + out_file.symlink_to(base / "missing_report.json") + self._assert_clean_failure( + [str(build_dir)], + expected_code=1, + fragments=("call_evidence:", "symlink"), + check_subprocess=False, + ) + out_file.unlink() + out_file.parent.rmdir() + out_file.parent.symlink_to(base / "dangling_calls_dir") + self._assert_clean_failure( + [str(build_dir)], + expected_code=1, + fragments=("call_evidence:", "not a directory"), + check_subprocess=False, + ) + self.assertEqual(real_target.read_text(encoding="utf-8"), "untouched") + + def test_corrupt_pe_and_dumpbin_failures_exit_1_without_creating_output(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + build_dir = base / "build" + _populate_valid_build_dir(build_dir) + fake_tool = base / "repo" / "tools" / "call_evidence.py" + fake_tool.parent.mkdir(parents=True) + out_dir = base / "repo" / "out" + + # 1) dumpbin SubprocessError and FileNotFoundError on valid synthetic PEs. + with mock.patch.object(call_evidence, "__file__", str(fake_tool)): + with mock.patch( + "call_evidence.subprocess.check_output", + side_effect=subprocess.CalledProcessError(1, ["dumpbin"]), + ): + self._assert_clean_failure( + [str(build_dir)], + expected_code=1, + fragments=("call_evidence:",), + check_subprocess=False, + ) + with mock.patch( + "call_evidence.subprocess.check_output", + side_effect=FileNotFoundError("dumpbin missing"), + ): + self._assert_clean_failure( + [str(build_dir)], + expected_code=1, + fragments=("call_evidence:", "dumpbin missing"), + check_subprocess=False, + ) + self.assertFalse(out_dir.exists()) + + # 2) Corrupt PE bytes (tested both in-process and via real subprocess). + (build_dir / call_evidence.NAMES[0]).write_bytes(b"not a valid PE32+ image") + with mock.patch.object(call_evidence, "__file__", str(fake_tool)): + self._assert_clean_failure( + [str(build_dir)], + expected_code=1, + fragments=("call_evidence:",), + ) + self.assertFalse(out_dir.exists()) + + def test_atomic_write_failures_leave_zero_tmp_files_and_preserve_existing_output(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + build_dir = base / "build" + _, disasm = _populate_valid_build_dir(build_dir) + fake_tool = base / "repo" / "tools" / "call_evidence.py" + fake_tool.parent.mkdir(parents=True) + out_file = base / "repo" / "out" / "calls" / "six-apis.json" + out_file.parent.mkdir(parents=True) + out_file.write_text("prior-report", encoding="utf-8") + + def fake_dumpbin(cmd: list[str]) -> bytes: + return disasm[Path(cmd[-1]).name] + + with ( + mock.patch.object(call_evidence, "__file__", str(fake_tool)), + mock.patch("call_evidence.subprocess.check_output", side_effect=fake_dumpbin), + mock.patch.object(Path, "replace", side_effect=OSError("simulated replace failure")), + ): + self._assert_clean_failure( + [str(build_dir)], + expected_code=1, + fragments=("call_evidence:", "simulated replace failure"), + check_subprocess=False, + ) + self.assertEqual(out_file.read_text(encoding="utf-8"), "prior-report") + self.assertEqual(sorted(p.name for p in out_file.parent.iterdir()), ["six-apis.json"]) + + with ( + mock.patch.object(call_evidence, "__file__", str(fake_tool)), + mock.patch("call_evidence.subprocess.check_output", side_effect=fake_dumpbin), + mock.patch("call_evidence.tempfile.NamedTemporaryFile", side_effect=OSError("disk full")), + ): + self._assert_clean_failure( + [str(build_dir)], + expected_code=1, + fragments=("call_evidence:", "disk full"), + check_subprocess=False, + ) + self.assertEqual(out_file.read_text(encoding="utf-8"), "prior-report") + self.assertEqual(sorted(p.name for p in out_file.parent.iterdir()), ["six-apis.json"]) + + def test_argparse_negative_controls_py314_safe(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + build_dir = Path(tmp) / "build" + _populate_valid_build_dir(build_dir) + for bad_argv in ( + [], + [str(build_dir), str(build_dir)], + [str(build_dir), "--unknown-flag"], + ): + with self.subTest(argv=bad_argv): + self._assert_clean_failure(bad_argv, expected_code=2) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/call_evidence.py b/tools/call_evidence.py index 5261d880e..0d8a2865d 100644 --- a/tools/call_evidence.py +++ b/tools/call_evidence.py @@ -2,12 +2,15 @@ import argparse from collections import defaultdict +from collections.abc import Sequence import hashlib import json +import os from pathlib import Path import re import struct import subprocess +import tempfile import pefile @@ -112,7 +115,63 @@ def inspect(path): containers=shader_containers(data, pe, memory)) -def main(argv=None): +def _validate_inputs(root: Path, parser: argparse.ArgumentParser) -> None: + missing = [] + for name in NAMES: + image = root / name + if image.is_symlink(): + raise ValueError(f"Expected image must not be a symlink: {image}") + if not image.exists(): + missing.append(name) + continue + if image.is_dir(): + raise IsADirectoryError(f"Expected image path is a directory: {image}") + if not image.is_file(): + raise ValueError(f"Expected image must be a regular file: {image}") + if not os.access(image, os.R_OK): + raise PermissionError(f"Expected image is not readable: {image}") + with image.open("rb"): + pass + if missing: + parser.error(f"Missing expected image(s) in {root}: {', '.join(missing)}") + + +def _validate_output(output: Path) -> None: + if output.is_symlink(): + raise ValueError(f"Output path must not be a symlink: {output}") + if output.is_dir(): + raise IsADirectoryError(f"Output path is a directory: {output}") + if output.exists() and not output.is_file(): + raise ValueError(f"Output path is not a regular file: {output}") + for parent in output.parents: + if parent.is_file() or ((parent.exists() or parent.is_symlink()) and not parent.is_dir()): + raise NotADirectoryError(f"Output parent is not a directory: {parent}") + + +def _write_atomic(path: Path, content: str) -> None: + """Write UTF-8 text to a sibling temp file and atomically replace path, leaving 0 temp files on failure.""" + path.parent.mkdir(parents=True, exist_ok=True) + tmp_path: Path | None = None + try: + with tempfile.NamedTemporaryFile( + mode="w", + encoding="utf-8", + newline="\n", + dir=path.parent, + prefix=f".{path.stem}.", + suffix=".tmp", + delete=False, + ) as handle: + tmp_path = Path(handle.name) + handle.write(content) + tmp_path.replace(path) + except BaseException: + if tmp_path is not None: + tmp_path.unlink(missing_ok=True) + raise + + +def main(argv: Sequence[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("directory", type=Path) args = parser.parse_args(argv) @@ -123,20 +182,18 @@ def main(argv=None): if not root.is_dir(): parser.error(f"Input path is not a directory: {root}") output = Path(__file__).resolve().parents[1] / "out/calls/six-apis.json" - if output.resolve().is_relative_to(root): - parser.error("Choose a build directory separate from the report directory") - missing = [name for name in NAMES if not (root / name).is_file()] - if missing: - parser.error(f"Missing expected image(s) in {root}: {', '.join(missing)}") try: + if output.is_relative_to(root) or output.resolve().is_relative_to(root): + parser.error("Choose a build directory separate from the report directory") + _validate_output(output) + _validate_inputs(root, parser) rows = {name: inspect(root / name) for name in NAMES} - except (OSError, ValueError, pefile.PEFormatError, subprocess.SubprocessError) as exc: + _write_atomic(output, json.dumps(rows, indent=2) + "\n") + except (OSError, ValueError, struct.error, pefile.PEFormatError, subprocess.SubprocessError) as exc: parser.exit(1, f"call_evidence: {exc}\n") - output.parent.mkdir(parents=True, exist_ok=True) - output.write_text(json.dumps(rows, indent=2) + "\n", encoding="utf-8") print(output) return 0 if __name__ == "__main__": - main() + raise SystemExit(main()) From c452959f4f4b777a70cb123edb750c3d301ed730 Mon Sep 17 00:00:00 2001 From: RavenCurseBurg Date: Thu, 26 Nov 2026 10:59:19 +0800 Subject: [PATCH 094/240] startup: share the bound render target members across draw paths (#2706) Co-authored-by: RavenCurseBurg <360931527+RavenCurseBurg@users.noreply.github.com> --- src/startup_stubs/d3d12_xs_device.cpp | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index a6e66c854..06265004d 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -2501,8 +2501,6 @@ struct Pass { UINT stencil_reference = 0; // last guest OMSetStencilRef on this recording UINT target_count = 0; ID3D12Resource* target0 = nullptr; // desktop resource of render target 0 (for per-draw dumps) - ID3D12Resource* bound_targets[8]{}; - ID3D12Resource* bound_depth = nullptr; ID3D12Resource* trace_targets[8]{}; ID3D12Resource* trace_depth = nullptr; ID3D12Resource* bound_targets[8]{}; // the last accepted bind: targets [0, target_count) and the depth texture @@ -3584,8 +3582,6 @@ void __stdcall list_targets(Wrapper* self, UINT count, const D3D12_CPU_DESCRIPTO } } if (!count && !dsv_ptr) return; - std::copy_n(targets, 8, pass.bound_targets); - pass.bound_depth = dsv_target; if (red_producers().enabled()) { std::copy_n(targets, 8, pass.trace_targets); pass.trace_depth = dsv_target; From d1cf668866c33d9f2445e56af276f854e80e2afb Mon Sep 17 00:00:00 2001 From: JB2WIN Date: Thu, 26 Nov 2026 03:59:31 +0100 Subject: [PATCH 095/240] startup: add the SDWA forms of v_cmp_class_f16 on top of the main helper (#2020) The plain e32/e64 register and encoded-literal path, including the 0x7c01 census form, landed with #2092 and is used unchanged. It still refused the SDWA spelling outright. This lowers v_cmp_class_f16_sdwa and v_cmpx_class_f16_sdwa through the same class16() helper and the same predicate/exec/destination code. src0_sel DWORD and WORD_0 are accepted on a plain register (class16 reads bits [15:0] itself); src1_sel selects and sign-extends the integer mask as the binary32 class compare does. WORD_1, bytes, sext() on src0, the abs/neg spellings, a missing or repeated select, a float source or mask and a bad destination are refused, WORD_1 and bytes with the existing "SDWA form of" reason. New check startup_gfx2hlsl_cmp_class_f16_sdwa_check.py: accepted forms times destination/select/register file against a struct 'e' reference with garbage in the upper half, refusals, and three mutated helpers (upper half read, sNaN/qNaN swapped, +0/-0 swapped) that must disagree. The draw mode (warp and hardware) draws a register with a qNaN upper half, a clean register, the encoded literal 0x7c01, the e32 spelling and both SDWA selects against one reference image; classifying the upper half, swapping sNaN/qNaN and ignoring the BYTE_1 mask select must each fail it. AI-assisted (Claude Code). Co-authored-by: Claude Opus 5.5 Co-authored-by: tedin7 --- .github/workflows/windows.yml | 4 +- AGENTS.md | 1 + CMakeLists.txt | 7 + ...artup_gfx2hlsl_cmp_class_f16_sdwa_check.py | 448 ++++++++++++++++++ tools/startup/gfx2hlsl.py | 17 +- 5 files changed, 473 insertions(+), 4 deletions(-) create mode 100644 tests/startup_gfx2hlsl_cmp_class_f16_sdwa_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 92a27f4bd..6a9720799 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -314,7 +314,8 @@ jobs: tests/startup_build_rev_check.py \ tests/startup_gfx2hlsl_bit_alu_check.py \ tests/startup_gfx2hlsl_int_alu_check.py \ - tests/startup_gfx2hlsl_interp_f16_check.py tests/startup_gfx2hlsl_interp_p2_hi_check.py \ + tests/startup_gfx2hlsl_interp_f16_check.py \ + tests/startup_gfx2hlsl_interp_p2_hi_check.py \ tests/startup_gfx2hlsl_sgpr_spill_check.py \ tests/startup_gfx2hlsl_spill_branches_check.py \ tests/startup_gfx2hlsl_mad_check.py \ @@ -331,6 +332,7 @@ jobs: tests/startup_gfx2hlsl_s_quadmask_check.py \ tests/startup_gfx2hlsl_fma_mix_check.py \ tests/startup_gfx2hlsl_shift64_check.py \ + tests/startup_gfx2hlsl_cmp_class_f16_sdwa_check.py \ tests/startup_gfx2hlsl_mul_hi_i32_check.py \ tests/startup_gfx2hlsl_mul_mad_i24_check.py \ tests/startup_gfx2hlsl_vopc_sdwa_check.py \ diff --git a/AGENTS.md b/AGENTS.md index d80240aa5..5be74bb03 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -257,6 +257,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_spill_branches_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_shift64_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_vopc_sdwa_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_cmp_class_f16_sdwa_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_cmp16_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_f32_lg_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_f32_nan_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 304452379..4571ab2b0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3437,6 +3437,9 @@ if(EXISTS "${INTAKE_PYTHON}") # The binary16 class comparison (#1855). add_test(NAME startup_gfx2hlsl_cmp_class_f16 COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_cmp_class_f16_check.py") + # The SDWA forms of the binary16 class comparison and their negative controls; the draws are registered below. + add_test(NAME startup_gfx2hlsl_cmp_class_f16_sdwa COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_cmp_class_f16_sdwa_check.py") # The 16-bit vector ALU: add, sub, mul, min, max, fma forms and the i16/u16 conversions (#1723). add_test(NAME startup_gfx2hlsl_f16_alu COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_f16_alu_check.py") @@ -3985,6 +3988,10 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_vopc_sdwa_check.py" draw "${DXC_EXECUTABLE}" "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_gfx2hlsl_vopc_sdwa_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + add_test(NAME startup_gfx2hlsl_cmp_class_f16_sdwa_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_cmp_class_f16_sdwa_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_cmp_class_f16_sdwa_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) add_test(NAME startup_gfx2hlsl_dpp_quad_broadcast_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_dpp_quad_broadcast_check.py" draw "${DXC_EXECUTABLE}" "$" ${adapter} $<$:${STARTUP_FXC}>) diff --git a/tests/startup_gfx2hlsl_cmp_class_f16_sdwa_check.py b/tests/startup_gfx2hlsl_cmp_class_f16_sdwa_check.py new file mode 100644 index 000000000..a800179f3 --- /dev/null +++ b/tests/startup_gfx2hlsl_cmp_class_f16_sdwa_check.py @@ -0,0 +1,448 @@ +"""The SDWA forms of `v_cmp_class_f16` / `v_cmpx_class_f16` in tools/startup/gfx2hlsl.py. + + (no arguments) translation controls and value checks, pure Python + draw [fxc] + compile source-built pixel programs with FXC ps_5_1 when given and with DXC + ps_6_0, draw 16 x 16 pixels and compare every pixel with a CPU reference + +The plain e32/e64 register and encoded-literal path (including the census form `0x7c01`) is covered by +startup_gfx2hlsl_cmp_class_f16_check.py. This file covers what that one does not: + + * SDWA: `src0_sel` DWORD and WORD_0 are lowered to the shared class16() helper on the register word (which reads + bits [15:0] only); `src1_sel` selects and sign-extends the integer mask as for the binary32 class compare. WORD_1, + each byte, sext() on src0, the abs/neg spellings, a missing select, a float mask and a bad destination are refused. + Words are built with the VOP_SDWA9Be layout tools/disasm_rdna2.py reads, and two of them are compared with the + bytes clang -cc1as (LLVM 15, gfx1013) emits for the same text. + * Value level: the emitted predicate is evaluated over boundary patterns of every class with garbage in the upper + half and against an independent reference written from the binary16 layout (struct 'e'). Three mutated helpers + (upper half read, sNaN and qNaN swapped, +0 and -0 swapped) must disagree with that reference. + * Draw: a register holding 0x7c01 in its low half (sNaN, class bit 0x1), a register with the same low half and a + qNaN (0x7e00, class bit 0x2) in the upper half, the encoded literal 0x7c01, the e32 spelling and both SDWA + selects all give the same class: the 16 x 16 pixels keep or discard by the class bit against a per-pixel mask, + and every variant must match one reference image. Two controls must fail it: classifying the upper half instead + of the low one (the independent high-half control) and swapping the sNaN/qNaN return values. A third reads the + whole mask dword instead of the BYTE_1 select. + +Encoded NEG and inline float constants are not lowered through the SDWA path and stay refused on the plain path +(tests/startup_gfx2hlsl_cmp_class_f16_check.py). +""" +import math +import re +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import Expr # noqa: E402 +from startup_gfx2hlsl_vopc_sdwa_check import ( # noqa: E402 + CLEAR, EXPORT_WORDS, HEIGHT, MASK, MUL_WORDS, MULTIPLIER, PACKED, WIDTH, draw, field, source, vopc_sdwa, + words_file) +from startup_image_3d_check import FULLSCREEN_VS, VS_WORDS, compile_hlsl, root_blob # noqa: E402 + +failures = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH'}") + if not condition: + failures.append(label) + if detail: + print(' ' + detail) + + +CMP_CLASS_F16, CMPX_CLASS_F16 = 0x8F, 0x9F # VOPC e32 opcodes +SGPR_DST = 6 +V1, V2 = 0x101, 0x102 + + +class Probe(G.Stage): + """A Stage with no pipeline: enough state for decoded instructions to be translated.""" + + def __init__(self, exec_known=True): + self.lines, self.sym = [], {} + self.used_s, self.used_v, self.uniform_v = set(), set(), set() + self.masks = set() + self.exec_known = exec_known + + +def translate(code, exec_known=True): + decoded = G.decode(code) + assert len(decoded) == 1 and decoded[0][1] == 8, decoded + stage = Probe(exec_known) + stage.one(decoded[0][2], decoded[0][3]) + return decoded[0][3], stage + + +def refusal_of(name, asm): + try: + stage = Probe() + stage.one(name, asm) + except G.Unsupported as error: + return str(error) + return None + + +# ---- the independent reference and the helper under test ------------------------------------------------------- +def ref_class16(word): + """The class bit of S0[15:0] from the binary16 layout read through struct 'e'; the upper half is ignored.""" + low = word & 0xFFFF + value = struct.unpack(' 0) + _asm, stage = translate(vopc_sdwa(CMP_CLASS_F16, source('v', 2), source('v', 1), None, 'WORD_0', 'DWORD')) + for name in HELPER_MUTATIONS: + bad = [(hex(word), hex(upper)) for word, _bit in BOUNDARIES for upper in UPPERS + if predicate(stage, (upper << 16) | word, ref_class16(word), helper=mutated(name)) != 1] + check('control %s fails the emitted predicate on a boundary pattern' % name, bool(bad)) + + +# ---- the draw ------------------------------------------------------------------------------------------------- +LOW = 0x7C01 # a signaling NaN: class bit 0x1 +UPPER_QNAN = 0x7E00 # a quiet NaN in the upper half: class bit 0x2, what a translation reading bits [31:16] sees + + +def v_mov_literal(vdst, literal): + return struct.pack('> 16u)'), + 'sNaN and qNaN swapped': ('(h & 0x0200u) != 0u ? 0x2u : 0x1u', '(h & 0x0200u) != 0u ? 0x1u : 0x2u'), +} + + +def pixel_words(name): + return MUL_WORDS + VARIANTS[name][1] + EXPORT_WORDS + + +def pixel_hlsl(name, control=None): + text = G.Pipeline(VS_WORDS, pixel_words(name), root_blob(), ps_hw_inputs=PACKED).hlsl_ps() + if control: + old, new = CONTROLS[control] + if old == 'class16(v2)' and name.startswith('encoded literal'): + old, new = 'class16(0x00007c01u)', 'class16(0x00007c01u >> 16u)' + assert text.count(old) == 1, (name, control, old) + text = text.replace(old, new) + return text + + +def image(select, class_bit): + words = [] + for y in range(HEIGHT): + for x in range(WIDTH): + position = x | (y << 16) + mask = (position * MULTIPLIER) & MASK + if select: + mask = field(mask, select, False) + words += [position if mask & class_bit else CLEAR] * 4 + return words + + +def check_fixture(): + for name, (text, _words, select) in VARIANTS.items(): + decoded = [asm for _o, _s, _n, asm in G.decode(pixel_words(name))] + wanted = (PS_HEAD + text + '\nexp mrt0 v0, v0, v0, v0 done vm\ns_endpgm').splitlines() + wanted = [line.replace('v_mov_b32_e32', 'v_mov_b32_e32') for line in wanted] + check('%s: fixture decodes to its source' % name, decoded == wanted, '%s\n%s' % (decoded, wanted)) + hlsl = pixel_hlsl(name) + check('%s: lowered through class16 behind exec' % name, + 'class16(' in hlsl and 'if (!(exec & 1)) discard;' in hlsl, hlsl) + reference = image(select, 0x1) + kept = sum(reference[i] != CLEAR for i in range(0, len(reference), 4)) + check('%s: reference keeps %d of %d pixels' % (name, kept, WIDTH * HEIGHT), 0 < kept < WIDTH * HEIGHT) + # The controls must be distinguishable by the image, or the draw could not tell them apart. + check('classifying the upper half (class bit 0x2) changes the image', image(None, 0x1) != image(None, 0x2)) + check('swapping sNaN and qNaN changes the image', image(None, 0x1) != image(None, 0x2)) + check('ignoring the BYTE_1 select changes the image', image('BYTE_1', 0x1) != image(None, 0x1)) + for name in VARIANTS: + for control in CONTROLS: + pixel_hlsl(name, control) # every control applies to exactly one place in every variant + + +def check_draw(dxc, renderer, adapter, fxc=None): + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + plain = words_file(directory, 'plain', image(None, 0x1)) + selected = words_file(directory, 'selected', image('BYTE_1', 0x1)) + upper = words_file(directory, 'upper', image(None, 0x2)) + for kind, compiler, vs_profile, ps_profile in compilers: + vs = compile_hlsl(compiler, kind, FULLSCREEN_VS, 'vs_%s' % kind, vs_profile, directory) + for index, (name, (_text, _words, select)) in enumerate(VARIANTS.items()): + ps = compile_hlsl(compiler, kind, pixel_hlsl(name), 'ps_%d_%s' % (index, kind), ps_profile, directory) + run = draw(renderer, adapter, vs, ps, selected if select else plain) + check('%s %s: %s matches all %d pixels' % (kind, adapter, name, WIDTH * HEIGHT), + run.returncode == 0 and 'all %d pixels matched' % (WIDTH * HEIGHT) in run.stdout, + run.stdout + run.stderr) + for control in CONTROLS: + name = 'register, upper qNaN, WORD_0 / DWORD' + bad = compile_hlsl(compiler, kind, pixel_hlsl(name, control), 'ps_bad_%s_%s' % (control[:5], kind), + ps_profile, directory) + run = draw(renderer, adapter, vs, bad, plain) + check('%s %s: control %s fails the draw' % (kind, adapter, control), + run.returncode != 0 and 'pixel mismatch' in run.stderr, run.stdout + run.stderr) + # A translation that classified the upper half draws the image of the upper class bit. + bad = compile_hlsl(compiler, kind, pixel_hlsl('register, upper qNaN, WORD_0 / DWORD', + 'upper half classified'), 'ps_up_%s' % kind, ps_profile, + directory) + run = draw(renderer, adapter, vs, bad, upper) + check('%s %s: upper-half control matches the upper-class image' % (kind, adapter), + run.returncode == 0, run.stdout + run.stderr) + # The select control: the same program with the mask read as a whole dword draws the plain image. + name = 'register, upper qNaN, WORD_0 / BYTE_1' + text = pixel_hlsl(name) + assert text.count('((v1 >> 8u) & 0xffu)') == 1, text + bad = compile_hlsl(compiler, kind, text.replace('((v1 >> 8u) & 0xffu)', 'v1'), 'ps_sel_%s' % kind, + ps_profile, directory) + run = draw(renderer, adapter, vs, bad, selected) + check('%s %s: mask select control fails the draw' % (kind, adapter), + run.returncode != 0 and 'pixel mismatch' in run.stderr, run.stdout + run.stderr) + run = draw(renderer, adapter, vs, bad, plain) + check('%s %s: mask select control matches the whole-dword image' % (kind, adapter), + run.returncode == 0, run.stdout + run.stderr) + + +def main(): + if len(sys.argv) == 1: + controls() + check_fixture() + elif sys.argv[1] == 'draw': + check_fixture() + check_draw(*sys.argv[2:]) + else: + raise SystemExit(__doc__) + if failures: + print('FAIL') + for text in failures: + print(' ' + text) + sys.exit(1) + print('PASS') + + +if __name__ == '__main__': + main() diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 061534962..d5e92922c 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -7362,8 +7362,6 @@ def compare(self, base, ops, mods=()): f16 = name.endswith('_f16') writes_exec = name in ('v_cmpx_class_f32', 'v_cmpx_class_f16') sdwa = name != base - if f16 and sdwa: - raise Unsupported('SDWA form of %s' % name) if sdwa: self.check_compare_sdwa_destination(base, writes_exec, ops) if len(ops) == 3: @@ -7373,7 +7371,20 @@ def compare(self, base, ops, mods=()): dst, (value, mask) = 'exec', ops else: raise Unsupported('%s with %d operands' % (base, len(ops))) - if sdwa: + if sdwa and f16: + # SDWA half class: classes bits [15:0] of a plain register. src0_sel DWORD and WORD_0 both + # leave those bits where class16 reads them; WORD_1, a byte, sext() and the abs/neg spellings + # (which print |v|, -v, abs(), neg()) would classify other bits, so they are refused. + selections = [m for m in mods if m.startswith('src0_sel:')] + if selections not in (['src0_sel:DWORD'], ['src0_sel:WORD_0']): + raise Unsupported('SDWA form of %s with %s' % (name, ' '.join(selections) or 'no src0_sel')) + if not reg_range(value): + raise Unsupported('%s with source %s' % (base, value)) + if mask in FLOATS: + raise Unsupported('%s mask %s: expected an integer class mask' % (base, mask)) + _word, mask = self.compare_sdwa_sources(base, 'u32', [value, mask], mods) + value = self.u(value) + elif sdwa: value, mask = self.compare_sdwa_sources(base, 'u32', [value, mask], mods, float_src0=True) elif f16: # abs() and - apply to bit 15 of the half, before the class test. From d5ea71b27f43b9646b75b8445a28e5893548f448 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?As=C4=B1m=20Mirza=20=C3=87iftler?= <113895866+Asimmimx@users.noreply.github.com> Date: Thu, 26 Nov 2026 06:03:07 +0300 Subject: [PATCH 096/240] shader: lower compute s_bitset0_b32 and s_bitset1_b32 (#1579) The SOP1 forms clear or set bit src0[4:0] of sD and keep its other bits (RDNA ISA: D.u32[S0.u32[4:0]] = 0 or 1, SCC not written; LLVM ties sdst to an sdst_in operand for both). They read sD as well as write it, so the compute store lowering accepts them in the scalar ALU on known words only when sD already holds a known word and src0 is a known SGPR word, an inline constant or a 32-bit literal. The result is the inline expression sD & ~(1u << (s & 31u)) or sD | (1u << (s & 31u)). Other forms stop with the existing scalar ALU diagnostics. tests/compute_salu_bitset_check.py dispatches one invocation over eight root constant words with two constant sets: bit 0, bit 31 through a runtime index and the inline constants 63 and -1, runtime indices 0x47, 0x20 and 0xffffffe3, already-set and already-clear bits, and a destination that is also the source. Expected words come from a CPU bit-list reference and are also listed by hand. Swapped set and clear, an unmasked index, a dropped destination, the other run's words and mutated translations must fail the readback. The translator controls refuse unknown, descriptor, table, group-ID, saved-exec and pending destinations, unknown and wide sources, s106, a vector source, the 64-bit forms, an oversized chain and a result used as an address. Verified with the new controls and draw modes on WARP, and the existing compute_store_check.py controls and draw-guard-read on WARP. Co-authored-by: tedin7 --- CMakeLists.txt | 5 + docs/experiments.md | 11 ++ tests/compute_salu_bitset_check.py | 216 +++++++++++++++++++++++++++++ tools/compute_store_aot.py | 13 ++ 4 files changed, 245 insertions(+) create mode 100644 tests/compute_salu_bitset_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 4571ab2b0..a8f8ba267 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -9974,6 +9974,11 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(compute_store_aot_gfx1013_gather4_l_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/compute_store_aot_gfx1013_gather4_l_${adapter}.txt") + add_test(NAME compute_store_aot_salu_bitset_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/compute_salu_bitset_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(compute_store_aot_salu_bitset_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/compute_store_aot_salu_bitset_${adapter}.txt") add_test(NAME compute_store_aot_mimg_store_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/compute_store_check.py" draw-mimg-store "${DXC_EXECUTABLE}" "$" ${adapter}) diff --git a/docs/experiments.md b/docs/experiments.md index 228af5c6b..8bd30b84c 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -6781,6 +6781,17 @@ The result becomes an inline HLSL expression, like a vector result, and a vector The check assembles one fixture that chains all six operations over the cap word and the bound, and requires the decoded program to lower to the same HLSL as its text. +#### Single-bit set and clear + +The SOP1 forms `s_bitset0_b32 sD, s` and `s_bitset1_b32 sD, s` clear or set bit `s[4:0]` of `sD` and keep its other bits (RDNA ISA: `D.u32[S0.u32[4:0]] = 0` or `1`; SCC is not written). They read `sD` as well as write it, so `sD` must already hold a known word, and `s` is a known word as above. The result is `sD & ~(1u << (s & 31u))` or `sD | (1u << (s & 31u))`. A destination that holds no known word (an unwritten SGPR, a descriptor, the table pointer, a group ID, the saved exec mask, or a load still waiting), an unknown or wider-than-32-bit source, a destination past s105, a vector source and the 64-bit forms stop the lowering, as does an expression over 1024 characters. + +`tests/compute_salu_bitset_check.py` dispatches one invocation that applies both forms to eight root constant words and stores eight results. Between its two constant sets it sets bit 0, clears and sets bit 31 (through a runtime index, the inline constants `63` and `-1`), uses runtime indices above 31 (`0x47`, `0x20`, `0xffffffe3`), sets bits that are already set, clears bits that are already clear, and reads a destination that is also the source. A CPU reference that rewrites one entry of the word's bit list gives the expected words, and the check also lists them as hand-worked values. Swapped set and clear, an unmasked index, a dropped destination and the other run's words must each fail the readback, and so must mutated translations. `controls` runs the translator checks only: + +```powershell +.\out\pe-env\Scripts\python.exe -B tests/compute_salu_bitset_check.py controls +ctest --preset dev --no-tests=error -R '^compute_store_aot_salu_bitset_warp$' -V +``` + #### Scalar bit-field extract `s_bfe_u32 sD, S0, S1` and `s_bfe_i32 sD, S0, S1` (SOP2) extract a `S1[22:16]`-bit field starting at `S1[4:0]` from a known 32-bit scalar word `S0`, zero- or sign-extending to 32 bits (`0` when `S1[22:16] == 0`, and `S0 >> S1[4:0]` when `S1[4:0] + S1[22:16] > 32`). `SCC` is written (`D != 0`) but unread in this subset. Both lower to explicit HLSL helpers (`s_bfe_u32` and `s_bfe_i32`) emitted only when referenced, so a width of `0` returns `0` rather than shifting by `32`, and every shift count stays in `0..31`. diff --git a/tests/compute_salu_bitset_check.py b/tests/compute_salu_bitset_check.py new file mode 100644 index 000000000..cfc415dbe --- /dev/null +++ b/tests/compute_salu_bitset_check.py @@ -0,0 +1,216 @@ +"""Check the compute lowering of s_bitset0_b32 and s_bitset1_b32 on known scalar words.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import compute_store_check as base + +aot = base.aot + +# One invocation reads eight root constant words c0..c7 and stores eight words at u0 words 4..11. Each SOP1 bitset +# reads and writes its destination SGPR: it clears (bitset0) or sets (bitset1) bit src0[4:0] and keeps the rest. +# w4 = c0 with bit c1[4:0] set (runtime destination and index) +# w5 = c2 with bit c3[4:0] cleared +# w6 = c4 with bit c5[4:0] set (c5 is above 31 in both runs) +# w7 = w4 with bit 4 set again (a copy of a bitset result; bit 4 is already set) +# w8 = c6 with bit 31 cleared (inline 63: only bits [4:0] count) +# w9 = c7 with bit 31 set (inline -1, 0xffffffff) +# w10 = 0x0f0f0f0f, bit 1 cleared (literal 0xffffffe1), then bit c5[4:0] set +# w11 = c3 with bit c3[4:0] cleared (destination and source are one SGPR) +BITSET = [ + "s_mov_b32 s9, 0", + "s_load_dwordx4 s[12:15], s[8:9], null", + "s_load_dwordx4 s[16:19], s[8:9], 0x20", + "s_waitcnt lgkmcnt(0)", + "s_buffer_load_dwordx4 s[20:23], s[16:19], null", + "s_buffer_load_dwordx4 s[24:27], s[16:19], 0x10", + "s_waitcnt lgkmcnt(0)", + "s_bitset1_b32 s20, s21", + "s_bitset0_b32 s22, s23", + "s_bitset1_b32 s24, s25", + "s_mov_b32 s28, s20", + "s_bitset1_b32 s28, 4", + "s_bitset0_b32 s26, 63", + "s_bitset1_b32 s27, -1", + "s_mov_b32 s29, 0x0f0f0f0f", + "s_bitset0_b32 s29, 0xffffffe1", + "s_bitset1_b32 s29, s25", + "s_bitset0_b32 s23, s23", + "v_mov_b32_e32 v4, s20", "v_mov_b32_e32 v5, s22", "v_mov_b32_e32 v6, s24", "v_mov_b32_e32 v7, s28", + "v_mov_b32_e32 v8, s26", "v_mov_b32_e32 v9, s27", "v_mov_b32_e32 v10, s29", "v_mov_b32_e32 v11, s23", + "s_clause 0x1", + "buffer_store_dwordx4 v[4:7], off, s[12:15], 0 offset:16", + "buffer_store_dwordx4 v[8:11], off, s[12:15], 0 offset:32", + "s_endpgm", +] +BINDING = base.RUNTIME_BINDING +FIRST_STORED = 4 +# Two runs of root constants (c8..c15 are not read). In the first run c1 = 0 sets bit 0, c3 = 31 clears bit 31 and +# c5 = 0x47 (71) selects bit 7. In the second c1 = 0x20 (32) selects bit 0 again, already set, c3 = 0x3e selects bit +# 30, c5 = 0xffffffe3 selects bit 3, c6 already has bit 31 clear and c7 already has it set. +RUNS = ( + [0x12345670, 0x00000000, 0x8000ffff, 0x0000001f, 0x00000100, 0x00000047, 0xfedcba98, 0x00000001, + *(0x5eed0000 + i for i in range(8, 16))], + [0xffffffff, 0x00000020, 0xffffffff, 0x0000003e, 0x80000000, 0xffffffe3, 0x7fffffff, 0x80000000, + *(0x5eed0000 + i for i in range(8, 16))], +) +# Worked by hand from the ISA definition, D.u32[S0.u32[4:0]] = 0 or 1, for the two runs above. +HAND = ( + [0x12345671, 0x0000ffff, 0x00000180, 0x12345671, 0x7edcba98, 0x80000001, 0x0f0f0f8d, 0x0000001f], + [0xffffffff, 0xbfffffff, 0x80000008, 0xffffffff, 0x7fffffff, 0x80000000, 0x0f0f0f0d, 0x0000003e], +) + + +def bitset(word, index, value, *, mask=True): + """Independent reference: rewrite one entry of the word's bit list. Unmasked, an index past 31 changes nothing.""" + bits = [(word >> i) & 1 for i in range(32)] + if mask or index < 32: + bits[index % 32 if mask else index] = value + return sum(bit << i for i, bit in enumerate(bits)) + + +def reference(c, *, swap=False, mask=True, keep=True): + """Expected u0 words. swap exchanges set and clear, mask=False ignores src0[4:0], keep=False drops sD's old bits.""" + def op(word, index, value): + return bitset(word if keep else (0 if value else 0xffffffff), index & 0xffffffff, value ^ swap, mask=mask) + + w4 = op(c[0], c[1], 1) + w10 = op(op(0x0f0f0f0f, 0xffffffe1, 0), c[5], 1) + stored = [w4, op(c[2], c[3], 0), op(c[4], c[5], 1), op(w4, 4, 1), op(c[6], 63, 0), op(c[7], -1, 1), w10, + op(c[3], c[3], 0)] + words = [base.SENTINEL] * 320 + words[FIRST_STORED:FIRST_STORED + len(stored)] = stored + return words + + +def lowered(*changes): + return aot.lower(base.variant(BITSET, *changes), 1, **BINDING) + + +def controls(): + """Exact HLSL for each form, then one rejection per operand form outside the subset.""" + for constants, hand in zip(RUNS, HAND, strict=True): + stored = reference(constants)[FIRST_STORED:FIRST_STORED + len(hand)] + assert stored == hand, [hex(word) for word in stored] + # The reference controls the draw uses must each differ from the expected words. + for wrong in (dict(swap=True), dict(mask=False), dict(keep=False)): + assert reference(RUNS[0], **wrong) != reference(RUNS[0]), wrong + source = lowered() + w4 = "(params[0].x | (1u << (params[0].y & 31u)))" + for expression in ( + w4, + "(params[0].z & ~(1u << (params[0].w & 31u)))", + "(params[1].x | (1u << (params[1].y & 31u)))", + f"({w4} | (1u << (0x00000004u & 31u)))", + "(params[1].z & ~(1u << (0x0000003fu & 31u)))", + "(params[1].w | (1u << (0xffffffffu & 31u)))", + "((0x0f0f0f0fu & ~(1u << (0xffffffe1u & 31u))) | (1u << (params[1].y & 31u)))", + "(params[0].w & ~(1u << (params[0].w & 31u)))", + ): + assert expression in source, (expression, source) + # w4 appears in its own store and inside w7, the bitset of its copy in s28. + assert source.count(w4) == 2, source + # A bitset on the copy leaves s20 alone: storing s20 after it is still w4. + assert w4 + ")" not in source and w4 + ")" in lowered(("v_mov_b32_e32 v7, s28", "v_mov_b32_e32 v7, s20")) + unsupported, operand = "Unsupported compute instruction: ", "Unverified scalar ALU operand" + for message, changes in ( + # A destination that holds no known word: an unwritten SGPR, a descriptor SGPR, the table pointer and an SGPR + # whose load still waits for its s_waitcnt. + (operand, (("s_bitset1_b32 s20, s21", "s_bitset1_b32 s30, s21"),)), + (operand, (("s_bitset1_b32 s20, s21", "s_bitset1_b32 s12, s21"),)), + (operand, (("s_bitset1_b32 s20, s21", "s_bitset1_b32 s8, s21"),)), + (operand, (("s_bitset1_b32 s20, s21", "s_buffer_load_dword s30, s[16:19], 0x20\ns_bitset1_b32 s30, 0"),)), + # A source that is not a known word: unwritten, descriptor, pending, or a literal wider than 32 bits. + (operand, (("s_bitset1_b32 s20, s21", "s_bitset1_b32 s20, s31"),)), + (operand, (("s_bitset1_b32 s20, s21", "s_bitset1_b32 s20, s13"),)), + (operand, (("s_bitset1_b32 s20, s21", "s_buffer_load_dword s30, s[16:19], 0x20\ns_bitset1_b32 s20, s30"),)), + (operand, (("s_bitset0_b32 s29, 0xffffffe1", "s_bitset0_b32 s29, 0x1ffffffe1"),)), + # A destination past s105. + (operand, (("s_bitset1_b32 s20, s21", "s_bitset1_b32 s106, s21"),)), + # A fixture register used before its s_waitcnt lgkmcnt(0): its loaded word is not yet known. + (operand, (("s_buffer_load_dwordx4 s[24:27], s[16:19], 0x10", + "s_buffer_load_dwordx4 s[24:27], s[16:19], 0x10\ns_bitset1_b32 s24, 0"),)), + # A vector source, and the 64-bit forms. + (unsupported + "s_bitset1_b32", (("s_bitset1_b32 s20, s21", "s_bitset1_b32 s20, v4"),)), + (unsupported + "s_bitset0_b64", (("s_bitset0_b32 s22, s23", "s_bitset0_b64 s[22:23], s21"),)), + (unsupported + "s_bitset1_b64", (("s_bitset1_b32 s24, s25", "s_bitset1_b64 s[24:25], s21"),)), + # Each self-referencing bitset doubles the inline expression, so a long chain is rejected. + ("ALU expression too large", (("s_bitset0_b32 s23, s23", + "s_bitset0_b32 s23, s23" + "\ns_bitset1_b32 s23, s23" * 6),)), + # A bitset result is data only, not a store address. + ("Unsupported store address", (("v_mov_b32_e32 v4, s20", "v_mov_b32_e32 v4, s20\nv_mov_b32_e32 v12, s20"), + ("v[4:7], off, s[12:15], 0 offset:16", "v[4:7], v12, s[12:15], 0 offen"))), + ): + base.rejects(message, lowered, *changes) + # In the guarded read fixture, the group-ID SGPR and the saved exec mask are not known words either. + def guarded(*changes): + return aot.lower(base.variant(base.READ_SCALAR, *changes), 32, **base.READ_BINDING) + + guarded() + base.rejects(operand, guarded, ("s_mov_b32 s2, s1", "s_bitset1_b32 s1, 0\ns_mov_b32 s2, s1")) + base.rejects(operand, guarded, ("s_lshr_b32 s21, s20, 3", "s_lshr_b32 s21, s20, 3\ns_bitset0_b32 s2, 0")) + # Nor is the saved exec mask a known bit index. + base.rejects(operand, guarded, ("s_lshr_b32 s21, s20, 3", "s_lshr_b32 s21, s20, 3\ns_bitset1_b32 s21, s2")) + + +def run(cmd, case, constants, words, *, expect=None): + case.write_bytes(struct.pack("<337I", 1, *words, *constants)) + if expect is None: + return subprocess.run(cmd).returncode + bad = subprocess.run(cmd, capture_output=True, text=True) + if bad.returncode != 1 or expect not in bad.stderr: + raise AssertionError(f"Expected '{expect}', got {bad.returncode}\n{bad.stdout}\n{bad.stderr}") + return 0 + + +def draw(directory, compiler, renderer, backend): + """Dispatch the fixture for both runs, then require wrong references and mutated translations to fail.""" + src, cso, case = [directory / x for x in ("bitset.hlsl", "bitset.cso", "bitset.case")] + source = lowered() + src.write_text(source, encoding="ascii") + subprocess.run([compiler, "-T", "cs_6_0", "-E", "main", "-Fo", cso, src], check=True) + cmd = [renderer, backend, "--compute-store-case", cso, case] + for constants in RUNS: + if result := run(cmd, case, constants, reference(constants)): + return result + # Wrong references: set and clear exchanged, src0[4:0] ignored, sD's other bits dropped, and the other run's + # words (a translation that folded the constants). + constants = RUNS[0] + expected = reference(constants) + for wrong in (reference(constants, swap=True), reference(constants, mask=False), + reference(constants, keep=False), reference(RUNS[1])): + word = next(i for i, (a, b) in enumerate(zip(expected, wrong)) if a != b) + run(cmd, case, constants, wrong, expect=f"word={word} expected=") + run(cmd, case, constants, expected) + w4 = "(params[0].x | (1u << (params[0].y & 31u)))" + for label, old, new in (("set for clear", "(params[0].z & ~(1u << ", "(params[0].z | (1u << "), + ("clear for set", w4, "(params[0].x & ~(1u << (params[0].y & 31u)))"), + ("destination dropped", w4, "(0x00000000u | (1u << (params[0].y & 31u)))"), + ("next bit", "(1u << (params[1].y & 31u))", "(2u << (params[1].y & 31u))"), + ("index from c1", "(params[1].x | (1u << (params[1].y", + "(params[1].x | (1u << (params[0].y")): + mutated = source.replace(old, new) + if mutated == source: + raise AssertionError(f"mutation '{label}' did not change the source") + msrc, mcso = directory / "mutated.hlsl", directory / "mutated.cso" + msrc.write_text(mutated, encoding="ascii") + subprocess.run([compiler, "-T", "cs_6_0", "-E", "main", "-Fo", mcso, msrc], check=True) + case.write_bytes(struct.pack("<337I", 1, *expected, *constants)) + bad = subprocess.run([*cmd[:3], mcso, case], capture_output=True, text=True) + if bad.returncode != 1 or "Compute readback differs" not in bad.stderr: + raise AssertionError(f"mutation '{label}' escaped detection\n{bad.stdout}\n{bad.stderr}") + return 0 + + +if __name__ == "__main__": + controls() + mode, *args = sys.argv[1:] + if mode == "controls": + sys.exit(0) + if mode != "draw" or len(args) != 3: + sys.exit("usage: compute_salu_bitset_check.py controls | draw ") + with tempfile.TemporaryDirectory() as tmp: + sys.exit(draw(Path(tmp), *args)) diff --git a/tools/compute_store_aot.py b/tools/compute_store_aot.py index fdb550aa1..b73584cb5 100644 --- a/tools/compute_store_aot.py +++ b/tools/compute_store_aot.py @@ -94,6 +94,8 @@ # RDNA2 SOP2: temp.i64 = (int64)S0.i32 - (int64)S1.i32; D.i32 = temp.i32[31:0]; SCC = (temp.i64 != (int64)D.i32) ? 1 : 0 (unread). "s_sub_i32": "({0} - {1})", "s_and_b32": "({0} & {1})", + "s_bitset0_b32": "({0} & ~(1u << ({1} & 31u)))", + "s_bitset1_b32": "({0} | (1u << ({1} & 31u)))", "s_or_b32": "({0} | {1})", "s_xor_b32": "({0} ^ {1})", "s_lshr_b32": "({0} >> ({1} & 31u))", @@ -1295,6 +1297,17 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N if len(expression) > ALU_EXPRESSION_LIMIT: raise ValueError("ALU expression too large") scalar[dst] = ("alu", expression) + elif m := re.fullmatch(rf"(s_bitset[01]_b32) s(\d+), {SALU_SOURCE}", line): + # SOP1 s_bitset0_b32 and s_bitset1_b32 clear or set bit src0[4:0] of sD and keep its other bits, so sD + # is read as well as written: it must already hold a known word. SCC is not written. + op, dst = m[1], int(m[2]) + words = [alu_word(f"s{dst}", scalar, vector, pending, sizes), alu_word(m[3], scalar, vector, pending, sizes)] + if dst > 105 or dst in pending or None in words: + raise ValueError("Unverified scalar ALU operand") + expression = SALU[op].format(*map(hlsl_word, words)) + if len(expression) > ALU_EXPRESSION_LIMIT: + raise ValueError("ALU expression too large") + scalar[dst] = ("alu", expression) elif m := re.fullmatch(rf"s_cmp_(eq|lg)_([iu])32 {SALU_SOURCE}, {SALU_SOURCE}", line): # SCC = S0 == S1 (eq) or S0 != S1 (lg); the signedness does not change a 32-bit equality. words = [alu_word(token, scalar, vector, pending, sizes) for token in m.groups()[2:]] From 404446e88a7f54d27a5241da580bc3b81be58b75 Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Thu, 26 Nov 2026 05:03:10 +0200 Subject: [PATCH 097/240] cpu: lift BMI1 ANDN, BEXTR, and TZCNT leaf functions to C++ (#2668) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 24 + tests/cpu/bmi1_logic_aot.asm | 296 +++++++++++ tests/cpu/bmi1_logic_aot.def | 24 + tests/cpu/bmi1_logic_aot_check.py | 803 ++++++++++++++++++++++++++++++ tools/cpu_bmi1_logic_aot.py | 670 +++++++++++++++++++++++++ 5 files changed, 1817 insertions(+) create mode 100644 tests/cpu/bmi1_logic_aot.asm create mode 100644 tests/cpu/bmi1_logic_aot.def create mode 100644 tests/cpu/bmi1_logic_aot_check.py create mode 100644 tools/cpu_bmi1_logic_aot.py diff --git a/CMakeLists.txt b/CMakeLists.txt index a8f8ba267..0e00d8781 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -7021,6 +7021,30 @@ if(EXISTS "${INTAKE_PYTHON}") SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/cpu_aot_bmi1_bit.txt") + # cpu_aot_bmi1_logic + set(cpu_bmi1_logic_aot_exports + "op_andn32,op_andn64,op_bextr32,op_bextr64,op_tzcnt32,op_tzcnt64," + "op_andn32_mem,op_andn64_mem,op_bextr32_mem,op_bextr64_mem,op_tzcnt32_mem,op_tzcnt64_mem," + "op_andn32_flags,op_andn64_flags,op_bextr32_flags,op_bextr64_flags," + "op_tzcnt32_flags,op_tzcnt64_flags,op_bextr64_mem_flags,op_tzcnt64_mem_flags," + "op_r8_source_then_store,op_dst_alias_src,op_bmi1_logic_discarded_read") + string(CONCAT cpu_bmi1_logic_aot_exports ${cpu_bmi1_logic_aot_exports}) + foreach(variant IN ITEMS original altered) + cpu_asm_fixture(cpu_bmi1_logic_aot_${variant} bmi1_logic_aot) + cpu_translation(cpu_bmi1_logic_aot_${variant} cpu_bmi1_logic_aot "${cpu_bmi1_logic_aot_exports}") + endforeach() + target_compile_definitions(cpu_bmi1_logic_aot_altered PRIVATE ALTER_BMI1_LOGIC) + add_test(NAME cpu_aot_bmi1_logic COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/cpu/bmi1_logic_aot_check.py" + "$" + "$" + "$" + "$" + "${CMAKE_CXX_COMPILER}") + set_tests_properties(cpu_aot_bmi1_logic PROPERTIES + SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/cpu_aot_bmi1_logic.txt") + cpu_asm_fixture(cpu_sse2_packed_cvt sse2_packed_cvt) target_sources(cpu_sse2_packed_cvt PRIVATE tests/cpu/sse2_mxcsr_test.asm) set(sse2_packed_cvt_fixture "${CMAKE_CURRENT_BINARY_DIR}/cpu_sse2_packed_cvt_lifted.cpp") diff --git a/tests/cpu/bmi1_logic_aot.asm b/tests/cpu/bmi1_logic_aot.asm new file mode 100644 index 000000000..fd13c6902 --- /dev/null +++ b/tests/cpu/bmi1_logic_aot.asm @@ -0,0 +1,296 @@ +; coverage: record cpu_aot_bmi1_logic +; Source-built MASM fixture for BMI1 ANDN, BEXTR, and TZCNT from +; docs/coverage/x64_zen2.tsv group BMI/ADX in 32-bit and 64-bit register and +; flat [rcx|rdx|r8] memory forms, plus SDM flag-packing, 32-bit zero-extension, +; destination aliasing, [r8] source-then-store, and discarded faulting m64 read. +.code + +PACK_CF_ZF_SF_OF MACRO + setb r9b + sete r10b + sets r11b + seto byte ptr [r8] + movzx r9d, r9b + movzx r10d, r10b + shl r10d, 1 + or r9d, r10d + movzx r11d, r11b + shl r11d, 2 + or r9d, r11d + movzx r10d, byte ptr [r8] + shl r10d, 3 + or r9d, r10d + mov dword ptr [r8], r9d +ENDM + +PACK_CF_ZF_OF MACRO + setb r9b + sete r10b + seto r11b + movzx r9d, r9b + movzx r10d, r10b + shl r10d, 1 + or r9d, r10d + movzx r11d, r11b + shl r11d, 3 + or r9d, r11d + mov dword ptr [r8], r9d +ENDM + +PACK_CF_ZF MACRO + setb r9b + sete r10b + movzx r9d, r9b + movzx r10d, r10b + shl r10d, 1 + or r9d, r10d + mov dword ptr [r8], r9d +ENDM + +; --- Register forms (32-bit & 64-bit; mov rax,-1 before 32-bit tests [63:32] zero-ext) --- + +op_andn32 PROC FRAME + .endprolog + mov rax, -1 +IFDEF ALTER_BMI1_LOGIC + andn eax, edx, ecx +ELSE + andn eax, ecx, edx +ENDIF + ret +op_andn32 ENDP + +op_andn64 PROC FRAME + .endprolog +IFDEF ALTER_BMI1_LOGIC + andn rax, rdx, rcx +ELSE + andn rax, rcx, rdx +ENDIF + ret +op_andn64 ENDP + +op_bextr32 PROC FRAME + .endprolog + mov rax, -1 +IFDEF ALTER_BMI1_LOGIC + bextr eax, edx, ecx +ELSE + bextr eax, ecx, edx +ENDIF + ret +op_bextr32 ENDP + +op_bextr64 PROC FRAME + .endprolog +IFDEF ALTER_BMI1_LOGIC + bextr rax, rdx, rcx +ELSE + bextr rax, rcx, rdx +ENDIF + ret +op_bextr64 ENDP + +op_tzcnt32 PROC FRAME + .endprolog + mov rax, -1 +IFDEF ALTER_BMI1_LOGIC + bextr eax, ecx, ecx +ELSE + tzcnt eax, ecx +ENDIF + ret +op_tzcnt32 ENDP + +op_tzcnt64 PROC FRAME + .endprolog +IFDEF ALTER_BMI1_LOGIC + bextr rax, rcx, rcx +ELSE + tzcnt rax, rcx +ENDIF + ret +op_tzcnt64 ENDP + +; --- Flat [rcx|rdx] m32 / m64 source forms --- + +op_andn32_mem PROC FRAME + .endprolog + mov rax, -1 +IFDEF ALTER_BMI1_LOGIC + bextr eax, dword ptr [rcx], edx +ELSE + andn eax, edx, dword ptr [rcx] +ENDIF + ret +op_andn32_mem ENDP + +op_andn64_mem PROC FRAME + .endprolog +IFDEF ALTER_BMI1_LOGIC + bextr rax, qword ptr [rcx], rdx +ELSE + andn rax, rdx, qword ptr [rcx] +ENDIF + ret +op_andn64_mem ENDP + +op_bextr32_mem PROC FRAME + .endprolog + mov rax, -1 +IFDEF ALTER_BMI1_LOGIC + andn eax, edx, dword ptr [rcx] +ELSE + bextr eax, dword ptr [rcx], edx +ENDIF + ret +op_bextr32_mem ENDP + +op_bextr64_mem PROC FRAME + .endprolog +IFDEF ALTER_BMI1_LOGIC + andn rax, rdx, qword ptr [rcx] +ELSE + bextr rax, qword ptr [rcx], rdx +ENDIF + ret +op_bextr64_mem ENDP + +op_tzcnt32_mem PROC FRAME + .endprolog + mov rax, -1 +IFDEF ALTER_BMI1_LOGIC + bextr eax, dword ptr [rdx], ecx +ELSE + tzcnt eax, dword ptr [rdx] +ENDIF + ret +op_tzcnt32_mem ENDP + +op_tzcnt64_mem PROC FRAME + .endprolog +IFDEF ALTER_BMI1_LOGIC + bextr rax, qword ptr [rdx], rcx +ELSE + tzcnt rax, qword ptr [rdx] +ENDIF + ret +op_tzcnt64_mem ENDP + +; --- Flag-packing exports stored at [r8] --- + +op_andn32_flags PROC FRAME + .endprolog + xor r9d, r9d + xor r10d, r10d + xor r11d, r11d + mov rax, -1 + andn eax, ecx, edx + PACK_CF_ZF_SF_OF + ret +op_andn32_flags ENDP + +op_andn64_flags PROC FRAME + .endprolog + xor r9d, r9d + xor r10d, r10d + xor r11d, r11d + andn rax, rcx, rdx + PACK_CF_ZF_SF_OF + ret +op_andn64_flags ENDP + +op_bextr32_flags PROC FRAME + .endprolog + xor r9d, r9d + xor r10d, r10d + xor r11d, r11d + mov rax, -1 + bextr eax, ecx, edx + PACK_CF_ZF_OF + ret +op_bextr32_flags ENDP + +op_bextr64_flags PROC FRAME + .endprolog + xor r9d, r9d + xor r10d, r10d + xor r11d, r11d + bextr rax, rcx, rdx + PACK_CF_ZF_OF + ret +op_bextr64_flags ENDP + +op_tzcnt32_flags PROC FRAME + .endprolog + xor r9d, r9d + xor r10d, r10d + mov rax, -1 + tzcnt eax, ecx + PACK_CF_ZF + ret +op_tzcnt32_flags ENDP + +op_tzcnt64_flags PROC FRAME + .endprolog + xor r9d, r9d + xor r10d, r10d + tzcnt rax, rcx + PACK_CF_ZF + ret +op_tzcnt64_flags ENDP + +op_bextr64_mem_flags PROC FRAME + .endprolog + xor r9d, r9d + xor r10d, r10d + xor r11d, r11d + bextr rax, qword ptr [rcx], rdx + PACK_CF_ZF_OF + ret +op_bextr64_mem_flags ENDP + +op_tzcnt64_mem_flags PROC FRAME + .endprolog + xor r9d, r9d + xor r10d, r10d + tzcnt rax, qword ptr [rcx] + PACK_CF_ZF + ret +op_tzcnt64_mem_flags ENDP + +; --- [r8] source-then-store, dst aliasing src, and discarded faulting m64 read --- + +op_r8_source_then_store PROC FRAME + .endprolog + mov r11, qword ptr [rdx] + andn r9, r11, qword ptr [r8] + bextr r10, qword ptr [rcx], r11 + tzcnt r11, qword ptr [rdx] + or r9, r10 + xor r9, r11 + mov qword ptr [r8], r9 + mov rax, r9 + ret +op_r8_source_then_store ENDP + +op_dst_alias_src PROC FRAME + .endprolog + mov r9, rcx + mov r10, rdx + andn r9, r9, r10 + bextr r10, r10, r9 + tzcnt r10, r10 + or r9, r10 + mov rax, r9 + ret +op_dst_alias_src ENDP + +op_bmi1_logic_discarded_read PROC FRAME + .endprolog + tzcnt r9, qword ptr [rdx] + mov rax, rcx + ret +op_bmi1_logic_discarded_read ENDP + +END diff --git a/tests/cpu/bmi1_logic_aot.def b/tests/cpu/bmi1_logic_aot.def new file mode 100644 index 000000000..8bde8d32f --- /dev/null +++ b/tests/cpu/bmi1_logic_aot.def @@ -0,0 +1,24 @@ +EXPORTS + op_andn32 + op_andn64 + op_bextr32 + op_bextr64 + op_tzcnt32 + op_tzcnt64 + op_andn32_mem + op_andn64_mem + op_bextr32_mem + op_bextr64_mem + op_tzcnt32_mem + op_tzcnt64_mem + op_andn32_flags + op_andn64_flags + op_bextr32_flags + op_bextr64_flags + op_tzcnt32_flags + op_tzcnt64_flags + op_bextr64_mem_flags + op_tzcnt64_mem_flags + op_r8_source_then_store + op_dst_alias_src + op_bmi1_logic_discarded_read diff --git a/tests/cpu/bmi1_logic_aot_check.py b/tests/cpu/bmi1_logic_aot_check.py new file mode 100644 index 000000000..3ca4e0750 --- /dev/null +++ b/tests/cpu/bmi1_logic_aot_check.py @@ -0,0 +1,803 @@ +"""Differential, /O2, flag-modeling, mutant, and rejection checks for cpu_bmi1_logic_aot (ANDN, BEXTR, TZCNT).""" + +import ctypes +import os +from pathlib import Path +import random +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory + +from iced_x86 import Code, Decoder, Encoder, Formatter, FormatterSyntax, Instruction, MemoryOperand, Register as R +import pefile + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "tools")) +from cpu_bmi1_logic_aot import lift_code, translate # noqa: E402 +from cpu_leaf_aot import bounded_code, export_rva # noqa: E402 + +EXPORTS = ( + "op_andn32", "op_andn64", + "op_bextr32", "op_bextr64", + "op_tzcnt32", "op_tzcnt64", + "op_andn32_mem", "op_andn64_mem", + "op_bextr32_mem", "op_bextr64_mem", + "op_tzcnt32_mem", "op_tzcnt64_mem", + "op_andn32_flags", "op_andn64_flags", + "op_bextr32_flags", "op_bextr64_flags", + "op_tzcnt32_flags", "op_tzcnt64_flags", + "op_bextr64_mem_flags", + "op_tzcnt64_mem_flags", + "op_r8_source_then_store", + "op_dst_alias_src", + "op_bmi1_logic_discarded_read", +) + +ALTERED_REG_EXPORTS = ( + "op_andn32", "op_andn64", + "op_bextr32", "op_bextr64", + "op_tzcnt32", "op_tzcnt64", +) +ALTERED_MEM_EXPORTS = ( + "op_andn32_mem", "op_andn64_mem", + "op_bextr32_mem", "op_bextr64_mem", + "op_tzcnt32_mem", "op_tzcnt64_mem", +) + +MASK32 = 0xFFFFFFFF +MASK64 = 0xFFFFFFFFFFFFFFFF +GUARD_PRE = bytes(range(0xA0, 0xB0)) +GUARD_POST = bytes(range(0xC0, 0xD0)) + + +# --- Independent Python reference model --- + +def ref_bmi1_logic(op, a, b, bits, *, quirk=None): + """Return (dst, packed_flags) matching SDM flags per instruction.""" + mask = MASK32 if bits == 32 else MASK64 + sign = 1 << (bits - 1) + s1 = a & mask + s2 = b & mask + + if op == "andn": + if quirk == "andn_swap": + d = ((~s2) & s1) & mask + elif quirk == "andn_plain_and": + d = (s1 & s2) & mask + else: + d = ((~s1) & s2) & mask + cf = True if quirk == "set_cf" else False + of = True if quirk == "set_of" else False + zf = (d == 0) + sf = False if quirk == "drop_sf" else ((d & sign) != 0) + elif op == "bextr": + if quirk == "bextr_swap_start_len": + start = (s2 >> 8) & 0xFF + length = s2 & 0xFF + else: + start = s2 & 0xFF + length = (s2 >> 8) & 0xFF + if quirk == "bextr_mask_start_bits": + start &= (bits - 1) + if quirk == "bextr_len_zero_all" and length == 0: + length = bits + if length == 0 or start >= bits: + d = 0 + else: + bit_mask = mask if length >= bits else ((1 << length) - 1) + d = ((s1 >> start) & bit_mask) & mask + cf = True if quirk == "set_cf" else False + of = True if quirk == "set_of" else False + zf = False if quirk == "bextr_zf_false" else (d == 0) + sf = False + elif op == "tzcnt": + if s1 == 0: + if quirk == "tzcnt_zero_0": + d = 0 + elif quirk == "tzcnt_zero_width_m1": + d = bits - 1 + else: + d = bits + cf = False if quirk == "tzcnt_invert_cf" else True + else: + d = (s1 & -s1).bit_length() - 1 + cf = True if quirk == "tzcnt_invert_cf" else False + zf = (s1 == 0) if quirk == "tzcnt_zf_from_src" else (d == 0) + sf = False + of = False + else: + raise ValueError(op) + + if quirk == "no_zext32" and bits == 32: + d |= 0xFFFFFFFF00000000 + packed = (int(cf) << 0) | (int(zf) << 1) | (int(sf) << 2) | (int(of) << 3) + return d, packed + + +def test_pairs(): + singles = [ + 0x0000000000000000, + 0x0000000000000001, + 0x0000000000000002, + 0x0000000000000010, + 0x000000007FFFFFFF, + 0x0000000080000000, + 0x0000000080000001, + 0x00000000FFFFFFFE, + 0x00000000FFFFFFFF, + 0xDEADBEEF00000000, + 0xDEADBEEF80000000, + 0x0000000100000000, + 0x7FFFFFFFFFFFFFFF, + 0x8000000000000000, + 0x8000000000000001, + 0xFFFFFFFFFFFFFFFE, + 0xFFFFFFFFFFFFFFFF, + 0x0123456789ABCDEF, + 0xFEDCBA9876543210, + ] + singles.extend(1 << b for b in range(64)) + bextr_ctrls = [ + 0x0000000000000000, # start=0, len=0 + 0x0000000000000005, # start=5, len=0 + 0x0000000000000100, # start=0, len=1 + 0x000000000000011F, # start=31, len=1 + 0x0000000000000120, # start=32, len=1 (out of 32b range, valid in 64b) + 0x000000000000013F, # start=63, len=1 + 0x0000000000000140, # start=64, len=1 (out of 64b range) + 0x0000000000001418, # start=24, len=20 (crosses 32b boundary) + 0x0000000000002000, # start=0, len=32 + 0x0000000000002010, # start=16, len=32 + 0x0000000000004000, # start=0, len=64 + 0x0000000000004020, # start=32, len=64 (crosses 64b boundary) + 0x000000000000FF00, # start=0, len=255 + 0x000000000000FF1F, # start=31, len=255 + 0x000000000000FF3F, # start=63, len=255 + 0x000000000000FFFF, # start=255, len=255 + 0xABCD123400000804, # dirty upper bits [31:16]/[63:16] + 0xCAFE000000002018, # dirty upper bits + ] + pairs = [ + (0x0000000000000000, 0x0000000080000000), + (0x0000000000000000, 0x8000000000000000), + (0x0000000080000000, 0x00000000FFFFFFFF), + (0x8000000000000000, 0xFFFFFFFFFFFFFFFF), + ] + for idx, a in enumerate(singles): + b = bextr_ctrls[idx % len(bextr_ctrls)] if idx < len(bextr_ctrls) * 2 else singles[(idx * 7 + 3) % len(singles)] + pairs.append((a, b)) + for ctrl in bextr_ctrls: + pairs.append((0xF0E1D2C3B4A59687, ctrl)) + pairs.append((0x8000000080000001, ctrl)) + rng = random.Random(0xB11101C) + for _ in range(32): + pairs.append((rng.getrandbits(64), rng.getrandbits(64))) + return pairs + + +# --- Guarded memory & DLL helpers --- + +def alloc_guarded(payload): + raw = ctypes.create_string_buffer(GUARD_PRE + payload + GUARD_POST, len(GUARD_PRE) + len(payload) + len(GUARD_POST)) + base = ctypes.addressof(raw) + return raw, base + len(GUARD_PRE), len(GUARD_PRE), len(payload) + + +def read_guarded(buf, off, length, label): + raw = buf.raw + if raw[:off] != GUARD_PRE or raw[off + length:] != GUARD_POST: + raise AssertionError(f"guard bytes corrupted around {label}") + return raw[off:off + length] + + +def bind_exports(dll_path, prefix=""): + lib = ctypes.CDLL(str(Path(dll_path).resolve())) + funcs = {} + for name in EXPORTS: + fn = getattr(lib, prefix + name) + fn.argtypes = [ctypes.c_uint64] * 3 + fn.restype = ctypes.c_uint64 + funcs[name] = fn + return lib, funcs + + +def unload_lib(lib): + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + kernel32.FreeLibrary.argtypes = [ctypes.c_void_p] + kernel32.FreeLibrary.restype = ctypes.c_int + handle = getattr(lib, "_handle", None) + if handle: + kernel32.FreeLibrary(handle) + + +def host_has_bmi1(lifted_lib): + if hasattr(lifted_lib, "host_has_bmi1"): + lifted_lib.host_has_bmi1.argtypes = [] + lifted_lib.host_has_bmi1.restype = ctypes.c_uint32 + return bool(lifted_lib.host_has_bmi1()) + return False + + +# --- Rejection & alternate-encoding controls --- + +def encode_seq(*instructions): + enc = Encoder(64) + ip = 0x1000 + for ins in instructions: + ip += enc.encode(ins, ip) + return enc.take_buffer() + + +def check_rejections(original_path): + ret = Instruction.create(Code.RETNQ) + mov_rax_rcx = Instruction.create_reg_reg(Code.MOV_R64_RM64, R.RAX, R.RCX) + xor_r9 = Instruction.create_reg_reg(Code.XOR_R32_RM32, R.R9D, R.R9D) + andn_eax_ecx_edx = Instruction.create_reg_reg_reg(Code.VEX_ANDN_R32_R32_RM32, R.EAX, R.ECX, R.EDX) + bextr_rax_rcx_rdx = Instruction.create_reg_reg_reg(Code.VEX_BEXTR_R64_RM64_R64, R.RAX, R.RCX, R.RDX) + tzcnt_rax_rcx = Instruction.create_reg_reg(Code.TZCNT_R64_RM64, R.RAX, R.RCX) + + # Alternate encodings accepted cleanly. + alt_accept = [ + ("andn32_r11_rdx_r8mem", (Instruction.create_reg_reg_mem(Code.VEX_ANDN_R32_R32_RM32, R.R11D, R.EDX, MemoryOperand(R.R8)), + Instruction.create_reg_reg(Code.MOV_R64_RM64, R.RAX, R.R11), ret), + "r11 = op_andn32((rdx & 0xFFFFFFFFull), ld_1000_2, flags);"), + ("bextr64_r10_rdxmem_rcx", (Instruction.create_reg_mem_reg(Code.VEX_BEXTR_R64_RM64_R64, R.R10, MemoryOperand(R.RDX), R.RCX), + Instruction.create_reg_reg(Code.MOV_R64_RM64, R.RAX, R.R10), ret), + "r10 = op_bextr64(ld_1000_1, rcx, flags);"), + ("tzcnt32_r9_r8d", (Instruction.create_reg_reg(Code.TZCNT_R32_RM32, R.R9D, R.R8D), + Instruction.create_reg_reg(Code.MOV_R32_RM32, R.EAX, R.R9D), ret), + "r9 = op_tzcnt32((r8 & 0xFFFFFFFFull), flags);"), + ] + for label, seq, expected in alt_accept: + src, count = lift_code(label, 0x1000, encode_seq(*seq)) + assert f"lifted_{label}" in src and count == len(seq), (label, count) + if expected not in src: + raise AssertionError(f"alt {label}: expected {expected!r}") + + seg_andn = Instruction.create_reg_reg_mem(Code.VEX_ANDN_R64_R64_RM64, R.RAX, R.RCX, MemoryOperand(R.RDX)) + seg_andn.segment_prefix = R.GS + evex_ins = Instruction.create_reg_reg_reg(Code.EVEX_VPADDD_XMM_K1Z_XMM_XMMM128B32, R.XMM0, R.XMM1, R.XMM2) + evex_ins.op_mask = R.K1 + + unit_cases = [ + # Other BMI1 instructions (BLSI / BLSMSK / BLSR) & 16-bit TZCNT & BSF/LZCNT + ("bmi1_blsi", (Instruction.create_reg_reg(Code.VEX_BLSI_R64_RM64, R.RAX, R.RCX), ret), + "unsupported VEX instruction"), + ("bmi1_blsmsk", (Instruction.create_reg_reg(Code.VEX_BLSMSK_R32_RM32, R.EAX, R.ECX), ret), + "unsupported VEX instruction"), + ("bmi1_blsr", (Instruction.create_reg_reg(Code.VEX_BLSR_R64_RM64, R.RAX, R.RCX), ret), + "unsupported VEX instruction"), + ("tzcnt_16bit", (Instruction.create_reg_reg(Code.TZCNT_R16_RM16, R.AX, R.CX), mov_rax_rcx, ret), + "unsupported instruction"), + ("bsf_32bit", (Instruction.create_reg_reg(Code.BSF_R32_RM32, R.EAX, R.ECX), ret), + "unsupported instruction"), + ("lzcnt_64bit", (Instruction.create_reg_reg(Code.LZCNT_R64_RM64, R.RAX, R.RCX), ret), + "unsupported instruction"), + # BMI2 rejections + ("bmi2_rorx", (Instruction.create_reg_reg_u32(Code.VEX_RORX_R64_RM64_IMM8, R.RAX, R.RCX, 5), ret), + "unsupported VEX instruction"), + ("bmi2_sarx", (Instruction.create_reg_reg_reg(Code.VEX_SARX_R64_RM64_R64, R.RAX, R.RCX, R.RDX), ret), + "unsupported VEX instruction"), + ("bmi2_shlx", (Instruction.create_reg_reg_reg(Code.VEX_SHLX_R32_RM32_R32, R.EAX, R.ECX, R.EDX), ret), + "unsupported VEX instruction"), + ("bmi2_bzhi", (Instruction.create_reg_reg_reg(Code.VEX_BZHI_R64_RM64_R64, R.RAX, R.RCX, R.RDX), ret), + "unsupported VEX instruction"), + # EVEX / XOP + ("evex_vpaddd", (evex_ins, mov_rax_rcx, ret), "unsupported EVEX instruction"), + ("xop_bextr32", (Instruction.create_reg_reg_u32(Code.XOP_BEXTR_R32_RM32_IMM32, R.EAX, R.ECX, 0x0804), ret), + "unsupported XOP instruction"), + ("xop_bextr64", (Instruction.create_reg_reg_u32(Code.XOP_BEXTR_R64_RM64_IMM32, R.RAX, R.RCX, 0x0804), ret), + "unsupported XOP instruction"), + # Undefined flag reads per instruction (including after prior XOR defining all flags!) + ("undef_pf_after_andn", (xor_r9, andn_eax_ecx_edx, Instruction.create_reg(Code.SETP_RM8, R.R9L), ret), + "undefined flag pf read"), + ("undef_sf_after_bextr", (xor_r9, bextr_rax_rcx_rdx, Instruction.create_reg(Code.SETS_RM8, R.R9L), ret), + "undefined flag sf read"), + ("undef_pf_after_bextr", (xor_r9, bextr_rax_rcx_rdx, Instruction.create_mem(Code.SETNP_RM8, MemoryOperand(R.R8)), ret), + "undefined flag pf read"), + ("undef_sf_after_tzcnt", (xor_r9, tzcnt_rax_rcx, Instruction.create_reg(Code.SETNS_RM8, R.R9L), ret), + "undefined flag sf read"), + ("undef_of_after_tzcnt", (xor_r9, tzcnt_rax_rcx, Instruction.create_mem(Code.SETO_RM8, MemoryOperand(R.R8)), ret), + "undefined flag of read"), + ("undef_pf_after_tzcnt", (xor_r9, tzcnt_rax_rcx, Instruction.create_reg(Code.SETP_RM8, R.R9L), ret), + "undefined flag pf read"), + ("undef_af_lahf_after_andn", (andn_eax_ecx_edx, Instruction.create(Code.LAHF), ret), + "unsupported instruction"), + ("undef_flags_pushfq", (tzcnt_rax_rcx, Instruction.create(Code.PUSHFQ), ret), + "unsupported instruction"), + ("undef_flags_before_op", (mov_rax_rcx, Instruction.create_mem(Code.SETB_RM8, MemoryOperand(R.R8)), ret), + "undefined flag cf read"), + # Nonvolatile GPRs, arg GPR writes, high-byte GPRs + ("nonvol_rbx_dst", (Instruction.create_reg_reg_reg(Code.VEX_ANDN_R64_R64_RM64, R.RBX, R.RCX, R.RDX), mov_rax_rcx, ret), + "nonvolatile GPR"), + ("nonvol_rsi_src", (Instruction.create_reg_reg_reg(Code.VEX_BEXTR_R64_RM64_R64, R.RAX, R.RSI, R.RDX), ret), + "nonvolatile GPR"), + ("nonvol_r12_dst", (Instruction.create_reg_reg(Code.TZCNT_R32_RM32, R.R12D, R.ECX), mov_rax_rcx, ret), + "nonvolatile GPR"), + ("write_arg_rcx", (Instruction.create_reg_reg_reg(Code.VEX_ANDN_R64_R64_RM64, R.RCX, R.RDX, R.R8), mov_rax_rcx, ret), + "cannot write argument GPR rcx"), + ("write_arg_edx", (Instruction.create_reg_reg_reg(Code.VEX_BEXTR_R32_RM32_R32, R.EDX, R.ECX, R.R8D), mov_rax_rcx, ret), + "cannot write argument GPR rdx"), + ("write_arg_r8", (Instruction.create_reg_reg(Code.TZCNT_R64_RM64, R.R8, R.RCX), mov_rax_rcx, ret), + "cannot write argument GPR r8"), + ("high_byte_ah", (mov_rax_rcx, Instruction.create_reg_u32(Code.MOV_R8_IMM8, R.AH, 1), ret), + "unsupported high-byte GPR"), + # Undefined GPRs + ("undef_gpr_r9_src", (Instruction.create_reg_reg_reg(Code.VEX_ANDN_R64_R64_RM64, R.RAX, R.R9, R.RCX), ret), + "undefined GPR r9"), + ("undef_gpr_r10_bextr_ctrl", (Instruction.create_reg_reg_reg(Code.VEX_BEXTR_R64_RM64_R64, R.RAX, R.RCX, R.R10), ret), + "undefined GPR r10"), + ("undef_rax_ret", (Instruction.create_reg_reg(Code.TZCNT_R64_RM64, R.R9, R.RCX), ret), + "return with undefined RAX"), + # Displaced / indexed / non-flat memory & non-r8 stores + ("displaced_andn_rcx", (Instruction.create_reg_reg_mem( + Code.VEX_ANDN_R64_R64_RM64, R.RAX, R.RDX, MemoryOperand(R.RCX, displ=8, displ_size=1)), ret), + "displaced memory operand"), + ("displaced_bextr_rdx", (Instruction.create_reg_mem_reg( + Code.VEX_BEXTR_R32_RM32_R32, R.EAX, MemoryOperand(R.RDX, displ=4, displ_size=1), R.ECX), ret), + "displaced memory operand"), + ("displaced_store_r8", (mov_rax_rcx, Instruction.create_mem_reg( + Code.MOV_RM64_R64, MemoryOperand(R.R8, displ=8, displ_size=1), R.RAX), ret), + "displaced memory operand"), + ("indexed_tzcnt", (Instruction.create_reg_mem( + Code.TZCNT_R64_RM64, R.RAX, MemoryOperand(R.RCX, R.RDX, 8)), ret), + "SIB index memory operand"), + ("rip_rel_andn", (Instruction.create_reg_reg_mem( + Code.VEX_ANDN_R64_R64_RM64, R.RAX, R.RCX, MemoryOperand(R.RIP, displ=0x1020, displ_size=4)), ret), + "RIP-relative memory operand"), + ("bad_base_rbx", (Instruction.create_reg_mem(Code.TZCNT_R64_RM64, R.RAX, MemoryOperand(R.RBX)), ret), + "bad base register in memory operand"), + ("bad_base_rsp", (Instruction.create_reg_mem_reg( + Code.VEX_BEXTR_R32_RM32_R32, R.EAX, MemoryOperand(R.RSP), R.ECX), ret), + "bad base register in memory operand"), + ("non_r8_store_rcx", (mov_rax_rcx, Instruction.create_mem_reg( + Code.MOV_RM64_R64, MemoryOperand(R.RCX), R.RAX), ret), "non-r8 store memory operand"), + ("non_r8_store_setb", (tzcnt_rax_rcx, Instruction.create_mem(Code.SETB_RM8, MemoryOperand(R.RDX)), ret), + "non-r8 store memory operand"), + # Prefixes, branches, missing/trailing ret + ("seg_prefix_andn", (seg_andn, ret), "unsupported instruction prefix"), + ("branch_jmp", (mov_rax_rcx, Instruction.create_branch(Code.JMP_REL8_64, 0x1010), ret), + "non-leaf branch or call"), + ("missing_ret", (andn_eax_ecx_edx,), "missing terminal ret"), + ("trailing_after_ret", (tzcnt_rax_rcx, ret, mov_rax_rcx), "unreachable instruction after ret"), + ] + + raw_cases = [ + ("lock_prefix", bytes.fromhex("f00fb109") + encode_seq(mov_rax_rcx, ret), "unsupported instruction prefix"), + ("rep_prefix", bytes.fromhex("f3a4") + encode_seq(mov_rax_rcx, ret), "unsupported instruction prefix"), + ("repne_bsf", bytes.fromhex("f20fbcc1") + encode_seq(ret), "unsupported instruction prefix"), + ("empty_stream", b"", "truncated instruction stream"), + ("invalid_bytes", bytes.fromhex("fffe") + encode_seq(ret), "invalid instruction"), + ] + + for label, seq, reason in unit_cases: + try: + lift_code(label, 0x1000, encode_seq(*seq)) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: translator accepted rejected control") + + for label, raw, reason in raw_cases: + try: + lift_code(label, 0x1000, raw) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: translator accepted raw rejected control") + + # End-to-end PE-patched rejections & CLI non-traceback / temp-cleanup rejections. + pe_bytes = Path(original_path).read_bytes() + with pefile.PE(data=pe_bytes, fast_load=True) as pe: + entry = export_rva(pe, "op_andn64_flags") + file_off = pe.get_offset_from_rva(entry) + pdata = pe.OPTIONAL_HEADER.DATA_DIRECTORY[3] + records = pe.get_data(pdata.VirtualAddress, pdata.Size) + rec_idx = next(i for i in range(0, len(records), 12) if struct.unpack_from(" max_len: + raise AssertionError(f"pe_{label}: patch ({len(patch)} bytes) exceeds max_len ({max_len})") + damaged = bytearray(pe_bytes) + damaged[file_off:file_off + len(patch)] = patch + struct.pack_into(" src1=rdx (b), src2=[rcx] (a) + buf, ptr, off, ln = alloc_guarded(struct.pack(fmt, a & mask)) + want, _ = ref_bmi1_logic(op, b, a, bits) + got = fn(ptr, b, 0) + elif op == "bextr": + # bextr dst, [rcx], rdx -> src1=[rcx] (a), src2=rdx (b) + buf, ptr, off, ln = alloc_guarded(struct.pack(fmt, a & mask)) + want, _ = ref_bmi1_logic(op, a, b, bits) + got = fn(ptr, b, 0) + else: + # tzcnt dst, [rdx] -> src=[rdx] (a) + buf, ptr, off, ln = alloc_guarded(struct.pack(fmt, a & mask)) + want, _ = ref_bmi1_logic(op, a, 0, bits) + got = fn(0, ptr, 0) if mem_reg == "rdx" else fn(ptr, 0, 0) + read_guarded(buf, off, ln, name) + if got != want: + raise AssertionError(f"{label} {name}({a:#x}, {b:#x}): got {got:#x} != exp {want:#x}") + total += 1 + + # 3) Flag-packing exports. + for op in ("andn", "bextr", "tzcnt"): + for bits in (32, 64): + name = f"op_{op}{bits}_flags" + fn = fns[name] + for a, b in pairs: + want_val, want_flags = ref_bmi1_logic(op, a, b, bits) + bo, po, oo, lo = alloc_guarded(b"\x5a" * 4) + got_val = fn(a, b, po) + got_flags = struct.unpack("(word rcx, word rdx, word r8) +where rcx, rdx, and r8 enter as 64-bit integer arguments or flat pointers to caller-owned +buffers and RAX carries the 64-bit return value. + +Supported BMI1 logic/extract/count instructions (docs/coverage/x64_zen2.tsv group BMI/ADX): + - ANDN r32, r32, r/m32 | ANDN r64, r64, r/m64 (dst = (~src1) & src2; SF/ZF, CF=OF=0) + - BEXTR r32, r/m32, r32 | BEXTR r64, r/m64, r64 (start=op2[7:0], len=op2[15:8]; ZF=(dst==0), CF=OF=0) + - TZCNT r32, r/m32 | TZCNT r64, r/m64 (dst=width/CF=1/ZF=0 if src==0 else ctz/CF=0/ZF=(dst==0)) + +32-bit destinations zero-extend into bits [63:32]. Per Intel SDM: + - ANDN leaves PF and AF undefined. + - BEXTR leaves SF, PF, and AF undefined. + - TZCNT leaves SF, OF, PF, and AF undefined. +Reading an undefined flag before a subsequent flag-defining instruction is rejected. +Memory operands are flat zero-displacement [rcx|rdx|r8] loads read unconditionally via +load_always() so /O2 cannot drop faulting reads. + +Transport / flag-packing glue: + - Volatile scratch GPR (rax/r9/r10/r11) mov, xor, or, shl, movzx, setb/sete/sets/seto + (and inverses, reg or flat [r8]), flat [r8] stores, and terminal ret. + +BMI1 BLSI/BLSMSK/BLSR, BMI2, EVEX/XOP, 16-bit TZCNT, BSF/BSR/LZCNT/POPCNT, nonvolatile GPRs, +writes to argument GPRs (rcx/rdx/r8), high-byte GPRs, undefined GPR or flag reads, +displaced/indexed/non-flat memory operands, stores outside [r8], instruction prefixes, +branches/calls, and missing or trailing instructions after ret are rejected. +""" + +import argparse +import os +from pathlib import Path +import sys +import tempfile + +import pefile +from iced_x86 import ( + Code, + Decoder, + EncodingKind, + FlowControl, + MemorySizeExt, + OpKind, + Register as R, + RegisterExt, +) + +from cpu_leaf_aot import bounded_code, export_rva + + +ARGUMENTS = {R.RCX: "rcx", R.RDX: "rdx", R.R8: "r8"} +ARGUMENT_NAMES = {"rcx", "rdx", "r8"} + +VOLATILE_GPR64 = { + R.RAX: "rax", R.RCX: "rcx", R.RDX: "rdx", R.R8: "r8", + R.R9: "r9", R.R10: "r10", R.R11: "r11", +} +VOLATILE_GPR32 = { + R.EAX: "rax", R.ECX: "rcx", R.EDX: "rdx", R.R8D: "r8", + R.R9D: "r9", R.R10D: "r10", R.R11D: "r11", +} +VOLATILE_GPR16 = { + R.AX: "rax", R.CX: "rcx", R.DX: "rdx", R.R8W: "r8", + R.R9W: "r9", R.R10W: "r10", R.R11W: "r11", +} +VOLATILE_GPR8 = { + R.AL: "rax", R.CL: "rcx", R.DL: "rdx", R.R8L: "r8", + R.R9L: "r9", R.R10L: "r10", R.R11L: "r11", +} +HIGH_BYTE_GPRS = {R.AH, R.CH, R.DH, R.BH} +NONVOLATILE_GPR = { + R.RBX, R.EBX, R.BX, R.BL, + R.RBP, R.EBP, R.BP, R.BPL, + R.RSI, R.ESI, R.SI, R.SIL, + R.RDI, R.EDI, R.DI, R.DIL, + R.RSP, R.ESP, R.SP, R.SPL, + R.R12, R.R12D, R.R12W, R.R12L, + R.R13, R.R13D, R.R13W, R.R13L, + R.R14, R.R14D, R.R14W, R.R14L, + R.R15, R.R15D, R.R15W, R.R15L, +} + +# (kind, width_bits, expected_encoding, defined_flags) +BMI1_LOGIC_SPECS = { + Code.VEX_ANDN_R32_R32_RM32: ("andn", 32, EncodingKind.VEX, frozenset({"sf", "zf", "cf", "of"})), + Code.VEX_ANDN_R64_R64_RM64: ("andn", 64, EncodingKind.VEX, frozenset({"sf", "zf", "cf", "of"})), + Code.VEX_BEXTR_R32_RM32_R32: ("bextr", 32, EncodingKind.VEX, frozenset({"zf", "cf", "of"})), + Code.VEX_BEXTR_R64_RM64_R64: ("bextr", 64, EncodingKind.VEX, frozenset({"zf", "cf", "of"})), + Code.TZCNT_R32_RM32: ("tzcnt", 32, EncodingKind.LEGACY, frozenset({"cf", "zf"})), + Code.TZCNT_R64_RM64: ("tzcnt", 64, EncodingKind.LEGACY, frozenset({"cf", "zf"})), +} + +MOV_WIDTHS = { + Code.MOV_R64_RM64: 64, + Code.MOV_RM64_R64: 64, + Code.MOV_RM64_IMM32: 64, + Code.MOV_R64_IMM64: 64, + Code.MOV_R32_RM32: 32, + Code.MOV_RM32_R32: 32, + Code.MOV_RM32_IMM32: 32, + Code.MOV_R32_IMM32: 32, + Code.MOV_R8_RM8: 8, + Code.MOV_RM8_R8: 8, + Code.MOV_RM8_IMM8: 8, + Code.MOV_R8_IMM8: 8, +} +MOVZX_SPECS = { + Code.MOVZX_R32_RM8: (32, 8), + Code.MOVZX_R64_RM8: (64, 8), +} +XOR_WIDTHS = { + Code.XOR_R32_RM32: 32, + Code.XOR_RM32_R32: 32, + Code.XOR_RM32_IMM8: 32, + Code.XOR_R64_RM64: 64, + Code.XOR_RM64_R64: 64, + Code.XOR_RM64_IMM8: 64, +} +OR_WIDTHS = { + Code.OR_R32_RM32: 32, + Code.OR_RM32_R32: 32, + Code.OR_RM32_IMM8: 32, + Code.OR_R64_RM64: 64, + Code.OR_RM64_R64: 64, + Code.OR_RM64_IMM8: 64, +} +SHL_SPECS = { + Code.SHL_RM32_1: (32, True), + Code.SHL_RM32_IMM8: (32, False), + Code.SHL_RM64_1: (64, True), + Code.SHL_RM64_IMM8: (64, False), +} +SETCC_SPECS = { + Code.SETB_RM8: ("cf", "flags.cf"), + Code.SETAE_RM8: ("cf", "!flags.cf"), + Code.SETE_RM8: ("zf", "flags.zf"), + Code.SETNE_RM8: ("zf", "!flags.zf"), + Code.SETS_RM8: ("sf", "flags.sf"), + Code.SETNS_RM8: ("sf", "!flags.sf"), + Code.SETO_RM8: ("of", "flags.of"), + Code.SETNO_RM8: ("of", "!flags.of"), + # PF is tracked solely to reject reading it when undefined. + Code.SETP_RM8: ("pf", "flags.pf"), + Code.SETNP_RM8: ("pf", "!flags.pf"), +} + +PRELUDE = """#include +#include +#include +#if defined(_MSC_VER) +#include +#endif + +using word = std::uint64_t; + +struct Flags { + bool cf = false; + bool zf = false; + bool sf = false; + bool of = false; + bool pf = false; +}; + +template +static inline T load_always(word address) { + std::atomic_signal_fence(std::memory_order_seq_cst); + T v{}; + std::memcpy(&v, reinterpret_cast(address), sizeof(T)); + const volatile T observed = v; + std::atomic_signal_fence(std::memory_order_seq_cst); + return observed; +} + +template +static inline void store_always(word address, T value) { + std::atomic_signal_fence(std::memory_order_seq_cst); + std::memcpy(reinterpret_cast(address), &value, sizeof(T)); + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +static inline bool parity_even(std::uint8_t byte) { + byte ^= static_cast(byte >> 4); + byte &= 0x0Fu; + return ((0x9669u >> byte) & 1u) != 0u; +} + +static inline word update_gpr_width(word cur, std::uint64_t val, unsigned width) { + if (width == 8u) { + return (cur & ~0xFFull) | (val & 0xFFull); + } + if (width == 32u) { + return val & 0xFFFFFFFFull; + } + return val; +} + +static inline void compute_logic_flags(word result, unsigned width, Flags& flags) { + const std::uint64_t masked = (width == 32u) ? (result & 0xFFFFFFFFull) : result; + flags.cf = false; + flags.of = false; + flags.zf = masked == 0ull; + flags.sf = ((masked >> (width - 1u)) & 1ull) != 0ull; + flags.pf = parity_even(static_cast(masked)); +} + +static inline word op_shl(word cur, unsigned width, unsigned count, Flags& flags) { + const unsigned mask = (width == 32u) ? 31u : 63u; + const unsigned c = count & mask; + if (width == 32u) { + const std::uint32_t v = static_cast(cur); + if (c == 0u) return static_cast(v); + const std::uint32_t r = v << c; + flags.cf = ((v >> (32u - c)) & 1u) != 0u; + flags.zf = r == 0u; + flags.sf = (r & 0x80000000u) != 0u; + flags.of = (((r >> 31) & 1u) != (flags.cf ? 1u : 0u)); + flags.pf = parity_even(static_cast(r)); + return static_cast(r); + } + if (c == 0u) return cur; + const word r = cur << c; + flags.cf = ((cur >> (64u - c)) & 1ull) != 0ull; + flags.zf = r == 0ull; + flags.sf = (r >> 63) != 0ull; + flags.of = (((r >> 63) & 1ull) != (flags.cf ? 1ull : 0ull)); + flags.pf = parity_even(static_cast(r)); + return r; +} + +// --- Portable BMI1 ANDN / BEXTR / TZCNT helpers --- + +static inline word op_andn32(word src1_w, word src2_w, Flags& flags) { + const std::uint32_t s1 = static_cast(src1_w); + const std::uint32_t s2 = static_cast(src2_w); + const std::uint32_t d = (~s1) & s2; + flags.cf = false; + flags.of = false; + flags.zf = (d == 0u); + flags.sf = (d & 0x80000000u) != 0u; + return static_cast(d); +} + +static inline word op_andn64(word s1, word s2, Flags& flags) { + const word d = (~s1) & s2; + flags.cf = false; + flags.of = false; + flags.zf = (d == 0ull); + flags.sf = (d >> 63) != 0ull; + return d; +} + +static inline word op_bextr32(word src1_w, word src2_w, Flags& flags) { + const std::uint32_t s1 = static_cast(src1_w); + const unsigned start = static_cast(src2_w & 0xFFull); + const unsigned len = static_cast((src2_w >> 8) & 0xFFull); + std::uint32_t d = 0u; + if (len != 0u && start < 32u) { + const std::uint32_t shifted = s1 >> start; + const std::uint32_t mask = (len >= 32u) ? 0xFFFFFFFFu : ((1u << len) - 1u); + d = shifted & mask; + } + flags.zf = (d == 0u); + flags.cf = false; + flags.of = false; + return static_cast(d); +} + +static inline word op_bextr64(word s1, word s2, Flags& flags) { + const unsigned start = static_cast(s2 & 0xFFull); + const unsigned len = static_cast((s2 >> 8) & 0xFFull); + word d = 0ull; + if (len != 0u && start < 64u) { + const word shifted = s1 >> start; + const word mask = (len >= 64u) ? ~0ull : ((1ull << len) - 1ull); + d = shifted & mask; + } + flags.zf = (d == 0ull); + flags.cf = false; + flags.of = false; + return d; +} + +static inline word op_tzcnt32(word src_w, Flags& flags) { + const std::uint32_t s = static_cast(src_w); + std::uint32_t count = 32u; + if (s != 0u) { + count = 0u; + std::uint32_t t = s; + while ((t & 1u) == 0u) { + t >>= 1u; + ++count; + } + } + flags.cf = (s == 0u); + flags.zf = (count == 0u); + return static_cast(count); +} + +static inline word op_tzcnt64(word s, Flags& flags) { + word count = 64ull; + if (s != 0ull) { + count = 0ull; + word t = s; + while ((t & 1ull) == 0ull) { + t >>= 1u; + ++count; + } + } + flags.cf = (s == 0ull); + flags.zf = (count == 0ull); + return count; +} + +#if defined(_MSC_VER) +extern "C" __declspec(dllexport) std::uint32_t host_has_bmi1() { + int info[4]{}; + __cpuid(info, 0); + if (info[0] < 7) return 0u; + __cpuidex(info, 7, 0); + return (static_cast(info[1]) & (1u << 3)) != 0u ? 1u : 0u; +} +#endif +""" + + +def gpr_info(register, ins): + """Map volatile GPR (64/32/16/8-bit low) to (name, width_bits), rejecting nonvolatile/high-byte.""" + if register in VOLATILE_GPR64: + return VOLATILE_GPR64[register], 64 + if register in VOLATILE_GPR32: + return VOLATILE_GPR32[register], 32 + if register in VOLATILE_GPR16: + return VOLATILE_GPR16[register], 16 + if register in VOLATILE_GPR8: + return VOLATILE_GPR8[register], 8 + if register in HIGH_BYTE_GPRS: + raise ValueError(f"unsupported high-byte GPR {register} at RVA {ins.ip:#x}: {ins}") + if register in NONVOLATILE_GPR: + raise ValueError(f"nonvolatile GPR {register} at RVA {ins.ip:#x}: {ins}") + raise ValueError(f"unsupported GPR {register} at RVA {ins.ip:#x}: {ins}") + + +def flat_address(ins, expected_bytes, *, write=False): + """Lower a flat zero-displacement [rcx|rdx|r8] memory operand (stores only to [r8]).""" + if ins.is_ip_rel_memory_operand or ins.memory_base in (R.RIP, R.EIP): + raise ValueError(f"RIP-relative memory operand at RVA {ins.ip:#x}: {ins}") + if ins.memory_index != R.NONE: + raise ValueError(f"SIB index memory operand at RVA {ins.ip:#x}: {ins}") + base = ins.memory_base + if base == R.NONE or not RegisterExt.is_gpr64(base) or base not in ARGUMENTS: + raise ValueError(f"bad base register in memory operand at RVA {ins.ip:#x}: {ins}") + if ins.memory_displacement != 0: + raise ValueError(f"displaced memory operand at RVA {ins.ip:#x}: {ins}") + if write and base != R.R8: + raise ValueError(f"non-r8 store memory operand at RVA {ins.ip:#x}: {ins}") + actual_bytes = MemorySizeExt.size(ins.memory_size) + if actual_bytes != expected_bytes: + raise ValueError( + f"unexpected {actual_bytes}-byte memory operand (expected {expected_bytes}) at RVA {ins.ip:#x}: {ins}" + ) + return ARGUMENTS[base] + + +def _immediate_value(ins, op_index, width): + kind = ins.op_kind(op_index) + if kind == OpKind.IMMEDIATE8: + return ins.immediate8 & 0xFF + if kind == OpKind.IMMEDIATE32: + return ins.immediate32 & 0xFFFFFFFF + if kind == OpKind.IMMEDIATE64: + return ins.immediate64 & 0xFFFFFFFFFFFFFFFF + if kind == OpKind.IMMEDIATE8TO32: + return ins.immediate8to32 & 0xFFFFFFFF + if kind == OpKind.IMMEDIATE8TO64: + return ins.immediate8to64 & 0xFFFFFFFFFFFFFFFF + if kind == OpKind.IMMEDIATE32TO64: + return ins.immediate32to64 & 0xFFFFFFFFFFFFFFFF + raise ValueError(f"unsupported immediate kind {kind} for {width}-bit op at RVA {ins.ip:#x}: {ins}") + + +def lift_code(name, start, raw): + """Decode and lift one bounded straight-line BMI1 ANDN/BEXTR/TZCNT leaf function.""" + instructions = list(Decoder(64, raw, ip=start)) + if not instructions or instructions[-1].next_ip != start + len(raw): + raise ValueError(f"truncated instruction stream in {name} at RVA {start:#x}") + if any(ins.is_invalid for ins in instructions): + bad = next(ins for ins in instructions if ins.is_invalid) + raise ValueError(f"invalid instruction at RVA {bad.ip:#x}") + + defined_gpr = {"rcx", "rdx", "r8"} + used_scratch = set() + defined_flags = set() + statements = [] + returned = False + + def note_scratch(reg_name): + if reg_name in ("r9", "r10", "r11"): + used_scratch.add(reg_name) + + def read_reg(op_index, ins, expected_width): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register operand {op_index} at RVA {ins.ip:#x}: {ins}") + reg_name, width = gpr_info(ins.op_register(op_index), ins) + if width != expected_width: + raise ValueError(f"unexpected GPR width {width} at RVA {ins.ip:#x}: {ins}") + if reg_name not in defined_gpr: + raise ValueError(f"undefined GPR {reg_name} at RVA {ins.ip:#x}: {ins}") + note_scratch(reg_name) + mask = {8: "0xFFull", 32: "0xFFFFFFFFull"}.get(width) + return f"({reg_name} & {mask})" if mask else reg_name + + def check_dst_reg(op_index, ins, expected_width, *, require_defined=False): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register destination at RVA {ins.ip:#x}: {ins}") + reg_name, width = gpr_info(ins.op_register(op_index), ins) + if width != expected_width: + raise ValueError(f"unexpected GPR destination width {width} at RVA {ins.ip:#x}: {ins}") + if reg_name in ARGUMENT_NAMES: + raise ValueError(f"cannot write argument GPR {reg_name} at RVA {ins.ip:#x}: {ins}") + if require_defined and reg_name not in defined_gpr: + raise ValueError(f"undefined GPR {reg_name} at RVA {ins.ip:#x}: {ins}") + note_scratch(reg_name) + return reg_name + + def read_rm(op_index, ins, width): + kind = ins.op_kind(op_index) + if kind == OpKind.REGISTER: + return read_reg(op_index, ins, width) + if kind == OpKind.MEMORY: + addr = flat_address(ins, width // 8, write=False) + ctype = {8: "std::uint8_t", 32: "std::uint32_t", 64: "std::uint64_t"}[width] + load_var = f"ld_{ins.ip:x}_{op_index}" + statements.append(f"const word {load_var} = static_cast(load_always<{ctype}>({addr}));") + return load_var + raise ValueError(f"unsupported operand at RVA {ins.ip:#x}: {ins}") + + for ins in instructions: + if returned: + raise ValueError(f"unreachable instruction after ret at RVA {ins.ip:#x}: {ins}") + if ins.has_lock_prefix or ins.has_rep_prefix or ins.has_repne_prefix or ins.has_segment_prefix: + raise ValueError(f"unsupported instruction prefix at RVA {ins.ip:#x}: {ins}") + + op_code = ins.op_code() + encoding = op_code.encoding + if encoding == EncodingKind.EVEX or ins.op_mask != R.NONE or ins.zeroing_masking or ins.is_broadcast: + raise ValueError(f"unsupported EVEX instruction at RVA {ins.ip:#x}: {ins}") + if encoding == EncodingKind.XOP: + raise ValueError(f"unsupported XOP instruction at RVA {ins.ip:#x}: {ins}") + if ins.code != Code.RETNQ and ins.flow_control != FlowControl.NEXT: + raise ValueError(f"non-leaf branch or call at RVA {ins.ip:#x}: {ins}") + + code = ins.code + if code in BMI1_LOGIC_SPECS: + kind, width, expected_enc, out_flags = BMI1_LOGIC_SPECS[code] + if encoding != expected_enc: + raise ValueError(f"unexpected encoding for {kind} at RVA {ins.ip:#x}: {ins}") + if kind == "andn": + src1_expr = read_reg(1, ins, width) + src2_expr = read_rm(2, ins, width) + dst = check_dst_reg(0, ins, width, require_defined=False) + statements.append(f"{dst} = op_andn{width}({src1_expr}, {src2_expr}, flags);") + elif kind == "bextr": + src1_expr = read_rm(1, ins, width) + src2_expr = read_reg(2, ins, width) + dst = check_dst_reg(0, ins, width, require_defined=False) + statements.append(f"{dst} = op_bextr{width}({src1_expr}, {src2_expr}, flags);") + else: # tzcnt + src_expr = read_rm(1, ins, width) + dst = check_dst_reg(0, ins, width, require_defined=False) + statements.append(f"{dst} = op_tzcnt{width}({src_expr}, flags);") + defined_gpr.add(dst) + defined_flags = set(out_flags) + elif encoding == EncodingKind.VEX: + raise ValueError(f"unsupported VEX instruction at RVA {ins.ip:#x}: {ins}") + elif code == Code.RETNQ: + if "rax" not in defined_gpr: + raise ValueError(f"return with undefined RAX at RVA {ins.ip:#x}") + statements.append("return rax;") + returned = True + elif code in MOV_WIDTHS: + width = MOV_WIDTHS[code] + if ins.op0_kind == OpKind.REGISTER and ins.op1_kind in (OpKind.REGISTER, OpKind.MEMORY): + src_expr = read_rm(1, ins, width) + dst = check_dst_reg(0, ins, width, require_defined=(width < 32)) + statements.append(f"{dst} = update_gpr_width({dst}, {src_expr}, {width}u);") + if width >= 32: + defined_gpr.add(dst) + elif ins.op0_kind == OpKind.MEMORY and ins.op1_kind == OpKind.REGISTER: + src_expr = read_rm(1, ins, width) + addr = flat_address(ins, width // 8, write=True) + ctype = {8: "std::uint8_t", 32: "std::uint32_t", 64: "std::uint64_t"}[width] + statements.append(f"store_always<{ctype}>({addr}, static_cast<{ctype}>({src_expr}));") + elif ins.op0_kind == OpKind.REGISTER: + imm = _immediate_value(ins, 1, width) + dst = check_dst_reg(0, ins, width, require_defined=(width < 32)) + statements.append(f"{dst} = update_gpr_width({dst}, {imm:#x}ull, {width}u);") + if width >= 32: + defined_gpr.add(dst) + elif ins.op0_kind == OpKind.MEMORY: + imm = _immediate_value(ins, 1, width) + addr = flat_address(ins, width // 8, write=True) + ctype = {8: "std::uint8_t", 32: "std::uint32_t", 64: "std::uint64_t"}[width] + statements.append(f"store_always<{ctype}>({addr}, static_cast<{ctype}>({imm:#x}ull));") + else: + raise ValueError(f"unsupported mov operands at RVA {ins.ip:#x}: {ins}") + elif code in MOVZX_SPECS: + dst_width, src_width = MOVZX_SPECS[code] + src_expr = read_rm(1, ins, src_width) + dst = check_dst_reg(0, ins, dst_width, require_defined=False) + statements.append(f"{dst} = {src_expr};") + defined_gpr.add(dst) + elif code in XOR_WIDTHS: + width = XOR_WIDTHS[code] + if ( + ins.op0_kind == OpKind.REGISTER + and ins.op1_kind == OpKind.REGISTER + and ins.op0_register == ins.op1_register + ): + dst = check_dst_reg(0, ins, width, require_defined=False) + statements.append(f"{dst} = 0ull;") + defined_gpr.add(dst) + else: + dst = check_dst_reg(0, ins, width, require_defined=True) + lhs_expr = read_reg(0, ins, width) + if ins.op1_kind in (OpKind.REGISTER, OpKind.MEMORY): + rhs_expr = read_rm(1, ins, width) + else: + rhs_expr = f"{_immediate_value(ins, 1, width):#x}ull" + statements.append(f"{dst} = update_gpr_width({dst}, {lhs_expr} ^ {rhs_expr}, {width}u);") + statements.append(f"compute_logic_flags({dst}, {width}u, flags);") + defined_flags = {"cf", "zf", "sf", "of", "pf"} + elif code in OR_WIDTHS: + width = OR_WIDTHS[code] + dst = check_dst_reg(0, ins, width, require_defined=True) + lhs_expr = read_reg(0, ins, width) + if ins.op1_kind in (OpKind.REGISTER, OpKind.MEMORY): + rhs_expr = read_rm(1, ins, width) + else: + rhs_expr = f"{_immediate_value(ins, 1, width):#x}ull" + statements.append(f"{dst} = update_gpr_width({dst}, {lhs_expr} | {rhs_expr}, {width}u);") + statements.append(f"compute_logic_flags({dst}, {width}u, flags);") + defined_flags = {"cf", "zf", "sf", "of", "pf"} + elif code in SHL_SPECS: + width, is_one = SHL_SPECS[code] + dst = check_dst_reg(0, ins, width, require_defined=True) + cnt = 1 if is_one else (ins.immediate8 & 0xFF) + eff = cnt & (31 if width == 32 else 63) + statements.append(f"{dst} = op_shl({dst}, {width}u, {cnt}u, flags);") + if eff == 1: + defined_flags = {"cf", "zf", "sf", "of", "pf"} + elif eff > 1: + defined_flags = {"cf", "zf", "sf", "pf"} + elif code in SETCC_SPECS: + flag_name, cond_expr = SETCC_SPECS[code] + if flag_name not in defined_flags: + raise ValueError(f"undefined flag {flag_name} read by {ins} at RVA {ins.ip:#x}") + if ins.op0_kind == OpKind.REGISTER: + dst = check_dst_reg(0, ins, 8, require_defined=True) + statements.append(f"{dst} = update_gpr_width({dst}, ({cond_expr}) ? 1ull : 0ull, 8u);") + elif ins.op0_kind == OpKind.MEMORY: + addr = flat_address(ins, 1, write=True) + statements.append( + f"store_always({addr}, static_cast(({cond_expr}) ? 1u : 0u));" + ) + else: + raise ValueError(f"unsupported setcc operand at RVA {ins.ip:#x}: {ins}") + else: + raise ValueError(f"unsupported instruction at RVA {ins.ip:#x}: {ins}") + + if not returned: + raise ValueError(f"missing terminal ret in {name} at RVA {start + len(raw):#x}") + + decls = [" word rax = 0ull;"] + for gpr in ("r9", "r10", "r11"): + if gpr in used_scratch: + decls.append(f" word {gpr} = 0ull;") + decls.append(" Flags flags{};") + decls.append(" (void)flags;") + body = [f" {stmt}" for stmt in statements] + lines = [ + f'extern "C" __declspec(dllexport) std::uint64_t lifted_{name}(word rcx, word rdx, word r8) {{', + " (void)rcx; (void)rdx; (void)r8;", + *decls, + *body, + "}", + ] + return "\n".join(lines), len(instructions) + + +def lift(pe, name): + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + source, count = lift_code(name, entry, raw) + return source, entry, count + + +def translate_pe(pe, names): + if pe.FILE_HEADER.Machine != 0x8664 or pe.OPTIONAL_HEADER.Magic != 0x20B: + raise ValueError("expected AMD64 PE32+") + lifted = [lift(pe, name) for name in names] + source = PRELUDE + "\n".join(f"\n{text}" for text, _, _ in lifted) + "\n" + meta = [(name, entry, count) for name, (_, entry, count) in zip(names, lifted)] + return source, meta + + +def translate(image, names): + with pefile.PE(str(image), fast_load=True) as pe: + return translate_pe(pe, names) + + +def _same_path(a, b): + try: + return os.path.samefile(a, b) + except OSError: + return a.resolve(strict=False) == b.resolve(strict=False) + + +def _write_atomic(path, text): + path.parent.mkdir(parents=True, exist_ok=True) + tmp_path = None + try: + with tempfile.NamedTemporaryFile( + mode="w", + encoding="utf-8", + dir=path.parent, + prefix=f".{path.name}.", + suffix=".tmp", + delete=False, + ) as handle: + tmp_path = Path(handle.name) + handle.write(text) + handle.flush() + os.replace(tmp_path, path) + except BaseException: + if tmp_path is not None: + tmp_path.unlink(missing_ok=True) + raise + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("image", type=Path) + parser.add_argument("exports", help="comma-separated export names") + parser.add_argument("output", type=Path) + args = parser.parse_args(argv) + try: + if not args.image.is_file(): + raise ValueError(f"input image is not a regular file: {args.image}") + names = [n for n in args.exports.split(",") if n] + if not names: + raise ValueError("expected at least one export name") + if args.output.is_symlink(): + raise ValueError(f"output path cannot be a symlink: {args.output}") + if args.output.exists() and args.output.is_dir(): + raise ValueError(f"output path is a directory: {args.output}") + if _same_path(args.image, args.output): + raise ValueError(f"output path matches input image: {args.output}") + source, meta = translate(args.image, names) + _write_atomic(args.output, source) + for name, entry, count in meta: + print(f"{name} at RVA {entry:#x}: {count} instructions") + return 0 + except (ValueError, OSError, pefile.PEFormatError) as error: + sys.stderr.write(f"{error}\n") + return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) From 41ad992efb87bad9abf97d7a60dbf35c92e572d1 Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Thu, 26 Nov 2026 05:03:27 +0200 Subject: [PATCH 098/240] cpu: add AVX VEX FP compare AOT lifter and test suite (#2671) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 35 ++ tests/cpu/avx_cmp_aot.asm | 502 +++++++++++++++++++++++++ tests/cpu/avx_cmp_aot.def | 155 ++++++++ tests/cpu/avx_cmp_aot_check.py | 652 +++++++++++++++++++++++++++++++++ tools/cpu_avx_cmp_aot.py | 630 +++++++++++++++++++++++++++++++ 5 files changed, 1974 insertions(+) create mode 100644 tests/cpu/avx_cmp_aot.asm create mode 100644 tests/cpu/avx_cmp_aot.def create mode 100644 tests/cpu/avx_cmp_aot_check.py create mode 100644 tools/cpu_avx_cmp_aot.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 0e00d8781..dca655a14 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -7500,6 +7500,41 @@ if(EXISTS "${INTAKE_PYTHON}") check "$" "$") set_tests_properties(cpu_aot_avx_cvt_cmp_test PROPERTIES SKIP_RETURN_CODE 77) + # cpu_aot_avx_cmp + set(cpu_avx_cmp_aot_exports) + foreach(mnem IN ITEMS vcmpps_ymm vcmppd_ymm vcmpss vcmpsd) + foreach(hi IN ITEMS 0 1) + foreach(lo IN ITEMS 0 1 2 3 4 5 6 7 8 9 a b c d e f) + list(APPEND cpu_avx_cmp_aot_exports "op_${mnem}_p${hi}${lo}") + endforeach() + endforeach() + endforeach() + list(APPEND cpu_avx_cmp_aot_exports + op_vcmpps_xmm_reg op_vcmppd_xmm_reg op_vcmpps_xmm_mem op_vcmppd_xmm_mem + op_vcmpps_ymm_mem_rcx op_vcmpps_ymm_mem_rdx op_vcmpps_ymm_mem_r8 + op_vcmppd_ymm_mem_rcx op_vcmppd_ymm_mem_rdx op_vcmppd_ymm_mem_r8 + op_vcmpss_mem_rcx op_vcmpss_mem_rdx op_vcmpss_mem_r8 + op_vcmpsd_mem_rcx op_vcmpsd_mem_rdx op_vcmpsd_mem_r8 + op_vcmpps_imm_highbits + op_vcmpps_alias_dst_src1 op_vcmppd_alias_dst_src2 op_vcmpps_alias_src1_src2 op_vcmpsd_alias_all + op_vmovss_mem_glue op_vmovsd_mem_glue op_vmovss_reg_merge_glue op_vmovsd_reg_merge_glue + op_vmov_aligned_glue) + string(JOIN "," cpu_avx_cmp_aot_exports_csv ${cpu_avx_cmp_aot_exports}) + foreach(variant IN ITEMS original altered) + cpu_asm_fixture(cpu_avx_cmp_aot_${variant} avx_cmp_aot) + cpu_translation(cpu_avx_cmp_aot_${variant} cpu_avx_cmp_aot "${cpu_avx_cmp_aot_exports_csv}") + endforeach() + target_compile_definitions(cpu_avx_cmp_aot_altered PRIVATE ALTER_AVX_CMP) + add_test(NAME cpu_aot_avx_cmp COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/cpu/avx_cmp_aot_check.py" + "$" + "$" + "$" + "$") + set_tests_properties(cpu_aot_avx_cmp PROPERTIES + SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/cpu_aot_avx_cmp.txt") + cpu_asm_fixture(cpu_avx_scalar_fp avx_scalar_fp) set(avx_scalar_fp_fixture "${CMAKE_CURRENT_BINARY_DIR}/cpu_avx_scalar_fp_lifted.cpp") add_custom_command(OUTPUT "${avx_scalar_fp_fixture}" diff --git a/tests/cpu/avx_cmp_aot.asm b/tests/cpu/avx_cmp_aot.asm new file mode 100644 index 000000000..fb7295d95 --- /dev/null +++ b/tests/cpu/avx_cmp_aot.asm @@ -0,0 +1,502 @@ +; coverage: record cpu_aot_avx_cmp +; Source-owned MASM fixture for VEX.128 and VEX.256 AVX FP compare instructions +; (vcmpps, vcmppd, vcmpss, vcmpsd) across all 32 5-bit predicates (0x00..0x1F), +; flat [rcx|rdx|r8] memory sources, scalar upper-lane preservation, and glue moves. +; ABI: void fn(const void* rcx, const void* rdx, void* r8). +.code + +MK_VCMPPS_YMM MACRO name, pred +name PROC FRAME + .endprolog + vmovups ymm1, YMMWORD PTR [rcx] + vmovups ymm2, YMMWORD PTR [rdx] + vcmpps ymm0, ymm1, ymm2, pred + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +name ENDP +ENDM + +MK_VCMPPD_YMM MACRO name, pred +name PROC FRAME + .endprolog + vmovupd ymm1, YMMWORD PTR [rcx] + vmovupd ymm2, YMMWORD PTR [rdx] + vcmppd ymm0, ymm1, ymm2, pred + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +name ENDP +ENDM + +MK_VCMPSS MACRO name, pred +name PROC FRAME + .endprolog + vmovups ymm0, YMMWORD PTR [r8] + vmovups ymm1, YMMWORD PTR [rcx] + vmovups ymm2, YMMWORD PTR [rdx] + vcmpss xmm0, xmm1, xmm2, pred + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +name ENDP +ENDM + +MK_VCMPSD MACRO name, pred +name PROC FRAME + .endprolog + vmovupd ymm0, YMMWORD PTR [r8] + vmovupd ymm1, YMMWORD PTR [rcx] + vmovupd ymm2, YMMWORD PTR [rdx] + vcmpsd xmm0, xmm1, xmm2, pred + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +name ENDP +ENDM + +; --- VCMPPS YMM predicates 0x00..0x1F --- +op_vcmpps_ymm_p00 PROC FRAME + .endprolog + vmovups ymm1, YMMWORD PTR [rcx] + vmovups ymm2, YMMWORD PTR [rdx] +IFDEF ALTER_AVX_CMP + vcmpps ymm0, ymm1, ymm2, 04h +ELSE + vcmpps ymm0, ymm1, ymm2, 00h +ENDIF + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmpps_ymm_p00 ENDP + +MK_VCMPPS_YMM op_vcmpps_ymm_p01, 01h +MK_VCMPPS_YMM op_vcmpps_ymm_p02, 02h +MK_VCMPPS_YMM op_vcmpps_ymm_p03, 03h +MK_VCMPPS_YMM op_vcmpps_ymm_p04, 04h +MK_VCMPPS_YMM op_vcmpps_ymm_p05, 05h +MK_VCMPPS_YMM op_vcmpps_ymm_p06, 06h +MK_VCMPPS_YMM op_vcmpps_ymm_p07, 07h +MK_VCMPPS_YMM op_vcmpps_ymm_p08, 08h +MK_VCMPPS_YMM op_vcmpps_ymm_p09, 09h +MK_VCMPPS_YMM op_vcmpps_ymm_p0a, 0Ah +MK_VCMPPS_YMM op_vcmpps_ymm_p0b, 0Bh +MK_VCMPPS_YMM op_vcmpps_ymm_p0c, 0Ch +MK_VCMPPS_YMM op_vcmpps_ymm_p0d, 0Dh +MK_VCMPPS_YMM op_vcmpps_ymm_p0e, 0Eh +MK_VCMPPS_YMM op_vcmpps_ymm_p0f, 0Fh +MK_VCMPPS_YMM op_vcmpps_ymm_p10, 10h +MK_VCMPPS_YMM op_vcmpps_ymm_p11, 11h +MK_VCMPPS_YMM op_vcmpps_ymm_p12, 12h +MK_VCMPPS_YMM op_vcmpps_ymm_p13, 13h +MK_VCMPPS_YMM op_vcmpps_ymm_p14, 14h +MK_VCMPPS_YMM op_vcmpps_ymm_p15, 15h +MK_VCMPPS_YMM op_vcmpps_ymm_p16, 16h +MK_VCMPPS_YMM op_vcmpps_ymm_p17, 17h +MK_VCMPPS_YMM op_vcmpps_ymm_p18, 18h +MK_VCMPPS_YMM op_vcmpps_ymm_p19, 19h +MK_VCMPPS_YMM op_vcmpps_ymm_p1a, 1Ah +MK_VCMPPS_YMM op_vcmpps_ymm_p1b, 1Bh +MK_VCMPPS_YMM op_vcmpps_ymm_p1c, 1Ch +MK_VCMPPS_YMM op_vcmpps_ymm_p1d, 1Dh +MK_VCMPPS_YMM op_vcmpps_ymm_p1e, 1Eh +MK_VCMPPS_YMM op_vcmpps_ymm_p1f, 1Fh + +; --- VCMPPD YMM predicates 0x00..0x1F --- +MK_VCMPPD_YMM op_vcmppd_ymm_p00, 00h +op_vcmppd_ymm_p01 PROC FRAME + .endprolog + vmovupd ymm1, YMMWORD PTR [rcx] + vmovupd ymm2, YMMWORD PTR [rdx] +IFDEF ALTER_AVX_CMP + vcmppd ymm0, ymm1, ymm2, 05h +ELSE + vcmppd ymm0, ymm1, ymm2, 01h +ENDIF + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmppd_ymm_p01 ENDP + +MK_VCMPPD_YMM op_vcmppd_ymm_p02, 02h +MK_VCMPPD_YMM op_vcmppd_ymm_p03, 03h +MK_VCMPPD_YMM op_vcmppd_ymm_p04, 04h +MK_VCMPPD_YMM op_vcmppd_ymm_p05, 05h +MK_VCMPPD_YMM op_vcmppd_ymm_p06, 06h +MK_VCMPPD_YMM op_vcmppd_ymm_p07, 07h +MK_VCMPPD_YMM op_vcmppd_ymm_p08, 08h +MK_VCMPPD_YMM op_vcmppd_ymm_p09, 09h +MK_VCMPPD_YMM op_vcmppd_ymm_p0a, 0Ah +MK_VCMPPD_YMM op_vcmppd_ymm_p0b, 0Bh +MK_VCMPPD_YMM op_vcmppd_ymm_p0c, 0Ch +MK_VCMPPD_YMM op_vcmppd_ymm_p0d, 0Dh +MK_VCMPPD_YMM op_vcmppd_ymm_p0e, 0Eh +MK_VCMPPD_YMM op_vcmppd_ymm_p0f, 0Fh +MK_VCMPPD_YMM op_vcmppd_ymm_p10, 10h +MK_VCMPPD_YMM op_vcmppd_ymm_p11, 11h +MK_VCMPPD_YMM op_vcmppd_ymm_p12, 12h +MK_VCMPPD_YMM op_vcmppd_ymm_p13, 13h +MK_VCMPPD_YMM op_vcmppd_ymm_p14, 14h +MK_VCMPPD_YMM op_vcmppd_ymm_p15, 15h +MK_VCMPPD_YMM op_vcmppd_ymm_p16, 16h +MK_VCMPPD_YMM op_vcmppd_ymm_p17, 17h +MK_VCMPPD_YMM op_vcmppd_ymm_p18, 18h +MK_VCMPPD_YMM op_vcmppd_ymm_p19, 19h +MK_VCMPPD_YMM op_vcmppd_ymm_p1a, 1Ah +MK_VCMPPD_YMM op_vcmppd_ymm_p1b, 1Bh +MK_VCMPPD_YMM op_vcmppd_ymm_p1c, 1Ch +MK_VCMPPD_YMM op_vcmppd_ymm_p1d, 1Dh +MK_VCMPPD_YMM op_vcmppd_ymm_p1e, 1Eh +MK_VCMPPD_YMM op_vcmppd_ymm_p1f, 1Fh + +; --- VCMPSS predicates 0x00..0x1F --- +MK_VCMPSS op_vcmpss_p00, 00h +MK_VCMPSS op_vcmpss_p01, 01h +op_vcmpss_p02 PROC FRAME + .endprolog + vmovups ymm0, YMMWORD PTR [r8] + vmovups ymm1, YMMWORD PTR [rcx] + vmovups ymm2, YMMWORD PTR [rdx] +IFDEF ALTER_AVX_CMP + vcmpss xmm0, xmm2, xmm1, 02h +ELSE + vcmpss xmm0, xmm1, xmm2, 02h +ENDIF + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmpss_p02 ENDP + +MK_VCMPSS op_vcmpss_p03, 03h +MK_VCMPSS op_vcmpss_p04, 04h +MK_VCMPSS op_vcmpss_p05, 05h +MK_VCMPSS op_vcmpss_p06, 06h +MK_VCMPSS op_vcmpss_p07, 07h +MK_VCMPSS op_vcmpss_p08, 08h +MK_VCMPSS op_vcmpss_p09, 09h +MK_VCMPSS op_vcmpss_p0a, 0Ah +MK_VCMPSS op_vcmpss_p0b, 0Bh +MK_VCMPSS op_vcmpss_p0c, 0Ch +MK_VCMPSS op_vcmpss_p0d, 0Dh +MK_VCMPSS op_vcmpss_p0e, 0Eh +MK_VCMPSS op_vcmpss_p0f, 0Fh +MK_VCMPSS op_vcmpss_p10, 10h +MK_VCMPSS op_vcmpss_p11, 11h +MK_VCMPSS op_vcmpss_p12, 12h +MK_VCMPSS op_vcmpss_p13, 13h +MK_VCMPSS op_vcmpss_p14, 14h +MK_VCMPSS op_vcmpss_p15, 15h +MK_VCMPSS op_vcmpss_p16, 16h +MK_VCMPSS op_vcmpss_p17, 17h +MK_VCMPSS op_vcmpss_p18, 18h +MK_VCMPSS op_vcmpss_p19, 19h +MK_VCMPSS op_vcmpss_p1a, 1Ah +MK_VCMPSS op_vcmpss_p1b, 1Bh +MK_VCMPSS op_vcmpss_p1c, 1Ch +MK_VCMPSS op_vcmpss_p1d, 1Dh +MK_VCMPSS op_vcmpss_p1e, 1Eh +MK_VCMPSS op_vcmpss_p1f, 1Fh + +; --- VCMPSD predicates 0x00..0x1F --- +MK_VCMPSD op_vcmpsd_p00, 00h +MK_VCMPSD op_vcmpsd_p01, 01h +MK_VCMPSD op_vcmpsd_p02, 02h +MK_VCMPSD op_vcmpsd_p03, 03h +MK_VCMPSD op_vcmpsd_p04, 04h +MK_VCMPSD op_vcmpsd_p05, 05h +MK_VCMPSD op_vcmpsd_p06, 06h +MK_VCMPSD op_vcmpsd_p07, 07h +MK_VCMPSD op_vcmpsd_p08, 08h +MK_VCMPSD op_vcmpsd_p09, 09h +MK_VCMPSD op_vcmpsd_p0a, 0Ah +MK_VCMPSD op_vcmpsd_p0b, 0Bh +MK_VCMPSD op_vcmpsd_p0c, 0Ch +MK_VCMPSD op_vcmpsd_p0d, 0Dh +MK_VCMPSD op_vcmpsd_p0e, 0Eh +MK_VCMPSD op_vcmpsd_p0f, 0Fh +MK_VCMPSD op_vcmpsd_p10, 10h +MK_VCMPSD op_vcmpsd_p11, 11h +MK_VCMPSD op_vcmpsd_p12, 12h +MK_VCMPSD op_vcmpsd_p13, 13h +MK_VCMPSD op_vcmpsd_p14, 14h +MK_VCMPSD op_vcmpsd_p15, 15h +MK_VCMPSD op_vcmpsd_p16, 16h +MK_VCMPSD op_vcmpsd_p17, 17h +MK_VCMPSD op_vcmpsd_p18, 18h +MK_VCMPSD op_vcmpsd_p19, 19h +MK_VCMPSD op_vcmpsd_p1a, 1Ah +MK_VCMPSD op_vcmpsd_p1b, 1Bh +MK_VCMPSD op_vcmpsd_p1c, 1Ch +MK_VCMPSD op_vcmpsd_p1d, 1Dh +MK_VCMPSD op_vcmpsd_p1e, 1Eh +MK_VCMPSD op_vcmpsd_p1f, 1Fh + +; --- VEX.128 packed & upper-zeroing checks --- +op_vcmpps_xmm_reg PROC FRAME + .endprolog + vmovups ymm0, YMMWORD PTR [r8] + vmovups ymm1, YMMWORD PTR [rcx] + vmovups ymm2, YMMWORD PTR [rdx] +IFDEF ALTER_AVX_CMP + vcmpps ymm0, ymm1, ymm2, 00h +ELSE + vcmpps xmm0, xmm1, xmm2, 00h +ENDIF + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmpps_xmm_reg ENDP + +op_vcmppd_xmm_reg PROC FRAME + .endprolog + vmovupd ymm0, YMMWORD PTR [r8] + vmovupd ymm1, YMMWORD PTR [rcx] + vmovupd ymm2, YMMWORD PTR [rdx] + vcmppd xmm0, xmm1, xmm2, 0Ch + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmppd_xmm_reg ENDP + +op_vcmpps_xmm_mem PROC FRAME + .endprolog + vmovups ymm0, YMMWORD PTR [r8] + vmovups ymm1, YMMWORD PTR [rcx] + vcmpps xmm0, xmm1, XMMWORD PTR [rdx], 02h + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmpps_xmm_mem ENDP + +op_vcmppd_xmm_mem PROC FRAME + .endprolog + vmovupd ymm0, YMMWORD PTR [r8] + vmovupd ymm1, YMMWORD PTR [rcx] + vcmppd xmm0, xmm1, XMMWORD PTR [rdx], 11h + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmppd_xmm_mem ENDP + +; --- Flat [rcx|rdx|r8] memory-source forms --- +op_vcmpps_ymm_mem_rcx PROC FRAME + .endprolog + vmovups ymm1, YMMWORD PTR [rdx] + vcmpps ymm0, ymm1, YMMWORD PTR [rcx], 01h + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmpps_ymm_mem_rcx ENDP + +op_vcmpps_ymm_mem_rdx PROC FRAME + .endprolog + vmovups ymm1, YMMWORD PTR [rcx] + vcmpps ymm0, ymm1, YMMWORD PTR [rdx], 0Eh + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmpps_ymm_mem_rdx ENDP + +op_vcmpps_ymm_mem_r8 PROC FRAME + .endprolog + vmovups ymm1, YMMWORD PTR [rcx] + vcmpps ymm0, ymm1, YMMWORD PTR [r8], 12h + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmpps_ymm_mem_r8 ENDP + +op_vcmppd_ymm_mem_rcx PROC FRAME + .endprolog + vmovupd ymm1, YMMWORD PTR [rdx] + vcmppd ymm0, ymm1, YMMWORD PTR [rcx], 0Dh + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmppd_ymm_mem_rcx ENDP + +op_vcmppd_ymm_mem_rdx PROC FRAME + .endprolog + vmovupd ymm1, YMMWORD PTR [rcx] + vcmppd ymm0, ymm1, YMMWORD PTR [rdx], 15h + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmppd_ymm_mem_rdx ENDP + +op_vcmppd_ymm_mem_r8 PROC FRAME + .endprolog + vmovupd ymm1, YMMWORD PTR [rcx] + vcmppd ymm0, ymm1, YMMWORD PTR [r8], 1Eh + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmppd_ymm_mem_r8 ENDP + +op_vcmpss_mem_rcx PROC FRAME + .endprolog + vmovups ymm0, YMMWORD PTR [r8] + vmovups ymm1, YMMWORD PTR [rdx] + vcmpss xmm0, xmm1, DWORD PTR [rcx], 01h + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmpss_mem_rcx ENDP + +op_vcmpss_mem_rdx PROC FRAME + .endprolog + vmovups ymm0, YMMWORD PTR [r8] + vmovups ymm1, YMMWORD PTR [rcx] + vcmpss xmm0, xmm1, DWORD PTR [rdx], 11h + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmpss_mem_rdx ENDP + +op_vcmpss_mem_r8 PROC FRAME + .endprolog + vmovups ymm1, YMMWORD PTR [rcx] + vcmpss xmm0, xmm1, DWORD PTR [r8], 0Ch + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmpss_mem_r8 ENDP + +op_vcmpsd_mem_rcx PROC FRAME + .endprolog + vmovupd ymm0, YMMWORD PTR [r8] + vmovupd ymm1, YMMWORD PTR [rdx] + vcmpsd xmm0, xmm1, QWORD PTR [rcx], 02h + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmpsd_mem_rcx ENDP + +op_vcmpsd_mem_rdx PROC FRAME + .endprolog + vmovupd ymm0, YMMWORD PTR [r8] + vmovupd ymm1, YMMWORD PTR [rcx] +IFDEF ALTER_AVX_CMP + vcmpsd xmm0, xmm1, QWORD PTR [rdx], 0Ah +ELSE + vcmpsd xmm0, xmm1, QWORD PTR [rdx], 0Eh +ENDIF + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmpsd_mem_rdx ENDP + +op_vcmpsd_mem_r8 PROC FRAME + .endprolog + vmovupd ymm1, YMMWORD PTR [rcx] + vcmpsd xmm0, xmm1, QWORD PTR [r8], 1Dh + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmpsd_mem_r8 ENDP + +; --- High imm8 bits [7:5] ignored (0xE5 & 0x1F == 0x05) --- +op_vcmpps_imm_highbits PROC FRAME + .endprolog + vmovups ymm1, YMMWORD PTR [rcx] + vmovups ymm2, YMMWORD PTR [rdx] + vcmpps ymm0, ymm1, ymm2, 0E5h + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmpps_imm_highbits ENDP + +; --- Register aliasing & scalar/packed glue moves --- +op_vcmpps_alias_dst_src1 PROC FRAME + .endprolog + vmovups ymm0, YMMWORD PTR [rcx] + vmovups ymm1, YMMWORD PTR [rdx] + vcmpps ymm0, ymm0, ymm1, 04h + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmpps_alias_dst_src1 ENDP + +op_vcmppd_alias_dst_src2 PROC FRAME + .endprolog + vmovupd ymm1, YMMWORD PTR [rcx] + vmovupd ymm0, YMMWORD PTR [rdx] + vcmppd ymm0, ymm1, ymm0, 06h + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmppd_alias_dst_src2 ENDP + +op_vcmpps_alias_src1_src2 PROC FRAME + .endprolog + vmovups ymm1, YMMWORD PTR [rcx] + vcmpps ymm0, ymm1, ymm1, 03h + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmpps_alias_src1_src2 ENDP + +op_vcmpsd_alias_all PROC FRAME + .endprolog + vmovupd ymm0, YMMWORD PTR [rcx] + vcmpsd xmm0, xmm0, xmm0, 00h + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmpsd_alias_all ENDP + +op_vmovss_mem_glue PROC FRAME + .endprolog + vmovss xmm0, DWORD PTR [rcx] + vmovss xmm1, DWORD PTR [rdx] + vcmpss xmm0, xmm0, xmm1, 01h + vmovss DWORD PTR [r8], xmm0 + vzeroupper + ret +op_vmovss_mem_glue ENDP + +op_vmovsd_mem_glue PROC FRAME + .endprolog + vmovsd xmm0, QWORD PTR [rcx] + vmovsd xmm1, QWORD PTR [rdx] + vcmpsd xmm0, xmm0, xmm1, 01h + vmovsd QWORD PTR [r8], xmm0 + vzeroupper + ret +op_vmovsd_mem_glue ENDP + +op_vmovss_reg_merge_glue PROC FRAME + .endprolog + vmovaps ymm0, YMMWORD PTR [r8] + vmovaps xmm1, XMMWORD PTR [rcx] + vmovaps xmm2, XMMWORD PTR [rdx] + vmovss xmm0, xmm1, xmm2 + vmovaps YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vmovss_reg_merge_glue ENDP + +op_vmovsd_reg_merge_glue PROC FRAME + .endprolog + vmovapd ymm0, YMMWORD PTR [r8] + vmovapd xmm1, XMMWORD PTR [rcx] + vmovapd xmm2, XMMWORD PTR [rdx] + vmovsd xmm0, xmm1, xmm2 + vmovapd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vmovsd_reg_merge_glue ENDP + +op_vmov_aligned_glue PROC FRAME + .endprolog + vmovaps ymm1, YMMWORD PTR [rcx] + vmovapd ymm2, YMMWORD PTR [rdx] + vmovaps ymm3, ymm1 + vmovapd ymm4, ymm2 + vcmpps ymm0, ymm3, ymm4, 0Ch + vmovaps YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vmov_aligned_glue ENDP + +END diff --git a/tests/cpu/avx_cmp_aot.def b/tests/cpu/avx_cmp_aot.def new file mode 100644 index 000000000..f92943cb9 --- /dev/null +++ b/tests/cpu/avx_cmp_aot.def @@ -0,0 +1,155 @@ +EXPORTS + op_vcmpps_ymm_p00 + op_vcmpps_ymm_p01 + op_vcmpps_ymm_p02 + op_vcmpps_ymm_p03 + op_vcmpps_ymm_p04 + op_vcmpps_ymm_p05 + op_vcmpps_ymm_p06 + op_vcmpps_ymm_p07 + op_vcmpps_ymm_p08 + op_vcmpps_ymm_p09 + op_vcmpps_ymm_p0a + op_vcmpps_ymm_p0b + op_vcmpps_ymm_p0c + op_vcmpps_ymm_p0d + op_vcmpps_ymm_p0e + op_vcmpps_ymm_p0f + op_vcmpps_ymm_p10 + op_vcmpps_ymm_p11 + op_vcmpps_ymm_p12 + op_vcmpps_ymm_p13 + op_vcmpps_ymm_p14 + op_vcmpps_ymm_p15 + op_vcmpps_ymm_p16 + op_vcmpps_ymm_p17 + op_vcmpps_ymm_p18 + op_vcmpps_ymm_p19 + op_vcmpps_ymm_p1a + op_vcmpps_ymm_p1b + op_vcmpps_ymm_p1c + op_vcmpps_ymm_p1d + op_vcmpps_ymm_p1e + op_vcmpps_ymm_p1f + op_vcmppd_ymm_p00 + op_vcmppd_ymm_p01 + op_vcmppd_ymm_p02 + op_vcmppd_ymm_p03 + op_vcmppd_ymm_p04 + op_vcmppd_ymm_p05 + op_vcmppd_ymm_p06 + op_vcmppd_ymm_p07 + op_vcmppd_ymm_p08 + op_vcmppd_ymm_p09 + op_vcmppd_ymm_p0a + op_vcmppd_ymm_p0b + op_vcmppd_ymm_p0c + op_vcmppd_ymm_p0d + op_vcmppd_ymm_p0e + op_vcmppd_ymm_p0f + op_vcmppd_ymm_p10 + op_vcmppd_ymm_p11 + op_vcmppd_ymm_p12 + op_vcmppd_ymm_p13 + op_vcmppd_ymm_p14 + op_vcmppd_ymm_p15 + op_vcmppd_ymm_p16 + op_vcmppd_ymm_p17 + op_vcmppd_ymm_p18 + op_vcmppd_ymm_p19 + op_vcmppd_ymm_p1a + op_vcmppd_ymm_p1b + op_vcmppd_ymm_p1c + op_vcmppd_ymm_p1d + op_vcmppd_ymm_p1e + op_vcmppd_ymm_p1f + op_vcmpss_p00 + op_vcmpss_p01 + op_vcmpss_p02 + op_vcmpss_p03 + op_vcmpss_p04 + op_vcmpss_p05 + op_vcmpss_p06 + op_vcmpss_p07 + op_vcmpss_p08 + op_vcmpss_p09 + op_vcmpss_p0a + op_vcmpss_p0b + op_vcmpss_p0c + op_vcmpss_p0d + op_vcmpss_p0e + op_vcmpss_p0f + op_vcmpss_p10 + op_vcmpss_p11 + op_vcmpss_p12 + op_vcmpss_p13 + op_vcmpss_p14 + op_vcmpss_p15 + op_vcmpss_p16 + op_vcmpss_p17 + op_vcmpss_p18 + op_vcmpss_p19 + op_vcmpss_p1a + op_vcmpss_p1b + op_vcmpss_p1c + op_vcmpss_p1d + op_vcmpss_p1e + op_vcmpss_p1f + op_vcmpsd_p00 + op_vcmpsd_p01 + op_vcmpsd_p02 + op_vcmpsd_p03 + op_vcmpsd_p04 + op_vcmpsd_p05 + op_vcmpsd_p06 + op_vcmpsd_p07 + op_vcmpsd_p08 + op_vcmpsd_p09 + op_vcmpsd_p0a + op_vcmpsd_p0b + op_vcmpsd_p0c + op_vcmpsd_p0d + op_vcmpsd_p0e + op_vcmpsd_p0f + op_vcmpsd_p10 + op_vcmpsd_p11 + op_vcmpsd_p12 + op_vcmpsd_p13 + op_vcmpsd_p14 + op_vcmpsd_p15 + op_vcmpsd_p16 + op_vcmpsd_p17 + op_vcmpsd_p18 + op_vcmpsd_p19 + op_vcmpsd_p1a + op_vcmpsd_p1b + op_vcmpsd_p1c + op_vcmpsd_p1d + op_vcmpsd_p1e + op_vcmpsd_p1f + op_vcmpps_xmm_reg + op_vcmppd_xmm_reg + op_vcmpps_xmm_mem + op_vcmppd_xmm_mem + op_vcmpps_ymm_mem_rcx + op_vcmpps_ymm_mem_rdx + op_vcmpps_ymm_mem_r8 + op_vcmppd_ymm_mem_rcx + op_vcmppd_ymm_mem_rdx + op_vcmppd_ymm_mem_r8 + op_vcmpss_mem_rcx + op_vcmpss_mem_rdx + op_vcmpss_mem_r8 + op_vcmpsd_mem_rcx + op_vcmpsd_mem_rdx + op_vcmpsd_mem_r8 + op_vcmpps_imm_highbits + op_vcmpps_alias_dst_src1 + op_vcmppd_alias_dst_src2 + op_vcmpps_alias_src1_src2 + op_vcmpsd_alias_all + op_vmovss_mem_glue + op_vmovsd_mem_glue + op_vmovss_reg_merge_glue + op_vmovsd_reg_merge_glue + op_vmov_aligned_glue diff --git a/tests/cpu/avx_cmp_aot_check.py b/tests/cpu/avx_cmp_aot_check.py new file mode 100644 index 000000000..83a14fbd6 --- /dev/null +++ b/tests/cpu/avx_cmp_aot_check.py @@ -0,0 +1,652 @@ +"""Differential, edge-case, MXCSR, refusal, CLI, and coverage checks for AVX VEX FP compare AOT.""" + +import ctypes +import os +from pathlib import Path +import struct +import sys +from tempfile import TemporaryDirectory + +from iced_x86 import ( + Code, + Decoder, + Encoder, + Instruction, + MemoryOperand, + Mnemonic, + Register as R, +) +import pefile + +THIS_DIR = Path(__file__).resolve().parent +TOOLS_DIR = THIS_DIR.parents[1] / "tools" +sys.path.insert(0, str(THIS_DIR)) +sys.path.insert(0, str(TOOLS_DIR)) + +from avx_horiz_fp import _guarded_buf # noqa: E402 +from cpu_avx_cmp_aot import lift_code, main as tool_main, translate # noqa: E402 +from cpu_leaf_aot import bounded_code, export_rva # noqa: E402 + + +VCMPPS_PRED_EXPORTS = tuple(f"op_vcmpps_ymm_p{p:02x}" for p in range(32)) +VCMPPD_PRED_EXPORTS = tuple(f"op_vcmppd_ymm_p{p:02x}" for p in range(32)) +VCMPSS_PRED_EXPORTS = tuple(f"op_vcmpss_p{p:02x}" for p in range(32)) +VCMPSD_PRED_EXPORTS = tuple(f"op_vcmpsd_p{p:02x}" for p in range(32)) + +EXTRA_EXPORTS = ( + "op_vcmpps_xmm_reg", + "op_vcmppd_xmm_reg", + "op_vcmpps_xmm_mem", + "op_vcmppd_xmm_mem", + "op_vcmpps_ymm_mem_rcx", + "op_vcmpps_ymm_mem_rdx", + "op_vcmpps_ymm_mem_r8", + "op_vcmppd_ymm_mem_rcx", + "op_vcmppd_ymm_mem_rdx", + "op_vcmppd_ymm_mem_r8", + "op_vcmpss_mem_rcx", + "op_vcmpss_mem_rdx", + "op_vcmpss_mem_r8", + "op_vcmpsd_mem_rcx", + "op_vcmpsd_mem_rdx", + "op_vcmpsd_mem_r8", + "op_vcmpps_imm_highbits", + "op_vcmpps_alias_dst_src1", + "op_vcmppd_alias_dst_src2", + "op_vcmpps_alias_src1_src2", + "op_vcmpsd_alias_all", + "op_vmovss_mem_glue", + "op_vmovsd_mem_glue", + "op_vmovss_reg_merge_glue", + "op_vmovsd_reg_merge_glue", + "op_vmov_aligned_glue", +) + +EXPORTS = ( + VCMPPS_PRED_EXPORTS + + VCMPPD_PRED_EXPORTS + + VCMPSS_PRED_EXPORTS + + VCMPSD_PRED_EXPORTS + + EXTRA_EXPORTS +) + +# (export_name, ref_export_override_or_None) +ALTERED_CASES = ( + ("op_vcmpps_ymm_p00", "op_vcmpps_ymm_p04"), + ("op_vcmppd_ymm_p01", "op_vcmppd_ymm_p05"), + ("op_vcmpss_p02", None), + ("op_vcmpsd_mem_rdx", None), + ("op_vcmpps_xmm_reg", "op_vcmpps_ymm_p00"), +) + +SEED = bytes(0xA0 + (i % 16) for i in range(32)) +MXCSR_DEFAULT = 0x1F80 +MXCSR_DAZ = 0x1FC0 + + +def encode_seq(*instructions): + encoder = Encoder(64) + rip = 0x1000 + for ins in instructions: + rip += encoder.encode(ins, rip) + return encoder.take_buffer() + + +def _is_nan_f32(bits: int) -> bool: + return (bits & 0x7FFFFFFF) > 0x7F800000 + + +def _is_nan_f64(bits: int) -> bool: + return (bits & 0x7FFFFFFFFFFFFFFF) > 0x7FF0000000000000 + + +def _is_subnormal_f32(bits: int) -> bool: + return 0 < (bits & 0x7FFFFFFF) < 0x00800000 + + +def _is_subnormal_f64(bits: int) -> bool: + return 0 < (bits & 0x7FFFFFFFFFFFFFFF) < 0x0010000000000000 + + +def _daz_f32(bits: int, daz: bool) -> float: + if daz and _is_subnormal_f32(bits): + bits &= 0x80000000 + return struct.unpack(" float: + if daz and _is_subnormal_f64(bits): + bits &= 0x8000000000000000 + return struct.unpack(" bool: + """Exact boolean semantics for all 32 5-bit AVX FP compare predicates (imm8 & 0x1F).""" + p = pred & 0x0F + if p == 0x00: + return not unord and x == y + if p == 0x01: + return not unord and x < y + if p == 0x02: + return not unord and x <= y + if p == 0x03: + return unord + if p == 0x04: + return unord or x != y + if p == 0x05: + return unord or not (x < y) + if p == 0x06: + return unord or not (x <= y) + if p == 0x07: + return not unord + if p == 0x08: + return unord or x == y + if p == 0x09: + return unord or x < y + if p == 0x0A: + return unord or x <= y + if p == 0x0B: + return False + if p == 0x0C: + return not unord and x != y + if p == 0x0D: + return not unord and x >= y + if p == 0x0E: + return not unord and x > y + return True + + +def ref_vcmpps(a: bytes, b: bytes, pred: int, wide: bool, daz: bool = False) -> bytes: + count = 8 if wide else 4 + xa = struct.unpack("<8I", a) + xb = struct.unpack("<8I", b) + masks = [] + for i in range(count): + unord = _is_nan_f32(xa[i]) or _is_nan_f32(xb[i]) + fx, fy = _daz_f32(xa[i], daz), _daz_f32(xb[i], daz) + masks.append(0xFFFFFFFF if cmp_pred_bool(fx, fy, unord, pred) else 0) + if not wide: + masks.extend([0, 0, 0, 0]) + return struct.pack("<8I", *masks) + + +def ref_vcmppd(a: bytes, b: bytes, pred: int, wide: bool, daz: bool = False) -> bytes: + count = 4 if wide else 2 + xa = struct.unpack("<4Q", a) + xb = struct.unpack("<4Q", b) + masks = [] + for i in range(count): + unord = _is_nan_f64(xa[i]) or _is_nan_f64(xb[i]) + dx, dy = _daz_f64(xa[i], daz), _daz_f64(xb[i], daz) + masks.append(0xFFFFFFFFFFFFFFFF if cmp_pred_bool(dx, dy, unord, pred) else 0) + if not wide: + masks.extend([0, 0]) + return struct.pack("<4Q", *masks) + + +def ref_vcmpss(a: bytes, b: bytes, pred: int, daz: bool = False) -> bytes: + xa = list(struct.unpack("<4I", a[:16])) + xb0 = struct.unpack(" bytes: + xa = list(struct.unpack("<2Q", a[:16])) + xb0 = struct.unpack(" bytes: + if name.startswith("op_vcmpps_ymm_p"): + return ref_vcmpps(a, b, int(name[-2:], 16), wide=True, daz=daz) + if name.startswith("op_vcmppd_ymm_p"): + return ref_vcmppd(a, b, int(name[-2:], 16), wide=True, daz=daz) + if name.startswith("op_vcmpss_p"): + return ref_vcmpss(a, b, int(name[-2:], 16), daz=daz) + if name.startswith("op_vcmpsd_p"): + return ref_vcmpsd(a, b, int(name[-2:], 16), daz=daz) + if name == "op_vcmpps_xmm_reg": + return ref_vcmpps(a, b, 0x00, wide=False, daz=daz) + if name == "op_vcmppd_xmm_reg": + return ref_vcmppd(a, b, 0x0C, wide=False, daz=daz) + if name == "op_vcmpps_xmm_mem": + return ref_vcmpps(a, b, 0x02, wide=False, daz=daz) + if name == "op_vcmppd_xmm_mem": + return ref_vcmppd(a, b, 0x11, wide=False, daz=daz) + if name == "op_vcmpps_ymm_mem_rcx": + return ref_vcmpps(b, a, 0x01, wide=True, daz=daz) + if name == "op_vcmpps_ymm_mem_rdx": + return ref_vcmpps(a, b, 0x0E, wide=True, daz=daz) + if name == "op_vcmpps_ymm_mem_r8": + return ref_vcmpps(a, seed, 0x12, wide=True, daz=daz) + if name == "op_vcmppd_ymm_mem_rcx": + return ref_vcmppd(b, a, 0x0D, wide=True, daz=daz) + if name == "op_vcmppd_ymm_mem_rdx": + return ref_vcmppd(a, b, 0x15, wide=True, daz=daz) + if name == "op_vcmppd_ymm_mem_r8": + return ref_vcmppd(a, seed, 0x1E, wide=True, daz=daz) + if name == "op_vcmpss_mem_rcx": + return ref_vcmpss(b, a, 0x01, daz=daz) + if name == "op_vcmpss_mem_rdx": + return ref_vcmpss(a, b, 0x11, daz=daz) + if name == "op_vcmpss_mem_r8": + return ref_vcmpss(a, seed, 0x0C, daz=daz) + if name == "op_vcmpsd_mem_rcx": + return ref_vcmpsd(b, a, 0x02, daz=daz) + if name == "op_vcmpsd_mem_rdx": + return ref_vcmpsd(a, b, 0x0E, daz=daz) + if name == "op_vcmpsd_mem_r8": + return ref_vcmpsd(a, seed, 0x1D, daz=daz) + if name == "op_vcmpps_imm_highbits": + return ref_vcmpps(a, b, 0x05, wide=True, daz=daz) + if name == "op_vcmpps_alias_dst_src1": + return ref_vcmpps(a, b, 0x04, wide=True, daz=daz) + if name == "op_vcmppd_alias_dst_src2": + return ref_vcmppd(a, b, 0x06, wide=True, daz=daz) + if name == "op_vcmpps_alias_src1_src2": + return ref_vcmpps(a, a, 0x03, wide=True, daz=daz) + if name == "op_vcmpsd_alias_all": + return ref_vcmpsd(a, a, 0x00, daz=daz) + if name == "op_vmovss_mem_glue": + res = ref_vcmpss(a[:4] + b"\x00" * 12, b[:4] + b"\x00" * 12, 0x01, daz=daz) + return res[:4] + seed[4:] + if name == "op_vmovsd_mem_glue": + res = ref_vcmpsd(a[:8] + b"\x00" * 8, b[:8] + b"\x00" * 8, 0x01, daz=daz) + return res[:8] + seed[8:] + if name == "op_vmovss_reg_merge_glue": + return b[:4] + a[4:16] + b"\x00" * 16 + if name == "op_vmovsd_reg_merge_glue": + return b[:8] + a[8:16] + b"\x00" * 16 + if name == "op_vmov_aligned_glue": + return ref_vcmpps(a, b, 0x0C, wide=True, daz=daz) + raise KeyError(name) + + +def check_translator(original_path: Path) -> None: + source_cpp, meta = translate(original_path, EXPORTS) + assert len(meta) == len(EXPORTS) and "host_has_avx" in source_cpp, len(meta) + assert "" not in source_cpp + + ld_ymm1 = Instruction.create_reg_mem(Code.VEX_VMOVUPS_YMM_YMMM256, R.YMM1, MemoryOperand(R.RCX)) + ld_ymm2 = Instruction.create_reg_mem(Code.VEX_VMOVUPD_YMM_YMMM256, R.YMM2, MemoryOperand(R.RDX)) + ld_xmm1 = Instruction.create_reg_mem(Code.VEX_VMOVAPS_XMM_XMMM128, R.XMM1, MemoryOperand(R.RCX)) + ld_xmm2 = Instruction.create_reg_mem(Code.VEX_VMOVAPD_XMM_XMMM128, R.XMM2, MemoryOperand(R.RDX)) + ld_xmm4 = Instruction.create_reg_mem(Code.VEX_VMOVUPS_XMM_XMMM128, R.XMM4, MemoryOperand(R.RCX)) + ld_xmm5 = Instruction.create_reg_mem(Code.VEX_VMOVUPS_XMM_XMMM128, R.XMM5, MemoryOperand(R.RDX)) + ld_ymm4 = Instruction.create_reg_mem(Code.VEX_VMOVAPS_YMM_YMMM256, R.YMM4, MemoryOperand(R.RCX)) + ld_ymm5 = Instruction.create_reg_mem(Code.VEX_VMOVAPS_YMM_YMMM256, R.YMM5, MemoryOperand(R.RDX)) + st_xmm0 = Instruction.create_mem_reg(Code.VEX_VMOVUPS_XMMM128_XMM, MemoryOperand(R.R8), R.XMM0) + st_ymm0 = Instruction.create_mem_reg(Code.VEX_VMOVUPS_YMMM256_YMM, MemoryOperand(R.R8), R.YMM0) + vzero = Instruction.create(Code.VEX_VZEROUPPER) + ret_ins = Instruction.create(Code.RETNQ) + + # Positive lift checks across all 6 VCMP Codes, reg & [rcx|rdx|r8] mem-src, and alternate encodings. + accepted = 0 + for code, wide, helper, is_scalar, is_double in ( + (Code.VEX_VCMPPS_XMM_XMM_XMMM128_IMM8, False, "op_vcmpps", False, False), + (Code.VEX_VCMPPS_YMM_YMM_YMMM256_IMM8, True, "op_vcmpps", False, False), + (Code.VEX_VCMPPD_XMM_XMM_XMMM128_IMM8, False, "op_vcmppd", False, True), + (Code.VEX_VCMPPD_YMM_YMM_YMMM256_IMM8, True, "op_vcmppd", False, True), + (Code.VEX_VCMPSS_XMM_XMM_XMMM32_IMM8, False, "op_vcmpss", True, False), + (Code.VEX_VCMPSD_XMM_XMM_XMMM64_IMM8, False, "op_vcmpsd", True, True), + ): + dst, s1, s2 = (R.YMM4, R.YMM4, R.YMM5) if wide else (R.XMM4, R.XMM4, R.XMM5) + loads = (ld_ymm4, ld_ymm5) if wide else (ld_xmm4, ld_xmm5) + st_code = Code.VEX_VMOVUPS_YMMM256_YMM if wide else Code.VEX_VMOVUPS_XMMM128_XMM + reg_src, _ = lift_code( + f"{helper}_reg", + 0x1000, + encode_seq( + *loads, + Instruction.create_reg_reg_reg_u32(code, dst, s1, s2, 0x3F), + Instruction.create_mem_reg(st_code, MemoryOperand(R.R8), dst), + vzero, + ret_ins, + ), + ) + assert f"{helper}(" in reg_src and "0x1fu" in reg_src, reg_src + accepted += 1 + + for base in (R.RCX, R.RDX, R.R8): + mem_src, _ = lift_code( + f"{helper}_mem_{base}", + 0x1000, + encode_seq( + loads[0], + Instruction.create_reg_reg_mem_u32(code, dst, s1, MemoryOperand(base), 0x11), + Instruction.create_mem_reg(st_code, MemoryOperand(R.R8), dst), + ret_ins, + ), + ) + loader = ( + ("load64" if is_double else "load32") + if is_scalar + else ("load256" if wide else "load128") + ) + assert f"{loader}(" in mem_src, mem_src + accepted += 1 + + # Alternate VMOVSS/VMOVSD 0F11 encodings. + for alt_code, helper in ( + (Code.VEX_VMOVSS_XMM_XMM_XMM_0F11, "op_vmovss_reg"), + (Code.VEX_VMOVSD_XMM_XMM_XMM_0F11, "op_vmovsd_reg"), + ): + alt_src, _ = lift_code( + f"alt_{helper}", + 0x1000, + encode_seq( + ld_xmm4, + ld_xmm5, + Instruction.create_reg_reg_reg(alt_code, R.XMM0, R.XMM4, R.XMM5), + st_xmm0, + ret_ins, + ), + ) + assert f"{helper}(ymm4," in alt_src, alt_src + accepted += 1 + + evex_ps = Instruction.create_reg_reg_reg_u32( + Code.EVEX_VCMPPS_KR_K1_XMM_XMMM128B32_IMM8, R.K1, R.XMM0, R.XMM1, 0 + ) + evex_pd = Instruction.create_reg_reg_reg_u32( + Code.EVEX_VCMPPD_KR_K1_YMM_YMMM256B64_IMM8, R.K1, R.YMM1, R.YMM2, 0 + ) + evex_ss = Instruction.create_reg_reg_reg_u32( + Code.EVEX_VCMPSS_KR_K1_XMM_XMMM32_IMM8_SAE, R.K1, R.XMM1, R.XMM2, 0 + ) + evex_sd = Instruction.create_reg_reg_reg_u32( + Code.EVEX_VCMPSD_KR_K1_XMM_XMMM64_IMM8_SAE, R.K1, R.XMM1, R.XMM2, 0 + ) + evex_mov = Instruction.create_reg_mem( + Code.EVEX_VMOVAPS_YMM_K1Z_YMMM256, R.YMM0, MemoryOperand(R.RCX) + ) + seg_ins = Instruction.create_reg_reg_mem_u32( + Code.VEX_VCMPPS_YMM_YMM_YMMM256_IMM8, R.YMM0, R.YMM1, MemoryOperand(R.RDX), 0 + ) + seg_ins.segment_prefix = R.FS + + rejects = [ + ("evex_vcmpps", (ld_xmm1, evex_ps, ret_ins), "unsupported EVEX instruction"), + ("evex_vcmppd", (ld_ymm1, ld_ymm2, evex_pd, ret_ins), "unsupported EVEX instruction"), + ("evex_vcmpss", (ld_xmm1, ld_xmm2, evex_ss, ret_ins), "unsupported EVEX instruction"), + ("evex_vcmpsd", (ld_xmm1, ld_xmm2, evex_sd, ret_ins), "unsupported EVEX instruction"), + ("evex_vmovaps", (evex_mov, ret_ins), "unsupported EVEX instruction"), + ("legacy_cmpps", (ld_xmm1, ld_xmm2, Instruction.create_reg_reg_u32(Code.CMPPS_XMM_XMMM128_IMM8, R.XMM1, R.XMM2, 0), ret_ins), "unsupported legacy SSE instruction"), + ("legacy_cmppd", (ld_xmm1, ld_xmm2, Instruction.create_reg_reg_u32(Code.CMPPD_XMM_XMMM128_IMM8, R.XMM1, R.XMM2, 0), ret_ins), "unsupported legacy SSE instruction"), + ("legacy_cmpss", (ld_xmm1, ld_xmm2, Instruction.create_reg_reg_u32(Code.CMPSS_XMM_XMMM32_IMM8, R.XMM1, R.XMM2, 0), ret_ins), "unsupported legacy SSE instruction"), + ("legacy_cmpsd", (ld_xmm1, ld_xmm2, Instruction.create_reg_reg_u32(Code.CMPSD_XMM_XMMM64_IMM8, R.XMM1, R.XMM2, 0), ret_ins), "unsupported legacy SSE instruction"), + ("legacy_movaps", (Instruction.create_reg_mem(Code.MOVAPS_XMM_XMMM128, R.XMM1, MemoryOperand(R.RCX)), ret_ins), "unsupported legacy SSE instruction"), + ("other_insn_vaddps", (ld_ymm1, ld_ymm2, Instruction.create_reg_reg_reg(Code.VEX_VADDPS_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2), ret_ins), "unsupported instruction"), + ("nonvol_ymm6_dst", (ld_ymm1, ld_ymm2, Instruction.create_reg_reg_reg_u32(Code.VEX_VCMPPS_YMM_YMM_YMMM256_IMM8, R.YMM6, R.YMM1, R.YMM2, 0), ret_ins), "nonvolatile vector register"), + ("nonvol_xmm15_src2", (ld_xmm1, Instruction.create_reg_reg_reg_u32(Code.VEX_VCMPSD_XMM_XMM_XMMM64_IMM8, R.XMM0, R.XMM1, R.XMM15, 0), ret_ins), "nonvolatile vector register"), + ("nonvol_ymm7_mov", (Instruction.create_reg_mem(Code.VEX_VMOVAPS_YMM_YMMM256, R.YMM7, MemoryOperand(R.RCX)), ret_ins), "nonvolatile vector register"), + ("nonvol_xmm8_movss", (Instruction.create_reg_mem(Code.VEX_VMOVSS_XMM_M32, R.XMM8, MemoryOperand(R.RCX)), ret_ins), "nonvolatile vector register"), + ("undef_vcmpps_src1", (ld_ymm2, Instruction.create_reg_reg_reg_u32(Code.VEX_VCMPPS_YMM_YMM_YMMM256_IMM8, R.YMM0, R.YMM3, R.YMM2, 0), ret_ins), "undefined vector register ymm3"), + ("undef_vcmppd_src2", (ld_ymm1, Instruction.create_reg_reg_reg_u32(Code.VEX_VCMPPD_YMM_YMM_YMMM256_IMM8, R.YMM0, R.YMM1, R.YMM4, 0), ret_ins), "undefined vector register ymm4"), + ("undef_vcmpss_alias", (ld_xmm2, Instruction.create_reg_reg_reg_u32(Code.VEX_VCMPSS_XMM_XMM_XMMM32_IMM8, R.XMM0, R.XMM0, R.XMM2, 0), ret_ins), "undefined vector register ymm0"), + ("undef_store", (Instruction.create_mem_reg(Code.VEX_VMOVUPS_YMMM256_YMM, MemoryOperand(R.R8), R.YMM0), ret_ins), "undefined vector register ymm0"), + ("disp_mem_rcx", (ld_ymm1, Instruction.create_reg_reg_mem_u32(Code.VEX_VCMPPS_YMM_YMM_YMMM256_IMM8, R.YMM0, R.YMM1, MemoryOperand(R.RCX, displ=32, displ_size=1), 0), ret_ins), "unsupported memory operand"), + ("disp_store_r8", (ld_ymm1, Instruction.create_mem_reg(Code.VEX_VMOVUPS_YMMM256_YMM, MemoryOperand(R.R8, displ=32, displ_size=1), R.YMM1), ret_ins), "unsupported memory operand"), + ("indexed_mem", (ld_ymm1, Instruction.create_reg_reg_mem_u32(Code.VEX_VCMPPD_YMM_YMM_YMMM256_IMM8, R.YMM0, R.YMM1, MemoryOperand(R.RDX, R.RCX, 4), 0), ret_ins), "unsupported memory operand"), + ("rip_rel_mem", (ld_xmm1, Instruction.create_reg_reg_mem_u32(Code.VEX_VCMPSS_XMM_XMM_XMMM32_IMM8, R.XMM0, R.XMM1, MemoryOperand(R.RIP, displ=0x1040, displ_size=4), 0), ret_ins), "unsupported memory operand"), + ("non_arg_base_rax", (ld_ymm1, Instruction.create_reg_reg_mem_u32(Code.VEX_VCMPPS_YMM_YMM_YMMM256_IMM8, R.YMM0, R.YMM1, MemoryOperand(R.RAX), 0), ret_ins), "unsupported memory operand"), + ("nonvol_base_rbx", (Instruction.create_reg_mem(Code.VEX_VMOVAPS_YMM_YMMM256, R.YMM0, MemoryOperand(R.RBX)), ret_ins), "unsupported memory operand"), + ("addr32_ecx", (ld_xmm1, Instruction.create_reg_reg_mem_u32(Code.VEX_VCMPSD_XMM_XMM_XMMM64_IMM8, R.XMM0, R.XMM1, MemoryOperand(R.ECX), 0), ret_ins), "unsupported memory operand"), + ("non_r8_store_rcx", (ld_ymm1, Instruction.create_mem_reg(Code.VEX_VMOVUPS_YMMM256_YMM, MemoryOperand(R.RCX), R.YMM1), ret_ins), "non-r8 store memory operand"), + ("non_r8_store_rdx", (ld_xmm1, Instruction.create_mem_reg(Code.VEX_VMOVSS_M32_XMM, MemoryOperand(R.RDX), R.XMM1), ret_ins), "non-r8 store memory operand"), + ("non_r8_store_sd_rcx", (ld_xmm1, Instruction.create_mem_reg(Code.VEX_VMOVSD_M64_XMM, MemoryOperand(R.RCX), R.XMM1), ret_ins), "non-r8 store memory operand"), + ("seg_prefix", (ld_ymm1, seg_ins, ret_ins), "unsupported instruction prefix"), + ("missing_ret", (ld_ymm1, ld_ymm2, Instruction.create_reg_reg_reg_u32(Code.VEX_VCMPPS_YMM_YMM_YMMM256_IMM8, R.YMM0, R.YMM1, R.YMM2, 0), st_ymm0), "missing terminal ret"), + ("after_ret", (ld_ymm1, ret_ins, st_ymm0), "unreachable instruction after ret"), + ] + for label, seq, reason in rejects: + try: + lift_code(label, 0x1000, encode_seq(*seq)) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: translator accepted invalid sequence") + + raw_rejects = [ + ("invalid_bytes", b"\xFF\xFE\xC3", "invalid instruction"), + ("empty_stream", b"", "truncated instruction stream"), + ] + for label, raw, reason in raw_rejects: + try: + lift_code(label, 0x1000, raw) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: raw stream unexpectedly accepted") + + # CLI failure exit code 1 without traceback and zero leftover temp files. + with TemporaryDirectory() as tmp: + root = Path(tmp) + out_cpp = root / "out.cpp" + out_dir = root / "out_dir" + out_dir.mkdir() + in_dir = root / "in_dir" + in_dir.mkdir() + for argv, label in ( + ([str(root / "missing.dll"), "op_vcmpps_ymm_p00", str(out_cpp)], "missing_dll"), + ([str(in_dir), "op_vcmpps_ymm_p00", str(out_cpp)], "input_dir"), + ([str(original_path), ",", str(out_cpp)], "empty_exports"), + ([str(original_path), "missing_export_xyz", str(out_cpp)], "missing_export"), + ([str(original_path), "op_vcmpps_ymm_p00", str(out_dir)], "output_dir"), + ): + try: + tool_main(argv) + except SystemExit as exc: + assert exc.code == 1, (label, exc.code) + else: + raise AssertionError(f"{label}: CLI did not exit") + assert not out_cpp.exists() + assert sorted(p.name for p in root.iterdir()) == ["in_dir", "out_dir"] + + print( + f"translator validated: {accepted} forms accepted, " + f"{len(rejects) + len(raw_rejects)} refusal controls and 5 CLI negative checks passed" + ) + + +def host_has_avx(lifted_lib) -> bool: + if hasattr(lifted_lib, "host_has_avx"): + lifted_lib.host_has_avx.argtypes = [] + lifted_lib.host_has_avx.restype = ctypes.c_uint32 + return bool(lifted_lib.host_has_avx()) + return False + + +def check_differential(native_path: Path, lifted_path: Path, altered_path: Path, altered_lifted_path: Path) -> None: + native = ctypes.CDLL(str(native_path.resolve())) + lifted = ctypes.CDLL(str(lifted_path.resolve())) + altered_native = ctypes.CDLL(str(altered_path.resolve())) + altered_lifted = ctypes.CDLL(str(altered_lifted_path.resolve())) + + exchange = lifted.host_exchange_mxcsr + exchange.argtypes, exchange.restype = [ctypes.c_uint32], ctypes.c_uint32 + + def _f32(*vals): + words = [v if isinstance(v, int) else struct.unpack(" quiet + ("op_vcmpps_ymm_p10", qnan_ps_a, qnan_ps_b, 1), # EQ_OS -> signaling + ("op_vcmpps_ymm_p11", qnan_ps_a, qnan_ps_b, 0), # LT_OQ -> quiet + ("op_vcmpps_ymm_p01", qnan_ps_a, qnan_ps_b, 1), # LT_OS -> signaling + ("op_vcmpps_ymm_p0f", qnan_ps_a, qnan_ps_b, 0), # TRUE_UQ -> quiet + ("op_vcmpps_ymm_p1f", qnan_ps_a, qnan_ps_b, 1), # TRUE_US -> signaling + ("op_vcmppd_ymm_p11", qnan_pd_a, qnan_pd_b, 0), # LT_OQ -> quiet + ("op_vcmppd_ymm_p01", qnan_pd_a, qnan_pd_b, 1), # LT_OS -> signaling + ("op_vcmpss_p11", qnan_ps_a, qnan_ps_b, 0), # scalar LT_OQ -> quiet (ignores lane1!) + ("op_vcmpss_p01", qnan_ps_a, qnan_ps_b, 1), # scalar LT_OS -> signaling + ("op_vcmpsd_p11", qnan_pd_a, qnan_pd_b, 0), # scalar LT_OQ -> quiet + ("op_vcmpsd_p01", qnan_pd_a, qnan_pd_b, 1), # scalar LT_OS -> signaling + ) + for name, a_bytes, b_bytes, want_ie in quiet_sig_checks: + _, st_n = invoke(native, "", name, a_bytes, b_bytes, MXCSR_DEFAULT, 0) + _, st_l = invoke(lifted, "lifted_", name, a_bytes, b_bytes, MXCSR_DEFAULT, 0) + if (st_n & 1) != want_ie or (st_l & 1) != want_ie: + raise AssertionError( + f"{name} MXCSR.IE mismatch: want={want_ie} native={st_n:#x} lifted={st_l:#x}" + ) + # Scalar sNaN in upper lane 1 must NOT trigger IE on lane 0 non-NaN operands. + _, st_scalar_n = invoke(native, "", "op_vcmpss_p01", f32_pairs[2][0], f32_pairs[2][1], MXCSR_DEFAULT, 0) + _, st_scalar_l = invoke(lifted, "lifted_", "op_vcmpss_p01", f32_pairs[2][0], f32_pairs[2][1], MXCSR_DEFAULT, 0) + assert (st_scalar_n & 1) == 0 and (st_scalar_l & 1) == 0, (st_scalar_n, st_scalar_l) + + # Altered controls must diverge from original and match altered native DLL. + for name, alt_ref_name in ALTERED_CASES: + is_pd = "pd_" in name or "vcmpsd" in name + a_bytes, b_bytes = (f64_pairs if is_pd else f32_pairs)[0] + if name == "op_vcmpss_p02": + a_bytes, b_bytes = f32_pairs[2] + want_orig = ref_export(name, a_bytes, b_bytes, SEED) + want_alt = ref_vcmpss(b_bytes, a_bytes, 0x02) + elif name == "op_vcmpsd_mem_rdx": + want_orig = ref_export(name, a_bytes, b_bytes, SEED) + want_alt = ref_vcmpsd(a_bytes, b_bytes, 0x0A) + else: + want_orig = ref_export(name, a_bytes, b_bytes, SEED) + want_alt = ref_export(alt_ref_name, a_bytes, b_bytes, SEED) + got_alt_n, _ = invoke(altered_native, "", name, a_bytes, b_bytes, MXCSR_DEFAULT, 0) + got_alt_l, _ = invoke(altered_lifted, "lifted_", name, a_bytes, b_bytes, MXCSR_DEFAULT, 0) + assert got_alt_n == want_alt and got_alt_l == want_alt, ( + name, got_alt_n.hex(), got_alt_l.hex(), want_alt.hex() + ) + assert got_alt_l != want_orig, f"altered {name} failed to diverge from original" + + print( + f"{cases} AVX VEX FP compare cases across {len(EXPORTS)} exports, 32 predicates, " + f"DAZ/IE modes matched native DLL and IEEE-754 reference; {len(ALTERED_CASES)} altered controls diverged" + ) + + +def record_covered_forms(original_path: Path) -> None: + record = os.environ.get("FORM_COVERAGE_RECORD") + if not record: + return + mnemonic_names = { + val: key.lower() + for key, val in vars(Mnemonic).items() + if not key.startswith("_") and isinstance(val, int) + } + forms = set() + with pefile.PE(str(original_path), fast_load=True) as pe: + for name in EXPORTS: + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + for ins in Decoder(64, raw, ip=entry): + forms.add(mnemonic_names[ins.mnemonic]) + out_path = Path(record) + out_path.parent.mkdir(parents=True, exist_ok=True) + out_path.write_text("".join(word + "\n" for word in sorted(forms)), encoding="utf-8") + + +def main() -> None: + if os.environ.get("FORM_COVERAGE_RECORD"): + Path(os.environ["FORM_COVERAGE_RECORD"]).unlink(missing_ok=True) + + original_path, lifted_path, altered_path, altered_lifted_path = (Path(p) for p in sys.argv[1:5]) + check_translator(original_path) + + lifted_lib = ctypes.CDLL(str(lifted_path.resolve())) + if not host_has_avx(lifted_lib): + print("Host lacks CPUID.01H:ECX[27:28] + XGETBV[2:1]; skipping native differential check") + sys.exit(77) + + check_differential(original_path, lifted_path, altered_path, altered_lifted_path) + record_covered_forms(original_path) + + +if __name__ == "__main__": + main() diff --git a/tools/cpu_avx_cmp_aot.py b/tools/cpu_avx_cmp_aot.py new file mode 100644 index 000000000..1e9bbf03a --- /dev/null +++ b/tools/cpu_avx_cmp_aot.py @@ -0,0 +1,630 @@ +"""Lift bounded Windows x64 leaf functions with AVX VEX FP compare instructions to C++. + +Each export uses the straight-line leaf ABI: + void lifted_(word rcx, word rdx, word r8) +where rcx, rdx, and r8 carry flat host pointers to caller-owned buffers. YMM0..YMM5 +are modeled as portable 256-bit value structs (four 64-bit lanes); every VEX.128 +write to XMM0..XMM5 zeroes bits [255:128] of the corresponding YMM register. + +Supported AVX FP compare encodings (docs/coverage/x64_zen2.tsv group AVX): + - VCMPPS: VEX.128 (xmm, xmm, xmm/m128, imm8) and VEX.256 (ymm, ymm, ymm/m256, imm8) + - VCMPPD: VEX.128 (xmm, xmm, xmm/m128, imm8) and VEX.256 (ymm, ymm, ymm/m256, imm8) + - VCMPSS: VEX.128 scalar f32 (xmm, xmm, xmm/m32, imm8), preserving src1[127:32] + - VCMPSD: VEX.128 scalar f64 (xmm, xmm, xmm/m64, imm8), preserving src1[127:64] +All 32 5-bit predicates (imm8 & 0x1F) are modeled via baseline SSE2 comparisons +on volatile operand copies (preventing fast-math folding while preserving +0.0 == -0.0, ++/-Inf, qNaN/sNaN, MXCSR DAZ, and quiet vs signaling NaN exception behavior). + +Transport / ABI glue: + - VMOVAPS, VMOVAPD, VMOVUPS, VMOVUPD (128/256-bit reg-reg, flat [rcx|rdx|r8] loads, + and flat [r8] stores) + - VMOVSS, VMOVSD (scalar reg-reg merge, flat [rcx|rdx|r8] load, flat [r8] store) + - VZEROUPPER and terminal RET. + +EVEX encodings, legacy SSE forms (CMPPS/CMPPD/CMPSS/CMPSD/MOVAPS/etc.), nonvolatile +vector registers (XMM6..15/YMM6..15), undefined vector reads, displaced or non-flat +memory operands, non-[r8] stores, instruction prefixes, branches, and trailing or +missing ret are rejected. +""" + +import argparse +from pathlib import Path +import tempfile + +import pefile +from iced_x86 import ( + Code, + Decoder, + EncodingKind, + MemorySizeExt, + OpKind, + Register as R, + RegisterExt, +) + +from cpu_leaf_aot import bounded_code, export_rva + + +ARGUMENTS = {R.RCX: "rcx", R.RDX: "rdx", R.R8: "r8"} +VOLATILE_XMM = {getattr(R, f"XMM{i}"): i for i in range(6)} +VOLATILE_YMM = {getattr(R, f"YMM{i}"): i for i in range(6)} +NONVOLATILE_VEC = ( + {getattr(R, f"XMM{i}") for i in range(6, 32)} + | {getattr(R, f"YMM{i}") for i in range(6, 32)} + | {getattr(R, f"ZMM{i}") for i in range(32)} +) + +# (helper_name, is_ymm, mem_size, is_scalar, is_double) +VCMP_CODES = { + Code.VEX_VCMPPS_XMM_XMM_XMMM128_IMM8: ("op_vcmpps", False, 16, False, False), + Code.VEX_VCMPPS_YMM_YMM_YMMM256_IMM8: ("op_vcmpps", True, 32, False, False), + Code.VEX_VCMPPD_XMM_XMM_XMMM128_IMM8: ("op_vcmppd", False, 16, False, True), + Code.VEX_VCMPPD_YMM_YMM_YMMM256_IMM8: ("op_vcmppd", True, 32, False, True), + Code.VEX_VCMPSS_XMM_XMM_XMMM32_IMM8: ("op_vcmpss", False, 4, True, False), + Code.VEX_VCMPSD_XMM_XMM_XMMM64_IMM8: ("op_vcmpsd", False, 8, True, True), +} + +# is_ymm for full-width VEX FP moves +VEC_MOVE_CODES = { + Code.VEX_VMOVAPS_XMM_XMMM128: False, + Code.VEX_VMOVAPS_XMMM128_XMM: False, + Code.VEX_VMOVAPS_YMM_YMMM256: True, + Code.VEX_VMOVAPS_YMMM256_YMM: True, + Code.VEX_VMOVAPD_XMM_XMMM128: False, + Code.VEX_VMOVAPD_XMMM128_XMM: False, + Code.VEX_VMOVAPD_YMM_YMMM256: True, + Code.VEX_VMOVAPD_YMMM256_YMM: True, + Code.VEX_VMOVUPS_XMM_XMMM128: False, + Code.VEX_VMOVUPS_XMMM128_XMM: False, + Code.VEX_VMOVUPS_YMM_YMMM256: True, + Code.VEX_VMOVUPS_YMMM256_YMM: True, + Code.VEX_VMOVUPD_XMM_XMMM128: False, + Code.VEX_VMOVUPD_XMMM128_XMM: False, + Code.VEX_VMOVUPD_YMM_YMMM256: True, + Code.VEX_VMOVUPD_YMMM256_YMM: True, +} + +VMOVSS_REG_CODES = { + Code.VEX_VMOVSS_XMM_XMM_XMM, + Code.VEX_VMOVSS_XMM_XMM_XMM_0F11, +} +VMOVSD_REG_CODES = { + Code.VEX_VMOVSD_XMM_XMM_XMM, + Code.VEX_VMOVSD_XMM_XMM_XMM_0F11, +} +SCALAR_MOVE_CODES = { + Code.VEX_VMOVSS_XMM_M32, + Code.VEX_VMOVSS_M32_XMM, + *VMOVSS_REG_CODES, + Code.VEX_VMOVSD_XMM_M64, + Code.VEX_VMOVSD_M64_XMM, + *VMOVSD_REG_CODES, +} + +LEGACY_SSE_REJECT_CODES = { + Code.CMPPS_XMM_XMMM128_IMM8, + Code.CMPPD_XMM_XMMM128_IMM8, + Code.CMPSS_XMM_XMMM32_IMM8, + Code.CMPSD_XMM_XMMM64_IMM8, + Code.MOVAPS_XMM_XMMM128, + Code.MOVAPS_XMMM128_XMM, + Code.MOVAPD_XMM_XMMM128, + Code.MOVAPD_XMMM128_XMM, + Code.MOVUPS_XMM_XMMM128, + Code.MOVUPS_XMMM128_XMM, + Code.MOVUPD_XMM_XMMM128, + Code.MOVUPD_XMMM128_XMM, + Code.MOVSS_XMM_XMMM32, + Code.MOVSS_XMMM32_XMM, + Code.MOVSD_XMM_XMMM64, + Code.MOVSD_XMMM64_XMM, +} + +ALLOWED_CODES = { + Code.RETNQ, + Code.VEX_VZEROUPPER, + *VCMP_CODES, + *VEC_MOVE_CODES, + *SCALAR_MOVE_CODES, +} + +PRELUDE = """#include +#include +#include +#include +#if defined(_MSC_VER) +#include +#define X2W_UNALIGNED __unaligned +#else +#define X2W_UNALIGNED +#endif + +using word = std::uint64_t; + +struct Vec256 { + std::uint64_t q[4]; +}; + +static inline std::uint32_t load32(word address) { + std::atomic_signal_fence(std::memory_order_seq_cst); + const std::uint32_t v = *reinterpret_cast(address); + std::atomic_signal_fence(std::memory_order_seq_cst); + return v; +} + +static inline std::uint64_t load64(word address) { + std::atomic_signal_fence(std::memory_order_seq_cst); + const std::uint64_t v = *reinterpret_cast(address); + std::atomic_signal_fence(std::memory_order_seq_cst); + return v; +} + +static inline Vec256 load128(word address) { + std::atomic_signal_fence(std::memory_order_seq_cst); + const auto* p = reinterpret_cast(address); + const std::uint64_t q0 = p[0]; + const std::uint64_t q1 = p[1]; + std::atomic_signal_fence(std::memory_order_seq_cst); + return {{q0, q1, 0ull, 0ull}}; +} + +static inline Vec256 load256(word address) { + std::atomic_signal_fence(std::memory_order_seq_cst); + const auto* p = reinterpret_cast(address); + const std::uint64_t q0 = p[0]; + const std::uint64_t q1 = p[1]; + const std::uint64_t q2 = p[2]; + const std::uint64_t q3 = p[3]; + std::atomic_signal_fence(std::memory_order_seq_cst); + return {{q0, q1, q2, q3}}; +} + +static inline void store32(word address, std::uint32_t val) { + std::atomic_signal_fence(std::memory_order_seq_cst); + std::memcpy(reinterpret_cast(address), &val, 4); + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +static inline void store64(word address, std::uint64_t val) { + std::atomic_signal_fence(std::memory_order_seq_cst); + std::memcpy(reinterpret_cast(address), &val, 8); + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +static inline void store128(word address, const Vec256& v) { + std::atomic_signal_fence(std::memory_order_seq_cst); + std::memcpy(reinterpret_cast(address), v.q, 16); + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +static inline void store256(word address, const Vec256& v) { + std::atomic_signal_fence(std::memory_order_seq_cst); + std::memcpy(reinterpret_cast(address), v.q, 32); + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +static inline Vec256 copy128(const Vec256& v) { + return {{v.q[0], v.q[1], 0ull, 0ull}}; +} + +static inline std::uint32_t lane32(const Vec256& v, unsigned i) { + return static_cast(v.q[i >> 1] >> ((i & 1u) * 32u)); +} + +static inline void set_lane32(Vec256& v, unsigned i, std::uint32_t val) { + const unsigned shift = (i & 1u) * 32u; + v.q[i >> 1] = (v.q[i >> 1] & ~(0xffffffffull << shift)) | (static_cast(val) << shift); +} + +// Model all 32 AVX FP compare predicates (imm8 & 0x1F) using baseline SSE2 scalar operations +// on volatile operand copies so /O2 cannot fast-math fold +0/-0, Inf, NaN, DAZ, or IE signaling. +static inline std::uint32_t cmp_f32_scalar(std::uint32_t a, std::uint32_t b, std::uint8_t pred) { + const volatile std::uint32_t va = a; + const volatile std::uint32_t vb = b; + const __m128 x = _mm_castsi128_ps(_mm_cvtsi32_si128(static_cast(va))); + const __m128 y = _mm_castsi128_ps(_mm_cvtsi32_si128(static_cast(vb))); + __m128 r; + switch (pred & 0x1fu) { + case 0x00u: r = _mm_cmpeq_ss(x, y); break; + case 0x01u: r = _mm_cmplt_ss(x, y); break; + case 0x02u: r = _mm_cmple_ss(x, y); break; + case 0x03u: r = _mm_cmpunord_ss(x, y); break; + case 0x04u: r = _mm_cmpneq_ss(x, y); break; + case 0x05u: r = _mm_cmpnlt_ss(x, y); break; + case 0x06u: r = _mm_cmpnle_ss(x, y); break; + case 0x07u: r = _mm_cmpord_ss(x, y); break; + case 0x08u: r = _mm_or_ps(_mm_cmpeq_ss(x, y), _mm_cmpunord_ss(x, y)); break; + case 0x09u: r = _mm_cmpnle_ss(y, x); break; + case 0x0au: r = _mm_cmpnlt_ss(y, x); break; + case 0x0bu: { const volatile __m128 t = _mm_cmpeq_ss(x, y); (void)t; return 0u; } + case 0x0cu: r = _mm_and_ps(_mm_cmpneq_ss(x, y), _mm_cmpord_ss(x, y)); break; + case 0x0du: r = _mm_cmple_ss(y, x); break; + case 0x0eu: r = _mm_cmplt_ss(y, x); break; + case 0x0fu: { const volatile __m128 t = _mm_cmpeq_ss(x, y); (void)t; return 0xffffffffu; } + case 0x10u: { const volatile __m128 t = _mm_cmplt_ss(x, y); (void)t; r = _mm_cmpeq_ss(x, y); break; } + case 0x11u: return _mm_ucomigt_ss(y, x) ? 0xffffffffu : 0u; + case 0x12u: return _mm_ucomige_ss(y, x) ? 0xffffffffu : 0u; + case 0x13u: { const volatile __m128 t = _mm_cmplt_ss(x, y); (void)t; r = _mm_cmpunord_ss(x, y); break; } + case 0x14u: { const volatile __m128 t = _mm_cmplt_ss(x, y); (void)t; r = _mm_cmpneq_ss(x, y); break; } + case 0x15u: return _mm_ucomigt_ss(y, x) ? 0u : 0xffffffffu; + case 0x16u: return _mm_ucomige_ss(y, x) ? 0u : 0xffffffffu; + case 0x17u: { const volatile __m128 t = _mm_cmplt_ss(x, y); (void)t; r = _mm_cmpord_ss(x, y); break; } + case 0x18u: { const volatile __m128 t = _mm_cmplt_ss(x, y); (void)t; r = _mm_or_ps(_mm_cmpeq_ss(x, y), _mm_cmpunord_ss(x, y)); break; } + case 0x19u: return _mm_ucomige_ss(x, y) ? 0u : 0xffffffffu; + case 0x1au: return _mm_ucomigt_ss(x, y) ? 0u : 0xffffffffu; + case 0x1bu: { const volatile __m128 t = _mm_cmplt_ss(x, y); (void)t; return 0u; } + case 0x1cu: { const volatile __m128 t = _mm_cmplt_ss(x, y); (void)t; r = _mm_and_ps(_mm_cmpneq_ss(x, y), _mm_cmpord_ss(x, y)); break; } + case 0x1du: return _mm_ucomige_ss(x, y) ? 0xffffffffu : 0u; + case 0x1eu: return _mm_ucomigt_ss(x, y) ? 0xffffffffu : 0u; + default: { const volatile __m128 t = _mm_cmplt_ss(x, y); (void)t; return 0xffffffffu; } + } + return static_cast(_mm_cvtsi128_si32(_mm_castps_si128(r))); +} + +static inline std::uint64_t cmp_f64_scalar(std::uint64_t a, std::uint64_t b, std::uint8_t pred) { + const volatile std::uint64_t va = a; + const volatile std::uint64_t vb = b; + const __m128d x = _mm_castsi128_pd(_mm_cvtsi64_si128(static_cast(va))); + const __m128d y = _mm_castsi128_pd(_mm_cvtsi64_si128(static_cast(vb))); + __m128d r; + switch (pred & 0x1fu) { + case 0x00u: r = _mm_cmpeq_sd(x, y); break; + case 0x01u: r = _mm_cmplt_sd(x, y); break; + case 0x02u: r = _mm_cmple_sd(x, y); break; + case 0x03u: r = _mm_cmpunord_sd(x, y); break; + case 0x04u: r = _mm_cmpneq_sd(x, y); break; + case 0x05u: r = _mm_cmpnlt_sd(x, y); break; + case 0x06u: r = _mm_cmpnle_sd(x, y); break; + case 0x07u: r = _mm_cmpord_sd(x, y); break; + case 0x08u: r = _mm_or_pd(_mm_cmpeq_sd(x, y), _mm_cmpunord_sd(x, y)); break; + case 0x09u: r = _mm_cmpnle_sd(y, x); break; + case 0x0au: r = _mm_cmpnlt_sd(y, x); break; + case 0x0bu: { const volatile __m128d t = _mm_cmpeq_sd(x, y); (void)t; return 0ull; } + case 0x0cu: r = _mm_and_pd(_mm_cmpneq_sd(x, y), _mm_cmpord_sd(x, y)); break; + case 0x0du: r = _mm_cmple_sd(y, x); break; + case 0x0eu: r = _mm_cmplt_sd(y, x); break; + case 0x0fu: { const volatile __m128d t = _mm_cmpeq_sd(x, y); (void)t; return 0xffffffffffffffffull; } + case 0x10u: { const volatile __m128d t = _mm_cmplt_sd(x, y); (void)t; r = _mm_cmpeq_sd(x, y); break; } + case 0x11u: return _mm_ucomigt_sd(y, x) ? 0xffffffffffffffffull : 0ull; + case 0x12u: return _mm_ucomige_sd(y, x) ? 0xffffffffffffffffull : 0ull; + case 0x13u: { const volatile __m128d t = _mm_cmplt_sd(x, y); (void)t; r = _mm_cmpunord_sd(x, y); break; } + case 0x14u: { const volatile __m128d t = _mm_cmplt_sd(x, y); (void)t; r = _mm_cmpneq_sd(x, y); break; } + case 0x15u: return _mm_ucomigt_sd(y, x) ? 0ull : 0xffffffffffffffffull; + case 0x16u: return _mm_ucomige_sd(y, x) ? 0ull : 0xffffffffffffffffull; + case 0x17u: { const volatile __m128d t = _mm_cmplt_sd(x, y); (void)t; r = _mm_cmpord_sd(x, y); break; } + case 0x18u: { const volatile __m128d t = _mm_cmplt_sd(x, y); (void)t; r = _mm_or_pd(_mm_cmpeq_sd(x, y), _mm_cmpunord_sd(x, y)); break; } + case 0x19u: return _mm_ucomige_sd(x, y) ? 0ull : 0xffffffffffffffffull; + case 0x1au: return _mm_ucomigt_sd(x, y) ? 0ull : 0xffffffffffffffffull; + case 0x1bu: { const volatile __m128d t = _mm_cmplt_sd(x, y); (void)t; return 0ull; } + case 0x1cu: { const volatile __m128d t = _mm_cmplt_sd(x, y); (void)t; r = _mm_and_pd(_mm_cmpneq_sd(x, y), _mm_cmpord_sd(x, y)); break; } + case 0x1du: return _mm_ucomige_sd(x, y) ? 0xffffffffffffffffull : 0ull; + case 0x1eu: return _mm_ucomigt_sd(x, y) ? 0xffffffffffffffffull : 0ull; + default: { const volatile __m128d t = _mm_cmplt_sd(x, y); (void)t; return 0xffffffffffffffffull; } + } + return static_cast(_mm_cvtsi128_si64(_mm_castpd_si128(r))); +} + +static inline Vec256 op_vcmpps(const Vec256& a, const Vec256& b, std::uint8_t pred, bool wide) { + Vec256 out{}; + const unsigned count = wide ? 8u : 4u; + for (unsigned i = 0; i < count; ++i) { + set_lane32(out, i, cmp_f32_scalar(lane32(a, i), lane32(b, i), pred)); + } + return out; +} + +static inline Vec256 op_vcmppd(const Vec256& a, const Vec256& b, std::uint8_t pred, bool wide) { + Vec256 out{}; + const unsigned count = wide ? 4u : 2u; + for (unsigned i = 0; i < count; ++i) { + out.q[i] = cmp_f64_scalar(a.q[i], b.q[i], pred); + } + return out; +} + +static inline Vec256 op_vcmpss(const Vec256& a, std::uint32_t b32, std::uint8_t pred) { + Vec256 out = copy128(a); + set_lane32(out, 0u, cmp_f32_scalar(lane32(a, 0u), b32, pred)); + return out; +} + +static inline Vec256 op_vcmpsd(const Vec256& a, std::uint64_t b64, std::uint8_t pred) { + Vec256 out = copy128(a); + out.q[0] = cmp_f64_scalar(a.q[0], b64, pred); + return out; +} + +static inline Vec256 op_vmovss_reg(const Vec256& a, std::uint32_t b32) { + Vec256 out = copy128(a); + set_lane32(out, 0u, b32); + return out; +} + +static inline Vec256 op_vmovss_mem(std::uint32_t b32) { + Vec256 out{}; + set_lane32(out, 0u, b32); + return out; +} + +static inline Vec256 op_vmovsd_reg(const Vec256& a, std::uint64_t b64) { + Vec256 out = copy128(a); + out.q[0] = b64; + return out; +} + +static inline Vec256 op_vmovsd_mem(std::uint64_t b64) { + return {{b64, 0ull, 0ull, 0ull}}; +} + +#if defined(_MSC_VER) +extern "C" __declspec(dllexport) std::uint32_t host_has_avx() { + int info[4]{}; + __cpuid(info, 1); + const int need = (1 << 27) | (1 << 28); + if ((info[2] & need) != need) return 0u; + return (_xgetbv(0) & 6u) == 6u ? 1u : 0u; +} + +extern "C" __declspec(dllexport) std::uint32_t host_exchange_mxcsr(std::uint32_t next) { + const std::uint32_t current = _mm_getcsr(); + _mm_setcsr(next); + return current; +} +#endif +""" + + +def vec_index(register, ins, *, expected_wide): + """Map XMM0..XMM5 or YMM0..YMM5 to register index, enforcing width and rejecting nonvolatile/other.""" + if register in VOLATILE_XMM: + if expected_wide: + raise ValueError(f"unsupported vector width for {register} at RVA {ins.ip:#x}: {ins}") + return VOLATILE_XMM[register] + if register in VOLATILE_YMM: + if not expected_wide: + raise ValueError(f"unsupported vector width for {register} at RVA {ins.ip:#x}: {ins}") + return VOLATILE_YMM[register] + if register in NONVOLATILE_VEC: + raise ValueError(f"nonvolatile vector register {register} at RVA {ins.ip:#x}: {ins}") + raise ValueError(f"unsupported vector register {register} at RVA {ins.ip:#x}: {ins}") + + +def flat_address(ins, *, store=False, expected_size=None): + """Lower a flat zero-displacement [rcx|rdx|r8] pointer operand (stores restricted to [r8]).""" + base = ins.memory_base + if ( + ins.is_ip_rel_memory_operand + or base in (R.NONE, R.RIP, R.EIP, R.RSP, R.ESP) + or ins.memory_index != R.NONE + or ins.memory_displacement != 0 + or not RegisterExt.is_gpr64(base) + or base not in ARGUMENTS + ): + raise ValueError(f"unsupported memory operand at RVA {ins.ip:#x}: {ins}") + if store and base != R.R8: + raise ValueError(f"non-r8 store memory operand at RVA {ins.ip:#x}: {ins}") + if expected_size is not None and MemorySizeExt.size(ins.memory_size) != expected_size: + raise ValueError(f"unsupported memory size at RVA {ins.ip:#x}: {ins}") + return ARGUMENTS[base] + + +def lift_code(name, start, raw): + """Decode and lift one bounded straight-line AVX VEX FP compare leaf function.""" + instructions = list(Decoder(64, raw, ip=start)) + if not instructions or instructions[-1].next_ip != start + len(raw): + raise ValueError(f"truncated instruction stream in {name} at RVA {start:#x}") + if any(ins.is_invalid for ins in instructions): + bad = next(ins for ins in instructions if ins.is_invalid) + raise ValueError(f"invalid instruction at RVA {bad.ip:#x}") + + used = set() + defined = set() + statements = [] + returned = False + + def read_vec(op_index, ins, *, expected_wide): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register operand {op_index} at RVA {ins.ip:#x}: {ins}") + idx = vec_index(ins.op_register(op_index), ins, expected_wide=expected_wide) + if idx not in defined: + raise ValueError(f"undefined vector register ymm{idx} at RVA {ins.ip:#x}: {ins}") + used.add(idx) + return f"ymm{idx}" + + def write_vec(op_index, ins, *, expected_wide): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register destination at RVA {ins.ip:#x}: {ins}") + idx = vec_index(ins.op_register(op_index), ins, expected_wide=expected_wide) + used.add(idx) + return idx, f"ymm{idx}" + + for ins in instructions: + if returned: + raise ValueError(f"unreachable instruction after ret at RVA {ins.ip:#x}: {ins}") + if ins.has_lock_prefix or ins.has_rep_prefix or ins.has_repne_prefix or ins.has_segment_prefix: + raise ValueError(f"unsupported instruction prefix at RVA {ins.ip:#x}: {ins}") + if ( + ins.op_code().encoding == EncodingKind.EVEX + or ins.op_mask != R.NONE + or ins.zeroing_masking + or ins.is_broadcast + ): + raise ValueError(f"unsupported EVEX instruction at RVA {ins.ip:#x}: {ins}") + if ins.code in LEGACY_SSE_REJECT_CODES: + raise ValueError(f"unsupported legacy SSE instruction at RVA {ins.ip:#x}: {ins}") + if ins.code not in ALLOWED_CODES: + raise ValueError(f"unsupported instruction at RVA {ins.ip:#x}: {ins}") + + if ins.code == Code.RETNQ: + statements.append("return;") + returned = True + elif ins.code == Code.VEX_VZEROUPPER: + for idx in sorted(defined): + statements.append(f"ymm{idx}.q[2] = 0ull; ymm{idx}.q[3] = 0ull;") + elif ins.code in VCMP_CODES: + helper, wide, mem_size, is_scalar, is_double = VCMP_CODES[ins.code] + if ins.op_count != 4 or ins.op0_kind != OpKind.REGISTER or ins.op1_kind != OpKind.REGISTER: + raise ValueError(f"unsupported AVX compare operands at RVA {ins.ip:#x}: {ins}") + pred = ins.immediate8 & 0x1F + src1 = read_vec(1, ins, expected_wide=wide) + if ins.op2_kind == OpKind.MEMORY: + addr = flat_address(ins, expected_size=mem_size) + if is_scalar: + src2 = f"{'load64' if is_double else 'load32'}({addr})" + else: + src2 = f"{'load256' if wide else 'load128'}({addr})" + elif ins.op2_kind == OpKind.REGISTER: + reg2 = read_vec(2, ins, expected_wide=wide) + if is_scalar: + src2 = f"{reg2}.q[0]" if is_double else f"lane32({reg2}, 0u)" + else: + src2 = reg2 + else: + raise ValueError(f"unsupported AVX compare operands at RVA {ins.ip:#x}: {ins}") + dst_idx, dst = write_vec(0, ins, expected_wide=wide) + if is_scalar: + statements.append(f"{dst} = {helper}({src1}, {src2}, {pred:#x}u);") + else: + statements.append(f"{dst} = {helper}({src1}, {src2}, {pred:#x}u, {'true' if wide else 'false'});") + defined.add(dst_idx) + elif ins.code in VEC_MOVE_CODES: + wide = VEC_MOVE_CODES[ins.code] + expected_size = 32 if wide else 16 + if ins.op0_kind == OpKind.REGISTER and ins.op1_kind == OpKind.MEMORY: + addr = flat_address(ins, expected_size=expected_size) + dst_idx, dst = write_vec(0, ins, expected_wide=wide) + statements.append(f"{dst} = {'load256' if wide else 'load128'}({addr});") + defined.add(dst_idx) + elif ins.op0_kind == OpKind.MEMORY and ins.op1_kind == OpKind.REGISTER: + src = read_vec(1, ins, expected_wide=wide) + addr = flat_address(ins, store=True, expected_size=expected_size) + statements.append(f"{'store256' if wide else 'store128'}({addr}, {src});") + elif ins.op0_kind == OpKind.REGISTER and ins.op1_kind == OpKind.REGISTER: + src = read_vec(1, ins, expected_wide=wide) + dst_idx, dst = write_vec(0, ins, expected_wide=wide) + statements.append(f"{dst} = {src};" if wide else f"{dst} = copy128({src});") + defined.add(dst_idx) + else: + raise ValueError(f"unsupported vector move operands at RVA {ins.ip:#x}: {ins}") + elif ins.code == Code.VEX_VMOVSS_XMM_M32: + addr = flat_address(ins, expected_size=4) + dst_idx, dst = write_vec(0, ins, expected_wide=False) + statements.append(f"{dst} = op_vmovss_mem(load32({addr}));") + defined.add(dst_idx) + elif ins.code == Code.VEX_VMOVSS_M32_XMM: + src = read_vec(1, ins, expected_wide=False) + addr = flat_address(ins, store=True, expected_size=4) + statements.append(f"store32({addr}, lane32({src}, 0u));") + elif ins.code in VMOVSS_REG_CODES: + src1 = read_vec(1, ins, expected_wide=False) + src2 = read_vec(2, ins, expected_wide=False) + dst_idx, dst = write_vec(0, ins, expected_wide=False) + statements.append(f"{dst} = op_vmovss_reg({src1}, lane32({src2}, 0u));") + defined.add(dst_idx) + elif ins.code == Code.VEX_VMOVSD_XMM_M64: + addr = flat_address(ins, expected_size=8) + dst_idx, dst = write_vec(0, ins, expected_wide=False) + statements.append(f"{dst} = op_vmovsd_mem(load64({addr}));") + defined.add(dst_idx) + elif ins.code == Code.VEX_VMOVSD_M64_XMM: + src = read_vec(1, ins, expected_wide=False) + addr = flat_address(ins, store=True, expected_size=8) + statements.append(f"store64({addr}, {src}.q[0]);") + elif ins.code in VMOVSD_REG_CODES: + src1 = read_vec(1, ins, expected_wide=False) + src2 = read_vec(2, ins, expected_wide=False) + dst_idx, dst = write_vec(0, ins, expected_wide=False) + statements.append(f"{dst} = op_vmovsd_reg({src1}, {src2}.q[0]);") + defined.add(dst_idx) + else: + raise ValueError(f"unsupported instruction at RVA {ins.ip:#x}: {ins}") + + if not returned: + raise ValueError(f"missing terminal ret in {name} at RVA {start + len(raw):#x}") + + decls = [f" Vec256 ymm{idx}{{}};" for idx in sorted(used)] + body = [f" {stmt}" for stmt in statements] + lines = [ + f'extern "C" __declspec(dllexport) void lifted_{name}(word rcx, word rdx, word r8) {{', + " (void)rcx; (void)rdx; (void)r8;", + *decls, + *body, + "}", + ] + return "\n".join(lines), len(instructions) + + +def lift(pe, name): + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + source, count = lift_code(name, entry, raw) + return source, entry, count + + +def translate_pe(pe, names): + if pe.FILE_HEADER.Machine != 0x8664 or pe.OPTIONAL_HEADER.Magic != 0x20B: + raise ValueError("expected AMD64 PE32+") + lifted = [lift(pe, name) for name in names] + source = PRELUDE + "\n".join(f"\n{text}" for text, _, _ in lifted) + "\n" + meta = [(name, entry, count) for name, (_, entry, count) in zip(names, lifted)] + return source, meta + + +def translate(image, names): + with pefile.PE(str(image), fast_load=True) as pe: + return translate_pe(pe, names) + + +def _write_atomic(path: Path, content: str) -> None: + if path.exists() and path.is_dir(): + raise ValueError(f"output path must not be a directory: {path}") + if path.is_symlink(): + raise ValueError(f"output path must not be a symlink: {path}") + path.parent.mkdir(parents=True, exist_ok=True) + tmp_path = None + try: + with tempfile.NamedTemporaryFile( + mode="w", + encoding="utf-8", + newline="\n", + dir=path.parent, + prefix=f".{path.stem}.", + suffix=".tmp", + delete=False, + ) as handle: + tmp_path = Path(handle.name) + handle.write(content) + tmp_path.replace(path) + except BaseException: + if tmp_path is not None: + tmp_path.unlink(missing_ok=True) + raise + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("image", type=Path) + parser.add_argument("exports", help="comma-separated export names") + parser.add_argument("output", type=Path) + args = parser.parse_args(argv) + try: + if not args.image.is_file(): + raise ValueError(f"input image must be a regular file: {args.image}") + exports = [name for name in args.exports.split(",") if name] + if not exports: + raise ValueError("exports list must not be empty") + if args.output.exists() and args.output.is_dir(): + raise ValueError(f"output path must not be a directory: {args.output}") + if args.output.is_symlink(): + raise ValueError(f"output path must not be a symlink: {args.output}") + source, meta = translate(args.image, exports) + _write_atomic(args.output, source) + for name, entry, count in meta: + print(f"{name} at RVA {entry:#x}: {count} instructions") + except (ValueError, OSError, pefile.PEFormatError) as error: + parser.exit(1, f"cpu_avx_cmp_aot: {error}\n") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) From 2a80119247b6b890d47e8dc75dab3ec0732a76c8 Mon Sep 17 00:00:00 2001 From: Chad Hyatt Date: Wed, 25 Nov 2026 21:04:49 -0600 Subject: [PATCH 099/240] cpu: normalize Windows compiler basename in EXE CLI reports (#2667) Use Windows path semantics for the compiler display name regardless of the host. Preserve the exact subprocess command. Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> Co-authored-by: Royoo <3230853833@qq.com> --- tools/exe_aot.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/tools/exe_aot.py b/tools/exe_aot.py index 7a00cc1b2..000e16d99 100644 --- a/tools/exe_aot.py +++ b/tools/exe_aot.py @@ -10,7 +10,7 @@ import hashlib import json import os -from pathlib import Path +from pathlib import Path, PureWindowsPath import re import shutil import subprocess @@ -143,6 +143,7 @@ def build(cxx, source, exe, *, timeout=BUILD_TIMEOUT_S): compiler = shutil.which(str(cxx)) if cxx else shutil.which("cl") if compiler is None: raise Refusal("build", f"C++ compiler {cxx or 'cl'} not found; run tools/dev.ps1 or pass --cxx") + compiler_name = PureWindowsPath(compiler).name # The provenance export would otherwise make the linker write an import library and .exp file. command = [compiler, *CXX_FLAGS, source.name, f"/Fe{exe.name}", f"/Fo{source.stem}.obj", "/link", "/NOIMPLIB", "/NOEXP"] @@ -163,15 +164,15 @@ def build(cxx, source, exe, *, timeout=BUILD_TIMEOUT_S): ) raise Refusal( "build", - f"{Path(compiler).name} timed out after {exc.timeout}s", + f"{compiler_name} timed out after {exc.timeout}s", output=_tail_lines(combined), ) from exc except (OSError, subprocess.SubprocessError) as exc: - raise Refusal("build", f"failed to run {Path(compiler).name}: {exc}") from exc + raise Refusal("build", f"failed to run {compiler_name}: {exc}") from exc if result.returncode or not exe.is_file(): tail = _tail_lines((result.stdout or "") + (result.stderr or "")) - raise Refusal("build", f"{Path(compiler).name} exited {result.returncode}", output=tail) - return Path(compiler).name + raise Refusal("build", f"{compiler_name} exited {result.returncode}", output=tail) + return compiler_name def convert(image, out_dir, *, entry_export=None, cxx=None, compile_exe=True): From a9cfecf08e2997ddd37a82f75d76af78a78b702b Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Thu, 26 Nov 2026 05:07:52 +0200 Subject: [PATCH 100/240] tooling: harden bink_descriptors_aot CLI path guards and atomic writes (#2670) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 3 + tests/bink_descriptors_aot_cli_check.py | 409 ++++++++++++++++++++++++ tools/bink_descriptors_aot.py | 51 ++- 3 files changed, 459 insertions(+), 4 deletions(-) create mode 100644 tests/bink_descriptors_aot_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index dca655a14..378025a16 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -10931,6 +10931,9 @@ if(EXISTS "${INTAKE_PYTHON}") set_tests_properties(ffx_working_set_delta_cli_check PROPERTIES TIMEOUT 60) add_test(NAME bink_descriptors_aot_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/bink_descriptors_aot_check.py") + add_test(NAME tooling_bink_descriptors_aot_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/bink_descriptors_aot_cli_check.py") + set_tests_properties(tooling_bink_descriptors_aot_cli_check PROPERTIES TIMEOUT 60) add_test(NAME range_manifest_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/range_manifest_check.py") add_test(NAME pe_resource_inventory_cli_check COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/bink_descriptors_aot_cli_check.py b/tests/bink_descriptors_aot_cli_check.py new file mode 100644 index 000000000..fd72ae78c --- /dev/null +++ b/tests/bink_descriptors_aot_cli_check.py @@ -0,0 +1,409 @@ +#!/usr/bin/env python3 +"""Pure-Python synthetic PE32+ CLI, atomic-write, path-guard, and mutation suite for tools/bink_descriptors_aot.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +import os +from pathlib import Path +import runpy +import struct +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOLS_DIR = ROOT / "tools" +TESTS_DIR = ROOT / "tests" +TOOL = TOOLS_DIR / "bink_descriptors_aot.py" +sys.path.insert(0, str(TOOLS_DIR)) +sys.path.insert(0, str(TESTS_DIR)) + +import bink_descriptors_aot # noqa: E402 +from bink_descriptors_aot_check import build_image # noqa: E402 + + +def _run_main(argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = bink_descriptors_aot.main(argv) + except SystemExit as exc: + code = exc.code + if not isinstance(code, int): + if code is not None: + stderr.write(f"{code}\n") + code = 0 if code is None else 1 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class BinkDescriptorsAotCliPositiveTests(unittest.TestCase): + def test_default_and_frame_planes_atomic_nested_outputs(self) -> None: + raw = build_image() + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "synthetic_bink_desc.dll" + image.write_bytes(raw) + + # 1) Default mode (no --frame-planes) in nested directory, tracking atomic os.replace. + default_out = base / "nested" / "default" / "descriptors.cpp" + seen_replaces: list[tuple[Path, Path]] = [] + real_replace = os.replace + + def tracking_replace(src, dst): + src_path, dst_path = Path(src), Path(dst) + seen_replaces.append((src_path, dst_path)) + self.assertEqual(src_path.parent.resolve(), dst_path.parent.resolve()) + self.assertTrue(src_path.name.endswith(".tmp")) + return real_replace(src, dst) + + with mock.patch.object(bink_descriptors_aot.os, "replace", side_effect=tracking_replace): + code, out, err = _run_main([str(image), str(default_out)]) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(out, "") + self.assertEqual(err, "") + self.assertEqual(len(seen_replaces), 1) + self.assertEqual([p.name for p in default_out.parent.iterdir()], ["descriptors.cpp"]) + default_text = default_out.read_text(encoding="ascii") + self.assertEqual(default_text, bink_descriptors_aot.generate(image, False, False)) + self.assertIn("group_init", default_text) + self.assertIn("group_append", default_text) + self.assertNotIn("frame_planes", default_text) + + # 2) --frame-planes mode atomically overwrites existing .cpp with 0 .tmp files left. + default_out.write_text("stale content", encoding="ascii") + code_fp, out_fp, err_fp = _run_main([str(image), str(default_out), "--frame-planes"]) + self.assertEqual(code_fp, 0, err_fp) + self.assertEqual(out_fp, "") + self.assertEqual(err_fp, "") + self.assertEqual([p.name for p in default_out.parent.iterdir()], ["descriptors.cpp"]) + fp_text = default_out.read_text(encoding="ascii") + self.assertEqual(fp_text, bink_descriptors_aot.generate(image, False, True)) + self.assertIn("frame_planes", fp_text) + self.assertIn("append_frame", fp_text) + + # 3) Subprocess end-to-end positive check. + sub_out = base / "sub_dir" / "cli_out.cpp" + proc = _run_subprocess(str(image), str(sub_out), "--frame-planes") + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertEqual(proc.stderr, "") + self.assertEqual([p.name for p in sub_out.parent.iterdir()], ["cli_out.cpp"]) + self.assertEqual(sub_out.read_text(encoding="ascii"), fp_text) + + def test_sys_argv_and_main_entrypoint(self) -> None: + raw = build_image() + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "entry.dll" + image.write_bytes(raw) + out_cpp = base / "entry.cpp" + + with mock.patch.object(sys, "argv", [str(TOOL), str(image), str(out_cpp)]): + code, out, err = _run_main(None) + self.assertEqual(code, 0, err) + self.assertEqual(out, "") + self.assertEqual(err, "") + self.assertEqual(out_cpp.read_text(encoding="ascii"), bink_descriptors_aot.generate(image, False, False)) + + out_cpp.unlink() + stdout, stderr = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", [str(TOOL), str(image), str(out_cpp), "--frame-planes"]), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 0) + self.assertEqual(stdout.getvalue(), "") + self.assertEqual(stderr.getvalue(), "") + self.assertEqual(out_cpp.read_text(encoding="ascii"), bink_descriptors_aot.generate(image, False, True)) + + +class BinkDescriptorsAotCliNegativeAndMutationTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_code: int | None, + fragments: tuple[str, ...] = (), + check_subprocess: bool = True, + ) -> str: + code, out, err = _run_main(argv) + if expected_code is None: + self.assertNotEqual(code, 0) + else: + self.assertEqual(code, expected_code, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertTrue(err.strip(), f"expected stderr for {argv!r}") + for fragment in fragments: + self.assertIn(fragment.lower(), err.lower()) + + if check_subprocess: + proc = _run_subprocess(*argv) + if expected_code is None: + self.assertNotEqual(proc.returncode, 0) + else: + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertTrue(proc.stderr.strip(), f"expected subprocess stderr for {argv!r}") + for fragment in fragments: + self.assertIn(fragment.lower(), proc.stderr.lower()) + return err + + def test_missing_and_directory_image_rejected_before_generate(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + dir_image = base / "dir_image" + dir_image.mkdir() + absent_out = base / "absent_dir" / "descriptors.cpp" + + with ( + mock.patch.object( + bink_descriptors_aot, + "generate", + side_effect=AssertionError("generate called for invalid image"), + ), + mock.patch.object( + bink_descriptors_aot, + "_write_atomic", + side_effect=AssertionError("_write_atomic called for invalid image"), + ), + ): + self._assert_clean_failure( + [str(base / "missing.dll"), str(absent_out)], + expected_code=1, + fragments=("image file not found",), + ) + self._assert_clean_failure( + [str(dir_image), str(absent_out)], + expected_code=1, + fragments=("image path is a directory",), + ) + self.assertFalse(absent_out.parent.exists()) + + def test_corrupt_pe_rejected_cleanly_without_creating_output_or_temps(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + absent_out = base / "absent_dir" / "descriptors.cpp" + for name, payload in ( + ("empty.dll", b""), + ("not_pe.dll", b"not a valid PE32+"), + ("trunc_pe.dll", b"MZ" + b"\x00" * 58 + struct.pack(" None: + raw = build_image() + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(raw) + same_cpp = base / "same.cpp" + same_cpp.write_bytes(raw) + hardlink_cpp = base / "hardlink.cpp" + hardlink_cpp.hardlink_to(image) + out_dir = base / "existing_dir.cpp" + out_dir.mkdir() + file_parent = base / "regular_parent.txt" + file_parent.write_text("keep-me", encoding="ascii") + + with ( + mock.patch.object( + bink_descriptors_aot, + "generate", + side_effect=AssertionError("generate called for invalid output"), + ), + mock.patch.object( + bink_descriptors_aot, + "_write_atomic", + side_effect=AssertionError("_write_atomic called for invalid output"), + ), + ): + for label, argv, code, frags in ( + ("non_cpp_suffix", [str(image), str(base / "out.txt")], 2, ("distinct .cpp output",)), + ("empty_output", [str(image), ""], 2, ("distinct .cpp output",)), + ("same_path", [str(same_cpp), str(same_cpp)], 2, ("distinct .cpp output",)), + ("hardlink_samefile", [str(image), str(hardlink_cpp)], 2, ("distinct .cpp output",)), + ("output_is_dir", [str(image), str(out_dir)], 1, ("directory",)), + ("parent_is_file", [str(image), str(file_parent / "out.cpp")], 1, ("not a directory",)), + ("ancestor_is_file", [str(image), str(file_parent / "sub" / "out.cpp")], 1, ("not a directory",)), + ): + with self.subTest(case=label): + self._assert_clean_failure(argv, expected_code=code, fragments=frags) + + self.assertEqual(same_cpp.read_bytes(), raw) + self.assertEqual(image.read_bytes(), raw) + self.assertEqual(list(out_dir.iterdir()), []) + self.assertEqual(file_parent.read_text(encoding="ascii"), "keep-me") + self.assertFalse((base / "out.txt").exists()) + + def test_output_symlink_rejected_before_generate_and_write(self) -> None: + raw = build_image() + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(raw) + out_dir = base / "out_dir" + out_dir.mkdir() + real_target = out_dir / "real.cpp" + real_target.write_text("untouched", encoding="ascii") + live_link = out_dir / "live_link.cpp" + dangling_link = out_dir / "dangling_link.cpp" + + try: + live_link.symlink_to(real_target) + dangling_link.symlink_to(out_dir / "missing.cpp") + has_symlinks = True + except OSError as exc: + if getattr(exc, "winerror", None) != 1314: + raise + has_symlinks = False + + with ( + mock.patch.object( + bink_descriptors_aot, + "generate", + side_effect=AssertionError("generate called for symlink output"), + ), + mock.patch.object( + bink_descriptors_aot, + "_write_atomic", + side_effect=AssertionError("_write_atomic called for symlink output"), + ), + ): + if has_symlinks: + for label, link in (("live_symlink", live_link), ("dangling_symlink", dangling_link)): + with self.subTest(case=label): + self._assert_clean_failure( + [str(image), str(link)], + expected_code=1, + fragments=("symlink",), + ) + else: + # Fallback when Windows account lacks SeCreateSymbolicLinkPrivilege (WinError 1314). + with mock.patch.object(Path, "is_symlink", autospec=True, side_effect=lambda p: p == real_target): + self._assert_clean_failure( + [str(image), str(real_target)], + expected_code=1, + fragments=("symlink",), + check_subprocess=False, + ) + self.assertEqual(real_target.read_text(encoding="ascii"), "untouched") + + def test_os_replace_and_staging_failures_preserve_target_and_leave_zero_tmp_files(self) -> None: + raw = build_image() + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(raw) + out_dir = base / "out_dir" + out_dir.mkdir() + out_cpp = out_dir / "descriptors.cpp" + out_cpp.write_text("original-target-bytes", encoding="ascii") + + # 1) os.replace fails on existing target -> target preserved, 0 .tmp files. + replace_calls: list[tuple[Path, Path]] = [] + + def fail_replace(src, dst): + src_path = Path(src) + replace_calls.append((src_path, Path(dst))) + self.assertTrue(src_path.is_file()) + raise OSError("simulated replace failure") + + with mock.patch.object(bink_descriptors_aot.os, "replace", side_effect=fail_replace): + self._assert_clean_failure( + [str(image), str(out_cpp)], + expected_code=1, + fragments=("simulated replace failure",), + check_subprocess=False, + ) + self.assertEqual(len(replace_calls), 1) + self.assertEqual(out_cpp.read_text(encoding="ascii"), "original-target-bytes") + self.assertEqual([p.name for p in out_dir.iterdir()], ["descriptors.cpp"]) + + # 2) os.replace fails on fresh nested path -> 0 output or .tmp files. + fresh_dir = base / "fresh_dir" + fresh_cpp = fresh_dir / "fresh.cpp" + with mock.patch.object(bink_descriptors_aot.os, "replace", side_effect=fail_replace): + self._assert_clean_failure( + [str(image), str(fresh_cpp)], + expected_code=1, + fragments=("simulated replace failure",), + check_subprocess=False, + ) + self.assertEqual(list(fresh_dir.iterdir()), []) + + # 3) Staging failure after .tmp creation -> os.replace not called, .tmp unlinked, target preserved. + real_ntf = bink_descriptors_aot.tempfile.NamedTemporaryFile + + class FailingWriteHandle: + def __init__(self, inner): + self._inner = inner + self.name = inner.name + + def __enter__(self): + self._inner.__enter__() + return self + + def __exit__(self, exc_type, exc, tb): + return self._inner.__exit__(exc_type, exc, tb) + + def write(self, _data): + raise OSError("simulated write failure") + + with ( + mock.patch.object(bink_descriptors_aot.os, "replace") as replace_mock, + mock.patch.object( + bink_descriptors_aot.tempfile, + "NamedTemporaryFile", + side_effect=lambda *a, **kw: FailingWriteHandle(real_ntf(*a, **kw)), + ), + ): + self._assert_clean_failure( + [str(image), str(out_cpp)], + expected_code=1, + fragments=("simulated write failure",), + check_subprocess=False, + ) + replace_mock.assert_not_called() + self.assertEqual(out_cpp.read_text(encoding="ascii"), "original-target-bytes") + self.assertEqual([p.name for p in out_dir.iterdir()], ["descriptors.cpp"]) + + def test_argparse_errors_py314_safe(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(b"synthetic") + out_cpp = base / "out.cpp" + + for argv, frags in ( + ([], ("required",)), + ([str(image)], ("required",)), + ([str(image), str(out_cpp), "--bogus-flag"], ("unrecognized",)), + ): + with self.subTest(argv=argv): + self._assert_clean_failure(argv, expected_code=None, fragments=frags) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/bink_descriptors_aot.py b/tools/bink_descriptors_aot.py index f6638f4db..da1f62f8e 100644 --- a/tools/bink_descriptors_aot.py +++ b/tools/bink_descriptors_aot.py @@ -1,6 +1,9 @@ """Translate the two Bink leaf functions that build grouped allocation descriptors.""" import argparse +import os from pathlib import Path +import struct +import tempfile import pefile from iced_x86 import Mnemonic as M, OpKind as K, Register as R @@ -70,6 +73,47 @@ def generate(image: Path, package: bool, frame_planes: bool = False) -> str: + append_body + '\n}\n' + planes) +def _validate_args(args: argparse.Namespace, parser: argparse.ArgumentParser) -> None: + if args.image.is_dir(): + raise IsADirectoryError(f"image path is a directory: {args.image}") + if not args.image.is_file(): + raise FileNotFoundError(f"image file not found: {args.image}") + if args.output.suffix.lower() != ".cpp": + parser.error("choose a distinct .cpp output") + if args.output.is_symlink(): + raise ValueError(f"output path must not be a symlink: {args.output}") + if args.output.is_dir(): + raise IsADirectoryError(f"output path is a directory: {args.output}") + for parent in args.output.parents: + if parent.is_file() or ((parent.exists() or parent.is_symlink()) and not parent.is_dir()): + raise NotADirectoryError(f"output parent is not a directory: {parent}") + if args.output.resolve() == args.image.resolve() or (args.output.exists() and args.image.samefile(args.output)): + parser.error("choose a distinct .cpp output") + + +def _write_atomic(path: Path, content: str) -> None: + """Write ASCII content to a sibling temp file and atomically replace path, leaving 0 temp files on failure.""" + path.parent.mkdir(parents=True, exist_ok=True) + tmp_path: Path | None = None + try: + with tempfile.NamedTemporaryFile( + mode="w", + encoding="ascii", + newline="\n", + dir=path.parent, + prefix=f".{path.stem}.", + suffix=".tmp", + delete=False, + ) as handle: + tmp_path = Path(handle.name) + handle.write(content) + os.replace(tmp_path, path) + except BaseException: + if tmp_path is not None: + tmp_path.unlink(missing_ok=True) + raise + + def main(argv=None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("image", type=Path) @@ -78,10 +122,9 @@ def main(argv=None) -> int: parser.add_argument("--frame-planes", action="store_true") args = parser.parse_args(argv) try: - if args.output.suffix.lower() != ".cpp" or args.output.resolve() == args.image.resolve(): - parser.error("choose a distinct .cpp output") - args.output.write_text(generate(args.image, args.package, args.frame_planes), encoding="ascii") - except (OSError, ValueError, pefile.PEFormatError) as error: + _validate_args(args, parser) + _write_atomic(args.output, generate(args.image, args.package, args.frame_planes)) + except (OSError, ValueError, struct.error, pefile.PEFormatError) as error: parser.exit(1, f"{error}\n") return 0 From e7573c32b835cb169bb229d84a767a97cd48e2b0 Mon Sep 17 00:00:00 2001 From: nanyoudegege <132808593+nanyoudegege@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:08:02 +0800 Subject: [PATCH 101/240] docs: create the reusable Vulkan host output directory (#2687) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- docs/non-windows-hosts.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/non-windows-hosts.md b/docs/non-windows-hosts.md index cf71bc2ca..fe66154ad 100644 --- a/docs/non-windows-hosts.md +++ b/docs/non-windows-hosts.md @@ -178,7 +178,7 @@ With the Linux build of DXC, `spirv-val` and `spirv-dis` from SPIRV-Tools, a C c python3 -B tests/pixel_denorm_vulkan_check.py /path/to/dxc tests/vk_pixel_draw.c --device Intel ``` -`--device` is a substring of the Vulkan device name (repeat it for several adapters), and `VK_DRIVER_FILES` selects a driver such as lavapipe. To build the host once and reuse it, run `cc -std=c11 -O1 -o out/vk/vk_pixel_draw tests/vk_pixel_draw.c -lvulkan` and pass `out/vk/vk_pixel_draw` instead of the `.c` file. +`--device` is a substring of the Vulkan device name (repeat it for several adapters), and `VK_DRIVER_FILES` selects a driver such as lavapipe. To build the host once and reuse it, run `mkdir -p out/vk && cc -std=c11 -O1 -o out/vk/vk_pixel_draw tests/vk_pixel_draw.c -lvulkan` and pass `out/vk/vk_pixel_draw` instead of the `.c` file. A `ps_6_2` pixel shader runs seven operations whose inputs or results are binary32 subnormals and writes each result word to its own RGBA32UI pixel. DXC compiles it with `-spirv -fspv-target-env=vulkan1.2 -fvk-b-shift 0 0 -fvk-t-shift 16 0 -fvk-s-shift 32 0 -fvk-u-shift 48 0`. The words read back must equal IEEE binary32 arithmetic computed in Python under `-denorm preserve`. The same shader compiled with `-denorm ftz` is the negative control and must differ, otherwise the check fails because it cannot tell preserve from flush. The log lists the device, driver, DXC and SPIRV-Tools versions, the SPIR-V execution mode, every word read back for both modes and the cases where the control differs. From aa16aae1a4904ed1be689fdb857e9a5bcf4dcf64 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Thu, 26 Nov 2026 04:08:07 +0100 Subject: [PATCH 102/240] gfx2hlsl: extend the uniform compute load proof to multi-register loads (#2454) * gfx2hlsl: prove a compute buffer load with a uniform address uniform v_readfirstlane_b32 needs a vector source with the same value in every active lane. A buffer_load_dword or buffer_load_format_x in a compute program reads a read-only descriptor (a descriptor used for a load and a store is already refused), so with a uniform VGPR index or offset, a uniform scalar offset and exec known in the entry block, every lane reads the same dword. Mark the destination uniform there. The value has no recomputable expression, so reads past the entry block still refuse. Tests: positive cases plus negative controls for a varying VGPR offset, a varying scalar offset, a graphics stage, no stage kind, unknown exec, a read after the entry block and a varying overwrite. Co-Authored-By: Claude Sonnet 5.5 * gfx2hlsl: extend the uniform compute load proof to multi-register loads The entry-block rule for a compute buffer load with a uniform address covered one destination register. Accept buffer_load_dwordx2/x3/x4 and buffer_load_format_xy/xyz/xyzw too: every destination register of such a load holds the same dword in every lane. The destination range must be exactly as long as the opcode writes, so no register the load leaves alone is marked uniform. None of them records a recomputable expression. Co-Authored-By: Claude Sonnet 5.5 --------- Co-authored-by: Claude Sonnet 5.5 Co-authored-by: tedin7 Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- ...up_gfx2hlsl_readfirstlane_uniform_check.py | 22 +++++++++++++++++++ tools/startup/gfx2hlsl.py | 16 ++++++++++---- 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py b/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py index b5b9fa437..eb64bd759 100644 --- a/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py +++ b/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py @@ -17,9 +17,14 @@ def check(label, condition, detail=''): class Pipe: """The single resource needed by the buffer-load probe.""" + resources = {(('table', 0), 0): {'index': 0}} # the formatted load reads the stride and FORMAT words by index + def resource(self, key, kind): return 'r0' + def ud(self, key): + return 0 + REFUSAL = 'v_readfirstlane_b32 requires a proven uniform source' READ = 'v_readfirstlane_b32 s9, v7' @@ -241,6 +246,23 @@ def run(*instructions, exec_known=True, kind=None, group=None): finally: G.UNIFORM_LOADS = original +# Every destination register of a multi-register load is uniform, and only the registers the opcode writes. +for label, instructions, read in ( + ('two-dword load, first word', ('buffer_load_dwordx2 v[7:8], off, s[4:7], s2',), 7), + ('two-dword load, second word', ('buffer_load_dwordx2 v[7:8], off, s[4:7], s2',), 8), + ('four-dword load, last word', ('buffer_load_dwordx4 v[6:9], off, s[4:7], s2',), 9), + ('load over a varying register', ('v_mov_b32_e32 v8, v0', 'buffer_load_dwordx2 v[7:8], off, s[4:7], s2'), 8), + ('formatted two-component load', ('buffer_load_format_xy v[7:8], off, s[4:7], s2',), 8)): + got = run(*instructions, 'v_readfirstlane_b32 s9, v%d' % read, kind='cs') + check(f'{label} accepted', got[-1] == 's9 = v%d;' % read, repr(got)) +for label, instructions, read in ( + ('two-dword load into three registers', ('v_mov_b32_e32 v9, v0', 'buffer_load_dwordx2 v[7:9], off, s[4:7], s2'), 9), + ('two-dword load into one register', ('v_mov_b32_e32 v8, v0', 'buffer_load_dwordx2 v7, off, s[4:7], s2'), 8), + ('two-dword load with a varying offset', ('buffer_load_dwordx2 v[7:8], v0, s[4:7], 0 offen',), 8), + ('other register after a load', ('v_mov_b32_e32 v6, v0', 'buffer_load_dwordx2 v[7:8], off, s[4:7], s2'), 6)): + got = run(*instructions, 'v_readfirstlane_b32 s9, v%d' % read, kind='cs') + check(f'{label} refused', got == REFUSAL, repr(got)) + # tid.x >> n is 0 in every lane when the group's X size is at most 1 << n (the thread id VGPR is untouched). WAVE = 'v_lshrrev_b32_e32 v1, 6, v0' READ1 = 'v_readfirstlane_b32 s9, v1' diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index d5e92922c..481c3123b 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -914,7 +914,10 @@ def smem_mods(mods): 'v_mul_f32', 'v_fma_f32', 'v_fmaak_f32', 'v_rcp_f32', 'v_med3_f32', 'v_mov_b32', )) -UNIFORM_LOADS = frozenset(('buffer_load_dword', 'buffer_load_format_x')) +UNIFORM_LOAD_WORDS = {'buffer_load_dword': 1, 'buffer_load_dwordx2': 2, 'buffer_load_dwordx3': 3, 'buffer_load_dwordx4': 4, + 'buffer_load_format_x': 1, 'buffer_load_format_xy': 2, 'buffer_load_format_xyz': 3, + 'buffer_load_format_xyzw': 4} +UNIFORM_LOADS = frozenset(UNIFORM_LOAD_WORDS) # DPP quad_perm selections that exchange lanes of a 2x2 pixel quad (lane = 2 * y + x), with the SM 6.0 intrinsic. @@ -3387,10 +3390,13 @@ def one(self, name, asm): all(m in ('idxen', 'offen', 'glc', 'slc', 'dlc') or m.startswith('offset:') for m in mods) and not ('idxen' in mods and 'offen' in mods) and (ops[1] == 'off') == ('idxen' not in mods and 'offen' not in mods) and (ops[1] == 'off' or self.uniform_source(ops[1])) and self.uniform_source(ops[3])) + loaded_regs = () if loaded: candidate = reg_range(ops[0]) - if candidate and candidate[0] == 'v' and candidate[1] == candidate[2]: - dst = candidate[1] + # Exactly the registers the opcode writes, as many as its name says. + count = UNIFORM_LOAD_WORDS[base] + if candidate and candidate[0] == 'v' and candidate[2] <= 255 and candidate[2] - candidate[1] + 1 == count: + dst, loaded_regs = candidate[1], range(candidate[1], candidate[2] + 1) else: loaded = False # A shift right of the X thread id, or of (uniform << K) + thread id, that leaves no thread-id bit. @@ -3424,7 +3430,9 @@ def one(self, name, asm): self.defined_uniform_s.discard(r) self.bad_sgprs.add(r) if dst is not None: - self.uniform_v.add(dst) + self.uniform_v.update(loaded_regs or (dst,)) + for reg in loaded_regs: + getattr(self, 'uniform_expr', {}).pop(reg, None) if hasattr(self, 'uniform_expr'): # Proven sources are scalars, constants and VGPRs; each VGPR needs its own current expression. expr = self.last_v[1] if self.last_v and self.last_v[0] == dst else None From a780d6587e935bd086c1a934333676070d2cc920 Mon Sep 17 00:00:00 2001 From: SimSalabimse <83839581+SimSalabimse@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:08:17 +0100 Subject: [PATCH 103/240] shader: lower s_ff0_i32_b32 in gfx2hlsl (#1723) (#2674) * shader: lower s_ff0_i32_b32 in gfx2hlsl (#1723) Port the pixel_aot find-first-zero SOP1 (firstbitlow of the complement). SCC is unchanged. Lane masks and descriptor words are refused. CPU fixture with a negative control. Co-authored-by: SimSalabimse * test: allow s_mul_hi_* own-arity templates in scalar table check #2405 added s_mul_hi_i32 (and an early arity refuse for both mul_hi forms). The negative control still expected only one non-IndexError survivor. Co-authored-by: SimSalabimse --------- Co-authored-by: Cursor Agent Co-authored-by: SimSalabimse Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- .github/workflows/windows.yml | 1 + AGENTS.md | 1 + CMakeLists.txt | 3 + docs/experiments.md | 9 ++ tests/startup_gfx2hlsl_s_ff0_check.py | 159 ++++++++++++++++++++++++++ tools/startup/gfx2hlsl.py | 39 +++++++ 6 files changed, 212 insertions(+) create mode 100644 tests/startup_gfx2hlsl_s_ff0_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 6a9720799..8fabc1a9b 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -326,6 +326,7 @@ jobs: tests/startup_compute_translate_check.py \ tests/startup_gfx2hlsl_swap_check.py \ tests/startup_gfx2hlsl_s_abs_check.py \ + tests/startup_gfx2hlsl_s_ff0_check.py \ tests/startup_gfx2hlsl_s_bitset_check.py \ tests/startup_gfx2hlsl_s_flbit_check.py \ tests/startup_gfx2hlsl_s_ff1_check.py \ diff --git a/AGENTS.md b/AGENTS.md index 5be74bb03..3afd7fb16 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -175,6 +175,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_compute_translate_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_swap_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_s_abs_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_s_ff0_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_s_bitset_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_s_flbit_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_s_ff1_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 378025a16..c72c8a2b6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3364,6 +3364,9 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(startup_gfx2hlsl_s_abs_dispatch_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl lowers s_ff0_i32_b32 (SOP1, #1723): CPU evaluation and refusals. + add_test(NAME startup_gfx2hlsl_s_ff0 COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_ff0_check.py") # gfx2hlsl lowers s_bitset0_b32 and s_bitset1_b32 (SOP1, #2023 Item J): CPU evaluation and refusals. add_test(NAME startup_gfx2hlsl_s_bitset COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_bitset_check.py") diff --git a/docs/experiments.md b/docs/experiments.md index 8bd30b84c..a32b7c3d3 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -8185,6 +8185,15 @@ word (plus an SCC-dependent branch token) against the same reference: `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_s_abs_dispatch_warp$' -V`. [Refs #1723](https://github.com/R0Y00/Xbox2Windows/issues/1723). +**Scalar find-first-zero.** Startup translation lowers `s_ff0_i32_b32` to +`firstbitlow(~S0)` (0xffffffff when every bit is set), matching `pixel_aot` / +`ff0_i32_b32`. SCC is unchanged. Lane masks and descriptor-bearing sources are +refused. Run +`ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_s_ff0$' -V` +(or `python3 -B tests/startup_gfx2hlsl_s_ff0_check.py`). The fixture is +CPU-only; Windows WARP/hardware draws are left for an independent retest. +[Refs #1723](https://github.com/R0Y00/Xbox2Windows/issues/1723). + **Scalar bit set and clear.** Startup translation lowers `s_bitset0_b32` and `s_bitset1_b32` in place: bit `S0[4:0]` of the destination is cleared or set, and SCC is unchanged (same form as `pixel_aot` / #1579; Refs #2023 Item J). diff --git a/tests/startup_gfx2hlsl_s_ff0_check.py b/tests/startup_gfx2hlsl_s_ff0_check.py new file mode 100644 index 000000000..34e0e283b --- /dev/null +++ b/tests/startup_gfx2hlsl_s_ff0_check.py @@ -0,0 +1,159 @@ +"""s_ff0_i32_b32 in tools/startup/gfx2hlsl.py (#1723). + +usage: startup_gfx2hlsl_s_ff0_check.py + +RDNA 2 ISA SOP1: S_FF0_I32_B32 returns the least-significant zero-bit index +(0xffffffff if every bit is set). SCC is unchanged. Matches pixel_aot / +ff0_i32_b32 (`firstbitlow(~S0)`). Lane masks and descriptor sources are refused. +The reference is plain Python; the translated text is evaluated on the CPU. +""" +import re +import struct +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import disasm_rdna2 as D # noqa: E402 +import gfx2hlsl as G # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import Expr # noqa: E402 + +MASK = 0xffffffff +SOP1 = {name: op for op, (name, _) in D.SOP1_OPS.items()} +WORDS = (0xffffffff, 0xfffffffe, 0x00000000, 0x80000000, 0x7fffffff, 0x55555555, 0x12345678) +SCC_UNSET = 2 +VCC_LO, EXEC_LO = 106, 126 + +failures = [] + + +def check(label, ok, detail=''): + print('%s: %s' % (label, 'ok' if ok else 'MISMATCH'), flush=True) + if not ok: + failures.append(label) + if detail: + print(' ' + detail) + + +def sop1(name, sdst, ssrc): + return struct.pack(' 105: + raise Unsupported('s_ff0_i32_b32 destination %s' % ops[0]) + if self.is_lane_mask(ops[0]) or dst[1] in self.masks: + raise Unsupported('s_ff0_i32_b32 on a lane mask') + imm = re.fullmatch(r'-?(0x[0-9a-fA-F]+|\d+)', ops[1]) + if imm: + value = int(ops[1], 0) & 0xffffffff + zeros = (~value) & 0xffffffff + folded = 0xffffffff if zeros == 0 else (zeros & -zeros).bit_length() - 1 + self.set_s(dst[1], '0x%08xu' % folded, ('const', folded)) + return None + src = reg_range(ops[1]) + if not src or src[0] != 's' or src[1] != src[2] or src[1] > 105: + raise Unsupported('s_ff0_i32_b32 source %s' % ops[1]) + if self.is_lane_mask(ops[1]) or src[1] in self.masks: + raise Unsupported('s_ff0_i32_b32 on a lane mask') + sym = self.sym.get(src[1]) + if sym and sym[0] not in ('const', 'ud', 'fixed_buffer_word'): + raise Unsupported('s_ff0_i32_b32 on %s data' % sym[0]) + if sym and sym[0] == 'const': + value = sym[1] & 0xffffffff + zeros = (~value) & 0xffffffff + folded = 0xffffffff if zeros == 0 else (zeros & -zeros).bit_length() - 1 + self.set_s(dst[1], '0x%08xu' % folded, ('const', folded)) + return None + src_u = self.u(ops[1]) + self.set_s(dst[1], 'firstbitlow(~%s)' % src_u) + return None + def op_s_ff1_i32_b32(self, ops, mods): """Find first set bit in a 32-bit scalar; SCC unchanged (#2022 Item F). From e60b755014d136e56e56f00b1f8b4bdf8a0c8196 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?As=C4=B1m=20Mirza=20=C3=87iftler?= <113895866+Asimmimx@users.noreply.github.com> Date: Thu, 26 Nov 2026 06:08:33 +0300 Subject: [PATCH 104/240] shader: lower compute v_bfm_b32 (#1580) Refs #1546. v_bfm_b32 vD, a, b (VOP3 only on gfx10) becomes the inline HLSL expression ((1u << (a & 31u)) - 1u) << (b & 31u): a width taken from src0[4:0] and an offset from src1[4:0], modulo 2^32. A width field of 0 gives an empty mask, a width of 32 cannot be encoded, and mask bits shifted past bit 31 are dropped. This matches LLVM's BFM selection pattern (shl (add (shl 1, a), -1), b) -> V_BFM_B32_e64 and Mesa's nir bfm definition. Both sources must be known words, as for v_mul_lo_u32, and the result is data only. tests/compute_alu_bfm_check.py varies the read-compute-write fixture by hand to store bfm(w, w >> 5) ^ bfm(cap, 0x7b) ^ bfm(44, gid). It covers VGPR, SGPR, literal, inline and dispatch-index sources, every width from 0 to 31 and masks cut at bit 31. Expected words come from a bit-by-bit Python model, checked against five hand-worked lanes. On WARP the full 320-word readback must match. Wrong references (operands swapped, 6-bit fields, width 0 as 32, rotated bits, one word off, lane 150 writing) and four HLSL mutants must each fail. The translator controls refuse modifiers, clamp, ranges, vcc_lo/exec_lo, a float inline constant, the _e64 spelling, s_bfm and v_bfe/v_bfi, and unknown sources. Co-authored-by: tedin7 Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 5 + docs/experiments.md | 8 ++ tests/compute_alu_bfm_check.py | 206 +++++++++++++++++++++++++++++++++ tools/compute_store_aot.py | 3 +- 4 files changed, 221 insertions(+), 1 deletion(-) create mode 100644 tests/compute_alu_bfm_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index c72c8a2b6..665afcfcb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -9791,6 +9791,11 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(compute_store_aot_f32_${adapter} PROPERTIES TIMEOUT 60 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/compute_store_aot_f32_${adapter}.txt") + add_test(NAME compute_store_aot_alu_bfm_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/compute_alu_bfm_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(compute_store_aot_alu_bfm_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/compute_store_aot_alu_bfm_${adapter}.txt") add_test(NAME compute_store_aot_cvt_u32_f32_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/compute_store_check.py" draw-cvt-u32-f32 "${DXC_EXECUTABLE}" "$" ${adapter}) diff --git a/docs/experiments.md b/docs/experiments.md index a32b7c3d3..f4d8a241f 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -6621,6 +6621,14 @@ The source-built 32-thread fixture stores four words per thread (`128` words act The fixture replaces the `umin` of the read-compute-write fixture with two `v_xor3_b32`, hand-edited in LLVM 15 spelling: `out = (p ^ key ^ gid) ^ 0x2c5a96e1 ^ -16`, where `p` is the product above and `key = params[0].y = 0xa5c30f96`. Its sources are a result, the dispatch index, an SGPR constant word, a literal and a negative inline constant. The expected words come from a Python model of the instruction definition; lane 0 is also worked by hand (`0x2d574c65`). The readback uses the read harness and its three dispatches and compares all 320 words. On five groups with `n = 150`, each of these references must fail at the first word where it differs: one word off, lane 150 also writing, OR, AND or an add instead of XOR, each source dropped, and `+16` for `-16`. So must recompiled HLSL with an OR for either XOR, the key read from `params[0].z`, the dispatch index dropped, the literal off by one bit, or the inline constant dropped. Run `ctest --preset dev --no-tests=error -R '^compute_store_aot_alu_xor3_(warp|hardware)$' -V`. The translation controls alone are `python -B tests/compute_alu_xor3_check.py controls`. +#### Bitfield mask (`v_bfm_b32`) + +`v_bfm_b32 vD, a, b` is VOP3 only on gfx10. Its result is `((1 << (a & 31)) - 1) << (b & 31)`, modulo 2^32: `a` is the width and `b` the offset. A width field of 0 gives 0. A width of 32 cannot be encoded, so the widest mask is `0x7fffffff`. Mask bits shifted past bit 31 are dropped. Both sources are known words, as for `v_mul_lo_u32`, and the result is data only. + +The fixture in `tests/compute_alu_bfm_check.py` is the read-compute-write kernel above with its ALU lines replaced by hand. With `w` the source word of lane `gid` and `cap = params[0].y = 0xc0de0029`, it stores `bfm(w, w >> 5) ^ bfm(cap, 0x7b) ^ bfm(44, gid)`. The sources are two VGPRs, an SGPR with a literal, and an inline constant with the dispatch index. Bits above bit 4 are set in every width and offset word. Lanes 0 to 31 see every width from 0 to 31, and many lanes have masks cut at bit 31. The expected words come from a Python model that builds each mask bit by bit. Five lanes are also worked out by hand: lane 0 is `0x78000fff`, lane 14 (width 31) is `0x0bffc000`, lane 31 (width 0) is `0x78000000`, lane 32 is `0x07ff0fff` and lane 149 is `0xf81f8000`. + +The Windows run uses the read harness and its three dispatches and compares all 320 words. Each of these references must fail at the first word where it differs: one word off by one bit, lane 150 also writing, the operands swapped, a 6-bit width or offset field, a width of 0 read as 32, and the cut bits rotated into the low bits. So must recompiled HLSL with the `- 1u` dropped, the inline width 43, the cap term's operands swapped, or the cap read from `params[0].z`. The translation controls refuse `abs` and negation modifiers, `clamp`, a register range, `vcc_lo`, `exec_lo`, a float inline constant, the `_e64` spelling, `s_bfm_b32`, `s_bfm_b64`, `v_bfe_u32` and `v_bfi_b32` with `Unsupported compute instruction`. Unknown sources and a destination past v255 fail with `Unverified ALU operand`. A result used as a store address or a lane-guard operand is refused. The fixture text is checked against LLVM 19 `llvm-mc` only; the test does not assemble it. Run `ctest --preset dev --no-tests=error -R '^compute_store_aot_alu_bfm_(warp|hardware)$' -V`. + #### Negated and absolute binary32 sources Issue #1546 lists the `-|v|` operand form among the gaps of the measured compute programs. The four binary32 forms above also lower in their VOP3 spelling, `v_add_f32_e64`, `v_sub_f32_e64`, `v_subrev_f32_e64` and `v_mul_f32_e64`, when at least one source carries a source modifier as LLVM 15 prints it on a register: `-v`, `|v|` or `-|v|` (likewise for an SGPR). The modifiers act on the sign bit of the 32-bit word, abs first and then neg, as the pixel translator does for `v_cvt_f64_f32_e64` and the binary64 compare sources: `|v|` is `(w & 0x7fffffffu)`, `-v` is `(w ^ 0x80000000u)` and `-|v|` is `((w & 0x7fffffffu) ^ 0x80000000u)`. They are integer operations on the word, so a signed zero or a NaN payload keeps its other bits; no float `abs()` or unary minus is emitted. In this spelling either source may be a VGPR, an SGPR that holds a known word, a literal, the integer zero or an inline float constant. The operation, its rounding and its finite-and-normal caller contract are those of the `_e32` forms. diff --git a/tests/compute_alu_bfm_check.py b/tests/compute_alu_bfm_check.py new file mode 100644 index 000000000..5745b2f5f --- /dev/null +++ b/tests/compute_alu_bfm_check.py @@ -0,0 +1,206 @@ +"""Check the compute lowering of v_bfm_b32 between a guarded read and its store (#1546). + +Modes: + controls translator output and rejections only + draw also dispatch the fixture and compare the UAV with an independent reference +""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import compute_store_check as base + +# v_bfm_b32 is VOP3 only on gfx10: D = ((1 << S0[4:0]) - 1) << S1[4:0], modulo 2^32. src0 is the width and +# src1 the offset. A width field of 0 gives an empty mask; a width of 32 cannot be encoded, so the widest mask is +# 0x7fffffff. Mask bits shifted past bit 31 are dropped, not rotated. +# +# The read-compute-write fixture of compute_store_check.py with its ALU lines replaced, by hand, in LLVM 15 gfx1013 +# spelling. With w = source word gid (byte offset gid * 4) and cap = params[0].y: +# a = bfm(w, w >> 5) VGPR sources; both fields come from words with higher bits set +# b = bfm(cap, 0x7b) SGPR width, literal offset 0x7b & 31 = 27 +# c = bfm(44, gid) inline width 44 & 31 = 12, offset from the dispatch index +# store a ^ b ^ c at element gid +# The low five bits of source_word(gid) are 17 * (gid + 1) mod 32, so lanes 0..31 see every width, 0 included. +READ_BFM = base.variant( + base.READ_COMPUTE, + ("v_and_b32_e32 v2, 0xffff, v1", ""), + ("v_lshrrev_b32_e32 v1, 16, v1", "v_lshrrev_b32_e32 v2, 5, v1"), + ("v_mad_u32_u24 v1, v2, v1, v0", "v_bfm_b32 v2, v1, v2\nv_bfm_b32 v3, s0, 0x7b\nv_bfm_b32 v4, 44, v0"), + ("v_min_u32_e32 v1, s0, v1", "v_xor_b32_e32 v2, v3, v2\nv_xor_b32_e32 v1, v4, v2"), +) +BFM_CASE = ("read_bfm", READ_BFM, 32, base.READ_BINDING) +# Width field 0x29 & 31 = 9 at offset 27: only bits 27..31 survive, b = 0xf8000000. +BFM_CAP = 0xc0de0029 +LOAD = base.READ_LOADS["read_copy"] +BFM_STORE = (" outputData.Store(tid.x * 4u + 0u, ((((1u << (0x0000002cu & 31u)) - 1u) << (tid.x & 31u)) ^ " + "((((1u << (params[0].y & 31u)) - 1u) << (0x0000007bu & 31u)) ^ (((1u << ({0} & 31u)) - 1u) << " + "(({0} >> (0x00000005u & 31u)) & 31u)))));").format(LOAD) +# Lanes worked out by hand from source_word(gid) = 0x8b02a7f1 + gid * 0x413b1 (gid: width, offset of a): +# 0: 17, 31 a = 0x80000000 c = 0x00000fff -> 0x78000fff +# 14: 31, 28 a = 0xf0000000 (widest field) c = 0x03ffc000 -> 0x0bffc000 +# 31: 0, 19 a = 0 (empty mask) c = 0x80000000 -> 0x78000000 +# 32: 17, 16 a = 0xffff0000 c = 0x00000fff -> 0x07ff0fff (c offset 32 & 31 = 0) +# 149: 22, 15 a = 0xffff8000 c = 0xffe00000 -> 0xf81f8000 +HAND_WORDS = {0: 0x78000fff, 14: 0x0bffc000, 31: 0x78000000, 32: 0x07ff0fff, 149: 0xf81f8000} + + +def bit_mask(width, offset, *, rotate=False): + """A mask built bit by bit: bits offset .. offset + width - 1, dropping (or, if rotate, wrapping) bits past 31.""" + bits = range(offset, offset + min(width, 32)) + return sum(1 << (bit % 32) for bit in bits) if rotate else sum(1 << bit for bit in bits if bit < 32) + + +def bfm_word(gid, *, swap=False, width_field=31, offset_field=31, zero_full=False, rotate=False): + """Independent CPU reference of read_bfm for one lane. The keywords select a wrong model of the instruction.""" + word = base.source_word(gid) + + def bfm(src0, src1): + width, offset = (src1, src0) if swap else (src0, src1) + width, offset = width & width_field, offset & offset_field + return bit_mask(32 if zero_full and width == 0 else width, offset, rotate=rotate) + + return bfm(word, word >> 5) ^ bfm(BFM_CAP, 0x7b) ^ bfm(44, gid) + + +def bfm_words(groups, bound, **reference): + words = [base.SENTINEL] * 320 + for gid in range(min(32 * groups, bound)): + words[gid] = bfm_word(gid, **reference) + return words + + +# Wrong models of the instruction; each must give other words for the largest dispatch and fail the readback. +WRONG = (("operands swapped", dict(swap=True)), ("6-bit width field", dict(width_field=63)), + ("6-bit offset field", dict(offset_field=63)), ("width 0 as 32", dict(zero_full=True)), + ("mask rotated", dict(rotate=True))) + + +def controls(): + """Translator output, the independent reference against hand-worked words, and the refused forms.""" + def bfm(*changes): + _, lines, width, binding = BFM_CASE + return base.aot.lower(base.variant(lines, *changes), width, **binding).splitlines() + + for gid, word in HAND_WORDS.items(): + assert bfm_word(gid) == word, (gid, hex(bfm_word(gid)), hex(word)) + widths = [base.source_word(gid) & 31 for gid in range(32)] + assert sorted(widths) == list(range(32)), widths + lines = bfm() + assert lines[-4:] == [base.GUARD_IF, BFM_STORE, " }", "}"], lines + # A copy of a result is the same program; exchanging the sources is another. + assert bfm(("v_bfm_b32 v4, 44, v0", "v_bfm_b32 v5, 44, v0\nv_mov_b32_e32 v4, v5")) == lines + assert bfm(("v_bfm_b32 v3, s0, 0x7b", "v_bfm_b32 v3, 0x7b, s0"))[-3] != lines[-3] + assert "(((1u << (0x0000007bu & 31u)) - 1u) << (params[0].y & 31u))" in bfm( + ("v_bfm_b32 v3, s0, 0x7b", "v_bfm_b32 v3, 0x7b, s0"))[-3] + # A negative inline constant is its 32-bit pattern: -1 & 31 = 31. + assert "(((1u << (0xffffffffu & 31u)) - 1u) << (tid.x & 31u))" in bfm(("44, v0", "-1, v0"))[-3] + bfm_a = "v_bfm_b32 v2, v1, v2" + unsupported, operand = "Unsupported compute instruction: ", "Unverified ALU operand" + for message, changes in ( + # Source modifiers: LLVM refuses them for this integer opcode, and so does the lowering. + (unsupported + "v_bfm_b32", ((bfm_a, "v_bfm_b32 v2, |v1|, v2"),)), + (unsupported + "v_bfm_b32", ((bfm_a, "v_bfm_b32 v2, -v1, v2"),)), + (unsupported + "v_bfm_b32", ((bfm_a, "v_bfm_b32 v2, v1, -v2"),)), + (unsupported + "v_bfm_b32", ((bfm_a, "v_bfm_b32 v2, v1, v2 clamp"),)), + # Operand spellings outside ALU_SOURCE: a register range, vcc_lo, exec_lo and a float inline constant. + (unsupported + "v_bfm_b32", ((bfm_a, "v_bfm_b32 v2, v[1:2], v2"),)), + (unsupported + "v_bfm_b32", ((bfm_a, "v_bfm_b32 v2, vcc_lo, v2"),)), + (unsupported + "v_bfm_b32", ((bfm_a, "v_bfm_b32 v2, v1, exec_lo"),)), + (unsupported + "v_bfm_b32", ((bfm_a, "v_bfm_b32 v2, v1, 0.5"),)), + # Spellings and neighbours that are not this lowering: the _e64 suffix LLVM 15 does not print, the scalar + # and 64-bit forms, and the bitfield extract and insert opcodes. + (unsupported + "v_bfm_b32_e64", ((bfm_a, "v_bfm_b32_e64 v2, v1, v2"),)), + (unsupported + "s_bfm_b32", (("v_bfm_b32 v3, s0, 0x7b", "s_bfm_b32 s16, s0, 27\nv_mov_b32_e32 v3, s16"),)), + (unsupported + "s_bfm_b64", (("v_bfm_b32 v3, s0, 0x7b", "s_bfm_b64 s[16:17], s0, 27\nv_mov_b32_e32 v3, s16"),)), + (unsupported + "v_bfe_u32", ((bfm_a, "v_bfe_u32 v2, v1, v2, 5"),)), + (unsupported + "v_bfi_b32", ((bfm_a, "v_bfi_b32 v2, v1, v2, v0"),)), + # Sources that are not known words: an unwritten, a descriptor and the saved exec-mask SGPR, an unwritten + # VGPR, a literal wider than 32 bits and a constant word still waiting for its s_waitcnt. Also a + # destination past v255. + (operand, (("s0, 0x7b", "s20, 0x7b"),)), + (operand, (("s0, 0x7b", "s8, 0x7b"),)), + (operand, (("s0, 0x7b", "s2, 0x7b"),)), + (operand, ((bfm_a, "v_bfm_b32 v2, v1, v9"),)), + (operand, (("s0, 0x7b", "s0, 0x1ffffffff"),)), + (operand, (("s_buffer_load_dword s0, s[4:7], 0x4", ""), + ("v_lshrrev_b32_e32 v2, 5, v1", "s_buffer_load_dword s0, s[4:7], 0x4\nv_lshrrev_b32_e32 v2, 5, v1"))), + (operand, ((bfm_a, "v_bfm_b32 v256, v1, v2"),)), + ("Vector load result used or overwritten before s_waitcnt vmcnt(0)", (("s_waitcnt vmcnt(0)", ""),)), + # A result is data only: not an address and not a lane-guard operand, and a doubling chain is refused. + ("Unsupported store address", (("v1, v0, s[8:11]", "v0, v4, s[8:11]"),)), + ("Unverified lane guard compare", (("v_xor_b32_e32 v1, v4, v2", + "v_xor_b32_e32 v1, v4, v2\nv_cmp_gt_u32_e32 vcc_lo, s3, v4"),)), + ("ALU expression too large", (("v_xor_b32_e32 v1, v4, v2", + "v_xor_b32_e32 v1, v4, v2" + "\nv_bfm_b32 v1, v1, v1" * 4),)), + ): + base.rejects(message, bfm, *changes) + + +def draw(directory, compiler, renderer, backend): + """Dispatch read_bfm on the renderer and compare the UAV with bfm_words, with wrong references and mutants.""" + name, lines, width, binding = BFM_CASE + src, cso, case = [directory / x for x in ("store.hlsl", "store.cso", "store.case")] + src.write_text(base.aot.lower(lines, width, **binding), encoding="ascii") + subprocess.run([compiler, "-T", "cs_6_0", "-E", "main", "-Fo", cso, src], check=True) + cmd = [renderer, backend, "--compute-store-case", cso, case] + constants = [0x5eed0000 + i for i in range(16)] + constants[1] = BFM_CAP + + def write(groups, bound, words): + case.write_bytes(struct.pack("<337I", groups, *words, bound, *constants[1:])) + + for groups, bound in base.READ_RUNS: + write(groups, bound, bfm_words(groups, bound)) + result = subprocess.run(cmd) + if result.returncode: + return result.returncode + groups, bound = base.READ_RUNS[-1] + expected = bfm_words(groups, bound) + assert all(expected[gid] == word for gid, word in HAND_WORDS.items() if gid < bound), "hand-worked words" + fields = [(base.source_word(g) & 31, (base.source_word(g) >> 5) & 31) for g in range(bound)] + # The inputs must show an empty mask, the widest mask, masks cut at bit 31 and masks that fit. + assert any(w == 0 for w, _ in fields) and any(w == 31 for w, _ in fields), "width extremes" + assert any(w + o > 32 for w, o in fields) and any(0 < w and w + o <= 32 for w, o in fields), "cut and whole masks" + off = list(expected) + off[bound - 1] ^= 1 + wrong = [("one word off", off), ("lane past the bound", bfm_words(groups, bound + 1))] + wrong += [(label, bfm_words(groups, bound, **reference)) for label, reference in WRONG] + for label, reference in wrong: + assert reference != expected, f"{label} would go unseen" + word = next(i for i, (a, b) in enumerate(zip(expected, reference)) if a != b) + write(groups, bound, reference) + bad = subprocess.run(cmd, capture_output=True, text=True) + if bad.returncode != 1 or f"word={word} expected=" not in bad.stderr: + raise AssertionError(f"{name}: reference '{label}' escaped detection\n{bad.stderr}") + write(groups, bound, expected) + source = src.read_text(encoding="ascii") + cap_term = "(((1u << (params[0].y & 31u)) - 1u) << (0x0000007bu & 31u))" + for label, old, new in (("mask without the minus one", " - 1u)", " - 0u)"), + ("inline width 43", "(0x0000002cu & 31u)", "(0x0000002bu & 31u)"), + ("cap term operands swapped", cap_term, + "(((1u << (0x0000007bu & 31u)) - 1u) << (params[0].y & 31u))"), + ("cap from another word", "params[0].y", "params[0].z")): + mutated = source.replace(old, new) + if mutated == source: + raise AssertionError(f"{name}: mutation '{label}' did not change the source") + mutant, mutant_cso = directory / "mutated.hlsl", directory / "mutated.cso" + mutant.write_text(mutated, encoding="ascii") + subprocess.run([compiler, "-T", "cs_6_0", "-E", "main", "-Fo", mutant_cso, mutant], check=True) + bad = subprocess.run([*cmd[:3], mutant_cso, case], capture_output=True, text=True) + if bad.returncode != 1 or "Compute readback differs" not in bad.stderr: + raise AssertionError(f"{name}: mutation '{label}' escaped detection") + return 0 + + +if __name__ == "__main__": + controls() + mode, *args = sys.argv[1:] + if mode == "controls" and not args: + sys.exit(0) + if mode != "draw" or len(args) != 3: + sys.exit(__doc__) + with tempfile.TemporaryDirectory() as tmp: + sys.exit(draw(Path(tmp), *args)) diff --git a/tools/compute_store_aot.py b/tools/compute_store_aot.py index b73584cb5..f5c274c7b 100644 --- a/tools/compute_store_aot.py +++ b/tools/compute_store_aot.py @@ -50,6 +50,7 @@ # src0[23:0] * src1[23:0] + src2, modulo 2^32. None of them writes vcc, so the guard compare stays valid. ALU = { "v_and_b32_e32": f"({INTEGER['and_b32'][1]})", + "v_bfm_b32": "(((1u << ({0} & 31u)) - 1u) << ({1} & 31u))", # VOP3 only: ((1 << src0[4:0]) - 1) << src1[4:0] "v_lshrrev_b32_e32": f"({INTEGER['lshrrev_b32'][1]})", "v_lshlrev_b32_e32": f"({INTEGER['lshlrev_b32'][1]})", # v_max3_u32 and v_min3_u32 are the unsigned maximum and minimum of the three sources, max(max(a, b), c). @@ -2308,7 +2309,7 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N + (f"{result};" if bound else f"{inside} ? {result} : ({hlsl_word(values[2])});"))) vector[dst] = ("alu", value) elif ((m := re.fullmatch(rf"(v_(?:and_b32|lshrrev_b32|min_u32|max_u32|add_nc_u32|or_b32|xor_b32|lshlrev_b32|ashrrev_i32|sub_nc_u32|subrev_nc_u32)_e32) v(\d+), {ALU_SOURCE}, (v\d+)", line)) - or (m := re.fullmatch(rf"(v_mul_lo_u32|v_add_nc_i32|v_sub_nc_i32|v_bcnt_u32_b32) v(\d+), {ALU_SOURCE}, {ALU_SOURCE}", line)) + or (m := re.fullmatch(rf"(v_mul_lo_u32|v_add_nc_i32|v_sub_nc_i32|v_bcnt_u32_b32|v_bfm_b32) v(\d+), {ALU_SOURCE}, {ALU_SOURCE}", line)) or (m := re.fullmatch(rf"(v_mad_u32_u24|v_xor3_b32|v_max3_u32|v_min3_u32|v_med3_u32|v_med3_i32|v_mad_i32_i24) v(\d+), {ALU_SOURCE}, {ALU_SOURCE}, {ALU_SOURCE}", line)) and None not in [alu_word(token, scalar, vector, pending, sizes) for token in m.groups()[2:]]): # VOP2 takes a VGPR as src1. A v_mad_u32_u24 with an address operand is a row pitch below. From 547a8c67a6920effa8aaf2c70670e893179b6794 Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Thu, 26 Nov 2026 05:09:32 +0200 Subject: [PATCH 105/240] tooling: harden fuzz_cpu CLI path/count guards and atomic writes (#2673) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 3 + tests/fuzz_cpu_cli_check.py | 464 ++++++++++++++++++++++++++++++++++++ tools/fuzz_cpu.py | 120 ++++++++-- 3 files changed, 569 insertions(+), 18 deletions(-) create mode 100644 tests/fuzz_cpu_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 665afcfcb..d7880636f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4927,6 +4927,9 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tools/fuzz_cpu.py" check "${CPU_FUZZ_SEED}" "${CPU_FUZZ_FUNCTIONS}" "$" "$" "${cpu_fuzz_o2}") set_tests_properties(cpu_aot_fuzz_smoke PROPERTIES TIMEOUT 60) + add_test(NAME tooling_fuzz_cpu_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/fuzz_cpu_cli_check.py") + set_tests_properties(tooling_fuzz_cpu_cli_check PROPERTIES TIMEOUT 60) # Fixed RSP frames: saved nonvolatile registers, partial spill overlaps and a planted reload fault. set(CPU_FUZZ_FRAMES_SEED "0xF4A3" CACHE STRING "Seed for the CPU differential fuzz frame test") set(CPU_FUZZ_FRAMES_FUNCTIONS "16" CACHE STRING "Number of generated functions in the CPU differential fuzz frame test") diff --git a/tests/fuzz_cpu_cli_check.py b/tests/fuzz_cpu_cli_check.py new file mode 100644 index 000000000..4f26ca185 --- /dev/null +++ b/tests/fuzz_cpu_cli_check.py @@ -0,0 +1,464 @@ +#!/usr/bin/env python3 +"""Pure-Python CLI, atomic-write, path/count guard, and mutation suite for tools/fuzz_cpu.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +import os +from pathlib import Path +import runpy +import struct +import subprocess +import sys +import tempfile +import types +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOLS_DIR = ROOT / "tools" +TOOL = TOOLS_DIR / "fuzz_cpu.py" +sys.path.insert(0, str(TOOLS_DIR)) + +import fuzz_cpu # noqa: E402 + + +def _run_main(argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = fuzz_cpu.main(argv) + except SystemExit as exc: + code = exc.code + if not isinstance(code, int): + if code is not None: + stderr.write(f"{code}\n") + code = 0 if code is None else 1 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class FuzzCpuCliPositiveTests(unittest.TestCase): + def test_emit_multi_area_atomic_nested_outputs_and_zero_tmp_files(self) -> None: + areas_to_check = ("leaf", "frames", "calls", "switches", "scalar_fp", "x87", "bits") + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + real_replace = os.replace + + for idx, area in enumerate(areas_to_check): + with self.subTest(area=area): + out_dir = base / f"nested_{idx}" / area + asm_path = out_dir / f"{area}.asm" + def_path = out_dir / f"{area}.def" + seen_replaces: list[tuple[Path, Path]] = [] + + def tracking_replace(src, dst): + src_path, dst_path = Path(src), Path(dst) + seen_replaces.append((src_path, dst_path)) + self.assertEqual(src_path.parent.resolve(), dst_path.parent.resolve()) + self.assertTrue(src_path.name.endswith(".tmp")) + return real_replace(src, dst) + + with mock.patch.object(fuzz_cpu.os, "replace", side_effect=tracking_replace): + code, out, err = _run_main([ + "emit", + "0xA902", + "4", + str(asm_path), + str(def_path), + "--area", + area, + ]) + + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(out, "") + self.assertEqual(err, "") + self.assertEqual(len(seen_replaces), 2) + self.assertEqual(sorted(p.name for p in out_dir.iterdir()), sorted([asm_path.name, def_path.name])) + asm_text = asm_path.read_text(encoding="utf-8") + def_text = def_path.read_text(encoding="utf-8") + self.assertIn(".code", asm_text) + self.assertTrue(asm_text.endswith("END\n")) + expected_lib = fuzz_cpu.AREAS[area][1] + self.assertTrue(def_text.startswith(f"LIBRARY {expected_lib}\nEXPORTS\n")) + + # End-to-end subprocess check with overwrite on existing files. + sub_dir = base / "sub_emit" + sub_asm = sub_dir / "out.asm" + sub_def = sub_dir / "out.def" + sub_dir.mkdir() + sub_asm.write_text("stale asm", encoding="utf-8") + sub_def.write_text("stale def", encoding="utf-8") + proc = _run_subprocess("emit", "0x1234", "2", str(sub_asm), str(sub_def), "--area", "loops") + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertEqual(proc.stderr, "") + self.assertEqual(sorted(p.name for p in sub_dir.iterdir()), ["out.asm", "out.def"]) + self.assertIn("LIBRARY cpu_fuzz_loops", sub_def.read_text(encoding="utf-8")) + + def test_translate_atomic_write_and_entrypoint(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "synthetic.dll" + image.write_bytes(b"MZ-synthetic-placeholder") + out_cpp = base / "nested" / "lifted.cpp" + translated_calls: list[tuple[Path, list[str]]] = [] + + def fake_translate(img: Path, names: list[str]) -> tuple[str, dict]: + translated_calls.append((img, list(names))) + return "// lifted\nint ok = 1;\n", {} + + fake_mod = types.SimpleNamespace(translate=fake_translate) + with mock.patch.object(fuzz_cpu, "translator_module", return_value=fake_mod): + code, out, err = _run_main(["translate", "0xA902", "2", str(image), str(out_cpp)]) + + self.assertEqual(code, 0, err) + self.assertEqual(out, "") + self.assertEqual(err, "") + self.assertEqual(len(translated_calls), 1) + self.assertEqual(translated_calls[0][0], image) + self.assertEqual(translated_calls[0][1], ["fuzz_0", "fuzz_1"]) + self.assertEqual(out_cpp.read_text(encoding="utf-8"), "// lifted\nint ok = 1;\n") + self.assertEqual([p.name for p in out_cpp.parent.iterdir()], ["lifted.cpp"]) + + # sys.argv forwarding (argv=None) and __main__ entrypoint via runpy. + asm_entry = base / "entry.asm" + def_entry = base / "entry.def" + cli_argv = [str(TOOL), "emit", "0x55", "1", str(asm_entry), str(def_entry)] + with mock.patch.object(sys, "argv", cli_argv): + code_none, out_none, err_none = _run_main(None) + self.assertEqual(code_none, 0, err_none) + self.assertEqual(out_none, "") + self.assertEqual(err_none, "") + self.assertTrue(asm_entry.is_file() and def_entry.is_file()) + + asm_entry.unlink() + def_entry.unlink() + stdout, stderr = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", cli_argv), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 0) + self.assertEqual(stdout.getvalue(), "") + self.assertEqual(stderr.getvalue(), "") + self.assertTrue(asm_entry.is_file() and def_entry.is_file()) + + +class FuzzCpuCliNegativeAndMutationTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_code: int | None = 1, + fragments: tuple[str, ...] = (), + check_subprocess: bool = True, + ) -> str: + code, out, err = _run_main(argv) + if expected_code is None: + self.assertNotEqual(code, 0) + else: + self.assertEqual(code, expected_code, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertTrue(err.strip(), f"expected stderr for {argv!r}") + for fragment in fragments: + self.assertIn(fragment.lower(), err.lower()) + + if check_subprocess: + proc = _run_subprocess(*argv) + if expected_code is None: + self.assertNotEqual(proc.returncode, 0) + else: + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertTrue(proc.stderr.strip(), f"expected subprocess stderr for {argv!r}") + for fragment in fragments: + self.assertIn(fragment.lower(), proc.stderr.lower()) + return err + + def test_non_positive_count_rejected_upfront_in_emit_translate_and_check(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "image.dll" + lifted = base / "lifted.dll" + o2 = base / "o2.dll" + for dll in (image, lifted, o2): + dll.write_bytes(b"MZ-placeholder") + absent_asm = base / "absent_emit" / "out.asm" + absent_def = base / "absent_emit" / "out.def" + absent_cpp = base / "absent_trans" / "out.cpp" + + for bad_count in ("0", "-3"): + with self.subTest(bad_count=bad_count): + with ( + mock.patch.object(fuzz_cpu, "_write_atomic", side_effect=AssertionError("should not write")), + mock.patch.object(fuzz_cpu, "translator_module", side_effect=AssertionError("should not lift")), + mock.patch.object(fuzz_cpu.ctypes, "CDLL", side_effect=AssertionError("should not load DLL")), + ): + self._assert_clean_failure( + ["emit", "1", bad_count, str(absent_asm), str(absent_def)], + fragments=("count must be >= 1",), + ) + self._assert_clean_failure( + ["translate", "1", bad_count, str(image), str(absent_cpp)], + fragments=("count must be >= 1",), + ) + self._assert_clean_failure( + ["check", "1", bad_count, str(image), str(lifted), str(o2)], + fragments=("count must be >= 1",), + ) + + self.assertFalse(absent_asm.parent.exists()) + self.assertFalse(absent_cpp.parent.exists()) + + def test_missing_and_directory_pe_rejected_upfront_in_translate_and_check(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + valid_dll = base / "valid.dll" + valid_dll.write_bytes(b"MZ-placeholder") + dir_dll = base / "dir_dll" + dir_dll.mkdir() + missing_dll = base / "missing.dll" + absent_cpp = base / "never_created" / "out.cpp" + + with ( + mock.patch.object(fuzz_cpu, "translator_module", side_effect=AssertionError("should not lift")), + mock.patch.object(fuzz_cpu, "_write_atomic", side_effect=AssertionError("should not write")), + ): + self._assert_clean_failure( + ["translate", "1", "2", str(missing_dll), str(absent_cpp)], + fragments=("image file not found",), + ) + self._assert_clean_failure( + ["translate", "1", "2", str(dir_dll), str(absent_cpp)], + fragments=("image path is a directory",), + ) + self.assertFalse(absent_cpp.parent.exists()) + + with mock.patch.object(fuzz_cpu.ctypes, "CDLL", side_effect=AssertionError("should not load DLL")): + for label, argv, frag in ( + ("missing_native", ["check", "1", "2", str(missing_dll), str(valid_dll), str(valid_dll)], "native file not found"), + ("dir_native", ["check", "1", "2", str(dir_dll), str(valid_dll), str(valid_dll)], "native path is a directory"), + ("missing_lifted", ["check", "1", "2", str(valid_dll), str(missing_dll), str(valid_dll)], "lifted file not found"), + ("dir_lifted", ["check", "1", "2", str(valid_dll), str(dir_dll), str(valid_dll)], "lifted path is a directory"), + ("missing_o2", ["check", "1", "2", str(valid_dll), str(valid_dll), str(missing_dll)], "o2 file not found"), + ("dir_o2", ["check", "1", "2", str(valid_dll), str(valid_dll), str(dir_dll)], "o2 path is a directory"), + ( + "missing_mutant", + ["check", "1", "2", str(valid_dll), str(valid_dll), str(valid_dll), "--area", "frames", "--mutant", str(missing_dll)], + "mutant file not found", + ), + ( + "dir_mutant", + ["check", "1", "2", str(valid_dll), str(valid_dll), str(valid_dll), "--area", "frames", "--mutant", str(dir_dll)], + "mutant path is a directory", + ), + ): + with self.subTest(case=label): + self._assert_clean_failure(argv, fragments=(frag,)) + + def test_corrupt_pe_translate_exits_cleanly_without_traceback(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + corrupt = base / "corrupt.dll" + corrupt.write_bytes(b"not a PE image") + out_cpp = base / "absent" / "lifted.cpp" + self._assert_clean_failure(["translate", "0xA902", "1", str(corrupt), str(out_cpp)]) + self.assertFalse(out_cpp.parent.exists()) + + def test_output_dir_file_parent_and_collision_guards(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(b"MZ-input") + existing_dir = base / "out_dir" + existing_dir.mkdir() + file_parent = base / "file_parent.txt" + file_parent.write_text("keep-parent", encoding="utf-8") + existing_asm = base / "existing.asm" + existing_asm.write_text("keep-asm", encoding="utf-8") + hardlink_def = base / "hardlink.def" + hardlink_def.hardlink_to(existing_asm) + hardlink_cpp = base / "hardlink.cpp" + hardlink_cpp.hardlink_to(image) + + with ( + mock.patch.object(fuzz_cpu, "_write_atomic", side_effect=AssertionError("should not write")), + mock.patch.object(fuzz_cpu, "translator_module", side_effect=AssertionError("should not lift")), + ): + for label, argv, frag in ( + ("emit_asm_dir", ["emit", "1", "1", str(existing_dir), str(base / "ok.def")], "directory"), + ("emit_def_dir", ["emit", "1", "1", str(base / "ok.asm"), str(existing_dir)], "directory"), + ("emit_asm_file_parent", ["emit", "1", "1", str(file_parent / "a.asm"), str(base / "ok.def")], "not a directory"), + ("emit_def_ancestor_file", ["emit", "1", "1", str(base / "ok.asm"), str(file_parent / "sub" / "a.def")], "not a directory"), + ("emit_same_path", ["emit", "1", "1", str(base / "same.asm"), str(base / "same.asm")], "distinct"), + ("emit_alias_path", ["emit", "1", "1", str(base / "same.asm"), str(existing_dir / ".." / "same.asm")], "distinct"), + ("emit_hardlink_asm_def", ["emit", "1", "1", str(existing_asm), str(hardlink_def)], "distinct"), + ("translate_out_dir", ["translate", "1", "1", str(image), str(existing_dir)], "directory"), + ("translate_file_parent", ["translate", "1", "1", str(image), str(file_parent / "out.cpp")], "not a directory"), + ("translate_same_image", ["translate", "1", "1", str(image), str(image)], "distinct"), + ("translate_hardlink_image", ["translate", "1", "1", str(image), str(hardlink_cpp)], "distinct"), + ): + with self.subTest(case=label): + self._assert_clean_failure(argv, fragments=(frag,)) + + self.assertEqual(file_parent.read_text(encoding="utf-8"), "keep-parent") + self.assertEqual(existing_asm.read_text(encoding="utf-8"), "keep-asm") + self.assertEqual(image.read_bytes(), b"MZ-input") + self.assertFalse((base / "ok.asm").exists()) + self.assertFalse((base / "ok.def").exists()) + + def test_output_symlink_rejected_before_write(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(b"MZ-input") + out_dir = base / "out" + out_dir.mkdir() + real_target = out_dir / "real.txt" + real_target.write_text("untouched", encoding="utf-8") + live_link = out_dir / "live_link.asm" + dangling_link = out_dir / "dangling_link.cpp" + + try: + live_link.symlink_to(real_target) + dangling_link.symlink_to(out_dir / "missing.cpp") + has_symlinks = True + except OSError as exc: + if getattr(exc, "winerror", None) != 1314: + raise + has_symlinks = False + + with ( + mock.patch.object(fuzz_cpu, "_write_atomic", side_effect=AssertionError("should not write")), + mock.patch.object(fuzz_cpu, "translator_module", side_effect=AssertionError("should not lift")), + ): + if has_symlinks: + self._assert_clean_failure( + ["emit", "1", "1", str(live_link), str(out_dir / "ok.def")], + fragments=("symlink",), + ) + self._assert_clean_failure( + ["translate", "1", "1", str(image), str(dangling_link)], + fragments=("symlink",), + ) + else: + with mock.patch.object(Path, "is_symlink", autospec=True, side_effect=lambda p: p == real_target): + self._assert_clean_failure( + ["emit", "1", "1", str(real_target), str(out_dir / "ok.def")], + fragments=("symlink",), + check_subprocess=False, + ) + self._assert_clean_failure( + ["translate", "1", "1", str(image), str(real_target)], + fragments=("symlink",), + check_subprocess=False, + ) + self.assertEqual(real_target.read_text(encoding="utf-8"), "untouched") + + def test_os_replace_and_staging_failures_preserve_target_and_leave_zero_tmp_files(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + out_dir = base / "out_dir" + out_dir.mkdir() + asm_path = out_dir / "fuzz.asm" + def_path = out_dir / "fuzz.def" + asm_path.write_text("prior-asm", encoding="utf-8") + def_path.write_text("prior-def", encoding="utf-8") + + # 1) os.replace fails on existing target -> target preserved, 0 .tmp files. + def fail_replace(src, _dst): + self.assertTrue(Path(src).is_file()) + raise OSError("simulated replace failure") + + with mock.patch.object(fuzz_cpu.os, "replace", side_effect=fail_replace): + self._assert_clean_failure( + ["emit", "0xA902", "2", str(asm_path), str(def_path)], + fragments=("simulated replace failure",), + check_subprocess=False, + ) + self.assertEqual(asm_path.read_text(encoding="utf-8"), "prior-asm") + self.assertEqual(def_path.read_text(encoding="utf-8"), "prior-def") + self.assertEqual(sorted(p.name for p in out_dir.iterdir()), ["fuzz.asm", "fuzz.def"]) + + # 2) os.replace fails on translate -> prior .cpp preserved, 0 .tmp files. + image = base / "input.dll" + image.write_bytes(b"MZ-input") + cpp_path = out_dir / "lifted.cpp" + cpp_path.write_text("prior-cpp", encoding="utf-8") + fake_mod = types.SimpleNamespace(translate=lambda _img, _names: ("// new\n", {})) + with ( + mock.patch.object(fuzz_cpu, "translator_module", return_value=fake_mod), + mock.patch.object(fuzz_cpu.os, "replace", side_effect=fail_replace), + ): + self._assert_clean_failure( + ["translate", "0xA902", "2", str(image), str(cpp_path)], + fragments=("simulated replace failure",), + check_subprocess=False, + ) + self.assertEqual(cpp_path.read_text(encoding="utf-8"), "prior-cpp") + self.assertEqual(sorted(p.name for p in out_dir.iterdir()), ["fuzz.asm", "fuzz.def", "lifted.cpp"]) + + # 3) Staging failure after .tmp creation -> .tmp unlinked, os.replace not called, target preserved. + real_ntf = fuzz_cpu.tempfile.NamedTemporaryFile + + class FailingWriteHandle: + def __init__(self, inner): + self._inner = inner + self.name = inner.name + + def __enter__(self): + self._inner.__enter__() + return self + + def __exit__(self, exc_type, exc, tb): + return self._inner.__exit__(exc_type, exc, tb) + + def write(self, _data): + raise OSError("simulated staging write failure") + + with ( + mock.patch.object(fuzz_cpu.os, "replace") as replace_mock, + mock.patch.object( + fuzz_cpu.tempfile, + "NamedTemporaryFile", + side_effect=lambda *a, **kw: FailingWriteHandle(real_ntf(*a, **kw)), + ), + ): + self._assert_clean_failure( + ["emit", "0xA902", "2", str(asm_path), str(def_path)], + fragments=("simulated staging write failure",), + check_subprocess=False, + ) + replace_mock.assert_not_called() + self.assertEqual(asm_path.read_text(encoding="utf-8"), "prior-asm") + self.assertEqual(sorted(p.name for p in out_dir.iterdir()), ["fuzz.asm", "fuzz.def", "lifted.cpp"]) + + def test_argparse_errors_py314_safe(self) -> None: + for argv, frags in ( + ([], ("required",)), + (["emit"], ("required",)), + (["emit", "0x1", "2", "a.asm", "a.def", "--area", "bogus"], ("invalid choice",)), + (["translate", "bad_seed", "1", "a.dll", "a.cpp"], ("invalid",)), + (["check", "1", "1", "n.dll", "l.dll", "o.dll", "--bogus-flag"], ("unrecognized",)), + ): + with self.subTest(argv=argv): + self._assert_clean_failure(argv, expected_code=None, fragments=frags) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/fuzz_cpu.py b/tools/fuzz_cpu.py index 36823e02e..99a49f06a 100644 --- a/tools/fuzz_cpu.py +++ b/tools/fuzz_cpu.py @@ -3,13 +3,21 @@ import argparse import ctypes from dataclasses import dataclass, field +import os from pathlib import Path import random import re import struct import sys +import tempfile import types +try: + import pefile + _PE_ERRORS: tuple[type[BaseException], ...] = (pefile.PEFormatError,) +except ImportError: + _PE_ERRORS = () + WIDTHS = { "b": ("al", "dl", "BYTE PTR", 1), "w": ("ax", "dx", "WORD PTR", 2), @@ -2037,13 +2045,75 @@ def buffer_text(data, start, stop): return " ".join(f"{byte:02x}" for byte in data[start:stop]) +def _validate_count(count: int) -> None: + if count < 1: + raise ValueError(f"count must be >= 1, got {count}") + + +def _validate_input_file(path: Path, label: str) -> None: + if path.is_dir(): + raise IsADirectoryError(f"{label} path is a directory: {path}") + if not path.is_file(): + raise FileNotFoundError(f"{label} file not found: {path}") + + +def _validate_output_path(path: Path, label: str) -> None: + if path.is_symlink(): + raise ValueError(f"{label} output path must not be a symlink: {path}") + if path.is_dir(): + raise IsADirectoryError(f"{label} output path is a directory: {path}") + for parent in path.parents: + if parent.is_file() or ((parent.exists() or parent.is_symlink()) and not parent.is_dir()): + raise NotADirectoryError(f"{label} output parent is not a directory: {parent}") + + +def _validate_distinct_paths(left: Path, right: Path, message: str) -> None: + left_resolved = left.resolve() + right_resolved = right.resolve() + if ( + left_resolved == right_resolved + or left_resolved in right_resolved.parents + or right_resolved in left_resolved.parents + or (left.exists() and right.exists() and left.samefile(right)) + ): + raise ValueError(message) + + +def _write_atomic(path: Path, text: str) -> None: + """Write UTF-8 text to a sibling temp file and atomically replace path, unlinking temps on failure.""" + path.parent.mkdir(parents=True, exist_ok=True) + tmp_path: Path | None = None + try: + with tempfile.NamedTemporaryFile( + mode="w", + encoding="utf-8", + newline="\n", + dir=path.parent, + prefix=f".{path.stem}.", + suffix=".tmp", + delete=False, + ) as handle: + tmp_path = Path(handle.name) + handle.write(text) + os.replace(tmp_path, path) + except BaseException: + if tmp_path is not None: + tmp_path.unlink(missing_ok=True) + raise + + def run_check(seed, count, native, lifted, o2, only=None, input_index=None, area="leaf", mutant=None): + _validate_count(count) + for path, label in ((native, "native"), (lifted, "lifted"), (o2, "o2")): + _validate_input_file(Path(path), label) + if mutant is not None: + _validate_input_file(Path(mutant), "mutant") if first_difference(b"\x01\x02", b"\x01\x02") is not None: raise SystemExit("comparator self-test failed on equal bytes") if first_difference(b"\x01\x02", b"\x01\x03") != 1: raise SystemExit("comparator self-test failed on a changed byte") if mutant is not None and area not in MUTANTS: - raise SystemExit(f"no planted translator fault for --area {area}") + raise ValueError(f"no planted translator fault for --area {area}") functions = AREAS[area][0](seed, count) controls = [function for function in functions if function.refused] @@ -2069,8 +2139,6 @@ def run_check(seed, count, native, lifted, o2, only=None, input_index=None, area loaded.append((library, prefix)) native_library, lifted_library, o2_library = (item[0] for item in loaded[:3]) - if count <= 0: - raise SystemExit("CPU_FUZZ_FUNCTIONS must be positive") selected = [function for function in functions if only is None or function.name == only] def function_inputs(function): @@ -2155,14 +2223,20 @@ def function_inputs(function): def emit(seed, count, asm_path, def_path, area="leaf"): + _validate_count(count) + asm_out = Path(asm_path) + def_out = Path(def_path) + _validate_output_path(asm_out, "asm") + _validate_output_path(def_out, "definition") + _validate_distinct_paths(asm_out, def_out, f"asm and definition outputs must be distinct: {asm_out}") generator, library = AREAS[area] functions = generator(seed, count) body = "\n\n".join(function.asm() for function in functions) asm = ("EXTERN __ImageBase:BYTE\n" if "__ImageBase" in body else "") + ".code\n\n" + body + "\n\nEND\n" definition = (f"LIBRARY {library}\nEXPORTS\n" + "".join(f" {function.name}\n" for function in functions if function.export)) - Path(asm_path).write_text(asm, encoding="utf-8") - Path(def_path).write_text(definition, encoding="utf-8") + _write_atomic(asm_out, asm) + _write_atomic(def_out, definition) def plant_reload_shift(cpu_switch_aot, image, functions): @@ -2364,33 +2438,39 @@ def plant_set_reset_swap(cpu_switch_aot, image, functions): def translate(seed, count, image, output, area="leaf", mutant=False): + _validate_count(count) + image_path = Path(image) + out_path = Path(output) + _validate_input_file(image_path, "image") + _validate_output_path(out_path, "output") + _validate_distinct_paths(out_path, image_path, f"output path must be distinct from input image: {out_path}") + if mutant and area not in MUTANTS: + raise ValueError(f"no planted translator fault for --area {area}") lifter = translator_module(area) functions = AREAS[area][0](seed, count) if mutant: - if area not in MUTANTS: - raise SystemExit(f"no planted translator fault for --area {area}") MUTANTS[area][1](lifter, image, functions) # Negative controls stay in the image for the check to translate on their own. functions = [function for function in functions if not function.refused and function.export and function.host_features is None] names = [export_name(function) for function in functions] try: - source, _ = lifter.translate(Path(image), names) + source, _ = lifter.translate(image_path, names) except ValueError as error: print(f"seed={seed:#x} functions={count}: {error}", file=sys.stderr) for function in functions: try: - lifter.translate(Path(image), [export_name(function)]) + lifter.translate(image_path, [export_name(function)]) except ValueError as inner: print(f"refused {function.name}: {inner}", file=sys.stderr) print(function.asm(), file=sys.stderr) break return 1 - Path(output).write_text(source, encoding="utf-8") + _write_atomic(out_path, source) return 0 -def main(argv=None): +def main(argv=None) -> int: parser = argparse.ArgumentParser(description=__doc__) commands = parser.add_subparsers(dest="command", required=True) emit_parser = commands.add_parser("emit") @@ -2420,13 +2500,17 @@ def main(argv=None): check_parser.add_argument("--mutant", type=Path, help="a translation with the planted fault, which must mismatch") args = parser.parse_args(argv) - if args.command == "emit": - emit(args.seed, args.count, args.asm, args.definition, args.area) - return 0 - if args.command == "translate": - return translate(args.seed, args.count, args.image, args.output, args.area, args.mutant) - return run_check(args.seed, args.count, args.native, args.lifted, args.o2, args.only, args.input_index, - args.area, args.mutant) + try: + if args.command == "emit": + emit(args.seed, args.count, args.asm, args.definition, args.area) + return 0 + if args.command == "translate": + return translate(args.seed, args.count, args.image, args.output, args.area, args.mutant) + return run_check(args.seed, args.count, args.native, args.lifted, args.o2, args.only, args.input_index, + args.area, args.mutant) + except (OSError, ValueError, struct.error, KeyError, *_PE_ERRORS) as error: + print(f"error: {error}", file=sys.stderr) + return 1 if __name__ == "__main__": From 546d881be2e14097fd086c52d711a3173d605471 Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Thu, 26 Nov 2026 05:10:07 +0200 Subject: [PATCH 106/240] shader: validate spirv_ballot_extract inputs/structure and add unit suite (#2692) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 3 + tests/spirv_ballot_extract_check.py | 227 ++++++++++++++++++++++++++++ tools/spirv_ballot_extract.py | 6 + 3 files changed, 236 insertions(+) create mode 100644 tests/spirv_ballot_extract_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index d7880636f..7e7c9845a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4716,6 +4716,9 @@ if(EXISTS "${INTAKE_PYTHON}") endforeach() add_test(NAME spirv_window_checks COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/spirv_sampler_split_check.py") + add_test(NAME shader_spirv_ballot_extract_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/spirv_ballot_extract_check.py") + set_tests_properties(shader_spirv_ballot_extract_check PROPERTIES TIMEOUT 60) add_test(NAME spirv_address_window_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/spirv_address_window_check.py") add_test(NAME shader_spirv_address_window_cli_check COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/spirv_ballot_extract_check.py b/tests/spirv_ballot_extract_check.py new file mode 100644 index 000000000..6ef84046a --- /dev/null +++ b/tests/spirv_ballot_extract_check.py @@ -0,0 +1,227 @@ +#!/usr/bin/env python3 +"""Pure-Python unit and mutation suite for tools/spirv_ballot_extract.py.""" + +import importlib.util +from pathlib import Path +import sys +from tempfile import TemporaryDirectory +import unittest + +ROOT = Path(__file__).resolve().parent.parent +TOOL = ROOT / "tools" / "spirv_ballot_extract.py" +BALLOT_SPVASM = ROOT / "tests" / "spirv_window" / "ballot.spvasm" +sys.path.insert(0, str(ROOT / "tools")) +import spirv_ballot_extract as sbe # noqa: E402 + + +EXTRACT_MODULE = BALLOT_SPVASM.read_text(encoding="utf-8") + +FIND_MODULE = """OpCapability Shader +OpCapability GroupNonUniformBallot +OpMemoryModel Logical GLSL450 +%uint = OpTypeInt 32 0 +%void = OpTypeVoid +%fn = OpTypeFunction %void +%scope = OpConstant %uint 0x3 +%workgroup = OpConstant %uint 2 +%main = OpFunction %void None %fn +%entry = OpLabel +%lsb = OpGroupNonUniformBallotFindLSB %uint %scope %mask +OpReturn +OpFunctionEnd +""" + +COMBINED_MODULE = """OpCapability Shader +OpCapability GroupNonUniformBallot +OpMemoryModel Logical GLSL450 +%uint = OpTypeInt 32 0 +%bool = OpTypeBool +%void = OpTypeVoid +%fn = OpTypeFunction %void +%scope = OpConstant %uint 3 +%main = OpFunction %void None %fn +%entry = OpLabel +%bit = OpGroupNonUniformBallotBitExtract %bool %scope %mask %lane ; trailing comment +%lsb = OpGroupNonUniformBallotFindLSB %uint %scope %mask +OpReturn +OpFunctionEnd +""" + + +def _load_module(path: Path, name: str): + spec = importlib.util.spec_from_file_location(name, path) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +class SpirvBallotExtractTest(unittest.TestCase): + def test_passthrough_preserves_input_verbatim(self) -> None: + plain = "OpCapability Shader\nOpMemoryModel Logical GLSL450\n%main = OpFunction %void None %fn\n" + for sample in ("", plain, "%x2w_ballot_unused = OpConstant %uint 0\n"): + self.assertEqual(sbe.lower_ballot_extract(sample), sample) + + # Unmatched FindLSB signatures (e.g. wrong result type) pass through untouched. + wrong_find = FIND_MODULE.replace( + "%lsb = OpGroupNonUniformBallotFindLSB %uint %scope %mask", + "%lsb = OpGroupNonUniformBallotFindLSB %bool %scope %mask", + ) + self.assertEqual(sbe.lower_ballot_extract(wrong_find), wrong_find) + + def test_ballot_bit_extract_lowering(self) -> None: + lowered = sbe.lower_ballot_extract(EXTRACT_MODULE) + lines = lowered.splitlines() + self.assertNotIn("OpGroupNonUniformBallotBitExtract", lowered) + self.assertNotIn("OpExtInstImport", lowered) + for c in (0, 1, 5, 31): + self.assertIn(f"%x2w_ballot_c{c} = OpConstant %uint {c}", lines) + for c in (32, 64, 96): + self.assertNotIn(f"%x2w_ballot_c{c}", lowered) + fn_idx = lines.index("%main = OpFunction %void None %fn") + self.assertEqual( + lines[fn_idx - 4:fn_idx], + [f"%x2w_ballot_c{c} = OpConstant %uint {c}" for c in (0, 1, 5, 31)], + ) + self.assertIn("%x2w_ballot_bit_word_index = OpShiftRightLogical %uint %i %x2w_ballot_c5", lines) + self.assertIn("%x2w_ballot_bit_word = OpVectorExtractDynamic %uint %mask %x2w_ballot_bit_word_index", lines) + self.assertIn("%x2w_ballot_bit_bit = OpBitwiseAnd %uint %i %x2w_ballot_c31", lines) + self.assertIn("%x2w_ballot_bit_shifted = OpShiftRightLogical %uint %x2w_ballot_bit_word %x2w_ballot_bit_bit", lines) + self.assertIn("%x2w_ballot_bit_low = OpBitwiseAnd %uint %x2w_ballot_bit_shifted %x2w_ballot_c1", lines) + self.assertIn("%bit = OpINotEqual %bool %x2w_ballot_bit_low %x2w_ballot_c0", lines) + + def test_ballot_find_lsb_injects_glsl_import(self) -> None: + lowered = sbe.lower_ballot_extract(FIND_MODULE) + lines = lowered.splitlines() + self.assertNotIn("OpGroupNonUniformBallotFindLSB", lowered) + self.assertEqual(lines.count('%x2w_ballot_glsl = OpExtInstImport "GLSL.std.450"'), 1) + mm_idx = lines.index("OpMemoryModel Logical GLSL450") + self.assertEqual(lines[mm_idx - 1], '%x2w_ballot_glsl = OpExtInstImport "GLSL.std.450"') + for c in (31, 32, 64, 96): + self.assertIn(f"%x2w_ballot_c{c} = OpConstant %uint {c}", lines) + for c in (0, 1, 5): + self.assertNotIn(f"%x2w_ballot_c{c} = OpConstant", lowered) + self.assertIn("%x2w_ballot_lsb_w0 = OpCompositeExtract %uint %mask 0", lines) + self.assertIn("%x2w_ballot_lsb_c0 = OpExtInst %uint %x2w_ballot_glsl FindILsb %x2w_ballot_lsb_w0", lines) + self.assertIn("%x2w_ballot_lsb_m3 = OpShiftRightArithmetic %uint %x2w_ballot_lsb_l3 %x2w_ballot_c31", lines) + self.assertIn("%x2w_ballot_lsb_a3 = OpIAdd %uint %x2w_ballot_lsb_l3 %x2w_ballot_c96", lines) + self.assertIn("%lsb = OpExtInst %uint %x2w_ballot_glsl UMin %x2w_ballot_lsb_c0 %x2w_ballot_lsb_u1", lines) + + def test_ballot_find_lsb_reuses_existing_glsl_import(self) -> None: + with_import = FIND_MODULE.replace( + "OpMemoryModel Logical GLSL450\n", + '%existing_glsl = OpExtInstImport "GLSL.std.450"\n', + ) + lowered = sbe.lower_ballot_extract(with_import) + lines = lowered.splitlines() + self.assertEqual(lowered.count("OpExtInstImport"), 1) + self.assertNotIn("%x2w_ballot_glsl", lowered) + self.assertIn("%x2w_ballot_lsb_c0 = OpExtInst %uint %existing_glsl FindILsb %x2w_ballot_lsb_w0", lines) + self.assertIn("%lsb = OpExtInst %uint %existing_glsl UMin %x2w_ballot_lsb_c0 %x2w_ballot_lsb_u1", lines) + + def test_combined_extract_and_find_lsb(self) -> None: + lowered = sbe.lower_ballot_extract(COMBINED_MODULE) + lines = lowered.splitlines() + self.assertNotIn("OpGroupNonUniformBallotBitExtract", lowered) + self.assertNotIn("OpGroupNonUniformBallotFindLSB", lowered) + fn_idx = lines.index("%main = OpFunction %void None %fn") + self.assertEqual( + lines[fn_idx - 7:fn_idx], + [f"%x2w_ballot_c{c} = OpConstant %uint {c}" for c in (0, 1, 5, 31, 32, 64, 96)], + ) + self.assertIn("%bit = OpINotEqual %bool %x2w_ballot_bit_low %x2w_ballot_c0", lines) + self.assertIn("%lsb = OpExtInst %uint %x2w_ballot_glsl UMin %x2w_ballot_lsb_c0 %x2w_ballot_lsb_u1", lines) + + def test_negative_controls(self) -> None: + for bad in (None, b"OpCapability Shader", 42, ["OpMemoryModel Logical GLSL450"]): + with self.subTest(bad=bad): + with self.assertRaisesRegex(TypeError, "assembly must be a str"): + sbe.lower_ballot_extract(bad) + + reserved = EXTRACT_MODULE.replace("%one", "%x2w_ballot_taken") + with self.assertRaisesRegex(ValueError, "Reserved ballot lowering ID already in use"): + sbe.lower_ballot_extract(reserved) + + for bad_scope in ("%workgroup", "%missing", "%main"): + with self.subTest(bad_scope=bad_scope): + probe = FIND_MODULE.replace("%scope %mask", f"{bad_scope} %mask") + with self.assertRaisesRegex(ValueError, "Subgroup scope constant"): + sbe.lower_ballot_extract(probe) + + no_fn_extract = EXTRACT_MODULE.replace("%main = OpFunction %void None %fn", "%main_alt = OpLabel") + with self.assertRaisesRegex(ValueError, "OpFunction"): + sbe.lower_ballot_extract(no_fn_extract) + + no_fn_find = FIND_MODULE.replace("%main = OpFunction %void None %fn", "%main_alt = OpLabel") + with self.assertRaisesRegex(ValueError, "OpFunction"): + sbe.lower_ballot_extract(no_fn_find) + + no_mm_find = FIND_MODULE.replace("OpMemoryModel Logical GLSL450\n", "") + with self.assertRaisesRegex(ValueError, "OpMemoryModel"): + sbe.lower_ballot_extract(no_mm_find) + + def test_fast_temp_mutations_killed(self) -> None: + original_src = TOOL.read_text(encoding="utf-8") + mutations = ( + ( + "drop_str_check", + " if not isinstance(assembly, str):", + " if False:", + lambda mod: mod.lower_ballot_extract(["OpCapability Shader"]), + TypeError, + "assembly must be a str", + ), + ( + "drop_reserved_id_check", + ' if "%x2w_ballot_" in assembly:', + " if False:", + lambda mod: mod.lower_ballot_extract(EXTRACT_MODULE.replace("%one", "%x2w_ballot_taken")), + ValueError, + "Reserved ballot lowering ID already in use", + ), + ( + "wrong_subgroup_scope", + "SUBGROUP_SCOPE = 3", + "SUBGROUP_SCOPE = 2", + lambda mod: mod.lower_ballot_extract(FIND_MODULE.replace("%scope %mask", "%workgroup %mask")), + ValueError, + "Subgroup scope constant", + ), + ( + "drop_opfunction_check", + " if not declared:", + " if False:", + lambda mod: mod.lower_ballot_extract( + EXTRACT_MODULE.replace("%main = OpFunction %void None %fn", "%main_alt = OpLabel") + ), + ValueError, + "OpFunction", + ), + ( + "drop_opmemorymodel_check", + " if import_needed and not imported:", + " if False:", + lambda mod: mod.lower_ballot_extract(FIND_MODULE.replace("OpMemoryModel Logical GLSL450\n", "")), + ValueError, + "OpMemoryModel", + ), + ) + with TemporaryDirectory() as folder: + root = Path(folder) + for label, old, new, trigger, expected_exc, expected_msg in mutations: + mutated_src = original_src.replace(old, new, 1) + self.assertNotEqual(mutated_src, original_src, label) + mut_path = root / f"mut_{label}.py" + mut_path.write_text(mutated_src, encoding="utf-8") + mod = _load_module(mut_path, f"mut_{label}") + try: + trigger(mod) + except expected_exc as exc: + if expected_msg in str(exc): + raise AssertionError(f"mutation {label} was not killed: {exc}") + except Exception: + pass + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/tools/spirv_ballot_extract.py b/tools/spirv_ballot_extract.py index 166bff52a..55afb3603 100644 --- a/tools/spirv_ballot_extract.py +++ b/tools/spirv_ballot_extract.py @@ -32,6 +32,8 @@ def _find_lsb(dst, ballot, glsl): def lower_ballot_extract(assembly): + if not isinstance(assembly, str): + raise TypeError("assembly must be a str") extracts = "OpGroupNonUniformBallotBitExtract" in assembly finds = any(FIND_LSB.fullmatch(line) for line in assembly.splitlines()) if not extracts and not finds: @@ -73,4 +75,8 @@ def lower_ballot_extract(assembly): f"{tmp}low = OpBitwiseAnd %uint {tmp}shifted %x2w_ballot_c1", f"{dst} = OpINotEqual %bool {tmp}low %x2w_ballot_c0", ]) + if not declared: + raise ValueError("Ballot lowering needs an OpFunction declaration") + if import_needed and not imported: + raise ValueError("Ballot find-lsb lowering needs an OpMemoryModel instruction") return "\n".join(lines) + "\n" From 46779a4d95ad5dd72794d572ef4c03fa941fd364 Mon Sep 17 00:00:00 2001 From: Louis <59670693+louisdibiasi@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:12:00 -0500 Subject: [PATCH 107/240] tooling: accept absolute startup build directories (#2700) * tooling: accept absolute startup build directories * tooling: copy startup DLLs from literal paths --- docs/startup-runtime.md | 2 ++ tests/startup_run_ps1_check.py | 22 ++++++++++++++++++---- tools/startup/run.ps1 | 3 ++- 3 files changed, 22 insertions(+), 5 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 3c8e79aa9..82e43def4 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -785,6 +785,8 @@ are not copied. Keep using the package root as `-DataDir`, then run the staged e ``` `run.ps1` copies the stand-ins next to the executable and starts `tools/startup/debug_launch.py`. +Use `-BuildDir` to select their build directory; relative paths are relative to the repository root, +and absolute paths are used as supplied. The default is `out/build/release`. It runs the debugger with `out/pe-env/Scripts/python.exe` when that environment exists, because `-HostCpu` needs `iced-x86` from `requirements-dev.txt`; otherwise it falls back to `python` from `PATH`. diff --git a/tests/startup_run_ps1_check.py b/tests/startup_run_ps1_check.py index 0e9d0dc2f..775d1dc3c 100644 --- a/tests/startup_run_ps1_check.py +++ b/tests/startup_run_ps1_check.py @@ -123,7 +123,7 @@ def alive(pid): def run_case(shell, script, code, work, translate=False, switches=(), passed=(), fake_user_env=False, - early_exit=False, trace_api_env=None): + early_exit=False, trace_api_env=None, absolute_build=False, missing_build=False): """Run one copy of the script on a stub that exits with `code`; return what is wrong. `switches` are extra run.ps1 switches and `passed` the debugger arguments they must add. @@ -137,9 +137,10 @@ def run_case(shell, script, code, work, translate=False, switches=(), passed=(), (startup / "run.ps1").write_bytes(script.encode("utf-8")) (startup / "debug_launch.py").write_text(STUB.format(code=code, early_exit=early_exit), encoding="utf-8") (startup / "gfx2hlsl.py").write_text(WATCH_STUB.format(early_exit=early_exit), encoding="utf-8") - (root / "bld").mkdir() + build = root / ("build [with spaces]" if absolute_build else "bld") + build.mkdir() for dll in DLLS: # the stand-ins the script copies next to the executable - (root / "bld" / f"{dll}.dll").write_bytes(b"") + (build / f"{dll}.dll").write_bytes(b"") exe, data, log = root / "run" / "t.exe", root / "data", root / "log" exe.parent.mkdir() exe.write_bytes(b"") @@ -157,8 +158,12 @@ def run_case(shell, script, code, work, translate=False, switches=(), passed=(), # In this tree run.ps1 finds `python` through PATH. This interpreter's directory # goes first so the stub runs under the Python that runs this check. env["PATH"] = os.path.dirname(sys.executable) + os.pathsep + env.get("PATH", "") + build_arg = str(build) if absolute_build else "bld" + if missing_build: + build_arg = str(root / "missing build") command = [shell, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(startup / "run.ps1"), - "-Exe", str(exe), "-DataDir", str(data), "-LogDir", str(log), "-BuildDir", "bld", + "-Exe", str(exe), "-DataDir", str(data), "-LogDir", str(log), + "-BuildDir", build_arg, "-Seconds", "9", "-MemoryGiB", "3", "-ContinueAsserts", "4", *switches] if translate: command += ["-Render", "-Translate", "-ShaderCache", "cache"] @@ -176,6 +181,9 @@ def run_case(shell, script, code, work, translate=False, switches=(), passed=(), printed = [line.strip() for line in stdout if line.strip()] error_text = stderr.read().strip() found = [] + for dll in DLLS: + if not (exe.parent / f"{dll}.dll").is_file(): + found.append(f"stand-in {dll}.dll was not copied") if out.returncode != code: found.append(f"stub debugger exited {code}, run.ps1 exited {out.returncode}") want_output = STUB_LINES[:HEAD_LINES] @@ -219,6 +227,9 @@ def run_problems(shell, script, work, first_only): found += run_case(shell, script, code, work) if found and first_only: return found + found += run_case(shell, script, 7, work, absolute_build=True) + if found and first_only: + return found found += run_case(shell, script, 0, work, switches=["-FakeUser"]) found += run_case(shell, script, 0, work, fake_user_env=True) if found and first_only: @@ -308,6 +319,9 @@ def shell_failures(shell, script, tmp): if mutant is None or not run_problems(shell, mutant, tmp, True): failures.append(f"{name}: mutant '{label}' was not detected") if shell: + missing = run_case(shell, script, 7, tmp, missing_build=True) + if not any("debugger [argv" in item and "was None" in item for item in missing): + failures.append(f"{name}: missing build directory did not prevent debugger startup") # Expire the live fixture tree after HasExited has been read. The launcher's # own taskkill then hits the missing PID and writes native stderr. kill = f"& {STOP} 2>&1 | Out-Null" diff --git a/tools/startup/run.ps1 b/tools/startup/run.ps1 index 8132b595e..370fac933 100644 --- a/tools/startup/run.ps1 +++ b/tools/startup/run.ps1 @@ -34,8 +34,9 @@ param( $ErrorActionPreference = "Stop" $repo = Resolve-Path (Join-Path $PSScriptRoot "..\..") $runDir = Split-Path -Parent (Resolve-Path $Exe) +$buildRoot = if ([System.IO.Path]::IsPathRooted($BuildDir)) { $BuildDir } else { Join-Path $repo $BuildDir } foreach ($dll in "xmem", "d3d12_xs", "AcpHal", "XCRDAPI", "chad", "xapu", "xg_xs", "GameInput") { - Copy-Item (Join-Path $repo "$BuildDir\$dll.dll") $runDir -Force + Copy-Item -LiteralPath (Join-Path $buildRoot "$dll.dll") -Destination $runDir -Force } $env:X2W_AUDIO_PERMISSIVE = "1"; $env:X2W_D3D12_DEVICE_NOOP = "1"; $env:X2W_D3D12_LIST_NOOP = "1" $env:X2W_D3D12_PERMISSIVE = "1"; $env:X2W_XMEM_PERMISSIVE = "1"; $env:X2W_RUNTIME_PROXY = "1" From ede9e4d36e360d1a4beb8d34b0e2a685cbe52820 Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Thu, 26 Nov 2026 05:12:58 +0200 Subject: [PATCH 108/240] cpu: lift 16/32/64-bit MOVBE load and store leaf functions to C++ (#2689) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 25 ++ tests/cpu/movbe_aot.asm | 227 +++++++++++++ tests/cpu/movbe_aot.def | 18 + tests/cpu/movbe_aot_check.py | 643 +++++++++++++++++++++++++++++++++++ tools/cpu_movbe_aot.py | 630 ++++++++++++++++++++++++++++++++++ 5 files changed, 1543 insertions(+) create mode 100644 tests/cpu/movbe_aot.asm create mode 100644 tests/cpu/movbe_aot.def create mode 100644 tests/cpu/movbe_aot_check.py create mode 100644 tools/cpu_movbe_aot.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 7e7c9845a..facb842a5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -6867,6 +6867,31 @@ if(EXISTS "${INTAKE_PYTHON}") check "$" "$" "$" "$" "$") set_tests_properties(cpu_aot_movbe PROPERTIES SKIP_RETURN_CODE 77) + + # cpu_aot_movbe_dedicated + set(cpu_movbe_aot_exports + "op_movbe_load16,op_movbe_load16_disp,op_movbe_load32,op_movbe_load32_disp," + "op_movbe_load64,op_movbe_load64_disp," + "op_movbe_store16,op_movbe_store16_disp,op_movbe_store32,op_movbe_store32_disp," + "op_movbe_store64,op_movbe_store64_disp," + "op_movbe_flags_cf_zf_of_pf,op_movbe_flags_sf_of_pf,op_movbe_flags_all_clear," + "op_r8_source_then_store,op_movbe_discarded_read") + string(CONCAT cpu_movbe_aot_exports ${cpu_movbe_aot_exports}) + foreach(variant IN ITEMS original altered) + cpu_asm_fixture(cpu_movbe_aot_${variant} movbe_aot) + cpu_translation(cpu_movbe_aot_${variant} cpu_movbe_aot "${cpu_movbe_aot_exports}") + endforeach() + target_compile_definitions(cpu_movbe_aot_altered PRIVATE ALTER_MOVBE) + add_test(NAME cpu_aot_movbe_dedicated COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/cpu/movbe_aot_check.py" + "$" + "$" + "$" + "$" + "${CMAKE_CXX_COMPILER}") + set_tests_properties(cpu_aot_movbe_dedicated PROPERTIES + SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/cpu_aot_movbe_dedicated.txt") cpu_asm_fixture(cpu_bmi1 bmi1) set(bmi1_fixture "${CMAKE_CURRENT_BINARY_DIR}/cpu_bmi1_lifted.cpp") add_custom_command(OUTPUT "${bmi1_fixture}" diff --git a/tests/cpu/movbe_aot.asm b/tests/cpu/movbe_aot.asm new file mode 100644 index 000000000..0c7eaa2ce --- /dev/null +++ b/tests/cpu/movbe_aot.asm @@ -0,0 +1,227 @@ +; coverage: record cpu_aot_movbe_dedicated +; Source-built MASM fixture for all 6 MOVBE forms (16/32/64-bit loads and stores) +; from docs/coverage/x64_zen2.tsv group MOVBE: [rcx|rdx|r8 (+small_disp)] loads, +; [r8 (+disp)] stores, 16-bit upper-bit preservation, 32-bit zero-extension, +; zero flag modification, [r8] source-then-store, and discarded faulting m64 read. +.code + +PACK_CF_ZF_SF_OF_PF MACRO + setb r9b + sete r10b + sets r11b + seto byte ptr [r8+16] + setp byte ptr [r8+20] + movzx r9d, r9b + movzx r10d, r10b + shl r10d, 1 + or r9d, r10d + movzx r11d, r11b + shl r11d, 2 + or r9d, r11d + movzx r10d, byte ptr [r8+16] + shl r10d, 3 + or r9d, r10d + movzx r10d, byte ptr [r8+20] + shl r10d, 4 + or r9d, r10d + mov dword ptr [r8+16], r9d +ENDM + +; --- Loads (16-bit preserves [63:16], 32-bit zero-extends [63:32], 64-bit full) --- + +op_movbe_load16 PROC FRAME + .endprolog + mov rax, rdx +IFDEF ALTER_MOVBE + mov ax, word ptr [rcx] +ELSE + movbe ax, word ptr [rcx] +ENDIF + ret +op_movbe_load16 ENDP + +op_movbe_load16_disp PROC FRAME + .endprolog + mov r9, rdx +IFDEF ALTER_MOVBE + movbe r9w, word ptr [rcx+1] +ELSE + movbe r9w, word ptr [rcx+3] +ENDIF + mov rax, r9 + ret +op_movbe_load16_disp ENDP + +op_movbe_load32 PROC FRAME + .endprolog + mov rax, -1 +IFDEF ALTER_MOVBE + mov eax, dword ptr [rcx] +ELSE + movbe eax, dword ptr [rcx] +ENDIF + ret +op_movbe_load32 ENDP + +op_movbe_load32_disp PROC FRAME + .endprolog + mov rax, -1 +IFDEF ALTER_MOVBE + movbe r10d, dword ptr [rdx+1] +ELSE + movbe r10d, dword ptr [rdx+5] +ENDIF + mov rax, r10 + ret +op_movbe_load32_disp ENDP + +op_movbe_load64 PROC FRAME + .endprolog +IFDEF ALTER_MOVBE + mov rax, qword ptr [rcx] +ELSE + movbe rax, qword ptr [rcx] +ENDIF + ret +op_movbe_load64 ENDP + +op_movbe_load64_disp PROC FRAME + .endprolog +IFDEF ALTER_MOVBE + movbe r11, qword ptr [rdx+4] +ELSE + movbe r11, qword ptr [rdx+8] +ENDIF + mov rax, r11 + ret +op_movbe_load64_disp ENDP + +; --- Stores strictly to [r8] or [r8+disp] --- + +op_movbe_store16 PROC FRAME + .endprolog +IFDEF ALTER_MOVBE + mov word ptr [r8], dx +ELSE + movbe word ptr [r8], dx +ENDIF + mov rax, rdx + ret +op_movbe_store16 ENDP + +op_movbe_store16_disp PROC FRAME + .endprolog +IFDEF ALTER_MOVBE + movbe word ptr [r8+4], dx +ELSE + movbe word ptr [r8+2], dx +ENDIF + mov rax, rdx + ret +op_movbe_store16_disp ENDP + +op_movbe_store32 PROC FRAME + .endprolog +IFDEF ALTER_MOVBE + mov dword ptr [r8], edx +ELSE + movbe dword ptr [r8], edx +ENDIF + mov eax, edx + ret +op_movbe_store32 ENDP + +op_movbe_store32_disp PROC FRAME + .endprolog +IFDEF ALTER_MOVBE + movbe dword ptr [r8+8], edx +ELSE + movbe dword ptr [r8+4], edx +ENDIF + mov eax, edx + ret +op_movbe_store32_disp ENDP + +op_movbe_store64 PROC FRAME + .endprolog +IFDEF ALTER_MOVBE + mov qword ptr [r8], rdx +ELSE + movbe qword ptr [r8], rdx +ENDIF + mov rax, rdx + ret +op_movbe_store64 ENDP + +op_movbe_store64_disp PROC FRAME + .endprolog +IFDEF ALTER_MOVBE + movbe qword ptr [r8+16], rdx +ELSE + movbe qword ptr [r8+8], rdx +ENDIF + mov rax, rdx + ret +op_movbe_store64_disp ENDP + +; --- Flag preservation checks (PACK_CF_ZF_SF_OF_PF -> dword ptr [r8+16]) --- + +op_movbe_flags_cf_zf_of_pf PROC FRAME + .endprolog + mov r9d, 80000000h + shl r9d, 1 + movbe eax, dword ptr [rcx] + movbe dword ptr [r8], eax + mov r10d, 0 + mov r11d, 0 + PACK_CF_ZF_SF_OF_PF + ret +op_movbe_flags_cf_zf_of_pf ENDP + +op_movbe_flags_sf_of_pf PROC FRAME + .endprolog + mov r9d, 40000000h + shl r9d, 1 + movbe rax, qword ptr [rcx] + movbe qword ptr [r8+8], rax + mov r10d, 0 + mov r11d, 0 + PACK_CF_ZF_SF_OF_PF + ret +op_movbe_flags_sf_of_pf ENDP + +op_movbe_flags_all_clear PROC FRAME + .endprolog + mov r9d, 0 + or r9d, 1 + mov rax, -1 + movbe ax, word ptr [rcx] + movbe word ptr [r8], ax + mov r10d, 0 + mov r11d, 0 + PACK_CF_ZF_SF_OF_PF + ret +op_movbe_flags_all_clear ENDP + +; --- [r8] source-then-store and discarded faulting m64 read --- + +op_r8_source_then_store PROC FRAME + .endprolog + mov r11, rdx + movbe r9, qword ptr [r8] + movbe r10d, dword ptr [rcx] + movbe r11w, word ptr [rdx] + movbe qword ptr [r8+8], r9 + movbe dword ptr [r8], r10d + mov rax, r11 + ret +op_r8_source_then_store ENDP + +op_movbe_discarded_read PROC FRAME + .endprolog + movbe r9, qword ptr [rdx] + mov rax, rcx + ret +op_movbe_discarded_read ENDP + +END diff --git a/tests/cpu/movbe_aot.def b/tests/cpu/movbe_aot.def new file mode 100644 index 000000000..4dc37d6e8 --- /dev/null +++ b/tests/cpu/movbe_aot.def @@ -0,0 +1,18 @@ +EXPORTS + op_movbe_load16 + op_movbe_load16_disp + op_movbe_load32 + op_movbe_load32_disp + op_movbe_load64 + op_movbe_load64_disp + op_movbe_store16 + op_movbe_store16_disp + op_movbe_store32 + op_movbe_store32_disp + op_movbe_store64 + op_movbe_store64_disp + op_movbe_flags_cf_zf_of_pf + op_movbe_flags_sf_of_pf + op_movbe_flags_all_clear + op_r8_source_then_store + op_movbe_discarded_read diff --git a/tests/cpu/movbe_aot_check.py b/tests/cpu/movbe_aot_check.py new file mode 100644 index 000000000..d62d31edc --- /dev/null +++ b/tests/cpu/movbe_aot_check.py @@ -0,0 +1,643 @@ +"""Differential, /O2, flag-preservation, mutant, and rejection checks for cpu_movbe_aot.""" + +import ctypes +import os +from pathlib import Path +import random +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory + +from iced_x86 import Code, Decoder, Encoder, Formatter, FormatterSyntax, Instruction, MemoryOperand, Register as R +import pefile + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "tools")) +from cpu_leaf_aot import bounded_code, export_rva # noqa: E402 +from cpu_movbe_aot import lift_code, translate # noqa: E402 + +EXPORTS = ( + "op_movbe_load16", "op_movbe_load16_disp", + "op_movbe_load32", "op_movbe_load32_disp", + "op_movbe_load64", "op_movbe_load64_disp", + "op_movbe_store16", "op_movbe_store16_disp", + "op_movbe_store32", "op_movbe_store32_disp", + "op_movbe_store64", "op_movbe_store64_disp", + "op_movbe_flags_cf_zf_of_pf", + "op_movbe_flags_sf_of_pf", + "op_movbe_flags_all_clear", + "op_r8_source_then_store", + "op_movbe_discarded_read", +) + +ALTERED_EXPORTS = ( + "op_movbe_load16", "op_movbe_load16_disp", + "op_movbe_load32", "op_movbe_load32_disp", + "op_movbe_load64", "op_movbe_load64_disp", + "op_movbe_store16", "op_movbe_store16_disp", + "op_movbe_store32", "op_movbe_store32_disp", + "op_movbe_store64", "op_movbe_store64_disp", +) + +MASK16 = 0xFFFF +MASK32 = 0xFFFFFFFF +MASK64 = 0xFFFFFFFFFFFFFFFF +GUARD_PRE = bytes(range(0xA0, 0xB0)) +GUARD_POST = bytes(range(0xC0, 0xD0)) + + +# --- Independent Python reference model --- + +def ref_movbe_load(buf, offset, width, prior_reg, *, quirk=None): + raw = buf[offset:offset + width // 8] + val = int.from_bytes(raw, "little" if quirk == "noswap" else "big") + if width == 16: + if quirk == "clear16": + return val + return (prior_reg & ~MASK16) | val + if width == 32: + if quirk == "no_zext32": + return val | 0xFFFFFFFF00000000 + return val + return val + + +def ref_movbe_store(val, width, *, quirk=None): + mask = (1 << width) - 1 + return (val & mask).to_bytes(width // 8, "little" if quirk == "noswap" else "big") + + +def test_inputs(): + mem_blocks = [ + bytes(range(0x10, 0x30)), + b"\x00" * 32, + b"\xff" * 32, + bytes((0x11 * k + 0x5A) & 0xFF for k in range(32)), + struct.pack("<4Q", 0x0102030405060708, 0x8000000000000001, 0xDEADBEEFCAFEF00D, 0x00FF00FF00FF00FF), + ] + regs = [ + 0x0000000000000000, + 0xFFFFFFFFFFFFFFFF, + 0xDEADBEEF12345678, + 0x0102030405060708, + 0x8000000000000001, + 0x00000000CAFEBABE, + ] + rng = random.Random(0x40DBE07) + for _ in range(8): + mem_blocks.append(rng.randbytes(32)) + regs.append(rng.getrandbits(64)) + return mem_blocks, regs + + +# --- Guarded memory & DLL helpers --- + +def alloc_guarded(payload): + raw = ctypes.create_string_buffer(GUARD_PRE + payload + GUARD_POST, len(GUARD_PRE) + len(payload) + len(GUARD_POST)) + base = ctypes.addressof(raw) + return raw, base + len(GUARD_PRE), len(GUARD_PRE), len(payload) + + +def read_guarded(buf, off, length, label): + raw = buf.raw + if raw[:off] != GUARD_PRE or raw[off + length:] != GUARD_POST: + raise AssertionError(f"guard bytes corrupted around {label}") + return raw[off:off + length] + + +def bind_exports(dll_path, prefix=""): + lib = ctypes.CDLL(str(Path(dll_path).resolve())) + funcs = {} + for name in EXPORTS: + fn = getattr(lib, prefix + name) + fn.argtypes = [ctypes.c_uint64] * 3 + fn.restype = ctypes.c_uint64 + funcs[name] = fn + return lib, funcs + + +def unload_lib(lib): + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + kernel32.FreeLibrary.argtypes = [ctypes.c_void_p] + kernel32.FreeLibrary.restype = ctypes.c_int + handle = getattr(lib, "_handle", None) + if handle: + kernel32.FreeLibrary(handle) + + +def host_has_movbe(lifted_lib): + if hasattr(lifted_lib, "host_has_movbe"): + lifted_lib.host_has_movbe.argtypes = [] + lifted_lib.host_has_movbe.restype = ctypes.c_uint32 + return bool(lifted_lib.host_has_movbe()) + return False + + +# --- Rejection & alternate-encoding controls --- + +def encode_seq(*instructions): + enc = Encoder(64) + ip = 0x1000 + for ins in instructions: + ip += enc.encode(ins, ip) + return enc.take_buffer() + + +def check_rejections(original_path): + ret = Instruction.create(Code.RETNQ) + mov_rax_rcx = Instruction.create_reg_reg(Code.MOV_R64_RM64, R.RAX, R.RCX) + mov_r9_rdx = Instruction.create_reg_reg(Code.MOV_R64_RM64, R.R9, R.RDX) + + # Alternate encodings accepted cleanly. + alt_accept = [ + ("movbe_r11w_r8_disp12", (Instruction.create_reg_reg(Code.MOV_R64_RM64, R.R11, R.RDX), + Instruction.create_reg_mem(Code.MOVBE_R16_M16, R.R11W, MemoryOperand(R.R8, displ=12, displ_size=1)), + Instruction.create_reg_reg(Code.MOV_R64_RM64, R.RAX, R.R11), ret), + "const word ld_1003_1 = static_cast(bswap16(load_always((r8 + 0xcull))));"), + ("movbe_m32_r10d_disp16", (Instruction.create_reg_reg(Code.MOV_R32_RM32, R.R10D, R.ECX), + Instruction.create_mem_reg(Code.MOVBE_M32_R32, MemoryOperand(R.R8, displ=16, displ_size=1), R.R10D), + mov_rax_rcx, ret), + "store_always((r8 + 0x10ull), bswap32(static_cast((r10 & 0xFFFFFFFFull))));"), + ("movbe_r9_rdx_disp64", (Instruction.create_reg_mem( + Code.MOVBE_R64_M64, R.R9, MemoryOperand(R.RDX, displ=64, displ_size=1)), + Instruction.create_reg_reg(Code.MOV_R64_RM64, R.RAX, R.R9), ret), + "const word ld_1000_1 = static_cast(bswap64(load_always((rdx + 0x40ull))));"), + ] + for label, seq, expected in alt_accept: + src, count = lift_code(label, 0x1000, encode_seq(*seq)) + assert f"lifted_{label}" in src and count == len(seq), (label, count) + if expected not in src: + raise AssertionError(f"alt {label}: expected {expected!r}") + + seg_movbe = Instruction.create_reg_mem(Code.MOVBE_R64_M64, R.RAX, MemoryOperand(R.RCX)) + seg_movbe.segment_prefix = R.GS + evex_ins = Instruction.create_reg_reg_reg(Code.EVEX_VPADDD_XMM_K1Z_XMM_XMMM128B32, R.XMM0, R.XMM1, R.XMM2) + evex_ins.op_mask = R.K1 + + unit_cases = [ + # Stores outside [r8] + ("store_rcx_movbe16", (Instruction.create_mem_reg(Code.MOVBE_M16_R16, MemoryOperand(R.RCX), R.DX), mov_rax_rcx, ret), + "non-r8 store memory operand"), + ("store_rdx_movbe32", (Instruction.create_mem_reg(Code.MOVBE_M32_R32, MemoryOperand(R.RDX, displ=4, displ_size=1), R.ECX), mov_rax_rcx, ret), + "non-r8 store memory operand"), + ("store_rcx_movbe64", (Instruction.create_mem_reg(Code.MOVBE_M64_R64, MemoryOperand(R.RCX), R.RDX), mov_rax_rcx, ret), + "non-r8 store memory operand"), + ("store_rcx_mov64", (mov_rax_rcx, Instruction.create_mem_reg(Code.MOV_RM64_R64, MemoryOperand(R.RCX), R.RAX), ret), + "non-r8 store memory operand"), + ("store_rdx_setb", (Instruction.create_reg_reg(Code.XOR_R32_RM32, R.R9D, R.R9D), + Instruction.create_mem(Code.SETB_RM8, MemoryOperand(R.RDX)), mov_rax_rcx, ret), + "non-r8 store memory operand"), + # Indexed / scaled / RIP-relative / bad base / out-of-range displacement + ("indexed_movbe64", (Instruction.create_reg_mem( + Code.MOVBE_R64_M64, R.RAX, MemoryOperand(R.RCX, R.RDX, 4)), ret), + "SIB index memory operand"), + ("scaled_store_movbe", (Instruction.create_mem_reg( + Code.MOVBE_M32_R32, MemoryOperand(R.R8, R.RCX, 2), R.EDX), mov_rax_rcx, ret), + "SIB index memory operand"), + ("rip_rel_movbe", (Instruction.create_reg_mem( + Code.MOVBE_R64_M64, R.RAX, MemoryOperand(R.RIP, displ=0x1020, displ_size=4)), ret), + "RIP-relative memory operand"), + ("bad_base_rbx", (Instruction.create_reg_mem(Code.MOVBE_R64_M64, R.RAX, MemoryOperand(R.RBX)), ret), + "bad base register in memory operand"), + ("bad_base_rsp", (Instruction.create_reg_mem(Code.MOVBE_R32_M32, R.EAX, MemoryOperand(R.RSP)), ret), + "bad base register in memory operand"), + ("neg_disp_movbe", (Instruction.create_reg_mem( + Code.MOVBE_R32_M32, R.EAX, MemoryOperand(R.RCX, displ=-4, displ_size=1)), ret), + "out-of-range displaced memory operand"), + ("large_disp_movbe", (Instruction.create_reg_mem( + Code.MOVBE_R64_M64, R.RAX, MemoryOperand(R.RCX, displ=128, displ_size=8)), ret), + "out-of-range displaced memory operand"), + ("large_disp_store", (Instruction.create_mem_reg( + Code.MOVBE_M64_R64, MemoryOperand(R.R8, displ=65, displ_size=1), R.RDX), mov_rax_rcx, ret), + "out-of-range displaced memory operand"), + # Nonvolatile GPRs, arg GPR writes, high-byte GPRs + ("nonvol_rbx_dst", (Instruction.create_reg_mem(Code.MOVBE_R64_M64, R.RBX, MemoryOperand(R.RCX)), mov_rax_rcx, ret), + "nonvolatile GPR"), + ("nonvol_rsi_src", (Instruction.create_mem_reg(Code.MOVBE_M64_R64, MemoryOperand(R.R8), R.RSI), mov_rax_rcx, ret), + "nonvolatile GPR"), + ("nonvol_r12_dst", (Instruction.create_reg_mem(Code.MOVBE_R32_M32, R.R12D, MemoryOperand(R.RCX)), mov_rax_rcx, ret), + "nonvolatile GPR"), + ("write_arg_rcx", (Instruction.create_reg_mem(Code.MOVBE_R64_M64, R.RCX, MemoryOperand(R.RDX)), mov_rax_rcx, ret), + "cannot write argument GPR rcx"), + ("write_arg_edx", (Instruction.create_reg_mem(Code.MOVBE_R32_M32, R.EDX, MemoryOperand(R.RCX)), mov_rax_rcx, ret), + "cannot write argument GPR rdx"), + ("write_arg_r8w", (Instruction.create_reg_mem(Code.MOVBE_R16_M16, R.R8W, MemoryOperand(R.RCX)), mov_rax_rcx, ret), + "cannot write argument GPR r8"), + ("high_byte_ah", (mov_rax_rcx, Instruction.create_reg_u32(Code.MOV_R8_IMM8, R.AH, 1), ret), + "unsupported high-byte GPR"), + # Undefined GPRs / flags + ("undef_r9_movbe16_dst", (Instruction.create_reg_mem(Code.MOVBE_R16_M16, R.R9W, MemoryOperand(R.RCX)), mov_rax_rcx, ret), + "undefined GPR r9"), + ("undef_r10_movbe_store", (Instruction.create_mem_reg(Code.MOVBE_M64_R64, MemoryOperand(R.R8), R.R10), mov_rax_rcx, ret), + "undefined GPR r10"), + ("undef_rax_ret", (mov_r9_rdx, ret), "return with undefined RAX"), + ("undef_flags_setb", (mov_rax_rcx, Instruction.create_mem(Code.SETB_RM8, MemoryOperand(R.R8)), ret), + "undefined flag cf read"), + # Out-of-scope / VEX / EVEX / XOP / prefixes / branches / ret + ("bswap_rejected", (mov_rax_rcx, Instruction.create_reg(Code.BSWAP_R64, R.RAX), ret), + "unsupported instruction"), + ("cmovbe_rejected", (Instruction.create_reg_reg(Code.XOR_R32_RM32, R.R9D, R.R9D), + Instruction.create_reg_reg(Code.CMOVBE_R64_RM64, R.RAX, R.RCX), ret), + "unsupported instruction"), + ("vex_blsi", (Instruction.create_reg_reg(Code.VEX_BLSI_R64_RM64, R.RAX, R.RCX), ret), + "unsupported VEX instruction"), + ("evex_vpaddd", (evex_ins, mov_rax_rcx, ret), "unsupported EVEX instruction"), + ("xop_blsic", (Instruction.create_reg_reg(Code.XOP_BLSIC_R64_RM64, R.RAX, R.RCX), ret), + "unsupported XOP instruction"), + ("seg_prefix_movbe", (seg_movbe, ret), "unsupported instruction prefix"), + ("branch_jmp", (mov_rax_rcx, Instruction.create_branch(Code.JMP_REL8_64, 0x1010), ret), + "non-leaf branch or call"), + ("missing_ret", (mov_rax_rcx,), "missing terminal ret"), + ("trailing_after_ret", (mov_rax_rcx, ret, mov_r9_rdx), "unreachable instruction after ret"), + ] + + raw_cases = [ + ("movbe_reg_reg_ud", bytes.fromhex("0f38f0c1") + encode_seq(ret), "invalid instruction"), + ("lock_prefix", bytes.fromhex("f00fb109") + encode_seq(mov_rax_rcx, ret), "unsupported instruction prefix"), + ("rep_prefix", bytes.fromhex("f3a4") + encode_seq(mov_rax_rcx, ret), "unsupported instruction prefix"), + ("empty_stream", b"", "truncated instruction stream"), + ("invalid_bytes", bytes.fromhex("fffe") + encode_seq(ret), "invalid instruction"), + ] + + for label, seq, reason in unit_cases: + try: + lift_code(label, 0x1000, encode_seq(*seq)) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: translator accepted rejected control") + + for label, raw, reason in raw_cases: + try: + lift_code(label, 0x1000, raw) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: translator accepted raw rejected control") + + # End-to-end PE-patched rejections & CLI non-traceback / temp-cleanup rejections. + pe_bytes = Path(original_path).read_bytes() + with pefile.PE(data=pe_bytes, fast_load=True) as pe: + entry = export_rva(pe, "op_movbe_flags_cf_zf_of_pf") + file_off = pe.get_offset_from_rva(entry) + pdata = pe.OPTIONAL_HEADER.DATA_DIRECTORY[3] + records = pe.get_data(pdata.VirtualAddress, pdata.Size) + rec_idx = next(i for i in range(0, len(records), 12) if struct.unpack_from(" max_len: + raise AssertionError(f"pe_{label}: patch ({len(patch)} bytes) exceeds max_len ({max_len})") + damaged = bytearray(pe_bytes) + damaged[file_off:file_off + len(patch)] = patch + struct.pack_into("(word rcx, word rdx, word r8) +where rcx, rdx, and r8 enter as 64-bit integer arguments or flat pointers to caller-owned +buffers and RAX carries the 64-bit return value. + +Supported MOVBE instructions (docs/coverage/x64_zen2.tsv group MOVBE): + - MOVBE r16, m16 | MOVBE r32, m32 | MOVBE r64, m64 (loads from [rcx|rdx|r8 (+0..64)]) + - MOVBE m16, r16 | MOVBE m32, r32 | MOVBE m64, r64 (stores to [r8 (+0..64)]) + +Exact x64 semantics: + - 16-bit MOVBE load reverses 2 bytes and preserves destination bits [63:16]. + - 32-bit MOVBE load reverses 4 bytes and zero-extends bits [63:32]. + - 64-bit MOVBE load and all MOVBE stores reverse byte order. + - All 6 MOVBE forms leave RFLAGS (CF, ZF, SF, OF, PF, AF) completely unmodified. + - Memory operands are flat [rcx|rdx|r8] or [rcx|rdx|r8 + small_disp] (0 <= disp <= 64) + read/written unconditionally via load_always()/store_always() so /O2 cannot drop + faulting accesses. + +Transport / flag-testing glue: + - Volatile scratch GPR (rax/r9/r10/r11) mov, xor, or, shl, movzx, setcc (reg or [r8+disp]), + flat [r8+disp] stores, and terminal ret. + +Stores outside [r8], negative or out-of-window displacements (> 64), indexed/scaled/RIP-rel +memory operands, nonvolatile GPRs, writes to argument GPRs (rcx/rdx/r8), high-byte GPRs, +undefined GPR or flag reads, VEX/EVEX/XOP encodings, instruction prefixes, branches/calls, +and missing or trailing instructions after ret are rejected. +""" + +import argparse +import os +from pathlib import Path +import sys +import tempfile + +import pefile +from iced_x86 import ( + Code, + Decoder, + EncodingKind, + FlowControl, + MemorySizeExt, + OpKind, + Register as R, + RegisterExt, +) + +from cpu_leaf_aot import bounded_code, export_rva + + +ARGUMENTS = {R.RCX: "rcx", R.RDX: "rdx", R.R8: "r8"} +ARGUMENT_NAMES = {"rcx", "rdx", "r8"} +MAX_DISPL = 64 + +VOLATILE_GPR64 = { + R.RAX: "rax", R.RCX: "rcx", R.RDX: "rdx", R.R8: "r8", + R.R9: "r9", R.R10: "r10", R.R11: "r11", +} +VOLATILE_GPR32 = { + R.EAX: "rax", R.ECX: "rcx", R.EDX: "rdx", R.R8D: "r8", + R.R9D: "r9", R.R10D: "r10", R.R11D: "r11", +} +VOLATILE_GPR16 = { + R.AX: "rax", R.CX: "rcx", R.DX: "rdx", R.R8W: "r8", + R.R9W: "r9", R.R10W: "r10", R.R11W: "r11", +} +VOLATILE_GPR8 = { + R.AL: "rax", R.CL: "rcx", R.DL: "rdx", R.R8L: "r8", + R.R9L: "r9", R.R10L: "r10", R.R11L: "r11", +} +HIGH_BYTE_GPRS = {R.AH, R.CH, R.DH, R.BH} +NONVOLATILE_GPR = { + R.RBX, R.EBX, R.BX, R.BL, + R.RBP, R.EBP, R.BP, R.BPL, + R.RSI, R.ESI, R.SI, R.SIL, + R.RDI, R.EDI, R.DI, R.DIL, + R.RSP, R.ESP, R.SP, R.SPL, + R.R12, R.R12D, R.R12W, R.R12L, + R.R13, R.R13D, R.R13W, R.R13L, + R.R14, R.R14D, R.R14W, R.R14L, + R.R15, R.R15D, R.R15W, R.R15L, +} + +# (is_store, width_bits) +MOVBE_SPECS = { + Code.MOVBE_R16_M16: (False, 16), + Code.MOVBE_R32_M32: (False, 32), + Code.MOVBE_R64_M64: (False, 64), + Code.MOVBE_M16_R16: (True, 16), + Code.MOVBE_M32_R32: (True, 32), + Code.MOVBE_M64_R64: (True, 64), +} + +MOV_WIDTHS = { + Code.MOV_R64_RM64: 64, + Code.MOV_RM64_R64: 64, + Code.MOV_RM64_IMM32: 64, + Code.MOV_R64_IMM64: 64, + Code.MOV_R32_RM32: 32, + Code.MOV_RM32_R32: 32, + Code.MOV_RM32_IMM32: 32, + Code.MOV_R32_IMM32: 32, + Code.MOV_R16_RM16: 16, + Code.MOV_RM16_R16: 16, + Code.MOV_RM16_IMM16: 16, + Code.MOV_R16_IMM16: 16, + Code.MOV_R8_RM8: 8, + Code.MOV_RM8_R8: 8, + Code.MOV_RM8_IMM8: 8, + Code.MOV_R8_IMM8: 8, +} +MOVZX_SPECS = { + Code.MOVZX_R32_RM8: (32, 8), + Code.MOVZX_R64_RM8: (64, 8), +} +XOR_WIDTHS = { + Code.XOR_R32_RM32: 32, + Code.XOR_RM32_R32: 32, + Code.XOR_RM32_IMM8: 32, + Code.XOR_R64_RM64: 64, + Code.XOR_RM64_R64: 64, + Code.XOR_RM64_IMM8: 64, +} +OR_WIDTHS = { + Code.OR_R32_RM32: 32, + Code.OR_RM32_R32: 32, + Code.OR_RM32_IMM8: 32, + Code.OR_R64_RM64: 64, + Code.OR_RM64_R64: 64, + Code.OR_RM64_IMM8: 64, +} +SHL_SPECS = { + Code.SHL_RM32_1: (32, True), + Code.SHL_RM32_IMM8: (32, False), + Code.SHL_RM64_1: (64, True), + Code.SHL_RM64_IMM8: (64, False), +} +SETCC_SPECS = { + Code.SETB_RM8: ("cf", "flags.cf"), + Code.SETAE_RM8: ("cf", "!flags.cf"), + Code.SETE_RM8: ("zf", "flags.zf"), + Code.SETNE_RM8: ("zf", "!flags.zf"), + Code.SETS_RM8: ("sf", "flags.sf"), + Code.SETNS_RM8: ("sf", "!flags.sf"), + Code.SETO_RM8: ("of", "flags.of"), + Code.SETNO_RM8: ("of", "!flags.of"), + Code.SETP_RM8: ("pf", "flags.pf"), + Code.SETNP_RM8: ("pf", "!flags.pf"), +} + +PRELUDE = """#include +#include +#include +#if defined(_MSC_VER) +#include +#endif + +using word = std::uint64_t; + +struct Flags { + bool cf = false; + bool zf = false; + bool sf = false; + bool of = false; + bool pf = false; +}; + +template +static inline T load_always(word address) { + std::atomic_signal_fence(std::memory_order_seq_cst); + T v{}; + std::memcpy(&v, reinterpret_cast(address), sizeof(T)); + const volatile T observed = v; + std::atomic_signal_fence(std::memory_order_seq_cst); + return observed; +} + +template +static inline void store_always(word address, T value) { + std::atomic_signal_fence(std::memory_order_seq_cst); + std::memcpy(reinterpret_cast(address), &value, sizeof(T)); + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +static inline std::uint16_t bswap16(std::uint16_t v) { + return static_cast((v >> 8) | (v << 8)); +} + +static inline std::uint32_t bswap32(std::uint32_t v) { + return ((v & 0x000000FFu) << 24) + | ((v & 0x0000FF00u) << 8) + | ((v & 0x00FF0000u) >> 8) + | ((v & 0xFF000000u) >> 24); +} + +static inline std::uint64_t bswap64(std::uint64_t v) { + return ((v & 0x00000000000000FFull) << 56) + | ((v & 0x000000000000FF00ull) << 40) + | ((v & 0x0000000000FF0000ull) << 24) + | ((v & 0x00000000FF000000ull) << 8) + | ((v & 0x000000FF00000000ull) >> 8) + | ((v & 0x0000FF0000000000ull) >> 24) + | ((v & 0x00FF000000000000ull) >> 40) + | ((v & 0xFF00000000000000ull) >> 56); +} + +static inline bool parity_even(std::uint8_t byte) { + byte ^= static_cast(byte >> 4); + byte &= 0x0Fu; + return ((0x9669u >> byte) & 1u) != 0u; +} + +static inline word update_gpr_width(word cur, std::uint64_t val, unsigned width) { + if (width == 8u) { + return (cur & ~0xFFull) | (val & 0xFFull); + } + if (width == 16u) { + return (cur & ~0xFFFFull) | (val & 0xFFFFull); + } + if (width == 32u) { + return val & 0xFFFFFFFFull; + } + return val; +} + +static inline void compute_logic_flags(word result, unsigned width, Flags& flags) { + const std::uint64_t masked = (width == 32u) ? (result & 0xFFFFFFFFull) : result; + flags.cf = false; + flags.of = false; + flags.zf = masked == 0ull; + flags.sf = ((masked >> (width - 1u)) & 1ull) != 0ull; + flags.pf = parity_even(static_cast(masked)); +} + +static inline word op_shl(word cur, unsigned width, unsigned count, Flags& flags) { + const unsigned mask = (width == 32u) ? 31u : 63u; + const unsigned c = count & mask; + if (width == 32u) { + const std::uint32_t v = static_cast(cur); + if (c == 0u) return static_cast(v); + const std::uint32_t r = v << c; + flags.cf = ((v >> (32u - c)) & 1u) != 0u; + flags.zf = r == 0u; + flags.sf = (r & 0x80000000u) != 0u; + flags.of = (((r >> 31) & 1u) != (flags.cf ? 1u : 0u)); + flags.pf = parity_even(static_cast(r)); + return static_cast(r); + } + if (c == 0u) return cur; + const word r = cur << c; + flags.cf = ((cur >> (64u - c)) & 1ull) != 0ull; + flags.zf = r == 0ull; + flags.sf = (r >> 63) != 0ull; + flags.of = (((r >> 63) & 1ull) != (flags.cf ? 1ull : 0ull)); + flags.pf = parity_even(static_cast(r)); + return r; +} + +#if defined(_MSC_VER) +extern "C" __declspec(dllexport) std::uint32_t host_has_movbe() { + int info[4]{}; + __cpuid(info, 1); + return (static_cast(info[2]) & (1u << 22)) != 0u ? 1u : 0u; +} +#endif +""" + + +def gpr_info(register, ins): + """Map volatile GPR (64/32/16/8-bit low) to (name, width_bits), rejecting nonvolatile/high-byte.""" + if register in VOLATILE_GPR64: + return VOLATILE_GPR64[register], 64 + if register in VOLATILE_GPR32: + return VOLATILE_GPR32[register], 32 + if register in VOLATILE_GPR16: + return VOLATILE_GPR16[register], 16 + if register in VOLATILE_GPR8: + return VOLATILE_GPR8[register], 8 + if register in HIGH_BYTE_GPRS: + raise ValueError(f"unsupported high-byte GPR {register} at RVA {ins.ip:#x}: {ins}") + if register in NONVOLATILE_GPR: + raise ValueError(f"nonvolatile GPR {register} at RVA {ins.ip:#x}: {ins}") + raise ValueError(f"unsupported GPR {register} at RVA {ins.ip:#x}: {ins}") + + +def flat_address(ins, expected_bytes, *, write=False): + """Lower a flat [rcx|rdx|r8 (+0..64)] memory operand (stores only to [r8 (+0..64)]).""" + if ins.is_ip_rel_memory_operand or ins.memory_base in (R.RIP, R.EIP): + raise ValueError(f"RIP-relative memory operand at RVA {ins.ip:#x}: {ins}") + if ins.memory_index != R.NONE: + raise ValueError(f"SIB index memory operand at RVA {ins.ip:#x}: {ins}") + base = ins.memory_base + if base == R.NONE or not RegisterExt.is_gpr64(base) or base not in ARGUMENTS: + raise ValueError(f"bad base register in memory operand at RVA {ins.ip:#x}: {ins}") + disp = ins.memory_displacement & 0xFFFFFFFFFFFFFFFF + if disp > MAX_DISPL: + raise ValueError(f"out-of-range displaced memory operand at RVA {ins.ip:#x}: {ins}") + if write and base != R.R8: + raise ValueError(f"non-r8 store memory operand at RVA {ins.ip:#x}: {ins}") + actual_bytes = MemorySizeExt.size(ins.memory_size) + if actual_bytes != expected_bytes: + raise ValueError( + f"unexpected {actual_bytes}-byte memory operand (expected {expected_bytes}) at RVA {ins.ip:#x}: {ins}" + ) + name = ARGUMENTS[base] + return f"({name} + {disp:#x}ull)" if disp else name + + +def _immediate_value(ins, op_index, width): + kind = ins.op_kind(op_index) + if kind == OpKind.IMMEDIATE8: + return ins.immediate8 & 0xFF + if kind == OpKind.IMMEDIATE16: + return ins.immediate16 & 0xFFFF + if kind == OpKind.IMMEDIATE32: + return ins.immediate32 & 0xFFFFFFFF + if kind == OpKind.IMMEDIATE64: + return ins.immediate64 & 0xFFFFFFFFFFFFFFFF + if kind == OpKind.IMMEDIATE8TO16: + return ins.immediate8to16 & 0xFFFF + if kind == OpKind.IMMEDIATE8TO32: + return ins.immediate8to32 & 0xFFFFFFFF + if kind == OpKind.IMMEDIATE8TO64: + return ins.immediate8to64 & 0xFFFFFFFFFFFFFFFF + if kind == OpKind.IMMEDIATE32TO64: + return ins.immediate32to64 & 0xFFFFFFFFFFFFFFFF + raise ValueError(f"unsupported immediate kind {kind} for {width}-bit op at RVA {ins.ip:#x}: {ins}") + + +def lift_code(name, start, raw): + """Decode and lift one bounded straight-line MOVBE leaf function.""" + instructions = list(Decoder(64, raw, ip=start)) + if not instructions or instructions[-1].next_ip != start + len(raw): + raise ValueError(f"truncated instruction stream in {name} at RVA {start:#x}") + if any(ins.is_invalid for ins in instructions): + bad = next(ins for ins in instructions if ins.is_invalid) + raise ValueError(f"invalid instruction at RVA {bad.ip:#x}") + + defined_gpr = {"rcx", "rdx", "r8"} + used_scratch = set() + defined_flags = set() + statements = [] + returned = False + + def note_scratch(reg_name): + if reg_name in ("r9", "r10", "r11"): + used_scratch.add(reg_name) + + def read_reg(op_index, ins, expected_width): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register operand {op_index} at RVA {ins.ip:#x}: {ins}") + reg_name, width = gpr_info(ins.op_register(op_index), ins) + if width != expected_width: + raise ValueError(f"unexpected GPR width {width} at RVA {ins.ip:#x}: {ins}") + if reg_name not in defined_gpr: + raise ValueError(f"undefined GPR {reg_name} at RVA {ins.ip:#x}: {ins}") + note_scratch(reg_name) + mask = {8: "0xFFull", 16: "0xFFFFull", 32: "0xFFFFFFFFull"}.get(width) + return f"({reg_name} & {mask})" if mask else reg_name + + def check_dst_reg(op_index, ins, expected_width, *, require_defined=False): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register destination at RVA {ins.ip:#x}: {ins}") + reg_name, width = gpr_info(ins.op_register(op_index), ins) + if width != expected_width: + raise ValueError(f"unexpected GPR destination width {width} at RVA {ins.ip:#x}: {ins}") + if reg_name in ARGUMENT_NAMES: + raise ValueError(f"cannot write argument GPR {reg_name} at RVA {ins.ip:#x}: {ins}") + if require_defined and reg_name not in defined_gpr: + raise ValueError(f"undefined GPR {reg_name} at RVA {ins.ip:#x}: {ins}") + note_scratch(reg_name) + return reg_name + + def read_rm(op_index, ins, width): + kind = ins.op_kind(op_index) + if kind == OpKind.REGISTER: + return read_reg(op_index, ins, width) + if kind == OpKind.MEMORY: + addr = flat_address(ins, width // 8, write=False) + ctype = { + 8: "std::uint8_t", + 16: "std::uint16_t", + 32: "std::uint32_t", + 64: "std::uint64_t", + }[width] + load_var = f"ld_{ins.ip:x}_{op_index}" + statements.append(f"const word {load_var} = static_cast(load_always<{ctype}>({addr}));") + return load_var + raise ValueError(f"unsupported operand at RVA {ins.ip:#x}: {ins}") + + for ins in instructions: + if returned: + raise ValueError(f"unreachable instruction after ret at RVA {ins.ip:#x}: {ins}") + if ins.has_lock_prefix or ins.has_rep_prefix or ins.has_repne_prefix or ins.has_segment_prefix: + raise ValueError(f"unsupported instruction prefix at RVA {ins.ip:#x}: {ins}") + + op_code = ins.op_code() + encoding = op_code.encoding + if encoding == EncodingKind.EVEX or ins.op_mask != R.NONE or ins.zeroing_masking or ins.is_broadcast: + raise ValueError(f"unsupported EVEX instruction at RVA {ins.ip:#x}: {ins}") + if encoding == EncodingKind.XOP: + raise ValueError(f"unsupported XOP instruction at RVA {ins.ip:#x}: {ins}") + if encoding == EncodingKind.VEX: + raise ValueError(f"unsupported VEX instruction at RVA {ins.ip:#x}: {ins}") + if ins.code != Code.RETNQ and ins.flow_control != FlowControl.NEXT: + raise ValueError(f"non-leaf branch or call at RVA {ins.ip:#x}: {ins}") + + code = ins.code + if code in MOVBE_SPECS: + is_store, width = MOVBE_SPECS[code] + ctype = {16: "std::uint16_t", 32: "std::uint32_t", 64: "std::uint64_t"}[width] + bswap_fn = {16: "bswap16", 32: "bswap32", 64: "bswap64"}[width] + if is_store: + if ins.op0_kind != OpKind.MEMORY or ins.op1_kind != OpKind.REGISTER: + raise ValueError(f"unsupported movbe store operands at RVA {ins.ip:#x}: {ins}") + src_expr = read_reg(1, ins, width) + addr = flat_address(ins, width // 8, write=True) + statements.append( + f"store_always<{ctype}>({addr}, {bswap_fn}(static_cast<{ctype}>({src_expr})));" + ) + else: + if ins.op0_kind != OpKind.REGISTER or ins.op1_kind != OpKind.MEMORY: + raise ValueError(f"unsupported movbe load operands at RVA {ins.ip:#x}: {ins}") + addr = flat_address(ins, width // 8, write=False) + dst = check_dst_reg(0, ins, width, require_defined=(width < 32)) + load_var = f"ld_{ins.ip:x}_1" + statements.append(f"const word {load_var} = static_cast({bswap_fn}(load_always<{ctype}>({addr})));") + statements.append(f"{dst} = update_gpr_width({dst}, {load_var}, {width}u);") + if width >= 32: + defined_gpr.add(dst) + elif code == Code.RETNQ: + if "rax" not in defined_gpr: + raise ValueError(f"return with undefined RAX at RVA {ins.ip:#x}") + statements.append("return rax;") + returned = True + elif code in MOV_WIDTHS: + width = MOV_WIDTHS[code] + ctype = { + 8: "std::uint8_t", + 16: "std::uint16_t", + 32: "std::uint32_t", + 64: "std::uint64_t", + }[width] + if ins.op0_kind == OpKind.REGISTER and ins.op1_kind in (OpKind.REGISTER, OpKind.MEMORY): + src_expr = read_rm(1, ins, width) + dst = check_dst_reg(0, ins, width, require_defined=(width < 32)) + statements.append(f"{dst} = update_gpr_width({dst}, {src_expr}, {width}u);") + if width >= 32: + defined_gpr.add(dst) + elif ins.op0_kind == OpKind.MEMORY and ins.op1_kind == OpKind.REGISTER: + src_expr = read_rm(1, ins, width) + addr = flat_address(ins, width // 8, write=True) + statements.append(f"store_always<{ctype}>({addr}, static_cast<{ctype}>({src_expr}));") + elif ins.op0_kind == OpKind.REGISTER: + imm = _immediate_value(ins, 1, width) + dst = check_dst_reg(0, ins, width, require_defined=(width < 32)) + statements.append(f"{dst} = update_gpr_width({dst}, {imm:#x}ull, {width}u);") + if width >= 32: + defined_gpr.add(dst) + elif ins.op0_kind == OpKind.MEMORY: + imm = _immediate_value(ins, 1, width) + addr = flat_address(ins, width // 8, write=True) + statements.append(f"store_always<{ctype}>({addr}, static_cast<{ctype}>({imm:#x}ull));") + else: + raise ValueError(f"unsupported mov operands at RVA {ins.ip:#x}: {ins}") + elif code in MOVZX_SPECS: + dst_width, src_width = MOVZX_SPECS[code] + src_expr = read_rm(1, ins, src_width) + dst = check_dst_reg(0, ins, dst_width, require_defined=False) + statements.append(f"{dst} = {src_expr};") + defined_gpr.add(dst) + elif code in XOR_WIDTHS: + width = XOR_WIDTHS[code] + if ( + ins.op0_kind == OpKind.REGISTER + and ins.op1_kind == OpKind.REGISTER + and ins.op0_register == ins.op1_register + ): + dst = check_dst_reg(0, ins, width, require_defined=False) + statements.append(f"{dst} = 0ull;") + defined_gpr.add(dst) + else: + dst = check_dst_reg(0, ins, width, require_defined=True) + lhs_expr = read_reg(0, ins, width) + if ins.op1_kind in (OpKind.REGISTER, OpKind.MEMORY): + rhs_expr = read_rm(1, ins, width) + else: + rhs_expr = f"{_immediate_value(ins, 1, width):#x}ull" + statements.append(f"{dst} = update_gpr_width({dst}, {lhs_expr} ^ {rhs_expr}, {width}u);") + statements.append(f"compute_logic_flags({dst}, {width}u, flags);") + defined_flags = {"cf", "zf", "sf", "of", "pf"} + elif code in OR_WIDTHS: + width = OR_WIDTHS[code] + dst = check_dst_reg(0, ins, width, require_defined=True) + lhs_expr = read_reg(0, ins, width) + if ins.op1_kind in (OpKind.REGISTER, OpKind.MEMORY): + rhs_expr = read_rm(1, ins, width) + else: + rhs_expr = f"{_immediate_value(ins, 1, width):#x}ull" + statements.append(f"{dst} = update_gpr_width({dst}, {lhs_expr} | {rhs_expr}, {width}u);") + statements.append(f"compute_logic_flags({dst}, {width}u, flags);") + defined_flags = {"cf", "zf", "sf", "of", "pf"} + elif code in SHL_SPECS: + width, is_one = SHL_SPECS[code] + dst = check_dst_reg(0, ins, width, require_defined=True) + cnt = 1 if is_one else (ins.immediate8 & 0xFF) + eff = cnt & (31 if width == 32 else 63) + statements.append(f"{dst} = op_shl({dst}, {width}u, {cnt}u, flags);") + if eff == 1: + defined_flags = {"cf", "zf", "sf", "of", "pf"} + elif eff > 1: + defined_flags = {"cf", "zf", "sf", "pf"} + elif code in SETCC_SPECS: + flag_name, cond_expr = SETCC_SPECS[code] + if flag_name not in defined_flags: + raise ValueError(f"undefined flag {flag_name} read by {ins} at RVA {ins.ip:#x}") + if ins.op0_kind == OpKind.REGISTER: + dst = check_dst_reg(0, ins, 8, require_defined=True) + statements.append(f"{dst} = update_gpr_width({dst}, ({cond_expr}) ? 1ull : 0ull, 8u);") + elif ins.op0_kind == OpKind.MEMORY: + addr = flat_address(ins, 1, write=True) + statements.append( + f"store_always({addr}, static_cast(({cond_expr}) ? 1u : 0u));" + ) + else: + raise ValueError(f"unsupported setcc operand at RVA {ins.ip:#x}: {ins}") + else: + raise ValueError(f"unsupported instruction at RVA {ins.ip:#x}: {ins}") + + if not returned: + raise ValueError(f"missing terminal ret in {name} at RVA {start + len(raw):#x}") + + decls = [" word rax = 0ull;"] + for gpr in ("r9", "r10", "r11"): + if gpr in used_scratch: + decls.append(f" word {gpr} = 0ull;") + decls.append(" Flags flags{};") + decls.append(" (void)flags;") + body = [f" {stmt}" for stmt in statements] + lines = [ + f'extern "C" __declspec(dllexport) std::uint64_t lifted_{name}(word rcx, word rdx, word r8) {{', + " (void)rcx; (void)rdx; (void)r8;", + *decls, + *body, + "}", + ] + return "\n".join(lines), len(instructions) + + +def lift(pe, name): + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + source, count = lift_code(name, entry, raw) + return source, entry, count + + +def translate_pe(pe, names): + if pe.FILE_HEADER.Machine != 0x8664 or pe.OPTIONAL_HEADER.Magic != 0x20B: + raise ValueError("expected AMD64 PE32+") + lifted = [lift(pe, name) for name in names] + source = PRELUDE + "\n".join(f"\n{text}" for text, _, _ in lifted) + "\n" + meta = [(name, entry, count) for name, (_, entry, count) in zip(names, lifted)] + return source, meta + + +def translate(image, names): + with pefile.PE(str(image), fast_load=True) as pe: + return translate_pe(pe, names) + + +def _same_path(a, b): + try: + return os.path.samefile(a, b) + except OSError: + return a.resolve(strict=False) == b.resolve(strict=False) + + +def _write_atomic(path, text): + path.parent.mkdir(parents=True, exist_ok=True) + tmp_path = None + try: + with tempfile.NamedTemporaryFile( + mode="w", + encoding="utf-8", + dir=path.parent, + prefix=f".{path.name}.", + suffix=".tmp", + delete=False, + ) as handle: + tmp_path = Path(handle.name) + handle.write(text) + handle.flush() + os.replace(tmp_path, path) + except BaseException: + if tmp_path is not None: + tmp_path.unlink(missing_ok=True) + raise + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("image", type=Path) + parser.add_argument("exports", help="comma-separated export names") + parser.add_argument("output", type=Path) + args = parser.parse_args(argv) + try: + if not args.image.is_file(): + raise ValueError(f"input image is not a regular file: {args.image}") + names = [n for n in args.exports.split(",") if n] + if not names: + raise ValueError("expected at least one export name") + if args.output.is_symlink(): + raise ValueError(f"output path cannot be a symlink: {args.output}") + if args.output.exists() and args.output.is_dir(): + raise ValueError(f"output path is a directory: {args.output}") + if _same_path(args.image, args.output): + raise ValueError(f"output path matches input image: {args.output}") + source, meta = translate(args.image, names) + _write_atomic(args.output, source) + for name, entry, count in meta: + print(f"{name} at RVA {entry:#x}: {count} instructions") + return 0 + except (ValueError, OSError, pefile.PEFormatError) as error: + sys.stderr.write(f"{error}\n") + return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) From 47ffb8771849c399f1d97bae199e217f37040192 Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Thu, 26 Nov 2026 05:13:23 +0200 Subject: [PATCH 109/240] textures: harden paged_resource validation and add unit suite (#2676) * textures: harden paged_resource validation and add unit suite * textures: defer unknown string codecs to read in paged_resource --------- Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 3 + tests/paged_resource_check.py | 319 ++++++++++++++++++++++++++++++++++ tools/paged_resource.py | 29 +++- 3 files changed, 346 insertions(+), 5 deletions(-) create mode 100644 tests/paged_resource_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index facb842a5..8990de64e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -10891,6 +10891,9 @@ if(EXISTS "${INTAKE_PYTHON}") "$" "$") add_test(NAME layout_chunk_summary COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/layout_chunks_check.py") + add_test(NAME textures_paged_resource_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/paged_resource_check.py") + set_tests_properties(textures_paged_resource_check PROPERTIES TIMEOUT 60) add_test(NAME dependency_paths_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/dependency_paths_check.py") add_test(NAME pe_dependency_paths_cli_check COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/paged_resource_check.py b/tests/paged_resource_check.py new file mode 100644 index 000000000..45ea58216 --- /dev/null +++ b/tests/paged_resource_check.py @@ -0,0 +1,319 @@ +#!/usr/bin/env python3 +"""Pure-Python unit, edge-case, and mutation suite for tools/paged_resource.py.""" + +from __future__ import annotations + +import io +import os +from pathlib import Path +import sys +import types +from types import SimpleNamespace +import unittest +import zlib + +ROOT = Path(__file__).resolve().parents[1] +TOOLS_DIR = ROOT / "tools" +TOOL = TOOLS_DIR / "paged_resource.py" +sys.path.insert(0, str(TOOLS_DIR)) +import paged_resource as pr # noqa: E402 + + +class _ShortReadStream: + """Seekable stream returning at most max_chunk bytes per read() and optionally truncating EOF.""" + + def __init__(self, data: bytes, *, max_chunk: int = 3, reported_size: int | None = None) -> None: + self._data = data + self._max_chunk = max_chunk + self._reported_size = len(data) if reported_size is None else reported_size + self._pos = 0 + + def seek(self, offset: int, whence: int = os.SEEK_SET) -> int: + if whence == os.SEEK_END: + self._pos = self._reported_size + offset + elif whence == os.SEEK_CUR: + self._pos += offset + else: + self._pos = offset + return self._pos + + def read(self, size: int = -1) -> bytes: + if self._pos >= len(self._data): + return b"" + if size < 0: + take = len(self._data) - self._pos + else: + take = min(size, self._max_chunk, len(self._data) - self._pos) + chunk = self._data[self._pos : self._pos + take] + self._pos += len(chunk) + return chunk + + +def _build_multi_segment_archive() -> tuple[bytes, list[pr.Segment], bytes]: + raw0 = b"RAW_HEAD_0" # 10 bytes + dec1 = b"ZLIB_PAYLOAD_SEG_ONE" * 2 # 40 bytes + cmp1 = zlib.compress(dec1) + raw2 = b"MIDDLE_RAW_BYTES" # 16 bytes + dec3 = b"TAIL_ZLIB_DATA!" * 3 # 45 bytes + cmp3 = zlib.compress(dec3) + + buf = bytearray(b"\xaa" * 4) + off0 = len(buf) + buf.extend(raw0) + buf.extend(b"\xbb" * 6) # physical alignment padding + off1 = len(buf) + buf.extend(cmp1) + buf.extend(b"\xcc" * 5) + off2 = len(buf) + buf.extend(raw2) + buf.extend(b"\xdd" * 3) + off3 = len(buf) + buf.extend(cmp3) + buf.extend(b"\xee" * 4) + + segments = [ + pr.Segment(off0, len(raw0), len(raw0), "raw"), + pr.Segment(off1, len(cmp1), len(dec1), "zlib"), + pr.Segment(off2, len(raw2), len(raw2), "raw"), + pr.Segment(off3, len(cmp3), len(dec3), "zlib"), + ] + logical = raw0 + dec1 + raw2 + dec3 + return bytes(buf), segments, logical + + +class PagedResourcePositiveTests(unittest.TestCase): + def test_multi_segment_raw_and_zlib_spanning_boundaries(self) -> None: + blob, segments, logical = _build_multi_segment_archive() + resource = pr.PagedResource(io.BytesIO(blob), segments) + + self.assertEqual(resource.size, len(logical)) + self.assertEqual(resource.starts, (0, 10, 50, 66)) + self.assertEqual(resource.read(0, len(logical)), logical) + + # Cross-boundary spans across raw -> zlib -> raw -> zlib. + for offset, length in ( + (0, 10), + (5, 20), + (10, 40), + (45, 25), + (0, 0), + (resource.size, 0), + (0, 0), + (len(logical) - 12, 12), + ): + with self.subTest(offset=offset, length=length): + self.assertEqual(resource.read(offset, length), logical[offset : offset + length]) + + self.assertEqual(resource.read(0, 0, limit=0), b"") + + # Empty segment table is valid with size 0. + empty = pr.PagedResource(io.BytesIO(b"unused"), []) + self.assertEqual(empty.size, 0) + self.assertEqual(empty.starts, ()) + self.assertEqual(empty.read(0, 0), b"") + + def test_short_read_reassembly(self) -> None: + blob, segments, logical = _build_multi_segment_archive() + stream = _ShortReadStream(blob, max_chunk=3) + resource = pr.PagedResource(stream, segments) + + self.assertEqual(resource._read_at(segments[0].offset, segments[0].stored), logical[:10]) + self.assertEqual(resource.read(0, len(logical)), logical) + self.assertEqual(resource.read(7, 65), logical[7:72]) + + +class PagedResourceNegativeTests(unittest.TestCase): + def test_segment_and_init_type_and_layout_rejections(self) -> None: + stream = io.BytesIO(b"\x00" * 64) + + # Bool / non-int Segment fields rejected at construction and in PagedResource.__init__. + for kwargs in ( + {"offset": True, "stored": 4, "size": 4, "codec": "raw"}, + {"offset": 0, "stored": False, "size": 4, "codec": "raw"}, + {"offset": 0, "stored": 4, "size": True, "codec": "raw"}, + {"offset": 1.5, "stored": 4, "size": 4, "codec": "raw"}, + {"offset": 0, "stored": "4", "size": 4, "codec": "raw"}, + {"offset": 0, "stored": 4, "size": None, "codec": "raw"}, + ): + with self.subTest(bad_segment=kwargs): + with self.assertRaisesRegex(ValueError, "must be an integer"): + pr.Segment(**kwargs) + with self.assertRaisesRegex(ValueError, "must be an integer"): + pr.PagedResource(stream, [SimpleNamespace(**kwargs)]) + + # Overlapping, descending, negative, empty segments. + bad_layout = ( + ("negative_offset", [pr.Segment(-1, 4, 4, "raw")]), + ("empty_stored", [pr.Segment(0, 0, 4, "raw")]), + ("empty_size", [pr.Segment(0, 4, 0, "raw")]), + ("negative_stored", [pr.Segment(0, -4, 4, "raw")]), + ("negative_size", [pr.Segment(0, 4, -4, "raw")]), + ("overlapping", [pr.Segment(0, 10, 10, "raw"), pr.Segment(9, 4, 4, "raw")]), + ("descending", [pr.Segment(16, 4, 4, "raw"), pr.Segment(8, 4, 4, "raw")]), + ) + for label, segs in bad_layout: + with self.subTest(case=label): + with self.assertRaisesRegex(ValueError, "Overlapping, descending or empty segment"): + pr.PagedResource(stream, segs) + + # Oversized and mismatched raw segments. + bad_extents = ( + ("past_eof", [pr.Segment(60, 8, 8, "raw")]), + ("raw_stored_gt_size", [pr.Segment(0, 8, 4, "raw")]), + ("raw_stored_lt_size", [pr.Segment(0, 4, 8, "raw")]), + ) + for label, segs in bad_extents: + with self.subTest(case=label): + with self.assertRaisesRegex(ValueError, "Segment extent disagrees"): + pr.PagedResource(stream, segs) + + # Non-str / empty codecs are rejected upfront in PagedResource.__init__. + for bad_codec in (None, 123, b"raw", ""): + with self.subTest(codec=bad_codec): + seg = pr.Segment(0, 4, 4, bad_codec) # type: ignore[arg-type] + with self.assertRaisesRegex(ValueError, "Unsupported segment codec"): + pr.PagedResource(stream, [seg]) + + # Unknown string codecs stay deferred to read() so later segments remain addressable. + for unknown_codec in ("other", "lz4", "zstd"): + with self.subTest(unknown_codec=unknown_codec): + mixed = pr.PagedResource( + io.BytesIO(b"abcdef"), + [ + pr.Segment(0, 2, 2, "raw"), + pr.Segment(2, 2, 2, unknown_codec), + pr.Segment(4, 2, 2, "raw"), + ], + ) + self.assertEqual(mixed.read(0, 2), b"ab") + self.assertEqual(mixed.read(4, 2), b"ef") + with self.assertRaisesRegex(ValueError, f"Unsupported segment codec {unknown_codec}"): + mixed.read(1, 2) + + def test_zlib_error_and_limit_cases(self) -> None: + payload = b"ABCD" * 8 # 32 bytes + compressed = zlib.compress(payload) + + cases = ( + ("corrupt_zlib", b"\x78\x9c" + b"\xff" * 16, len(payload)), + ("truncated_zlib", compressed[:-3], len(payload)), + ("trailing_data", compressed + b"\x00", len(payload)), + ("decoded_smaller_than_declared", compressed, len(payload) + 1), + ("decoded_larger_than_declared", compressed, len(payload) - 1), + ) + for label, data, declared_size in cases: + with self.subTest(case=label): + res = pr.PagedResource(io.BytesIO(data), [pr.Segment(0, len(data), declared_size, "zlib")]) + with self.assertRaisesRegex(ValueError, "Invalid compressed segment"): + res.read(0, 4) + + # Over-limit zlib (both decoded size > limit and stored size > limit). + over_dec = pr.PagedResource(io.BytesIO(compressed), [pr.Segment(0, len(compressed), len(payload), "zlib")]) + with self.assertRaisesRegex(ValueError, "Compressed segment exceeds read budget"): + over_dec.read(0, 4, limit=len(payload) - 1) + + incompressible = os.urandom(32) if False else bytes((i * 37) & 0xFF for i in range(32)) + big_cmp = zlib.compress(incompressible) + self.assertGreater(len(big_cmp), len(incompressible)) + over_stored = pr.PagedResource(io.BytesIO(big_cmp), [pr.Segment(0, len(big_cmp), len(incompressible), "zlib")]) + with self.assertRaisesRegex(ValueError, "Compressed segment exceeds read budget"): + over_stored.read(0, 4, limit=len(big_cmp) - 1) + + # Truncated physical read detected cleanly. + trunc_raw = pr.PagedResource(_ShortReadStream(b"AB", reported_size=8), [pr.Segment(0, 8, 8, "raw")]) + with self.assertRaisesRegex(ValueError, "Truncated segment"): + trunc_raw.read(0, 8) + + trunc_zlib = pr.PagedResource( + _ShortReadStream(compressed[:4], reported_size=len(compressed)), + [pr.Segment(0, len(compressed), len(payload), "zlib")], + ) + with self.assertRaisesRegex(ValueError, "Invalid compressed segment"): + trunc_zlib.read(0, 4) + + def test_read_bounds_and_type_rejections(self) -> None: + res = pr.PagedResource(io.BytesIO(b"0123456789"), [pr.Segment(0, 10, 10, "raw")]) + + for args, kwargs in ( + ((-1, 1), {}), + ((0, -1), {}), + ((0, 0), {"limit": -1}), + ((0, 5), {"limit": 4}), + ((8, 3), {}), + ((11, 0), {}), + ): + with self.subTest(args=args, kwargs=kwargs): + with self.assertRaisesRegex(ValueError, "Logical range outside resource or read budget"): + res.read(*args, **kwargs) + + for args, kwargs in ( + ((True, 1), {}), + ((0, False), {}), + ((0, 1), {"limit": True}), + ((0.0, 1), {}), + ((0, "1"), {}), + ((0, 1), {"limit": None}), + ): + with self.subTest(bad_types=(args, kwargs)): + with self.assertRaisesRegex(ValueError, "must be an integer"): + res.read(*args, **kwargs) + + def test_fast_temp_mutations(self) -> None: + source = TOOL.read_text(encoding="utf-8") + payload = b"MUTATION_TEST_DATA" + cmp_plus_trail = zlib.compress(payload) + b"\x00" + + mutations = ( + ( + "allow_bool_segment_offset", + " if isinstance(value, bool) or not isinstance(value, int):\n", + " if not isinstance(value, int):\n", + lambda mod: mod.Segment(True, 1, 1, "raw"), + ), + ( + "skip_upfront_codec_type_check", + ' if not isinstance(segment.codec, str) or not segment.codec:\n' + ' raise ValueError(f"Unsupported segment codec {segment.codec!r}")\n', + " pass\n", + lambda mod: mod.PagedResource(io.BytesIO(b"abcd"), [mod.Segment(0, 4, 4, "")]), + ), + ( + "allow_negative_limit", + " if limit < 0 or offset < 0 or length < 0 or length > limit or offset + length > self.size:\n", + " if offset < 0 or length < 0 or (limit >= 0 and length > limit) or offset + length > self.size:\n", + lambda mod: mod.PagedResource(io.BytesIO(b"abcd"), [mod.Segment(0, 4, 4, "raw")]).read( + 0, 0, limit=-1 + ), + ), + ( + "ignore_trailing_zlib_data", + " if (len(data) != segment.stored or not decoder.eof or decoder.unused_data\n", + " if (len(data) != segment.stored or not decoder.eof\n", + lambda mod: mod.PagedResource( + io.BytesIO(cmp_plus_trail), + [mod.Segment(0, len(cmp_plus_trail), len(payload), "zlib")], + ).read(0, len(payload)), + ), + ( + "ignore_raw_size_mismatch", + ' if physical_end > file_size or (segment.codec == "raw" and stored != size):\n', + " if physical_end > file_size:\n", + lambda mod: mod.PagedResource(io.BytesIO(b"abcd"), [mod.Segment(0, 4, 2, "raw")]), + ), + ) + + for label, target, replacement, trigger in mutations: + with self.subTest(mutation=label): + self.assertEqual(source.count(target), 1, target) + mod = types.ModuleType(f"paged_resource_mut_{label}") + mod.__file__ = str(TOOL) + sys.modules[mod.__name__] = mod + try: + exec(compile(source.replace(target, replacement, 1), str(TOOL), "exec"), mod.__dict__) + trigger(mod) + finally: + sys.modules.pop(mod.__name__, None) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/paged_resource.py b/tools/paged_resource.py index c80271e45..4d1ee1c26 100644 --- a/tools/paged_resource.py +++ b/tools/paged_resource.py @@ -5,6 +5,12 @@ import zlib +def _require_int(value: object, name: str) -> int: + if isinstance(value, bool) or not isinstance(value, int): + raise ValueError(f"{name} must be an integer") + return value + + @dataclass(frozen=True) class Segment: offset: int # Physical byte offset in the open file @@ -12,6 +18,11 @@ class Segment: size: int # Decoded bytes in logical order codec: str + def __post_init__(self) -> None: + _require_int(self.offset, "segment.offset") + _require_int(self.stored, "segment.stored") + _require_int(self.size, "segment.size") + class PagedResource: """The caller owns the binary file and supplies segments in logical order.""" @@ -23,13 +34,18 @@ def __init__(self, stream, segments): starts = [] physical_end = logical_end = 0 for segment in self.segments: - if segment.offset < physical_end or min(segment.stored, segment.size) <= 0: + offset = _require_int(segment.offset, "segment.offset") + stored = _require_int(segment.stored, "segment.stored") + size = _require_int(segment.size, "segment.size") + if not isinstance(segment.codec, str) or not segment.codec: + raise ValueError(f"Unsupported segment codec {segment.codec!r}") + if offset < physical_end or min(stored, size) <= 0: raise ValueError("Overlapping, descending or empty segment") - physical_end = segment.offset + segment.stored - if physical_end > file_size or (segment.codec == "raw" and segment.stored != segment.size): + physical_end = offset + stored + if physical_end > file_size or (segment.codec == "raw" and stored != size): raise ValueError("Segment extent disagrees with file or raw size") starts.append(logical_end) - logical_end += segment.size + logical_end += size self.starts = tuple(starts) self.size = logical_end @@ -47,7 +63,10 @@ def _read_at(self, offset: int, size: int) -> bytes: return bytes(data) def read(self, offset, length, *, limit=64 << 20): - if offset < 0 or length < 0 or length > limit or offset + length > self.size: + offset = _require_int(offset, "offset") + length = _require_int(length, "length") + limit = _require_int(limit, "limit") + if limit < 0 or offset < 0 or length < 0 or length > limit or offset + length > self.size: raise ValueError("Logical range outside resource or read budget") index = bisect_right(self.starts, offset) - 1 result = bytearray() From 22013b20654ec6218e49f310d6db2fcb2d7d8af2 Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Thu, 26 Nov 2026 05:18:30 +0200 Subject: [PATCH 110/240] cpu: add legacy SSE4.1 FP AOT lifter and test suite (#2691) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 34 ++ tests/cpu/sse41_fp_aot.asm | 527 +++++++++++++++++++++++ tests/cpu/sse41_fp_aot.def | 58 +++ tests/cpu/sse41_fp_aot_check.py | 549 ++++++++++++++++++++++++ tools/cpu_sse41_fp_aot.py | 716 ++++++++++++++++++++++++++++++++ 5 files changed, 1884 insertions(+) create mode 100644 tests/cpu/sse41_fp_aot.asm create mode 100644 tests/cpu/sse41_fp_aot.def create mode 100644 tests/cpu/sse41_fp_aot_check.py create mode 100644 tools/cpu_sse41_fp_aot.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 8990de64e..ff2cbb8e9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -7397,6 +7397,40 @@ if(EXISTS "${INTAKE_PYTHON}") check "$" "$") set_tests_properties(cpu_aot_sse34_fp PROPERTIES SKIP_RETURN_CODE 77) + # cpu_aot_sse41_fp + set(cpu_sse41_fp_aot_exports + "op_roundps_reg_0,op_roundps_reg_1,op_roundps_reg_2,op_roundps_reg_3,op_roundps_reg_4,op_roundps_reg_8," + "op_roundps_mem_rcx,op_roundps_mem_rdx,op_roundps_mem_r8," + "op_roundpd_reg_0,op_roundpd_reg_1,op_roundpd_reg_2,op_roundpd_reg_3,op_roundpd_reg_4," + "op_roundpd_mem_rcx,op_roundpd_mem_rdx,op_roundpd_mem_r8," + "op_roundss_reg_0,op_roundss_reg_1,op_roundss_reg_2,op_roundss_reg_3,op_roundss_reg_4," + "op_roundss_mem_rcx,op_roundss_mem_rdx,op_roundss_mem_r8," + "op_roundsd_reg_0,op_roundsd_reg_1,op_roundsd_reg_2,op_roundsd_reg_3,op_roundsd_reg_4," + "op_roundsd_mem_rcx,op_roundsd_mem_rdx,op_roundsd_mem_r8," + "op_dpps_reg_f1,op_dpps_reg_ff,op_dpps_reg_5a,op_dpps_reg_0f," + "op_dpps_mem_rcx,op_dpps_mem_rdx,op_dpps_mem_r8," + "op_dppd_reg_33,op_dppd_reg_11,op_dppd_reg_22,op_dppd_reg_03," + "op_dppd_mem_rcx,op_dppd_mem_rdx,op_dppd_mem_r8," + "op_insertps_reg_s1_d2_z5,op_insertps_reg_s3_d0_z0,op_insertps_reg_s0_d3_z8," + "op_insertps_mem_rcx,op_insertps_mem_rdx,op_insertps_mem_r8," + "op_extractps_r32_lane2,op_extractps_r64_lane3,op_extractps_mem_lane1," + "op_sse41_glue_pipeline") + string(CONCAT cpu_sse41_fp_aot_exports ${cpu_sse41_fp_aot_exports}) + foreach(variant IN ITEMS original altered) + cpu_asm_fixture(cpu_sse41_fp_aot_${variant} sse41_fp_aot) + cpu_translation(cpu_sse41_fp_aot_${variant} cpu_sse41_fp_aot "${cpu_sse41_fp_aot_exports}") + endforeach() + target_compile_definitions(cpu_sse41_fp_aot_altered PRIVATE ALTER_SSE41_FP) + add_test(NAME cpu_aot_sse41_fp COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/cpu/sse41_fp_aot_check.py" + "$" + "$" + "$" + "$") + set_tests_properties(cpu_aot_sse41_fp PROPERTIES + SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/cpu_aot_sse41_fp.txt") + cpu_asm_fixture(cpu_avx_packed_int avx_packed_int) set(avx_packed_int_fixture "${CMAKE_CURRENT_BINARY_DIR}/cpu_avx_packed_int_lifted.cpp") add_custom_command(OUTPUT "${avx_packed_int_fixture}" diff --git a/tests/cpu/sse41_fp_aot.asm b/tests/cpu/sse41_fp_aot.asm new file mode 100644 index 000000000..02d7d0f21 --- /dev/null +++ b/tests/cpu/sse41_fp_aot.asm @@ -0,0 +1,527 @@ +; coverage: record cpu_aot_sse41_fp +; Source-owned MASM fixture for legacy SSE4.1 floating-point instructions +; (roundps, roundpd, roundss, roundsd, dpps, dppd, insertps, extractps) +; across register and flat [rcx|rdx|r8] memory-source forms plus glue moves. +; ABI: void fn(const void* rcx, const void* rdx, void* r8). +.code + +; --- ROUNDPS (reg imm 0,1,2,3,4,8 & flat [rcx|rdx|r8] mem) --- +op_roundps_reg_0 PROC FRAME + .endprolog + movaps xmm1, XMMWORD PTR [rcx] + roundps xmm0, xmm1, 00h + movaps XMMWORD PTR [r8], xmm0 + ret +op_roundps_reg_0 ENDP + +op_roundps_reg_1 PROC FRAME + .endprolog + movaps xmm1, XMMWORD PTR [rcx] +IFDEF ALTER_SSE41_FP + roundps xmm0, xmm1, 02h +ELSE + roundps xmm0, xmm1, 01h +ENDIF + movaps XMMWORD PTR [r8], xmm0 + ret +op_roundps_reg_1 ENDP + +op_roundps_reg_2 PROC FRAME + .endprolog + movaps xmm1, XMMWORD PTR [rcx] + roundps xmm0, xmm1, 02h + movaps XMMWORD PTR [r8], xmm0 + ret +op_roundps_reg_2 ENDP + +op_roundps_reg_3 PROC FRAME + .endprolog + movaps xmm1, XMMWORD PTR [rcx] + roundps xmm0, xmm1, 03h + movaps XMMWORD PTR [r8], xmm0 + ret +op_roundps_reg_3 ENDP + +op_roundps_reg_4 PROC FRAME + .endprolog + movaps xmm1, XMMWORD PTR [rcx] + roundps xmm0, xmm1, 04h + movaps XMMWORD PTR [r8], xmm0 + ret +op_roundps_reg_4 ENDP + +op_roundps_reg_8 PROC FRAME + .endprolog + movaps xmm1, XMMWORD PTR [rcx] + roundps xmm0, xmm1, 08h + movaps XMMWORD PTR [r8], xmm0 + ret +op_roundps_reg_8 ENDP + +op_roundps_mem_rcx PROC FRAME + .endprolog + roundps xmm0, XMMWORD PTR [rcx], 01h + movaps XMMWORD PTR [r8], xmm0 + ret +op_roundps_mem_rcx ENDP + +op_roundps_mem_rdx PROC FRAME + .endprolog + roundps xmm0, XMMWORD PTR [rdx], 02h + movaps XMMWORD PTR [r8], xmm0 + ret +op_roundps_mem_rdx ENDP + +op_roundps_mem_r8 PROC FRAME + .endprolog + roundps xmm0, XMMWORD PTR [r8], 03h + movaps XMMWORD PTR [r8], xmm0 + ret +op_roundps_mem_r8 ENDP + +; --- ROUNDPD (reg imm 0,1,2,3,4 & flat [rcx|rdx|r8] mem) --- +op_roundpd_reg_0 PROC FRAME + .endprolog + movapd xmm1, XMMWORD PTR [rcx] + roundpd xmm0, xmm1, 00h + movapd XMMWORD PTR [r8], xmm0 + ret +op_roundpd_reg_0 ENDP + +op_roundpd_reg_1 PROC FRAME + .endprolog + movapd xmm1, XMMWORD PTR [rcx] + roundpd xmm0, xmm1, 01h + movapd XMMWORD PTR [r8], xmm0 + ret +op_roundpd_reg_1 ENDP + +op_roundpd_reg_2 PROC FRAME + .endprolog + movapd xmm1, XMMWORD PTR [rcx] +IFDEF ALTER_SSE41_FP + roundpd xmm0, xmm1, 01h +ELSE + roundpd xmm0, xmm1, 02h +ENDIF + movapd XMMWORD PTR [r8], xmm0 + ret +op_roundpd_reg_2 ENDP + +op_roundpd_reg_3 PROC FRAME + .endprolog + movapd xmm1, XMMWORD PTR [rcx] + roundpd xmm0, xmm1, 03h + movapd XMMWORD PTR [r8], xmm0 + ret +op_roundpd_reg_3 ENDP + +op_roundpd_reg_4 PROC FRAME + .endprolog + movapd xmm1, XMMWORD PTR [rcx] + roundpd xmm0, xmm1, 04h + movapd XMMWORD PTR [r8], xmm0 + ret +op_roundpd_reg_4 ENDP + +op_roundpd_mem_rcx PROC FRAME + .endprolog + roundpd xmm0, XMMWORD PTR [rcx], 00h + movapd XMMWORD PTR [r8], xmm0 + ret +op_roundpd_mem_rcx ENDP + +op_roundpd_mem_rdx PROC FRAME + .endprolog + roundpd xmm0, XMMWORD PTR [rdx], 01h + movapd XMMWORD PTR [r8], xmm0 + ret +op_roundpd_mem_rdx ENDP + +op_roundpd_mem_r8 PROC FRAME + .endprolog + roundpd xmm0, XMMWORD PTR [r8], 02h + movapd XMMWORD PTR [r8], xmm0 + ret +op_roundpd_mem_r8 ENDP + +; --- ROUNDSS (preserves dst[127:32], reg & flat [rcx|rdx|r8] m32) --- +op_roundss_reg_0 PROC FRAME + .endprolog + movups xmm0, XMMWORD PTR [rcx] + movups xmm1, XMMWORD PTR [rdx] +IFDEF ALTER_SSE41_FP + roundss xmm0, xmm1, 03h +ELSE + roundss xmm0, xmm1, 00h +ENDIF + movups XMMWORD PTR [r8], xmm0 + ret +op_roundss_reg_0 ENDP + +op_roundss_reg_1 PROC FRAME + .endprolog + movups xmm0, XMMWORD PTR [rcx] + movups xmm1, XMMWORD PTR [rdx] + roundss xmm0, xmm1, 01h + movups XMMWORD PTR [r8], xmm0 + ret +op_roundss_reg_1 ENDP + +op_roundss_reg_2 PROC FRAME + .endprolog + movups xmm0, XMMWORD PTR [rcx] + movups xmm1, XMMWORD PTR [rdx] + roundss xmm0, xmm1, 02h + movups XMMWORD PTR [r8], xmm0 + ret +op_roundss_reg_2 ENDP + +op_roundss_reg_3 PROC FRAME + .endprolog + movups xmm0, XMMWORD PTR [rcx] + movups xmm1, XMMWORD PTR [rdx] + roundss xmm0, xmm1, 03h + movups XMMWORD PTR [r8], xmm0 + ret +op_roundss_reg_3 ENDP + +op_roundss_reg_4 PROC FRAME + .endprolog + movups xmm0, XMMWORD PTR [rcx] + movups xmm1, XMMWORD PTR [rdx] + roundss xmm0, xmm1, 04h + movups XMMWORD PTR [r8], xmm0 + ret +op_roundss_reg_4 ENDP + +op_roundss_mem_rcx PROC FRAME + .endprolog + movups xmm0, XMMWORD PTR [rdx] + roundss xmm0, DWORD PTR [rcx], 01h + movups XMMWORD PTR [r8], xmm0 + ret +op_roundss_mem_rcx ENDP + +op_roundss_mem_rdx PROC FRAME + .endprolog + movups xmm0, XMMWORD PTR [rcx] + roundss xmm0, DWORD PTR [rdx], 02h + movups XMMWORD PTR [r8], xmm0 + ret +op_roundss_mem_rdx ENDP + +op_roundss_mem_r8 PROC FRAME + .endprolog + movups xmm0, XMMWORD PTR [rcx] + roundss xmm0, DWORD PTR [r8], 03h + movups XMMWORD PTR [r8], xmm0 + ret +op_roundss_mem_r8 ENDP + +; --- ROUNDSD (preserves dst[127:64], reg & flat [rcx|rdx|r8] m64) --- +op_roundsd_reg_0 PROC FRAME + .endprolog + movupd xmm0, XMMWORD PTR [rcx] + movupd xmm1, XMMWORD PTR [rdx] + roundsd xmm0, xmm1, 00h + movupd XMMWORD PTR [r8], xmm0 + ret +op_roundsd_reg_0 ENDP + +op_roundsd_reg_1 PROC FRAME + .endprolog + movupd xmm0, XMMWORD PTR [rcx] + movupd xmm1, XMMWORD PTR [rdx] + roundsd xmm0, xmm1, 01h + movupd XMMWORD PTR [r8], xmm0 + ret +op_roundsd_reg_1 ENDP + +op_roundsd_reg_2 PROC FRAME + .endprolog + movupd xmm0, XMMWORD PTR [rcx] + movupd xmm1, XMMWORD PTR [rdx] + roundsd xmm0, xmm1, 02h + movupd XMMWORD PTR [r8], xmm0 + ret +op_roundsd_reg_2 ENDP + +op_roundsd_reg_3 PROC FRAME + .endprolog + movupd xmm0, XMMWORD PTR [rcx] + movupd xmm1, XMMWORD PTR [rdx] +IFDEF ALTER_SSE41_FP + roundsd xmm0, xmm1, 02h +ELSE + roundsd xmm0, xmm1, 03h +ENDIF + movupd XMMWORD PTR [r8], xmm0 + ret +op_roundsd_reg_3 ENDP + +op_roundsd_reg_4 PROC FRAME + .endprolog + movupd xmm0, XMMWORD PTR [rcx] + movupd xmm1, XMMWORD PTR [rdx] + roundsd xmm0, xmm1, 04h + movupd XMMWORD PTR [r8], xmm0 + ret +op_roundsd_reg_4 ENDP + +op_roundsd_mem_rcx PROC FRAME + .endprolog + movupd xmm0, XMMWORD PTR [rdx] + roundsd xmm0, QWORD PTR [rcx], 01h + movupd XMMWORD PTR [r8], xmm0 + ret +op_roundsd_mem_rcx ENDP + +op_roundsd_mem_rdx PROC FRAME + .endprolog + movupd xmm0, XMMWORD PTR [rcx] + roundsd xmm0, QWORD PTR [rdx], 02h + movupd XMMWORD PTR [r8], xmm0 + ret +op_roundsd_mem_rdx ENDP + +op_roundsd_mem_r8 PROC FRAME + .endprolog + movupd xmm0, XMMWORD PTR [rcx] + roundsd xmm0, QWORD PTR [r8], 03h + movupd XMMWORD PTR [r8], xmm0 + ret +op_roundsd_mem_r8 ENDP + +; --- DPPS (reg & flat [rcx|rdx|r8] mem) --- +op_dpps_reg_f1 PROC FRAME + .endprolog + movaps xmm0, XMMWORD PTR [rcx] + movaps xmm1, XMMWORD PTR [rdx] + dpps xmm0, xmm1, 0F1h + movaps XMMWORD PTR [r8], xmm0 + ret +op_dpps_reg_f1 ENDP + +op_dpps_reg_ff PROC FRAME + .endprolog + movaps xmm0, XMMWORD PTR [rcx] + movaps xmm1, XMMWORD PTR [rdx] +IFDEF ALTER_SSE41_FP + dpps xmm0, xmm1, 055h +ELSE + dpps xmm0, xmm1, 0FFh +ENDIF + movaps XMMWORD PTR [r8], xmm0 + ret +op_dpps_reg_ff ENDP + +op_dpps_reg_5a PROC FRAME + .endprolog + movaps xmm0, XMMWORD PTR [rcx] + movaps xmm1, XMMWORD PTR [rdx] + dpps xmm0, xmm1, 05Ah + movaps XMMWORD PTR [r8], xmm0 + ret +op_dpps_reg_5a ENDP + +op_dpps_reg_0f PROC FRAME + .endprolog + movaps xmm0, XMMWORD PTR [rcx] + movaps xmm1, XMMWORD PTR [rdx] + dpps xmm0, xmm1, 00Fh + movaps XMMWORD PTR [r8], xmm0 + ret +op_dpps_reg_0f ENDP + +op_dpps_mem_rcx PROC FRAME + .endprolog + movaps xmm0, XMMWORD PTR [rdx] + dpps xmm0, XMMWORD PTR [rcx], 0F3h + movaps XMMWORD PTR [r8], xmm0 + ret +op_dpps_mem_rcx ENDP + +op_dpps_mem_rdx PROC FRAME + .endprolog + movaps xmm0, XMMWORD PTR [rcx] + dpps xmm0, XMMWORD PTR [rdx], 0C5h + movaps XMMWORD PTR [r8], xmm0 + ret +op_dpps_mem_rdx ENDP + +op_dpps_mem_r8 PROC FRAME + .endprolog + movaps xmm0, XMMWORD PTR [rcx] + dpps xmm0, XMMWORD PTR [r8], 0AAh + movaps XMMWORD PTR [r8], xmm0 + ret +op_dpps_mem_r8 ENDP + +; --- DPPD (reg & flat [rcx|rdx|r8] mem) --- +op_dppd_reg_33 PROC FRAME + .endprolog + movapd xmm0, XMMWORD PTR [rcx] + movapd xmm1, XMMWORD PTR [rdx] +IFDEF ALTER_SSE41_FP + dppd xmm0, xmm1, 011h +ELSE + dppd xmm0, xmm1, 033h +ENDIF + movapd XMMWORD PTR [r8], xmm0 + ret +op_dppd_reg_33 ENDP + +op_dppd_reg_11 PROC FRAME + .endprolog + movapd xmm0, XMMWORD PTR [rcx] + movapd xmm1, XMMWORD PTR [rdx] + dppd xmm0, xmm1, 011h + movapd XMMWORD PTR [r8], xmm0 + ret +op_dppd_reg_11 ENDP + +op_dppd_reg_22 PROC FRAME + .endprolog + movapd xmm0, XMMWORD PTR [rcx] + movapd xmm1, XMMWORD PTR [rdx] + dppd xmm0, xmm1, 022h + movapd XMMWORD PTR [r8], xmm0 + ret +op_dppd_reg_22 ENDP + +op_dppd_reg_03 PROC FRAME + .endprolog + movapd xmm0, XMMWORD PTR [rcx] + movapd xmm1, XMMWORD PTR [rdx] + dppd xmm0, xmm1, 003h + movapd XMMWORD PTR [r8], xmm0 + ret +op_dppd_reg_03 ENDP + +op_dppd_mem_rcx PROC FRAME + .endprolog + movapd xmm0, XMMWORD PTR [rdx] + dppd xmm0, XMMWORD PTR [rcx], 031h + movapd XMMWORD PTR [r8], xmm0 + ret +op_dppd_mem_rcx ENDP + +op_dppd_mem_rdx PROC FRAME + .endprolog + movapd xmm0, XMMWORD PTR [rcx] + dppd xmm0, XMMWORD PTR [rdx], 032h + movapd XMMWORD PTR [r8], xmm0 + ret +op_dppd_mem_rdx ENDP + +op_dppd_mem_r8 PROC FRAME + .endprolog + movapd xmm0, XMMWORD PTR [rcx] + dppd xmm0, XMMWORD PTR [r8], 023h + movapd XMMWORD PTR [r8], xmm0 + ret +op_dppd_mem_r8 ENDP + +; --- INSERTPS (reg count_s/count_d/zmask & flat [rcx|rdx|r8] m32) --- +op_insertps_reg_s1_d2_z5 PROC FRAME + .endprolog + movups xmm0, XMMWORD PTR [rcx] + movups xmm1, XMMWORD PTR [rdx] +IFDEF ALTER_SSE41_FP + insertps xmm0, xmm1, 060h +ELSE + insertps xmm0, xmm1, 065h +ENDIF + movups XMMWORD PTR [r8], xmm0 + ret +op_insertps_reg_s1_d2_z5 ENDP + +op_insertps_reg_s3_d0_z0 PROC FRAME + .endprolog + movups xmm0, XMMWORD PTR [rcx] + movups xmm1, XMMWORD PTR [rdx] + insertps xmm0, xmm1, 0C0h + movups XMMWORD PTR [r8], xmm0 + ret +op_insertps_reg_s3_d0_z0 ENDP + +op_insertps_reg_s0_d3_z8 PROC FRAME + .endprolog + movups xmm0, XMMWORD PTR [rcx] + movups xmm1, XMMWORD PTR [rdx] + insertps xmm0, xmm1, 038h + movups XMMWORD PTR [r8], xmm0 + ret +op_insertps_reg_s0_d3_z8 ENDP + +op_insertps_mem_rcx PROC FRAME + .endprolog + movups xmm0, XMMWORD PTR [rdx] + insertps xmm0, DWORD PTR [rcx], 0D2h + movups XMMWORD PTR [r8], xmm0 + ret +op_insertps_mem_rcx ENDP + +op_insertps_mem_rdx PROC FRAME + .endprolog + movups xmm0, XMMWORD PTR [rcx] + insertps xmm0, DWORD PTR [rdx], 0E4h + movups XMMWORD PTR [r8], xmm0 + ret +op_insertps_mem_rdx ENDP + +op_insertps_mem_r8 PROC FRAME + .endprolog + movups xmm0, XMMWORD PTR [rcx] + insertps xmm0, DWORD PTR [r8], 091h + movups XMMWORD PTR [r8], xmm0 + ret +op_insertps_mem_r8 ENDP + +; --- EXTRACTPS (r32 zero-extend, r64 zero-extend, and m32 [r8]) --- +op_extractps_r32_lane2 PROC FRAME + .endprolog + movdqa xmm0, XMMWORD PTR [rcx] + mov rax, QWORD PTR [rdx] +IFDEF ALTER_SSE41_FP + extractps eax, xmm0, 01h +ELSE + extractps eax, xmm0, 02h +ENDIF + mov QWORD PTR [r8], rax + ret +op_extractps_r32_lane2 ENDP + +op_extractps_r64_lane3 PROC FRAME + .endprolog + movdqa xmm0, XMMWORD PTR [rcx] + mov r9, QWORD PTR [rdx] + db 66h, 49h, 0Fh, 3Ah, 17h, 0C1h, 03h ; extractps r9, xmm0, 03h (REX.W) + mov QWORD PTR [r8], r9 + ret +op_extractps_r64_lane3 ENDP + +op_extractps_mem_lane1 PROC FRAME + .endprolog + movdqu xmm0, XMMWORD PTR [rcx] + extractps DWORD PTR [r8], xmm0, 01h + ret +op_extractps_mem_lane1 ENDP + +; --- Glue transport pipeline --- +op_sse41_glue_pipeline PROC FRAME + .endprolog + movss xmm0, DWORD PTR [rcx] + movsd xmm1, QWORD PTR [rdx] + movdqa xmm2, XMMWORD PTR [rcx] + movdqu xmm3, XMMWORD PTR [rdx] + movss xmm2, xmm1 + movsd xmm3, xmm0 + roundps xmm4, xmm2, 01h + insertps xmm4, xmm3, 052h + movupd XMMWORD PTR [r8], xmm4 + ret +op_sse41_glue_pipeline ENDP + +END diff --git a/tests/cpu/sse41_fp_aot.def b/tests/cpu/sse41_fp_aot.def new file mode 100644 index 000000000..0a8c0d674 --- /dev/null +++ b/tests/cpu/sse41_fp_aot.def @@ -0,0 +1,58 @@ +EXPORTS + op_roundps_reg_0 + op_roundps_reg_1 + op_roundps_reg_2 + op_roundps_reg_3 + op_roundps_reg_4 + op_roundps_reg_8 + op_roundps_mem_rcx + op_roundps_mem_rdx + op_roundps_mem_r8 + op_roundpd_reg_0 + op_roundpd_reg_1 + op_roundpd_reg_2 + op_roundpd_reg_3 + op_roundpd_reg_4 + op_roundpd_mem_rcx + op_roundpd_mem_rdx + op_roundpd_mem_r8 + op_roundss_reg_0 + op_roundss_reg_1 + op_roundss_reg_2 + op_roundss_reg_3 + op_roundss_reg_4 + op_roundss_mem_rcx + op_roundss_mem_rdx + op_roundss_mem_r8 + op_roundsd_reg_0 + op_roundsd_reg_1 + op_roundsd_reg_2 + op_roundsd_reg_3 + op_roundsd_reg_4 + op_roundsd_mem_rcx + op_roundsd_mem_rdx + op_roundsd_mem_r8 + op_dpps_reg_f1 + op_dpps_reg_ff + op_dpps_reg_5a + op_dpps_reg_0f + op_dpps_mem_rcx + op_dpps_mem_rdx + op_dpps_mem_r8 + op_dppd_reg_33 + op_dppd_reg_11 + op_dppd_reg_22 + op_dppd_reg_03 + op_dppd_mem_rcx + op_dppd_mem_rdx + op_dppd_mem_r8 + op_insertps_reg_s1_d2_z5 + op_insertps_reg_s3_d0_z0 + op_insertps_reg_s0_d3_z8 + op_insertps_mem_rcx + op_insertps_mem_rdx + op_insertps_mem_r8 + op_extractps_r32_lane2 + op_extractps_r64_lane3 + op_extractps_mem_lane1 + op_sse41_glue_pipeline diff --git a/tests/cpu/sse41_fp_aot_check.py b/tests/cpu/sse41_fp_aot_check.py new file mode 100644 index 000000000..4fbf408e0 --- /dev/null +++ b/tests/cpu/sse41_fp_aot_check.py @@ -0,0 +1,549 @@ +"""Differential, MXCSR, refusal, CLI, and coverage checks for legacy SSE4.1 FP AOT.""" + +import ctypes +from fractions import Fraction +import math +import os +from pathlib import Path +import struct +import sys +from tempfile import TemporaryDirectory + +from iced_x86 import ( + Code, + Decoder, + Encoder, + Instruction, + MemoryOperand, + Mnemonic, + Register as R, +) +import pefile + +THIS_DIR = Path(__file__).resolve().parent +TOOLS_DIR = THIS_DIR.parents[1] / "tools" +sys.path.insert(0, str(THIS_DIR)) +sys.path.insert(0, str(TOOLS_DIR)) + +from cpu_leaf_aot import bounded_code, export_rva # noqa: E402 +from cpu_sse41_fp_aot import lift_code, main as tool_main, translate # noqa: E402 +from sse34_fp import F32, F64, _dp_allowed, _guarded_buf, _round_nearest_even # noqa: E402 + + +EXPORTS = ( + "op_roundps_reg_0", "op_roundps_reg_1", "op_roundps_reg_2", "op_roundps_reg_3", + "op_roundps_reg_4", "op_roundps_reg_8", + "op_roundps_mem_rcx", "op_roundps_mem_rdx", "op_roundps_mem_r8", + "op_roundpd_reg_0", "op_roundpd_reg_1", "op_roundpd_reg_2", "op_roundpd_reg_3", + "op_roundpd_reg_4", + "op_roundpd_mem_rcx", "op_roundpd_mem_rdx", "op_roundpd_mem_r8", + "op_roundss_reg_0", "op_roundss_reg_1", "op_roundss_reg_2", "op_roundss_reg_3", + "op_roundss_reg_4", + "op_roundss_mem_rcx", "op_roundss_mem_rdx", "op_roundss_mem_r8", + "op_roundsd_reg_0", "op_roundsd_reg_1", "op_roundsd_reg_2", "op_roundsd_reg_3", + "op_roundsd_reg_4", + "op_roundsd_mem_rcx", "op_roundsd_mem_rdx", "op_roundsd_mem_r8", + "op_dpps_reg_f1", "op_dpps_reg_ff", "op_dpps_reg_5a", "op_dpps_reg_0f", + "op_dpps_mem_rcx", "op_dpps_mem_rdx", "op_dpps_mem_r8", + "op_dppd_reg_33", "op_dppd_reg_11", "op_dppd_reg_22", "op_dppd_reg_03", + "op_dppd_mem_rcx", "op_dppd_mem_rdx", "op_dppd_mem_r8", + "op_insertps_reg_s1_d2_z5", "op_insertps_reg_s3_d0_z0", "op_insertps_reg_s0_d3_z8", + "op_insertps_mem_rcx", "op_insertps_mem_rdx", "op_insertps_mem_r8", + "op_extractps_r32_lane2", "op_extractps_r64_lane3", "op_extractps_mem_lane1", + "op_sse41_glue_pipeline", +) + +ALTERED_EXPORTS = ( + "op_roundps_reg_1", + "op_roundpd_reg_2", + "op_roundss_reg_0", + "op_roundsd_reg_3", + "op_dpps_reg_ff", + "op_dppd_reg_33", + "op_insertps_reg_s1_d2_z5", + "op_extractps_r32_lane2", +) + +SEED = bytes(0xB0 + (i % 16) for i in range(16)) +MXCSR_MODES = (0x1F80, 0x3F80, 0x5F80, 0x7F80, 0x1FC0, 0x9F80, 0x9FC0) + + +def encode_seq(*instructions): + encoder = Encoder(64) + rip = 0x1000 + for ins in instructions: + rip += encoder.encode(ins, rip) + return encoder.take_buffer() + + +def _u32s(buf: bytes) -> tuple[int, ...]: + return struct.unpack("<4I", buf[:16]) + + +def _u64s(buf: bytes) -> tuple[int, ...]: + return struct.unpack("<2Q", buf[:16]) + + +def _p32s(vals) -> bytes: + return struct.pack("<4I", *vals) + + +def _p64s(vals) -> bytes: + return struct.pack("<2Q", *vals) + + +def _round_ref(fmt, raw: int, imm: int, mxcsr: int) -> int: + if fmt.is_nan(raw): + return fmt.quiet(raw) + if fmt.is_inf(raw) or fmt.is_zero(raw): + return raw + sa, exp, _ = fmt.unpack(raw) + daz = bool(mxcsr & 0x0040) + if daz and exp == 0: + return fmt.sign_mask if sa else 0 + mode = ((mxcsr >> 13) & 3) if (imm & 4) else (imm & 3) + f = fmt.to_fraction(raw) + if mode == 0: + n = _round_nearest_even(f) + elif mode == 1: + n = math.floor(f) + elif mode == 2: + n = math.ceil(f) + else: + n = int(f) + return fmt.from_fraction(Fraction(n, 1), zero_sign=sa) + + +def _insertps_ref(dst_bytes: bytes, src_bytes: bytes, imm: int, *, mem: bool) -> bytes: + xa = list(_u32s(dst_bytes)) + val = _u32s(src_bytes)[0 if mem else ((imm >> 6) & 3)] + xa[(imm >> 4) & 3] = val + for k in range(4): + if (imm >> k) & 1: + xa[k] = 0 + return _p32s(xa) + + +def ref_export(name: str, a: bytes, b: bytes, seed: bytes, mxcsr: int, *, altered: bool = False) -> bytes: + if name.startswith("op_roundps_"): + if name == "op_roundps_mem_rcx": + src, imm = a, 1 + elif name == "op_roundps_mem_rdx": + src, imm = b, 2 + elif name == "op_roundps_mem_r8": + src, imm = seed, 3 + else: + imm = 2 if (altered and name == "op_roundps_reg_1") else int(name.split("_")[-1]) + src = a + return _p32s(_round_ref(F32, x, imm, mxcsr) for x in _u32s(src)) + + if name.startswith("op_roundpd_"): + if name == "op_roundpd_mem_rcx": + src, imm = a, 0 + elif name == "op_roundpd_mem_rdx": + src, imm = b, 1 + elif name == "op_roundpd_mem_r8": + src, imm = seed, 2 + else: + imm = 1 if (altered and name == "op_roundpd_reg_2") else int(name.split("_")[-1]) + src = a + return _p64s(_round_ref(F64, x, imm, mxcsr) for x in _u64s(src)) + + if name.startswith("op_roundss_"): + if name == "op_roundss_mem_rcx": + dst, src, imm = b, a, 1 + elif name == "op_roundss_mem_rdx": + dst, src, imm = a, b, 2 + elif name == "op_roundss_mem_r8": + dst, src, imm = a, seed, 3 + else: + imm = 3 if (altered and name == "op_roundss_reg_0") else int(name.split("_")[-1]) + dst, src = a, b + out = list(_u32s(dst)) + out[0] = _round_ref(F32, _u32s(src)[0], imm, mxcsr) + return _p32s(out) + + if name.startswith("op_roundsd_"): + if name == "op_roundsd_mem_rcx": + dst, src, imm = b, a, 1 + elif name == "op_roundsd_mem_rdx": + dst, src, imm = a, b, 2 + elif name == "op_roundsd_mem_r8": + dst, src, imm = a, seed, 3 + else: + imm = 2 if (altered and name == "op_roundsd_reg_3") else int(name.split("_")[-1]) + dst, src = a, b + out = list(_u64s(dst)) + out[0] = _round_ref(F64, _u64s(src)[0], imm, mxcsr) + return _p64s(out) + + if name.startswith("op_insertps_"): + imms = { + "op_insertps_reg_s1_d2_z5": (a, b, 0x60 if altered else 0x65, False), + "op_insertps_reg_s3_d0_z0": (a, b, 0xC0, False), + "op_insertps_reg_s0_d3_z8": (a, b, 0x38, False), + "op_insertps_mem_rcx": (b, a, 0xD2, True), + "op_insertps_mem_rdx": (a, b, 0xE4, True), + "op_insertps_mem_r8": (a, seed, 0x91, True), + } + dst, src, imm, is_mem = imms[name] + return _insertps_ref(dst, src, imm, mem=is_mem) + + if name == "op_extractps_r32_lane2": + lane = 1 if altered else 2 + return struct.pack(" None: + imms = { + "op_dpps_reg_f1": (a, b, 0xF1), + "op_dpps_reg_ff": (a, b, 0x55 if altered else 0xFF), + "op_dpps_reg_5a": (a, b, 0x5A), + "op_dpps_reg_0f": (a, b, 0x0F), + "op_dpps_mem_rcx": (b, a, 0xF3), + "op_dpps_mem_rdx": (a, b, 0xC5), + "op_dpps_mem_r8": (a, seed, 0xAA), + "op_dppd_reg_33": (a, b, 0x11 if altered else 0x33), + "op_dppd_reg_11": (a, b, 0x11), + "op_dppd_reg_22": (a, b, 0x22), + "op_dppd_reg_03": (a, b, 0x03), + "op_dppd_mem_rcx": (b, a, 0x31), + "op_dppd_mem_rdx": (a, b, 0x32), + "op_dppd_mem_r8": (a, seed, 0x23), + } + x, y, imm = imms[name] + is_pd = name.startswith("op_dppd_") + fmt, unpack, lanes = (F64, _u64s, 2) if is_pd else (F32, _u32s, 4) + allowed = _dp_allowed(fmt, unpack(x), unpack(y), imm) + for label, got in (("native", got_n), ("lifted", got_l)): + words = unpack(got) + for k in range(lanes): + if not ((imm >> k) & 1) and words[k] != 0: + raise AssertionError(f"{name} ({label}): disabled lane {k} is {words[k]:#x}, expected +0.0") + enabled = {words[k] for k in range(lanes) if (imm >> k) & 1} + if mxcsr == 0x1F80 and not enabled <= allowed: + raise AssertionError(f"{name} ({label}): {enabled} not in {sorted(allowed)}") + # Where the architectural reduction set has a single value (including single-NaN, +/-Inf, + # signed zero, normal, and non-associative finite cancellation), require bit-for-bit equality. + if len(allowed) == 1 and got_n != got_l: + raise AssertionError(f"{name} mxcsr={mxcsr:#x}: native={got_n.hex()} != lifted={got_l.hex()}") + + +def check_translator(original_path: Path) -> None: + source_cpp, meta = translate(original_path, EXPORTS) + assert len(meta) == len(EXPORTS) and "host_has_sse41" in source_cpp, len(meta) + assert "" not in source_cpp and "" not in source_cpp + + ld_xmm0 = Instruction.create_reg_mem(Code.MOVAPS_XMM_XMMM128, R.XMM0, MemoryOperand(R.RCX)) + ld_xmm1 = Instruction.create_reg_mem(Code.MOVAPS_XMM_XMMM128, R.XMM1, MemoryOperand(R.RDX)) + ld_xmm4 = Instruction.create_reg_mem(Code.MOVDQU_XMM_XMMM128, R.XMM4, MemoryOperand(R.RCX)) + ld_xmm5 = Instruction.create_reg_mem(Code.MOVDQU_XMM_XMMM128, R.XMM5, MemoryOperand(R.RDX)) + st_xmm0 = Instruction.create_mem_reg(Code.MOVAPS_XMMM128_XMM, MemoryOperand(R.R8), R.XMM0) + st_xmm4 = Instruction.create_mem_reg(Code.MOVAPS_XMMM128_XMM, MemoryOperand(R.R8), R.XMM4) + ret_ins = Instruction.create(Code.RETNQ) + + accepted = 0 + for code, helper, needs_dst, mem_size in ( + (Code.ROUNDPS_XMM_XMMM128_IMM8, "op_roundps", False, 16), + (Code.ROUNDPD_XMM_XMMM128_IMM8, "op_roundpd", False, 16), + (Code.ROUNDSS_XMM_XMMM32_IMM8, "op_roundss", True, 4), + (Code.ROUNDSD_XMM_XMMM64_IMM8, "op_roundsd", True, 8), + (Code.DPPS_XMM_XMMM128_IMM8, "op_dpps", True, 16), + (Code.DPPD_XMM_XMMM128_IMM8, "op_dppd", True, 16), + (Code.INSERTPS_XMM_XMMM32_IMM8, "op_insertps", True, 4), + ): + loads = (ld_xmm4, ld_xmm5) if needs_dst else (ld_xmm5,) + reg_src, _ = lift_code( + f"{helper}_reg", + 0x1000, + encode_seq( + *loads, + Instruction.create_reg_reg_u32(code, R.XMM4, R.XMM5, 0x54), + st_xmm4, + ret_ins, + ), + ) + assert f"{helper}(" in reg_src, reg_src + accepted += 1 + + for base in (R.RCX, R.RDX, R.R8): + mem_loads = (ld_xmm4,) if needs_dst else () + mem_src, _ = lift_code( + f"{helper}_mem_{base}", + 0x1000, + encode_seq( + *mem_loads, + Instruction.create_reg_mem_u32(code, R.XMM4, MemoryOperand(base), 0x11), + st_xmm4, + ret_ins, + ), + ) + loader = {4: "load32", 8: "load64", 16: "load128"}[mem_size] + assert f"{loader}(" in mem_src, mem_src + accepted += 1 + + # Alternate EXTRACTPS (r32/r64/m32) and MOVSS/MOVSD 0F11 encodings. + for label, seq, frag in ( + ("ext_r32", (ld_xmm4, Instruction.create_reg_reg_u32(Code.EXTRACTPS_RM32_XMM_IMM8, R.R10D, R.XMM4, 2), Instruction.create_mem_reg(Code.MOV_RM64_R64, MemoryOperand(R.R8), R.R10), ret_ins), "r10 = static_cast(lane32(xmm4, 2u));"), + ("ext_r64", (ld_xmm4, Instruction.create_reg_reg_u32(Code.EXTRACTPS_R64M32_XMM_IMM8, R.R11, R.XMM4, 3), Instruction.create_mem_reg(Code.MOV_RM64_R64, MemoryOperand(R.R8), R.R11), ret_ins), "r11 = static_cast(lane32(xmm4, 3u));"), + ("ext_m32", (ld_xmm4, Instruction.create_mem_reg_u32(Code.EXTRACTPS_RM32_XMM_IMM8, MemoryOperand(R.R8), R.XMM4, 1), ret_ins), "store32(r8, lane32(xmm4, 1u));"), + ("movss_0f11", (ld_xmm4, ld_xmm5, Instruction.create_reg_reg(Code.MOVSS_XMMM32_XMM, R.XMM4, R.XMM5), st_xmm4, ret_ins), "set_lane32(xmm4, 0u, lane32(xmm5, 0u));"), + ("movsd_0f11", (ld_xmm4, ld_xmm5, Instruction.create_reg_reg(Code.MOVSD_XMMM64_XMM, R.XMM4, R.XMM5), st_xmm4, ret_ins), "xmm4.q[0] = xmm5.q[0];"), + ): + src, _ = lift_code(label, 0x1000, encode_seq(*seq)) + assert frag in src, src + accepted += 1 + + seg_ins = Instruction.create_reg_mem_u32(Code.ROUNDPS_XMM_XMMM128_IMM8, R.XMM0, MemoryOperand(R.RCX), 0) + seg_ins.segment_prefix = R.GS + + rejects = [ + ("vex_vroundps", (ld_xmm1, Instruction.create_reg_reg_u32(Code.VEX_VROUNDPS_XMM_XMMM128_IMM8, R.XMM0, R.XMM1, 0), ret_ins), "non-legacy encoding"), + ("vex_vdpps", (ld_xmm0, ld_xmm1, Instruction.create_reg_reg_reg_u32(Code.VEX_VDPPS_XMM_XMM_XMMM128_IMM8, R.XMM0, R.XMM0, R.XMM1, 0xFF), ret_ins), "non-legacy encoding"), + ("vex_vinsertps", (ld_xmm0, ld_xmm1, Instruction.create_reg_reg_reg_u32(Code.VEX_VINSERTPS_XMM_XMM_XMMM32_IMM8, R.XMM0, R.XMM0, R.XMM1, 0), ret_ins), "non-legacy encoding"), + ("vex_vextractps", (ld_xmm0, Instruction.create_reg_reg_u32(Code.VEX_VEXTRACTPS_RM32_XMM_IMM8, R.EAX, R.XMM0, 0), ret_ins), "non-legacy encoding"), + ("evex_vmovaps", (Instruction.create_reg_mem(Code.EVEX_VMOVAPS_XMM_K1Z_XMMM128, R.XMM0, MemoryOperand(R.RCX)), ret_ins), "non-legacy encoding"), + ("unsupported_addps", (ld_xmm0, ld_xmm1, Instruction.create_reg_reg(Code.ADDPS_XMM_XMMM128, R.XMM0, R.XMM1), ret_ins), "unsupported instruction"), + ("unsupported_blendps", (ld_xmm0, ld_xmm1, Instruction.create_reg_reg_u32(Code.BLENDPS_XMM_XMMM128_IMM8, R.XMM0, R.XMM1, 1), ret_ins), "unsupported instruction"), + ("nonvol_xmm6_roundps", (ld_xmm1, Instruction.create_reg_reg_u32(Code.ROUNDPS_XMM_XMMM128_IMM8, R.XMM6, R.XMM1, 0), ret_ins), "nonvolatile vector register"), + ("nonvol_xmm15_dpps", (ld_xmm0, Instruction.create_reg_reg_u32(Code.DPPS_XMM_XMMM128_IMM8, R.XMM0, R.XMM15, 0xFF), ret_ins), "nonvolatile vector register"), + ("nonvol_xmm8_extractps", (Instruction.create_reg_reg_u32(Code.EXTRACTPS_RM32_XMM_IMM8, R.EAX, R.XMM8, 0), ret_ins), "nonvolatile vector register"), + ("nonvol_rbx_extractps", (ld_xmm0, Instruction.create_reg_reg_u32(Code.EXTRACTPS_R64M32_XMM_IMM8, R.RBX, R.XMM0, 0), ret_ins), "nonvolatile GPR"), + ("arg_write_rcx_extractps", (ld_xmm0, Instruction.create_reg_reg_u32(Code.EXTRACTPS_R64M32_XMM_IMM8, R.RCX, R.XMM0, 0), ret_ins), "write to argument GPR"), + ("arg_write_rdx_mov", (Instruction.create_reg_mem(Code.MOV_R64_RM64, R.RDX, MemoryOperand(R.RCX)), ret_ins), "write to argument GPR"), + ("undef_roundss_dst", (ld_xmm1, Instruction.create_reg_reg_u32(Code.ROUNDSS_XMM_XMMM32_IMM8, R.XMM0, R.XMM1, 0), ret_ins), "undefined vector register xmm0"), + ("undef_roundsd_dst", (ld_xmm1, Instruction.create_reg_reg_u32(Code.ROUNDSD_XMM_XMMM64_IMM8, R.XMM0, R.XMM1, 0), ret_ins), "undefined vector register xmm0"), + ("undef_dpps_dst", (ld_xmm1, Instruction.create_reg_reg_u32(Code.DPPS_XMM_XMMM128_IMM8, R.XMM0, R.XMM1, 0xFF), ret_ins), "undefined vector register xmm0"), + ("undef_insertps_src", (ld_xmm0, Instruction.create_reg_reg_u32(Code.INSERTPS_XMM_XMMM32_IMM8, R.XMM0, R.XMM3, 0), ret_ins), "undefined vector register xmm3"), + ("undef_extractps_src", (Instruction.create_reg_reg_u32(Code.EXTRACTPS_RM32_XMM_IMM8, R.EAX, R.XMM2, 0), ret_ins), "undefined vector register xmm2"), + ("undef_gpr_store", (Instruction.create_mem_reg(Code.MOV_RM64_R64, MemoryOperand(R.R8), R.RAX), ret_ins), "undefined GPR rax"), + ("disp_mem_rcx", (Instruction.create_reg_mem_u32(Code.ROUNDPS_XMM_XMMM128_IMM8, R.XMM0, MemoryOperand(R.RCX, displ=16, displ_size=1), 0), ret_ins), "unsupported memory operand"), + ("indexed_mem", (ld_xmm0, Instruction.create_reg_mem_u32(Code.DPPS_XMM_XMMM128_IMM8, R.XMM0, MemoryOperand(R.RDX, R.RCX, 4), 0xFF), ret_ins), "unsupported memory operand"), + ("rip_rel_mem", (ld_xmm0, Instruction.create_reg_mem_u32(Code.INSERTPS_XMM_XMMM32_IMM8, R.XMM0, MemoryOperand(R.RIP, displ=0x1040, displ_size=4), 0), ret_ins), "unsupported memory operand"), + ("nonvol_base_rbx", (Instruction.create_reg_mem_u32(Code.ROUNDPD_XMM_XMMM128_IMM8, R.XMM0, MemoryOperand(R.RBX), 0), ret_ins), "nonvolatile GPR base"), + ("non_arg_base_rax", (Instruction.create_reg_mem_u32(Code.ROUNDPS_XMM_XMMM128_IMM8, R.XMM0, MemoryOperand(R.RAX), 0), ret_ins), "unsupported memory base"), + ("addr32_ecx", (ld_xmm0, Instruction.create_reg_mem_u32(Code.ROUNDSS_XMM_XMMM32_IMM8, R.XMM0, MemoryOperand(R.ECX), 0), ret_ins), "unsupported memory operand"), + ("non_r8_store_extractps", (ld_xmm0, Instruction.create_mem_reg_u32(Code.EXTRACTPS_RM32_XMM_IMM8, MemoryOperand(R.RDX), R.XMM0, 0), ret_ins), "non-r8 store memory operand"), + ("non_r8_store_movaps", (ld_xmm0, Instruction.create_mem_reg(Code.MOVAPS_XMMM128_XMM, MemoryOperand(R.RCX), R.XMM0), ret_ins), "non-r8 store memory operand"), + ("non_r8_store_gpr", (ld_xmm0, Instruction.create_reg_reg_u32(Code.EXTRACTPS_RM32_XMM_IMM8, R.EAX, R.XMM0, 0), Instruction.create_mem_reg(Code.MOV_RM32_R32, MemoryOperand(R.RDX), R.EAX), ret_ins), "non-r8 store memory operand"), + ("seg_prefix", (seg_ins, ret_ins), "unsupported instruction prefix"), + ("missing_ret", (ld_xmm0, st_xmm0), "missing terminal ret"), + ("after_ret", (ld_xmm0, ret_ins, st_xmm0), "unreachable instruction after ret"), + ] + for label, seq, reason in rejects: + try: + lift_code(label, 0x1000, encode_seq(*seq)) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: translator accepted invalid sequence") + + for label, raw, reason in ( + ("invalid_bytes", b"\xFF\xFE\xC3", "invalid instruction"), + ("empty_stream", b"", "truncated instruction stream"), + ): + try: + lift_code(label, 0x1000, raw) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: raw stream unexpectedly accepted") + + with TemporaryDirectory() as tmp: + root = Path(tmp) + out_cpp = root / "out.cpp" + out_dir = root / "out_dir" + out_dir.mkdir() + in_dir = root / "in_dir" + in_dir.mkdir() + for argv in ( + [str(root / "missing.dll"), "op_roundps_reg_0", str(out_cpp)], + [str(in_dir), "op_roundps_reg_0", str(out_cpp)], + [str(original_path), ",", str(out_cpp)], + [str(original_path), "missing_export_xyz", str(out_cpp)], + [str(original_path), "op_roundps_reg_0", str(out_dir)], + ): + try: + tool_main(argv) + except SystemExit as exc: + assert exc.code == 1, (argv, exc.code) + else: + raise AssertionError(f"CLI did not exit for {argv}") + assert not out_cpp.exists() and sorted(p.name for p in root.iterdir()) == ["in_dir", "out_dir"] + + print( + f"translator validated: {accepted} forms accepted, " + f"{len(rejects) + 2} refusal controls and 5 CLI negative checks passed" + ) + + +def host_has_sse41(lifted_lib) -> bool: + if hasattr(lifted_lib, "host_has_sse41"): + lifted_lib.host_has_sse41.argtypes = [] + lifted_lib.host_has_sse41.restype = ctypes.c_uint32 + return bool(lifted_lib.host_has_sse41()) + return False + + +def check_differential(native_path: Path, lifted_path: Path, altered_path: Path, altered_lifted_path: Path) -> None: + native = ctypes.CDLL(str(native_path.resolve())) + lifted = ctypes.CDLL(str(lifted_path.resolve())) + altered_native = ctypes.CDLL(str(altered_path.resolve())) + altered_lifted = ctypes.CDLL(str(altered_lifted_path.resolve())) + + exchange = lifted.host_exchange_mxcsr + exchange.argtypes, exchange.restype = [ctypes.c_uint32], ctypes.c_uint32 + + def _f32(*vals): + words = [v if isinstance(v, int) else struct.unpack(" 0, f"altered {name} failed to diverge" + + print( + f"{cases} legacy SSE4.1 FP cases across {len(EXPORTS)} exports and {len(MXCSR_MODES)} MXCSR modes " + f"matched native DLL and IEEE-754 reference; {len(ALTERED_EXPORTS)} altered controls diverged" + ) + + +def record_covered_forms(original_path: Path) -> None: + record = os.environ.get("FORM_COVERAGE_RECORD") + if not record: + return + mnemonic_names = { + val: key.lower() + for key, val in vars(Mnemonic).items() + if not key.startswith("_") and isinstance(val, int) + } + forms = set() + with pefile.PE(str(original_path), fast_load=True) as pe: + for name in EXPORTS: + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + for ins in Decoder(64, raw, ip=entry): + forms.add(mnemonic_names[ins.mnemonic]) + out_path = Path(record) + out_path.parent.mkdir(parents=True, exist_ok=True) + out_path.write_text("".join(word + "\n" for word in sorted(forms)), encoding="utf-8") + + +def main() -> None: + if os.environ.get("FORM_COVERAGE_RECORD"): + Path(os.environ["FORM_COVERAGE_RECORD"]).unlink(missing_ok=True) + + original_path, lifted_path, altered_path, altered_lifted_path = (Path(p) for p in sys.argv[1:5]) + check_translator(original_path) + + lifted_lib = ctypes.CDLL(str(lifted_path.resolve())) + if not host_has_sse41(lifted_lib): + print("Host lacks CPUID.01H:ECX[19] (SSE4.1); skipping native differential check") + sys.exit(77) + + check_differential(original_path, lifted_path, altered_path, altered_lifted_path) + record_covered_forms(original_path) + + +if __name__ == "__main__": + main() diff --git a/tools/cpu_sse41_fp_aot.py b/tools/cpu_sse41_fp_aot.py new file mode 100644 index 000000000..e5c1ca2d1 --- /dev/null +++ b/tools/cpu_sse41_fp_aot.py @@ -0,0 +1,716 @@ +"""Lift bounded Windows x64 leaf functions with legacy SSE4.1 FP ops to C++. + +Each export uses the straight-line leaf ABI: + void lifted_(word rcx, word rdx, word r8) +where rcx, rdx, and r8 carry flat host pointers to caller-owned buffers. XMM0..XMM5 +are modeled as portable 128-bit value structs (two 64-bit lanes); volatile scratch +GPRs (rax, r9, r10, r11) are modeled as 64-bit words for EXTRACTPS and 32/64-bit +mov glue. + +Supported legacy SSE4.1 FP encodings (docs/coverage/x64_zen2.tsv group SSE3-4): + - ROUNDPS, ROUNDPD: imm8[1:0] when imm8[2]==0 else host MXCSR RC; handles -0.0, + +/-Inf, qNaN/sNaN quieting, and MXCSR DAZ. + - ROUNDSS, ROUNDSD: scalar rounding preserving destination bits [127:32]/[127:64]. + - DPPS, DPPD: dot product using source mask imm8[7:4]/[5:4] and destination mask + imm8[3:0]/[1:0] (disabled outputs set to +0.0), executing under host MXCSR + (rounding mode, DAZ, FTZ). + - INSERTPS: inserts count_s=imm8[7:6] from xmm (or lane 0 from m32) into + count_d=imm8[5:4] of dst, then applies zmask=imm8[3:0] last. + - EXTRACTPS: extracts lane imm8[1:0] to scratch r32/r64 (zero-extending [63:32]) + or flat m32 [r8]. + +Transport / ABI glue: + - MOVAPS, MOVAPD, MOVDQA (128-bit reg-reg, 16-byte-aligned flat loads & [r8] stores) + - MOVUPS, MOVUPD, MOVDQU (128-bit reg-reg, flat loads & [r8] stores) + - MOVSS, MOVSD (scalar load/store/reg-merge) + - MOV (32/64-bit scratch GPR reg-reg, flat load, [r8] store) and terminal RET. + +VEX/EVEX encodings, nonvolatile XMM6..15 / GPRs, writes to argument GPRs, undefined +reads, unaligned 128-bit aligned-only memory operands, non-flat memory operands, +non-[r8] stores, prefixes, branches, and trailing or missing ret are rejected. +""" + +import argparse +from pathlib import Path +import tempfile + +import pefile +from iced_x86 import ( + Code, + Decoder, + EncodingKind, + MemorySizeExt, + OpKind, + Register as R, + RegisterExt, +) + +from cpu_leaf_aot import bounded_code, export_rva + + +ARGUMENTS = {R.RCX: "rcx", R.RDX: "rdx", R.R8: "r8"} +ARGUMENT_GPRS = {R.RCX, R.ECX, R.CL, R.RDX, R.EDX, R.DL, R.R8, R.R8D, R.R8L} + +VOLATILE_XMM = {getattr(R, f"XMM{i}"): i for i in range(6)} +NONVOLATILE_VEC = ( + {getattr(R, f"XMM{i}") for i in range(6, 32)} + | {getattr(R, f"YMM{i}") for i in range(32)} + | {getattr(R, f"ZMM{i}") for i in range(32)} +) + +SCRATCH_GPR64 = {R.RAX: "rax", R.R9: "r9", R.R10: "r10", R.R11: "r11"} +SCRATCH_GPR32 = {R.EAX: "rax", R.R9D: "r9", R.R10D: "r10", R.R11D: "r11"} +NONVOLATILE_GPR = { + R.RBX, R.EBX, R.BX, R.BL, R.BH, + R.RBP, R.EBP, R.BP, R.BPL, + R.RSI, R.ESI, R.SI, R.SIL, + R.RDI, R.EDI, R.DI, R.DIL, + R.RSP, R.ESP, R.SP, R.SPL, + R.R12, R.R12D, R.R12W, R.R12L, + R.R13, R.R13D, R.R13W, R.R13L, + R.R14, R.R14D, R.R14W, R.R14L, + R.R15, R.R15D, R.R15W, R.R15L, +} + +LOAD_ALIGNED_VEC_CODES = { + Code.MOVAPS_XMM_XMMM128, + Code.MOVAPD_XMM_XMMM128, + Code.MOVDQA_XMM_XMMM128, +} +STORE_ALIGNED_VEC_CODES = { + Code.MOVAPS_XMMM128_XMM, + Code.MOVAPD_XMMM128_XMM, + Code.MOVDQA_XMMM128_XMM, +} +LOAD_UNALIGNED_VEC_CODES = { + Code.MOVUPS_XMM_XMMM128, + Code.MOVUPD_XMM_XMMM128, + Code.MOVDQU_XMM_XMMM128, +} +STORE_UNALIGNED_VEC_CODES = { + Code.MOVUPS_XMMM128_XMM, + Code.MOVUPD_XMMM128_XMM, + Code.MOVDQU_XMMM128_XMM, +} +MOVSS_REG_CODES = {Code.MOVSS_XMM_XMMM32, Code.MOVSS_XMMM32_XMM} +MOVSD_REG_CODES = {Code.MOVSD_XMM_XMMM64, Code.MOVSD_XMMM64_XMM} +EXTRACTPS_CODES = {Code.EXTRACTPS_RM32_XMM_IMM8, Code.EXTRACTPS_R64M32_XMM_IMM8} +MOV_GPR_CODES = { + Code.MOV_R32_RM32: False, + Code.MOV_RM32_R32: False, + Code.MOV_R64_RM64: True, + Code.MOV_RM64_R64: True, +} + +ALLOWED_CODES = { + Code.RETNQ, + Code.ROUNDPS_XMM_XMMM128_IMM8, + Code.ROUNDPD_XMM_XMMM128_IMM8, + Code.ROUNDSS_XMM_XMMM32_IMM8, + Code.ROUNDSD_XMM_XMMM64_IMM8, + Code.DPPS_XMM_XMMM128_IMM8, + Code.DPPD_XMM_XMMM128_IMM8, + Code.INSERTPS_XMM_XMMM32_IMM8, + *EXTRACTPS_CODES, + *LOAD_ALIGNED_VEC_CODES, + *STORE_ALIGNED_VEC_CODES, + *LOAD_UNALIGNED_VEC_CODES, + *STORE_UNALIGNED_VEC_CODES, + *MOVSS_REG_CODES, + *MOVSD_REG_CODES, + *MOV_GPR_CODES, +} + +PRELUDE = """#include +#include +#include +#include +#if defined(_MSC_VER) +#include +#define X2W_UNALIGNED __unaligned +#else +#define X2W_UNALIGNED +#endif + +using word = std::uint64_t; + +struct Vec128 { + std::uint64_t q[2]; +}; + +static inline std::uint32_t load32(word address) { + std::atomic_signal_fence(std::memory_order_seq_cst); + const std::uint32_t v = *reinterpret_cast(address); + std::atomic_signal_fence(std::memory_order_seq_cst); + return v; +} + +static inline std::uint64_t load64(word address) { + std::atomic_signal_fence(std::memory_order_seq_cst); + const std::uint64_t v = *reinterpret_cast(address); + std::atomic_signal_fence(std::memory_order_seq_cst); + return v; +} + +static inline Vec128 load128(word address) { + std::atomic_signal_fence(std::memory_order_seq_cst); + const auto* p = reinterpret_cast(address); + const std::uint64_t q0 = p[0]; + const std::uint64_t q1 = p[1]; + std::atomic_signal_fence(std::memory_order_seq_cst); + return {{q0, q1}}; +} + +static inline void store32(word address, std::uint32_t val) { + std::atomic_signal_fence(std::memory_order_seq_cst); + std::memcpy(reinterpret_cast(address), &val, 4); + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +static inline void store64(word address, std::uint64_t val) { + std::atomic_signal_fence(std::memory_order_seq_cst); + std::memcpy(reinterpret_cast(address), &val, 8); + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +static inline void store128(word address, const Vec128& v) { + std::atomic_signal_fence(std::memory_order_seq_cst); + std::memcpy(reinterpret_cast(address), v.q, 16); + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +static inline std::uint32_t lane32(const Vec128& v, unsigned i) { + return static_cast(v.q[i >> 1] >> ((i & 1u) * 32u)); +} + +static inline void set_lane32(Vec128& v, unsigned i, std::uint32_t val) { + const unsigned shift = (i & 1u) * 32u; + v.q[i >> 1] = (v.q[i >> 1] & ~(0xffffffffull << shift)) | (static_cast(val) << shift); +} + +static inline std::uint32_t round_mode(std::uint8_t imm8) { + if ((imm8 & 4u) == 0u) { + return static_cast(imm8 & 3u); + } + return (_mm_getcsr() >> 13u) & 3u; +} + +static inline std::int64_t round_double_to_int(double val, std::uint32_t rc) { + const std::int64_t t = static_cast(val); + const double tf = static_cast(t); + if (rc == 1u) { + return (tf > val) ? (t - 1) : t; + } + if (rc == 2u) { + return (tf < val) ? (t + 1) : t; + } + if (rc == 3u) { + return t; + } + const double rem = val - tf; + if (val >= 0.0) { + return (rem > 0.5 || (rem == 0.5 && (t & 1) != 0)) ? (t + 1) : t; + } + return (rem < -0.5 || (rem == -0.5 && (t & 1) != 0)) ? (t - 1) : t; +} + +static inline std::uint32_t round_f32_bits(std::uint32_t bits, std::uint8_t imm8) { + const volatile std::uint32_t vb = bits; + const std::uint32_t raw = vb; + const std::uint32_t abs_bits = raw & 0x7fffffffu; + const std::uint32_t sign_bit = raw & 0x80000000u; + if (abs_bits > 0x7f800000u) { + return raw | 0x00400000u; + } + if (abs_bits == 0x7f800000u || abs_bits == 0u) { + return raw; + } + if ((_mm_getcsr() & 0x0040u) != 0u && abs_bits < 0x00800000u) { + return sign_bit; + } + if (abs_bits >= 0x4b000000u) { + return raw; + } + float f = 0.0f; + std::memcpy(&f, &raw, 4); + const std::int64_t n = round_double_to_int(static_cast(f), round_mode(imm8)); + if (n == 0) { + return sign_bit; + } + const float out_f = static_cast(n); + std::uint32_t out_bits = 0u; + std::memcpy(&out_bits, &out_f, 4); + return out_bits; +} + +static inline std::uint64_t round_f64_bits(std::uint64_t bits, std::uint8_t imm8) { + const volatile std::uint64_t vb = bits; + const std::uint64_t raw = vb; + const std::uint64_t abs_bits = raw & 0x7fffffffffffffffull; + const std::uint64_t sign_bit = raw & 0x8000000000000000ull; + if (abs_bits > 0x7ff0000000000000ull) { + return raw | 0x0008000000000000ull; + } + if (abs_bits == 0x7ff0000000000000ull || abs_bits == 0ull) { + return raw; + } + if ((_mm_getcsr() & 0x0040u) != 0u && abs_bits < 0x0010000000000000ull) { + return sign_bit; + } + if (abs_bits >= 0x4330000000000000ull) { + return raw; + } + double d = 0.0; + std::memcpy(&d, &raw, 8); + const std::int64_t n = round_double_to_int(d, round_mode(imm8)); + if (n == 0) { + return sign_bit; + } + const double out_d = static_cast(n); + std::uint64_t out_bits = 0ull; + std::memcpy(&out_bits, &out_d, 8); + return out_bits; +} + +static inline Vec128 op_roundps(const Vec128& src, std::uint8_t imm8) { + Vec128 out{}; + for (unsigned i = 0; i < 4u; ++i) { + set_lane32(out, i, round_f32_bits(lane32(src, i), imm8)); + } + return out; +} + +static inline Vec128 op_roundpd(const Vec128& src, std::uint8_t imm8) { + return {{round_f64_bits(src.q[0], imm8), round_f64_bits(src.q[1], imm8)}}; +} + +static inline Vec128 op_roundss(const Vec128& dst, std::uint32_t src32, std::uint8_t imm8) { + Vec128 out = dst; + set_lane32(out, 0u, round_f32_bits(src32, imm8)); + return out; +} + +static inline Vec128 op_roundsd(const Vec128& dst, std::uint64_t src64, std::uint8_t imm8) { + return {{round_f64_bits(src64, imm8), dst.q[1]}}; +} + +static inline __m128 sse_ss_from_bits(std::uint32_t bits) { + const volatile std::uint32_t vb = bits; + return _mm_castsi128_ps(_mm_cvtsi32_si128(static_cast(vb))); +} + +static inline std::uint32_t bits_from_sse_ss(__m128 v) { + return static_cast(_mm_cvtsi128_si32(_mm_castps_si128(v))); +} + +static inline __m128d sse_sd_from_bits(std::uint64_t bits) { + const volatile std::uint64_t vb = bits; + return _mm_castsi128_pd(_mm_cvtsi64_si128(static_cast(vb))); +} + +static inline std::uint64_t bits_from_sse_sd(__m128d v) { + return static_cast(_mm_cvtsi128_si64(_mm_castpd_si128(v))); +} + +// DPPS executes products and pairwise sums via host SSE2 so MXCSR RC, DAZ, FTZ, +// +/-0.0, Inf, and NaN quieting match the host processor. +static inline Vec128 op_dpps(const Vec128& a, const Vec128& b, std::uint8_t imm8) { + __m128 t[4]; + for (unsigned k = 0; k < 4u; ++k) { + if ((imm8 & (1u << (4u + k))) != 0u) { + t[k] = _mm_mul_ss(sse_ss_from_bits(lane32(a, k)), sse_ss_from_bits(lane32(b, k))); + } else { + t[k] = _mm_setzero_ps(); + } + } + const __m128 s01 = _mm_add_ss(t[0], t[1]); + const __m128 s23 = _mm_add_ss(t[2], t[3]); + const std::uint32_t sum = bits_from_sse_ss(_mm_add_ss(s01, s23)); + Vec128 out{}; + for (unsigned k = 0; k < 4u; ++k) { + set_lane32(out, k, ((imm8 >> k) & 1u) != 0u ? sum : 0u); + } + return out; +} + +static inline Vec128 op_dppd(const Vec128& a, const Vec128& b, std::uint8_t imm8) { + __m128d t[2]; + for (unsigned k = 0; k < 2u; ++k) { + if ((imm8 & (1u << (4u + k))) != 0u) { + t[k] = _mm_mul_sd(sse_sd_from_bits(a.q[k]), sse_sd_from_bits(b.q[k])); + } else { + t[k] = _mm_setzero_pd(); + } + } + const std::uint64_t sum = bits_from_sse_sd(_mm_add_sd(t[0], t[1])); + return {{ + (imm8 & 1u) != 0u ? sum : 0ull, + (imm8 & 2u) != 0u ? sum : 0ull, + }}; +} + +static inline Vec128 op_insertps(const Vec128& dst, std::uint32_t src_lane, std::uint8_t imm8) { + Vec128 out = dst; + const unsigned count_d = (imm8 >> 4u) & 3u; + set_lane32(out, count_d, src_lane); + for (unsigned k = 0; k < 4u; ++k) { + if (((imm8 >> k) & 1u) != 0u) { + set_lane32(out, k, 0u); + } + } + return out; +} + +#if defined(_MSC_VER) +extern "C" __declspec(dllexport) std::uint32_t host_has_sse41() { + int info[4]{}; + __cpuid(info, 1); + return (info[2] & (1 << 19)) != 0 ? 1u : 0u; +} + +extern "C" __declspec(dllexport) std::uint32_t host_exchange_mxcsr(std::uint32_t next) { + const std::uint32_t current = _mm_getcsr(); + _mm_setcsr(next); + return current; +} +#endif +""" + + +def vec_index(register, ins): + """Map XMM0..XMM5 to an index, rejecting nonvolatile and unsupported registers.""" + if register in VOLATILE_XMM: + return VOLATILE_XMM[register] + if register in NONVOLATILE_VEC: + raise ValueError(f"nonvolatile vector register {register} at RVA {ins.ip:#x}: {ins}") + raise ValueError(f"unsupported vector register {register} at RVA {ins.ip:#x}: {ins}") + + +def gpr_target(register, ins, *, write=False): + """Map scratch GPR32/GPR64 to its 64-bit variable name, rejecting nonvolatile/arg writes.""" + if register in SCRATCH_GPR64: + return SCRATCH_GPR64[register] + if register in SCRATCH_GPR32: + return SCRATCH_GPR32[register] + if register in NONVOLATILE_GPR: + raise ValueError(f"nonvolatile GPR {register} at RVA {ins.ip:#x}: {ins}") + if write and register in ARGUMENT_GPRS: + raise ValueError(f"write to argument GPR {register} at RVA {ins.ip:#x}: {ins}") + raise ValueError(f"unsupported GPR {register} at RVA {ins.ip:#x}: {ins}") + + +def flat_address(ins, *, alignment=1, write=False, expected_size=None): + """Lower a flat zero-displacement [rcx|rdx|r8] pointer operand (stores restricted to [r8]).""" + base = ins.memory_base + if ( + ins.is_ip_rel_memory_operand + or base in (R.NONE, R.RIP, R.EIP, R.RSP, R.ESP) + or ins.memory_index != R.NONE + or ins.memory_displacement != 0 + or not RegisterExt.is_gpr64(base) + ): + raise ValueError(f"unsupported memory operand at RVA {ins.ip:#x}: {ins}") + if base in NONVOLATILE_GPR: + raise ValueError(f"nonvolatile GPR base {base} in memory operand at RVA {ins.ip:#x}: {ins}") + if base not in ARGUMENTS: + raise ValueError(f"unsupported memory base {base} at RVA {ins.ip:#x}: {ins}") + if write and base != R.R8: + raise ValueError(f"non-r8 store memory operand at RVA {ins.ip:#x}: {ins}") + if expected_size is not None and MemorySizeExt.size(ins.memory_size) != expected_size: + raise ValueError(f"unsupported memory size at RVA {ins.ip:#x}: {ins}") + if alignment > 1 and (ins.memory_displacement % alignment) != 0: + raise ValueError(f"unaligned {alignment}-byte memory operand at RVA {ins.ip:#x}: {ins}") + return ARGUMENTS[base] + + +def lift_code(name, start, raw): + """Decode and lift one bounded straight-line legacy SSE4.1 FP leaf function.""" + instructions = list(Decoder(64, raw, ip=start)) + if not instructions or instructions[-1].next_ip != start + len(raw): + raise ValueError(f"truncated instruction stream in {name} at RVA {start:#x}") + if any(ins.is_invalid for ins in instructions): + bad = next(ins for ins in instructions if ins.is_invalid) + raise ValueError(f"invalid instruction at RVA {bad.ip:#x}") + + used_vec = set() + defined_vec = set() + used_gpr = set() + defined_gpr = set() + statements = [] + returned = False + + def read_vec(op_index, ins): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register operand {op_index} at RVA {ins.ip:#x}: {ins}") + idx = vec_index(ins.op_register(op_index), ins) + if idx not in defined_vec: + raise ValueError(f"undefined vector register xmm{idx} at RVA {ins.ip:#x}: {ins}") + used_vec.add(idx) + return f"xmm{idx}" + + def write_vec(op_index, ins): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register destination at RVA {ins.ip:#x}: {ins}") + idx = vec_index(ins.op_register(op_index), ins) + used_vec.add(idx) + return idx, f"xmm{idx}" + + def vec_src128(op_index, ins, *, alignment): + if ins.op_kind(op_index) == OpKind.MEMORY: + return f"load128({flat_address(ins, alignment=alignment, expected_size=16)})" + return read_vec(op_index, ins) + + def read_gpr(op_index, ins): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected GPR operand {op_index} at RVA {ins.ip:#x}: {ins}") + gpr = gpr_target(ins.op_register(op_index), ins, write=False) + if gpr not in defined_gpr: + raise ValueError(f"undefined GPR {gpr} at RVA {ins.ip:#x}: {ins}") + used_gpr.add(gpr) + return gpr + + def write_gpr(op_index, ins): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected GPR destination at RVA {ins.ip:#x}: {ins}") + gpr = gpr_target(ins.op_register(op_index), ins, write=True) + used_gpr.add(gpr) + return gpr + + for ins in instructions: + if returned: + raise ValueError(f"unreachable instruction after ret at RVA {ins.ip:#x}: {ins}") + if ins.has_lock_prefix or ins.has_rep_prefix or ins.has_repne_prefix or ins.has_segment_prefix: + raise ValueError(f"unsupported instruction prefix at RVA {ins.ip:#x}: {ins}") + if ins.op_code().encoding != EncodingKind.LEGACY: + raise ValueError(f"non-legacy encoding at RVA {ins.ip:#x}: {ins}") + if ins.code not in ALLOWED_CODES: + raise ValueError(f"unsupported instruction at RVA {ins.ip:#x}: {ins}") + + if ins.code == Code.RETNQ: + statements.append("return;") + returned = True + elif ins.code in (Code.ROUNDPS_XMM_XMMM128_IMM8, Code.ROUNDPD_XMM_XMMM128_IMM8): + helper = "op_roundpd" if ins.code == Code.ROUNDPD_XMM_XMMM128_IMM8 else "op_roundps" + imm = ins.immediate8 & 0x0F + src = vec_src128(1, ins, alignment=16) + dst_idx, dst = write_vec(0, ins) + statements.append(f"{dst} = {helper}({src}, {imm:#x}u);") + defined_vec.add(dst_idx) + elif ins.code == Code.ROUNDSS_XMM_XMMM32_IMM8: + imm = ins.immediate8 & 0x0F + dst_in = read_vec(0, ins) + if ins.op1_kind == OpKind.MEMORY: + src32 = f"load32({flat_address(ins, expected_size=4)})" + else: + src32 = f"lane32({read_vec(1, ins)}, 0u)" + dst_idx, dst = write_vec(0, ins) + statements.append(f"{dst} = op_roundss({dst_in}, {src32}, {imm:#x}u);") + defined_vec.add(dst_idx) + elif ins.code == Code.ROUNDSD_XMM_XMMM64_IMM8: + imm = ins.immediate8 & 0x0F + dst_in = read_vec(0, ins) + if ins.op1_kind == OpKind.MEMORY: + src64 = f"load64({flat_address(ins, expected_size=8)})" + else: + src64 = f"{read_vec(1, ins)}.q[0]" + dst_idx, dst = write_vec(0, ins) + statements.append(f"{dst} = op_roundsd({dst_in}, {src64}, {imm:#x}u);") + defined_vec.add(dst_idx) + elif ins.code in (Code.DPPS_XMM_XMMM128_IMM8, Code.DPPD_XMM_XMMM128_IMM8): + helper = "op_dppd" if ins.code == Code.DPPD_XMM_XMMM128_IMM8 else "op_dpps" + imm = ins.immediate8 & 0xFF + dst_in = read_vec(0, ins) + src = vec_src128(1, ins, alignment=16) + dst_idx, dst = write_vec(0, ins) + statements.append(f"{dst} = {helper}({dst_in}, {src}, {imm:#x}u);") + defined_vec.add(dst_idx) + elif ins.code == Code.INSERTPS_XMM_XMMM32_IMM8: + imm = ins.immediate8 & 0xFF + dst_in = read_vec(0, ins) + if ins.op1_kind == OpKind.MEMORY: + src32 = f"load32({flat_address(ins, expected_size=4)})" + else: + count_s = (imm >> 6) & 3 + src32 = f"lane32({read_vec(1, ins)}, {count_s}u)" + dst_idx, dst = write_vec(0, ins) + statements.append(f"{dst} = op_insertps({dst_in}, {src32}, {imm:#x}u);") + defined_vec.add(dst_idx) + elif ins.code in EXTRACTPS_CODES: + lane = ins.immediate8 & 3 + src = read_vec(1, ins) + if ins.op0_kind == OpKind.MEMORY: + addr = flat_address(ins, write=True, expected_size=4) + statements.append(f"store32({addr}, lane32({src}, {lane}u));") + else: + gpr = write_gpr(0, ins) + statements.append(f"{gpr} = static_cast(lane32({src}, {lane}u));") + defined_gpr.add(gpr) + elif ins.code in (*LOAD_ALIGNED_VEC_CODES, *LOAD_UNALIGNED_VEC_CODES): + align = 16 if ins.code in LOAD_ALIGNED_VEC_CODES else 1 + src = vec_src128(1, ins, alignment=align) + dst_idx, dst = write_vec(0, ins) + statements.append(f"{dst} = {src};") + defined_vec.add(dst_idx) + elif ins.code in (*STORE_ALIGNED_VEC_CODES, *STORE_UNALIGNED_VEC_CODES): + align = 16 if ins.code in STORE_ALIGNED_VEC_CODES else 1 + src = read_vec(1, ins) + if ins.op0_kind == OpKind.MEMORY: + addr = flat_address(ins, alignment=align, write=True, expected_size=16) + statements.append(f"store128({addr}, {src});") + else: + dst_idx, dst = write_vec(0, ins) + statements.append(f"{dst} = {src};") + defined_vec.add(dst_idx) + elif ins.code in MOVSS_REG_CODES: + if ins.op0_kind == OpKind.REGISTER and ins.op1_kind == OpKind.MEMORY: + addr = flat_address(ins, expected_size=4) + dst_idx, dst = write_vec(0, ins) + statements.append(f"{dst} = Vec128{{static_cast(load32({addr})), 0ull}};") + defined_vec.add(dst_idx) + elif ins.op0_kind == OpKind.MEMORY and ins.op1_kind == OpKind.REGISTER: + src = read_vec(1, ins) + addr = flat_address(ins, write=True, expected_size=4) + statements.append(f"store32({addr}, lane32({src}, 0u));") + elif ins.op0_kind == OpKind.REGISTER and ins.op1_kind == OpKind.REGISTER: + read_vec(0, ins) + src = read_vec(1, ins) + dst_idx, dst = write_vec(0, ins) + statements.append(f"set_lane32({dst}, 0u, lane32({src}, 0u));") + defined_vec.add(dst_idx) + else: + raise ValueError(f"unsupported movss operands at RVA {ins.ip:#x}: {ins}") + elif ins.code in MOVSD_REG_CODES: + if ins.op0_kind == OpKind.REGISTER and ins.op1_kind == OpKind.MEMORY: + addr = flat_address(ins, expected_size=8) + dst_idx, dst = write_vec(0, ins) + statements.append(f"{dst} = Vec128{{load64({addr}), 0ull}};") + defined_vec.add(dst_idx) + elif ins.op0_kind == OpKind.MEMORY and ins.op1_kind == OpKind.REGISTER: + src = read_vec(1, ins) + addr = flat_address(ins, write=True, expected_size=8) + statements.append(f"store64({addr}, {src}.q[0]);") + elif ins.op0_kind == OpKind.REGISTER and ins.op1_kind == OpKind.REGISTER: + read_vec(0, ins) + src = read_vec(1, ins) + dst_idx, dst = write_vec(0, ins) + statements.append(f"{dst}.q[0] = {src}.q[0];") + defined_vec.add(dst_idx) + else: + raise ValueError(f"unsupported movsd operands at RVA {ins.ip:#x}: {ins}") + elif ins.code in MOV_GPR_CODES: + is64 = MOV_GPR_CODES[ins.code] + sz = 8 if is64 else 4 + if ins.op0_kind == OpKind.REGISTER and ins.op1_kind == OpKind.MEMORY: + addr = flat_address(ins, expected_size=sz) + dst = write_gpr(0, ins) + loader = f"load64({addr})" if is64 else f"static_cast(load32({addr}))" + statements.append(f"{dst} = {loader};") + defined_gpr.add(dst) + elif ins.op0_kind == OpKind.MEMORY and ins.op1_kind == OpKind.REGISTER: + src = read_gpr(1, ins) + addr = flat_address(ins, write=True, expected_size=sz) + if is64: + statements.append(f"store64({addr}, {src});") + else: + statements.append(f"store32({addr}, static_cast({src}));") + elif ins.op0_kind == OpKind.REGISTER and ins.op1_kind == OpKind.REGISTER: + src = read_gpr(1, ins) + dst = write_gpr(0, ins) + expr = src if is64 else f"static_cast(static_cast({src}))" + statements.append(f"{dst} = {expr};") + defined_gpr.add(dst) + else: + raise ValueError(f"unsupported GPR mov operands at RVA {ins.ip:#x}: {ins}") + else: + raise ValueError(f"unsupported instruction at RVA {ins.ip:#x}: {ins}") + + if not returned: + raise ValueError(f"missing terminal ret in {name} at RVA {start + len(raw):#x}") + + decls = [f" Vec128 xmm{idx}{{}};" for idx in sorted(used_vec)] + decls.extend(f" word {gpr} = 0ull;" for gpr in sorted(used_gpr)) + body = [f" {stmt}" for stmt in statements] + lines = [ + f'extern "C" __declspec(dllexport) void lifted_{name}(word rcx, word rdx, word r8) {{', + " (void)rcx; (void)rdx; (void)r8;", + *decls, + *body, + "}", + ] + return "\n".join(lines), len(instructions) + + +def lift(pe, name): + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + source, count = lift_code(name, entry, raw) + return source, entry, count + + +def translate_pe(pe, names): + if pe.FILE_HEADER.Machine != 0x8664 or pe.OPTIONAL_HEADER.Magic != 0x20B: + raise ValueError("expected AMD64 PE32+") + lifted = [lift(pe, name) for name in names] + source = PRELUDE + "\n".join(f"\n{text}" for text, _, _ in lifted) + "\n" + meta = [(name, entry, count) for name, (_, entry, count) in zip(names, lifted)] + return source, meta + + +def translate(image, names): + with pefile.PE(str(image), fast_load=True) as pe: + return translate_pe(pe, names) + + +def _write_atomic(path: Path, content: str) -> None: + if path.exists() and path.is_dir(): + raise ValueError(f"output path must not be a directory: {path}") + if path.is_symlink(): + raise ValueError(f"output path must not be a symlink: {path}") + path.parent.mkdir(parents=True, exist_ok=True) + tmp_path = None + try: + with tempfile.NamedTemporaryFile( + mode="w", + encoding="utf-8", + newline="\n", + dir=path.parent, + prefix=f".{path.stem}.", + suffix=".tmp", + delete=False, + ) as handle: + tmp_path = Path(handle.name) + handle.write(content) + tmp_path.replace(path) + except BaseException: + if tmp_path is not None: + tmp_path.unlink(missing_ok=True) + raise + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("image", type=Path) + parser.add_argument("exports", help="comma-separated export names") + parser.add_argument("output", type=Path) + args = parser.parse_args(argv) + try: + if not args.image.is_file(): + raise ValueError(f"input image must be a regular file: {args.image}") + exports = [name for name in args.exports.split(",") if name] + if not exports: + raise ValueError("exports list must not be empty") + if args.output.exists() and args.output.is_dir(): + raise ValueError(f"output path must not be a directory: {args.output}") + if args.output.is_symlink(): + raise ValueError(f"output path must not be a symlink: {args.output}") + source, meta = translate(args.image, exports) + _write_atomic(args.output, source) + for name, entry, count in meta: + print(f"{name} at RVA {entry:#x}: {count} instructions") + except (ValueError, OSError, pefile.PEFormatError) as error: + parser.exit(1, f"cpu_sse41_fp_aot: {error}\n") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) From 51a198da94e125aa7669cff6909b74d3538dbb85 Mon Sep 17 00:00:00 2001 From: Louis <59670693+louisdibiasi@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:18:44 -0500 Subject: [PATCH 111/240] runtime: keep save name handling safe on allocation failure (#2709) --- src/startup_stubs/runtime_proxy.cpp | 2 +- src/startup_stubs/save_store.h | 19 ++++++++++++++----- tests/startup_gamesave_submit.cpp | 17 +++++++++++++++++ 3 files changed, 32 insertions(+), 6 deletions(-) diff --git a/src/startup_stubs/runtime_proxy.cpp b/src/startup_stubs/runtime_proxy.cpp index eac6941c8..bf117e9e8 100644 --- a/src/startup_stubs/runtime_proxy.cpp +++ b/src/startup_stubs/runtime_proxy.cpp @@ -832,8 +832,8 @@ std::string update_container(u64 update) { std::string name; AcquireSRWLockShared(&save_lock); + struct Unlock { ~Unlock() { ReleaseSRWLockShared(&save_lock); } } unlock; if (update >= save_update_handle) name = save_table.update_container(static_cast(update - save_update_handle)); - ReleaseSRWLockShared(&save_lock); return name; } #include "startup_stubs/save_read.inl" diff --git a/src/startup_stubs/save_store.h b/src/startup_stubs/save_store.h index 26d0ec8c9..2237dd77b 100644 --- a/src/startup_stubs/save_store.h +++ b/src/startup_stubs/save_store.h @@ -57,12 +57,21 @@ inline bool valid_name(std::string_view name) noexcept same = std::tolower(static_cast(tail[i])) == suffix[i]; if (same) return false; } - std::string stem(name.substr(0, name.find('.'))); - for (char& c : stem) c = static_cast(c >= 'a' && c <= 'z' ? c - 'a' + 'A' : c); - while (!stem.empty() && stem.back() == ' ') stem.pop_back(); + std::string_view stem = name.substr(0, name.find('.')); + while (!stem.empty() && stem.back() == ' ') stem.remove_suffix(1); + const auto upper = [](char c) { return static_cast(c >= 'a' && c <= 'z' ? c - 'a' + 'A' : c); }; + const auto matches = [&](std::string_view device) { + if (stem.size() != device.size()) return false; + for (std::size_t i = 0; i < stem.size(); ++i) + if (upper(stem[i]) != device[i]) return false; + return true; + }; for (const char* device : {"CON", "PRN", "AUX", "NUL"}) - if (stem == device) return false; - if (stem.size() == 4 && (stem.compare(0, 3, "COM") == 0 || stem.compare(0, 3, "LPT") == 0) && stem[3] >= '0' && stem[3] <= '9') return false; + if (matches(device)) return false; + if (stem.size() == 4 && stem[3] >= '0' && stem[3] <= '9') { + stem.remove_suffix(1); + if (matches("COM") || matches("LPT")) return false; + } return true; } diff --git a/tests/startup_gamesave_submit.cpp b/tests/startup_gamesave_submit.cpp index d17489a9f..687b361a3 100644 --- a/tests/startup_gamesave_submit.cpp +++ b/tests/startup_gamesave_submit.cpp @@ -108,6 +108,23 @@ int run(bool system) call(16,provider_handle,ptr("profile"),ptr(&container)) || call(23,container,0,ptr(&good)) || call(23,container,0,ptr(&bad))) return 1; unsigned char byte=0x11; + const std::string long_name(80, 'c'); + const std::string name_copy(long_name); + const std::size_t name_allocation = name_copy.capacity() + 1; + fail_allocation_size = name_allocation; + if (!x2w_save::valid_name(long_name) || fail_allocation_size != name_allocation) return 26; + fail_allocation_size = 0; + u64 long_container{}, long_update{}; + if (call(16,provider_handle,ptr(long_name.c_str()),ptr(&long_container)) || + call(23,long_container,0,ptr(&long_update))) return 22; + fail_allocation_size = name_allocation; // Fail the same string copy under save_lock. + const u64 name_copy_result = call(25,long_update,ptr("preference"),ptr(&byte),1); + if (fail_allocation_size || name_copy_result != e_outofmemory) return 23; + if (!TryAcquireSRWLockExclusive(&save_lock)) return 24; + ReleaseSRWLockExclusive(&save_lock); + if (call(25,long_update,ptr("preference"),ptr(&byte),1) || call(27,long_update)) return 25; + call(24,long_update); + call(17,long_container); const std::array large_blob{}; for (const auto data_size : {std::size_t{1}, large_blob.size()}) { fail_allocation_size = data_size == 1 ? sizeof(x2w_save::Action) : data_size; From f14219f220df38ac3ee2be9a06b5527b48de63d5 Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Thu, 26 Nov 2026 05:18:57 +0200 Subject: [PATCH 112/240] cpu: lift legacy SSE and VEX.128 AES-NI and PCLMULQDQ leaf functions to C++ (#2677) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 31 ++ tests/cpu/aes_pclmul_aot.asm | 401 +++++++++++++++ tests/cpu/aes_pclmul_aot.def | 38 ++ tests/cpu/aes_pclmul_aot_check.py | 817 ++++++++++++++++++++++++++++++ tools/cpu_aes_pclmul_aot.py | 668 ++++++++++++++++++++++++ 5 files changed, 1955 insertions(+) create mode 100644 tests/cpu/aes_pclmul_aot.asm create mode 100644 tests/cpu/aes_pclmul_aot.def create mode 100644 tests/cpu/aes_pclmul_aot_check.py create mode 100644 tools/cpu_aes_pclmul_aot.py diff --git a/CMakeLists.txt b/CMakeLists.txt index ff2cbb8e9..7246893a5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -7254,6 +7254,37 @@ if(EXISTS "${INTAKE_PYTHON}") check "$" "$") set_tests_properties(cpu_aot_crypto_aes_pclmul PROPERTIES SKIP_RETURN_CODE 77) + # cpu_aot_aes_pclmul + set(cpu_aes_pclmul_aot_exports + "op_aesenc_reg,op_aesenclast_reg,op_aesdec_reg,op_aesdeclast_reg," + "op_aesimc_reg,op_aeskeygenassist_reg," + "op_pclmulqdq_00_reg,op_pclmulqdq_11_reg,op_pclmulqdq_ignore_bits_reg," + "op_aesenc_mem,op_aesenclast_mem,op_aesdec_mem,op_aesdeclast_mem," + "op_aesimc_mem,op_aeskeygenassist_mem,op_pclmulqdq_01_mem," + "op_vaesenc_reg,op_vaesenclast_reg,op_vaesdec_reg,op_vaesdeclast_reg," + "op_vaesimc_reg,op_vaeskeygenassist_reg," + "op_vpclmulqdq_10_reg,op_vpclmulqdq_ignore_bits_reg," + "op_vaesenc_mem,op_vaesenclast_mem,op_vaesdec_mem,op_vaesdeclast_mem," + "op_vaesimc_mem,op_vaeskeygenassist_mem,op_vpclmulqdq_11_mem," + "op_sse_preserves_ymm_hi,op_vex_zeroes_ymm_hi,op_vzeroupper_clears_ymm_hi," + "op_r8_source_then_store,op_dst_alias_src,op_aes_pclmul_discarded_read") + string(CONCAT cpu_aes_pclmul_aot_exports ${cpu_aes_pclmul_aot_exports}) + foreach(variant IN ITEMS original altered) + cpu_asm_fixture(cpu_aes_pclmul_aot_${variant} aes_pclmul_aot) + cpu_translation(cpu_aes_pclmul_aot_${variant} cpu_aes_pclmul_aot "${cpu_aes_pclmul_aot_exports}") + endforeach() + target_compile_definitions(cpu_aes_pclmul_aot_altered PRIVATE ALTER_AES_PCLMUL) + add_test(NAME cpu_aot_aes_pclmul COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/cpu/aes_pclmul_aot_check.py" + "$" + "$" + "$" + "$" + "${CMAKE_CXX_COMPILER}") + set_tests_properties(cpu_aot_aes_pclmul PROPERTIES + SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/cpu_aot_aes_pclmul.txt") + # cpu_aot_sha256 set(cpu_sha256_aot_exports "op_sha256rnds2_reg,op_sha256rnds2_mem,op_sha256rnds2_mem_r8," diff --git a/tests/cpu/aes_pclmul_aot.asm b/tests/cpu/aes_pclmul_aot.asm new file mode 100644 index 000000000..c9497881d --- /dev/null +++ b/tests/cpu/aes_pclmul_aot.asm @@ -0,0 +1,401 @@ +; coverage: record cpu_aot_aes_pclmul +; Source-built MASM fixture for legacy SSE and VEX.128 AES-NI and PCLMULQDQ +; instructions from docs/coverage/x64_zen2.tsv: register and flat [rcx|rdx|r8] +; m128 forms, YMM[255:128] preservation vs VEX.128 zeroing, vzeroupper, +; aliased source-before-dst overwrite, and discarded faulting m128 read. +.code + +; --- Legacy SSE register forms --- + +op_aesenc_reg PROC FRAME + .endprolog + movdqa xmm0, xmmword ptr [rcx] + movdqa xmm1, xmmword ptr [rdx] +IFDEF ALTER_AES_PCLMUL + aesenclast xmm0, xmm1 +ELSE + aesenc xmm0, xmm1 +ENDIF + movdqa xmmword ptr [r8], xmm0 + ret +op_aesenc_reg ENDP + +op_aesenclast_reg PROC FRAME + .endprolog + movdqa xmm0, xmmword ptr [rcx] + movdqa xmm1, xmmword ptr [rdx] +IFDEF ALTER_AES_PCLMUL + aesenc xmm0, xmm1 +ELSE + aesenclast xmm0, xmm1 +ENDIF + movdqa xmmword ptr [r8], xmm0 + ret +op_aesenclast_reg ENDP + +op_aesdec_reg PROC FRAME + .endprolog + movdqa xmm0, xmmword ptr [rcx] + movdqa xmm1, xmmword ptr [rdx] +IFDEF ALTER_AES_PCLMUL + aesdeclast xmm0, xmm1 +ELSE + aesdec xmm0, xmm1 +ENDIF + movdqa xmmword ptr [r8], xmm0 + ret +op_aesdec_reg ENDP + +op_aesdeclast_reg PROC FRAME + .endprolog + movdqa xmm0, xmmword ptr [rcx] + movdqa xmm1, xmmword ptr [rdx] +IFDEF ALTER_AES_PCLMUL + aesdec xmm0, xmm1 +ELSE + aesdeclast xmm0, xmm1 +ENDIF + movdqa xmmword ptr [r8], xmm0 + ret +op_aesdeclast_reg ENDP + +op_aesimc_reg PROC FRAME + .endprolog + movdqa xmm1, xmmword ptr [rcx] +IFDEF ALTER_AES_PCLMUL + movdqa xmm0, xmm1 +ELSE + aesimc xmm0, xmm1 +ENDIF + movdqa xmmword ptr [r8], xmm0 + ret +op_aesimc_reg ENDP + +op_aeskeygenassist_reg PROC FRAME + .endprolog + movdqa xmm1, xmmword ptr [rcx] +IFDEF ALTER_AES_PCLMUL + aeskeygenassist xmm0, xmm1, 1Ch +ELSE + aeskeygenassist xmm0, xmm1, 1Bh +ENDIF + movdqa xmmword ptr [r8], xmm0 + ret +op_aeskeygenassist_reg ENDP + +op_pclmulqdq_00_reg PROC FRAME + .endprolog + movdqa xmm0, xmmword ptr [rcx] + movdqa xmm1, xmmword ptr [rdx] +IFDEF ALTER_AES_PCLMUL + pclmulqdq xmm0, xmm1, 11h +ELSE + pclmulqdq xmm0, xmm1, 00h +ENDIF + movdqa xmmword ptr [r8], xmm0 + ret +op_pclmulqdq_00_reg ENDP + +op_pclmulqdq_11_reg PROC FRAME + .endprolog + movdqa xmm0, xmmword ptr [rcx] + movdqa xmm1, xmmword ptr [rdx] +IFDEF ALTER_AES_PCLMUL + pclmulqdq xmm0, xmm1, 00h +ELSE + pclmulqdq xmm0, xmm1, 11h +ENDIF + movdqa xmmword ptr [r8], xmm0 + ret +op_pclmulqdq_11_reg ENDP + +op_pclmulqdq_ignore_bits_reg PROC FRAME + .endprolog + movdqa xmm0, xmmword ptr [rcx] + movdqa xmm1, xmmword ptr [rdx] + pclmulqdq xmm0, xmm1, 0EFh + movdqa xmmword ptr [r8], xmm0 + ret +op_pclmulqdq_ignore_bits_reg ENDP + +; --- Legacy SSE flat [rcx|rdx] m128 forms (16-byte aligned) --- + +op_aesenc_mem PROC FRAME + .endprolog + movdqa xmm0, xmmword ptr [rcx] + aesenc xmm0, xmmword ptr [rdx] + movdqa xmmword ptr [r8], xmm0 + ret +op_aesenc_mem ENDP + +op_aesenclast_mem PROC FRAME + .endprolog + movdqa xmm0, xmmword ptr [rcx] + aesenclast xmm0, xmmword ptr [rdx] + movdqa xmmword ptr [r8], xmm0 + ret +op_aesenclast_mem ENDP + +op_aesdec_mem PROC FRAME + .endprolog + movdqa xmm0, xmmword ptr [rcx] + aesdec xmm0, xmmword ptr [rdx] + movdqa xmmword ptr [r8], xmm0 + ret +op_aesdec_mem ENDP + +op_aesdeclast_mem PROC FRAME + .endprolog + movdqa xmm0, xmmword ptr [rcx] + aesdeclast xmm0, xmmword ptr [rdx] + movdqa xmmword ptr [r8], xmm0 + ret +op_aesdeclast_mem ENDP + +op_aesimc_mem PROC FRAME + .endprolog + aesimc xmm0, xmmword ptr [rcx] + movdqa xmmword ptr [r8], xmm0 + ret +op_aesimc_mem ENDP + +op_aeskeygenassist_mem PROC FRAME + .endprolog + aeskeygenassist xmm0, xmmword ptr [rcx], 80h + movdqa xmmword ptr [r8], xmm0 + ret +op_aeskeygenassist_mem ENDP + +op_pclmulqdq_01_mem PROC FRAME + .endprolog + movdqa xmm0, xmmword ptr [rcx] + pclmulqdq xmm0, xmmword ptr [rdx], 01h + movdqa xmmword ptr [r8], xmm0 + ret +op_pclmulqdq_01_mem ENDP + +; --- VEX.128 register forms --- + +op_vaesenc_reg PROC FRAME + .endprolog + vmovdqu xmm1, xmmword ptr [rcx] + vmovdqu xmm2, xmmword ptr [rdx] +IFDEF ALTER_AES_PCLMUL + vaesdec xmm0, xmm1, xmm2 +ELSE + vaesenc xmm0, xmm1, xmm2 +ENDIF + vmovdqu xmmword ptr [r8], xmm0 + ret +op_vaesenc_reg ENDP + +op_vaesenclast_reg PROC FRAME + .endprolog + vmovdqu xmm1, xmmword ptr [rcx] + vmovdqu xmm2, xmmword ptr [rdx] +IFDEF ALTER_AES_PCLMUL + vaesdeclast xmm0, xmm1, xmm2 +ELSE + vaesenclast xmm0, xmm1, xmm2 +ENDIF + vmovdqu xmmword ptr [r8], xmm0 + ret +op_vaesenclast_reg ENDP + +op_vaesdec_reg PROC FRAME + .endprolog + vmovdqu xmm1, xmmword ptr [rcx] + vmovdqu xmm2, xmmword ptr [rdx] +IFDEF ALTER_AES_PCLMUL + vaesenc xmm0, xmm1, xmm2 +ELSE + vaesdec xmm0, xmm1, xmm2 +ENDIF + vmovdqu xmmword ptr [r8], xmm0 + ret +op_vaesdec_reg ENDP + +op_vaesdeclast_reg PROC FRAME + .endprolog + vmovdqu xmm1, xmmword ptr [rcx] + vmovdqu xmm2, xmmword ptr [rdx] +IFDEF ALTER_AES_PCLMUL + vaesenclast xmm0, xmm1, xmm2 +ELSE + vaesdeclast xmm0, xmm1, xmm2 +ENDIF + vmovdqu xmmword ptr [r8], xmm0 + ret +op_vaesdeclast_reg ENDP + +op_vaesimc_reg PROC FRAME + .endprolog + vmovdqu xmm1, xmmword ptr [rcx] +IFDEF ALTER_AES_PCLMUL + vmovdqa xmm0, xmm1 +ELSE + vaesimc xmm0, xmm1 +ENDIF + vmovdqu xmmword ptr [r8], xmm0 + ret +op_vaesimc_reg ENDP + +op_vaeskeygenassist_reg PROC FRAME + .endprolog + vmovdqu xmm1, xmmword ptr [rcx] +IFDEF ALTER_AES_PCLMUL + vaeskeygenassist xmm0, xmm1, 37h +ELSE + vaeskeygenassist xmm0, xmm1, 36h +ENDIF + vmovdqu xmmword ptr [r8], xmm0 + ret +op_vaeskeygenassist_reg ENDP + +op_vpclmulqdq_10_reg PROC FRAME + .endprolog + vmovdqu xmm1, xmmword ptr [rcx] + vmovdqu xmm2, xmmword ptr [rdx] +IFDEF ALTER_AES_PCLMUL + vpclmulqdq xmm0, xmm1, xmm2, 01h +ELSE + vpclmulqdq xmm0, xmm1, xmm2, 10h +ENDIF + vmovdqu xmmword ptr [r8], xmm0 + ret +op_vpclmulqdq_10_reg ENDP + +op_vpclmulqdq_ignore_bits_reg PROC FRAME + .endprolog + vmovdqu xmm1, xmmword ptr [rcx] + vmovdqu xmm2, xmmword ptr [rdx] + vpclmulqdq xmm0, xmm1, xmm2, 0FCh + vmovdqu xmmword ptr [r8], xmm0 + ret +op_vpclmulqdq_ignore_bits_reg ENDP + +; --- VEX.128 flat [rcx|rdx] m128 forms --- + +op_vaesenc_mem PROC FRAME + .endprolog + vmovdqu xmm1, xmmword ptr [rcx] +IFDEF ALTER_AES_PCLMUL + vaesdec xmm0, xmm1, xmmword ptr [rdx] +ELSE + vaesenc xmm0, xmm1, xmmword ptr [rdx] +ENDIF + vmovdqu xmmword ptr [r8], xmm0 + ret +op_vaesenc_mem ENDP + +op_vaesenclast_mem PROC FRAME + .endprolog + vmovdqu xmm1, xmmword ptr [rcx] + vaesenclast xmm0, xmm1, xmmword ptr [rdx] + vmovdqu xmmword ptr [r8], xmm0 + ret +op_vaesenclast_mem ENDP + +op_vaesdec_mem PROC FRAME + .endprolog + vmovdqu xmm1, xmmword ptr [rcx] + vaesdec xmm0, xmm1, xmmword ptr [rdx] + vmovdqu xmmword ptr [r8], xmm0 + ret +op_vaesdec_mem ENDP + +op_vaesdeclast_mem PROC FRAME + .endprolog + vmovdqu xmm1, xmmword ptr [rcx] + vaesdeclast xmm0, xmm1, xmmword ptr [rdx] + vmovdqu xmmword ptr [r8], xmm0 + ret +op_vaesdeclast_mem ENDP + +op_vaesimc_mem PROC FRAME + .endprolog + vaesimc xmm0, xmmword ptr [rcx] + vmovdqu xmmword ptr [r8], xmm0 + ret +op_vaesimc_mem ENDP + +op_vaeskeygenassist_mem PROC FRAME + .endprolog + vaeskeygenassist xmm0, xmmword ptr [rcx], 0FFh + vmovdqu xmmword ptr [r8], xmm0 + ret +op_vaeskeygenassist_mem ENDP + +op_vpclmulqdq_11_mem PROC FRAME + .endprolog + vmovdqu xmm1, xmmword ptr [rcx] +IFDEF ALTER_AES_PCLMUL + vpclmulqdq xmm0, xmm1, xmmword ptr [rdx], 00h +ELSE + vpclmulqdq xmm0, xmm1, xmmword ptr [rdx], 11h +ENDIF + vmovdqu xmmword ptr [r8], xmm0 + ret +op_vpclmulqdq_11_mem ENDP + +; --- YMM[255:128] preservation vs VEX.128 zeroing, vzeroupper, aliasing, [r8] src, discarded read --- + +op_sse_preserves_ymm_hi PROC FRAME + .endprolog + vmovdqu ymm0, ymmword ptr [rcx] + movdqa xmm1, xmmword ptr [rdx] +IFDEF ALTER_AES_PCLMUL + vaesenc xmm0, xmm0, xmm1 +ELSE + aesenc xmm0, xmm1 +ENDIF + vmovdqu ymmword ptr [r8], ymm0 + ret +op_sse_preserves_ymm_hi ENDP + +op_vex_zeroes_ymm_hi PROC FRAME + .endprolog + vmovdqu ymm0, ymmword ptr [rcx] + vmovdqu xmm1, xmmword ptr [rdx] + vaesenc xmm0, xmm0, xmm1 + vmovdqu ymmword ptr [r8], ymm0 + ret +op_vex_zeroes_ymm_hi ENDP + +op_vzeroupper_clears_ymm_hi PROC FRAME + .endprolog + vmovdqu ymm1, ymmword ptr [rcx] + vzeroupper + vmovdqu ymmword ptr [r8], ymm1 + ret +op_vzeroupper_clears_ymm_hi ENDP + +op_r8_source_then_store PROC FRAME + .endprolog + vmovdqu xmm1, xmmword ptr [rcx] + vaesenc xmm0, xmm1, xmmword ptr [r8] + vpclmulqdq xmm0, xmm0, xmmword ptr [rdx], 00h + vmovdqa xmmword ptr [r8], xmm0 + ret +op_r8_source_then_store ENDP + +op_dst_alias_src PROC FRAME + .endprolog + vmovdqu xmm0, xmmword ptr [rcx] + vaesenc xmm0, xmm0, xmm0 + aesimc xmm0, xmm0 + aeskeygenassist xmm0, xmm0, 01h + vpclmulqdq xmm0, xmm0, xmm0, 01h + movdqu xmmword ptr [r8], xmm0 + ret +op_dst_alias_src ENDP + +op_aes_pclmul_discarded_read PROC FRAME + .endprolog + vmovdqu xmm1, xmmword ptr [rcx] + vaesenc xmm0, xmm1, xmmword ptr [rdx] + vmovdqu xmmword ptr [r8], xmm1 + ret +op_aes_pclmul_discarded_read ENDP + +END diff --git a/tests/cpu/aes_pclmul_aot.def b/tests/cpu/aes_pclmul_aot.def new file mode 100644 index 000000000..1df0227d2 --- /dev/null +++ b/tests/cpu/aes_pclmul_aot.def @@ -0,0 +1,38 @@ +EXPORTS + op_aesenc_reg + op_aesenclast_reg + op_aesdec_reg + op_aesdeclast_reg + op_aesimc_reg + op_aeskeygenassist_reg + op_pclmulqdq_00_reg + op_pclmulqdq_11_reg + op_pclmulqdq_ignore_bits_reg + op_aesenc_mem + op_aesenclast_mem + op_aesdec_mem + op_aesdeclast_mem + op_aesimc_mem + op_aeskeygenassist_mem + op_pclmulqdq_01_mem + op_vaesenc_reg + op_vaesenclast_reg + op_vaesdec_reg + op_vaesdeclast_reg + op_vaesimc_reg + op_vaeskeygenassist_reg + op_vpclmulqdq_10_reg + op_vpclmulqdq_ignore_bits_reg + op_vaesenc_mem + op_vaesenclast_mem + op_vaesdec_mem + op_vaesdeclast_mem + op_vaesimc_mem + op_vaeskeygenassist_mem + op_vpclmulqdq_11_mem + op_sse_preserves_ymm_hi + op_vex_zeroes_ymm_hi + op_vzeroupper_clears_ymm_hi + op_r8_source_then_store + op_dst_alias_src + op_aes_pclmul_discarded_read diff --git a/tests/cpu/aes_pclmul_aot_check.py b/tests/cpu/aes_pclmul_aot_check.py new file mode 100644 index 000000000..64267bec9 --- /dev/null +++ b/tests/cpu/aes_pclmul_aot_check.py @@ -0,0 +1,817 @@ +"""Differential, FIPS-197, YMM[255:128], /O2, mutant, and rejection checks for cpu_aes_pclmul_aot.""" + +import ctypes +import os +from pathlib import Path +import random +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory + +from iced_x86 import Code, Decoder, Encoder, Formatter, FormatterSyntax, Instruction, MemoryOperand, Register as R +import pefile + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "tools")) +from cpu_aes_pclmul_aot import lift_code, translate # noqa: E402 +from cpu_leaf_aot import bounded_code, export_rva # noqa: E402 + +EXPORTS = ( + "op_aesenc_reg", "op_aesenclast_reg", "op_aesdec_reg", "op_aesdeclast_reg", + "op_aesimc_reg", "op_aeskeygenassist_reg", + "op_pclmulqdq_00_reg", "op_pclmulqdq_11_reg", "op_pclmulqdq_ignore_bits_reg", + "op_aesenc_mem", "op_aesenclast_mem", "op_aesdec_mem", "op_aesdeclast_mem", + "op_aesimc_mem", "op_aeskeygenassist_mem", "op_pclmulqdq_01_mem", + "op_vaesenc_reg", "op_vaesenclast_reg", "op_vaesdec_reg", "op_vaesdeclast_reg", + "op_vaesimc_reg", "op_vaeskeygenassist_reg", + "op_vpclmulqdq_10_reg", "op_vpclmulqdq_ignore_bits_reg", + "op_vaesenc_mem", "op_vaesenclast_mem", "op_vaesdec_mem", "op_vaesdeclast_mem", + "op_vaesimc_mem", "op_vaeskeygenassist_mem", "op_vpclmulqdq_11_mem", + "op_sse_preserves_ymm_hi", "op_vex_zeroes_ymm_hi", "op_vzeroupper_clears_ymm_hi", + "op_r8_source_then_store", "op_dst_alias_src", "op_aes_pclmul_discarded_read", +) + +ALTERED_EXPORTS = ( + "op_aesenc_reg", "op_aesenclast_reg", "op_aesdec_reg", "op_aesdeclast_reg", + "op_aesimc_reg", "op_aeskeygenassist_reg", "op_pclmulqdq_00_reg", "op_pclmulqdq_11_reg", + "op_vaesenc_reg", "op_vaesenclast_reg", "op_vaesdec_reg", "op_vaesdeclast_reg", + "op_vaesimc_reg", "op_vaeskeygenassist_reg", "op_vpclmulqdq_10_reg", + "op_vaesenc_mem", "op_vpclmulqdq_11_mem", "op_sse_preserves_ymm_hi", +) + +GUARD_PRE = bytes(range(0xA0, 0xB0)) +GUARD_POST = bytes(range(0xC0, 0xD0)) + + +# --- Independent Python GF(2^8) AES & GF(2) PCLMULQDQ reference model --- + +def _gf_mul(a, b): + p = 0 + for _ in range(8): + if b & 1: + p ^= a + hi = a & 0x80 + a = (a << 1) & 0xFF + if hi: + a ^= 0x1B + b >>= 1 + return p + + +def _gf_inv(a): + if a == 0: + return 0 + for x in range(1, 256): + if _gf_mul(a, x) == 1: + return x + raise ValueError(a) + + +def _rotl8(x, n): + return ((x << n) | (x >> (8 - n))) & 0xFF + + +SBOX = tuple(_gf_inv(i) ^ _rotl8(_gf_inv(i), 1) ^ _rotl8(_gf_inv(i), 2) ^ _rotl8(_gf_inv(i), 3) ^ _rotl8(_gf_inv(i), 4) ^ 0x63 for i in range(256)) +INV_SBOX = tuple(SBOX.index(i) for i in range(256)) + + +def _shift_rows(b, *, inv=False): + idx = (0, 13, 10, 7, 4, 1, 14, 11, 8, 5, 2, 15, 12, 9, 6, 3) if inv else (0, 5, 10, 15, 4, 9, 14, 3, 8, 13, 2, 7, 12, 1, 6, 11) + return bytes(b[i] for i in idx) + + +def _mix_columns(b, *, inv=False): + out = bytearray(16) + coeffs = (0x0E, 0x0B, 0x0D, 0x09) if inv else (2, 3, 1, 1) + for c in range(4): + col = b[c * 4:(c + 1) * 4] + for r in range(4): + val = 0 + for k in range(4): + coef = coeffs[(k - r) % 4] + val ^= _gf_mul(coef, col[k]) + out[c * 4 + r] = val + return bytes(out) + + +def _xor16(a, b): + return bytes(x ^ y for x, y in zip(a, b)) + + +def ref_aesenc(state, key, *, quirk=None): + if quirk == "aes_no_shiftrows": + sb = bytes(SBOX[x] for x in state) + return _xor16(_mix_columns(sb), key) + if quirk == "aes_no_mixcols": + return ref_aesenclast(state, key) + sr = _shift_rows(state) + sb = bytes(SBOX[x] for x in sr) + return _xor16(_mix_columns(sb), key) + + +def ref_aesenclast(state, key): + sb = bytes(SBOX[x] for x in _shift_rows(state)) + return _xor16(sb, key) + + +def ref_aesdec(state, key): + sb = bytes(INV_SBOX[x] for x in _shift_rows(state, inv=True)) + return _xor16(_mix_columns(sb, inv=True), key) + + +def ref_aesdeclast(state, key): + sb = bytes(INV_SBOX[x] for x in _shift_rows(state, inv=True)) + return _xor16(sb, key) + + +def ref_aesimc(src): + return _mix_columns(src, inv=True) + + +def ref_aeskeygenassist(src, imm8, *, quirk=None): + words = list(struct.unpack("<4I", src)) + def sub_w(w): + return (SBOX[w & 0xFF] | (SBOX[(w >> 8) & 0xFF] << 8) + | (SBOX[(w >> 16) & 0xFF] << 16) | (SBOX[(w >> 24) & 0xFF] << 24)) + def rot_w(w): + return ((w >> 8) | (w << 24)) & 0xFFFFFFFF + s1, s3 = sub_w(words[1]), sub_w(words[3]) + rcon = 0 if quirk == "keygen_drop_rcon" else (imm8 & 0xFF) + if quirk == "keygen_wrong_words": + s1, s3 = sub_w(words[0]), sub_w(words[2]) + return struct.pack("<4I", s1, rot_w(s1) ^ rcon, s3, rot_w(s3) ^ rcon) + + +def ref_pclmulqdq(src1, src2, imm8, *, quirk=None): + a0, a1 = struct.unpack("<2Q", src1) + b0, b1 = struct.unpack("<2Q", src2) + a = a1 if (imm8 & 0x01) else a0 + if quirk == "pclmul_wrong_op2_bit": + b = b1 if (imm8 & 0x02) else b0 + elif quirk == "pclmul_reject_other_bits": + b = 0 if (imm8 & 0xEE) else (b1 if (imm8 & 0x10) else b0) + else: + b = b1 if (imm8 & 0x10) else b0 + res = 0 + for i in range(64): + if (b >> i) & 1: + res ^= (a << i) + return struct.pack("<2Q", res & 0xFFFFFFFFFFFFFFFF, (res >> 64) & 0xFFFFFFFFFFFFFFFF) + + +# --- Guarded aligned memory & DLL helpers --- + +def alloc_guarded(payload, *, align=32): + total = len(GUARD_PRE) + len(payload) + len(GUARD_POST) + align + raw = ctypes.create_string_buffer(total) + base = ctypes.addressof(raw) + aligned_ptr = (base + len(GUARD_PRE) + align - 1) & ~(align - 1) + off = aligned_ptr - base + ctypes.memmove(aligned_ptr - len(GUARD_PRE), GUARD_PRE, len(GUARD_PRE)) + ctypes.memmove(aligned_ptr, payload, len(payload)) + ctypes.memmove(aligned_ptr + len(payload), GUARD_POST, len(GUARD_POST)) + return raw, aligned_ptr, off, len(payload) + + +def read_guarded(buf, off, length, label): + raw = buf.raw + if raw[off - len(GUARD_PRE):off] != GUARD_PRE or raw[off + length:off + length + len(GUARD_POST)] != GUARD_POST: + raise AssertionError(f"guard bytes corrupted around {label}") + return raw[off:off + length] + + +def bind_exports(dll_path, prefix=""): + lib = ctypes.CDLL(str(Path(dll_path).resolve())) + funcs = {} + for name in EXPORTS: + fn = getattr(lib, prefix + name) + fn.argtypes = [ctypes.c_uint64] * 3 + fn.restype = None + funcs[name] = fn + return lib, funcs + + +def unload_lib(lib): + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + kernel32.FreeLibrary.argtypes = [ctypes.c_void_p] + kernel32.FreeLibrary.restype = ctypes.c_int + handle = getattr(lib, "_handle", None) + if handle: + kernel32.FreeLibrary(handle) + + +def host_has_aes_pclmul_avx(lifted_lib): + if hasattr(lifted_lib, "host_has_aes_pclmul_avx"): + lifted_lib.host_has_aes_pclmul_avx.argtypes = [] + lifted_lib.host_has_aes_pclmul_avx.restype = ctypes.c_uint32 + return bool(lifted_lib.host_has_aes_pclmul_avx()) + return False + + +def test_vectors(): + fips_a = bytes.fromhex("3243f6a8885a308d313198a2e0370734") + fips_b = bytes.fromhex("2b7e151628aed2a6abf7158809cf4f3c") + vectors = [ + (b"\x00" * 16, b"\x00" * 16), + (b"\xff" * 16, b"\xff" * 16), + (b"\x00" * 16, b"\xff" * 16), + (b"\xff" * 16, b"\x00" * 16), + (fips_a, fips_b), + (fips_b, fips_a), + (bytes(range(16)), bytes(range(16, 32))), + (struct.pack("<2Q", 0x8000000000000001, 0xFFFFFFFFFFFFFFFF), + struct.pack("<2Q", 0x8000000000000001, 0x0123456789ABCDEF)), + ] + rng = random.Random(0xAE59C1) + for _ in range(16): + vectors.append((rng.randbytes(16), rng.randbytes(16))) + return vectors + + +# --- Rejection & alternate-encoding controls --- + +def encode_seq(*instructions): + enc = Encoder(64) + ip = 0x1000 + for ins in instructions: + ip += enc.encode(ins, ip) + return enc.take_buffer() + + +def check_rejections(original_path): + ret = Instruction.create(Code.RETNQ) + ld_xmm0 = Instruction.create_reg_mem(Code.MOVDQA_XMM_XMMM128, R.XMM0, MemoryOperand(R.RCX)) + ld_xmm1 = Instruction.create_reg_mem(Code.VEX_VMOVDQU_XMM_XMMM128, R.XMM1, MemoryOperand(R.RDX)) + ld_ymm0 = Instruction.create_reg_mem(Code.VEX_VMOVDQU_YMM_YMMM256, R.YMM0, MemoryOperand(R.RCX)) + ld_ymm1 = Instruction.create_reg_mem(Code.VEX_VMOVDQU_YMM_YMMM256, R.YMM1, MemoryOperand(R.RCX)) + ld_ymm2 = Instruction.create_reg_mem(Code.VEX_VMOVDQU_YMM_YMMM256, R.YMM2, MemoryOperand(R.RDX)) + st_xmm0 = Instruction.create_mem_reg(Code.MOVDQU_XMMM128_XMM, MemoryOperand(R.R8), R.XMM0) + + # Alternate encodings accepted cleanly. + alt_accept = [ + ("vaesenc_xmm5_xmm1_r8mem", (ld_xmm1, Instruction.create_reg_reg_mem( + Code.VEX_VAESENC_XMM_XMM_XMMM128, R.XMM5, R.XMM1, MemoryOperand(R.R8)), + Instruction.create_mem_reg(Code.VEX_VMOVDQU_XMMM128_XMM, MemoryOperand(R.R8), R.XMM5), ret), + "ymm5 = zext256(op_aesenc(low128(ymm1), ld_1004_2));"), + ("aesimc_xmm3_xmm1", (ld_xmm1, Instruction.create_reg_reg(Code.AESIMC_XMM_XMMM128, R.XMM3, R.XMM1), + Instruction.create_mem_reg(Code.MOVDQU_XMMM128_XMM, MemoryOperand(R.R8), R.XMM3), ret), + "set_low128(ymm3, op_aesimc(low128(ymm1)));"), + ("vpclmulqdq_xmm4_xmm1_r8mem", (ld_xmm1, Instruction.create_reg_reg_mem_u32( + Code.VEX_VPCLMULQDQ_XMM_XMM_XMMM128_IMM8, R.XMM4, R.XMM1, MemoryOperand(R.R8), 0x11), + Instruction.create_mem_reg(Code.VEX_VMOVDQA_XMMM128_XMM, MemoryOperand(R.R8), R.XMM4), ret), + "ymm4 = zext256(op_pclmulqdq(low128(ymm1), ld_1004_2, 0x11u));"), + ] + for label, seq, expected in alt_accept: + src, count = lift_code(label, 0x1000, encode_seq(*seq)) + assert f"lifted_{label}" in src and count == len(seq), (label, count) + if expected not in src: + raise AssertionError(f"alt {label}: expected {expected!r}") + + seg_aes = Instruction.create_reg_mem(Code.AESENC_XMM_XMMM128, R.XMM0, MemoryOperand(R.RDX)) + seg_aes.segment_prefix = R.GS + evex_vaes = Instruction.create_reg_reg_reg(Code.EVEX_VAESENC_XMM_XMM_XMMM128, R.XMM0, R.XMM1, R.XMM2) + + unit_cases = [ + # VEX.256 compute rejections + ("vex256_vaesenc", (ld_ymm1, ld_ymm2, Instruction.create_reg_reg_reg( + Code.VEX_VAESENC_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2), ret), "unsupported VEX.256 instruction"), + ("vex256_vaesdeclast", (ld_ymm1, ld_ymm2, Instruction.create_reg_reg_reg( + Code.VEX_VAESDECLAST_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2), ret), "unsupported VEX.256 instruction"), + ("vex256_vpclmulqdq", (ld_ymm1, ld_ymm2, Instruction.create_reg_reg_reg_u32( + Code.VEX_VPCLMULQDQ_YMM_YMM_YMMM256_IMM8, R.YMM0, R.YMM1, R.YMM2, 0), ret), "unsupported VEX.256 instruction"), + ("vex256_vpaddq", (ld_ymm1, ld_ymm2, Instruction.create_reg_reg_reg( + Code.VEX_VPADDQ_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2), ret), "unsupported VEX.256 instruction"), + # EVEX / KeyLocker / out-of-scope + ("evex_vaesenc", (ld_xmm0, ld_xmm1, evex_vaes, ret), "unsupported EVEX instruction"), + ("aes128kl", (ld_xmm0, Instruction.create_reg_mem( + Code.AESENC128KL_XMM_M384, R.XMM0, MemoryOperand(R.RCX)), ret), "unsupported instruction"), + ("xop_vpcmov", (ld_xmm0, ld_xmm1, Instruction.create_reg_reg_reg_reg( + Code.XOP_VPCMOV_XMM_XMM_XMMM128_XMM, R.XMM0, R.XMM1, R.XMM1, R.XMM0), ret), "unsupported XOP instruction"), + # Nonvolatile XMM6..15 / YMM6..15 + ("nonvol_xmm6", (Instruction.create_reg_mem( + Code.MOVDQU_XMM_XMMM128, R.XMM6, MemoryOperand(R.RCX)), ret), "nonvolatile vector register"), + ("nonvol_ymm7", (Instruction.create_reg_mem( + Code.VEX_VMOVDQU_YMM_YMMM256, R.YMM7, MemoryOperand(R.RCX)), ret), "nonvolatile vector register"), + ("nonvol_xmm15_aes", (ld_xmm0, Instruction.create_reg_reg( + Code.AESENC_XMM_XMMM128, R.XMM0, R.XMM15), ret), "nonvolatile vector register"), + # Undefined XMM / YMM reads + ("undef_xmm2_vaesenc", (ld_xmm1, Instruction.create_reg_reg_reg( + Code.VEX_VAESENC_XMM_XMM_XMMM128, R.XMM0, R.XMM1, R.XMM2), ret), "undefined vector register xmm2"), + ("undef_xmm0_aesenc_dst", (ld_xmm1, Instruction.create_reg_reg( + Code.AESENC_XMM_XMMM128, R.XMM0, R.XMM1), ret), "undefined vector register xmm0"), + ("undef_xmm0_pclmul_dst", (ld_xmm1, Instruction.create_reg_reg_u32( + Code.PCLMULQDQ_XMM_XMMM128_IMM8, R.XMM0, R.XMM1, 0), ret), "undefined vector register xmm0"), + ("undef_ymm0_hi_after_sse", (ld_xmm0, ld_xmm1, Instruction.create_reg_reg( + Code.AESENC_XMM_XMMM128, R.XMM0, R.XMM1), + Instruction.create_mem_reg(Code.VEX_VMOVDQU_YMMM256_YMM, MemoryOperand(R.R8), R.YMM0), ret), + "undefined vector register ymm0"), + # Bad memory operands & non-[r8] stores + ("displaced_aesenc_rdx", (ld_xmm0, Instruction.create_reg_mem( + Code.AESENC_XMM_XMMM128, R.XMM0, MemoryOperand(R.RDX, displ=16, displ_size=1)), ret), + "displaced memory operand"), + ("displaced_store_r8", (ld_xmm0, Instruction.create_mem_reg( + Code.MOVDQU_XMMM128_XMM, MemoryOperand(R.R8, displ=16, displ_size=1), R.XMM0), ret), + "displaced memory operand"), + ("indexed_vaesdec", (ld_xmm1, Instruction.create_reg_reg_mem( + Code.VEX_VAESDEC_XMM_XMM_XMMM128, R.XMM0, R.XMM1, MemoryOperand(R.RCX, R.RDX, 1)), ret), + "SIB index memory operand"), + ("rip_rel_aesimc", (Instruction.create_reg_mem( + Code.AESIMC_XMM_XMMM128, R.XMM0, MemoryOperand(R.RIP, displ=0x1020, displ_size=4)), ret), + "RIP-relative memory operand"), + ("bad_base_rbx", (Instruction.create_reg_mem( + Code.MOVDQA_XMM_XMMM128, R.XMM0, MemoryOperand(R.RBX)), ret), "nonvolatile GPR base"), + ("bad_base_r9", (Instruction.create_reg_mem( + Code.MOVDQA_XMM_XMMM128, R.XMM0, MemoryOperand(R.R9)), ret), "bad base register"), + ("non_r8_store_rcx", (ld_xmm0, Instruction.create_mem_reg( + Code.MOVDQU_XMMM128_XMM, MemoryOperand(R.RCX), R.XMM0), ret), "non-r8 store memory operand"), + ("non_r8_store_ymm_rdx", (ld_ymm0, Instruction.create_mem_reg( + Code.VEX_VMOVDQU_YMMM256_YMM, MemoryOperand(R.RDX), R.YMM0), ret), "non-r8 store memory operand"), + # Prefixes, branches, missing/trailing ret + ("seg_prefix_aesenc", (ld_xmm0, seg_aes, ret), "unsupported instruction prefix"), + ("branch_jmp", (ld_xmm0, Instruction.create_branch(Code.JMP_REL8_64, 0x1010), ret), + "non-leaf branch or call"), + ("missing_ret", (ld_xmm0, st_xmm0), "missing terminal ret"), + ("trailing_after_ret", (ld_xmm0, st_xmm0, ret, ld_xmm1), "unreachable instruction after ret"), + ] + + raw_cases = [ + ("lock_prefix", bytes.fromhex("f00fb109") + encode_seq(ret), "unsupported instruction prefix"), + ("rep_prefix", bytes.fromhex("f3a4") + encode_seq(ret), "unsupported instruction prefix"), + ("empty_stream", b"", "truncated instruction stream"), + ("invalid_bytes", bytes.fromhex("fffe") + encode_seq(ret), "invalid instruction"), + ] + + for label, seq, reason in unit_cases: + try: + lift_code(label, 0x1000, encode_seq(*seq)) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: translator accepted rejected control") + + for label, raw, reason in raw_cases: + try: + lift_code(label, 0x1000, raw) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: translator accepted raw rejected control") + + # End-to-end PE-patched rejections & CLI non-traceback / temp-cleanup rejections. + pe_bytes = Path(original_path).read_bytes() + with pefile.PE(data=pe_bytes, fast_load=True) as pe: + entry = export_rva(pe, "op_dst_alias_src") + file_off = pe.get_offset_from_rva(entry) + pdata = pe.OPTIONAL_HEADER.DATA_DIRECTORY[3] + records = pe.get_data(pdata.VirtualAddress, pdata.Size) + rec_idx = next(i for i in range(0, len(records), 12) if struct.unpack_from(" max_len: + raise AssertionError(f"pe_{label}: patch ({len(patch)} bytes) exceeds max_len ({max_len})") + damaged = bytearray(pe_bytes) + damaged[file_off:file_off + len(patch)] = patch + struct.pack_into("" in source_text or "_mm_aes" in source_text or "_mm_clmul" in source_text: + raise AssertionError("translated C++ must be pure portable C++ without AES/PCLMUL intrinsics") + with TemporaryDirectory() as folder: + tmp = Path(folder) + cpp_path = tmp / "aes_pclmul_aot_o2.cpp" + dll_path = tmp / "aes_pclmul_aot_o2.dll" + cpp_path.write_text(source_text, encoding="utf-8") + proc = subprocess.run( + [str(cxx_path), "/nologo", "/O2", "/W4", "/WX", "/LD", str(cpp_path), + f"/Fo{tmp / 'aes_pclmul_aot_o2.obj'}", f"/Fe{dll_path}"], + capture_output=True, + text=True, + errors="replace", + ) + if proc.returncode != 0: + raise AssertionError(f"/O2 compile failed:\n{proc.stdout}\n{proc.stderr}") + o2_lib, o2_fns = bind_exports(dll_path, "lifted_") + try: + return verify_suite(o2_fns, "lifted_o2", vectors) + finally: + o2_fns.clear() + unload_lib(o2_lib) + + +def record_covered_forms(original_path): + record = os.environ.get("FORM_COVERAGE_RECORD") + if not record: + return + formatter = Formatter(FormatterSyntax.INTEL) + forms = set() + with pefile.PE(str(original_path), fast_load=True) as pe: + for name in EXPORTS: + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + for ins in Decoder(64, raw, ip=entry): + forms.add(formatter.format_mnemonic(ins).lower()) + out_path = Path(record) + out_path.parent.mkdir(parents=True, exist_ok=True) + out_path.write_text("".join(word + "\n" for word in sorted(forms)), encoding="utf-8") + + +def main(): + if os.environ.get("FORM_COVERAGE_RECORD"): + Path(os.environ["FORM_COVERAGE_RECORD"]).unlink(missing_ok=True) + + original_path, lifted_path, altered_path, altered_lifted_path, cxx_path = ( + Path(p) for p in sys.argv[1:6] + ) + + # 1) Lift + rejections + portable lifted + mutants + /O2 run unconditionally BEFORE CPUID skip. + check_rejections(original_path) + + vectors = test_vectors() + lifted_lib, lifted_fns = bind_exports(lifted_path, "lifted_") + alt_lifted_lib, alt_lifted_fns = bind_exports(altered_lifted_path, "lifted_") + try: + lifted_cases = verify_suite(lifted_fns, "lifted", vectors) + diverged, mutants = check_altered_and_mutants(lifted_fns, alt_lifted_fns, vectors) + o2_cases = compile_o2_and_verify(original_path, cxx_path, vectors) + + if not host_has_aes_pclmul_avx(lifted_lib): + print( + f"portable lifted passed ({lifted_cases} lifted + {o2_cases} /O2 cases, " + f"{diverged} ALTER_AES_PCLMUL + {mutants} mutants); " + "Host lacks CPUID.01H:ECX[1,25,27,28]/XGETBV[2:1] (PCLMULQDQ+AES+AVX), skipping native differential check" + ) + sys.exit(77) + + # 2) Native AES-NI + PCLMULQDQ + AVX hardware differential checks. + orig_lib, orig_fns = bind_exports(original_path) + alt_lib, alt_fns = bind_exports(altered_path) + try: + native_cases = verify_suite(orig_fns, "native", vectors) + hi_sentinel = bytes(range(0x10, 0x20)) + for name in ALTERED_EXPORTS: + is_ymm = name == "op_sse_preserves_ymm_hi" + out_len = 32 if is_ymm else 16 + for a, b in vectors[:8]: + buf_a = (a + hi_sentinel) if is_ymm else a + ba, pa, oa, la = alloc_guarded(buf_a) + bb, pb, ob, lb = alloc_guarded(b) + bn, pn, on, ln = alloc_guarded(b"\x5a" * out_len) + bl, pl, ol, ll = alloc_guarded(b"\x5a" * out_len) + alt_fns[name](pa, pb, pn) + alt_lifted_fns[name](pa, pb, pl) + got_an = read_guarded(bn, on, ln, f"alt_nat_{name}") + got_al = read_guarded(bl, ol, ll, f"alt_lift_{name}") + if got_an != got_al: + raise AssertionError(f"altered native vs lifted {name}: {got_an.hex()} != {got_al.hex()}") + finally: + orig_fns.clear() + alt_fns.clear() + unload_lib(orig_lib) + unload_lib(alt_lib) + finally: + lifted_fns.clear() + alt_lifted_fns.clear() + unload_lib(lifted_lib) + unload_lib(alt_lifted_lib) + + record_covered_forms(original_path) + print( + f"aes_pclmul_aot passed: {native_cases} native + {lifted_cases} lifted + {o2_cases} /O2 cases " + f"across {len(EXPORTS)} exports; ALTER_AES_PCLMUL diverged on {diverged} exports + {mutants} mutants caught" + ) + + +if __name__ == "__main__": + main() diff --git a/tools/cpu_aes_pclmul_aot.py b/tools/cpu_aes_pclmul_aot.py new file mode 100644 index 000000000..50c09626a --- /dev/null +++ b/tools/cpu_aes_pclmul_aot.py @@ -0,0 +1,668 @@ +"""Lift bounded Windows x64 leaf functions with legacy SSE & VEX.128 AES-NI and PCLMULQDQ to C++. + +Each export uses the straight-line leaf ABI: + void lifted_(word rcx, word rdx, word r8) +where rcx, rdx, and r8 carry flat host pointers to caller-owned 16/32-byte buffers +(rcx and rdx are inputs, r8 is the output/in-out buffer). YMM0..YMM5 are modeled +as pure portable 256-bit value structs (four 64-bit lanes) with GF(2^8) AES tables/math +and GF(2) carryless multiplication (zero compiler intrinsics / zero ). + +Supported AES-NI and PCLMULQDQ instructions (docs/coverage/x64_zen2.tsv groups AES/Crypto): + - Legacy SSE (preserves YMM_dst[255:128]): + AESENC, AESENCLAST, AESDEC, AESDECLAST, AESIMC, AESKEYGENASSIST, PCLMULQDQ + - VEX.128 (zeroes YMM_dst[255:128]): + VAESENC, VAESENCLAST, VAESDEC, VAESDECLAST, VAESIMC, VAESKEYGENASSIST, VPCLMULQDQ + +Transport / ABI glue: + - MOVDQA / MOVDQU (legacy 128-bit reg/flat-[rcx|rdx|r8] loads, [r8] stores, reg-reg copies; preserves YMM[255:128]) + - VMOVDQA / VMOVDQU (VEX.128 128-bit zeroes YMM[255:128]; VEX.256 256-bit move glue only) + - VZEROUPPER (zeroes YMM[255:128] of all defined XMMs) + - terminal RET + +VEX.256 compute ops (VAES*/VPCLMULQDQ on YMM), EVEX/XOP, nonvolatile XMM6-15/YMM6-15, +nonvolatile/unsupported GPRs, undefined XMM/YMM reads, displaced/indexed/RIP-relative/ +non-argument memory operands, stores outside [r8], instruction prefixes, branches, and +missing or trailing instructions after ret are rejected. +""" + +import argparse +import os +from pathlib import Path +import sys +import tempfile + +import pefile +from iced_x86 import ( + Code, + Decoder, + EncodingKind, + FlowControl, + MemorySizeExt, + OpKind, + Register as R, + RegisterExt, +) + +from cpu_leaf_aot import bounded_code, export_rva + + +ARGUMENTS = {R.RCX: "rcx", R.RDX: "rdx", R.R8: "r8"} + +VOLATILE_XMM = {getattr(R, f"XMM{i}"): i for i in range(6)} +VOLATILE_YMM = {getattr(R, f"YMM{i}"): i for i in range(6)} +NONVOLATILE_VEC = ( + {getattr(R, f"XMM{i}") for i in range(6, 32)} + | {getattr(R, f"YMM{i}") for i in range(6, 32)} + | {getattr(R, f"ZMM{i}") for i in range(32)} +) +NONVOLATILE_GPR = { + R.RBX, R.EBX, R.BX, R.BL, R.BH, + R.RBP, R.EBP, R.BP, R.BPL, + R.RSI, R.ESI, R.SI, R.SIL, + R.RDI, R.EDI, R.DI, R.DIL, + R.RSP, R.ESP, R.SP, R.SPL, + R.R12, R.R12D, R.R12W, R.R12L, + R.R13, R.R13D, R.R13W, R.R13L, + R.R14, R.R14D, R.R14W, R.R14L, + R.R15, R.R15D, R.R15W, R.R15L, +} + +# (helper, arity, has_imm8, is_vex) +CRYPTO_SPECS = { + Code.AESENC_XMM_XMMM128: ("op_aesenc", 2, False, False), + Code.AESENCLAST_XMM_XMMM128: ("op_aesenclast", 2, False, False), + Code.AESDEC_XMM_XMMM128: ("op_aesdec", 2, False, False), + Code.AESDECLAST_XMM_XMMM128: ("op_aesdeclast", 2, False, False), + Code.AESIMC_XMM_XMMM128: ("op_aesimc", 1, False, False), + Code.AESKEYGENASSIST_XMM_XMMM128_IMM8: ("op_aeskeygenassist", 1, True, False), + Code.PCLMULQDQ_XMM_XMMM128_IMM8: ("op_pclmulqdq", 2, True, False), + Code.VEX_VAESENC_XMM_XMM_XMMM128: ("op_aesenc", 2, False, True), + Code.VEX_VAESENCLAST_XMM_XMM_XMMM128: ("op_aesenclast", 2, False, True), + Code.VEX_VAESDEC_XMM_XMM_XMMM128: ("op_aesdec", 2, False, True), + Code.VEX_VAESDECLAST_XMM_XMM_XMMM128: ("op_aesdeclast", 2, False, True), + Code.VEX_VAESIMC_XMM_XMMM128: ("op_aesimc", 1, False, True), + Code.VEX_VAESKEYGENASSIST_XMM_XMMM128_IMM8: ("op_aeskeygenassist", 1, True, True), + Code.VEX_VPCLMULQDQ_XMM_XMM_XMMM128_IMM8: ("op_pclmulqdq", 2, True, True), +} + +# (is_ymm, is_vex) +MOVE_LOAD_CODES = { + Code.MOVDQA_XMM_XMMM128: (False, False), + Code.MOVDQU_XMM_XMMM128: (False, False), + Code.VEX_VMOVDQA_XMM_XMMM128: (False, True), + Code.VEX_VMOVDQU_XMM_XMMM128: (False, True), + Code.VEX_VMOVDQA_YMM_YMMM256: (True, True), + Code.VEX_VMOVDQU_YMM_YMMM256: (True, True), +} +MOVE_STORE_CODES = { + Code.MOVDQA_XMMM128_XMM: (False, False), + Code.MOVDQU_XMMM128_XMM: (False, False), + Code.VEX_VMOVDQA_XMMM128_XMM: (False, True), + Code.VEX_VMOVDQU_XMMM128_XMM: (False, True), + Code.VEX_VMOVDQA_YMMM256_YMM: (True, True), + Code.VEX_VMOVDQU_YMMM256_YMM: (True, True), +} + +ALLOWED_CODES = { + Code.RETNQ, + Code.VEX_VZEROUPPER, + *CRYPTO_SPECS, + *MOVE_LOAD_CODES, + *MOVE_STORE_CODES, +} + +PRELUDE = """#include +#include +#include +#if defined(_MSC_VER) +#include +#endif + +#if defined(_MSC_VER) +extern "C" __declspec(dllexport) std::uint32_t host_has_aes_pclmul_avx() { + int info[4]{}; + __cpuid(info, 1); + const int need = (1 << 1) | (1 << 25) | (1 << 27) | (1 << 28); + if ((info[2] & need) != need) return 0u; + return (_xgetbv(0) & 6u) == 6u ? 1u : 0u; +} +#endif + +using word = std::uint64_t; + +struct Vec128 { + std::uint64_t q[2]; +}; + +struct Vec256 { + std::uint64_t q[4]; +}; + +static inline Vec128 low128(const Vec256& v) { + return {{v.q[0], v.q[1]}}; +} + +static inline void set_low128(Vec256& dst, const Vec128& v) { + dst.q[0] = v.q[0]; + dst.q[1] = v.q[1]; +} + +static inline Vec256 zext256(const Vec128& v) { + return {{v.q[0], v.q[1], 0ull, 0ull}}; +} + +static inline Vec128 load128(word address) { + std::atomic_signal_fence(std::memory_order_seq_cst); + Vec128 out{}; + std::memcpy(out.q, reinterpret_cast(address), sizeof(out.q)); + const volatile std::uint64_t q0 = out.q[0]; + const volatile std::uint64_t q1 = out.q[1]; + std::atomic_signal_fence(std::memory_order_seq_cst); + return {{q0, q1}}; +} + +static inline Vec256 load256(word address) { + std::atomic_signal_fence(std::memory_order_seq_cst); + Vec256 out{}; + std::memcpy(out.q, reinterpret_cast(address), sizeof(out.q)); + const volatile std::uint64_t q0 = out.q[0]; + const volatile std::uint64_t q1 = out.q[1]; + const volatile std::uint64_t q2 = out.q[2]; + const volatile std::uint64_t q3 = out.q[3]; + std::atomic_signal_fence(std::memory_order_seq_cst); + return {{q0, q1, q2, q3}}; +} + +static inline void store128(word address, const Vec128& v) { + std::atomic_signal_fence(std::memory_order_seq_cst); + std::memcpy(reinterpret_cast(address), v.q, sizeof(v.q)); + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +static inline void store256(word address, const Vec256& v) { + std::atomic_signal_fence(std::memory_order_seq_cst); + std::memcpy(reinterpret_cast(address), v.q, sizeof(v.q)); + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +static constexpr std::uint8_t AES_SBOX[256] = { + 0x63u, 0x7Cu, 0x77u, 0x7Bu, 0xF2u, 0x6Bu, 0x6Fu, 0xC5u, 0x30u, 0x01u, 0x67u, 0x2Bu, 0xFEu, 0xD7u, 0xABu, 0x76u, + 0xCAu, 0x82u, 0xC9u, 0x7Du, 0xFAu, 0x59u, 0x47u, 0xF0u, 0xADu, 0xD4u, 0xA2u, 0xAFu, 0x9Cu, 0xA4u, 0x72u, 0xC0u, + 0xB7u, 0xFDu, 0x93u, 0x26u, 0x36u, 0x3Fu, 0xF7u, 0xCCu, 0x34u, 0xA5u, 0xE5u, 0xF1u, 0x71u, 0xD8u, 0x31u, 0x15u, + 0x04u, 0xC7u, 0x23u, 0xC3u, 0x18u, 0x96u, 0x05u, 0x9Au, 0x07u, 0x12u, 0x80u, 0xE2u, 0xEBu, 0x27u, 0xB2u, 0x75u, + 0x09u, 0x83u, 0x2Cu, 0x1Au, 0x1Bu, 0x6Eu, 0x5Au, 0xA0u, 0x52u, 0x3Bu, 0xD6u, 0xB3u, 0x29u, 0xE3u, 0x2Fu, 0x84u, + 0x53u, 0xD1u, 0x00u, 0xEDu, 0x20u, 0xFCu, 0xB1u, 0x5Bu, 0x6Au, 0xCBu, 0xBEu, 0x39u, 0x4Au, 0x4Cu, 0x58u, 0xCFu, + 0xD0u, 0xEFu, 0xAAu, 0xFBu, 0x43u, 0x4Du, 0x33u, 0x85u, 0x45u, 0xF9u, 0x02u, 0x7Fu, 0x50u, 0x3Cu, 0x9Fu, 0xA8u, + 0x51u, 0xA3u, 0x40u, 0x8Fu, 0x92u, 0x9Du, 0x38u, 0xF5u, 0xBCu, 0xB6u, 0xDAu, 0x21u, 0x10u, 0xFFu, 0xF3u, 0xD2u, + 0xCDu, 0x0Cu, 0x13u, 0xECu, 0x5Fu, 0x97u, 0x44u, 0x17u, 0xC4u, 0xA7u, 0x7Eu, 0x3Du, 0x64u, 0x5Du, 0x19u, 0x73u, + 0x60u, 0x81u, 0x4Fu, 0xDCu, 0x22u, 0x2Au, 0x90u, 0x88u, 0x46u, 0xEEu, 0xB8u, 0x14u, 0xDEu, 0x5Eu, 0x0Bu, 0xDBu, + 0xE0u, 0x32u, 0x3Au, 0x0Au, 0x49u, 0x06u, 0x24u, 0x5Cu, 0xC2u, 0xD3u, 0xACu, 0x62u, 0x91u, 0x95u, 0xE4u, 0x79u, + 0xE7u, 0xC8u, 0x37u, 0x6Du, 0x8Du, 0xD5u, 0x4Eu, 0xA9u, 0x6Cu, 0x56u, 0xF4u, 0xEAu, 0x65u, 0x7Au, 0xAEu, 0x08u, + 0xBAu, 0x78u, 0x25u, 0x2Eu, 0x1Cu, 0xA6u, 0xB4u, 0xC6u, 0xE8u, 0xDDu, 0x74u, 0x1Fu, 0x4Bu, 0xBDu, 0x8Bu, 0x8Au, + 0x70u, 0x3Eu, 0xB5u, 0x66u, 0x48u, 0x03u, 0xF6u, 0x0Eu, 0x61u, 0x35u, 0x57u, 0xB9u, 0x86u, 0xC1u, 0x1Du, 0x9Eu, + 0xE1u, 0xF8u, 0x98u, 0x11u, 0x69u, 0xD9u, 0x8Eu, 0x94u, 0x9Bu, 0x1Eu, 0x87u, 0xE9u, 0xCEu, 0x55u, 0x28u, 0xDFu, + 0x8Cu, 0xA1u, 0x89u, 0x0Du, 0xBFu, 0xE6u, 0x42u, 0x68u, 0x41u, 0x99u, 0x2Du, 0x0Fu, 0xB0u, 0x54u, 0xBBu, 0x16u, +}; + +static constexpr std::uint8_t AES_INV_SBOX[256] = { + 0x52u, 0x09u, 0x6Au, 0xD5u, 0x30u, 0x36u, 0xA5u, 0x38u, 0xBFu, 0x40u, 0xA3u, 0x9Eu, 0x81u, 0xF3u, 0xD7u, 0xFBu, + 0x7Cu, 0xE3u, 0x39u, 0x82u, 0x9Bu, 0x2Fu, 0xFFu, 0x87u, 0x34u, 0x8Eu, 0x43u, 0x44u, 0xC4u, 0xDEu, 0xE9u, 0xCBu, + 0x54u, 0x7Bu, 0x94u, 0x32u, 0xA6u, 0xC2u, 0x23u, 0x3Du, 0xEEu, 0x4Cu, 0x95u, 0x0Bu, 0x42u, 0xFAu, 0xC3u, 0x4Eu, + 0x08u, 0x2Eu, 0xA1u, 0x66u, 0x28u, 0xD9u, 0x24u, 0xB2u, 0x76u, 0x5Bu, 0xA2u, 0x49u, 0x6Du, 0x8Bu, 0xD1u, 0x25u, + 0x72u, 0xF8u, 0xF6u, 0x64u, 0x86u, 0x68u, 0x98u, 0x16u, 0xD4u, 0xA4u, 0x5Cu, 0xCCu, 0x5Du, 0x65u, 0xB6u, 0x92u, + 0x6Cu, 0x70u, 0x48u, 0x50u, 0xFDu, 0xEDu, 0xB9u, 0xDAu, 0x5Eu, 0x15u, 0x46u, 0x57u, 0xA7u, 0x8Du, 0x9Du, 0x84u, + 0x90u, 0xD8u, 0xABu, 0x00u, 0x8Cu, 0xBCu, 0xD3u, 0x0Au, 0xF7u, 0xE4u, 0x58u, 0x05u, 0xB8u, 0xB3u, 0x45u, 0x06u, + 0xD0u, 0x2Cu, 0x1Eu, 0x8Fu, 0xCAu, 0x3Fu, 0x0Fu, 0x02u, 0xC1u, 0xAFu, 0xBDu, 0x03u, 0x01u, 0x13u, 0x8Au, 0x6Bu, + 0x3Au, 0x91u, 0x11u, 0x41u, 0x4Fu, 0x67u, 0xDCu, 0xEAu, 0x97u, 0xF2u, 0xCFu, 0xCEu, 0xF0u, 0xB4u, 0xE6u, 0x73u, + 0x96u, 0xACu, 0x74u, 0x22u, 0xE7u, 0xADu, 0x35u, 0x85u, 0xE2u, 0xF9u, 0x37u, 0xE8u, 0x1Cu, 0x75u, 0xDFu, 0x6Eu, + 0x47u, 0xF1u, 0x1Au, 0x71u, 0x1Du, 0x29u, 0xC5u, 0x89u, 0x6Fu, 0xB7u, 0x62u, 0x0Eu, 0xAAu, 0x18u, 0xBEu, 0x1Bu, + 0xFCu, 0x56u, 0x3Eu, 0x4Bu, 0xC6u, 0xD2u, 0x79u, 0x20u, 0x9Au, 0xDBu, 0xC0u, 0xFEu, 0x78u, 0xCDu, 0x5Au, 0xF4u, + 0x1Fu, 0xDDu, 0xA8u, 0x33u, 0x88u, 0x07u, 0xC7u, 0x31u, 0xB1u, 0x12u, 0x10u, 0x59u, 0x27u, 0x80u, 0xECu, 0x5Fu, + 0x60u, 0x51u, 0x7Fu, 0xA9u, 0x19u, 0xB5u, 0x4Au, 0x0Du, 0x2Du, 0xE5u, 0x7Au, 0x9Fu, 0x93u, 0xC9u, 0x9Cu, 0xEFu, + 0xA0u, 0xE0u, 0x3Bu, 0x4Du, 0xAEu, 0x2Au, 0xF5u, 0xB0u, 0xC8u, 0xEBu, 0xBBu, 0x3Cu, 0x83u, 0x53u, 0x99u, 0x61u, + 0x17u, 0x2Bu, 0x04u, 0x7Eu, 0xBAu, 0x77u, 0xD6u, 0x26u, 0xE1u, 0x69u, 0x14u, 0x63u, 0x55u, 0x21u, 0x0Cu, 0x7Du, +}; + +static inline std::uint8_t aes_gf_mul(std::uint8_t a, std::uint8_t b) { + std::uint8_t p = 0u; + for (int i = 0; i < 8; ++i) { + if ((b & 1u) != 0u) { + p ^= a; + } + const bool hi = (a & 0x80u) != 0u; + a = static_cast(a << 1); + if (hi) { + a ^= 0x1Bu; + } + b >>= 1; + } + return p; +} + +static inline void unpack_bytes(const Vec128& v, std::uint8_t out[16]) { + std::memcpy(out, v.q, 16); +} + +static inline Vec128 pack_bytes(const std::uint8_t in[16]) { + Vec128 v{}; + std::memcpy(v.q, in, 16); + return v; +} + +static inline Vec128 xor128(const Vec128& a, const Vec128& b) { + return {{a.q[0] ^ b.q[0], a.q[1] ^ b.q[1]}}; +} + +static inline void aes_shift_sub(const std::uint8_t in[16], std::uint8_t out[16]) { + static constexpr unsigned idx[16] = {0u, 5u, 10u, 15u, 4u, 9u, 14u, 3u, 8u, 13u, 2u, 7u, 12u, 1u, 6u, 11u}; + for (unsigned i = 0u; i < 16u; ++i) { + out[i] = AES_SBOX[in[idx[i]]]; + } +} + +static inline void aes_inv_shift_sub(const std::uint8_t in[16], std::uint8_t out[16]) { + static constexpr unsigned idx[16] = {0u, 13u, 10u, 7u, 4u, 1u, 14u, 11u, 8u, 5u, 2u, 15u, 12u, 9u, 6u, 3u}; + for (unsigned i = 0u; i < 16u; ++i) { + out[i] = AES_INV_SBOX[in[idx[i]]]; + } +} + +static inline void aes_mix_columns(const std::uint8_t in[16], std::uint8_t out[16]) { + for (unsigned c = 0u; c < 4u; ++c) { + const std::uint8_t a0 = in[c * 4u + 0u]; + const std::uint8_t a1 = in[c * 4u + 1u]; + const std::uint8_t a2 = in[c * 4u + 2u]; + const std::uint8_t a3 = in[c * 4u + 3u]; + out[c * 4u + 0u] = static_cast(aes_gf_mul(2u, a0) ^ aes_gf_mul(3u, a1) ^ a2 ^ a3); + out[c * 4u + 1u] = static_cast(a0 ^ aes_gf_mul(2u, a1) ^ aes_gf_mul(3u, a2) ^ a3); + out[c * 4u + 2u] = static_cast(a0 ^ a1 ^ aes_gf_mul(2u, a2) ^ aes_gf_mul(3u, a3)); + out[c * 4u + 3u] = static_cast(aes_gf_mul(3u, a0) ^ a1 ^ a2 ^ aes_gf_mul(2u, a3)); + } +} + +static inline void aes_inv_mix_columns(const std::uint8_t in[16], std::uint8_t out[16]) { + for (unsigned c = 0u; c < 4u; ++c) { + const std::uint8_t a0 = in[c * 4u + 0u]; + const std::uint8_t a1 = in[c * 4u + 1u]; + const std::uint8_t a2 = in[c * 4u + 2u]; + const std::uint8_t a3 = in[c * 4u + 3u]; + out[c * 4u + 0u] = static_cast(aes_gf_mul(0x0Eu, a0) ^ aes_gf_mul(0x0Bu, a1) ^ aes_gf_mul(0x0Du, a2) ^ aes_gf_mul(0x09u, a3)); + out[c * 4u + 1u] = static_cast(aes_gf_mul(0x09u, a0) ^ aes_gf_mul(0x0Eu, a1) ^ aes_gf_mul(0x0Bu, a2) ^ aes_gf_mul(0x0Du, a3)); + out[c * 4u + 2u] = static_cast(aes_gf_mul(0x0Du, a0) ^ aes_gf_mul(0x09u, a1) ^ aes_gf_mul(0x0Eu, a2) ^ aes_gf_mul(0x0Bu, a3)); + out[c * 4u + 3u] = static_cast(aes_gf_mul(0x0Bu, a0) ^ aes_gf_mul(0x0Du, a1) ^ aes_gf_mul(0x09u, a2) ^ aes_gf_mul(0x0Eu, a3)); + } +} + +static inline Vec128 op_aesenc(const Vec128& state, const Vec128& key) { + std::uint8_t b[16]{}, tmp[16]{}, mixed[16]{}; + unpack_bytes(state, b); + aes_shift_sub(b, tmp); + aes_mix_columns(tmp, mixed); + return xor128(pack_bytes(mixed), key); +} + +static inline Vec128 op_aesenclast(const Vec128& state, const Vec128& key) { + std::uint8_t b[16]{}, tmp[16]{}; + unpack_bytes(state, b); + aes_shift_sub(b, tmp); + return xor128(pack_bytes(tmp), key); +} + +static inline Vec128 op_aesdec(const Vec128& state, const Vec128& key) { + std::uint8_t b[16]{}, tmp[16]{}, mixed[16]{}; + unpack_bytes(state, b); + aes_inv_shift_sub(b, tmp); + aes_inv_mix_columns(tmp, mixed); + return xor128(pack_bytes(mixed), key); +} + +static inline Vec128 op_aesdeclast(const Vec128& state, const Vec128& key) { + std::uint8_t b[16]{}, tmp[16]{}; + unpack_bytes(state, b); + aes_inv_shift_sub(b, tmp); + return xor128(pack_bytes(tmp), key); +} + +static inline Vec128 op_aesimc(const Vec128& src) { + std::uint8_t b[16]{}, mixed[16]{}; + unpack_bytes(src, b); + aes_inv_mix_columns(b, mixed); + return pack_bytes(mixed); +} + +static inline std::uint32_t aes_sub_word(std::uint32_t w) { + return static_cast(AES_SBOX[w & 0xFFu]) + | (static_cast(AES_SBOX[(w >> 8) & 0xFFu]) << 8) + | (static_cast(AES_SBOX[(w >> 16) & 0xFFu]) << 16) + | (static_cast(AES_SBOX[(w >> 24) & 0xFFu]) << 24); +} + +static inline Vec128 op_aeskeygenassist(const Vec128& src, std::uint8_t imm8) { + std::uint32_t w[4]{}; + std::memcpy(w, src.q, 16); + const std::uint32_t s1 = aes_sub_word(w[1]); + const std::uint32_t s3 = aes_sub_word(w[3]); + const std::uint32_t rcon = static_cast(imm8); + const std::uint32_t out[4] = { + s1, + ((s1 >> 8) | (s1 << 24)) ^ rcon, + s3, + ((s3 >> 8) | (s3 << 24)) ^ rcon, + }; + Vec128 res{}; + std::memcpy(res.q, out, 16); + return res; +} + +static inline Vec128 op_pclmulqdq(const Vec128& src1, const Vec128& src2, std::uint8_t imm8) { + const std::uint64_t a = ((imm8 & 0x01u) != 0u) ? src1.q[1] : src1.q[0]; + const std::uint64_t b = ((imm8 & 0x10u) != 0u) ? src2.q[1] : src2.q[0]; + std::uint64_t lo = 0ull; + std::uint64_t hi = 0ull; + for (unsigned i = 0u; i < 64u; ++i) { + if (((b >> i) & 1ull) != 0ull) { + lo ^= (a << i); + if (i != 0u) { + hi ^= (a >> (64u - i)); + } + } + } + return {{lo, hi}}; +} +""" + + +def vec_index(register, ins): + """Map volatile XMM0..XMM5/YMM0..YMM5 to (index, is_ymm), rejecting nonvolatile/unsupported.""" + if register in VOLATILE_XMM: + return VOLATILE_XMM[register], False + if register in VOLATILE_YMM: + return VOLATILE_YMM[register], True + if register in NONVOLATILE_VEC: + raise ValueError(f"nonvolatile vector register {register} at RVA {ins.ip:#x}: {ins}") + raise ValueError(f"unsupported vector register {register} at RVA {ins.ip:#x}: {ins}") + + +def flat_address(ins, expected_bytes, *, store=False): + """Lower a flat zero-displacement [rcx|rdx|r8] memory operand (stores only to [r8]).""" + if ins.is_ip_rel_memory_operand or ins.memory_base in (R.RIP, R.EIP): + raise ValueError(f"RIP-relative memory operand at RVA {ins.ip:#x}: {ins}") + if ins.memory_index != R.NONE: + raise ValueError(f"SIB index memory operand at RVA {ins.ip:#x}: {ins}") + base = ins.memory_base + if base == R.NONE or not RegisterExt.is_gpr64(base) or base not in ARGUMENTS: + if base in NONVOLATILE_GPR: + raise ValueError(f"nonvolatile GPR base {base} in memory operand at RVA {ins.ip:#x}: {ins}") + raise ValueError(f"bad base register in memory operand at RVA {ins.ip:#x}: {ins}") + if ins.memory_displacement != 0: + raise ValueError(f"displaced memory operand at RVA {ins.ip:#x}: {ins}") + if store and base != R.R8: + raise ValueError(f"non-r8 store memory operand at RVA {ins.ip:#x}: {ins}") + actual_bytes = MemorySizeExt.size(ins.memory_size) + if actual_bytes != expected_bytes: + raise ValueError( + f"unexpected {actual_bytes}-byte memory operand (expected {expected_bytes}) at RVA {ins.ip:#x}: {ins}" + ) + return ARGUMENTS[base] + + +def lift_code(name, start, raw): + """Decode and lift one bounded straight-line AES-NI / PCLMULQDQ leaf function.""" + instructions = list(Decoder(64, raw, ip=start)) + if not instructions or instructions[-1].next_ip != start + len(raw): + raise ValueError(f"truncated instruction stream in {name} at RVA {start:#x}") + if any(ins.is_invalid for ins in instructions): + bad = next(ins for ins in instructions if ins.is_invalid) + raise ValueError(f"invalid instruction at RVA {bad.ip:#x}") + + used_vec = set() + defined_xmm = set() + defined_ymm_hi = set() + statements = [] + returned = False + + def read_vec(op_index, ins, *, require_ymm=False): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register operand {op_index} at RVA {ins.ip:#x}: {ins}") + idx, wide = vec_index(ins.op_register(op_index), ins) + if wide != require_ymm: + raise ValueError(f"unexpected vector register width {ins.op_register(op_index)} at RVA {ins.ip:#x}: {ins}") + if idx not in defined_xmm or (require_ymm and idx not in defined_ymm_hi): + reg_label = f"ymm{idx}" if require_ymm else f"xmm{idx}" + raise ValueError(f"undefined vector register {reg_label} at RVA {ins.ip:#x}: {ins}") + used_vec.add(idx) + return f"ymm{idx}" if require_ymm else f"low128(ymm{idx})" + + def read_rm128(op_index, ins): + kind = ins.op_kind(op_index) + if kind == OpKind.REGISTER: + return read_vec(op_index, ins, require_ymm=False) + if kind == OpKind.MEMORY: + addr = flat_address(ins, 16, store=False) + load_var = f"ld_{ins.ip:x}_{op_index}" + statements.append(f"const Vec128 {load_var} = load128({addr});") + return load_var + raise ValueError(f"unsupported operand at RVA {ins.ip:#x}: {ins}") + + def read_rm256(op_index, ins): + kind = ins.op_kind(op_index) + if kind == OpKind.REGISTER: + return read_vec(op_index, ins, require_ymm=True) + if kind == OpKind.MEMORY: + addr = flat_address(ins, 32, store=False) + load_var = f"ld_{ins.ip:x}_{op_index}" + statements.append(f"const Vec256 {load_var} = load256({addr});") + return load_var + raise ValueError(f"unsupported operand at RVA {ins.ip:#x}: {ins}") + + def check_dst_vec(op_index, ins, *, expect_ymm=False): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register destination at RVA {ins.ip:#x}: {ins}") + idx, wide = vec_index(ins.op_register(op_index), ins) + if wide != expect_ymm: + raise ValueError(f"unexpected vector destination width at RVA {ins.ip:#x}: {ins}") + used_vec.add(idx) + return idx + + for ins in instructions: + if returned: + raise ValueError(f"unreachable instruction after ret at RVA {ins.ip:#x}: {ins}") + if ( + ins.has_lock_prefix + or ins.has_rep_prefix + or ins.has_repne_prefix + or ins.has_segment_prefix + or ins.has_xacquire_prefix + or ins.has_xrelease_prefix + ): + raise ValueError(f"unsupported instruction prefix at RVA {ins.ip:#x}: {ins}") + + op_code = ins.op_code() + encoding = op_code.encoding + if encoding == EncodingKind.EVEX or ins.op_mask != R.NONE or ins.zeroing_masking or ins.is_broadcast: + raise ValueError(f"unsupported EVEX instruction at RVA {ins.ip:#x}: {ins}") + if encoding == EncodingKind.XOP: + raise ValueError(f"unsupported XOP instruction at RVA {ins.ip:#x}: {ins}") + if ins.code != Code.RETNQ and ins.flow_control != FlowControl.NEXT: + raise ValueError(f"non-leaf branch or call at RVA {ins.ip:#x}: {ins}") + if encoding == EncodingKind.VEX and op_code.l == 1 and ins.code not in ( + Code.VEX_VMOVDQA_YMM_YMMM256, + Code.VEX_VMOVDQA_YMMM256_YMM, + Code.VEX_VMOVDQU_YMM_YMMM256, + Code.VEX_VMOVDQU_YMMM256_YMM, + ): + raise ValueError(f"unsupported VEX.256 instruction at RVA {ins.ip:#x}: {ins}") + if ins.code not in ALLOWED_CODES: + raise ValueError(f"unsupported instruction at RVA {ins.ip:#x}: {ins}") + + code = ins.code + if code == Code.RETNQ: + statements.append("return;") + returned = True + elif code == Code.VEX_VZEROUPPER: + for idx in sorted(defined_xmm): + statements.append(f"ymm{idx}.q[2] = 0ull;") + statements.append(f"ymm{idx}.q[3] = 0ull;") + defined_ymm_hi.add(idx) + elif code in CRYPTO_SPECS: + helper, arity, has_imm8, is_vex = CRYPTO_SPECS[code] + expected_enc = EncodingKind.VEX if is_vex else EncodingKind.LEGACY + if encoding != expected_enc: + raise ValueError(f"unexpected encoding for {helper} at RVA {ins.ip:#x}: {ins}") + if is_vex: + if arity == 2: + arg1 = read_vec(1, ins, require_ymm=False) + arg2 = read_rm128(2, ins) + args = [arg1, arg2] + else: + args = [read_rm128(1, ins)] + else: + if arity == 2: + arg1 = read_vec(0, ins, require_ymm=False) + arg2 = read_rm128(1, ins) + args = [arg1, arg2] + else: + args = [read_rm128(1, ins)] + if has_imm8: + imm8 = ins.immediate8 & 0xFF + args.append(f"{imm8:#x}u") + dst_idx = check_dst_vec(0, ins, expect_ymm=False) + call_expr = f"{helper}({', '.join(args)})" + if is_vex: + statements.append(f"ymm{dst_idx} = zext256({call_expr});") + defined_ymm_hi.add(dst_idx) + else: + statements.append(f"set_low128(ymm{dst_idx}, {call_expr});") + defined_xmm.add(dst_idx) + elif code in MOVE_LOAD_CODES: + is_ymm, is_vex = MOVE_LOAD_CODES[code] + if is_ymm: + src_expr = read_rm256(1, ins) + dst_idx = check_dst_vec(0, ins, expect_ymm=True) + statements.append(f"ymm{dst_idx} = {src_expr};") + defined_ymm_hi.add(dst_idx) + else: + src_expr = read_rm128(1, ins) + dst_idx = check_dst_vec(0, ins, expect_ymm=False) + if is_vex: + statements.append(f"ymm{dst_idx} = zext256({src_expr});") + defined_ymm_hi.add(dst_idx) + else: + statements.append(f"set_low128(ymm{dst_idx}, {src_expr});") + defined_xmm.add(dst_idx) + elif code in MOVE_STORE_CODES: + is_ymm, is_vex = MOVE_STORE_CODES[code] + src_expr = read_vec(1, ins, require_ymm=is_ymm) + if ins.op0_kind == OpKind.MEMORY: + addr = flat_address(ins, 32 if is_ymm else 16, store=True) + fn = "store256" if is_ymm else "store128" + statements.append(f"{fn}({addr}, {src_expr});") + else: + dst_idx = check_dst_vec(0, ins, expect_ymm=is_ymm) + if is_ymm: + statements.append(f"ymm{dst_idx} = {src_expr};") + defined_ymm_hi.add(dst_idx) + elif is_vex: + statements.append(f"ymm{dst_idx} = zext256({src_expr});") + defined_ymm_hi.add(dst_idx) + else: + statements.append(f"set_low128(ymm{dst_idx}, {src_expr});") + defined_xmm.add(dst_idx) + else: + raise ValueError(f"unsupported instruction at RVA {ins.ip:#x}: {ins}") + + if not returned: + raise ValueError(f"missing terminal ret in {name} at RVA {start + len(raw):#x}") + + decls = [f" Vec256 ymm{idx}{{}};" for idx in sorted(used_vec)] + body = [f" {stmt}" for stmt in statements] + lines = [ + f'extern "C" __declspec(dllexport) void lifted_{name}(word rcx, word rdx, word r8) {{', + " (void)rcx; (void)rdx; (void)r8;", + *decls, + *body, + "}", + ] + return "\n".join(lines), len(instructions) + + +def lift(pe, name): + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + source, count = lift_code(name, entry, raw) + return source, entry, count + + +def translate_pe(pe, names): + if pe.FILE_HEADER.Machine != 0x8664 or pe.OPTIONAL_HEADER.Magic != 0x20B: + raise ValueError("expected AMD64 PE32+") + lifted = [lift(pe, name) for name in names] + source = PRELUDE + "\n".join(f"\n{text}" for text, _, _ in lifted) + "\n" + meta = [(name, entry, count) for name, (_, entry, count) in zip(names, lifted)] + return source, meta + + +def translate(image, names): + with pefile.PE(str(image), fast_load=True) as pe: + return translate_pe(pe, names) + + +def _same_path(a, b): + try: + return os.path.samefile(a, b) + except OSError: + return a.resolve(strict=False) == b.resolve(strict=False) + + +def _write_atomic(path, text): + path.parent.mkdir(parents=True, exist_ok=True) + tmp_path = None + try: + with tempfile.NamedTemporaryFile( + mode="w", + encoding="utf-8", + dir=path.parent, + prefix=f".{path.name}.", + suffix=".tmp", + delete=False, + ) as handle: + tmp_path = Path(handle.name) + handle.write(text) + handle.flush() + os.replace(tmp_path, path) + except BaseException: + if tmp_path is not None: + tmp_path.unlink(missing_ok=True) + raise + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("image", type=Path) + parser.add_argument("exports", help="comma-separated export names") + parser.add_argument("output", type=Path) + args = parser.parse_args(argv) + try: + if not args.image.is_file(): + raise ValueError(f"input image is not a regular file: {args.image}") + names = [n for n in args.exports.split(",") if n] + if not names: + raise ValueError("expected at least one export name") + if args.output.is_symlink(): + raise ValueError(f"output path cannot be a symlink: {args.output}") + if args.output.exists() and args.output.is_dir(): + raise ValueError(f"output path is a directory: {args.output}") + if _same_path(args.image, args.output): + raise ValueError(f"output path matches input image: {args.output}") + source, meta = translate(args.image, names) + _write_atomic(args.output, source) + for name, entry, count in meta: + print(f"{name} at RVA {entry:#x}: {count} instructions") + return 0 + except (ValueError, OSError, pefile.PEFormatError) as error: + sys.stderr.write(f"{error}\n") + return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) From 9caa69850a4327ca4949cd8f5d3704d7bba10077 Mon Sep 17 00:00:00 2001 From: lukaslw-lab Date: Thu, 26 Nov 2026 04:19:40 +0100 Subject: [PATCH 113/240] startup: probe DirectStorage destinations instead of walking them with VirtualQuery (#2685) * startup: probe DirectStorage destinations instead of walking them with VirtualQuery destination_writable walked the destination with VirtualQuery. On the title's multi-gigabyte regions each query scans to the end of the region, which cost the storage worker about 10 ms of kernel time per request during the first load. Probe one byte per page with an atomic OR of zero under SEH instead (x2w_local::probe_writable, the write twin of probe_readable). It faults where a write would, changes no byte, and re-arms a guard page it trips. The test now also checks the guard bit after the refusal and that probed pages past the data keep their bytes. Co-Authored-By: Claude Opus 5.5 * startup: check DirectStorage destinations without touching them Review of #2685: the write probe raised a first-chance guard-page exception that a vectored handler sees, and it gave a copy-on-write page its private copy even when a later page refused the request. Remove probe_writable. destination_writable now reads page attributes only: one QueryWorkingSetEx per 512 pages accepts a destination whose pages are all valid, PAGE_READWRITE or PAGE_EXECUTE_READWRITE and not guarded; any other page goes to the VirtualQuery walk from main, unchanged. The test adds a first vectored handler that must see no guard-page exception on any refusal, a copy-on-write page followed by a no-access page whose first page must stay shared, and a committed but untouched destination that takes the fallback. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: lukaslw-lab <291379150+lukaslw-lab@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- docs/startup-runtime.md | 4 +- src/startup_stubs/xcrdapi.cpp | 29 +++++++- tests/startup_dstorage_destination_check.cpp | 78 +++++++++++++++++++- 3 files changed, 106 insertions(+), 5 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 82e43def4..2d01ed7ee 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1388,11 +1388,11 @@ cmake --build --preset release --target startup_inflate_probe ## DirectStorage destinations that are not writable -A request whose destination (a plain pointer, not 64 KiB page tokens) is not writable up to its declared capacity fails before any byte is written: the stand-in walks the destination with `VirtualQuery`, and a page that is uncommitted, read-only, `PAGE_GUARD` or `PAGE_NOACCESS` refuses the whole request. The log line ends `destination not writable`, `requests_failed` counts it, the next status entry reports `E_FAIL` and the queue goes on with later requests. Before this check, a destination shorter in memory than its declared capacity faulted inside the stand-in's copy (#870). The check covers the whole declared capacity, not only the bytes the request would write. Cost: one `VirtualQuery` per region the destination spans, per request that reaches the copy. +A request whose destination (a plain pointer, not 64 KiB page tokens) is not writable up to its declared capacity fails before any byte is written: the stand-in reads the attributes of the destination's pages without touching them, and a page that is uncommitted, read-only, `PAGE_GUARD` or `PAGE_NOACCESS` refuses the whole request. When every page is resident and plain read-write (`QueryWorkingSetEx`: valid, `PAGE_READWRITE` or `PAGE_EXECUTE_READWRITE`, no guard bit), the request goes ahead; otherwise the destination is walked with `VirtualQuery`, which also accepts copy-on-write pages. The log line ends `destination not writable`, `requests_failed` counts it, the next status entry reports `E_FAIL` and the queue goes on with later requests. Before this check, a destination shorter in memory than its declared capacity faulted inside the stand-in's copy (#870). The check covers the whole declared capacity, not only the bytes the request would write. Cost: one `QueryWorkingSetEx` per 512 pages of the declared capacity, per request that reaches the copy, plus the `VirtualQuery` walk when a page is not resident and plain read-write. On the title's multi-gigabyte regions each `VirtualQuery` scans to the end of the region, about 10 ms of kernel time per request (#2684). Failed requests report distinct status HRESULTs where the cause is known (#1843). A destination smaller than the data (`destination capacity exceeded`) reports `0x8007007A` (`ERROR_INSUFFICIENT_BUFFER`); a file read at or past the end, or crossing it, reports `0x80070026` (`ERROR_HANDLE_EOF`); every other cause stays `E_FAIL`. The same code is the `HRESULT` of the first-failure record. `OpenFile` with a null path returns `E_INVALIDARG`, `CreateQueue` with a null descriptor returns `E_INVALIDARG`, and a null output pointer returns `E_POINTER`; the output is set to null on every refusal. `tests/startup_dstorage_destination_check.cpp` pins each code on the real stand-in. -`tests/startup_dstorage_destination_check.cpp` (ctest `startup_dstorage_destination`) sends memory-source requests through the real queue: a read-only, a guard and a no-access middle page, and a capacity one page past the committed pages. Each must fail with the process alive and the bytes of the pages before the bad one still `0xAA`. Afterwards, requests into a fully writable (`PAGE_READWRITE`) buffer and a copy-on-write (`PAGE_WRITECOPY`) mapped view on the same queue must write every byte: +`tests/startup_dstorage_destination_check.cpp` (ctest `startup_dstorage_destination`) sends memory-source requests through the real queue: a read-only, a guard and a no-access middle page, and a capacity one page past the committed pages. Each must fail with the process alive and the bytes of the pages before the bad one still `0xAA`; the guard page must still be `PAGE_GUARD` afterwards, and a vectored exception handler must see no guard-page exception. A copy-on-write page followed by a no-access page must be refused with the first page still shared (`QueryWorkingSetEx`) and unchanged. A writable destination whose capacity is three pages but whose data is one page must succeed with the two unwritten pages still `0xAA`, and a committed page that was never touched (not resident) must be accepted. Afterwards, requests into a fully writable (`PAGE_READWRITE`) buffer and a copy-on-write (`PAGE_WRITECOPY`) mapped view on the same queue must write every byte: ```powershell ctest --preset release --no-tests=error -R '^startup_dstorage_destination$' -V diff --git a/src/startup_stubs/xcrdapi.cpp b/src/startup_stubs/xcrdapi.cpp index 50d543a16..1a2806889 100644 --- a/src/startup_stubs/xcrdapi.cpp +++ b/src/startup_stubs/xcrdapi.cpp @@ -152,9 +152,33 @@ static bool has_zlib_header(const unsigned char* bytes, std::size_t size) return true; } +// True when every page of [start, end) is resident and plain read-write: valid in the working set, PAGE_READWRITE +// or PAGE_EXECUTE_READWRITE, no guard bit. One QueryWorkingSetEx per 512 pages, so the cost follows the +// destination's size, not the region's. Reads attributes only; no page is touched. +static bool resident_read_write(std::uintptr_t start, std::uintptr_t end) +{ + PSAPI_WORKING_SET_EX_INFORMATION pages[512]; + std::uintptr_t page = start & ~std::uintptr_t{0xFFF}; + while (page < end) { + DWORD count = 0; + for (; count < 512 && page < end; ++count, page += 0x1000) pages[count].VirtualAddress = reinterpret_cast(page); + if (!QueryWorkingSetEx(GetCurrentProcess(), pages, count * sizeof(pages[0]))) return false; + for (DWORD i = 0; i < count; ++i) { + const auto& page_info = pages[i].VirtualAttributes; + const DWORD protect = static_cast(page_info.Win32Protection); + if (!page_info.Valid || page_info.Bad || (protect & PAGE_GUARD) || + ((protect & 0xFF) != PAGE_READWRITE && (protect & 0xFF) != PAGE_EXECUTE_READWRITE)) + return false; + } + } + return true; +} + // True when every byte of [destination, destination + bytes) is committed and writable, with no guard or -// no-access page in between. Walks the regions one VirtualQuery at a time, so a destination that spans -// regions of different protection is judged page by page. Nothing is written or touched. +// no-access page in between. Nothing is written or touched. Resident read-write pages are accepted from +// their working-set attributes; any other page (not resident, copy-on-write, guard, no access) sends the +// destination to the VirtualQuery walk, which judges it region by region. That walk is slow on the title's +// large regions: each query scans to the end of the region (#2684). static bool destination_writable(const void* destination, std::size_t bytes) { if (bytes == 0) return true; @@ -162,6 +186,7 @@ static bool destination_writable(const void* destination, std::size_t bytes) if (!destination || bytes > UINTPTR_MAX - cursor) return false; x2w_local::commit_lazy(destination, bytes); // lazily mapped physical pages (X2W_XMEM_LAZY_COMMIT) const std::uintptr_t end = cursor + bytes; + if (resident_read_write(cursor, end)) return true; while (cursor < end) { MEMORY_BASIC_INFORMATION info{}; if (!VirtualQuery(reinterpret_cast(cursor), &info, sizeof(info)) || info.State != MEM_COMMIT) diff --git a/tests/startup_dstorage_destination_check.cpp b/tests/startup_dstorage_destination_check.cpp index 6e456b9b8..1c05da696 100644 --- a/tests/startup_dstorage_destination_check.cpp +++ b/tests/startup_dstorage_destination_check.cpp @@ -12,6 +12,7 @@ #define NOMINMAX #endif #include +#include #include #include @@ -33,9 +34,16 @@ using OpenFileFn = long(__stdcall*)(void*, const wchar_t*, const void*, void**); constexpr unsigned page = 4096; constexpr unsigned pages = 3; constexpr unsigned bytes = pages * page; -constexpr unsigned cases = 12; +constexpr unsigned cases = 15; unsigned char source[bytes]; int failures; +volatile LONG guard_notifications; // first-chance guard-page exceptions any thread raised + +LONG CALLBACK count_guard(EXCEPTION_POINTERS* info) +{ + if (info->ExceptionRecord->ExceptionCode == STATUS_GUARD_PAGE_VIOLATION) InterlockedIncrement(&guard_notifications); + return EXCEPTION_CONTINUE_SEARCH; +} Object* status; Object* queue; @@ -84,6 +92,14 @@ unsigned char* fresh_region() return region; } +// A guard page must still be armed after the check; other protections are not checked here. +bool guard_kept(const unsigned char* at, DWORD protect) +{ + if (!(protect & PAGE_GUARD)) return true; + MEMORY_BASIC_INFORMATION info{}; + return VirtualQuery(at, &info, sizeof(info)) && (info.Protect & PAGE_GUARD); +} + // Refusal: the middle page, or the last, is made unusable in the way `how` names. void refused(const char* name, DWORD protect, bool decommit_last) { @@ -94,12 +110,15 @@ void refused(const char* name, DWORD protect, bool decommit_last) if (decommit_last) ok = VirtualFree(region + 2 * page, page, MEM_DECOMMIT) != 0; else ok = VirtualProtect(region + page, page, protect, &old) != 0; if (!ok) { fail(name, "could not change the page"); VirtualFree(region, 0, MEM_RELEASE); return; } + const LONG guards_before = guard_notifications; const long hr = run_request(region, bytes, decommit_last ? page : bytes); if (hr == -1) fail(name, "no completion"); + else if (guard_notifications != guards_before) fail(name, "the check raised a guard-page exception"); else if (hr == 0) fail(name, "request succeeded"); // The page the case changed is not read (a guard or no-access page would trip the check itself). else if (!untouched(region, 0, page)) fail(name, "first page was written"); else if (!decommit_last && !untouched(region, 2 * page, bytes)) fail(name, "last page was written"); + else if (!guard_kept(region + page, protect)) fail(name, "guard page lost its guard bit"); else std::printf("ok: %s refused, bytes before the bad page intact\n", name); VirtualFree(region, 0, MEM_RELEASE); } @@ -126,6 +145,8 @@ int main(int argc, char** argv) status = static_cast(status_pointer); queue = static_cast(queue_pointer); for (unsigned i = 0; i < bytes; ++i) source[i] = static_cast(i % 251); + // Observes every first-chance exception before any handler of the stand-in: the check must raise none. + if (!AddVectoredExceptionHandler(1, count_guard)) return 1; refused("read-only middle page", PAGE_READONLY, false); refused("guard middle page", PAGE_READWRITE | PAGE_GUARD, false); @@ -142,6 +163,25 @@ int main(int argc, char** argv) else std::printf("ok: writable control after the refusals wrote every byte\n"); VirtualFree(region, 0, MEM_RELEASE); + // Committed but never touched: not in the working set, so judged by the VirtualQuery walk, and writable. + auto* untouched_region = static_cast(VirtualAlloc(nullptr, bytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); + if (!untouched_region) return 1; + const long cold_hr = run_request(untouched_region, bytes, bytes); + if (cold_hr != 0) fail("non-resident destination", "request failed"); + else if (std::memcmp(untouched_region, source, bytes) != 0) fail("non-resident destination", "bytes differ"); + else std::printf("ok: non-resident writable destination wrote every byte\n"); + VirtualFree(untouched_region, 0, MEM_RELEASE); + + // The check covers every page of the declared capacity; past the data it must leave each byte as it was. + unsigned char* roomy = fresh_region(); + if (!roomy) return 1; + const long roomy_hr = run_request(roomy, bytes, page); + if (roomy_hr != 0) fail("capacity past the data", "request failed"); + else if (std::memcmp(roomy, source, page) != 0) fail("capacity past the data", "data bytes differ"); + else if (!untouched(roomy, page, bytes)) fail("capacity past the data", "a byte past the data changed"); + else std::printf("ok: capacity past the data wrote the data, later bytes unchanged\n"); + VirtualFree(roomy, 0, MEM_RELEASE); + // Copy-on-write destination (PAGE_WRITECOPY) is also allowed and must succeed. HANDLE mapping = CreateFileMappingA(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, bytes, nullptr); auto* cow = mapping ? static_cast(MapViewOfFile(mapping, FILE_MAP_COPY, 0, 0, bytes)) : nullptr; @@ -161,6 +201,42 @@ int main(int argc, char** argv) } if (mapping) CloseHandle(mapping); + // A copy-on-write page followed by a no-access page: the request is refused, and the first page stays + // shared (the check took no private copy of it) with its bytes unchanged. + HANDLE shared_mapping = CreateFileMappingA(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, 2 * page, nullptr); + auto* filler = shared_mapping ? static_cast(MapViewOfFile(shared_mapping, FILE_MAP_WRITE, 0, 0, 2 * page)) : nullptr; + auto* cow_pair = shared_mapping ? static_cast(MapViewOfFile(shared_mapping, FILE_MAP_COPY, 0, 0, 2 * page)) : nullptr; + DWORD old_protect = 0; + if (!filler || !cow_pair) { + fail("copy-on-write before no-access", "MapViewOfFile"); + } else { + std::memset(filler, 0xAA, 2 * page); + volatile unsigned char sink = cow_pair[0]; // a read maps the first page in, still shared + (void)sink; + PSAPI_WORKING_SET_EX_INFORMATION first{}; + first.VirtualAddress = cow_pair; + if (!VirtualProtect(cow_pair + page, page, PAGE_NOACCESS, &old_protect)) { + fail("copy-on-write before no-access", "VirtualProtect"); + } else if (!QueryWorkingSetEx(GetCurrentProcess(), &first, sizeof(first)) || !first.VirtualAttributes.Valid || + !first.VirtualAttributes.Shared) { + fail("copy-on-write before no-access", "first page not resident and shared before the request"); + } else { + const long pair_hr = run_request(cow_pair, 2 * page, 2 * page); + first.VirtualAttributes.Flags = 0; + const bool queried = QueryWorkingSetEx(GetCurrentProcess(), &first, sizeof(first)) != 0; + const bool still_shared = queried && (first.VirtualAttributes.Valid ? first.VirtualAttributes.Shared + : first.VirtualAttributes.Invalid.Shared); + if (pair_hr == -1) fail("copy-on-write before no-access", "no completion"); + else if (pair_hr == 0) fail("copy-on-write before no-access", "request succeeded"); + else if (!untouched(cow_pair, 0, page)) fail("copy-on-write before no-access", "first page was written"); + else if (!still_shared) fail("copy-on-write before no-access", "first page became private"); + else std::printf("ok: copy-on-write before no-access refused, first page still shared\n"); + } + } + if (cow_pair) UnmapViewOfFile(cow_pair); + if (filler) UnmapViewOfFile(filler); + if (shared_mapping) CloseHandle(shared_mapping); + // Distinct failure codes: a destination too small for the data, and a read past the end of a file. const long insufficient = static_cast(HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER)); const long end_of_file = static_cast(HRESULT_FROM_WIN32(ERROR_HANDLE_EOF)); From 7967c5afbed6584fad1cd5f9d84b5ae286438c50 Mon Sep 17 00:00:00 2001 From: RavenCurseBurg Date: Thu, 26 Nov 2026 11:20:22 +0800 Subject: [PATCH 114/240] tests: distinguish adapter notices from LDS readback diagnostics (#2704) Co-authored-by: RavenCurseBurg <360931527+RavenCurseBurg@users.noreply.github.com> --- tests/startup_compute_lds_b64_check.py | 11 +++++++---- .../startup_compute_lds_dual_atomics_check.py | 10 ++++++---- tests/startup_gfx2hlsl_compute_check.py | 18 ++++++++++++------ 3 files changed, 25 insertions(+), 14 deletions(-) diff --git a/tests/startup_compute_lds_b64_check.py b/tests/startup_compute_lds_b64_check.py index 312c2529a..220764ee4 100644 --- a/tests/startup_compute_lds_b64_check.py +++ b/tests/startup_compute_lds_b64_check.py @@ -7,6 +7,7 @@ compiles with DXC (cs_6_0) and runs WARP / hardware GPU readback verification via offscreen_check. """ +import re import struct import subprocess import sys @@ -20,7 +21,7 @@ sys.path.insert(0, str(HERE)) import gfx2hlsl as G -from startup_gfx2hlsl_compute_check import TGID_X, USER7, patch, refused, root_blob +from startup_gfx2hlsl_compute_check import TGID_X, USER7, patch, refused, renderer_diagnostics, root_blob def le32(w): @@ -325,11 +326,13 @@ def check_dispatch(dxc, runner, adapter, control=None): print(run.stdout, end='') if run.returncode == 77: return 77 + diagnostics = renderer_diagnostics(run.stderr, adapter) if control: - if run.returncode != 1 or 'expected=' not in run.stderr: + if run.returncode != 1 or not diagnostics or not re.fullmatch( + r'word=\d+ expected=[0-9a-f]{8} actual=[0-9a-f]{8}', diagnostics[0]): raise AssertionError('control %s: not rejected (exit %d) %s' % (control, run.returncode, run.stderr)) - print('control %s: rejected at %s' % (control, run.stderr.strip().splitlines()[0])) - elif run.returncode or run.stderr: + print('control %s: rejected at %s' % (control, diagnostics[0])) + elif run.returncode or diagnostics: raise AssertionError('case %s: %s' % (name, run.stderr or 'exit %d' % run.returncode)) else: print('case %s: all %d words match' % (name, WORDS)) diff --git a/tests/startup_compute_lds_dual_atomics_check.py b/tests/startup_compute_lds_dual_atomics_check.py index 17b4fdd1f..84dadc0c3 100644 --- a/tests/startup_compute_lds_dual_atomics_check.py +++ b/tests/startup_compute_lds_dual_atomics_check.py @@ -27,7 +27,7 @@ sys.path.insert(0, str(HERE)) import gfx2hlsl as G # noqa: E402 -from startup_gfx2hlsl_compute_check import MASK, SENTINEL, TGID_X, USER7, WORDS, patch, refused, root_blob # noqa: E402 +from startup_gfx2hlsl_compute_check import MASK, SENTINEL, TGID_X, USER7, WORDS, patch, refused, renderer_diagnostics, root_blob # noqa: E402 def le32(w): @@ -770,11 +770,13 @@ def check_dispatch(dxc, runner, adapter, control=None): return 77 if check_debug_layer(name, run.stdout, run.stderr) == 'unavailable': print('case %s: debug_layer=unavailable (word readback still verified)' % name) + diagnostics = renderer_diagnostics(run.stderr, adapter) if control: - if run.returncode != 1 or 'expected=' not in run.stderr: + if run.returncode != 1 or not diagnostics or not re.fullmatch( + r'word=\d+ expected=[0-9a-f]{8} actual=[0-9a-f]{8}', diagnostics[0]): raise AssertionError('control %s: not rejected (exit %d) %s' % (control, run.returncode, run.stderr)) - print('control %s: rejected at %s' % (control, run.stderr.strip().splitlines()[0])) - elif run.returncode or run.stderr: + print('control %s: rejected at %s' % (control, diagnostics[0])) + elif run.returncode or diagnostics: raise AssertionError('case %s: %s' % (name, run.stderr or 'exit %d' % run.returncode)) else: print('case %s: all %d words match' % (name, WORDS)) diff --git a/tests/startup_gfx2hlsl_compute_check.py b/tests/startup_gfx2hlsl_compute_check.py index 088033026..82b5921ec 100644 --- a/tests/startup_gfx2hlsl_compute_check.py +++ b/tests/startup_gfx2hlsl_compute_check.py @@ -1550,6 +1550,17 @@ def run_case(name, dxc, runner, adapter, directory, control=None): return subprocess.run([runner, adapter, '--compute-store-case', str(cso), str(case)], capture_output=True, text=True) +def renderer_diagnostics(stderr, adapter): + """Echo hardware enumeration notices and retain the remaining lines for the readback check.""" + diagnostics = [] + for line in stderr.splitlines(): + if adapter == 'hardware' and line.startswith('XBOX2WINDOWS_ADAPTER: skipping '): + print(line, file=sys.stderr) + else: + diagnostics.append(line) + return diagnostics + + def check_dispatch(dxc, runner, adapter, control=None): runner = str(Path(runner).resolve()) out = HERE.parent / 'out' @@ -1567,12 +1578,7 @@ def check_dispatch(dxc, runner, adapter, control=None): print(run.stdout, end='') if run.returncode == 77: return 77 - diagnostics = [] - for line in run.stderr.splitlines(): - if adapter == 'hardware' and line.startswith('XBOX2WINDOWS_ADAPTER: skipping '): - print(line, file=sys.stderr) - else: - diagnostics.append(line) + diagnostics = renderer_diagnostics(run.stderr, adapter) if mutation: first = diagnostics[:1] if (run.returncode != 1 or not any('expected=' in line for line in diagnostics) or From c74f943bf8c6abffb72bbf63ff569b4f17adf77d Mon Sep 17 00:00:00 2001 From: Royoo <3230853833@qq.com> Date: Thu, 26 Nov 2026 11:21:38 +0800 Subject: [PATCH 115/240] tests: decode startup staging diagnostics safely on Windows (#2599) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- tests/startup_stage_package_check.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/tests/startup_stage_package_check.py b/tests/startup_stage_package_check.py index fdc7cfeae..a3ca4a7d1 100644 --- a/tests/startup_stage_package_check.py +++ b/tests/startup_stage_package_check.py @@ -12,7 +12,7 @@ def call(powershell, package, exe, run): return subprocess.run( [powershell, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(SCRIPT), "-PackageDir", str(package), "-Exe", str(exe), "-RunDir", str(run)], - capture_output=True, text=True, timeout=30, + capture_output=True, encoding="utf-8", errors="replace", timeout=30, ) @@ -22,7 +22,8 @@ def stage_from_changed_location(powershell, root, package, location): r"$ErrorActionPreference = 'Stop'; Set-Location -LiteralPath $env:X2W_TEST_LOCATION; " r"& $env:X2W_TEST_SCRIPT -PackageDir $env:X2W_TEST_PACKAGE -Exe 'bin\child.exe' -RunDir 'package-run'"], cwd=root, env=dict(os.environ, X2W_TEST_LOCATION=str(location), X2W_TEST_SCRIPT=str(SCRIPT), - X2W_TEST_PACKAGE=str(package)), capture_output=True, text=True, timeout=30, + X2W_TEST_PACKAGE=str(package)), + capture_output=True, encoding="utf-8", errors="replace", timeout=30, ) @@ -84,7 +85,7 @@ def main(): junction = root / "link" result = subprocess.run(["cmd.exe", "/c", "mklink", "/J", str(junction), str(location)], - capture_output=True, text=True, timeout=30) + capture_output=True, errors="replace", timeout=30) assert result.returncode == 0, result.stdout + result.stderr try: result = call(powershell, package, exe.name, junction / "new-run") From 293e77f6b3696f85154d60d668791d51d405d73f Mon Sep 17 00:00:00 2001 From: Royoo <3230853833@qq.com> Date: Thu, 26 Nov 2026 11:21:47 +0800 Subject: [PATCH 116/240] Keep live SRVs intact during resource retirement (#2679) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 6 +- docs/startup-runtime.md | 31 ++--- src/startup_stubs/d3d12_xs_device.cpp | 134 ++---------------- tests/startup_resource_retire_views.cpp | 174 +++++++++++------------- 4 files changed, 109 insertions(+), 236 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 7246893a5..e9c6d17d7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1482,8 +1482,8 @@ foreach(backend IN ITEMS warp hardware) ENVIRONMENT "X2W_D3D12_BUDGET=1;X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_RESOURCE_INDEX_CHECK=1;X2W_D3D12_DEBUG=0") endforeach() -# X2W_D3D12_RELEASE_RETIRED_VIEWS=1 frees a released class texture that only tracked slot-18 descriptor slots keep alive by -# replacing those slots with null descriptors. `keep` is the negative control (views switch off, or retire switch off). +# Preserve live SRVs and their copies with and without the legacy views switch. Also verify that an +# explicit overwrite permits ordinary retirement, and that disabling base retirement keeps the resource. add_executable(startup_resource_retire_views tests/startup_resource_retire_views.cpp) target_include_directories(startup_resource_retire_views PRIVATE src) target_compile_features(startup_resource_retire_views PRIVATE cxx_std_17) @@ -1496,7 +1496,7 @@ foreach(backend IN ITEMS warp hardware) ENVIRONMENT "${retire_views_env};X2W_D3D12_RELEASE_RETIRED=1;X2W_D3D12_RELEASE_RETIRED_VIEWS=1") endforeach() set(retire_views_keep "X2W_D3D12_BUDGET=1;X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=0") - add_test(NAME startup_resource_retire_views_keep_${backend} COMMAND startup_resource_retire_views ${backend} keep) + add_test(NAME startup_resource_retire_views_keep_${backend} COMMAND startup_resource_retire_views ${backend}) set_tests_properties(startup_resource_retire_views_keep_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "${retire_views_keep};X2W_D3D12_RELEASE_RETIRED=1") add_test(NAME startup_resource_retire_views_noretire_${backend} COMMAND startup_resource_retire_views ${backend} keep) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 2d01ed7ee..57605f7ed 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1461,7 +1461,7 @@ ctest --preset dev --no-tests=error -R '^startup_trap_header(_prefix_control|_pr | `X2W_D3D12_QUERY_SLOTS=1` | diagnostic, in render mode: binds command-list slots 28 to 30 to the hypothesised occlusion query methods (see [Occlusion queries](#occlusion-queries)). Unset, the three slots stay no-ops | | `X2W_D3D12_BUDGET=1` | adds [video memory budget and allocation counts](#d3d12-resource-budget) to the D3D12 heartbeat | | `X2W_D3D12_RELEASE_RETIRED=1` | opt-in, effective with `X2W_D3D12_RENDER=1` only (the list handlers that record holds exist only there): frees the desktop object of a released committed 2D texture of one narrow class once no recorded list, submission or release-time fence refers to it ([details](#d3d12-resource-budget)). Unset, nothing changes | -| `X2W_D3D12_RELEASE_RETIRED_VIEWS=1` | opt-in, effective only together with `X2W_D3D12_RELEASE_RETIRED=1`: a released class texture that only tracked slot-18 descriptor slots keep alive (the title never overwrites them) is freed once those slots are replaced by null descriptors ([details](#d3d12-resource-budget)). Unset, nothing changes | +| `X2W_D3D12_RELEASE_RETIRED_VIEWS=1` | legacy diagnostic. Logs that clearing live slots is disabled and enables the existing retirement breakdown when base retirement and budgets are on ([details](#d3d12-resource-budget)) | | `X2W_D3D12_RETIRE_REASONS=1` | diagnostic only, effective with `X2W_D3D12_RELEASE_RETIRED=1` and `X2W_D3D12_BUDGET=1`: adds one `x2w-retire held:` line to the heartbeat that counts final-released resources whose desktop object is still alive, by reason ([details](#d3d12-resource-budget)). Unset, nothing is recorded | | `X2W_D3D12_VIEW_DEFAULTS=all` or `=off` | `all` is experimental: UAV, RTV and DSV descriptions with `ViewDimension` 0 also get the resource's default view, which drops their requested format and component mapping. `off` skips the measured SRV case too. Unset, only SRVs of typed non-depth textures get the default view ([details](#unknown-and-mismatched-view-dimensions)) | | `X2W_D3D12_VIEW_CENSUS=1` | diagnostic only: counts new distinct view records by device slot (a heartbeat line), and logs the record vector capacity and hash bucket count before either grows ([details](#d3d12-view-census)). Unset, nothing is counted or logged | @@ -1573,24 +1573,17 @@ unordered-access flag, and live in a default heap without heap flags: reusing the same title address or desktop pointer does not skip uploads or resolve a retired wrapper. -`X2W_D3D12_RELEASE_RETIRED_VIEWS=1` (only with `X2W_D3D12_RELEASE_RETIRED=1`) ends the -`view-refs` retention. Once a released class texture's release-time fences have passed, -the drain (a try-lock, never blocking) replaces every tracked slot-18 descriptor slot -that names it, in every heap and so every `CopyDescriptors*` copy, by a null SRV of the -same dimension: the shadow entry and its ref are dropped, the desktop descriptor is -rewritten with `CreateShaderResourceView(nullptr, ...)`, the view records naming the -resource lose it, and the view token in title descriptor memory is cleared when it -still carries that id. A draw that reads the slot afterwards binds a null texture -(zeros). The texture is then freed by the normal rules: lists and submissions that hold -it through `retire_hold` keep the desktop object until the recording is dropped or the -submission's fence passes. No recorded list or submission reads a title heap's SRV -descriptor (translated draws build their own descriptors from the tokens at draw time -and hold what they sample), so the rewrite cannot reach GPU work. A slot that cannot be -rewritten keeps its ref and the texture stays retained. Not covered: a title thread -that writes the same slot at the moment of the drain, and a guest that uses the -resource after its final release (unsupported with the switch, as before). -`startup_resource_retire_views_*` reads the desktop descriptors back through a compute -probe; the `keep` and `noretire` cases are the negative controls. +A slot-18 descriptor and each tracked copy hold the resource until the slot is explicitly overwritten +or its heap is destroyed. A later binding of that slot still reads the resource after the last guest +Release and the release-time fences. A list or submission holding the resource keeps it alive after +the slot is overwritten, until the recording is discarded or the submission retires. + +The legacy `X2W_D3D12_RELEASE_RETIRED_VIEWS=1` setting only enables the retirement breakdown below and +logs that clearing live slots is disabled. The memory-pressure A/B in +[#2379](https://github.com/R0Y00/Xbox2Windows/issues/2379#issuecomment-7179801296) used the earlier +experimental rewrite. `startup_resource_retire_views_*` checks GPU readback from the original and +copied descriptors, and from a recorded copy behind a gated queue. It also checks retirement after +explicit overwrite and normal completion, with the legacy setting on and off. `X2W_D3D12_RETIRE_REASONS=1` (with `X2W_D3D12_RELEASE_RETIRED=1` and `X2W_D3D12_BUDGET=1`) adds a diagnostic line to the heartbeat. It counts every diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 06265004d..0d38d99d5 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -174,8 +174,6 @@ struct alignas(16) WrapperOwn { // accesses: a race needs the guest to use a resource across its own final Release. bool retire_hold_missed; // Resource: retire_hold could not record a use (no desktop object or no room), so the // drain must keep it for the process instead of dropping a list's desktop object. - bool retire_views_stuck; // Resource: X2W_D3D12_RELEASE_RETIRED_VIEWS could not clear every descriptor slot that - // names it, so it stays retained (and is not scanned again). std::uint8_t retire_never; // RetireNever of this resource (set only with X2W_D3D12_RELEASE_RETIRED) std::uint8_t retire_left; // RetireLeft: the first use that took it out of the class volatile LONG retire_view_refs; // Live tracked slot-18 SRV descriptor slots referencing this resource. @@ -827,17 +825,22 @@ const D3D12_CLEAR_VALUE* packed_clear_value(const D3D12_CLEAR_VALUE* clear, DXGI return © } -bool release_retired_enabled() +bool legacy_retire_view_stats() { - static const bool on = x2w_local::env_on("X2W_D3D12_RELEASE_RETIRED"); - return on; + static const bool requested = [] { + if (!x2w_local::env_on("X2W_D3D12_RELEASE_RETIRED_VIEWS")) return false; + log("x2w-d3d12: X2W_D3D12_RELEASE_RETIRED_VIEWS no longer clears live descriptors; budget statistics only"); + return true; + }(); + return requested; } -// X2W_D3D12_RELEASE_RETIRED_VIEWS=1 (needs X2W_D3D12_RELEASE_RETIRED=1): a released class member that only tracked slot-18 -// descriptor slots keep alive is freed once every such slot has been replaced by a null descriptor. -bool release_retired_views_enabled() +bool release_retired_enabled() { - static const bool on = release_retired_enabled() && x2w_local::env_on("X2W_D3D12_RELEASE_RETIRED_VIEWS"); + static const bool on = [] { + (void)legacy_retire_view_stats(); + return x2w_local::env_on("X2W_D3D12_RELEASE_RETIRED"); + }(); return on; } @@ -5178,15 +5181,6 @@ void retire_resource(Wrapper* w) if (!queued) InterlockedIncrement64(&retire_kept); // stays retained, as without the switch } -// A null SRV of the dimension the title's view had (the draw path binds the same R8G8B8A8_UNORM null for a view that -// resolves to nothing). A null resource reads no more of the description than its format and dimension. -D3D12_SHADER_RESOURCE_VIEW_DESC retire_null_srv_desc(const ViewRecord& record) -{ - unsigned dimension = D3D12_SRV_DIMENSION_TEXTURE2D; - if (record.desc_bytes >= 40) std::memcpy(&dimension, record.desc + 4, sizeof(dimension)); - return null_srv_desc(dimension); -} - // True when the release-time fence of every queue has passed (retire_lock held). bool retire_fences_reached(const RetiredResource& item) { @@ -5196,106 +5190,10 @@ bool retire_fences_reached(const RetiredResource& item) return reached; } -// X2W_D3D12_RELEASE_RETIRED_VIEWS=1: a released class member whose release-time fences have passed and that only -// tracked slot-18 descriptor slots still name gets those slots replaced by null descriptors, so the main drain loop can -// free it. Every slot of every heap that has a shadow is handled, copies included (they are counted the same way). For -// each slot, under note_lock: the shadow entry is cleared and its ref dropped, and the desktop descriptor is rewritten -// as a null SRV of the same dimension. The view records that name the resource then lose it (so a token that a raw -// title copy left behind resolves to nothing), and the token in title descriptor memory is cleared when it still -// carries the id. A slot that cannot be rewritten keeps its ref, and the resource stays retained. Nothing waits. -// Why this cannot reach GPU work: translated draws never bind a title heap. They build their own descriptors from the -// title's tokens at draw time and retire_hold what they sample, so a descriptor of a title heap is read by no recorded -// list or submission (ClearUnorderedAccessView binds a heap for UAV slots only, and those are not touched here). -void retire_null_ready_views() -{ - std::vector ready; - try { - ready.reserve(64); - } catch (const std::bad_alloc&) { - return; - } - if (!TryAcquireSRWLockShared(&retire_lock)) return; - for (const RetiredResource& item : retired_resources) { - Wrapper* w = item.wrapper; - if (ready.size() == ready.capacity()) break; - if (w->own().retire_hold_missed || w->own().retire_views_stuck || !retire_fences_reached(item)) continue; - if (InterlockedCompareExchange(&w->own().retire_view_refs, 0, 0) <= 0) continue; - if (InterlockedCompareExchange(&w->own().refs, 0, 0) != 0) continue; // referenced again: leave its views - ready.push_back(w); - } - ReleaseSRWLockShared(&retire_lock); - if (ready.empty()) return; - - struct Cleared { - u64 title_cpu; - std::uint32_t index, increment, id; - }; - std::vector cleared; - std::size_t stuck = 0; - // draw_lock first, in the order draw_translated takes them: a draw holds it from reading a view record until it - // retire_holds the texture, so clearing the records under it means a draw either recorded its hold already or - // resolves the token to nothing. - if (!TryAcquireSRWLockExclusive(&draw_lock)) return; - if (!TryAcquireSRWLockExclusive(¬e_lock)) { - ReleaseSRWLockExclusive(&draw_lock); - return; - } - try { - std::unordered_set ids; // view ids that name a ready resource - for (std::uint32_t id = 0; id < view_records().size(); ++id) { - const ViewRecord& record = view_records()[id]; - if (record.slot != 18 || !view_materialized()[id]) continue; - if (std::find(ready.begin(), ready.end(), reinterpret_cast(record.resource)) != ready.end()) - ids.insert(id); - } - ID3D12Device* const device = the_device ? device_of(the_device) : nullptr; - for (const HeapInfo& h : heap_infos()) { - if (!h.shadow || ids.empty() || !device || !h.desktop_cpu) continue; - for (std::uint32_t i = 0; i < h.count; ++i) { - const std::uint32_t slot_id = h.shadow[i]; - if (!slot_id || !ids.count(slot_id - 1)) continue; - const ViewRecord& record = view_records()[slot_id - 1]; - const D3D12_SHADER_RESOURCE_VIEW_DESC null_view = retire_null_srv_desc(record); - device->CreateShaderResourceView(nullptr, &null_view, - D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(h.desktop_cpu + u64{i} * h.increment)}); - h.shadow[i] = 0; - retire_release_view_ref(reinterpret_cast(record.resource)); - if (h.title_cpu && h.title_cpu != h.desktop_cpu) cleared.push_back({h.title_cpu, i, h.increment, slot_id - 1}); - } - } - for (Wrapper* w : ready) { - if (InterlockedCompareExchange(&w->own().retire_view_refs, 0, 0) > 0) { - w->own().retire_views_stuck = true; - ++stuck; - continue; - } - for (std::uint32_t id : ids) - if (view_records()[id].resource == reinterpret_cast(w)) view_records()[id].resource = 0; - } - } catch (const std::bad_alloc&) { - } - ReleaseSRWLockExclusive(¬e_lock); - ReleaseSRWLockExclusive(&draw_lock); - for (const Cleared& slot : cleared) { - const u64 token = slot.title_cpu + u64{slot.index} * title_descriptor_stride(slot.title_cpu, slot.increment); - if (!title_backed(token, 32) || !x2w_local::writable(reinterpret_cast(token), 32)) continue; - std::uint32_t words[2]; - std::memcpy(words, reinterpret_cast(token), sizeof(words)); - if (words[0] == view_token_magic && words[1] == slot.id) - InterlockedCompareExchange(reinterpret_cast(token), 0, static_cast(view_token_magic)); - } - if (stuck) { - static LONG reported; - if (first_calls(reported, 4)) log("x2w-d3d12 retire: %zu released textures keep an untracked descriptor; they stay retained", stuck); - } -} - - // Never blocks: a contended lock or an unfinished queue leaves the work for the next call. void drain_retired_resources() { if (!InterlockedCompareExchange(&retire_pending, 0, 0)) return; - if (release_retired_views_enabled()) retire_null_ready_views(); constexpr std::size_t batch = 256; struct RetiredDrop { Wrapper* wrapper; @@ -5326,10 +5224,7 @@ void drain_retired_resources() ++i; continue; } - bool reached = item.targets.size() <= retire_queues.size(); - for (std::size_t q = 0; q < item.targets.size() && reached; ++q) - reached = retire_queues[q].fence->GetCompletedValue() >= item.targets[q]; - if (!reached) { + if (!retire_fences_reached(item)) { ++i; continue; } @@ -5394,7 +5289,8 @@ void drain_retired_resources() // is recorded and no line is built. bool retire_reasons_enabled() { - static const bool on = release_retired_enabled() && x2w_budget::enabled() && x2w_local::env_on("X2W_D3D12_RETIRE_REASONS"); + static const bool on = release_retired_enabled() && x2w_budget::enabled() && + (legacy_retire_view_stats() || x2w_local::env_on("X2W_D3D12_RETIRE_REASONS")); return on; } diff --git a/tests/startup_resource_retire_views.cpp b/tests/startup_resource_retire_views.cpp index 6db82d289..263dd96dc 100644 --- a/tests/startup_resource_retire_views.cpp +++ b/tests/startup_resource_retire_views.cpp @@ -1,24 +1,9 @@ -// X2W_D3D12_RELEASE_RETIRED_VIEWS=1 (with X2W_D3D12_RELEASE_RETIRED=1, Refs #2379): a released committed 2D texture that -// only tracked slot-18 descriptor slots keep alive is freed once those slots hold null descriptors. The title never has -// to overwrite them. -// +// Live SRVs keep retired textures available for later bindings (#2379). // startup_resource_retire_views [keep] -// -// `keep` is the negative control: the views switch is off (or the retire switch is, with the views switch set), so a -// released texture stays retained exactly as before and its descriptors keep naming it. -// -// The fixture reads the desktop descriptors the shim wrote: a compute shader on the fixture's own desktop queue loads -// texel (0,0) through a slot of a guest heap (bound directly when the heap is shader-visible, copied into a probe -// heap when it is not). A filled texture reads back non-zero, a null descriptor reads back zero. -// Cases: -// 1 single SRV in a shader-visible heap, never overwritten: freed after the release fences, descriptor null, view -// token in title descriptor memory cleared. -// 2 the same texture also copied into a second (non-shader-visible) heap, release behind a gated queue: nothing is -// touched until the gate opens, then both copies are null and the texture is freed (copies are handled). -// 3 a closed list recorded a CopyResource from the texture, submitted behind a gate: descriptors are nulled but the -// desktop object lives until the submission's fence, and the copy still reads the texels. -// 4 a closed, never submitted list names the texture: nulled, retained until the recording is discarded. -// 5 a live texture's descriptor is never touched. +// `keep` runs without base retirement, as a control for the budget drop after explicit overwrite. +// The legacy views switch may be on or off. Both settings preserve the original and copied slots. +// The fixture uses the shim's descriptor creation and copying paths and reads the desktop descriptors +// with a compute probe. The gated queue and the two recorded copies cover pending GPU work. #include "startup_stubs/resource_budget.h" #include @@ -417,75 +402,74 @@ D3D12_SHADER_RESOURCE_VIEW_DESC texture_view() return srv; } -// 1: one SRV in a shader-visible heap, never overwritten. -bool case1_single_view(Context& c, bool on, GuestHeap& visible) +void overwrite_srv(Context& c, const GuestHeap& heap, UINT index) { - Res& T = c.make_committed("T1"); - if (!c.fill_desktop(T.guest.Get(), 1)) return false; const auto srv = texture_view(); - invoke(c.guest, 18, T.guest.Get(), &srv, visible.cpu); - if (!c.slot_is(visible, 0, false, "case 1 control: live texture's descriptor") || - Context::token_word(visible, 0, c.increment) != view_token_magic) { - std::puts("FAIL: case 1 control: live texture's view token missing"); - return false; - } - c.release(T); - if (on) { - T.freed = true; - if (!c.settle("T1 freed with its descriptor never overwritten", "T1 kept although only a descriptor names it")) - return false; - if (!c.slot_is(visible, 0, true, "case 1: descriptor after the free")) return false; - if (Context::token_word(visible, 0, c.increment) == view_token_magic) { - std::puts("FAIL: case 1: view token still in title descriptor memory after the free"); - return false; - } - return true; - } + invoke(c.guest, 18, static_cast(nullptr), &srv, heap.cpu + c.increment * static_cast(index)); +} + +// 1: a later binding of the same slot after the last guest Release. +bool case1_single_view(Context& c, bool retire_on, GuestHeap& visible) +{ + Res& texture = c.make_committed("T1"); + if (!c.fill_desktop(texture.guest.Get(), 1)) return false; + const auto srv = texture_view(); + invoke(c.guest, 18, texture.guest.Get(), &srv, visible.cpu); + if (!c.slot_is(visible, 0, false, "case 1: live descriptor") || + Context::token_word(visible, 0, c.increment) != view_token_magic) return false; + + c.release(texture); for (int i = 0; i < 8; ++i) - if (!c.stays("T1 released, views switch off", "T1 freed without the views switch")) return false; - return c.slot_is(visible, 0, false, "case 1 control: descriptor with the views switch off"); + if (!c.stays("T1 with a live slot", "T1 retired before its slot was overwritten")) return false; + if (!c.slot_is(visible, 0, false, "case 1: rebound descriptor after Release") || + Context::token_word(visible, 0, c.increment) != view_token_magic) return false; + + overwrite_srv(c, visible, 0); + if (!c.slot_is(visible, 0, true, "case 1: explicitly overwritten slot")) return false; + texture.freed = retire_on; + return c.settle("T1 after explicit overwrite", "unexpected backing lifetime after overwrite"); } // 2: a copy in a second heap, release behind a gated queue. -bool case2_copy_and_gate(Context& c, bool on, GuestHeap& visible, GuestHeap& staging) +bool case2_copy_and_gate(Context& c, bool retire_on, GuestHeap& visible, GuestHeap& staging) { - Res& T = c.make_committed("T2"); - if (!c.fill_desktop(T.guest.Get(), 2)) return false; + Res& texture = c.make_committed("T2"); + if (!c.fill_desktop(texture.guest.Get(), 2)) return false; const auto srv = texture_view(); - invoke(c.guest, 18, T.guest.Get(), &srv, visible.cpu + c.increment); + invoke(c.guest, 18, texture.guest.Get(), &srv, visible.cpu + c.increment); invoke(c.guest, 24, 1u, staging.cpu, visible.cpu + c.increment, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); ComPtr gate; if (!require(invoke(c.guest, 36, UINT64{0}, D3D12_FENCE_FLAG_NONE, &__uuidof(ID3D12Fence), gate.GetAddressOf()), "gate") || - !require(invoke(c.gated.queue.Get(), 17, gate.Get(), UINT64{1}), "wait")) - return false; - c.release(T); + !require(invoke(c.gated.queue.Get(), 17, gate.Get(), UINT64{1}), "wait")) return false; + + c.release(texture); for (int i = 0; i < 8; ++i) - if (!c.stays("T2 released behind a closed gate", "T2 freed before the release fences passed")) return false; - if (!c.slot_is(visible, 1, false, "case 2: original descriptor before the gate opens") || - !c.slot_is(staging, 0, false, "case 2: copied descriptor before the gate opens")) - return false; + if (!c.stays("T2 behind a closed gate", "T2 retired before the release fences passed")) return false; + if (!c.slot_is(visible, 1, false, "case 2: original before the gate opens") || + !c.slot_is(staging, 0, false, "case 2: copy before the gate opens")) return false; if (!require(invoke(gate.Get(), 10, UINT64{1}), "signal gate") || !c.sync(c.gated)) return false; - if (!on) { - for (int i = 0; i < 8; ++i) - if (!c.stays("T2 released, views switch off", "T2 freed without the views switch")) return false; - return c.slot_is(staging, 0, false, "case 2 control: copied descriptor with the views switch off"); - } - T.freed = true; - if (!c.settle("T2 freed after the gate opened", "T2 kept after its fences passed")) return false; - return c.slot_is(visible, 1, true, "case 2: original descriptor after the free") && - c.slot_is(staging, 0, true, "case 2: copied descriptor after the free"); + if (!c.stays("T2 after its release fences", "T2 retired while both descriptors were live") || + !c.slot_is(visible, 1, false, "case 2: original after the release fences") || + !c.slot_is(staging, 0, false, "case 2: copy after the release fences")) return false; + + overwrite_srv(c, visible, 1); + if (!c.stays("T2 with only its copy live", "T2 retired while its copy was live") || + !c.slot_is(staging, 0, false, "case 2: copy after overwriting the original")) return false; + overwrite_srv(c, staging, 0); + if (!c.slot_is(staging, 0, true, "case 2: explicitly overwritten copy")) return false; + texture.freed = retire_on; + return c.settle("T2 after both slots were overwritten", "unexpected backing lifetime after overwriting both slots"); } -// 3 and 4: lists that name the texture. -bool case3_list_holds(Context& c, bool on, GuestHeap& visible) +// 3 and 4: lists that name the texture. Overwriting the slots cannot drop list or submission holds. +bool case3_list_holds(Context& c, bool retire_on, GuestHeap& visible) { Res& T3 = c.make_committed("T3"); Res& D3 = c.make_committed("D3"); Res& T4 = c.make_committed("T4"); Res& D4 = c.make_committed("D4"); if (!c.fill_desktop(T3.guest.Get(), 3) || !c.fill_desktop(D3.guest.Get(), 99) || !c.fill_desktop(T4.guest.Get(), 4) || - !c.fill_desktop(D4.guest.Get(), 99)) - return false; + !c.fill_desktop(D4.guest.Get(), 99)) return false; const auto srv = texture_view(); invoke(c.guest, 18, T3.guest.Get(), &srv, visible.cpu + 2 * c.increment); invoke(c.guest, 18, T4.guest.Get(), &srv, visible.cpu + 3 * c.increment); @@ -494,30 +478,31 @@ bool case3_list_holds(Context& c, bool on, GuestHeap& visible) invoke(submitted.list.Get(), 17, D3.guest.Get(), T3.guest.Get()); invoke(discarded.list.Get(), 17, D4.guest.Get(), T4.guest.Get()); if (!c.close(submitted) || !c.close(discarded)) return false; + c.release(T3); c.release(T4); for (int i = 0; i < 8; ++i) - if (!c.stays("T3/T4 released behind closed lists", "a texture left the budget while a closed list names it")) - return false; - if (on && (!c.slot_is(visible, 2, true, "case 3: descriptor of the listed texture T3") || - !c.slot_is(visible, 3, true, "case 4: descriptor of the listed texture T4"))) - return false; + if (!c.stays("T3/T4 behind closed lists", "a texture retired while its list was closed")) return false; + if (!c.slot_is(visible, 2, false, "case 3: slot with a closed list") || + !c.slot_is(visible, 3, false, "case 4: slot with a closed list")) return false; + ComPtr gate; if (!require(invoke(c.guest, 36, UINT64{0}, D3D12_FENCE_FLAG_NONE, &__uuidof(ID3D12Fence), gate.GetAddressOf()), "gate3") || - !require(invoke(c.gated.queue.Get(), 17, gate.Get(), UINT64{1}), "wait3")) - return false; + !require(invoke(c.gated.queue.Get(), 17, gate.Get(), UINT64{1}), "wait3")) return false; c.execute(c.gated, submitted); - if (!SUCCEEDED(c.reset_list(submitted))) return false; + if (!SUCCEEDED(c.reset_list(submitted)) || + !c.slot_is(visible, 2, false, "case 3: live slot during an in-flight recording")) return false; + overwrite_srv(c, visible, 2); + overwrite_srv(c, visible, 3); for (int i = 0; i < 8; ++i) - if (!c.stays("T3 held by a gated submission", "T3 left the budget while its submission is in flight")) return false; - if (!SUCCEEDED(c.reset_list(discarded))) return false; // discards the recording that was never submitted - if (on) T4.freed = true; - if (!c.settle("T4 freed after its recording was discarded", "T4 kept after its recording was discarded")) return false; + if (!c.stays("T3/T4 after overwrite", "a texture retired while its list or submission still held it")) return false; + if (!SUCCEEDED(c.reset_list(discarded))) return false; + T4.freed = retire_on; + if (!c.settle("T4 after its recording was discarded", "unexpected T4 lifetime after discarding the list")) return false; if (!require(invoke(gate.Get(), 10, UINT64{1}), "signal gate3") || !c.sync(c.gated)) return false; - if (on) T3.freed = true; - if (!c.settle("T3 freed after its submission's fence", "T3 kept after its submission's fence passed")) return false; - // The copy ran against the live texels, not against anything freed or nulled. - return c.holds(D3.guest.Get(), 3, "D3 copy of T3 recorded before the release"); + T3.freed = retire_on; + if (!c.settle("T3 after its submission's fence", "unexpected T3 lifetime after the fence")) return false; + return c.holds(D3.guest.Get(), 3, "D3 copy of T3 recorded before Release and overwrite"); } // 5: a live texture is never touched. @@ -573,12 +558,11 @@ int main(int argc, char** argv) value[0] = 0; const bool views_on = GetEnvironmentVariableA("X2W_D3D12_RELEASE_RETIRED_VIEWS", value, sizeof(value)) == 1 && value[0] == '1'; const bool keep_mode = argc == 3; - // The effective switch needs both; `keep` runs with either one missing. - if ((retire_on && views_on) == keep_mode) return 2; - const bool on = !keep_mode; + if (retire_on == keep_mode) return 2; DXGI_ADAPTER_DESC1 adapter_desc{}; adapter->GetDesc1(&adapter_desc); - std::printf("adapter=%ls debug_layer=%s mode=%s\n", adapter_desc.Description, debug ? "enabled" : "off", keep_mode ? "keep" : "on"); + std::printf("adapter=%ls debug_layer=%s retire=%s legacy_views=%s\n", adapter_desc.Description, + debug ? "enabled" : "off", retire_on ? "on" : "off", views_on ? "on" : "off"); Context c{guest.Get(), device.Get()}; try { @@ -638,12 +622,12 @@ int main(int argc, char** argv) GuestHeap visible, staging; if (!c.make_heap(visible, 8, true) || !c.make_heap(staging, 1, false)) return 4; - if (!case1_single_view(c, on, visible)) return 5; - std::puts("1 single SRV in a shader-visible heap, never overwritten: freed with a null descriptor and a cleared token"); - if (!case2_copy_and_gate(c, on, visible, staging)) return 5; - std::puts("2 copied descriptor behind a closed gate: untouched until the fences pass, then both copies null"); - if (!case3_list_holds(c, on, visible)) return 5; - std::puts("3/4 listed texture: descriptors null, desktop object kept until the submission's fence or the discard"); + if (!case1_single_view(c, retire_on, visible)) return 5; + std::puts("1 same slot rebind reads its texture after Release and permits retirement after overwrite"); + if (!case2_copy_and_gate(c, retire_on, visible, staging)) return 5; + std::puts("2 original and copied slots read their texture after the release fences, retaining it through the final overwrite"); + if (!case3_list_holds(c, retire_on, visible)) return 5; + std::puts("3/4 overwritten slots preserve list and submission holds, recorded copy reads the original texels"); if (!case5_live_control(c, visible)) return 5; std::puts("5 live texture: descriptor untouched"); } catch (int code) { @@ -652,6 +636,6 @@ int main(int argc, char** argv) const UINT64 errors = debug ? debug->GetNumStoredMessages() : 0; std::printf("debug_errors_or_warnings=%llu\n", errors); if (errors || FAILED(device->GetDeviceRemovedReason())) return 4; - std::puts(on ? "release-retired views checks passed" : "views-off control checks passed"); + std::puts(retire_on ? "live descriptor retirement checks passed" : "base retirement off: all retention controls passed"); return 0; } From 817396ad0b20d9dfc6cc6fd412332e5f96507ab3 Mon Sep 17 00:00:00 2001 From: RavenCurseBurg Date: Thu, 26 Nov 2026 11:22:36 +0800 Subject: [PATCH 117/240] tests: reuse identical vertex-fetch compiler inputs within each fixture run (#2711) Co-authored-by: RavenCurseBurg <360931527+RavenCurseBurg@users.noreply.github.com> --- tests/startup_vertex_fetch_formats_check.py | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/tests/startup_vertex_fetch_formats_check.py b/tests/startup_vertex_fetch_formats_check.py index 554209f8a..52904e985 100644 --- a/tests/startup_vertex_fetch_formats_check.py +++ b/tests/startup_vertex_fetch_formats_check.py @@ -22,9 +22,10 @@ xyz load with its own descriptor word, then descriptor words with swizzles and constants 0 and 1 run through the same translated body. Each TBUFFER format runs its matching reference and each wrong reference that changes a word in one renderer -batch. The first mismatched word must match the predicted index and values. Mutated translations -compile and dispatch separately. +batch. The first mismatched word must match the predicted index and values. Each distinct vertex or compute +source compiles once in the fixture's temporary directory. Mutated translations dispatch separately. """ +import hashlib import re import struct import subprocess @@ -443,13 +444,15 @@ def runtime_gate_controls(): def compile_fetch(directory, compiler, name, source): - hlsl, binary = directory / 'fetch.hlsl', directory / 'fetch.cso' - hlsl.write_text(source, encoding='ascii') - # Compile the vertex entry as the startup tools do, then the same body in the compute wrapper. - subprocess.run([compiler, '-T', 'vs_6_0', '-E', 'main', '-Fo', binary, hlsl], check=True) - with hlsl.open('a', encoding='ascii') as handle: - handle.write(wrapper(name)) - subprocess.run([compiler, '-T', 'cs_6_0', '-E', 'readback', '-Fo', binary, hlsl], check=True) + hlsl, output = directory / 'fetch.hlsl', directory / 'fetch.cso' + # Descriptor words can change without changing the vertex program. The readback wrapper + # also depends on the format, so key each stage by its complete input in this run's temporary directory. + for profile, entry, text in (('vs_6_0', 'main', source), ('cs_6_0', 'readback', source + wrapper(name))): + binary = directory / ('%s-%s.cso' % (profile, hashlib.sha256(text.encode('ascii')).hexdigest())) + if not binary.exists(): + hlsl.write_text(text, encoding='ascii') + subprocess.run([compiler, '-T', profile, '-E', entry, '-Fo', output, hlsl], check=True) + output.replace(binary) return binary From e46d336c52bf4cfe465f47acf5fe3b29ebcf930f Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Thu, 26 Nov 2026 05:24:46 +0200 Subject: [PATCH 118/240] pe: validate intake_exe CLI build, candidate, metadata, and report paths upfront (#2686) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 3 + tests/intake_exe_cli_check.py | 336 ++++++++++++++++++++++++++++++++++ tools/intake_exe.py | 33 +++- 3 files changed, 371 insertions(+), 1 deletion(-) create mode 100644 tests/intake_exe_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index e9c6d17d7..fd00c1c4e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -10983,6 +10983,9 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/pe_run_package_cli_check.py") add_test(NAME pe_intake_checks COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/intake_exe_check.py") + add_test(NAME pe_intake_exe_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/intake_exe_cli_check.py") + set_tests_properties(pe_intake_exe_cli_check PROPERTIES TIMEOUT 60) add_test(NAME pe_host_commit_preflight COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/host_commit_check.py") add_test(NAME xgameruntime_preflight_stub_refused COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/intake_exe_cli_check.py b/tests/intake_exe_cli_check.py new file mode 100644 index 000000000..0f97c248d --- /dev/null +++ b/tests/intake_exe_cli_check.py @@ -0,0 +1,336 @@ +#!/usr/bin/env python3 +"""Pure-Python CLI validation, atomic-report, and mutation suite for tools/intake_exe.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +import json +from pathlib import Path +import runpy +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOLS_DIR = ROOT / "tools" +TESTS_DIR = ROOT / "tests" +TOOL = TOOLS_DIR / "intake_exe.py" +sys.path.insert(0, str(TOOLS_DIR)) +sys.path.insert(0, str(TESTS_DIR)) + +import intake_exe # noqa: E402 +from intake_exe_check import _build_pe, _fake_scan_for, _synthetic_package # noqa: E402 + + +def _run_main(argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = intake_exe.main(argv) + except SystemExit as exc: + code = exc.code + if not isinstance(code, int): + if code is not None: + stderr.write(f"{code}\n") + code = 0 if code is None else 1 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class IntakeExeCliPositiveTests(unittest.TestCase): + def test_inspected_awaiting_error_json_and_require_routing_with_zero_tmp(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + + # 1) awaiting_executable -> exit 3, 0 .tmp files. + pkg_wait, base_w, int_w = _synthetic_package(base / "wait", write_candidate=False) + rep_wait = base / "wait" / "nested" / "reports" + code_w, out_w, err_w = _run_main([ + "--build", str(pkg_wait), + "--baseline", str(base_w), + "--integrity", str(int_w), + "--reports", str(rep_wait), + ]) + self.assertIs(type(code_w), int) + self.assertEqual(code_w, 3, (out_w, err_w)) + self.assertEqual(err_w, "") + self.assertIn("awaiting_executable |", out_w) + wait_files = list(rep_wait.iterdir()) + self.assertEqual(len(wait_files), 1) + self.assertTrue(wait_files[0].name.endswith(".awaiting_executable.json")) + self.assertEqual(json.loads(wait_files[0].read_text(encoding="utf-8"))["status"], "awaiting_executable") + + # 2) inspected with explicit PE candidate -> exit 0, 0 .tmp files. + pe_ok = _build_pe(imports=[("normal", "xmem.dll", "XMemAlloc")]) + pkg_ok, base_ok, int_ok = _synthetic_package(base / "ok", write_candidate=False) + cand_ok = base / "ok" / "candidate.exe" + cand_ok.write_bytes(pe_ok) + rep_ok = base / "ok" / "reports" + with mock.patch.object(intake_exe, "scan", _fake_scan_for(pkg_ok, pe_ok)): + code_ok, out_ok, err_ok = _run_main([ + str(cand_ok), + "--build", str(pkg_ok), + "--baseline", str(base_ok), + "--integrity", str(int_ok), + "--reports", str(rep_ok), + "--require-routing", + ]) + self.assertEqual(code_ok, 0, (out_ok, err_ok)) + self.assertEqual(err_ok, "") + self.assertIn("inspected |", out_ok) + ok_files = list(rep_ok.iterdir()) + self.assertEqual(len(ok_files), 1) + self.assertTrue(ok_files[0].name.endswith(".inspected.json")) + ok_payload = json.loads(ok_files[0].read_text(encoding="utf-8")) + self.assertEqual(ok_payload["status"], "inspected") + self.assertEqual(ok_payload["pe"]["machine"], "AMD64") + + # 3) --require-routing failure -> exit 1, stderr names unsupported import, JSON written w/ 0 .tmp. + pe_bad_route = _build_pe( + imports=[("normal", "xmem.dll", "XMemAlloc"), ("normal", "mystery.dll", "MissingExport")] + ) + cand_bad = base / "ok" / "bad_route.exe" + cand_bad.write_bytes(pe_bad_route) + rep_route = base / "ok" / "reports_route" + with mock.patch.object(intake_exe, "scan", _fake_scan_for(pkg_ok, pe_bad_route)): + code_rt, out_rt, err_rt = _run_main([ + str(cand_bad), + "--build", str(pkg_ok), + "--baseline", str(base_ok), + "--integrity", str(int_ok), + "--reports", str(rep_route), + "--require-routing", + ]) + self.assertEqual(code_rt, 1, (out_rt, err_rt)) + self.assertIn("unsupported: main.exe -> mystery.dll!MissingExport", err_rt) + self.assertIn("inspected |", out_rt) + rt_files = list(rep_route.iterdir()) + self.assertEqual(len(rt_files), 1) + self.assertTrue(rt_files[0].name.endswith(".inspected.json")) + + # 4) error JSON (malformed MicrosoftGame.Config) -> exit 2, 0 .tmp files. + (pkg_ok / "MicrosoftGame.Config").write_text(" None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + pkg, baseline, integrity = _synthetic_package(base / "entry", write_candidate=False) + rep = base / "entry" / "reports" + cli_argv = [ + str(TOOL), + "--build", str(pkg), + "--baseline", str(baseline), + "--integrity", str(integrity), + "--reports", str(rep), + ] + + with mock.patch.object(sys, "argv", cli_argv): + code, out, err = _run_main(None) + self.assertEqual(code, 3, (out, err)) + self.assertEqual(err, "") + self.assertIn("awaiting_executable |", out) + + stdout, stderr = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", cli_argv), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 3) + self.assertEqual(stderr.getvalue(), "") + self.assertIn("awaiting_executable |", stdout.getvalue()) + + proc = _run_subprocess(*cli_argv[1:]) + self.assertEqual(proc.returncode, 3, proc.stderr) + self.assertEqual(proc.stderr, "") + self.assertIn("awaiting_executable |", proc.stdout) + + +class IntakeExeCliNegativeAndMutationTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_code: int | None = 1, + fragments: tuple[str, ...] = (), + check_subprocess: bool = True, + ) -> str: + code, out, err = _run_main(argv) + if expected_code is None: + self.assertNotEqual(code, 0) + else: + self.assertEqual(code, expected_code, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertTrue(err.strip(), f"expected stderr for {argv!r}") + for fragment in fragments: + self.assertIn(fragment.lower(), err.lower()) + + if check_subprocess: + proc = _run_subprocess(*argv) + if expected_code is None: + self.assertNotEqual(proc.returncode, 0) + else: + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertTrue(proc.stderr.strip(), f"expected subprocess stderr for {argv!r}") + for fragment in fragments: + self.assertIn(fragment.lower(), proc.stderr.lower()) + return err + + def test_upfront_build_candidate_baseline_integrity_guards_before_collect(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + pkg, baseline, integrity = _synthetic_package(base / "pkg", write_candidate=False) + rep_absent = base / "never_created_reports" + regular_file = base / "regular.txt" + regular_file.write_text("keep", encoding="utf-8") + a_dir = base / "a_dir" + a_dir.mkdir() + missing = base / "missing.json" + + with mock.patch.object(intake_exe, "collect", side_effect=AssertionError("collect called upfront")): + for label, argv, frag in ( + ("missing_build", ["--build", str(base / "no_pkg"), "--reports", str(rep_absent)], "directory not found"), + ("file_build", ["--build", str(regular_file), "--reports", str(rep_absent)], "not a directory"), + ( + "dir_candidate", + [str(a_dir), "--build", str(pkg), "--baseline", str(baseline), "--integrity", str(integrity), "--reports", str(rep_absent)], + "candidate path is not a regular file", + ), + ( + "missing_baseline", + ["--build", str(pkg), "--baseline", str(missing), "--integrity", str(integrity), "--reports", str(rep_absent)], + "--baseline file not found", + ), + ( + "dir_baseline", + ["--build", str(pkg), "--baseline", str(a_dir), "--integrity", str(integrity), "--reports", str(rep_absent)], + "--baseline path is a directory", + ), + ( + "missing_integrity", + ["--build", str(pkg), "--baseline", str(baseline), "--integrity", str(missing), "--reports", str(rep_absent)], + "--integrity file not found", + ), + ( + "dir_integrity", + ["--build", str(pkg), "--baseline", str(baseline), "--integrity", str(a_dir), "--reports", str(rep_absent)], + "--integrity path is a directory", + ), + ): + with self.subTest(case=label): + self._assert_clean_failure(argv, expected_code=1, fragments=(frag,)) + + self.assertFalse(rep_absent.exists()) + self.assertEqual(regular_file.read_text(encoding="utf-8"), "keep") + + def test_reports_file_symlink_parent_file_and_inside_build_rejected_before_collect(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + pkg, baseline, integrity = _synthetic_package(base / "pkg", write_candidate=False) + rep_file = base / "rep_file.txt" + rep_file.write_text("keep-rep", encoding="utf-8") + real_dir = base / "real_dir" + real_dir.mkdir() + symlink_rep = base / "symlink_rep" + + try: + symlink_rep.symlink_to(real_dir, target_is_directory=True) + has_symlinks = True + except OSError as exc: + if getattr(exc, "winerror", None) != 1314: + raise + has_symlinks = False + + with mock.patch.object(intake_exe, "collect", side_effect=AssertionError("collect called for bad --reports")): + self._assert_clean_failure( + ["--build", str(pkg), "--baseline", str(baseline), "--integrity", str(integrity), "--reports", str(rep_file)], + expected_code=1, + fragments=("failed to write report", "regular file"), + ) + self._assert_clean_failure( + ["--build", str(pkg), "--baseline", str(baseline), "--integrity", str(integrity), "--reports", str(rep_file / "sub" / "out")], + expected_code=1, + fragments=("failed to write report", "not a directory"), + ) + self._assert_clean_failure( + ["--build", str(pkg), "--baseline", str(baseline), "--integrity", str(integrity), "--reports", str(pkg / "inside")], + expected_code=2, + fragments=("outside game files",), + ) + if has_symlinks: + self._assert_clean_failure( + ["--build", str(pkg), "--baseline", str(baseline), "--integrity", str(integrity), "--reports", str(symlink_rep)], + expected_code=1, + fragments=("failed to write report", "symlink"), + ) + else: + with mock.patch.object(Path, "is_symlink", autospec=True, side_effect=lambda p: p == real_dir): + self._assert_clean_failure( + ["--build", str(pkg), "--baseline", str(baseline), "--integrity", str(integrity), "--reports", str(real_dir)], + expected_code=1, + fragments=("failed to write report", "symlink"), + check_subprocess=False, + ) + self.assertEqual(rep_file.read_text(encoding="utf-8"), "keep-rep") + self.assertEqual(list(real_dir.iterdir()), []) + + def test_report_replace_failure_leaves_zero_tmp_files(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + pkg, baseline, integrity = _synthetic_package(base / "pkg", write_candidate=False) + rep_dir = base / "rep_dir" + rep_dir.mkdir() + (rep_dir / "existing.txt").write_text("keep", encoding="utf-8") + + with mock.patch.object(intake_exe.os, "replace", side_effect=OSError("simulated replace fail")): + self._assert_clean_failure( + ["--build", str(pkg), "--baseline", str(baseline), "--integrity", str(integrity), "--reports", str(rep_dir)], + expected_code=1, + fragments=("failed to write report", "simulated replace fail"), + check_subprocess=False, + ) + self.assertEqual([p.name for p in rep_dir.iterdir()], ["existing.txt"]) + + def test_argparse_errors_py314_safe(self) -> None: + for argv, frags in ( + (["--bogus-flag"], ("unrecognized",)), + (["--build"], ("expected one argument",)), + (["--baseline"], ("expected one argument",)), + (["--integrity"], ("expected one argument",)), + (["--reports"], ("expected one argument",)), + ): + with self.subTest(argv=argv): + self._assert_clean_failure(argv, expected_code=None, fragments=frags) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/intake_exe.py b/tools/intake_exe.py index 6216ab76e..df99d3623 100644 --- a/tools/intake_exe.py +++ b/tools/intake_exe.py @@ -230,14 +230,45 @@ def main(argv: list[str] | None = None) -> int: parser.error("Use --build to select a package") args.build = builds[0].parent try: + if not args.build.exists(): + raise FileNotFoundError(f"--build directory not found: {args.build}") + if not args.build.is_dir(): + raise NotADirectoryError(f"--build path is not a directory: {args.build}") + if args.reports.is_symlink(): + raise ValueError(f"failed to write report in {args.reports}: report directory must not be a symlink") + if args.reports.is_file(): + raise ValueError(f"failed to write report in {args.reports}: path is a regular file") + for parent in args.reports.parents: + if parent.is_file() or ((parent.exists() or parent.is_symlink()) and not parent.is_dir()): + raise NotADirectoryError( + f"failed to write report in {args.reports}: parent is not a directory: {parent}" + ) root = args.build.resolve() reports = args.reports.resolve() - except OSError as exc: + except (OSError, ValueError) as exc: print(f"error: {exc}", file=sys.stderr) return 1 if reports.is_relative_to(root) or reports.is_relative_to(PROJECT / "game-files"): parser.error("Choose a report directory outside game files") integrity = args.integrity or PROJECT / "out/integrity" / (root.name + ".json") + try: + if ( + args.candidate is not None + and (args.candidate.exists() or args.candidate.is_symlink()) + and not args.candidate.is_file() + ): + raise ValueError(f"candidate path is not a regular file: {args.candidate}") + if args.baseline.is_dir(): + raise IsADirectoryError(f"--baseline path is a directory: {args.baseline}") + if not args.baseline.is_file(): + raise FileNotFoundError(f"--baseline file not found: {args.baseline}") + if integrity.is_dir(): + raise IsADirectoryError(f"--integrity path is a directory: {integrity}") + if not integrity.is_file(): + raise FileNotFoundError(f"--integrity file not found: {integrity}") + except (OSError, ValueError) as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 report = {"schema": 1, "status": "error"} try: code = collect(root, args.candidate.resolve() if args.candidate else None, From 12c45b842ff9f146ce45744e51cd5e5142411d7b Mon Sep 17 00:00:00 2001 From: triggered02 <153171514+triggered02@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:59:18 +0530 Subject: [PATCH 119/240] startup: verify reaching SCC writer before reading src_scc (#1821) Fixes #1820. Addresses review feedback on #1821: Stage.u() now refuses src_scc unless a modeled SCC writer set scc_verified on the reaching path in the current block. scc_verified starts False at entry, clears at branch targets/joins, non-fallthroughs, SCC_UNMODELLED (such as s_add_u32, cleared after reading its sources), descriptor-elided SCC writes, calculated-PC elision, and s_wqm. Test runs full Stage.translate() over synthetic bytes covering entry refusal, modeled compare/bitwise writers, low16_only=True, the s_add_u32 carry case, input-before-write on s_add_u32, and CFG joins; all 62 pure-Python startup_gfx2hlsl checks and CTest src_scc/sopk_accum/startup_translator pass. Co-authored-by: Royoo <3230853833@qq.com> --- CMakeLists.txt | 3 + docs/experiments.md | 11 ++ tests/startup_gfx2hlsl_src_scc_check.py | 194 ++++++++++++++++++++++++ tools/startup/gfx2hlsl.py | 20 +++ 4 files changed, 228 insertions(+) create mode 100644 tests/startup_gfx2hlsl_src_scc_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index fd00c1c4e..92a43abbd 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3431,6 +3431,9 @@ if(EXISTS "${INTAKE_PYTHON}") # Handlers that do not model a modifier they can receive refuse it (#1771). add_test(NAME startup_gfx2hlsl_modifier_free COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_modifier_free_check.py") + # The src_scc scalar source (#1820). + add_test(NAME startup_gfx2hlsl_src_scc COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_src_scc_check.py") # image_sample_c_lz with sampler word 2 bits 28-30 set (#1723). add_test(NAME startup_gfx2hlsl_sample_c_lz_mip COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_sample_c_lz_mip_check.py") diff --git a/docs/experiments.md b/docs/experiments.md index f4d8a241f..c6597510c 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -16692,3 +16692,14 @@ Linux controls, `form_coverage_check.check_sdwa_cvt_forms`, and Python reference ```powershell ctest --test-dir out/build/release --no-tests=error -R "^startup_gfx2hlsl_scalar_null_(controls|warp|hardware)$" -V ``` +## `src_scc` as a scalar source + +`s_mul_i32 s28, 1.0, src_scc` was refused as `operand 'src_scc'` (issue #1820), one of the refused shaders +in the loading-screen cache (#870). Scalar source code 253 reads the SCC bit as the integer value 0 or 1 +(fitting in 16 bits, so `low16_only=True` returns the same expression), and the generated shader carries SCC +as a `bool scc`, so `Stage.u()` lowers `src_scc` to `(scc ? 1u : 0u)` when a modeled writer has set SCC +on every reaching path in the current block (`s_cmp_*` / `s_and_b32` etc. via `set_scc()`, `set_exec_scc()`, +or `scalar_wide_op()`). Reads where incoming SCC is unverified are refused: at shader entry, across +control-flow joins/branch targets, after descriptor-elided SCC writes, and after unmodeled SCC writers in +`SCC_UNMODELLED` such as `s_add_u32` (after `s_add_u32` finishes reading its own sources). Run +`ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_src_scc$' -V`. diff --git a/tests/startup_gfx2hlsl_src_scc_check.py b/tests/startup_gfx2hlsl_src_scc_check.py new file mode 100644 index 000000000..4880cd72d --- /dev/null +++ b/tests/startup_gfx2hlsl_src_scc_check.py @@ -0,0 +1,194 @@ +"""The `src_scc` scalar source in tools/startup/gfx2hlsl.py (issue #1820). + +usage: startup_gfx2hlsl_src_scc_check.py + +The census contained `s_mul_i32 s28, 1.0, src_scc`, refused as `operand 'src_scc'` (#870, issue #1820). +Source code 253 reads the SCC bit as the integer value 0 or 1; the generated shader carries SCC as a +`bool scc`, so `Stage.u()` lowers `src_scc` to `(scc ? 1u : 0u)` when a modeled writer has set SCC on +every reaching path in the current block, and refuses when the incoming SCC is unverified (at shader entry, +after an unmodeled SCC writer such as `s_add_u32`, after descriptor-elided SCC, or across control-flow +joins). + +The instruction bytes are **constructed here** from the field layout the checked-in decoder reads +(`tools/disasm_rdna2.py`): +- SOP2 (`[31:30] == 0b10`, op in `w0[29:23]`, sdst in `w0[22:16]`, src1 in `w0[15:8]`, src0 in `w0[7:0]`, + optional literal dword when a source is 255) +- SOPC (`[31:23] == 0b101111110`, op in `w0[22:16]`, src1 in `w0[15:8]`, src0 in `w0[7:0]`) +- SOPP (`[31:23] == 0b101111111`, op in `w0[22:16]`, simm16 in `w0[15:0]`) +""" +import os +import struct +import sys + +here = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(here, '..', 'tools')) +sys.path.insert(0, os.path.join(here, '..', 'tools', 'startup')) +import gfx2hlsl as G # noqa: E402 + +failures = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH'}") + if not condition: + failures.append(label) + if detail: + print(' ' + detail) + + +SOP2_ADD_U32 = 0x00 +SOP2_AND_B32 = 0x0E +SOP2_MUL_I32 = 0x26 +SOPC_CMP_EQ_U32 = 0x06 +SOPP_NOP = 0x00 +SOPP_ENDPGM = 0x01 +SOPP_CBRANCH_SCC0 = 0x04 + +S_ZERO = 128 # inline integer 0 +S_ONE = 129 # inline integer 1 +S_SCC = 253 # the src_scc scalar source code +S_1_0 = 242 # the inline float constant 1.0 (its raw bits are 0x3f800000) +LITERAL = 255 +S1, S4, S5, S27, S28, S29 = 1, 4, 5, 27, 28, 29 + + +def encode_sop2(op, sdst, ssrc0, ssrc1, literal=None): + w0 = ((0b10 << 30) | ((op & 0x7F) << 23) | ((sdst & 0x7F) << 16) + | ((ssrc1 & 0xFF) << 8) | (ssrc0 & 0xFF)) + code = struct.pack(' census s_mul_i32 s28, 1.0, src_scc: decodes and lowers using the SCC bit. +cmp_census = (encode_sopc(SOPC_CMP_EQ_U32, S_ZERO, S_ZERO) + + encode_sop2(SOP2_MUL_I32, S28, S_1_0, S_SCC) + + encode_sopp(SOPP_ENDPGM)) +asm, emitted, stage = translate_program(cmp_census) +check('encodes and decodes compare + census form', + asm[:2] == ['s_cmp_eq_u32 0, 0', 's_mul_i32 s28, 1.0, src_scc'], repr(asm)) +check('compare + census form lowers to the SCC bit', + 'scc = 0x00000000u == 0x00000000u;' in emitted and 's28 = 0x3f800000u * (scc ? 1u : 0u);' in emitted, + emitted) +check('low16_only=True returns the same 0/1 expression', + stage.u('src_scc', low16_only=True) == '(scc ? 1u : 0u)') + +# 3. Modeled bitwise writer -> src_scc in the first source position -> next instruction reads updated SCC. +bitwise_seq = (encode_sop2(SOP2_AND_B32, S27, S4, S5) + + encode_sop2(SOP2_AND_B32, S28, S_SCC, S5) + + encode_sop2(SOP2_MUL_I32, S29, S_1_0, S_SCC) + + encode_sopp(SOPP_ENDPGM)) +asm, emitted, _stage = translate_program(bitwise_seq) +check('encodes and decodes bitwise sequence with src_scc in first position', + asm[:3] == ['s_and_b32 s27, s4, s5', 's_and_b32 s28, src_scc, s5', 's_mul_i32 s29, 1.0, src_scc'], + repr(asm)) +check('bitwise sequence reads and updates SCC cleanly', + 's28 = (scc ? 1u : 0u) & s5; scc = s28 != 0;' in emitted + and 's29 = 0x3f800000u * (scc ? 1u : 0u);' in emitted, + emitted) + +# 4. Distinguishing carry case: compare sets SCC=0, then s_add_u32 0xffffffff + 1 wraps and sets hardware +# carry SCC=1 without an HLSL SCC update. Reading src_scc afterwards must refuse rather than read stale 0. +carry_seq = (encode_sopc(SOPC_CMP_EQ_U32, S_ZERO, S_ONE) + + encode_sop2(SOP2_ADD_U32, S1, LITERAL, S_ONE, literal=0xFFFFFFFF) + + encode_sop2(SOP2_MUL_I32, S28, S_1_0, S_SCC) + + encode_sopp(SOPP_ENDPGM)) +check('s_add_u32 carry after compare leaves SCC unverified and is refused', + refused_reason(carry_seq) == 'src_scc with unverified SCC', + repr(refused_reason(carry_seq))) + +# 5. s_add_u32 reading src_scc as an input before overwriting SCC is accepted (input read precedes write), +# while a second src_scc after s_add_u32 is refused. +add_reads_scc = (encode_sopc(SOPC_CMP_EQ_U32, S_ZERO, S_ZERO) + + encode_sop2(SOP2_ADD_U32, S1, S_SCC, S_ONE) + + encode_sopp(SOPP_ENDPGM)) +asm, emitted, _stage = translate_program(add_reads_scc) +check('s_add_u32 reading incoming verified src_scc is accepted', + 's1 = (scc ? 1u : 0u) + 0x00000001u;' in emitted, emitted) +check('reading src_scc after s_add_u32 is refused', + refused_reason(encode_sopc(SOPC_CMP_EQ_U32, S_ZERO, S_ZERO) + + encode_sop2(SOP2_ADD_U32, S1, S_SCC, S_ONE) + + encode_sop2(SOP2_MUL_I32, S28, S_1_0, S_SCC) + + encode_sopp(SOPP_ENDPGM)) == 'src_scc with unverified SCC') + +# 6. Across a control-flow join: branch skips s_nop 0 to target 0x10; incoming SCC at the join is unverified, +# so src_scc there is refused unless a modeled writer runs inside the joined block first. +join_refused = (encode_sopc(SOPC_CMP_EQ_U32, S_ZERO, S_ZERO) # 0x00 + + encode_sopp(SOPP_CBRANCH_SCC0, simm=1) # 0x04 -> label_0x0c (skip 1 dword at 0x08) + + encode_sopp(SOPP_NOP, simm=0) # 0x08 + + encode_sop2(SOP2_MUL_I32, S28, S_1_0, S_SCC) # 0x0c (branch target / join) + + encode_sopp(SOPP_ENDPGM)) # 0x10 +check('src_scc across a control-flow join is refused', + refused_reason(join_refused) == 'src_scc with unverified SCC', + repr(refused_reason(join_refused))) + +join_rewritten = (encode_sopc(SOPC_CMP_EQ_U32, S_ZERO, S_ZERO) # 0x00 + + encode_sopp(SOPP_CBRANCH_SCC0, simm=1) # 0x04 -> 0x0c + + encode_sopp(SOPP_NOP, simm=0) # 0x08 + + encode_sopc(SOPC_CMP_EQ_U32, S4, S5) # 0x0c (modeled writer after join) + + encode_sop2(SOP2_MUL_I32, S28, S_1_0, S_SCC) # 0x10 + + encode_sopp(SOPP_ENDPGM)) +asm, emitted, _stage = translate_program(join_rewritten) +check('src_scc after a modeled writer in the joined block is accepted', + 's28 = 0x3f800000u * (scc ? 1u : 0u);' in emitted, emitted) + +if failures: + print('FAIL') + for text in failures: + print(' ' + text) + sys.exit(1) +print('PASS') diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 6f3dcfdbf..ab5eed675 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -2159,6 +2159,12 @@ def note_whole_read(self, reg): def u(self, tok, *, low16_only=False): """uint expression for a 32-bit operand.""" + if tok == 'src_scc': + # Source code 253 reads SCC as 0 or 1 (fits in 16 bits, so low16_only=True needs no mask). + # Refuse unless a modeled writer set SCC on the reaching path in this block. + if not getattr(self, 'scc_verified', False): + raise Unsupported('src_scc with unverified SCC') + return '(scc ? 1u : 0u)' if tok in ('vcc_lo', 'vcc'): self.read_vcc() return 'vcc' @@ -2395,6 +2401,7 @@ def set_scc(self, expr, proof=None): """Emit an SCC assignment and track its uniformity from `proof` (an expression over the sources) when the emitted text names a register, such as m0, that the proof cannot judge.""" self.scc_effect = 'emitted' + self.scc_verified = True if self.tracks_uniformity(): self.scc_uniform = self.scalar_expr_uniform(expr if proof is None else proof) self.emit('scc = %s;' % expr) @@ -2983,6 +2990,7 @@ def translate(self): self.uniform_v = set() self.varying_s = set() self.scc_uniform = True + self.scc_verified = False self.low16_only_v = set() # VGPRs whose upper 16 bits are undefined after odd-dmask d16 image_load self.pinned_low16_v = set() # low16_only_v live across basic-block boundaries self.whole_read_v = set() # VGPRs read outside a proven low-16-bit consumer @@ -3023,6 +3031,8 @@ def translate(self): self.pc = off self.descriptor_instruction_index = instruction_index self.scc_effect = None + if not falls: + self.scc_verified = False # Before the first branch target or terminator every path has run exactly the instructions above, so # the program-order tracking is exact there even in a program with branches. Code after s_endpgm in a # branch-free program is past it too (dead code). @@ -3072,6 +3082,7 @@ def translate(self): tentative_kept.update((kept_u & clobber) - blocked) self.uniform_v.clear() self.since_join, self.scc_uniform = kept_u, False + self.scc_verified = False # A constant is only known here if no other path into the join writes the register: a loop counter # set before the loop and incremented in it reaches the loop head with a new value on every pass. # set_s also assigns constants at run time, so the register reads its real value once it is dropped. @@ -3528,6 +3539,7 @@ def lower(self, base, asm, ops, mods): self.varying_s.add(reg) if base in ('s_add_u32', 's_addc_u32'): self.scc_uniform = False + self.scc_verified = False return None if getattr(self, 'fetched', False): # unit probes build a Stage without __init__ # Behind a fetch call the definite-assignment guard relies on exec_known: every exec write must clear it. @@ -3546,6 +3558,7 @@ def lower(self, base, asm, ops, mods): self.uniform_v.clear() if hasattr(self, 'scc_uniform'): self.scc_uniform = False # the hardware SCC result is not modelled + self.scc_verified = False return None if base == 's_setreg_imm32_b32': # The write itself changes nothing the lowering models, except MODE[1:0] (the binary32 rounding mode): @@ -4160,8 +4173,11 @@ def src_sym(t): return None raise Unsupported('TG_SIZE register s%d read outside s_and_b32 with 0xfc0' % tg_srcs[0]) if any(s and s[0] in ('desc', 'descnum', 'ptr', 'ptrhi') for s in syms): + if 'src_scc' in srcs and not getattr(self, 'scc_verified', False): + raise Unsupported('src_scc with unverified SCC') if scc or base in SCC_UNMODELLED: self.scc_effect = 'descriptor' + self.scc_verified = False if self.tracks_uniformity(): self.scc_uniform = False if shift_add or word_complement or word_absdiff: @@ -4249,6 +4265,8 @@ def src_sym(t): # Compute carry before writing the low register, which can also be an addend. self.set_scc('(%s) < %s' % (expr, values[0])) self.address_carry_reader = self.address_carry_pairs[self.pc] + elif base in SCC_UNMODELLED: + self.scc_verified = False if shift_add: # carry = bits shifted out of S0, or a wrap of the 32-bit sum; read before the destination is written n = SHIFT_ADD[base] @@ -4362,6 +4380,7 @@ def known(tok): def set_exec_scc(self, expr): self.exec_known = False self.scc_effect = 'emitted' + self.scc_verified = True self.emit('exec = (%s) & 1; scc = exec != 0;' % expr) if hasattr(self, 'scc_uniform'): self.scc_uniform = False @@ -4847,6 +4866,7 @@ def scalar_wide_op(self, name, ops, mods, wide_src, wide_dst, helper, signed=Non if self.tracks_uniformity(): (self.varying_s.discard if uniform else self.varying_s.add)(r) self.scc_effect = 'emitted' + self.scc_verified = True if self.tracks_uniformity(): self.scc_uniform = uniform return None From 2a772bd49b0bd7f5461aeb6a50d23d2413885238 Mon Sep 17 00:00:00 2001 From: jj <30307984+ColorMeBoom@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:31:14 -0800 Subject: [PATCH 120/240] startup: opt-in split of a batched indirect Dispatch (Refs #2626) (#2683) On an AMD Radeon RX 5700 XT (RDNA 1, device 731f), desktop ExecuteIndirect with a Dispatch signature runs only its first command, and a single-command call ignores its count buffer. With X2W_SPLIT_INDIRECT_DISPATCH=1, slot 61 splits a batched or counted Dispatch with a rootless signature and a desktop compute pipeline and root: the count word and records are copied into a scratch buffer, a one-group pass rewrites record i as itself while i < min(count, MaxCommandCount) and as (0,0,0) otherwise, and MaxCommandCount single-command calls without a count buffer read the result. The native call stays the default on every adapter. The translated compute path, graphics, mesh and rooted Dispatch signatures are unchanged. The pass replaces the compute root and pipeline. The split sets the pipeline again and restore_compute_root sets the root with every view recorded by bind_compute_root_view. Slot 43 records its root SRVs there, the indexed-draw validation pass restores through the same function, and the rectangle-list refusal checks the same views. The fixture-only export x2w_d3d12_fixture_compute_root_uav binds the fixture's desktop result UAV through bind_compute_root_view; x2w_d3d12_recording_scratches reports the scratch the recording's allocator holds until its fences pass. startup_indirect_count_(warp|hardware) keep the native call and stay strict. startup_indirect_count_split_(warp|hardware) run count mode with the split: GPU-written counts 2, 9, 0, 1 and 3, a follow-up Dispatch that needs the restored root, pipeline and UAV, the scratch count after Close, and a guest-queue submission behind a gate whose allocator is reset while pending. AI-assisted. Co-authored-by: Royoo <3230853833@qq.com> --- CMakeLists.txt | 11 +- CMakePresets.json | 2 +- docs/experiments.md | 78 +++++++++ src/startup_stubs/d3d12_draw.inl | 9 +- src/startup_stubs/d3d12_xs_device.cpp | 143 ++++++++++++++++- src/startup_stubs/split_indirect_dispatch.h | 169 ++++++++++++++++++++ tests/startup_indirect_dispatch.cpp | 91 +++++++++-- 7 files changed, 475 insertions(+), 28 deletions(-) create mode 100644 src/startup_stubs/split_indirect_dispatch.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 92a43abbd..ebf3056d9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1516,9 +1516,16 @@ foreach(backend IN ITEMS warp hardware) add_test(NAME startup_indirect_dispatch_${backend} COMMAND startup_indirect_dispatch ${backend}) add_test(NAME startup_indirect_root_constants_${backend} COMMAND startup_indirect_dispatch ${backend} constants) add_test(NAME startup_indirect_count_${backend} COMMAND startup_indirect_dispatch ${backend} count) - set_tests_properties(startup_indirect_dispatch_${backend} startup_indirect_root_constants_${backend} startup_indirect_count_${backend} PROPERTIES TIMEOUT 30) + # The same cases with the opt-in split of a batched or counted Dispatch into single commands + # (split_indirect_dispatch.h), plus the follow-up Dispatch and the pending-allocator reset. The plain count tests + # keep the native call. + add_test(NAME startup_indirect_count_split_${backend} COMMAND startup_indirect_dispatch ${backend} count) + set_tests_properties(startup_indirect_count_split_${backend} PROPERTIES ENVIRONMENT "X2W_SPLIT_INDIRECT_DISPATCH=1") + set_tests_properties(startup_indirect_dispatch_${backend} startup_indirect_root_constants_${backend} startup_indirect_count_${backend} + startup_indirect_count_split_${backend} PROPERTIES TIMEOUT 30) endforeach() -set_tests_properties(startup_indirect_dispatch_hardware startup_indirect_root_constants_hardware startup_indirect_count_hardware PROPERTIES SKIP_RETURN_CODE 77) +set_tests_properties(startup_indirect_dispatch_hardware startup_indirect_root_constants_hardware startup_indirect_count_hardware + startup_indirect_count_split_hardware PROPERTIES SKIP_RETURN_CODE 77) # Occlusion queries recorded through command-list slots 28 to 30 reach the readback buffer (#870). add_executable(startup_list_queries tests/startup_list_queries.cpp tests/desktop_gpu.cpp) diff --git a/CMakePresets.json b/CMakePresets.json index 1327cb617..861add0bc 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -42,7 +42,7 @@ "displayName": "Windows pull request smoke tests", "filter": { "include": { - "name": "^(desktop_root_signature|era_heap_(allocation|failure)|xmem_shim_mapped_pages|cpu_aot_fuzz_smoke|cpu_archive_texture_gpu_warp|dual_uav_warp|spirv_.*_warp|static_exe_intake|descriptor_heap_paging(_swapped)?_warp|startup_launch|startup_tools_lint|startup_gfx2hlsl_cvt_off_f32_i4_controls|startup_indirect_(dispatch|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|counts_control)_warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_shader_cache_key)$" + "name": "^(desktop_root_signature|era_heap_(allocation|failure)|xmem_shim_mapped_pages|cpu_aot_fuzz_smoke|cpu_archive_texture_gpu_warp|dual_uav_warp|spirv_.*_warp|static_exe_intake|descriptor_heap_paging(_swapped)?_warp|startup_launch|startup_tools_lint|startup_gfx2hlsl_cvt_off_f32_i4_controls|startup_indirect_(dispatch|count_split|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|counts_control)_warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_shader_cache_key)$" } } }, diff --git a/docs/experiments.md b/docs/experiments.md index c6597510c..11ec23f98 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9417,6 +9417,84 @@ On a multi-GPU system, set `$env:XBOX2WINDOWS_ADAPTER` to a case-insensitive par adapter's name, then run `startup_indirect_count_hardware`. The fixture prints the selected adapter, driver, GPU-written count and fenced result. An unmatched or overlong hardware selector fails the test. +#### Batched indirect Dispatch on RDNA 1 + +On an AMD Radeon RX 5700 XT (RDNA 1, vendor `1002`, device `731f`), Windows 11 +build 26200.9974, debug layer unavailable, desktop `ExecuteIndirect` with a +12-byte Dispatch signature runs exactly one command whatever its +`MaxCommandCount`, with or without a count buffer. A standalone D3D12 program +without the shim ran three records `(2,1,1)`, `(1,2,1)`, `(1,1,3)` and got only +the first one's groups. This held for the direct and compute queues, a root UAV +and a descriptor table, `numthreads(1,1,1)` and `(64,1,1)`, records of 64 +groups, arguments in a DEFAULT or UPLOAD heap, a count buffer in the argument +buffer or apart from it, and strides of 12 and 16. A single-command call also +ignores its count buffer: a count word of 0 still ran the record. Three +single-command calls without a count buffer were exact. WARP 10.0.26100.9818 +was exact in every case. Drivers 32.0.21045.29003, 32.0.21045.16010, +32.0.21025.10016, 32.0.12033.1030 and 31.0.23013.1023 (Adrenalin 26.11.2 back +to 23.12.1) behave the same. On the issue, an NVIDIA GeForce RTX 4060 +(32.0.15.9579), an Intel UHD Graphics 770 (32.0.101.5973) and WARP +10.0.26100.9711 matched all nine standalone variants. No second RDNA 1 adapter +has been measured, and the cause is not established. +[Report](https://github.com/R0Y00/Xbox2Windows/issues/2626) + +With `X2W_SPLIT_INDIRECT_DISPATCH=1`, slot 61 splits a batched or counted +Dispatch ([`split_indirect_dispatch.h`](../src/startup_stubs/split_indirect_dispatch.h)). +It is opt-in: without the variable the native call runs on every adapter, +RDNA 1 included, until a second RDNA 1 adapter has been measured. It applies +only to a rootless Dispatch signature with a desktop compute pipeline and root; +the translated compute path and the other indirect command kinds are +unchanged. The count word and the records are copied into a scratch buffer. A +compute pass rewrites record `i` as itself while `i < min(count, MaxCommandCount)` +and as `(0,0,0)` otherwise. `MaxCommandCount` single-command calls without a +count buffer then read the rewritten records. + +The pass replaces the compute root and pipeline. The compute state a title can +set on the desktop list is the pipeline (slot 25), the root (slot 33) and root +SRVs (slot 43); the other compute root setters are not forwarded. The split +sets the pipeline again, and `restore_compute_root` sets the root with every +view recorded by `bind_compute_root_view`. The indexed-draw validation pass +uses the same restore. Slot 43 records its root SRVs through +`bind_compute_root_view`. The fixture's result UAV is a desktop address that no +guest slot can bind, so the fixture binds it through the export +`x2w_d3d12_fixture_compute_root_uav`, which records it through the same +function. A UAV bound on the desktop list directly is lost after the split: in +an earlier fixture that did so, the split left the result at its sentinel. + +The scratch is kept with the recording's desktop allocator +(`x2w_d3d12_recording_scratches` reports how many it holds) and is released +only when that allocator is reset after every queue that ran it has passed its +fence. + +`startup_indirect_count_(warp|hardware)` keep the native call. On the RX 5700 +XT (driver 32.0.21045.29003) the hardware test still fails at its first case +(`result=0x31415929`, expected `0x31415935`), which shows the driver behavior. +`startup_indirect_count_split_(warp|hardware)` run the same fixture with the +split on. Each case checks the whole readback, sentinel and guard included: + +- GPU-written counts 2, 9 (above the maximum of 3), 0, 1 and 3; a zero count + leaves the result at its sentinel; +- an omitted writer, no count buffer, and the five refusals; +- a follow-up `Dispatch(1, 1, 2)` recorded on the desktop list after the split, + which adds 102 only if the consumer pipeline, its compute root and the result + UAV are still bound; +- the scratch count after Close (one per accepted call with the split on, none + otherwise); +- a submission through a guest queue that waits on a gate fence. The guest + allocator is reset while the work is pending, the recording must still hold + its scratch, and after the gate opens the records produce the count-2 result. + +Both pass on WARP 10.0.26100.9818 and the RX 5700 XT. Two local controls, not +committed, each failed both: skipping `restore_compute_root` after the pass +(first case, `result=0x31415926`, expected `0x31415935`), and not retaining the +scratch with the recording ("recording holds 0 split scratch buffers after +Close, expected 1"). + +```powershell +cmake --build --preset dev --target startup_indirect_dispatch +ctest --preset dev --no-tests=error -R '^startup_indirect_count(_split)?_(warp|hardware)$' -V +``` + #### Root constants in an indirect dispatch signature Device slot 41 also accepts a compute signature with a root signature, whose diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index c45c49b9f..4c31e03ca 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -1842,14 +1842,7 @@ ID3D12Resource* validate_indexed_arguments(Wrapper* self, ID3D12GraphicsCommandL // The clamp changes the native compute root and invalidates its arguments. // In render mode slot 43 is the forwarded compute parameter setter. - const auto& pass = pass_of(self); - if (pass.desktop_compute_root) { - list->SetComputeRootSignature(pass.desktop_compute_root.Get()); - for (UINT parameter = 0; parameter < pass.desktop_compute_upload_srvs.size(); ++parameter) { - const auto address = pass.desktop_compute_upload_srvs[parameter]; - if (address) list->SetComputeRootShaderResourceView(parameter, address); - } - } + restore_compute_root(pass_of(self), list); return scratch.Get(); } diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 0d38d99d5..37ac888e7 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -53,6 +53,7 @@ #include "startup_stubs/list_copy.h" #include "startup_stubs/d3d12_teardown.h" #include "startup_stubs/rect_indirect_args.h" +#include "startup_stubs/split_indirect_dispatch.h" #include "startup_stubs/profile_zone.h" #include "startup_stubs/slice_footprints.h" @@ -1525,6 +1526,39 @@ ID3D12Resource* recording_rect_scratch(Wrapper* self) return scratch; } +// Keeps `resource` with this recording's desktop allocator, like the rectangle-list scratch above. False if the list +// is not recording (the caller must not use the resource then). +bool retain_with_recording(Wrapper* self, x2w_startup::ComPtr resource) +{ + bool retained = false; + AcquireSRWLockExclusive(&allocator_lock); + const auto& state = self->own(); + const auto found = list_recordings.find(self); + if (state.list_open && found != list_recordings.end() && found->second) { + try { + found->second->scratches.push_back(std::move(resource)); + retained = true; + } catch (const std::bad_alloc&) { + } + } + ReleaseSRWLockExclusive(&allocator_lock); + return retained; +} + +// Fixture query: how many scratch buffers the desktop allocator of this list's latest recording still holds (the +// rectangle-list scratch and the split indirect Dispatch records). They are released only when that allocator is +// reset after every queue that ran its recordings has passed its fence (allocator_reset). +extern "C" __declspec(dllexport) UINT x2w_d3d12_recording_scratches(void* guest_list) +{ + Wrapper* self = as_wrapper(guest_list); + if (!self || self->own().kind != list_kind) return 0; + AcquireSRWLockShared(&allocator_lock); + const auto found = list_recordings.find(self); + const UINT held = found != list_recordings.end() && found->second ? static_cast(found->second->scratches.size()) : 0; + ReleaseSRWLockShared(&allocator_lock); + return held; +} + // Fixture query for two closed recordings before either is submitted. extern "C" __declspec(dllexport) BOOL x2w_d3d12_distinct_rect_scratch(void* first, void* second) { @@ -2465,6 +2499,8 @@ struct Pass { std::array desktop_compute_upload_srvs{}; ID3D12RootSignature* compute_pipeline_root = nullptr; // root the bound compute pipeline was built against UINT compute_srv_bound = 0; // root SRV parameters that reached the desktop list since slot 33 + // Desktop root UAVs a fixture bound through x2w_d3d12_fixture_compute_root_uav, set again after a shim compute pass. + std::array desktop_compute_root_uavs{}; const std::vector* compute_params = nullptr; std::unique_ptr compute_trace; bool compute_root_has_arguments = false; // that root declares parameters other than root SRVs, or static samplers @@ -2688,6 +2724,40 @@ UINT __stdcall list_resource_barriers(Wrapper* self, UINT count, const D3D12_RES return 0; // no console barrier actions to perform on the caller's side } +// Compute root views on the desktop list. Root SRVs come from slot 43; root UAVs only from the fixture hook +// x2w_d3d12_fixture_compute_root_uav (slot 45 is not forwarded). Both are recorded here so restore_compute_root can set +// them again after a shim compute pass has replaced the desktop compute root. +void bind_compute_root_view(Pass& pass, ID3D12GraphicsCommandList* list, UINT parameter, D3D12_ROOT_PARAMETER_TYPE type, + D3D12_GPU_VIRTUAL_ADDRESS address) +{ + if (type == D3D12_ROOT_PARAMETER_TYPE_SRV) { + pass.desktop_compute_upload_srvs[parameter] = address; + list->SetComputeRootShaderResourceView(parameter, address); + } else if (type == D3D12_ROOT_PARAMETER_TYPE_UAV) { + pass.desktop_compute_root_uavs[parameter] = address; + list->SetComputeRootUnorderedAccessView(parameter, address); + } +} +bool has_compute_root_views(const Pass& pass) +{ + const auto live = [](D3D12_GPU_VIRTUAL_ADDRESS address) { return address != 0; }; + return std::any_of(pass.desktop_compute_upload_srvs.begin(), pass.desktop_compute_upload_srvs.end(), live) || + std::any_of(pass.desktop_compute_root_uavs.begin(), pass.desktop_compute_root_uavs.end(), live); +} +// Sets the title's desktop compute root again, with every view bind_compute_root_view recorded under it, after a shim +// compute pass (indexed-draw validation, split indirect Dispatch) replaced the root and invalidated its arguments. +void restore_compute_root(const Pass& pass, ID3D12GraphicsCommandList* list) +{ + if (!pass.desktop_compute_root) return; + list->SetComputeRootSignature(pass.desktop_compute_root.Get()); + for (UINT parameter = 0; parameter < pass.desktop_compute_upload_srvs.size(); ++parameter) { + if (const auto address = pass.desktop_compute_upload_srvs[parameter]) + list->SetComputeRootShaderResourceView(parameter, address); + if (const auto address = pass.desktop_compute_root_uavs[parameter]) + list->SetComputeRootUnorderedAccessView(parameter, address); + } +} + void __stdcall list_compute_root(Wrapper* self, void* root) { auto* list = recording(self); @@ -2712,13 +2782,35 @@ void __stdcall list_compute_root(Wrapper* self, void* root) // Root SRV parameters are forwarded by their own slot; anything else the root declares is not. pass.compute_root_has_arguments = real && !w->own().root_without_bindings && !w->own().root_srv_only; if (pass.compute_root) { - if (pass.desktop_compute_root.Get() != pass.compute_root) + if (pass.desktop_compute_root.Get() != pass.compute_root) { pass.desktop_compute_upload_srvs.fill(0); + pass.desktop_compute_root_uavs.fill(0); + } pass.desktop_compute_root = pass.compute_root; list->SetComputeRootSignature(pass.compute_root); } } +// Fixture binding of a desktop root UAV (a desktop GPU address) on a guest list's recording, under the compute root +// set through slot 33. Not a guest slot: titles have no compute root UAV on the desktop list (slot 45 is not +// forwarded). It records the view through bind_compute_root_view, as slot 43 does for root SRVs, so +// restore_compute_root sets it again after a shim compute pass; a binding made on the desktop list directly would be +// lost there. +extern "C" __declspec(dllexport) BOOL x2w_d3d12_fixture_compute_root_uav(void* guest_list, UINT parameter, UINT64 address) +{ + Wrapper* self = as_wrapper(guest_list); + if (!self || self->own().kind != list_kind) return FALSE; + auto* list = recording(self); + auto& pass = pass_of(self); + const auto* params = pass.compute_params; + if (!list || !pass.compute_root || !params || parameter >= params->size() || + parameter >= pass.desktop_compute_root_uavs.size() || (*params)[parameter].type != D3D12_ROOT_PARAMETER_TYPE_UAV || + !address) + return FALSE; + bind_compute_root_view(pass, list, parameter, D3D12_ROOT_PARAMETER_TYPE_UAV, address); + return TRUE; +} + // Query slots 28 to 30, as a hypothesis (command_list_slot_names.h): no fixture here establishes which console // methods sit there, so they are bound only with X2W_D3D12_QUERY_SLOTS=1. The heap reaches device slot 39 with the // desktop desc. Only occlusion queries are @@ -2894,6 +2986,7 @@ constexpr const char* aliased_index_unaligned = "aliased_index_unaligned"; constexpr const char* mesh_xmem_read = "mesh_xmem_read"; constexpr const char* rect_live_compute_root = "rect_live_compute_root"; constexpr const char* rect_conversion_unavailable = "rect_conversion_unavailable"; +constexpr const char* split_dispatch_unavailable = "split_dispatch_unavailable"; constexpr const char* count_missing_resource = "count_missing_resource"; constexpr const char* count_invalid_offset = "count_invalid_offset"; constexpr const char* count_outside_placed_buffer = "count_outside_placed_buffer"; @@ -2901,6 +2994,13 @@ constexpr const char* count_not_common_state = "count_not_common_state"; constexpr const char* unknown = "unknown"; } // namespace indirect_other_refusal_code +// Opt-in (X2W_SPLIT_INDIRECT_DISPATCH=1): a batched or counted indirect Dispatch with a desktop compute pipeline is +// split into single-command calls (split_indirect_dispatch.h). Without it the native call runs on every adapter. +bool split_indirect_dispatch_enabled() +{ + return x2w_local::env_on("X2W_SPLIT_INDIRECT_DISPATCH"); +} + // The guest method has independent resource and byte-offset arguments. void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, void* argument, u64 offset, void* count_buffer, u64 count_offset) @@ -3141,8 +3241,7 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, } } if (rect_list) { - if (std::any_of(pass.desktop_compute_upload_srvs.begin(), pass.desktop_compute_upload_srvs.end(), - [](u64 address) { return address != 0; })) + if (has_compute_root_views(pass)) return refuse("rectangle-list conversion would drop live compute root arguments", indirect_other, indirect_other_refusal_code::rect_live_compute_root); // The producer's count names three vertices per rectangle; the desktop draw needs six. Convert on the GPU @@ -3172,6 +3271,11 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, } } } + // Opt-in split of a batched or counted Dispatch for adapters that run only its first command + // (split_indirect_dispatch.h). Only a rootless Dispatch signature with a desktop compute pipeline and root reaches + // here with a count above one or a count buffer; graphics and mesh signatures are refused above. + const bool split = command == IndirectCommand::dispatch && pass.compute_pipeline && pass.compute_root && + (count > 1 || count_buffer) && split_indirect_dispatch_enabled(); ID3D12Resource* counts = nullptr; if (count_buffer) { // The count word is four bytes in a unique placed buffer that also tracks state from COMMON. @@ -3188,7 +3292,35 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, if (!count_info || count_info->initial_state != D3D12_RESOURCE_STATE_COMMON) return refuse("count buffer does not use COMMON state tracking", indirect_other, indirect_other_refusal_code::count_not_common_state); counts = static_cast(count_wrapper->own().real); - if (counts != resource) require_state(self, counts, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + if (counts != resource) + require_state(self, counts, split ? D3D12_RESOURCE_STATE_COPY_SOURCE : D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + } + if (split) { + // The rewrite reads the title's records and count word by copies only, then replaces the compute root and + // pipeline. The compute state the title can set on the desktop list is the pipeline (slot 25), the root + // (slot 33) and root SRVs (slot 43); the other compute root setters are not forwarded. The pipeline is set + // again here and the root with its views by restore_compute_root, the same code as after the indexed-draw + // validation pass, before the single-command calls. + auto* desktop = device_of(self->own().list_device); + const auto stride = static_cast(sig->own().indirect_bytes); + auto rewritten = x2w_startup::SplitIndirectDispatch::make_scratch(desktop, count, stride); + if (!rewritten || !retain_with_recording(self, rewritten)) + return refuse("split indirect Dispatch has no scratch buffer", indirect_other, + indirect_other_refusal_code::split_dispatch_unavailable); + require_state(self, resource, D3D12_RESOURCE_STATE_COPY_SOURCE); + if (!x2w_startup::split_indirect_dispatch().rewrite(list, resource, offset, count, stride, counts, count_offset, + rewritten.Get())) + return refuse("split indirect Dispatch rewrite is unavailable", indirect_other, + indirect_other_refusal_code::split_dispatch_unavailable); + list->SetPipelineState(static_cast(pass.pipeline->own().real)); + restore_compute_root(pass, list); + const auto first = x2w_startup::SplitIndirectDispatch::rewritten_offset(count, stride); + auto* command = static_cast(sig->own().real); + for (UINT i = 0; i < count; ++i) + list->ExecuteIndirect(command, 1, rewritten.Get(), first + u64{i} * sizeof(D3D12_DISPATCH_ARGUMENTS), nullptr, 0); + x2w_startup::SplitIndirectDispatch::finish(list, rewritten.Get()); + InterlockedIncrement64(&indirect_calls[indirect_forwarded][static_cast(kind)]); + return; } if (!leased_arguments && !rect_list) { require_state(self, resource, argument_state); @@ -3650,8 +3782,7 @@ void __stdcall list_compute_upload_srv(Wrapper* self, UINT parameter, UINT64 add // A rejected replacement leaves no valid binding: the desktop list may still hold the previous address. if (parameter < 32) pass.compute_srv_bound &= ~(1u << parameter); if (gpu && !(gpu % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT)) { - pass.desktop_compute_upload_srvs[parameter] = gpu; - list->SetComputeRootShaderResourceView(parameter, gpu); + bind_compute_root_view(pass, list, parameter, D3D12_ROOT_PARAMETER_TYPE_SRV, gpu); if (parameter < 32) pass.compute_srv_bound |= 1u << parameter; } } diff --git a/src/startup_stubs/split_indirect_dispatch.h b/src/startup_stubs/split_indirect_dispatch.h new file mode 100644 index 000000000..ad967323b --- /dev/null +++ b/src/startup_stubs/split_indirect_dispatch.h @@ -0,0 +1,169 @@ +// Split of a batched indirect Dispatch into single-command calls, for adapters whose driver runs only the first +// command of an ExecuteIndirect with a Dispatch signature. Opt-in only: slot 61 applies it with +// X2W_SPLIT_INDIRECT_DISPATCH=1, to a rootless Dispatch signature with a desktop compute pipeline and root. +// +// On an AMD Radeon RX 5700 XT (RDNA 1, device 731f), drivers 31.0.23013.1023 to 32.0.21045.29003 run exactly one +// command of ExecuteIndirect(Dispatch signature, MaxCommandCount > 1), with or without a count buffer, and ignore +// the count buffer of a single-command call. Single-command calls without a count buffer are exact. Measurements: +// docs/experiments.md#batched-indirect-dispatch-on-rdna-1. +// +// The split copies the count word and the records into a scratch buffer, and a one-group compute pass rewrites +// record i as itself when i < min(count, MaxCommandCount) and as (0,0,0) otherwise. A zero-group Dispatch does +// nothing. The caller then issues MaxCommandCount single-command calls without a count buffer over the rewritten +// records. The title's own buffers are only read by copies, as in rect_indirect_args.h. +#pragma once + +#include +#include +#include + +#include +#include +#include + +namespace x2w_startup { + +// Scratch layout: the count word at byte 0, the title's records copied at byte `split_records_copy`, the rewritten +// 12-byte records at `rewritten_offset(...)`. +inline constexpr UINT64 split_records_copy = 16; + +inline constexpr char split_indirect_dispatch_hlsl[] = R"( +RWByteAddressBuffer scratch : register(u0); +cbuffer Split : register(b0) { uint max_count; uint stride; uint counted; uint rewritten; }; + +[numthreads(64, 1, 1)] +void split(uint i : SV_DispatchThreadID) { + if (i >= max_count) return; + uint count = counted != 0 ? scratch.Load(0) : max_count; + uint3 groups = i < count ? scratch.Load3(16 + i * stride) : uint3(0, 0, 0); + scratch.Store3(rewritten + 12 * i, groups); +} +)"; + +class SplitIndirectDispatch { +public: + // Bytes the title's records occupy: every record up to the maximum, the last one only its 12 Dispatch bytes. + static UINT64 record_span(UINT max_count, UINT stride) + { + return UINT64{max_count - 1} * stride + sizeof(D3D12_DISPATCH_ARGUMENTS); + } + static UINT64 rewritten_offset(UINT max_count, UINT stride) + { + return (split_records_copy + record_span(max_count, stride) + 15) & ~UINT64{15}; + } + // A fresh scratch buffer for one call (rests in COMMON). The caller keeps it alive with the recording. + static Microsoft::WRL::ComPtr make_scratch(ID3D12Device* device, UINT max_count, UINT stride) + { + Microsoft::WRL::ComPtr scratch; + D3D12_HEAP_PROPERTIES heap{}; + heap.Type = D3D12_HEAP_TYPE_DEFAULT; + D3D12_RESOURCE_DESC buffer{}; + buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + buffer.Width = rewritten_offset(max_count, stride) + UINT64{max_count} * sizeof(D3D12_DISPATCH_ARGUMENTS); + buffer.Height = buffer.DepthOrArraySize = buffer.MipLevels = buffer.SampleDesc.Count = 1; + buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + buffer.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + if (!device || FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer, + D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&scratch)))) + scratch.Reset(); + return scratch; + } + // Records the copies and the rewrite into `scratch` (from make_scratch, in COMMON) and leaves it in + // INDIRECT_ARGUMENT state. `records` (and `counts`, if given) must already be in a state that includes + // COPY_SOURCE. Returns false if the pass could not be set up (nothing was recorded then). The compute root + // signature and pipeline of the list are replaced: the caller restores them. `finish` puts the scratch back in COMMON. + bool rewrite(ID3D12GraphicsCommandList* list, ID3D12Resource* records, UINT64 records_offset, UINT max_count, UINT stride, + ID3D12Resource* counts, UINT64 count_offset, ID3D12Resource* scratch) + { + Microsoft::WRL::ComPtr device; + if (!list || !records || !scratch || !max_count || stride < sizeof(D3D12_DISPATCH_ARGUMENTS) || + FAILED(list->GetDevice(IID_PPV_ARGS(&device)))) + return false; + Entry* entry = entry_for(device.Get()); + if (!entry) return false; + transition(list, scratch, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST); + if (counts) list->CopyBufferRegion(scratch, 0, counts, count_offset, sizeof(UINT)); + list->CopyBufferRegion(scratch, split_records_copy, records, records_offset, record_span(max_count, stride)); + transition(list, scratch, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + list->SetComputeRootSignature(entry->root.Get()); + list->SetPipelineState(entry->pipeline.Get()); + list->SetComputeRootUnorderedAccessView(0, scratch->GetGPUVirtualAddress()); + const UINT constants[4]{max_count, stride, counts ? 1u : 0u, static_cast(rewritten_offset(max_count, stride))}; + list->SetComputeRoot32BitConstants(1, 4, constants, 0); + list->Dispatch((max_count + 63) / 64, 1, 1); + // As in rect_indirect_args.h: make the stores visible to the argument fetch without relying on the transition. + D3D12_RESOURCE_BARRIER written{}; + written.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + written.UAV.pResource = scratch; + list->ResourceBarrier(1, &written); + transition(list, scratch, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + return true; + } + static void finish(ID3D12GraphicsCommandList* list, ID3D12Resource* scratch) + { + transition(list, scratch, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON); + } + +private: + struct Entry { + ID3D12Device* device = nullptr; + Microsoft::WRL::ComPtr root; + Microsoft::WRL::ComPtr pipeline; + }; + static void transition(ID3D12GraphicsCommandList* list, ID3D12Resource* resource, D3D12_RESOURCE_STATES before, + D3D12_RESOURCE_STATES after) + { + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier.Transition.pResource = resource; + barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + barrier.Transition.StateBefore = before; + barrier.Transition.StateAfter = after; + list->ResourceBarrier(1, &barrier); + } + // Root signature and pipeline per device. Entries are never freed: a rewrite may still be queued when its list is released. + Entry* entry_for(ID3D12Device* device) + { + std::lock_guard guard(lock_); + for (auto& known : entries_) + if (known->device == device) return known->pipeline ? known.get() : nullptr; + auto entry = std::make_unique(); + entry->device = device; + build(device, *entry); + entries_.push_back(std::move(entry)); + return entries_.back()->pipeline ? entries_.back().get() : nullptr; + } + static void build(ID3D12Device* device, Entry& entry) + { + Microsoft::WRL::ComPtr code, error; + if (FAILED(D3DCompile(split_indirect_dispatch_hlsl, sizeof(split_indirect_dispatch_hlsl) - 1, "split_indirect_dispatch", + nullptr, nullptr, "split", "cs_5_0", 0, 0, &code, &error))) + return; + D3D12_ROOT_PARAMETER parameters[2]{}; + parameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + parameters[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + parameters[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + parameters[1].Constants = {0, 0, 4}; + parameters[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + const D3D12_ROOT_SIGNATURE_DESC desc{2, parameters, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + Microsoft::WRL::ComPtr serialized; + if (FAILED(D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1_0, &serialized, &error)) || + FAILED(device->CreateRootSignature(0, serialized->GetBufferPointer(), serialized->GetBufferSize(), + IID_PPV_ARGS(&entry.root)))) + return; + D3D12_COMPUTE_PIPELINE_STATE_DESC pipeline{}; + pipeline.pRootSignature = entry.root.Get(); + pipeline.CS = {code->GetBufferPointer(), code->GetBufferSize()}; + if (FAILED(device->CreateComputePipelineState(&pipeline, IID_PPV_ARGS(&entry.pipeline)))) entry.pipeline.Reset(); + } + std::mutex lock_; + std::vector> entries_; +}; + +inline SplitIndirectDispatch& split_indirect_dispatch() +{ + static SplitIndirectDispatch splitter; + return splitter; +} + +} // namespace x2w_startup diff --git a/tests/startup_indirect_dispatch.cpp b/tests/startup_indirect_dispatch.cpp index 773fb1c04..090b97a1d 100644 --- a/tests/startup_indirect_dispatch.cpp +++ b/tests/startup_indirect_dispatch.cpp @@ -16,6 +16,8 @@ #include extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); +extern "C" __declspec(dllimport) BOOL x2w_d3d12_fixture_compute_root_uav(void*, UINT, UINT64); +extern "C" __declspec(dllimport) UINT x2w_d3d12_recording_scratches(void*); namespace { using Microsoft::WRL::ComPtr; @@ -25,6 +27,13 @@ using Words = std::vector; bool constants = false; // The `count` mode runs a three-record argument buffer behind a GPU-written count word (max count 3). bool counted = false; +// X2W_SPLIT_INDIRECT_DISPATCH=1 (the startup_indirect_count_split_* tests): the shim splits a batched or counted +// Dispatch into single-command calls over a scratch copy of the records (split_indirect_dispatch.h). +bool split = false; +// The follow-up case records one more Dispatch(1, 1, 2) on the desktop list after the counted ExecuteIndirect, with +// the state the shim left there. It adds 1 + 101 = 102 to the result only if the consumer pipeline, its compute root +// and the result UAV are still bound, also after the split replaced them for its own pass. +constexpr std::uint32_t follow_up_term = 102; constexpr UINT max_commands = 3; Words initial; UINT argument_bytes = 0; @@ -62,6 +71,10 @@ void write_count2() { write_records(2); } void write_count9() { write_records(9); } [numthreads(1, 1, 1)] void write_count0() { write_records(0); } +[numthreads(1, 1, 1)] +void write_count1() { write_records(1); } +[numthreads(1, 1, 1)] +void write_count3() { write_records(3); } [numthreads(1, 1, 1)] void write_args() { data.Store3(4, uint3(4, 3, 2)); } @@ -148,9 +161,13 @@ enum class Rejection { none, unmapped, short_range, placeholder, other_root, par // The constants mode also refuses a rooted signature with two records (rooted_multi) or a count buffer // (rooted_count_buffer): batching is rootless-only in this slice. // The other-root control binds `other_guest_root`, which lacks the signature's constants. +// Count mode only: `follow_up` adds the follow-up Dispatch above. `retire` submits through a guest queue held +// behind a gate fence, resets the guest allocator while that work is still pending, and requires the recording's +// split scratch to be held until the gate opens and the records run. bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* root, ID3D12RootSignature* guest_root, ID3D12RootSignature* other_guest_root, ID3D12PipelineState* writer, IUnknown* consumer, - ID3D12CommandSignature* signature, const Words& record, Rejection rejection) + ID3D12CommandSignature* signature, const Words& record, Rejection rejection, bool follow_up = false, + bool retire = false) { const UINT total_bytes = static_cast(initial.size() * sizeof(std::uint32_t)); auto upload = make_buffer(device, total_bytes, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); @@ -210,7 +227,10 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* root, I using Bind = void (WINAPI*)(IUnknown*, IUnknown*); slot(guest_list.Get(), 25)(guest_list.Get(), consumer); slot(guest_list.Get(), 33)(guest_list.Get(), rejection == Rejection::other_root ? other_guest_root : guest_root); - list->SetComputeRootUnorderedAccessView(0, result->GetGPUVirtualAddress()); + // Bound through the shim, which sets it again after a compute pass of its own (the split of a batched Dispatch). + // If the shim has no matching UAV parameter for the bound guest root, bind on the desktop list as before. + if (!x2w_d3d12_fixture_compute_root_uav(guest_list.Get(), 0, result->GetGPUVirtualAddress())) + list->SetComputeRootUnorderedAccessView(0, result->GetGPUVirtualAddress()); using Execute = void (WINAPI*)(IUnknown*, IUnknown*, UINT, IUnknown*, UINT64, IUnknown*, UINT64); auto* argument = rejection == Rejection::unmapped ? nullptr : guest_arguments.Get(); UINT64 offset = counted ? 2 * sizeof(std::uint32_t) : argument_offset; @@ -229,19 +249,54 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* root, I argument, offset, rejection == Rejection::rooted_count_buffer ? argument : nullptr, rejection == Rejection::rooted_count_buffer ? sizeof(std::uint32_t) : 0); + if (follow_up) list->Dispatch(1, 1, 2); transition(list, result.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); list->CopyBufferRegion(readback.Get(), argument_bytes, result.Get(), 0, result_bytes); using Close = HRESULT (WINAPI*)(IUnknown*); check(slot(guest_list.Get(), 9)(guest_list.Get()), "close guest command list"); + // Each run records on a fresh guest allocator: an accepted counted call holds one split scratch when the split is on. + const bool accepted = rejection == Rejection::none || rejection == Rejection::no_count_buffer; + const UINT scratches = counted && split && accepted ? 1 : 0; + if (counted && x2w_d3d12_recording_scratches(guest_list.Get()) != scratches) { + std::fprintf(stderr, "recording holds %u split scratch buffers after Close, expected %u\n", + x2w_d3d12_recording_scratches(guest_list.Get()), scratches); + return false; + } const D3D12_COMMAND_QUEUE_DESC queue_desc{}; - ComPtr queue; ComPtr fence; - check(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue)), "create queue"); check(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)), "create completion fence"); - ID3D12CommandList* submitted[]{list}; - queue->ExecuteCommandLists(1, submitted); - check(queue->Signal(fence.Get(), 1), "signal completion fence"); - check(fence->SetEventOnCompletion(1, nullptr), "wait for completion"); + if (retire) { + // The shim tracks this submission's fence, so the allocator reset below must not release the scratch the + // split calls read: the desktop queue waits on the gate before it can run them. + ComPtr guest_queue; + check(guest->CreateCommandQueue(&queue_desc, __uuidof(ID3D12CommandQueue), + reinterpret_cast(guest_queue.GetAddressOf())), "create guest queue"); + const auto queue = native_object(device, guest, guest_queue.Get()); + ComPtr gate; + check(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&gate)), "create gate fence"); + check(queue->Wait(gate.Get(), 1), "hold the guest queue on the gate"); + using Submit = void (WINAPI*)(IUnknown*, UINT, IUnknown* const*); + IUnknown* submitted_list = guest_list.Get(); + slot(guest_queue.Get(), 10)(guest_queue.Get(), 1, &submitted_list); + const HRESULT reset = allocator->Reset(); + const UINT held = x2w_d3d12_recording_scratches(guest_list.Get()); + check(gate->Signal(1), "open the gate"); + check(queue->Signal(fence.Get(), 1), "signal completion fence"); + check(fence->SetEventOnCompletion(1, nullptr), "wait for completion"); + std::printf("retire: allocator reset while pending -> 0x%08lx, recording holds %u split scratch buffers\n", + static_cast(reset), held); + if (FAILED(reset) || held != scratches) { + std::fprintf(stderr, "split scratch was released before its submission retired\n"); + return false; + } + } else { + ComPtr queue; + check(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue)), "create queue"); + ID3D12CommandList* submitted[]{list}; + queue->ExecuteCommandLists(1, submitted); + check(queue->Signal(fence.Get(), 1), "signal completion fence"); + check(fence->SetEventOnCompletion(1, nullptr), "wait for completion"); + } check(device->GetDeviceRemovedReason(), "GPU completion"); const D3D12_RANGE read{0, total_bytes}; @@ -262,9 +317,11 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* root, I for (std::uint32_t y = 0; y < expected[3 + 3 * i]; ++y) for (std::uint32_t x = 0; x < expected[2 + 3 * i]; ++x) expected[result_word] += 1 + x + 10 * y + 100 * z; - std::printf("%s: count word=%u, executed=%u, result=0x%08x (expected 0x%08x)\n", + if (follow_up) expected[result_word] += follow_up_term; + std::printf("%s%s%s: count word=%u, executed=%u, result=0x%08x (expected 0x%08x)\n", rejection == Rejection::none ? (writer ? "GPU writer" : "omitted writer") : rejection == Rejection::no_count_buffer ? "no count buffer" : "refused call", + follow_up ? " + follow-up Dispatch" : "", retire ? " + retired allocator" : "", observed[1], executed, observed[result_word], expected[result_word]); for (std::size_t i = 0; i < expected.size(); ++i) { if (observed[i] == expected[i]) continue; @@ -304,6 +361,10 @@ int main(int argc, char** argv) try constants = argc == 3 && std::strcmp(argv[2], "constants") == 0; counted = argc == 3 && std::strcmp(argv[2], "count") == 0; if (argc > 3 || (argc == 3 && !constants && !counted)) return 2; + { + char value[4]{}; + split = GetEnvironmentVariableA("X2W_SPLIT_INDIRECT_DISPATCH", value, sizeof(value)) && value[0] == '1'; + } initial = counted ? Words{0xa5a5a5a5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x31415926, 0x5a5a5a5a} : constants ? Words{0xa5a5a5a5, 0, 0, 0, 0, 0, 3, 5, 1, 1, 1, 0x31415926, 0x5a5a5a5a} : Words{0xa5a5a5a5, 0, 0, 0, 0x31415926, 0x5a5a5a5a}; argument_bytes = static_cast((initial.size() - 2) * sizeof(std::uint32_t)); @@ -400,20 +461,28 @@ int main(int argc, char** argv) try const auto writer = pipeline(device.Get(), root.Get(), counted ? "write_count2" : constants ? "write_constant_args" : "write_args"); const auto clamped_writer = pipeline(device.Get(), root.Get(), "write_count9"); const auto zero_writer = pipeline(device.Get(), root.Get(), "write_count0"); + const auto one_writer = pipeline(device.Get(), root.Get(), "write_count1"); + const auto three_writer = pipeline(device.Get(), root.Get(), "write_count3"); const auto other_writer = pipeline(device.Get(), root.Get(), constants ? "write_swapped_args" : "write_fewer_args"); const auto consumer = guest_pipeline(guest.Get(), guest_root.Get()); const auto verify = [&](ID3D12PipelineState* producer, const Words& record, Rejection rejection, - ID3D12CommandSignature* command_signature) { + ID3D12CommandSignature* command_signature, bool follow_up = false, bool retire = false) { return run(device.Get(), guest.Get(), root.Get(), guest_root.Get(), other_guest_root.Get(), producer, - consumer.Get(), command_signature, record, rejection); + consumer.Get(), command_signature, record, rejection, follow_up, retire); }; const auto run_counted = [&] { const Words records{0, 2, 1, 1, 1, 2, 1, 1, 1, 3}; const auto with_count = [&](std::uint32_t count) { Words r = records; r[0] = count; return r; }; const auto& sig = signature; + // GPU-written counts 2, above the maximum (9), 0, 1 and 3; a zero count must leave the result untouched. + // With the split on, the last case also resets the guest allocator before its submission retires. return verify(writer.Get(), with_count(2), Rejection::none, sig.Get()) && verify(clamped_writer.Get(), with_count(9), Rejection::none, sig.Get()) && verify(zero_writer.Get(), with_count(0), Rejection::none, sig.Get()) && + verify(one_writer.Get(), with_count(1), Rejection::none, sig.Get()) && + verify(three_writer.Get(), with_count(3), Rejection::none, sig.Get()) && + verify(writer.Get(), with_count(2), Rejection::none, sig.Get(), true) && + (!split || verify(writer.Get(), with_count(2), Rejection::none, sig.Get(), false, true)) && verify(nullptr, {}, Rejection::none, sig.Get()) && verify(zero_writer.Get(), with_count(0), Rejection::no_count_buffer, sig.Get()) && verify(writer.Get(), with_count(2), Rejection::unmapped, sig.Get()) && From 08814b4f79e94de0e6cfa1ab254b2312501ded3b Mon Sep 17 00:00:00 2001 From: RavenCurseBurg Date: Thu, 26 Nov 2026 11:33:59 +0800 Subject: [PATCH 121/240] tests: dispatch twice on the same slot 67 pipeline around late publication (#2716) Fence the untranslated first call, run the real offline compiler while the original device and pipeline stay alive, and check all output words on the second call. Repeat without publishing as a negative control. AI-assisted with Codex (GPT-6.2 Astra, xhigh). (cherry picked from commit 3d596a2845e3267eb530f2dad2ee0524d5105476) Co-authored-by: RavenCurseBurg <360931527+RavenCurseBurg@users.noreply.github.com> Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 6 +- docs/experiments.md | 7 +++ tests/startup_compute_dispatch_check.py | 29 ++++++---- tests/startup_compute_live_retry_check.py | 68 +++++++++++++++++++++++ tests/startup_stream_consumer.cpp | 12 +++- 5 files changed, 108 insertions(+), 14 deletions(-) create mode 100644 tests/startup_compute_live_retry_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index ebf3056d9..a2c7fd652 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4380,8 +4380,12 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME startup_compute_dispatch_heap_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_dispatch_heap_check.py" "$" "${DXC_EXECUTABLE}" ${adapter}) + add_test(NAME startup_compute_live_retry_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_live_retry_check.py" "$" + "${DXC_EXECUTABLE}" ${adapter}) set_tests_properties(startup_compute_dispatch_${adapter} startup_compute_dispatch_texture_${adapter} - startup_compute_dispatch_heap_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + startup_compute_dispatch_heap_${adapter} startup_compute_live_retry_${adapter} + PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() add_test(NAME startup_stream_adapter_filter COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stream_rasterizer_check.py" diff --git a/docs/experiments.md b/docs/experiments.md index 11ec23f98..611eaf520 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -16392,6 +16392,13 @@ The log line `x2w-render compute dispatches: translated , refused , no tra Measured on three fixture programs. The sampling fixture uses a 1x1 texture, so it does not tell sampler filter or address modes apart. Programs with other texture kinds, sampler heaps, the same texture as input and output, or buffer outputs in memory that is not aliased are not dispatched. +The `startup_compute_live_retry_warp` and `startup_compute_live_retry_hardware` tests keep the device and +slot 67 pipeline alive across two fenced Dispatch calls. The first observes the missing translation and +preserves all 320 output words. The test runs `gfx2hlsl.py --pending` while the process waits, then checks +the second output against the source program once the one-second manifest poll interval has elapsed. +A second run keeps the manifest absent and checks both refusals and both untouched outputs. +Run the two backends with `ctest --preset release --no-tests=error -j 1 -R '^startup_compute_live_retry_(warp|hardware)$' -V`. + ```powershell cmake --build --preset dev --target startup_stream_consumer ctest --preset dev --no-tests=error -R "^startup_compute_dispatch_" -V diff --git a/tests/startup_compute_dispatch_check.py b/tests/startup_compute_dispatch_check.py index 018d4a4b7..bc1ee0577 100644 --- a/tests/startup_compute_dispatch_check.py +++ b/tests/startup_compute_dispatch_check.py @@ -51,20 +51,27 @@ def lines(result, text): return [line for line in result.stderr.splitlines() if text in line] +def prepare_case(directory, adapter): + cache, env = prepare(directory) + env.update(X2W_D3D12_LIST_NOOP='1', X2W_D3D12_DEBUG='1') + if adapter == 'hardware': + env['X2W_TEST_DISPATCH_HARDWARE'] = '1' + else: + env.pop('X2W_TEST_DISPATCH_HARDWARE', None) + (directory / 'compute_root').write_bytes(C.root_blob(table_range=True)) + env['X2W_TEST_COMPUTE_ROOT'] = str(directory / 'compute_root') + _, words, rsrc2, group, groups = C.CASES['A'] + assert groups == (3, 2, 2) and (C.KEY, C.STRIDE) == (0x01234567, 0x9e3779b9), 'the consumer hard-codes case A' + (directory / 'program').write_bytes(words) + (directory / 'data').write_bytes(DATA) + (directory / 'state').write_bytes(state_a(group, rsrc2)) + return cache, env + + def main(consumer, dxc, adapter): with tempfile.TemporaryDirectory() as temporary: directory = Path(temporary) - cache, env = prepare(directory) - env.update(X2W_D3D12_LIST_NOOP='1', X2W_D3D12_DEBUG='1') # guest lists; debug-layer messages go to the log - if adapter == 'hardware': - env['X2W_TEST_DISPATCH_HARDWARE'] = '1' - (directory / 'compute_root').write_bytes(C.root_blob(table_range=True)) - env['X2W_TEST_COMPUTE_ROOT'] = str(directory / 'compute_root') - _, words, rsrc2, group, groups = C.CASES['A'] - assert groups == (3, 2, 2) and (C.KEY, C.STRIDE) == (0x01234567, 0x9e3779b9), 'the consumer hard-codes case A' - (directory / 'program').write_bytes(words) - (directory / 'data').write_bytes(DATA) - (directory / 'state').write_bytes(state_a(group, rsrc2)) + cache, env = prepare_case(directory, adapter) untouched, expected = [C.SENTINEL] * C.WORDS, C.expected('A') assert expected != untouched diff --git a/tests/startup_compute_live_retry_check.py b/tests/startup_compute_live_retry_check.py new file mode 100644 index 000000000..40adb04d6 --- /dev/null +++ b/tests/startup_compute_live_retry_check.py @@ -0,0 +1,68 @@ +"""Dispatch twice through the same device slot 67 pipeline with an offline translation arriving between calls.""" +import os +from pathlib import Path +import struct +import subprocess +import sys +import tempfile +import time + +from startup_compute_dispatch_check import C, G, prepare_case + + +def words(output): + return list(struct.unpack(f'<{C.WORDS}I', output.read_bytes())) + + +def run(directory, consumer, dxc, adapter, publish): + cache, env = prepare_case(directory, adapter) + output = directory / 'out.bin' + args = [consumer, directory / 'vertex', directory / 'pixel', directory / 'root', 'slot67', + directory / 'program', directory / 'data', directory / 'state', 'dispatch-retry'] + stdout, stderr = directory / 'stdout', directory / 'stderr' + sentinel = [C.SENTINEL] * C.WORDS + with stdout.open('wb') as out, stderr.open('wb') as err, subprocess.Popen( + args, stdin=subprocess.PIPE, stdout=out, stderr=err, env=dict(env, X2W_TEST_DISPATCH_OUT=str(output))) as process: + try: + deadline = time.monotonic() + 20 + while 'first slot 67 Dispatch fenced' not in stdout.read_text(): + if process.poll() == 77: + print(stdout.read_text(), end='') + raise SystemExit(77) + if process.poll() is not None or time.monotonic() > deadline: + raise AssertionError(f'first Dispatch did not fence\n{stderr.read_text()[-2500:]}') + time.sleep(0.025) + first = time.monotonic() + assert words(output) == sentinel, 'first Dispatch wrote before translation' + output.unlink() + request, = cache.glob('req_*.c67') + key = request.stem.removeprefix('req_') + assert not (cache / (key + '.txt')).exists() + if publish: + result = subprocess.run([sys.executable, '-B', G.__file__, '--pending', cache], check=True, + capture_output=True, text=True, env=dict(os.environ, X2W_DXC=dxc)) + assert f'{key}: ok' in result.stdout, result.stdout + # The runtime polls a missing manifest at one-second intervals. + time.sleep(max(0, first + 1.1 - time.monotonic())) + process.communicate(input=b'\n', timeout=20) + finally: + if process.poll() is None: + process.kill() + process.wait() + log = stderr.read_text() + assert process.returncode == 0, log[-2500:] + assert log.count('Dispatch(3, 2, 2) refused: no translation') == (1 if publish else 2), log[-2500:] + assert log.count('Dispatch(3, 2, 2) translated:') == int(publish), log[-2500:] + assert words(output) == (C.expected('A') if publish else sentinel) + errors = [line for line in log.splitlines() if 'x2w-d3d12-debug ' in line and (' sev=0 ' in line or ' sev=1 ' in line)] + assert not errors, errors + print(stdout.read_text(), end='') + print(f'{key}: both fenced {C.WORDS}-word readbacks match, late publication={publish}') + + +if __name__ == '__main__': + if len(sys.argv) != 4 or sys.argv[3] not in ('warp', 'hardware'): + sys.exit('usage: startup_compute_live_retry_check.py ') + for publish in (True, False): + with tempfile.TemporaryDirectory() as tmp: + run(Path(tmp), *sys.argv[1:], publish) diff --git a/tests/startup_stream_consumer.cpp b/tests/startup_stream_consumer.cpp index 8d672d385..120634bbb 100644 --- a/tests/startup_stream_consumer.cpp +++ b/tests/startup_stream_consumer.cpp @@ -488,8 +488,16 @@ int main(int argc, char** argv) if (const int rc = prepare_stream_pipeline(argv[1], argv[2], argv[3], hardware, textured, adapter, device, pso)) return rc; // slot67 [case]: WARP device and root only, then slot-67 creations. - if (argc == 9 && std::strcmp(argv[4], "slot67") == 0 && std::strncmp(argv[8], "dispatch", 8) == 0) - return create_slot67(device, argv[5], argv[6], argv[7], argv[8]) ? dispatch_slot67(device, argv[8]) : 10; + if (argc == 9 && std::strcmp(argv[4], "slot67") == 0 && std::strncmp(argv[8], "dispatch", 8) == 0) { + if (!create_slot67(device, argv[5], argv[6], argv[7], argv[8])) return 10; + if (std::strcmp(argv[8], "dispatch-retry") == 0) { + if (int rc = dispatch_slot67(device, "dispatch")) return rc; + std::puts("first slot 67 Dispatch fenced"); + std::fflush(stdout); + if (std::getchar() != '\n') return 2; + } + return dispatch_slot67(device, argv[8]); + } if (argc == 9 && std::strcmp(argv[4], "slot67") == 0 && std::strncmp(argv[8], "texture", 7) == 0) return create_slot67(device, argv[5], argv[6], argv[7], argv[8]) ? texture_slot67(device, argv[8]) : 10; if ((argc == 8 || argc == 9) && std::strcmp(argv[4], "slot67") == 0) From 65060974d36e834096c7fa30d236d276d5efaeed Mon Sep 17 00:00:00 2001 From: Royoo <3230853833@qq.com> Date: Thu, 26 Nov 2026 11:38:57 +0800 Subject: [PATCH 122/240] Verify raw vertex-buffer reads through copied descriptors (#2720) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 4 ++ docs/experiments.md | 17 +++++++++ tests/startup_address_srv.cpp | 47 ++++++++++++++++++++++++ tests/startup_address_srv_check.py | 11 ++++-- tests/startup_copied_vertex_srv_check.py | 47 ++++++++++++++++++++++++ tests/startup_stream_draw.cpp | 3 ++ 6 files changed, 126 insertions(+), 3 deletions(-) create mode 100644 tests/startup_copied_vertex_srv_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index a2c7fd652..237531e30 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4531,6 +4531,10 @@ if(EXISTS "${INTAKE_PYTHON}") "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_address_buffer_srv_check.py" "$" "${backend}") set_tests_properties(startup_address_buffer_srv_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + add_test(NAME startup_copied_vertex_srv_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_copied_vertex_srv_check.py" + "$" "${backend}") + set_tests_properties(startup_copied_vertex_srv_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) add_test(NAME startup_mubuf_descriptor_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_mubuf_descriptor_check.py" "$" "${backend}") diff --git a/docs/experiments.md b/docs/experiments.md index 611eaf520..2d4e97831 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15746,6 +15746,23 @@ and array views and for unreadable arguments. `startup_address_srv_hardware` and `startup_address_srv_warp` also match the five lines of their refused calls (zero address, other width, interior address, a buffer view, a destination off the heap) and show the descriptor unchanged. +### Copied raw vertex-buffer SRVs + +`startup_copied_vertex_srv` publishes 512-byte and 256-byte raw views of the +same source-built buffer into separate slots. It copies each view in turn to +the bound table slot, compares the guest-visible descriptor bytes with the +source slot, and draws a band with that binding. The vertex shader reads +distinct words at byte offsets 224 and 288. All 32 pixels must show both words +with the full view, only the first word with the stale short view, and both +words again after copying the full view back. This covers the copy and lookup +sequence through slot 24 for #2695. The descriptor producer in the executable's +diagnostic run remains unidentified. + +```powershell +cmake --build --preset release --target startup_stream_consumer +ctest --preset release --no-tests=error -R '^startup_(copied_vertex_srv|address_buffer_srv|frame_copy)_(warp|hardware)$' -V +``` + ```powershell cmake --build --preset release --target startup_memory_srv_report_check startup_stream_consumer d3d12_xs_shim ctest --preset release --no-tests=error -R '^(startup_memory_srv_report|startup_address_srv_)' -V diff --git a/tests/startup_address_srv.cpp b/tests/startup_address_srv.cpp index 7e2c58f21..3f0211a19 100644 --- a/tests/startup_address_srv.cpp +++ b/tests/startup_address_srv.cpp @@ -473,6 +473,53 @@ int draw_formatted_view(void* guest, void* list) return 0; } +int draw_copied_vertex_buffer_srv(void* guest, void* list) +{ + constexpr UINT full_bytes = 512; + constexpr UINT short_bytes = 256; + static std::array storage{}; + auto* records = reinterpret_cast((ptr(storage.data()) + 0xffff) & ~Word{0xffff}); + records[224 / sizeof(*records)] = 57; + records[288 / sizeof(*records)] = 181; + + const D3D12_RESOURCE_DESC buffer{D3D12_RESOURCE_DIMENSION_BUFFER, 0, full_bytes, 1, 1, 1, + DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; + void* placed = nullptr; + if (FAILED(static_cast(invoke(guest, 133, ptr(records), ptr(&buffer), D3D12_RESOURCE_STATE_COMMON, + 0, ptr(&__uuidof(ID3D12Resource)), ptr(&placed))))) return 47; + + const Word stride = invoke(guest, 15, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + alignas(64) static std::array descriptors{}; + Word cpu = 0; + if (!stride || stride > descriptors.size() / 3 || + !bind_view_table(guest, list, cpu, 3, ptr(descriptors.data()), 3 * stride) || + cpu != ptr(descriptors.data())) return 42; + + ViewAt view{}; + view.view.Format = DXGI_FORMAT_R32_TYPELESS; + view.view.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + view.view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + view.view.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + view.address = ptr(records); + view.view.Buffer.NumElements = full_bytes / sizeof(*records); + invoke(guest, 70, ptr(&buffer), ptr(&view), cpu + stride); + view.view.Buffer.NumElements = short_bytes / sizeof(*records); + invoke(guest, 70, ptr(&buffer), ptr(&view), cpu + 2 * stride); + if (std::memcmp(descriptors.data() + stride, descriptors.data() + 2 * stride, stride) == 0) return 54; + + const auto copy_and_draw = [&](Word source, LONG left, LONG right) { + invoke(guest, 24, 1, cpu, cpu + source * stride, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + if (std::memcmp(descriptors.data(), descriptors.data() + source * stride, stride) != 0) return false; + const D3D12_RECT strip{left, 0, right, 4}; + invoke(list, 22, 1, ptr(&strip)); + invoke(list, 12, 3, 1); + return true; + }; + if (!copy_and_draw(1, 0, 2) || !copy_and_draw(2, 2, 6) || !copy_and_draw(1, 6, 8)) return 55; + std::printf("copied vertex buffer SRV with %llu-byte descriptors\n", static_cast(stride)); + return 0; +} + int draw_address_buffer_srvs(ID3D12Device* desktop, void* guest, void* list) { static std::array raw_buf0{}; diff --git a/tests/startup_address_srv_check.py b/tests/startup_address_srv_check.py index a5a6cc5c3..0fbfe7f73 100644 --- a/tests/startup_address_srv_check.py +++ b/tests/startup_address_srv_check.py @@ -9,7 +9,7 @@ from startup_stream_draw_check import gfx2hlsl, pixel, vertex -def prepare_draw_cache(directory, consumer, hlsl, modes, binding): +def prepare_draw_cache(directory, consumer, hlsl, modes, binding, *, vertex_hlsl=None): cache = directory / "cache" cache.mkdir() vs, ps, root, output = (directory / name for name in ("vs", "ps", "root", "pixels")) @@ -27,12 +27,17 @@ def prepare_draw_cache(directory, consumer, hlsl, modes, binding): source.write_text(hlsl) subprocess.run([env["X2W_FXC"], "/nologo", "/T", "ps_5_0", "/E", "main", "/Fo", manifest.with_suffix(".ps.cso"), source], check=True) + if vertex_hlsl is not None: + source = manifest.with_suffix(".vs.hlsl") + source.write_text(vertex_hlsl, encoding="ascii") + subprocess.run([env["X2W_FXC"], "/nologo", "/T", "vs_5_0", "/E", "main", "/Fo", + manifest.with_suffix(".vs.cso"), source], check=True) return env, args, output -def draw_texture(directory, consumer, backend, hlsl, modes, view_kind="tex2d", *, binding=None): +def draw_texture(directory, consumer, backend, hlsl, modes, view_kind="tex2d", *, binding=None, vertex_hlsl=None): binding = binding or f"srv 0 {view_kind} table 0 0" - env, args, output = prepare_draw_cache(directory, consumer, hlsl, modes, binding) + env, args, output = prepare_draw_cache(directory, consumer, hlsl, modes, binding, vertex_hlsl=vertex_hlsl) result = subprocess.run([*args, backend, output], env=env, capture_output=True, text=True) print(result.stdout, end="") if result.returncode == 77: diff --git a/tests/startup_copied_vertex_srv_check.py b/tests/startup_copied_vertex_srv_check.py new file mode 100644 index 000000000..48e0ca0fd --- /dev/null +++ b/tests/startup_copied_vertex_srv_check.py @@ -0,0 +1,47 @@ +"""Read both sides of a 256-byte boundary through a copied vertex-buffer SRV.""" +from pathlib import Path +import sys +import tempfile + +from startup_address_srv_check import draw_texture + +VERTEX = """ +ByteAddressBuffer records : register(t0); +struct Vertex { + float4 position : SV_Position; + nointerpolation uint2 values : TEXCOORD0; +}; +Vertex main(uint id : SV_VertexID) { + const float2 corners[3] = {float2(-1, 1), float2(3, 1), float2(-1, -3)}; + Vertex output; + output.position = float4(corners[id], 0.5, 1); + output.values = uint2(records.Load(224), records.Load(288)); + return output; +} +""" + +PIXEL = """ +float4 main(float4 position : SV_Position, nointerpolation uint2 values : TEXCOORD0) : SV_Target { + return float4(float2(values) / 255.0, 0, 1); +} +""" + + +def check(directory, consumer, backend): + pixels = draw_texture(directory, consumer, backend, PIXEL, + {"X2W_TEST_COPIED_VERTEX_SRV": "1"}, + binding="srv 0 buf table 0 0", vertex_hlsl=VERTEX) + if pixels is None: + return 77 + full = bytes((57, 181, 0, 255)) + short = bytes((57, 0, 0, 255)) + expected = (full * 2 + short * 4 + full * 2) * 4 + if pixels != expected: + raise AssertionError(f"{backend}: copied vertex SRV got {pixels.hex()}, expected {expected.hex()}") + print(f"{backend}: 32 pixels matched full, short, and restored copied descriptors") + return 0 + + +if __name__ == "__main__": + with tempfile.TemporaryDirectory() as temporary: + sys.exit(check(Path(temporary), *sys.argv[1:])) diff --git a/tests/startup_stream_draw.cpp b/tests/startup_stream_draw.cpp index 3f2405a97..a99e0c19a 100644 --- a/tests/startup_stream_draw.cpp +++ b/tests/startup_stream_draw.cpp @@ -335,6 +335,9 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* } else if (GetEnvironmentVariableW(L"X2W_TEST_FORMATTED_VIEW", nullptr, 0)) { extern int draw_formatted_view(void*, void*); if (const int result = draw_formatted_view(guest, list)) return result; + } else if (GetEnvironmentVariableW(L"X2W_TEST_COPIED_VERTEX_SRV", nullptr, 0)) { + extern int draw_copied_vertex_buffer_srv(void*, void*); + if (const int result = draw_copied_vertex_buffer_srv(guest, list)) return result; } else if (GetEnvironmentVariableW(L"X2W_TEST_ADDRESS_BUFFER_SRV", nullptr, 0)) { extern int draw_address_buffer_srvs(ID3D12Device*, void*, void*); if (const int result = draw_address_buffer_srvs(desktop.Get(), guest, list)) return result; From 8016c393d1c4772508c87bc07629ff3077649251 Mon Sep 17 00:00:00 2001 From: Jess Doit <86271385+Jess-Doit@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:40:53 -0800 Subject: [PATCH 123/240] shader: preserve signed zero in floating-point min and max (#2044) Both translators resolve a pair of zeros from the sign bits (maximum ANDs the signs, minimum ORs them), following the RDNA 2 V_MIN/V_MAX clauses. The startup shader cache revisions advance from 14 to 15 and 15cs. Co-authored-by: Claude Opus 5.5 Co-authored-by: tedin7 Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- .github/workflows/windows.yml | 2 + AGENTS.md | 1 + CMakeLists.txt | 8 + docs/experiments.md | 32 ++ docs/startup-runtime.md | 9 +- src/startup_stubs/d3d12_draw.inl | 6 +- tests/pixel_aot_check.py | 13 +- tests/shader_signed_zero_minmax_check.py | 276 ++++++++++++++++++ .../startup_compute_request_offline_check.py | 4 +- tests/startup_gfx2hlsl_buffer_store_check.py | 4 +- tests/startup_gfx2hlsl_f32_med3_check.py | 6 +- tests/startup_gfx2hlsl_float_alu_check.py | 12 +- tests/startup_gfx2hlsl_fract_check.py | 6 +- tests/startup_gfx2hlsl_root_check.py | 8 +- tests/startup_indirect_draw_indexed.cpp | 2 +- ...tartup_packed_position_provenance_check.py | 2 +- tests/startup_resource_retire_title.cpp | 2 +- tests/startup_shader_cache_key_check.py | 6 +- tools/pixel_aot.py | 29 +- tools/shader_minmax.py | 18 ++ tools/startup/gfx2hlsl.py | 22 +- 21 files changed, 413 insertions(+), 55 deletions(-) create mode 100644 tests/shader_signed_zero_minmax_check.py create mode 100644 tools/shader_minmax.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 8fabc1a9b..db21607e1 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -134,6 +134,7 @@ jobs: (["tests/startup_gfx2hlsl_interp_p2_hi_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_sgpr_spill_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_mad_check.py", "binary", "llvm-mc-15"], {}), + (["tests/shader_signed_zero_minmax_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_compute_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_compute_lds_b64_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_compute_lds_b128_check.py", "binary", "llvm-mc-15"], {}), @@ -320,6 +321,7 @@ jobs: tests/startup_gfx2hlsl_spill_branches_check.py \ tests/startup_gfx2hlsl_mad_check.py \ tests/startup_gfx2hlsl_neg_check.py \ + tests/shader_signed_zero_minmax_check.py \ tests/startup_gfx2hlsl_compute_check.py \ tests/startup_compute_lds_b64_check.py \ tests/startup_compute_lds_b128_check.py \ diff --git a/AGENTS.md b/AGENTS.md index 3afd7fb16..e435d0cb9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -167,6 +167,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_mad_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_neg_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_interp_p2_hi_check.py +./out/pe-env/bin/python -B tests/shader_signed_zero_minmax_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_compute_check.py ./out/pe-env/bin/python -B tests/startup_compute_image_store_check.py ./out/pe-env/bin/python -B tests/startup_compute_image_store_d16_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 237531e30..eaf0a4b5f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4045,6 +4045,14 @@ if(EXISTS "${INTAKE_PYTHON}") endforeach() add_test(NAME startup_gfx2hlsl_mad_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_mad_check.py") + add_test(NAME shader_signed_zero_minmax_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/shader_signed_zero_minmax_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME shader_signed_zero_minmax_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/shader_signed_zero_minmax_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(shader_signed_zero_minmax_${adapter} PROPERTIES TIMEOUT 240 SKIP_RETURN_CODE 77) + endforeach() foreach(adapter IN ITEMS warp hardware) add_test(NAME startup_gfx2hlsl_mad_dispatch_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_mad_check.py" dispatch "${DXC_EXECUTABLE}" diff --git a/docs/experiments.md b/docs/experiments.md index 2d4e97831..dbe49ec77 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -7727,6 +7727,38 @@ cmake --build --preset dev --target offscreen_check ctest --preset dev --no-tests=error -R '^compute_to_pixel_(warp|hardware)$' -V ``` +## Signed zero in floating-point min and max + +The RDNA 2 ISA defines `-0 < +0` for `V_MIN_F32`, `V_MAX_F32`, `V_MIN_F16` +and `V_MAX_F16` (§12.7, pp. 132–133 and 136). Its three-input min and max +compose these operations (§12.12, p. 170), and its packed instructions apply +min or max to each half (§12.10, p. 164). The median description specifies a +median without a separate mixed-zero rule. The fixture uses the same signed-zero +ordering for the median. DXIL FMin and FMax permit either operand when their +values compare equal. [AMD RDNA 2 ISA](https://docs.amd.com/api/khub/documents/Et~wpu9g~Ffl7d9q0QZ~Og/content), [DXIL operation reference](https://github.com/microsoft/DirectXShaderCompiler/blob/main/docs/DXIL.rst#fmax) + +Both translators now resolve a pair of zeros from the sign bits. Maximum ANDs +the signs and minimum ORs them. The startup shader cache revision advances to +`x2w-startup-shader-18`, so translations cached before the change are not reused. The pixel translator applies the same rule to +each widened half for packed binary16 min and max. It retains the packed NaN +selection and the existing output modifiers. The startup translator retains +its own median NaN behavior. Scalar binary16 min/max, three-input binary16 +forms and startup SDWA min/max remain outside the supported instruction set. + +On Windows 10 (10.0.19045.6456), the in-box WARP baseline (10.0.19041.5794) +returned `00000000` for `(-0, +0)` and `80000000` for `(+0, -0)` for both +two-input operations. Three-input and packed results also varied with operand +order. WARP differed from the reference on 50 of 252 result words. The GTX 1060 +(32.0.15.6094) already matched all 252. With the helper, both adapters matched +all words, including single quiet NaN inputs and binary16 packed results. +The draws use DXC for the offline pixel path and DXC and FXC for the startup +path. These comparisons cover desktop results. Median and packed tie behavior +on console hardware, signaling NaNs and NaN payload propagation were unmeasured. + +Run `ctest --preset dev --no-tests=error -R '^shader_signed_zero_minmax_' -V`. +The Python test pins each emitted lowering and the LLVM 15 check reassembles +the source-built instructions. + ## Offline pixel shader recompilation The 64-bit scalar set and clear forms are s_bitset0_b64 and s_bitset1_b64. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 57605f7ed..78047747d 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -208,10 +208,11 @@ The translation is refused when: - either header has another size; - the code reads an attribute the table does not list. -The shader cache revision is `x2w-startup-shader-17`. Earlier translations lower `v_med3_f32` through a -branchless median, which returns the smaller of the other two operands when a source is NaN. The matching -compute (`x2w-startup-shader-17cs`) and fixed slot 57 mesh (`x2w-startup-mesh-57-2`) keys advance -because those stages use the shared lowering. +The shader cache revision is `x2w-startup-shader-18`. Revision 18 preserves the sign of zero in +floating-point min, max, min3, max3 and med3. The matching compute (`x2w-startup-shader-18cs`) and fixed +slot 57 mesh (`x2w-startup-mesh-57-3`) keys advance because those stages use the shared lowering. +Revisions before 17 lower `v_med3_f32` through a branchless median, which returns the smaller of the +other two operands when a source is NaN. Revisions before 16 lower `v_fract_f32` through a bare `frac` instead of the clamped `fract32` helper. Revisions before 15 lower `v_cvt_pk_u8_f32` with a float clamp and accept `s_setreg_imm32_b32` writes of the rounding mode. diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 4c31e03ca..abb29f224 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -353,7 +353,7 @@ Translation* cached_translation(const void* a, std::size_t a_bytes, const void* { // Keep pre-fix desktop bytecode and manifests out of this ABI's cache. // tools/startup/gfx2hlsl.py hashes the same bytes, without a trailing NUL. - constexpr char revision[] = "x2w-startup-shader-17"; + constexpr char revision[] = "x2w-startup-shader-18"; const u64 seed = fnv_bytes(revision, sizeof(revision) - 1); u64 key = fnv_bytes(root_blob.data(), root_blob.size(), fnv_bytes(b, b_bytes, fnv_bytes(a, a_bytes, seed))); // A stream's input layout (stream_input_layout) feeds the vertex fetch, so it is part of the key. @@ -474,7 +474,7 @@ u64 publish_compute_request(const void* desc) std::vector fields(sizeof(words)); words[0] = words[1] = words[3] = words[5] = words[7] = words[9] = words[10] = 0; std::memcpy(fields.data(), words, sizeof(words)); - constexpr char compute_revision[] = "x2w-startup-shader-17cs"; // tools/startup/gfx2hlsl.py compute_key + constexpr char compute_revision[] = "x2w-startup-shader-18cs"; // tools/startup/gfx2hlsl.py compute_key u64 key = fnv_bytes(compute_revision, sizeof(compute_revision) - 1); const std::vector* order[] = {&code, &data, &root_blob, &fields, &state_a, &state_b}; for (const auto* part : order) key = fnv_part(*part, key); @@ -538,7 +538,7 @@ void request_slot57_mesh(Wrapper* pipeline, const std::vector* bo return copy_title_bytes(out.data(), pointer, out.size()); }; if (!copy_stage(13, true, mesh) || !copy_stage(5, false, pixel)) return; - constexpr char revision[] = "x2w-startup-mesh-57-2"; + constexpr char revision[] = "x2w-startup-mesh-57-3"; const u64 key = fnv_part(root_blob, fnv_part(pixel, fnv_part(mesh, fnv_bytes(revision, sizeof(revision) - 1)))); static SRWLOCK request_lock = SRWLOCK_INIT; static std::unordered_set written; diff --git a/tests/pixel_aot_check.py b/tests/pixel_aot_check.py index 2c1098356..813432849 100644 --- a/tests/pixel_aot_check.py +++ b/tests/pixel_aot_check.py @@ -8764,7 +8764,8 @@ def check_literal_fma_draw(directory, compiler, renderer, backend): def check_scalar_pair_reads() -> None: program = with_scalar_pair_reads() source = translate(program) - for field in ("(params[0].w * sample", "max(params[15].z, ", "(params[1].x + sample", "(params[1].y - sample", + for field in ("(params[0].w * sample", "minmax_zero32(params[15].z, alu22, true)", + "(params[1].x + sample", "(params[1].y - sample", "= params[1].z;", "(params[15].w * alu"): assert field in source, field @@ -9816,9 +9817,11 @@ def three_way_case(directory, low, high, cap, middle, *, name="three_way.case"): def check_three_way_templates(): """The HLSL forms must pick the expected operand for every operand order, NaN operands included.""" names = {"min": min_num, "max": max_num, "asuint": lambda x: struct.unpack(" (0x[0-9a-f]+)u \? (.+) : (.+);\n\}") + r" return top > (0x[0-9a-f]+)u\n \? (.+)\n : (.+);\n\}") for top, limit, nan_form, finite_form in re.findall(helper, pixel_aot.PREAMBLE, re.M): top = re.sub(r"(0x[0-9a-f]+)u\b", r"\1", top) names["med3_32"] = lambda a, b, c: eval( @@ -18904,9 +18907,9 @@ def _check_controls_inline(directory): must_reject(translate, [line.replace(old, new) for line in shaping()]) source = translate(three_way()) for expected in ("med3_32(params[1].z, sample16.y, sample16.x)", - "max(max(sample16.x, sample16.z), sample16.y)", + "minmax_zero32(minmax_zero32(sample16.x, sample16.z, true), sample16.y, true)", "med3_32(sample16.x, params[0].w, params[1].x)", - "min(min(abs(params[1].y), sample16.y), alu"): + "minmax_zero32(minmax_zero32(abs(params[1].y), sample16.y, false), alu22, false)"): assert expected in source, expected for old, new in (("v_med3_f32 v12, v12, s44, s45", "v_med3_f32 v12, v12, s44"), ("v_med3_f32 v15, s47", "v_med3_i32 v15, |s47|"), @@ -24162,7 +24165,7 @@ def check_three_way_draw(directory, compiler, renderer, backend): run_pixel_batch(renderer, backend, shader, cases) # Desktop min and max alone skip a NaN operand instead of taking V_MIN3_F32 of the rest. text = source.read_text(encoding="ascii") - nan_ignored = text.replace("? min(min(a, b), c) :", "? max(min(a, b), min(max(a, b), c)) :") + nan_ignored = text.replace("return top > 0x7f800000u", "return false") assert nan_ignored != text source.write_text(nan_ignored, encoding="ascii") compile_shader(compiler, source, shader) diff --git a/tests/shader_signed_zero_minmax_check.py b/tests/shader_signed_zero_minmax_check.py new file mode 100644 index 000000000..035bc91fd --- /dev/null +++ b/tests/shader_signed_zero_minmax_check.py @@ -0,0 +1,276 @@ +"""Source-built gfx1013 min/max translation and pixel checks. + +No arguments checks the emitted HLSL. Binary mode verifies the encodings with +llvm-mc. The before, draw, plain and invert modes take DXC, offscreen_check, +the adapter name and optionally FXC. +""" + +import math +import re +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +from startup_gfx2hlsl_bit_alu_check import G, POST_SOURCE, POST_WORDS, PRE_SOURCE, PRE_WORDS, vs_source, vs_words +from startup_flat_param_check import assemble, compile_hlsl, draw, root_blob + +import pixel_aot + +NEG_ZERO, POS_ZERO = 0x80000000, 0 +NEG_ONE, TWO, NAN = 0xbf800000, 0x40000000, 0x7fc01234 +CASE_TEXELS = 8 * 8 +DRAW_TEXELS = 64 * 64 +OPS = { + "min": ("v_min_f32_e32", 2), "max": ("v_max_f32_e32", 2), + "min-e64": ("v_min_f32_e64", 2), "max-e64": ("v_max_f32_e64", 2), + "min3": ("v_min3_f32", 3), "max3": ("v_max3_f32", 3), "med3": ("v_med3_f32", 3), + "min-sdwa": ("v_min_f32_sdwa", 2), "max-sdwa": ("v_max_f32_sdwa", 2), + "min-dpp": ("v_min_f32_dpp", 2), "max-dpp": ("v_max_f32_dpp", 2), + "min-pack": ("v_pk_min_f16", 2), "max-pack": ("v_pk_max_f16", 2), +} +STARTUP_OPS = ("min", "max", "min-e64", "max-e64", "min3", "max3", "med3") +BODY_WORDS = { + "min": "0009181e010b1a1e020d1c1e030f1e1e", + "max": "00091820010b1a20020d1c20030f1e20", + "min-e64": "0c000fd5000902000d000fd5010b02000e000fd5020d02000f000fd5030f0200", + "max-e64": "0c0010d5000902000d0010d5010b02000e0010d5020d02000f0010d5030f0200", + "min3": "0c0051d5000922040d0051d5010b26040e0051d5020d2a040f0051d5030f2e04", + "max3": "0c0054d5000922040d0054d5010b26040e0054d5020d2a040f0054d5030f2e04", + "med3": "0c0057d5000922040d0057d5010b26040e0057d5020d2a040f0057d5030f2e04", + "min-sdwa": "f908181e00060606f90a1a1e01060606f90c1c1e02060606f90e1e1e03060606", + "max-sdwa": "f908182000060606f90a1a2001060606f90c1c2002060606f90e1e2003060606", + "min-dpp": "fa08181e00e400fffa0a1a1e01e400fffa0c1c1e02e400fffa0e1e1e03e400ff", + "max-dpp": "fa08182000e400fffa0a1a2001e400fffa0c1c2002e400fffa0e1e2003e400ff", + "min-pack": "0c4011cc000902180d4011cc010b02180e4011cc020d02180f4011cc030f0218", + "max-pack": "0c4012cc000902180d4012cc010b02180e4012cc020d02180f4012cc030f0218", +} + +PIXEL_PREFIX = """s_mov_b32 s21, 0 +s_load_dwordx4 s[44:47], s[20:21], 0x40 +s_waitcnt lgkmcnt(0) +s_buffer_load_dwordx4 s[48:51], s[44:47], 0xc +s_buffer_load_dwordx4 s[52:55], s[44:47], 0x1c +s_buffer_load_dwordx4 s[56:59], s[44:47], 0x2c +s_waitcnt lgkmcnt(0) +""" + "".join(f"v_mov_b32_e32 v{i}, s{48 + i}\n" for i in range(12)) +PIXEL_PREFIX_WORDS = ( + "800395be0a0b08f4400000fa7fc08cbf160c28f40c0000fa160d28f41c0000fa" + "160e28f42c0000fa7fc08cbf3002007e3102027e3202047e3302067e3402087e" + "35020a7e36020c7e37020e7e3802107e3902127e3a02147e3b02167e" +) + + +def body_source(op): + mnemonic, arity = OPS[op] + mods = "" + if op.endswith("-sdwa"): + mods = " dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:DWORD src1_sel:DWORD" + if op.endswith("-dpp"): + mods = " quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf" + return "".join(f"{mnemonic} v{12 + lane}, " + + ", ".join(f"v{lane + 4 * arg}" for arg in range(arity)) + mods + "\n" + for lane in range(4)) + + +def draw_cases(op): + nz, pz = NEG_ZERO, POS_ZERO + if op.endswith("-pack"): + # Each word has distinct low and high halves. The first two lanes swap the packed operands. + return (((0x00008000, 0x80000000, 0), (0x80000000, 0x00008000, 0), + (0x80000000, 0x80000000, 0), (0x00008000, 0x00008000, 0)), + ((0x7e003c00, 0x4000fe00, 0), (0x4000fe00, 0x7e003c00, 0), + (0x3c00bc00, 0x40004000, 0), (0x40004000, 0x3c00bc00, 0))) + if OPS[op][1] == 2: + return (((nz, pz, 0), (pz, nz, 0), (nz, nz, 0), (pz, pz, 0)), + ((NAN, NEG_ONE, 0), (NEG_ONE, NAN, 0), (NAN, TWO, 0), (NEG_ONE, TWO, 0))) + return (((nz, pz, NEG_ONE), (pz, nz, NEG_ONE), (nz, pz, TWO), (pz, nz, TWO)), + ((nz, nz, pz), (pz, pz, nz), (nz, pz, pz), (pz, nz, nz)), + ((NAN, NEG_ONE, TWO), (NEG_ONE, NAN, TWO), (NEG_ONE, TWO, NAN), (NEG_ONE, pz, TWO))) + + +def value(bits, size): + return struct.unpack("> shift) & 0xffff for word in words[:2]] + return reference_word(op, selected, 16, kind) + return lane(0) | (lane(16) << 16) + return reference_word(op, words[:OPS[op][1]], 32, kind) + + +def reference_word(op, words, size, kind): + numeric = [word for word in words if not math.isnan(value(word, size))] + ordered_words = sorted(numeric, key=lambda word: ordered(word, size)) + if op.startswith("min"): + return ordered_words[0] + if op.startswith("max"): + return ordered_words[-1] + # A NaN source makes V_MED3_F32 return V_MIN3_F32 of the three: the smallest number (#2095). + if len(numeric) < len(words): + return ordered_words[0] + return ordered_words[1] + + +def pixel_hlsl(op): + code = bytes.fromhex(PIXEL_PREFIX_WORDS + BODY_WORDS[op]) + POST_WORDS + asm = [line for _, _, _, line in G.decode(code)] + return pixel_aot.lower(asm, 20, 24, None, constant_descriptor=64, integer_export=True) + + +def startup_pipeline(op, rows): + ps = PRE_WORDS + bytes.fromhex(BODY_WORDS[op]) + POST_WORDS + return G.Pipeline(vs_words(rows), ps, root_blob()) + + +def check_binary(llvm_mc): + assert assemble(llvm_mc, PIXEL_PREFIX).hex() == PIXEL_PREFIX_WORDS, "pixel constant-load prologue" + for op in OPS: + assert assemble(llvm_mc, body_source(op)).hex() == BODY_WORDS[op], op + if op in STARTUP_OPS: + for rows in draw_cases(op): + assert assemble(llvm_mc, vs_source(rows)) == vs_words(rows), op + assert assemble(llvm_mc, PRE_SOURCE + body_source(op) + POST_SOURCE) == ( + PRE_WORDS + bytes.fromhex(BODY_WORDS[op]) + POST_WORDS), op + print("All signed-zero fixtures match llvm-mc") + + +def check_lowering(kind, op, source): + assert "uint a_bits = asuint(a), b_bits = asuint(b);" in source + assert "uint either = a_bits | b_bits;" in source + assert "uint zero = maximum ? (a_bits & b_bits) : either;" in source + assert "return asfloat((either & 0x7fffffffu) == 0u ? zero :" in source + body = source[source.index(" main("):] + polarity = "true" if op.startswith("max") else "false" + if op.endswith("-pack"): + assert "isnan(a) ? b : (isnan(b) ? a : minmax_zero32(a, b, maximum))" in source + assert body.count("minmax16_num(") == body.count(", " + polarity + ")") == 8, (op, body) + elif op == "med3": + name = "med3_32" + assert body.count(name + "(") == 4, (kind, body) + start = source.index("float " + name + "(") + helper = source[start:source.index("\n}", start)] + assert helper.count("minmax_zero32(") == 6, helper + else: + count = 8 if OPS[op][1] == 3 else 4 + assert body.count("minmax_zero32(") == body.count(", " + polarity + ")") == count, (op, body) + + +def mutate(source, mode): + start = source.index("float minmax_zero32(") + end = source.index("\n}", start) + helper = source[start:end] + if mode == "plain": + replacement = helper.splitlines()[0] + "\n return maximum ? max(a, b) : min(a, b);" + else: + replacement = helper.replace("maximum ? (a_bits & b_bits) : either", + "maximum ? either : (a_bits & b_bits)") + assert replacement != helper + return source[:start] + replacement + source[end:] + + +def check_translation(): + for kind, ops in (("pixel", OPS), ("startup", STARTUP_OPS)): + for op in ops: + source = pixel_hlsl(op) if kind == "pixel" else startup_pipeline(op, draw_cases(op)[0]).hlsl_ps() + check_lowering(kind, op, source) + for mode in ("plain", "invert"): + try: + check_lowering(kind, op, mutate(source, mode)) + except AssertionError: + continue + raise AssertionError(f"{kind} {op} accepted the {mode} control") + print("20 signed-zero lowering checks reject both helper mutations") + + +def pixel_readback(renderer, backend, directory, shader, rows, expect): + # Existing integer-target case format, with three runtime uint4 operands from b0. + constants = [0] * 64 + for arg in range(3): + constants[3 + 4 * arg:7 + 4 * arg] = [row[arg] for row in rows] + case, raw = (directory / name for name in ("minmax.case", "minmax.bin")) + case.write_bytes(struct.pack("<64I", *constants) + struct.pack("<4I", *expect) * CASE_TEXELS + b"\x01") + raw.unlink(missing_ok=True) + run = subprocess.run([renderer, backend, "--check-pixel-case", str(shader), str(case), str(raw)], + capture_output=True, text=True) + return run, tuple(struct.iter_unpack("<4I", raw.read_bytes())) if raw.exists() else () + + +def startup_readback(renderer, backend, vs, ps, expect): + run = draw(renderer, backend, vs, ps, ",".join(f"{word:08x}" for word in expect)) + match = re.search(r"startup_flat_param words=([0-9a-f,]+)", run.stdout) + return run, (tuple(int(word, 16) for word in match[1].split(",")),) if match else () + + +def check_draw(mode, dxc, renderer, backend, fxc=None): + renderer = str(Path(renderer).resolve()) + sites = [("pixel", dxc, "dxc", "ps_6_2"), ("startup", dxc, "dxc", "ps_6_0")] + if fxc: + sites.append(("startup", fxc, "fxc", "ps_5_1")) + out = Path(__file__).resolve().parents[1] / "out" + out.mkdir(exist_ok=True) + mismatches = total = 0 + with tempfile.TemporaryDirectory(dir=out) as tmp: + directory = Path(tmp) + for kind, compiler, tool, profile in sites: + for op in OPS if kind == "pixel" else STARTUP_OPS: + cases = draw_cases(op) + source = pixel_hlsl(op) if kind == "pixel" else startup_pipeline(op, cases[0]).hlsl_ps() + if mode in ("plain", "invert"): + source = mutate(source, mode) + if kind == "pixel": + hlsl, shader = (directory / name for name in ("pixel.hlsl", "pixel.cso")) + hlsl.write_text(source, encoding="ascii") + subprocess.run([dxc, "-Gis", "-T", profile, "-E", "main", "-Fo", str(shader), str(hlsl)], + check=True) + else: + shader = compile_hlsl(compiler, tool, source, "pixel", profile, directory) + for index, rows in enumerate(cases): + expected = tuple(reference(op, row, kind) for row in rows) + if kind == "pixel": + run, raw = pixel_readback(renderer, backend, directory, shader, rows, expected) + else: + pipeline = startup_pipeline(op, rows) + vs = compile_hlsl(compiler, tool, pipeline.hlsl_vs(), "vertex", profile.replace("ps", "vs"), directory) + run, raw = startup_readback(renderer, backend, vs, shader, expected) + if run.returncode == 77: + print(run.stdout + run.stderr) + return 77 + pixel_count = DRAW_TEXELS if kind == "pixel" else 1 + if len(raw) != pixel_count: + raise AssertionError(f"{kind} {op}: expected {pixel_count} readback pixels, got {len(raw)}\n" + f"{run.stdout}\n{run.stderr}") + if (any(row != raw[0] for row in raw) or run.returncode not in (0, 1) + or ("debug_layer=enabled" in run.stdout and "debug_errors=0 debug_warnings=0" not in run.stdout)): + raise AssertionError(f"{kind} {op}: {run.stdout}\n{run.stderr}") + got = ",".join(f"{word:08x}" for word in raw[0]) + want = ",".join(f"{word:08x}" for word in expected) + print(f"{backend} {kind} {profile} {op} row {index}: {got} (expected {want})") + if bool(run.returncode) != (raw[0] != expected): + raise AssertionError(f"{kind} {op}: {run.stdout}\n{run.stderr}") + mismatches += sum(got != want for got, want in zip(raw[0], expected)) + total += len(expected) + print(f"{backend} {mode}: {mismatches}/{total} result words differ") + if mode == "invert" and not mismatches: + raise AssertionError("The inverted sign rule escaped detection") + return int(mode != "before" and mismatches != 0) + + +if __name__ == "__main__": + if len(sys.argv) == 3 and sys.argv[1] == "binary": + check_binary(sys.argv[2]) + elif len(sys.argv) in (5, 6) and sys.argv[1] in ("before", "draw", "plain", "invert"): + sys.exit(check_draw(*sys.argv[1:])) + elif len(sys.argv) == 1: + check_translation() + else: + sys.exit(__doc__) diff --git a/tests/startup_compute_request_offline_check.py b/tests/startup_compute_request_offline_check.py index f57f4b28c..f2f0299a8 100644 --- a/tests/startup_compute_request_offline_check.py +++ b/tests/startup_compute_request_offline_check.py @@ -25,12 +25,12 @@ DESC = struct.pack('<12Q', 0, 0, 24, 0, 20, 0, len(CODE), 0, len(DATA), 0, 0, 11) STATE_A = struct.pack('<3Q', 1, 0x2c, 0xfff0000000000003) STATE_B = struct.pack('<5I', 0x1234abcd, 0xffff0000, 0, 0, 0) -KEY = 0x8421b8080fd0a5e6 # framed key at revision 17cs +KEY = 0x375fa7c3f8f4a3dd # framed key at revision 18cs def framed_key(): h = 1469598103934665603 - for b in b'x2w-startup-shader-17cs': + for b in b'x2w-startup-shader-18cs': h = ((h ^ b) * 1099511628211) & 0xffffffffffffffff for part in (CODE, DATA, ROOT, DESC, STATE_A, STATE_B): for b in struct.pack('` of `0x7f800000u` and - `min(min(a, b), c)` for the NaN branch; no line calls a `med3(` helper; + the signed-zero `minmax_zero32` min3 chain for the NaN branch; no line calls a `med3(` helper; - the binary32 table points `v_med3_f32` at `med3_32` and the integer forms are unchanged; - every lane of the fixture lowers to `U(med3_32(F(v1), F(v2), F(v3)))` reading s44..s47, which the entry constant buffer fills at draw time; @@ -87,7 +87,9 @@ MED3_32 = ('float med3_32(float a, float b, float c) {\n' ' uint top = max(max(asuint(a) & 0x7fffffffu, asuint(b) & 0x7fffffffu), asuint(c) & 0x7fffffffu);\n' - ' return top > 0x7f800000u ? min(min(a, b), c) : max(min(a, b), min(max(a, b), c));\n' + ' return top > 0x7f800000u\n' + ' ? minmax_zero32(minmax_zero32(a, b, false), c, false)\n' + ' : minmax_zero32(minmax_zero32(a, b, false), minmax_zero32(minmax_zero32(a, b, true), c, false), true);\n' '}') BRANCHLESS = 'float med3_32(float a, float b, float c) {\n return max(min(a, b), min(max(a, b), c));\n}' OLD_ISNAN = ('float med3_32(float a, float b, float c) {\n' diff --git a/tests/startup_gfx2hlsl_float_alu_check.py b/tests/startup_gfx2hlsl_float_alu_check.py index ae6131850..e3bff9bca 100644 --- a/tests/startup_gfx2hlsl_float_alu_check.py +++ b/tests/startup_gfx2hlsl_float_alu_check.py @@ -87,8 +87,10 @@ def sets(*rows): 'v_subrev_f32': (r'U\(%s - %s\)' % (F, F), r'U(F(\2) - F(\1))', op2(lambda a, b: a - b)), 'v_mul_f32': (r'U\(%s \* %s\)' % (F, F), r'U(F(\1) + F(\2))', op2(lambda a, b: a + b)), 'v_mul_legacy_f32': (r'U\(mul_legacy\(', r'U(2.0 * mul_legacy(', op2(lambda a, b: 2.0 * legacy(a, b))), - 'v_min_f32': (r'U\(min\(', r'U(max(', op2(max)), - 'v_max_f32': (r'U\(max\(', r'U(min(', op2(min)), + 'v_min_f32': (r'U\(minmax_zero32\(%s, %s, false\)\)' % (F, F), r'U(minmax_zero32(F(\1), F(\2), true))', + op2(max)), + 'v_max_f32': (r'U\(minmax_zero32\(%s, %s, true\)\)' % (F, F), r'U(minmax_zero32(F(\1), F(\2), false))', + op2(min)), 'v_fma_f32': (r' \+ (F\(v\d+\))\)', r' - \1)', op3(lambda a, b, c: a * b - c)), 'v_mad_f32': (r'mad32\(%s, %s, (F\(v\d+\)), false\)' % (F, F), r'mad32(F(\1), F(\2), -\3, false)', op3(lambda a, b, c: a * b - c)), @@ -96,8 +98,10 @@ def sets(*rows): op3(lambda a, b, c: 2.0 * legacy(a, b) + c)), 'v_med3_f32': (r'med3_32\(%s, %s, %s\)' % (F, F, F), r'max(F(\1), max(F(\2), F(\3)))', op3(lambda a, b, c: max(a, b, c))), - 'v_min3_f32': (r'U\(min\(%s, min\(' % F, r'U(max(F(\1), min(', op3(lambda a, b, c: max(a, min(b, c)))), - 'v_max3_f32': (r'U\(max\(%s, max\(' % F, r'U(min(F(\1), max(', op3(lambda a, b, c: min(a, max(b, c)))), + 'v_min3_f32': (r'U\(minmax_zero32\(%s, (minmax_zero32\(F\(v\d+\), F\(v\d+\), false\)), false\)\)' % F, + r'U(minmax_zero32(F(\1), \2, true))', op3(lambda a, b, c: max(a, min(b, c)))), + 'v_max3_f32': (r'U\(minmax_zero32\(%s, (minmax_zero32\(F\(v\d+\), F\(v\d+\), true\)), true\)\)' % F, + r'U(minmax_zero32(F(\1), \2, false))', op3(lambda a, b, c: min(a, max(b, c)))), } BODY = { 'v_add_f32': words('000918060d0003d5010b0200020d1c060f0003d5030f0200'), diff --git a/tests/startup_gfx2hlsl_fract_check.py b/tests/startup_gfx2hlsl_fract_check.py index de05a5e1f..9c568f6b1 100644 --- a/tests/startup_gfx2hlsl_fract_check.py +++ b/tests/startup_gfx2hlsl_fract_check.py @@ -170,8 +170,8 @@ def float_capped(word): repr((seed and seed.group(1), literal and literal.group(1)))) check('the two literals are identical', seed and literal and seed.group(1) == literal.group(1), repr((seed and seed.group(1), literal and literal.group(1)))) -check('the revision is x2w-startup-shader-17, after the fix to the cap', - bool(seed and seed.group(1) == 'x2w-startup-shader-17'), repr(seed and seed.group(1))) +check('the revision is x2w-startup-shader-18, after the fix to the cap and the signed-zero min and max', + bool(seed and seed.group(1) == 'x2w-startup-shader-18'), repr(seed and seed.group(1))) def key_from_seed(word): @@ -183,7 +183,7 @@ def key_from_seed(word): check('pipeline_key hashes the seed the source spells', G.pipeline_key(b'vs', b'ps', b'root') == key_from_seed(seed.group(1)), '%016x vs %016x' % (G.pipeline_key(b'vs', b'ps', b'root'), key_from_seed(seed.group(1)))) - old, new = key_from_seed('x2w-startup-shader-16'), key_from_seed('x2w-startup-shader-17') + old, new = key_from_seed('x2w-startup-shader-16'), key_from_seed(seed.group(1)) check('the -16 seed produces a different key, so the pre-fix entries are out of the cache', old != new, '%016x vs %016x' % (old, new)) diff --git a/tests/startup_gfx2hlsl_root_check.py b/tests/startup_gfx2hlsl_root_check.py index 31413e53d..a32c5dbb1 100644 --- a/tests/startup_gfx2hlsl_root_check.py +++ b/tests/startup_gfx2hlsl_root_check.py @@ -51,7 +51,13 @@ def container(parts): def main(): table = gfx2hlsl.parse_root(TABLE_ROOT)["params"] assert table == [dict(type=1, vis=0, reg=5, space=2, count=3)], table - vs, ps = code(12), code(0) + # --pending visits requests in key order, and every key hashes the cache revision. Pick the pixel + # export target (mrt0..mrt7) so that the valid request sorts after a bad one at the current revision. + vs = code(12) + for target in range(8): + ps = code(target) + if gfx2hlsl.pipeline_key(vs, ps, VALID_ROOT) > min(gfx2hlsl.pipeline_key(vs, ps, root) for root, _ in BAD.values()): + break with tempfile.TemporaryDirectory() as tmp: directory = Path(tmp) requests = {name: root for name, (root, _) in BAD.items()} diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index cece4f068..144e13cab 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -295,7 +295,7 @@ ComPtr translated_pipeline(ID3D12Device* guest, ID3D12RootSignature* r bool needs_start, bool table_buffer = false, bool indexed = false, bool rect = false) { // The opaque guest programs identify synthetic cache entries. The actual bound shaders are source-built DXBC. - constexpr char revision[] = "x2w-startup-shader-17"; + constexpr char revision[] = "x2w-startup-shader-18"; static std::uint32_t vertex_ids[]{0xe0000101, 0xe0000102, 0xe0000103}; static std::uint32_t pixel_ids[]{0xe0000202, 0xe0000203, 0xe0000204}; auto& vertex_id = vertex_ids[indexed ? 2 : needs_start]; diff --git a/tests/startup_packed_position_provenance_check.py b/tests/startup_packed_position_provenance_check.py index 5182ac18c..bd848f3db 100644 --- a/tests/startup_packed_position_provenance_check.py +++ b/tests/startup_packed_position_provenance_check.py @@ -206,7 +206,7 @@ def refused(label, cache, key, reason): cache = Path(tmp) bare = G.pipeline_key(VS_WORDS, ps_words(4), root_blob()) check('without a description the key is unchanged', - bare == G.fnv(root_blob(), G.fnv(ps_words(4), G.fnv(VS_WORDS, G.fnv(b'x2w-startup-shader-17'))))) + bare == G.fnv(root_blob(), G.fnv(ps_words(4), G.fnv(VS_WORDS, G.fnv(b'x2w-startup-shader-18'))))) keys = [put_request(cache, ps_words(4), masks) for masks in (TARGET, SAME_V4, DECOY)] check('same stages, root and layout with three mask pairs: three request identities', len(set(keys)) == 3 and bare not in keys diff --git a/tests/startup_resource_retire_title.cpp b/tests/startup_resource_retire_title.cpp index fa6fbaf4c..05f8f0a38 100644 --- a/tests/startup_resource_retire_title.cpp +++ b/tests/startup_resource_retire_title.cpp @@ -371,7 +371,7 @@ constexpr UINT draw_side = 4; // 4x4 R8G8B8A8_UNORM target constexpr UINT draw_covered = 3; // scissor leaves the last row and column untouched as the sentinel constexpr int draw_seed = 77; constexpr UINT draw_clear_pixel = 0xffff00ffu; // ClearRenderTargetView({1, 0, 1, 1}) in R8G8B8A8_UNORM -constexpr char draw_revision[] = "x2w-startup-shader-17"; // d3d12_draw.inl cached_translation +constexpr char draw_revision[] = "x2w-startup-shader-18"; // d3d12_draw.inl cached_translation constexpr char draw_vertex_shader[] = R"( struct Varying { float4 position : SV_Position; }; diff --git a/tests/startup_shader_cache_key_check.py b/tests/startup_shader_cache_key_check.py index 7a7d7218a..8de395820 100644 --- a/tests/startup_shader_cache_key_check.py +++ b/tests/startup_shader_cache_key_check.py @@ -49,10 +49,10 @@ def check_request(blobs, key, diagnostic=None, rtv_request=None, layout=None): def main(): # Independently executed C++ runtime fnv_bytes/cached_translation known-answer vector. - # Revision x2w-startup-shader-17 excludes NUL. Stored order is a, b, root, then optional input layout. + # Revision x2w-startup-shader-18 excludes NUL. Stored order is a, b, root, then optional input layout. vector = (b"\x00VS\xff", b"PS\x00\x80", b"RTS0\x00") - assert gfx2hlsl.pipeline_key(*vector) == 0xd9521cd3fde79d61 - assert gfx2hlsl.pipeline_key(*vector, b"ia\x00\xfe") == 0xbaa2837ef61006ad + assert gfx2hlsl.pipeline_key(*vector) == 0x8d1cb58fb148b30a + assert gfx2hlsl.pipeline_key(*vector, b"ia\x00\xfe") == 0xf9e74efdcb8283d2 blobs = (VERTEX, PIXEL, ROOT) canonical = gfx2hlsl.pipeline_key(*blobs) check_request(blobs, canonical) diff --git a/tools/pixel_aot.py b/tools/pixel_aot.py index a064c669a..d79f40377 100644 --- a/tools/pixel_aot.py +++ b/tools/pixel_aot.py @@ -13,6 +13,7 @@ import zlib from resource_inventory import parts +from shader_minmax import FLOAT_MINMAX MESH_WAVE64 = b"+wavefrontsize64,-wavefrontsize32" @@ -454,7 +455,9 @@ def comparison_resources(state): // The NaN test is on the encoding, because some desktop compilers fold float NaN tests. float med3_32(float a, float b, float c) { uint top = max(max(asuint(a) & 0x7fffffffu, asuint(b) & 0x7fffffffu), asuint(c) & 0x7fffffffu); - return top > 0x7f800000u ? min(min(a, b), c) : max(min(a, b), min(max(a, b), c)); + return top > 0x7f800000u + ? minmax_zero32(minmax_zero32(a, b, false), c, false) + : minmax_zero32(minmax_zero32(a, b, false), minmax_zero32(minmax_zero32(a, b, true), c, false), true); } // v_fract_f32: x - floor(x) clamped to 0x3f7fffff, so a tiny negative input cannot round up to 1.0. // D3D frac has no clamp and differs between adapters. NaN fails the comparison and propagates. @@ -763,7 +766,7 @@ def vgpr_span(token, count): "rndne": (1, "round({0})"), # HLSL round is DXIL Round_ne: ties to even "sin": (1, "sin32({0})"), "cos": (1, "cos32({0})"), "add": (2, "({0} + {1})"), "mul": (2, "({0} * {1})"), - "max": (2, "max({0}, {1})"), "min": (2, "min({0}, {1})"), "sub": (2, "({0} - {1})"), + "max": (2, "minmax_zero32({0}, {1}, true)"), "min": (2, "minmax_zero32({0}, {1}, false)"), "sub": (2, "({0} - {1})"), "subrev": (2, "({1} - {0})"), "mul_legacy": (2, "(({0} == 0 || {1} == 0) ? 0.0f : {0} * {1})"), # Legacy multiply, then an unfused add: 0 * x is 0 even for an infinite or NaN x. @@ -773,7 +776,8 @@ def vgpr_span(token, count): "fma": (3, "mad({0}, {1}, {2})"), "fmac": (3, "mad({0}, {1}, {2})"), "mad": (3, "mad32({0}, {1}, {2})"), "mac": (3, "mad32({0}, {1}, {2})"), # Each result is one of the operands, so finite inputs need no rounding. - "min3": (3, "min(min({0}, {1}), {2})"), "max3": (3, "max(max({0}, {1}), {2})"), + "min3": (3, "minmax_zero32(minmax_zero32({0}, {1}, false), {2}, false)"), + "max3": (3, "minmax_zero32(minmax_zero32({0}, {1}, true), {2}, true)"), "med3": (3, "med3_32({0}, {1}, {2})"), } # LLVM 15 sets HasExtDPP = 0 for v_mac_legacy_f32, and fma, mad, mad_legacy, min3, max3 and med3 are VOP3-only, so @@ -1246,14 +1250,9 @@ def check_vopc_e32_dst(enc, dst): " return (res_sign << 15u) | sig;\n" "}" ), - "min16_num": ( - "float min16_num(float a, float b) {\n" - " return isnan(a) ? b : (isnan(b) ? a : min(a, b));\n" - "}" - ), - "max16_num": ( - "float max16_num(float a, float b) {\n" - " return isnan(a) ? b : (isnan(b) ? a : max(a, b));\n" + "minmax16_num": ( + "float minmax16_num(float a, float b, bool maximum) {\n" + " return isnan(a) ? b : (isnan(b) ? a : minmax_zero32(a, b, maximum));\n" "}" ), "dot_u64_add": ( @@ -1476,8 +1475,8 @@ def check_vopc_e32_dst(enc, dst): VOP3P_F16 = { "add": (2, "({0} + {1})"), "mul": (2, "({0} * {1})"), - "min": (2, "min16_num({0}, {1})"), - "max": (2, "max16_num({0}, {1})"), + "min": (2, "minmax16_num({0}, {1}, false)"), + "max": (2, "minmax16_num({0}, {1}, true)"), "fma": (3, "mad({0}, {1}, {2})"), } INLINE_F16 = { @@ -7274,7 +7273,7 @@ def known_sample_float(reg): packed_lanes.append(f"pack16_rne({lvar})") helpers.add("pack16_rne") if op in ("min", "max"): - helpers.add(f"{op}16_num") + helpers.add("minmax16_num") vector[dst] = f"alu{i}" lines.append(f" precise float alu{i} = asfloat({packed_lanes[0]} | ({packed_lanes[1]} << 16));") elif m := match(r"v_cvt_u32_f32_e32 (v\d+), ([vs]\d+|0x[0-9a-f]{1,8})"): @@ -7947,7 +7946,7 @@ def known_sample_float(reg): memory = TITLE_MEMORY + (TITLE_MEMORY_X2 if title_loads_x2 else "") memory += TITLE_MEMORY_X4 if title_loads_x4 else "" lines[:0] = [lookup, memory.format(slots=TITLE_ALIAS_SLOTS, count=title_ranges, miss=TITLE_MISS)] - source = "\n".join([*lines, "}", ""]) + source = "\n".join([FLOAT_MINMAX, *lines, "}", ""]) return (source, channel_mask) if return_write_mask else source diff --git a/tools/shader_minmax.py b/tools/shader_minmax.py new file mode 100644 index 000000000..96880b7df --- /dev/null +++ b/tools/shader_minmax.py @@ -0,0 +1,18 @@ +"""HLSL shared by the gfx1013 pixel and startup translators.""" + +# RDNA 2 ISA section 12.7 settles both operand orders for signed zeros: +# V_MIN_F32: S0 = +0, S1 = -0 -> S1; S0 = -0, S1 = +0 -> S0 (min returns -0 if either operand is -0) +# V_MAX_F32: S0 = +0, S1 = -0 -> S0; S0 = -0, S1 = +0 -> S1 (max returns +0 when the zeros differ) +# Equal zeros take the general branch, so max(-0, -0) stays -0. For two zeros, the OR of the bit +# patterns gives the min result and the AND gives the max result, in either order. V_MIN3_F32, +# V_MAX3_F32 and V_MED3_F32 are defined through nested V_MIN_F32/V_MAX_F32, so chaining this helper +# applies the same rule. The emitted HLSL below is unchanged by this note. +FLOAT_MINMAX = """// RDNA 2 ISA section 12.7 orders -0 below +0 for min and max. +float minmax_zero32(float a, float b, bool maximum) { + uint a_bits = asuint(a), b_bits = asuint(b); + uint either = a_bits | b_bits; + uint zero = maximum ? (a_bits & b_bits) : either; + // Keep the selection integer so the compiler cannot merge the two float zeros. + return asfloat((either & 0x7fffffffu) == 0u ? zero : asuint(maximum ? max(a, b) : min(a, b))); +} +""" diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index ab5eed675..c9b363eda 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -19,6 +19,7 @@ sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')) import disasm_rdna2 as D # noqa: E402 +from shader_minmax import FLOAT_MINMAX # noqa: E402 class Unsupported(Exception): @@ -7773,7 +7774,7 @@ def declarations(self): VEC_F = { 'v_add_f32': (2, '{0} + {1}'), 'v_sub_f32': (2, '{0} - {1}'), 'v_subrev_f32': (2, '{1} - {0}'), 'v_mul_f32': (2, '{0} * {1}'), 'v_mul_legacy_f32': (2, 'mul_legacy({0}, {1})'), - 'v_min_f32': (2, 'min({0}, {1})'), 'v_max_f32': (2, 'max({0}, {1})'), + 'v_min_f32': (2, 'minmax_zero32({0}, {1}, false)'), 'v_max_f32': (2, 'minmax_zero32({0}, {1}, true)'), 'v_fmac_f32': (2, '{0} * {1} + {2}'), 'v_mac_f32': (2, 'mad32({0}, {1}, {2}, false)'), 'v_fma_f32': (3, '{0} * {1} + {2}'), 'v_mad_f32': (3, 'mad32({0}, {1}, {2}, false)'), 'v_mad_legacy_f32': (3, 'mad32({0}, {1}, {2}, true)'), @@ -7783,7 +7784,9 @@ def declarations(self): 'v_exp_f32': (1, 'exp2({0})'), 'v_log_f32': (1, 'log2({0})'), 'v_floor_f32': (1, 'floor({0})'), 'v_ceil_f32': (1, 'ceil({0})'), 'v_trunc_f32': (1, 'trunc({0})'), 'v_fract_f32': (1, 'fract32({0})'), 'v_rndne_f32': (1, 'round({0})'), 'v_sin_f32': (1, 'sin({0} * 6.283185307)'), 'v_cos_f32': (1, 'cos({0} * 6.283185307)'), - 'v_med3_f32': (3, 'med3_32({0}, {1}, {2})'), 'v_min3_f32': (3, 'min({0}, min({1}, {2}))'), 'v_max3_f32': (3, 'max({0}, max({1}, {2}))'), + 'v_med3_f32': (3, 'med3_32({0}, {1}, {2})'), + 'v_min3_f32': (3, 'minmax_zero32({0}, minmax_zero32({1}, {2}, false), false)'), + 'v_max3_f32': (3, 'minmax_zero32({0}, minmax_zero32({1}, {2}, true), true)'), } # 16-bit VALU: (sources, source kind, float or uint expression of the sources, result kind). 'h' sources are # binary16 read from the low half and computed in binary32; an 'h' result is rounded back to binary16. The @@ -8238,7 +8241,7 @@ def sampler_lines(self): def common(self): import pixel_aot - out = ['#define F(x) asfloat(x)', '#define U(x) asuint(x)', + out = ['#define F(x) asfloat(x)', '#define U(x) asuint(x)', FLOAT_MINMAX, 'float mul_legacy(float a, float b) { return (a == 0.0 || b == 0.0) ? 0.0 : a * b; }', # Match pixel_aot: round the product before adding and flush denormals to signed zero. 'float ftz32(float value) {', @@ -8265,11 +8268,14 @@ def common(self): '}', # v_med3_f32 with a NaN source is the minimum of the three (ISA "343 V_MED3_F32"), so the test is # on the encoding: a float isnan() may be folded away by the compiler. D3D min() returns the - # other operand, so min(min(a, b), c) over a NaN source is the smallest of the non-NaN ones. + # other operand, so the min3 chain over a NaN source is the smallest of the non-NaN ones. min, max + # and med3 go through minmax_zero32, which orders -0 below +0 and passes a NaN to D3D min/max. # Same body as med3_32 in tools/pixel_aot.py. 'float med3_32(float a, float b, float c) {', ' uint top = max(max(asuint(a) & 0x7fffffffu, asuint(b) & 0x7fffffffu), asuint(c) & 0x7fffffffu);', - ' return top > 0x7f800000u ? min(min(a, b), c) : max(min(a, b), min(max(a, b), c));', + ' return top > 0x7f800000u', + ' ? minmax_zero32(minmax_zero32(a, b, false), c, false)', + ' : minmax_zero32(minmax_zero32(a, b, false), minmax_zero32(minmax_zero32(a, b, true), c, false), true);', '}', # High half of an unsigned 32x32 product, by halfword products so it fits 32-bit HLSL. 'uint mul_hi_u32(uint a, uint b) { uint la = a & 0xffffu, lb = b & 0xffffu;' @@ -8791,7 +8797,7 @@ def pipeline_key(vs_code, ps_code, root_blob, layout=b'', ps_inputs=None): SPI_PS_INPUT_ENA and SPI_PS_INPUT_ADDR as little-endian u32. Two pipelines with the same stages, root signature and input layout but different masks are then two requests with their own results. Without a description the key is unchanged.""" - key = fnv(root_blob, fnv(ps_code, fnv(vs_code, fnv(b'x2w-startup-shader-17')))) + key = fnv(root_blob, fnv(ps_code, fnv(vs_code, fnv(b'x2w-startup-shader-18')))) key = fnv(layout, key) if layout else key return key if ps_inputs is None else fnv(b'psin1' + struct.pack(' Date: Thu, 26 Nov 2026 04:44:37 +0100 Subject: [PATCH 124/240] pixel_aot: build export16 on the integer binary16 helpers (#2717) export16 narrowed with f32tof16 and widened with f16tof32. NVIDIA's Vulkan compiler folds f16tof32(f32tof16(x)) into x, so the round toward zero correction was lost and draw-core read 3e14a000 instead of 3e148000 at pixel x=16. Use narrow16 (round to nearest even) and widen16, which work on the encoding, and step the half back by one when it exceeds the input in magnitude. export16 moves below narrow16 so HLSL sees the declarations in order. --- docs/experiments.md | 2 +- tools/pixel_aot.py | 14 ++++++++------ 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index dbe49ec77..18e2931e5 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -16335,7 +16335,7 @@ Measured on 2026-11-25 with base `25317c63` plus this change, DXC 1.10.2605.37 a | NVIDIA RTX 3060 Laptop, driver 620.70.06, `shaderDenormPreserveFloat32` = 0 | none | exit 77 | | NVIDIA RTX 3060 Laptop | `--allow-denorm-mismatch` | exit 1, `pixel_mismatch x=16 y=0` | -The NVIDIA mismatch is a measurement: in that pixel, byte 37 reads back `0x3e14a000` where the reference has `0x3e148000`. The reference comes from `export16` in `tools/pixel_aot.py`, which converts with `f32tof16`, steps the half down by one when `f16tof32` of it exceeds the input in magnitude, and widens it again, so the value is rounded toward zero to a binary16. One hypothesis, not tested further, is that the NVIDIA compiler folds `f16tof32(f32tof16(x))` to `x`, so that rounding does not happen. A compute probe on the same device gave the correct binary16 `0x30a5` and a widened value `0x3e149495`, which is consistent with that hypothesis but does not prove it. It is not known whether the NVIDIA D3D12 driver behaves the same way. The run is a diagnostic and says nothing about NVIDIA's subnormal handling. +The NVIDIA mismatch was in pixel x=16, byte 37: `0x3e14a000` where the reference has `0x3e148000`. The reference comes from `export16` in `tools/pixel_aot.py`, which rounds toward zero to a binary16 and widens it again. It used to convert with `f32tof16` and `f16tof32`, and the NVIDIA compiler folded `f16tof32(f32tof16(x))` into `x`, so the rounding did not happen (a compute probe on the same device gave the correct binary16 `0x30a5` and a widened value `0x3e149495`). `export16` is now built on the integer helpers `narrow16` and `widen16`, and the same NVIDIA run with `--allow-denorm-mismatch` exits 0. The NVIDIA D3D12 driver read `0x3e148000` on an RTX 4060 before the change. The diagnostic run says nothing about NVIDIA's subnormal handling. This shows that these shaders produce the same bits on two Vulkan drivers for the covered modes. It does not cover the other `offscreen_check` modes or title-memory cases, and it is not a D3D12 result. diff --git a/tools/pixel_aot.py b/tools/pixel_aot.py index d79f40377..3177dfbc4 100644 --- a/tools/pixel_aot.py +++ b/tools/pixel_aot.py @@ -537,12 +537,6 @@ def comparison_resources(state): float cos32(float value) { return cos(turns(value) * 6.28318548f); } -// Finite binary32 to binary16, round toward zero, then widen for the float target. -float export16(float value) { - uint h = f32tof16(value); - if (abs(f16tof32(h)) > abs(value)) h--; - return f16tof32(h); -} // v_cvt_f32_f16: widen the binary16 in the low half of a word, built from its encoding so that // desktop denormal handling cannot change it. Subnormal halves stay exact as m * 2^-24; NaN payloads widen. float widen16(uint word) { @@ -582,6 +576,14 @@ def comparison_resources(state): uint rounded = (full + 0xfffu + ((full >> 13) & 1u)) >> 13; return sign | min(((exponent - 113u) << 10) + rounded, 0x7c00u); } +// Finite binary32 to binary16, round toward zero, then widen for the float target. Built on the integer +// helpers: a driver may fold f16tof32(f32tof16(x)) into x and lose the correction. The round-to-nearest-even +// result is one step too large exactly when it exceeds the input in magnitude, so step it back toward zero. +float export16(float value) { + uint h = narrow16(value); + if (abs(widen16(h)) > abs(value)) h--; + return widen16(h); +} """ From 62946ccfc393b70e514c57506ebf48914edd8e61 Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Thu, 26 Nov 2026 05:46:19 +0200 Subject: [PATCH 125/240] runtime: harden bink_frame_aot CLI with atomic writes and add CLI suite (#2688) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 3 + tests/bink_frame_aot_cli_check.py | 420 ++++++++++++++++++++++++++++++ tools/bink_frame_aot.py | 47 +++- 3 files changed, 467 insertions(+), 3 deletions(-) create mode 100644 tests/bink_frame_aot_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index eaf0a4b5f..0119840ef 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -11031,6 +11031,9 @@ if(EXISTS "${INTAKE_PYTHON}") set_tests_properties(runtime_bink_heap_aot_cli_check PROPERTIES TIMEOUT 60) add_test(NAME bink_frame_aot_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/bink_frame_aot_check.py") + add_test(NAME runtime_bink_frame_aot_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/bink_frame_aot_cli_check.py") + set_tests_properties(runtime_bink_frame_aot_cli_check PROPERTIES TIMEOUT 60) add_test(NAME cpu_stdio_exe_aot_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu_stdio_exe_aot_check.py") # Documented in the AGENTS platform-independent list but never registered here, so ctest did diff --git a/tests/bink_frame_aot_cli_check.py b/tests/bink_frame_aot_cli_check.py new file mode 100644 index 000000000..f49bbe9a0 --- /dev/null +++ b/tests/bink_frame_aot_cli_check.py @@ -0,0 +1,420 @@ +#!/usr/bin/env python3 +"""Pure-Python CLI, atomic-write, path-guard, and mutation suite for tools/bink_frame_aot.py.""" + +from __future__ import annotations + +from contextlib import redirect_stderr, redirect_stdout +import io +import os +from pathlib import Path +import runpy +import subprocess +import sys +import tempfile +import types +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOLS_DIR = ROOT / "tools" +TOOL = TOOLS_DIR / "bink_frame_aot.py" +sys.path.insert(0, str(TOOLS_DIR)) +import bink_frame_aot # noqa: E402 + + +SYNTHETIC_CPP = ( + '#include \n' + 'using word = uint64_t;\n' + 'extern "C" __declspec(dllexport) uint32_t frame_allocate(word, word, uint32_t) { return 0; }\n' +) + + +def _run_main(module, argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = module.main(argv) + except SystemExit as exc: + code = exc.code + if not isinstance(code, int): + if code is not None: + stderr.write(f"{code}\n") + code = 0 if code is None else 1 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class BinkFrameAotCliPositiveTests(unittest.TestCase): + def test_atomic_cpp_output_in_nested_dirs_and_overwrite_with_zero_tmp(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "synthetic.dll" + image.write_bytes(b"synthetic-image-placeholder") + nested_out = base / "nested" / "sub" / "frame_aot.cpp" + + real_replace = os.replace + replaced_pairs: list[tuple[Path, Path]] = [] + + def tracking_replace(src, dst): + src_p, dst_p = Path(src), Path(dst) + replaced_pairs.append((src_p, dst_p)) + self.assertEqual(src_p.parent.resolve(), dst_p.parent.resolve()) + return real_replace(src, dst) + + with ( + mock.patch.object(bink_frame_aot, "generate", return_value=SYNTHETIC_CPP) as gen, + mock.patch.object(os, "replace", side_effect=tracking_replace), + ): + code, out, err = _run_main(bink_frame_aot, [str(image), str(nested_out)]) + gen.assert_called_once_with(image) + self.assertEqual(code, 0, err) + self.assertEqual(out, "") + self.assertEqual(err, "") + self.assertEqual(nested_out.read_text(encoding="ascii"), SYNTHETIC_CPP) + self.assertEqual([p.name for p in nested_out.parent.iterdir()], ["frame_aot.cpp"]) + self.assertEqual(len(replaced_pairs), 1) + self.assertEqual(replaced_pairs[0][1].resolve(), nested_out.resolve()) + + # Atomic overwrite preserves zero .tmp files. + updated_cpp = SYNTHETIC_CPP + "// updated\n" + with mock.patch.object(bink_frame_aot, "generate", return_value=updated_cpp): + code_ow, out_ow, err_ow = _run_main(bink_frame_aot, [str(image), str(nested_out)]) + self.assertEqual(code_ow, 0, err_ow) + self.assertEqual(out_ow, "") + self.assertEqual(err_ow, "") + self.assertEqual(nested_out.read_text(encoding="ascii"), updated_cpp) + self.assertEqual([p.name for p in nested_out.parent.iterdir()], ["frame_aot.cpp"]) + + # argv=None forwards sys.argv cleanly. + with ( + mock.patch.object(sys, "argv", [str(TOOL), str(image), str(nested_out)]), + mock.patch.object(bink_frame_aot, "generate", return_value=SYNTHETIC_CPP), + ): + code_none, out_none, err_none = _run_main(bink_frame_aot, None) + self.assertEqual(code_none, 0, err_none) + self.assertEqual(out_none, "") + self.assertEqual(err_none, "") + self.assertEqual(nested_out.read_text(encoding="ascii"), SYNTHETIC_CPP) + + # __main__ entrypoint propagates SystemExit(1) cleanly on unmatched image. + stdout_m, stderr_m = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", [str(TOOL), str(image), str(base / "unused.cpp")]), + redirect_stdout(stdout_m), + redirect_stderr(stderr_m), + self.assertRaises(SystemExit) as exited, + ): + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 1) + self.assertEqual(stdout_m.getvalue(), "") + self.assertNotIn("Traceback", stderr_m.getvalue()) + self.assertTrue(stderr_m.getvalue().strip()) + + +class BinkFrameAotCliNegativeTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_code: int | None = 1, + fragments: tuple[str, ...] = (), + check_subprocess: bool = True, + ) -> str: + code, out, err = _run_main(bink_frame_aot, argv) + if expected_code is None: + self.assertNotEqual(code, 0) + else: + self.assertEqual(code, expected_code, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertTrue(err.strip()) + for fragment in fragments: + self.assertIn(fragment.lower(), err.lower()) + + if check_subprocess: + proc = _run_subprocess(*argv) + if expected_code is None: + self.assertNotEqual(proc.returncode, 0) + else: + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + for fragment in fragments: + self.assertIn(fragment.lower(), proc.stderr.lower()) + return err + + def test_missing_dir_corrupt_and_unmatched_hash_image_rejected(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + dir_image = base / "dir_image" + dir_image.mkdir() + absent_out = base / "absent_dir" / "frame_aot.cpp" + + with ( + mock.patch.object( + bink_frame_aot, + "generate", + side_effect=AssertionError("generate called for invalid image path"), + ), + mock.patch.object( + bink_frame_aot, + "_write_atomic", + side_effect=AssertionError("_write_atomic called for invalid image path"), + ), + ): + self._assert_clean_failure( + [str(base / "missing.dll"), str(absent_out)], + expected_code=1, + fragments=("image file not found",), + ) + self._assert_clean_failure( + [str(dir_image), str(absent_out)], + expected_code=1, + fragments=("image path is a directory",), + ) + + # Unmatched SHA-256 hash image fails cleanly without creating output parent. + unmatched = base / "unmatched.dll" + unmatched.write_bytes(b"not-the-pinned-bink-sha256") + self._assert_clean_failure( + [str(unmatched), str(absent_out)], + expected_code=1, + fragments=("version-query profile",), + ) + self.assertFalse(absent_out.parent.exists()) + + # Corrupt PE bytes (with patched SHA-256) fail cleanly without creating output parent. + import hashlib + + digest = hashlib.sha256(b"not a PE32+").hexdigest() + corrupt = base / "corrupt.dll" + corrupt.write_bytes(b"not a PE32+") + with mock.patch.object(bink_frame_aot, "BINK_SHA256", digest): + self._assert_clean_failure( + [str(corrupt), str(absent_out)], + expected_code=1, + check_subprocess=False, + ) + self.assertFalse(absent_out.parent.exists()) + + def test_output_guards_dir_file_parent_samefile_and_non_cpp(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(b"synthetic-image-bytes") + same_cpp = base / "same.cpp" + same_cpp.write_bytes(b"synthetic-cpp-bytes") + hardlink_cpp = base / "hardlink.cpp" + hardlink_cpp.hardlink_to(image) + out_dir = base / "existing_dir.cpp" + out_dir.mkdir() + file_parent = base / "regular_parent.txt" + file_parent.write_text("keep-me", encoding="ascii") + + with ( + mock.patch.object( + bink_frame_aot, + "generate", + side_effect=AssertionError("generate called for invalid output path"), + ), + mock.patch.object( + bink_frame_aot, + "_write_atomic", + side_effect=AssertionError("_write_atomic called for invalid output path"), + ), + ): + for label, argv, code, frags in ( + ("non_cpp_suffix", [str(image), str(base / "out.txt")], 2, ("distinct .cpp output",)), + ("empty_output", [str(image), ""], 2, ("distinct .cpp output",)), + ("same_path", [str(same_cpp), str(same_cpp)], 2, ("distinct .cpp output",)), + ("hardlink_samefile", [str(image), str(hardlink_cpp)], 2, ("distinct .cpp output",)), + ("output_is_dir", [str(image), str(out_dir)], 1, ("directory",)), + ("parent_is_file", [str(image), str(file_parent / "frame_aot.cpp")], 1, ("not a directory",)), + ("ancestor_is_file", [str(image), str(file_parent / "sub" / "frame_aot.cpp")], 1, ("not a directory",)), + ): + with self.subTest(case=label): + self._assert_clean_failure(argv, expected_code=code, fragments=frags) + + self.assertEqual(same_cpp.read_bytes(), b"synthetic-cpp-bytes") + self.assertEqual(image.read_bytes(), b"synthetic-image-bytes") + self.assertEqual(list(out_dir.iterdir()), []) + self.assertEqual(file_parent.read_text(encoding="ascii"), "keep-me") + self.assertFalse((base / "out.txt").exists()) + + def test_output_symlink_rejected_before_generate_and_write(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(b"synthetic-image-bytes") + out_dir = base / "out_dir" + out_dir.mkdir() + real_target = out_dir / "real.cpp" + real_target.write_text("untouched", encoding="ascii") + live_link = out_dir / "live_link.cpp" + dangling_link = out_dir / "dangling_link.cpp" + try: + live_link.symlink_to(real_target) + dangling_link.symlink_to(out_dir / "missing.cpp") + except OSError as exc: + if getattr(exc, "winerror", None) != 1314: + raise + self.skipTest("this Windows account cannot create symlinks (WinError 1314)") + + with ( + mock.patch.object( + bink_frame_aot, + "generate", + side_effect=AssertionError("generate called for symlink output"), + ), + mock.patch.object( + bink_frame_aot, + "_write_atomic", + side_effect=AssertionError("_write_atomic called for symlink output"), + ), + ): + for label, link in (("live_symlink", live_link), ("dangling_symlink", dangling_link)): + with self.subTest(case=label): + self._assert_clean_failure( + [str(image), str(link)], + expected_code=1, + fragments=("symlink",), + ) + + self.assertEqual(real_target.read_text(encoding="ascii"), "untouched") + self.assertEqual( + sorted(p.name for p in out_dir.iterdir()), + ["dangling_link.cpp", "live_link.cpp", "real.cpp"], + ) + + def test_os_replace_failure_preserves_target_bytes_and_leaves_zero_tmp_files(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(b"synthetic-image-bytes") + out_dir = base / "out_dir" + out_dir.mkdir() + out_cpp = out_dir / "frame_aot.cpp" + out_cpp.write_text("original", encoding="ascii") + + with ( + mock.patch.object(bink_frame_aot, "generate", return_value=SYNTHETIC_CPP), + mock.patch.object(os, "replace", side_effect=OSError("simulated replace failure")), + ): + self._assert_clean_failure( + [str(image), str(out_cpp)], + expected_code=1, + fragments=("simulated replace failure",), + check_subprocess=False, + ) + + self.assertEqual(out_cpp.read_text(encoding="ascii"), "original") + self.assertEqual([p.name for p in out_dir.iterdir()], ["frame_aot.cpp"]) + + def test_argparse_errors_py314_safe(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(b"synthetic") + + for argv, frags in ( + ([], ("required",)), + ([str(image)], ("required",)), + ([str(image), str(base / "frame_aot.cpp"), "--bogus-flag"], ("unrecognized",)), + ): + with self.subTest(argv=argv): + self._assert_clean_failure( + argv, + expected_code=None, + fragments=frags, + ) + + def test_fast_temp_mutations(self) -> None: + source = TOOL.read_text(encoding="utf-8") + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(b"synthetic-image-bytes") + dir_image = base / "dir_image" + dir_image.mkdir() + hardlink_cpp = base / "hardlink.cpp" + hardlink_cpp.hardlink_to(image) + file_parent = base / "file_parent.txt" + file_parent.write_text("keep", encoding="ascii") + out_dir = base / "out_dir" + out_dir.mkdir() + out_cpp = out_dir / "frame_aot.cpp" + out_cpp.write_text("original", encoding="ascii") + + # 1) Removing directory image check misses "image path is a directory". + # 2) Removing parent.is_file check drops "output parent is not a directory". + # 3) Removing samefile check allows hardlink collision past _validate_args. + # 4) Removing temp unlink leaves a .tmp file behind on os.replace failure. + for label, target, replacement, check_fn in ( + ( + "drop_image_is_dir_guard", + ' if args.image.is_dir():\n raise IsADirectoryError(f"image path is a directory: {args.image}")\n', + " pass\n", + lambda mod: self.assertNotIn( + "image path is a directory", + _run_main(mod, [str(dir_image), str(out_dir / "a.cpp")])[2].lower(), + ), + ), + ( + "drop_parent_is_file_guard", + ' if parent.is_file() or ((parent.exists() or parent.is_symlink()) and not parent.is_dir()):\n' + ' raise NotADirectoryError(f"output parent is not a directory: {parent}")\n', + " pass\n", + lambda mod: self.assertNotIn( + "output parent is not a directory", + _run_main(mod, [str(image), str(file_parent / "frame_aot.cpp")])[2].lower(), + ), + ), + ( + "drop_samefile_guard", + " if args.output.resolve() == args.image.resolve() or (args.output.exists() and args.image.samefile(args.output)):\n", + " if args.output.resolve() == args.image.resolve():\n", + lambda mod: self.assertNotIn( + "choose a distinct .cpp output", + _run_main(mod, [str(image), str(hardlink_cpp)])[2].lower(), + ), + ), + ( + "drop_tmp_unlink", + " if tmp_path is not None:\n tmp_path.unlink(missing_ok=True)\n", + " pass\n", + lambda mod: self._verify_tmp_leaked_on_replace_fail(mod, image, out_cpp, out_dir), + ), + ): + with self.subTest(mutation=label): + self.assertEqual(source.count(target), 1, target) + mod = types.ModuleType(f"bink_frame_aot_mut_{label}") + mod.__file__ = str(TOOL) + sys.modules[mod.__name__] = mod + try: + exec(compile(source.replace(target, replacement, 1), str(TOOL), "exec"), mod.__dict__) + with mock.patch.object(mod, "generate", return_value=SYNTHETIC_CPP): + check_fn(mod) + finally: + sys.modules.pop(mod.__name__, None) + + def _verify_tmp_leaked_on_replace_fail(self, mod, image: Path, out_cpp: Path, out_dir: Path) -> None: + with mock.patch.object(os, "replace", side_effect=OSError("boom")): + code, _, _ = _run_main(mod, [str(image), str(out_cpp)]) + self.assertEqual(code, 1) + leaked = [p for p in out_dir.iterdir() if p.suffix == ".tmp"] + self.assertTrue(leaked, "expected unlinked .tmp file under mutation") + for p in leaked: + p.unlink(missing_ok=True) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/bink_frame_aot.py b/tools/bink_frame_aot.py index 9b72bb297..8ccef7594 100644 --- a/tools/bink_frame_aot.py +++ b/tools/bink_frame_aot.py @@ -1,6 +1,7 @@ """Translate the frame allocator, binding its direct calls to the existing Bink translations.""" import argparse from pathlib import Path +import tempfile from iced_x86 import Mnemonic as M, OpKind as K, Register as R import pefile @@ -64,15 +65,55 @@ def generate(image): """ + code + "\n}\n" +def _validate_args(args: argparse.Namespace, parser: argparse.ArgumentParser) -> None: + if args.image.is_dir(): + raise IsADirectoryError(f"image path is a directory: {args.image}") + if not args.image.is_file(): + raise FileNotFoundError(f"image file not found: {args.image}") + if args.output.suffix.lower() != ".cpp": + parser.error("choose a distinct .cpp output") + if args.output.is_symlink(): + raise ValueError(f"output path must not be a symlink: {args.output}") + if args.output.is_dir(): + raise IsADirectoryError(f"output path is a directory: {args.output}") + for parent in args.output.parents: + if parent.is_file() or ((parent.exists() or parent.is_symlink()) and not parent.is_dir()): + raise NotADirectoryError(f"output parent is not a directory: {parent}") + if args.output.resolve() == args.image.resolve() or (args.output.exists() and args.image.samefile(args.output)): + parser.error("choose a distinct .cpp output") + + +def _write_atomic(path: Path, content: str) -> None: + """Write ASCII content to a sibling temp file and atomically replace path, leaving 0 temp files on failure.""" + path.parent.mkdir(parents=True, exist_ok=True) + tmp_path = None + try: + with tempfile.NamedTemporaryFile( + mode="w", + encoding="ascii", + newline="\n", + dir=path.parent, + prefix=f".{path.stem}.", + suffix=".tmp", + delete=False, + ) as handle: + tmp_path = Path(handle.name) + handle.write(content) + tmp_path.replace(path) + except BaseException: + if tmp_path is not None: + tmp_path.unlink(missing_ok=True) + raise + + def main(argv=None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("image", type=Path) parser.add_argument("output", type=Path) args = parser.parse_args(argv) - if args.output.suffix.lower() != ".cpp" or args.output.resolve() == args.image.resolve(): - parser.error("choose a distinct .cpp output") try: - args.output.write_text(generate(args.image), encoding="ascii") + _validate_args(args, parser) + _write_atomic(args.output, generate(args.image)) except (OSError, ValueError, pefile.PEFormatError) as error: parser.exit(1, f"{error}\n") return 0 From 0827f43c7aad0c7707ad37bb7cfdbad179063030 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Thu, 26 Nov 2026 04:52:45 +0100 Subject: [PATCH 126/240] startup: keep src_scc proven at a branch target one uniform SCC write reaches (#2577) * startup: verify reaching SCC writer before reading src_scc Fixes #1820. Addresses review feedback on #1821: Stage.u() now refuses src_scc unless a modeled SCC writer set scc_verified on the reaching path in the current block. scc_verified starts False at entry, clears at branch targets/joins, non-fallthroughs, SCC_UNMODELLED (such as s_add_u32, cleared after reading its sources), descriptor-elided SCC writes, calculated-PC elision, and s_wqm. Test runs full Stage.translate() over synthetic bytes covering entry refusal, modeled compare/bitwise writers, low16_only=True, the s_add_u32 carry case, input-before-write on s_add_u32, and CFG joins; all 62 pure-Python startup_gfx2hlsl checks and CTest src_scc/sopk_accum/startup_translator pass. * startup: keep src_scc proven at a branch target one uniform SCC write reaches A compiler copies SCC into an SGPR on both arms of an if/else (s_cmp_* or s_bitcmp*, s_cbranch_scc0/1, then s_mov_b32 sN, src_scc in each arm). The arm at the branch target was refused as unverified, because every target dropped SCC. In 230 of the 239 locally refused requests, the first refused read has a single reaching SCC write. Each forward branch now carries the offset of the emitted SCC write that reaches it, but only when that write was uniform. A target keeps SCC proven when the fall-through and every edge into it carry the same write and no back edge enters it. Lane-mask SCC, unmodelled and elided writers, different writes on different paths, and loop heads stay refused. Co-Authored-By: Claude Opus 5.5 * test: read back src_scc at a branch target on D3D12 (WARP) --------- Co-authored-by: triggered02 <153171514+triggered02@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 Co-authored-by: tedin7 --- CMakeLists.txt | 9 + docs/experiments.md | 37 +++ tests/startup_gfx2hlsl_src_scc_check.py | 7 +- tests/startup_gfx2hlsl_src_scc_join_check.py | 263 +++++++++++++++++++ tools/startup/gfx2hlsl.py | 18 +- 5 files changed, 330 insertions(+), 4 deletions(-) create mode 100644 tests/startup_gfx2hlsl_src_scc_join_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 0119840ef..e4ad68ace 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3441,6 +3441,15 @@ if(EXISTS "${INTAKE_PYTHON}") # The src_scc scalar source (#1820). add_test(NAME startup_gfx2hlsl_src_scc COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_src_scc_check.py") + # src_scc at a branch target that one uniform SCC write reaches on every path. + add_test(NAME startup_gfx2hlsl_src_scc_join COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_src_scc_join_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_src_scc_join_dispatch_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_src_scc_join_check.py" dispatch "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_gfx2hlsl_src_scc_join_dispatch_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() # image_sample_c_lz with sampler word 2 bits 28-30 set (#1723). add_test(NAME startup_gfx2hlsl_sample_c_lz_mip COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_sample_c_lz_mip_check.py") diff --git a/docs/experiments.md b/docs/experiments.md index 18e2931e5..4346e02bc 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -16675,6 +16675,43 @@ ctest --preset dev --no-tests=error -R '^(pixel_aot_sdwa_int_extra_warp|pixel_ao Linux controls, `form_coverage_check.check_sdwa_int_extra_forms`, and Python reference/mutation checks ran locally; LLVM 15 `pixel_aot_binary` round-trips and Windows WARP/hardware D3D12 draws run in CI. +## `src_scc` as a scalar source + +`s_mul_i32 s28, 1.0, src_scc` was refused as `operand 'src_scc'` (issue #1820), one of the refused shaders +in the loading-screen cache (#870). Scalar source code 253 reads the SCC bit as the integer value 0 or 1 +(fitting in 16 bits, so `low16_only=True` returns the same expression), and the generated shader carries SCC +as a `bool scc`, so `Stage.u()` lowers `src_scc` to `(scc ? 1u : 0u)` when a modeled writer has set SCC +on every reaching path in the current block (`s_cmp_*` / `s_and_b32` etc. via `set_scc()`, `set_exec_scc()`, +or `scalar_wide_op()`). Reads where incoming SCC is unverified are refused: at shader entry, across +control-flow joins/branch targets, after descriptor-elided SCC writes, and after unmodeled SCC writers in +`SCC_UNMODELLED` such as `s_add_u32` (after `s_add_u32` finishes reading its own sources). Run +`ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_src_scc$' -V`. + +A branch target no longer drops a proven SCC in every case. In the local request cache, 238 of 239 requests +refused this way stop first at `s_mov_b32 sN, src_scc`, and 1 at `s_mul_i32 sN, sN, src_scc`. Walking the +control-flow graph back from each read finds the SCC writes that reach it: `s_bitcmp1_b32 sN, imm` (169 +reads), `s_bitcmp0_b32 sN, imm` (17), `s_cmp_eq_i32 sN, imm` (17), `s_cmp_lg_i32 sN, imm` (16), +`s_cmp_lt_i32` (7), `s_cmp_lt_u32 sN, sN` (6), `s_cmp_eq_u64 sN, sN` (3), `s_and_b64 sN, vcc, exec` (2), or +both `s_cmp_eq_i32` and `s_cmp_lg_i32` (2). One write reaches 230 reads, and two or three different writes +reach 9. In the samples inspected, this is the compiler copying SCC into an SGPR on both arms of an if/else +after `s_cbranch_scc0/1`, with the read in the arm that only the taken edge enters. Program-order tracking +marked that arm unverified because of the other arm's `s_branch`, or a descriptor-elided SCC write there +(`s_bfe_u32` of a descriptor word). + +Each forward branch now carries the offset of the emitted SCC write that reaches it, but only when that write +was uniform (`scc_uniform`). A target keeps SCC proven when the fall-through and every edge into it carry the +same write and no back edge enters it. Every path then ran that one write last, both for the modelled lane +and for the wave. This holds whichever path each took, including a block that `s_cbranch_execz` skips for +one lane only, so the model's SCC is the hardware value. Lane-mask SCC (`set_exec_scc`, a mask op on `vcc` or +`exec`), unmodelled and elided writers, different writes on different paths, and loop heads stay refused. + +The translator was origin/main plus #1821, run over the 239 requests with 4 workers. Before the change, 85 +refuse first on `src_scc`; the other 154 stop earlier, 137 of them on `NEG on an integer or literal source`. +After it, 75 of the 85 move on and 1 translates and compiles. The 10 left are compute requests. Each has a +reaching `s_cmp_*` whose source the model does not prove uniform. In 7 a different write reaches on another +path, and in 3 the path crosses a loop head. +`ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_src_scc(_join)?$' -V`. + ## Startup shader request identity `startup_shader_cache_key` uses the explicit `X2W_FXC=''` manifest-only mode: no GPU diff --git a/tests/startup_gfx2hlsl_src_scc_check.py b/tests/startup_gfx2hlsl_src_scc_check.py index 4880cd72d..e97bb0595 100644 --- a/tests/startup_gfx2hlsl_src_scc_check.py +++ b/tests/startup_gfx2hlsl_src_scc_check.py @@ -165,11 +165,12 @@ def refused_reason(code): + encode_sop2(SOP2_MUL_I32, S28, S_1_0, S_SCC) + encode_sopp(SOPP_ENDPGM)) == 'src_scc with unverified SCC') -# 6. Across a control-flow join: branch skips s_nop 0 to target 0x10; incoming SCC at the join is unverified, -# so src_scc there is refused unless a modeled writer runs inside the joined block first. +# 6. Across a control-flow join: branch skips an SCC write to target 0x0c, so the two paths into the join carry +# different SCC writes and src_scc there is refused unless a modeled writer runs inside the joined block first. +# (A skipped block without an SCC write keeps SCC proven: startup_gfx2hlsl_src_scc_join_check.py.) join_refused = (encode_sopc(SOPC_CMP_EQ_U32, S_ZERO, S_ZERO) # 0x00 + encode_sopp(SOPP_CBRANCH_SCC0, simm=1) # 0x04 -> label_0x0c (skip 1 dword at 0x08) - + encode_sopp(SOPP_NOP, simm=0) # 0x08 + + encode_sopc(SOPC_CMP_EQ_U32, S4, S5) # 0x08 + encode_sop2(SOP2_MUL_I32, S28, S_1_0, S_SCC) # 0x0c (branch target / join) + encode_sopp(SOPP_ENDPGM)) # 0x10 check('src_scc across a control-flow join is refused', diff --git a/tests/startup_gfx2hlsl_src_scc_join_check.py b/tests/startup_gfx2hlsl_src_scc_join_check.py new file mode 100644 index 000000000..5dc0417c2 --- /dev/null +++ b/tests/startup_gfx2hlsl_src_scc_join_check.py @@ -0,0 +1,263 @@ +"""`src_scc` at a branch target in tools/startup/gfx2hlsl.py. + +usage: startup_gfx2hlsl_src_scc_join_check.py [dispatch ] + +`dispatch` also compiles the accepted if/else and skipped-block programs with DXC and compares a D3D12 UAV +readback (WARP or hardware) with the compare each read must see. + +A compiler materializes SCC into an SGPR on both arms of an if/else: `s_bitcmp1_b32 s4, 3`, +`s_cbranch_scc0 ELSE`, then `s_mov_b32 s10, src_scc` in each arm. The arm at ELSE starts at a branch +target, where `src_scc` was refused as unverified. The translator now carries, on every forward branch +edge, the offset of the emitted SCC write that reaches it, and only when that write was uniform. A branch +target keeps SCC proven when the fall-through and every edge into it carry the same write and no back edge +enters it. Every path into the target then ran that one write last, both for the lane being modelled and +for the wave, whichever path each took (a per-lane `s_cbranch_execz` skip included). So the model's SCC is +the hardware value. + +Negative controls keep the refusal: an SCC write in one arm, an SCC write in a block `s_cbranch_execz` +skips, a back edge into the target, a lane-mask SCC (`s_and_b32` with `vcc_lo`), and an unmodelled +writer (`s_add_u32`) on one path. + +The instruction words are built here from the field layout that `tools/disasm_rdna2.py` decodes: +- SOP1 (`[31:23] == 0b101111101`, sdst in `w0[22:16]`, op in `w0[15:8]`, src0 in `w0[7:0]`) +- SOP2 (`[31:30] == 0b10`, op in `w0[29:23]`, sdst in `w0[22:16]`, src1 in `w0[15:8]`, src0 in `w0[7:0]`) +- SOPC (`[31:23] == 0b101111110`, op in `w0[22:16]`, src1 in `w0[15:8]`, src0 in `w0[7:0]`) +- SOPP (`[31:23] == 0b101111111`, op in `w0[22:16]`, simm16 in `w0[15:0]`, branch target + `pc + 4 + 4 * simm16`) +""" +import os +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +here = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(here, '..', 'tools')) +sys.path.insert(0, os.path.join(here, '..', 'tools', 'startup')) +import gfx2hlsl as G # noqa: E402 + +failures = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH'}") + if not condition: + failures.append(label) + if detail: + print(' ' + detail) + + +SOP1_MOV_B32 = 0x03 +SOP2_ADD_U32 = 0x00 +SOP2_AND_B32 = 0x0E +SOPC_CMP_EQ_U32 = 0x06 +SOPC_BITCMP1_B32 = 0x0D +SOPP_NOP, SOPP_ENDPGM, SOPP_BRANCH, SOPP_CBRANCH_SCC0, SOPP_CBRANCH_EXECZ = 0x00, 0x01, 0x02, 0x04, 0x08 + +S_SCC = 253 +S_THREE = 131 # inline integer 3 +VCC_LO = 106 +S4, S5, S6, S7, S10 = 4, 5, 6, 7, 10 +UNVERIFIED = 'src_scc with unverified SCC' + + +def sop1(op, sdst, ssrc0): + return struct.pack(' 0x14 + + READ # 0x08 + + sopc(SOPC_CMP_EQ_U32, S4, S5) # 0x0c + + branch(SOPP_BRANCH, 0x10, 0x18) # 0x10 -> 0x18 + + READ # 0x14 (target of the taken edge only) + + sopp(SOPP_ENDPGM)) # 0x18 (join) +asm, blocks = translate_program(if_else) +check('if/else words decode as written', + asm == ['s_bitcmp1_b32 s4, 3', 's_cbranch_scc0 label_0x14', 's_mov_b32 s10, src_scc', 's_cmp_eq_u32 s4, s5', + 's_branch label_0x18', 's_mov_b32 s10, src_scc', 's_endpgm'], repr(asm)) +check('if/else: both arms read the SCC of s_bitcmp1_b32', + blocks == [['scc = ((s4 >> (0x00000003u & 31)) & 1u) == 1u;'], + ['s10 = (scc ? 1u : 0u);', 'scc = s4 == s5;'], + ['s10 = (scc ? 1u : 0u);'], []], repr(blocks)) + +# 2. A join that a skipped block without an SCC write reaches: both edges carry the compare at 0x00. +skip_nop = (sopc(SOPC_CMP_EQ_U32, S4, S5) # 0x00 + + branch(SOPP_CBRANCH_SCC0, 0x04, 0x0c) # 0x04 -> 0x0c + + sopp(SOPP_NOP) # 0x08 + + READ # 0x0c (join) + + sopp(SOPP_ENDPGM)) +asm, blocks = translate_program(skip_nop) +check('join after a block without SCC writes reads the compare', + blocks == [['scc = s4 == s5;'], [], ['s10 = (scc ? 1u : 0u);']], repr(blocks)) + +# 3. The same over s_cbranch_execz: the lane can skip a block the wave runs, which is harmless only because +# the block writes no SCC. +skip_execz = (sopc(SOPC_CMP_EQ_U32, S4, S5) # 0x00 + + branch(SOPP_CBRANCH_EXECZ, 0x04, 0x0c) # 0x04 -> 0x0c + + sopp(SOPP_NOP) # 0x08 + + READ # 0x0c (join) + + sopp(SOPP_ENDPGM)) +asm, blocks = translate_program(skip_execz) +check('join after an execz-skipped block without SCC writes reads the compare', + blocks == [['scc = s4 == s5;'], [], ['s10 = (scc ? 1u : 0u);']], repr(blocks)) + +# Negative controls: each keeps `src_scc with unverified SCC`. +# 4. An SCC write in the skipped arm: the two edges carry different writes. +check('SCC write in one arm refuses the read at the join', + refused_reason(sopc(SOPC_CMP_EQ_U32, S4, S5) # 0x00 + + branch(SOPP_CBRANCH_SCC0, 0x04, 0x0c) # 0x04 -> 0x0c + + sopc(SOPC_CMP_EQ_U32, S6, S7) # 0x08 + + READ + sopp(SOPP_ENDPGM)) == UNVERIFIED) # 0x0c +# 5. An SCC write inside a block s_cbranch_execz skips: the wave may run it while the lane skips it. +check('SCC write in an execz-skipped block refuses the read at the join', + refused_reason(sopc(SOPC_CMP_EQ_U32, S4, S5) + + branch(SOPP_CBRANCH_EXECZ, 0x04, 0x0c) + + sopc(SOPC_CMP_EQ_U32, S6, S7) + + READ + sopp(SOPP_ENDPGM)) == UNVERIFIED) +# 6. A back edge into the target: the loop body's SCC write is not known when the target is reached. +check('back-edge target refuses the read', + refused_reason(sopc(SOPC_CMP_EQ_U32, S4, S5) # 0x00 + + READ # 0x04 (loop head) + + sopc(SOPC_CMP_EQ_U32, S6, S7) # 0x08 + + branch(SOPP_CBRANCH_SCC0, 0x0c, 0x04) # 0x0c -> 0x04 + + sopp(SOPP_ENDPGM)) == UNVERIFIED) +# 7. A lane-mask SCC: s_and_b32 with vcc_lo sets SCC from every lane's bit, which one lane does not see. +check('lane-mask SCC across a branch refuses the read', + refused_reason(sop2(SOP2_AND_B32, S6, S4, VCC_LO) # 0x00 + + branch(SOPP_CBRANCH_EXECZ, 0x04, 0x0c) # 0x04 -> 0x0c + + sopp(SOPP_NOP) # 0x08 + + READ + sopp(SOPP_ENDPGM)) == UNVERIFIED) # 0x0c +# 8. An unmodelled SCC writer on one path: s_add_u32 sets the carry the model does not emit. +check('unmodelled writer on one path refuses the read', + refused_reason(sopc(SOPC_CMP_EQ_U32, S4, S5) + + branch(SOPP_CBRANCH_SCC0, 0x04, 0x0c) + + sop2(SOP2_ADD_U32, S6, S4, S5) + + READ + sopp(SOPP_ENDPGM)) == UNVERIFIED) + + +MASK = 0xFFFFFFFF +DISPATCH_CASES = ((0x00000000, 0x00000000), (0x00000008, 0x00000008), (0x00000008, 0x00000001), + (0xFFFFFFF7, 0xFFFFFFF7), (0xFFFFFFFF, 0x12345678), (0x12345678, 0x12345678)) + + +def dispatch_hlsl(cases, fill): + """One thread, one block per case: structured if/else, then the skipped-block join, on the translated lines.""" + _, if_blocks = translate_program(if_else) + _, skip_blocks = translate_program(skip_nop) + lines = ['RWByteAddressBuffer data : register(u0);', '[numthreads(1, 1, 1)]', 'void main() {'] + for i, (a, b) in enumerate(cases): + out = 4 * (len(fill) + 2 * i) + lines += [' {', + f' uint s4 = data.Load({8 * i}) ^ {fill[2 * i] ^ a:#010x}u;', + f' uint s5 = data.Load({8 * i + 4}) ^ {fill[2 * i + 1] ^ b:#010x}u;', + ' uint s10 = 0u;', ' bool scc = true;'] + lines += [' ' + t for t in if_blocks[0]] + lines += [' if (scc) {'] + [' ' + t for t in if_blocks[1]] + lines += [' } else {'] + [' ' + t for t in if_blocks[2]] + [' }'] + lines.append(f' data.Store({out}, s10);') + lines += [' s10 = 0u;', ' scc = true;'] + lines += [' ' + t for t in skip_blocks[0] + skip_blocks[2]] + lines += [f' data.Store({out + 4}, s10);', ' }'] + return '\n'.join(lines + ['}']) + '\n' + + +def check_dispatch(dxc, runner, adapter): + runner = str(Path(runner).resolve()) + fill = tuple(((i + 1) * 0x9e3779b1 & MASK) | 1 for i in range(2 * len(DISPATCH_CASES))) + out = Path(__file__).resolve().parent.parent / 'out' + out.mkdir(exist_ok=True) + with tempfile.TemporaryDirectory(dir=out) as tmp: + src, cso, dump = (Path(tmp) / ('src_scc_join' + e) for e in ('.hlsl', '.cso', '.bin')) + src.write_text(dispatch_hlsl(DISPATCH_CASES, fill), encoding='ascii') + compiled = subprocess.run([dxc, '-T', 'cs_6_0', '-E', 'main', '-Fo', str(cso), str(src)], + stderr=subprocess.PIPE, text=True) + if compiled.returncode or compiled.stderr: + raise AssertionError(compiled.stderr or f'DXC exited with {compiled.returncode}') + words = len(fill) + 2 * len(DISPATCH_CASES) + padded = (words + 3) // 4 * 4 + run = subprocess.run([runner, adapter, '--raw-uav-dump', str(cso), '1', str(4 * padded), str(dump)], + capture_output=True, text=True) + print(run.stdout, end='') + if run.returncode == 77: + sys.exit(77) + if run.returncode or run.stderr: + raise AssertionError(run.stderr or f'raw UAV dump exited with {run.returncode}') + got = struct.unpack(f'<{padded}I', dump.read_bytes()) + check('operand region unchanged', got[:len(fill)] == fill) + for i, (a, b) in enumerate(DISPATCH_CASES): + # CPU reference: the if/else reads the s_bitcmp1_b32 s4, 3 result on both arms; the join reads s4 == s5. + want = ((a >> 3) & 1, int(a == b)) + have = got[len(fill) + 2 * i:len(fill) + 2 * i + 2] + check(f'readback s4={a:#010x} s5={b:#010x}: got {have}, want {want}', have == want) + if failures: + sys.exit(1) + + +if len(sys.argv) == 5 and sys.argv[1] == 'dispatch': + check_dispatch(*sys.argv[2:]) + print('PASS') + sys.exit(0) +elif len(sys.argv) != 1: + sys.exit(__doc__) + +if failures: + print('FAIL') + for text in failures: + print(' ' + text) + sys.exit(1) +print('PASS') diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index c9b363eda..e91368432 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -2929,6 +2929,7 @@ def translate(self): names = {off: name for off, _n, name, _asm in self.ins} execz_targets = set() if getattr(self, 'kind', None) == 'cs' else { t for t in targets if all(pc < t and names[pc] == 's_cbranch_execz' for pc, to in branches if to == t)} + back_targets = {to for pc, to in branches if to <= pc} self.mesh_allocation_block = None splits = set(targets) if getattr(self, 'kind', None) == 'ms' and targets: @@ -2992,6 +2993,9 @@ def translate(self): self.varying_s = set() self.scc_uniform = True self.scc_verified = False + # Offset of the emitted, uniform SCC write that reaches here (None: none, or not proven), and the one + # each forward branch carries to its target. + self.scc_def, scc_in = None, {} self.low16_only_v = set() # VGPRs whose upper 16 bits are undefined after odd-dmask d16 image_load self.pinned_low16_v = set() # low16_only_v live across basic-block boundaries self.whole_read_v = set() # VGPRs read outside a proven low-16-bit consumer @@ -3032,6 +3036,15 @@ def translate(self): self.pc = off self.descriptor_instruction_index = instruction_index self.scc_effect = None + if off in targets: + # Every path in carries the same uniform emitted write, which the lane and the wave both ran + # last, whichever path each took (a per-lane s_cbranch_execz edge included); the SCC writes on a + # back edge are not known yet. + defs = ([self.scc_def] if falls else []) + scc_in.get(off, []) + one_def = off not in back_targets and len(set(defs)) == 1 + self.scc_def = defs[0] if one_def else None + elif not falls: + self.scc_def = None if not falls: self.scc_verified = False # Before the first branch target or terminator every path has run exactly the instructions above, so @@ -3083,7 +3096,7 @@ def translate(self): tentative_kept.update((kept_u & clobber) - blocked) self.uniform_v.clear() self.since_join, self.scc_uniform = kept_u, False - self.scc_verified = False + self.scc_verified = self.scc_def is not None # A constant is only known here if no other path into the join writes the register: a loop counter # set before the loop and incremented in it reaches the loop head with a new value on every pass. # set_s also assigns constants at run time, so the register reads its real value once it is dropped. @@ -3108,6 +3121,7 @@ def translate(self): there = joined.get(b_target, set()) if b_target > off: incoming.setdefault(b_target, []).append(({reg: self.sym.get(reg) for reg in there}, written & there)) + scc_in.setdefault(b_target, []).append(self.scc_def) else: for reg in there & written: back, sym = self.sym.get(reg), kept.get(b_target, {}).get(reg) @@ -3194,6 +3208,8 @@ def translate(self): self.join_masks = (self.join_masks | every_sgpr) if 'any' in dests else self.join_masks - dests if self.scc_effect: scc_effects[off] = self.scc_effect + if self.scc_effect or not self.scc_verified: + self.scc_def = off if self.scc_effect == 'emitted' and self.scc_verified and self.scc_uniform else None if term: self.pinned_low16_v.update(self.low16_only_v) self.blocks.append((start, self.lines, term)) From 562f7ddbe74820ec9b77a52e73493508ef27f353 Mon Sep 17 00:00:00 2001 From: triggered02 <153171514+triggered02@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:31:32 +0530 Subject: [PATCH 127/240] docs: link the four unlinked hardware reports in the coverage table (#2726) Co-authored-by: triggered02 --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index b0e70f346..fd93fb254 100644 --- a/README.md +++ b/README.md @@ -212,9 +212,9 @@ Results are grouped by adapter. Open a report for the driver, build and any capa | Adapter or backend | Default native lanes | Forced wave64 | BVH differential | Evidence | |---|---:|---|---|---| | NVIDIA GeForce RTX 2060 | 32 | Skipped | 408 queries passed | [Maintainer baseline](docs/experiments.md#independent-bvh-checks-on-pc) · [32.0.16.2124 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7077064410) | -| NVIDIA GeForce RTX 3070 (driver 32.0.16.1088) | 32 | Skipped, lane range 32–32 | 408 queries passed | [RTX 3070 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7063566753) · [32.0.16.2101 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064780514) · [Independent 32.0.16.2101 run, source build at b860dd5](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7070552394) · [Independent 32.0.16.1088 run, Windows 10](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7084482487) | +| NVIDIA GeForce RTX 3070 (driver 32.0.16.1088) | 32 | Skipped, lane range 32–32 | 408 queries passed | [RTX 3070 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7063566753) · [32.0.16.2101 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064780514) · [Independent 32.0.16.2101 run, source build at b860dd5](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7070552394) · [Independent 32.0.16.1088 run, Windows 10](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7084482487) · [32.0.16.1742 report by @hencydsouza, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7170984432) · [32.0.16.1656 report by @upipibi, source 2f7fd28, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7175561067) | | NVIDIA GeForce RTX 3070 Ti | 32 | Skipped, lane range 32–32 | 408 queries passed | [32.0.16.1692 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7099622883) · [32.0.16.1742 report, Windows build 26200](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7121943659) · [32.0.16.2114 report by @Maxim-Root, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7129028243) · [32.0.16.1088 (610.88) report by @wanchudao](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7166634226) | -| NVIDIA GeForce RTX 4060 Laptop GPU | 32 | Skipped | 408 queries passed | [Second maintainer workstation](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7058907095) · [Independent Windows run, driver 32.0.16.2124](https://github.com/R0Y00/Xbox2Windows/issues/60) · [32.0.16.1742 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064580375) · [32.0.16.1091 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7082946105) | +| NVIDIA GeForce RTX 4060 Laptop GPU | 32 | Skipped | 408 queries passed | [Second maintainer workstation](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7058907095) · [Independent Windows run, driver 32.0.16.2124](https://github.com/R0Y00/Xbox2Windows/issues/60) · [32.0.16.1742 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064580375) · [32.0.16.1091 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7082946105) · [32.0.16.2124 report by @vfd9654, debug layer unavailable](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7165908151) | | NVIDIA GeForce RTX 5070 | 32 on every run | Skipped on every run, lane range 32–32 | 408 queries passed per run | [32.0.16.1692, debug layer unavailable](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7063361337) · [32.0.16.2135 retest, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7063626309) · [32.0.16.2124 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7066814242) · [32.0.16.1686 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7067154644) · [Independent 32.0.16.2135 run](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7068151257) · [38.0.1.104 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7066183143) | | AMD Radeon RX 6600 (driver 32.0.21045.16010) | 32 | Passed, 64 lanes; skipped, Shader Model 6.5 on build 19044 | 408 queries passed | [RX 6600 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7063312495) · [32.0.11037.4004 retest](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7063794169) · [32.0.21045.29003 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064667296) · [32.0.21030.2001 report, Windows 10 build 19044](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7080061922) · [31.0.22017.3004 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7080963908) · [Independent 32.0.21045.29003 run, Windows build 26300](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7122426568) | | AMD Radeon RX 6750 XT (driver 32.0.21045.29003) | 32 | Passed, 64 lanes | 408 queries passed | [RX 6750 XT report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7062253227) | @@ -243,7 +243,7 @@ Results are grouped by adapter. Open a report for the driver, build and any capa | NVIDIA GeForce RTX 3080 Ti Laptop GPU | 32 | Skipped, lane range 32–32 | 408 queries passed | [32.0.16.2135 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064722299) | | AMD Radeon RX 6700 XT | 32 | Passed, 64 lanes; skipped at SM 6.5 on 32.0.21045.9003 | 408 queries passed | [32.0.21045.16010 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064730965) · [32.0.21045.29003 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7076337541) · [Independent 32.0.21045.29003 run](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7081698039) · [32.0.21045.9003 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7106794867) | | NVIDIA GeForce RTX 4090 Laptop GPU | 32 | Skipped, lane range 32–32 | 408 queries passed | [32.0.16.1656 report](https://github.com/R0Y00/Xbox2Windows/issues/64) · [32.0.16.2124 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7138088095) | -| NVIDIA GeForce RTX 5070 Ti | 32 | Skipped, lane range 32–32 | 408 queries passed | [32.0.16.2124 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064221428) · [Independent 32.0.16.2124 run](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7066648123) · [32.0.16.1664 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7068298651) · [32.0.16.1742 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7071681613) · [32.0.16.1714 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7086202845) · [32.0.16.2101 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7135432772) | +| NVIDIA GeForce RTX 5070 Ti | 32 | Skipped, lane range 32–32 | 408 queries passed | [32.0.16.2124 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064221428) · [Independent 32.0.16.2124 run](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7066648123) · [32.0.16.1664 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7068298651) · [32.0.16.1742 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7071681613) · [32.0.16.1714 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7086202845) · [32.0.16.2101 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7135432772) · [32.0.16.2124 report by @alecselle, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7123603068) | | NVIDIA GeForce RTX 5050 | 32 | Skipped, lane range 32–32 | 408 queries passed | [32.0.16.2101 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064238316) | | AMD Radeon RX 7800 XT | 32 on every run | Skipped on Windows 10 runs capped at Shader Model 6.5. Passed with 64 lanes in the other reports | 408 queries passed per run | [32.0.32015.16001 report, Windows 10 build 19045](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064791654) · [32.0.32029.2010 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/101) · [Independent 32.0.32029.2010 run](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7068788175) · [32.0.32015.7029 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7079560197) · [32.0.32015.16001 report, build 26300, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7084752103) · [Third 32.0.32029.2010 run, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7085397975) · [32.0.32029.2010 report, Windows 10 build 19045, Shader Model 6.5](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7093682244) · [32.0.32029.2010 report, Windows build 26300.10075, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7124179405) | | NVIDIA GeForce GTX 1070 | 32 | Skipped, lane range 32–32 | Skipped, DXR tier 1.0 | [32.0.15.8180 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064831532) · [32.0.15.8278 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7078694248) · [32.0.15.8266 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7079940198) | From 2215c26d3019299764ba1b3149fcf6e2ee403916 Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Thu, 26 Nov 2026 06:05:11 +0200 Subject: [PATCH 128/240] tooling: harden hardware_reports CLI guards and add CLI suite (#2682) * tooling: harden hardware_reports CLI guards and add CLI suite * test: decode hardware_reports CLI subprocess output as UTF-8 --------- Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> Co-authored-by: tedin7 --- CMakeLists.txt | 3 + tests/hardware_reports_cli_check.py | 288 ++++++++++++++++++++++++++++ tools/hardware_reports.py | 20 +- 3 files changed, 308 insertions(+), 3 deletions(-) create mode 100644 tests/hardware_reports_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index e4ad68ace..fc51abd42 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -11062,6 +11062,9 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/gpu_report_format_check.py") add_test(NAME hardware_reports COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/hardware_reports_check.py") + add_test(NAME tooling_hardware_reports_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/hardware_reports_cli_check.py") + set_tests_properties(tooling_hardware_reports_cli_check PROPERTIES TIMEOUT 60) add_test(NAME shader_corpus_report COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/shader_corpus_report_check.py") add_test(NAME xgameruntime_table COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/hardware_reports_cli_check.py b/tests/hardware_reports_cli_check.py new file mode 100644 index 000000000..5ec465586 --- /dev/null +++ b/tests/hardware_reports_cli_check.py @@ -0,0 +1,288 @@ +#!/usr/bin/env python3 +"""Pure-Python CLI validation, comment-ID guard, and mutation suite for tools/hardware_reports.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +import json +import os +from pathlib import Path +import runpy +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOLS_DIR = ROOT / "tools" +TESTS_DIR = ROOT / "tests" +TOOL = TOOLS_DIR / "hardware_reports.py" +sys.path.insert(0, str(TOOLS_DIR)) +sys.path.insert(0, str(TESTS_DIR)) + +import hardware_reports as hr # noqa: E402 +from hardware_reports_check import README, comment, report # noqa: E402 + + +def _run_main(argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = hr.main(argv) + except SystemExit as exc: + code = exc.code + if not isinstance(code, int): + if code is not None: + stderr.write(f"{code}\n") + code = 0 if code is None else 1 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + encoding="utf-8", + env={**os.environ, "PYTHONIOENCODING": "utf-8"}, + timeout=30, + ) + + +class HardwareReportsCliPositiveTests(unittest.TestCase): + def test_markdown_json_after_filtering_and_boundary_id_zero(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + readme = base / "README.md" + readme.write_text(README, encoding="utf-8") + + c0 = comment(0, report(adapter="Example GPU 000", device="0001", driver="0.9")) + c101 = comment(101, report()) + c202 = comment(202, report(adapter="Example GPU 300", device="3333", driver="3.0")) + c205 = comment(205, report(adapter="Example GPU 400", device="4444", driver="4.0")) + + page1 = base / "page1.json" + page2 = base / "page2.json" + page1.write_text(json.dumps([c0, c101]), encoding="utf-8") + page2.write_text(json.dumps([c202]) + "\n" + json.dumps([c205]), encoding="utf-16") + + # 1) Markdown output across multiple comment files, including id=0. + code, out, err = _run_main([str(page1), str(page2), "--readme", str(readme)]) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertIn("Read 4 comments. 4 reports use the generated layout; README.md links 1 of them.", out) + self.assertIn("## 1. Example GPU 000 (new row)", out) + self.assertIn("## 2. Example GPU 300 (new row)", out) + self.assertIn("## 3. Example GPU 400 (new row)", out) + + # 2) --json with --after 0 includes positive IDs (and excludes id=0). + code_a0, out_a0, err_a0 = _run_main( + [str(page1), str(page2), "--readme", str(readme), "--after", "0", "--json"] + ) + self.assertEqual(code_a0, 0, err_a0) + self.assertEqual(err_a0, "") + data_a0 = json.loads(out_a0) + self.assertEqual(data_a0["after"], 0) + self.assertEqual([item["comment_id"] for item in data_a0["unrecorded"]], [202, 205]) + + # 3) --json with --after 202 filters to > 202. + code_a202, out_a202, err_a202 = _run_main( + [str(page1), str(page2), "--readme", str(readme), "--after", "202", "--json"] + ) + self.assertEqual(code_a202, 0, err_a202) + data_a202 = json.loads(out_a202) + self.assertEqual(data_a202["after"], 202) + self.assertEqual([item["comment_id"] for item in data_a202["unrecorded"]], [205]) + + # 4) Subprocess end-to-end positive check. + proc = _run_subprocess(str(page1), str(page2), "--readme", str(readme), "--after", "202", "--json") + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stderr, "") + self.assertEqual(json.loads(proc.stdout), data_a202) + + def test_sys_argv_and_script_entrypoint(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + readme = base / "README.md" + readme.write_text(README, encoding="utf-8") + comments_file = base / "comments.json" + comments_file.write_text( + json.dumps([comment(202, report(adapter="Example GPU 300", device="3333", driver="3.0"))]), + encoding="utf-8", + ) + cli_argv = [str(TOOL), str(comments_file), "--readme", str(readme), "--json"] + + with mock.patch.object(sys, "argv", cli_argv): + code, out, err = _run_main(None) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertEqual([item["comment_id"] for item in json.loads(out)["unrecorded"]], [202]) + + stdout, stderr = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", cli_argv), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 0) + self.assertEqual(stderr.getvalue(), "") + self.assertEqual([item["comment_id"] for item in json.loads(stdout.getvalue())["unrecorded"]], [202]) + + +class HardwareReportsCliNegativeAndMutationTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_code: int | None = 2, + fragments: tuple[str, ...] = (), + check_subprocess: bool = True, + ) -> str: + code, out, err = _run_main(argv) + if expected_code is None: + self.assertNotEqual(code, 0) + else: + self.assertEqual(code, expected_code, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertTrue(err.strip(), f"expected stderr for {argv!r}") + for fragment in fragments: + self.assertIn(fragment.lower(), err.lower()) + + if check_subprocess: + proc = _run_subprocess(*argv) + if expected_code is None: + self.assertNotEqual(proc.returncode, 0) + else: + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertTrue(proc.stderr.strip(), f"expected subprocess stderr for {argv!r}") + for fragment in fragments: + self.assertIn(fragment.lower(), proc.stderr.lower()) + return err + + def test_upfront_paths_and_negative_after_rejected_before_reading(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + readme = base / "README.md" + readme.write_text(README, encoding="utf-8") + valid_comments = base / "valid.json" + valid_comments.write_text("[]", encoding="utf-8") + missing_comments = base / "missing.json" + missing_readme = base / "missing_readme.md" + a_dir = base / "a_dir" + a_dir.mkdir() + + with ( + mock.patch.object(hr, "load_comments", side_effect=AssertionError("load_comments called upfront")), + mock.patch.object(hr, "summarize", side_effect=AssertionError("summarize called upfront")), + ): + for label, argv, frag in ( + ("missing_comments", [str(missing_comments), "--readme", str(readme)], "comments file not found"), + ( + "second_missing_comments", + [str(valid_comments), str(missing_comments), "--readme", str(readme)], + "comments file not found", + ), + ("dir_comments", [str(a_dir), "--readme", str(readme)], "comments path is a directory"), + ( + "second_dir_comments", + [str(valid_comments), str(a_dir), "--readme", str(readme)], + "comments path is a directory", + ), + ("missing_readme", [str(valid_comments), "--readme", str(missing_readme)], "--readme file not found"), + ("dir_readme", [str(valid_comments), "--readme", str(a_dir)], "--readme path is a directory"), + ("neg_after_1", [str(valid_comments), "--readme", str(readme), "--after", "-1"], "non-negative"), + ("neg_after_99", [str(valid_comments), "--readme", str(readme), "--after", "-99"], "non-negative"), + ): + with self.subTest(case=label): + self._assert_clean_failure(argv, expected_code=2, fragments=(frag,)) + + def test_load_comments_rejects_bool_negative_non_int_ids_and_bad_json(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + readme = base / "README.md" + readme.write_text(README, encoding="utf-8") + + for label, bad_id in ( + ("bool_true", True), + ("bool_false", False), + ("neg_one", -1), + ("neg_large", -100), + ("str_id", "101"), + ("float_id", 10.5), + ("none_id", None), + ): + with self.subTest(case=label, bad_id=bad_id): + bad_file = base / f"{label}.json" + bad_file.write_text( + json.dumps([{"id": bad_id, "body": "x"}]), + encoding="utf-8", + ) + with self.assertRaises(ValueError) as ctx: + hr.load_comments([bad_file]) + self.assertIn("non-negative integer id", str(ctx.exception)) + self._assert_clean_failure( + [str(bad_file), "--readme", str(readme)], + expected_code=2, + fragments=("non-negative integer id",), + ) + + # Missing body / non-dict item / malformed JSON / bad UTF-8 / bad README table. + missing_body = base / "missing_body.json" + missing_body.write_text(json.dumps([{"id": 1}]), encoding="utf-8") + self._assert_clean_failure( + [str(missing_body), "--readme", str(readme)], + expected_code=2, + fragments=("expected github issue comment objects",), + ) + + non_dict = base / "non_dict.json" + non_dict.write_text(json.dumps([123]), encoding="utf-8") + self._assert_clean_failure( + [str(non_dict), "--readme", str(readme)], + expected_code=2, + fragments=("expected github issue comment objects",), + ) + + malformed = base / "malformed.json" + malformed.write_text('[{"id": 1, "body": ', encoding="utf-8") + self._assert_clean_failure([str(malformed), "--readme", str(readme)], expected_code=2) + + bad_utf8 = base / "bad_utf8.json" + bad_utf8.write_bytes(b"\xff\xfe\x00") + self._assert_clean_failure([str(bad_utf8), "--readme", str(readme)], expected_code=2) + + valid_comments = base / "valid.json" + valid_comments.write_text("[]", encoding="utf-8") + bad_readme = base / "bad_readme.md" + bad_readme.write_text("# No coverage table here\n", encoding="utf-8") + self._assert_clean_failure( + [str(valid_comments), "--readme", str(bad_readme)], + expected_code=2, + fragments=("no hardware coverage table header",), + ) + + def test_argparse_errors_py314_safe(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + comments = base / "comments.json" + comments.write_text("[]", encoding="utf-8") + + for argv, frags in ( + ([], ("required",)), + ([str(comments), "--bogus-flag"], ("unrecognized",)), + ([str(comments), "--after", "not_int"], ("invalid",)), + ([str(comments), "--readme"], ("expected one argument",)), + ): + with self.subTest(argv=argv): + self._assert_clean_failure(argv, expected_code=None, fragments=frags) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/hardware_reports.py b/tools/hardware_reports.py index 732cba8cb..f52ff82d0 100644 --- a/tools/hardware_reports.py +++ b/tools/hardware_reports.py @@ -108,9 +108,12 @@ def load_comments(paths: list[Path]) -> list[dict]: break value, index = decoder.raw_decode(text, index) for item in value if isinstance(value, list) else [value]: - if not isinstance(item, dict) or not isinstance(item.get("id"), int) or "body" not in item: - raise ValueError(f"{path}: expected GitHub issue comment objects with id and body") - comments[item["id"]] = item + cid = item.get("id") if isinstance(item, dict) else None + if isinstance(cid, bool) or not isinstance(cid, int) or cid < 0 or "body" not in item: + raise ValueError( + f"{path}: expected GitHub issue comment objects with non-negative integer id and body" + ) + comments[cid] = item return [comments[key] for key in sorted(comments)] @@ -446,6 +449,17 @@ def main(argv: list[str] | None = None) -> int: parser.add_argument("--json", action="store_true", help="print JSON instead of Markdown") args = parser.parse_args(argv) try: + if args.after is not None and args.after < 0: + raise ValueError(f"--after must be non-negative, got {args.after}") + for path in args.comments: + if path.is_dir(): + raise IsADirectoryError(f"comments path is a directory: {path}") + if not path.is_file(): + raise FileNotFoundError(f"comments file not found: {path}") + if args.readme.is_dir(): + raise IsADirectoryError(f"--readme path is a directory: {args.readme}") + if not args.readme.is_file(): + raise FileNotFoundError(f"--readme file not found: {args.readme}") comments = load_comments(args.comments) summary = summarize(comments, args.readme.read_text(encoding="utf-8"), args.after) except (OSError, ValueError) as error: From feec219e2561e88c266ce825fc69f9ae53da9a7a Mon Sep 17 00:00:00 2001 From: Royoo <3230853833@qq.com> Date: Thu, 26 Nov 2026 12:12:25 +0800 Subject: [PATCH 129/240] Bind a proven live index alias for direct draws without sliced streams (#2724) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 4 ++ docs/experiments.md | 23 ++++++++ src/startup_stubs/d3d12_draw.inl | 39 ++++++++++--- .../startup_direct_index_late_write_check.py | 56 +++++++++++++++++++ tests/startup_stream_draw.cpp | 42 +++++++++++++- 5 files changed, 156 insertions(+), 8 deletions(-) create mode 100644 tests/startup_direct_index_late_write_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index fc51abd42..dbd01e826 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4552,6 +4552,10 @@ if(EXISTS "${INTAKE_PYTHON}") "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_copied_vertex_srv_check.py" "$" "${backend}") set_tests_properties(startup_copied_vertex_srv_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + add_test(NAME startup_direct_index_late_write_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_direct_index_late_write_check.py" + "$" "${backend}") + set_tests_properties(startup_direct_index_late_write_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) add_test(NAME startup_mubuf_descriptor_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_mubuf_descriptor_check.py" "$" "${backend}") diff --git a/docs/experiments.md b/docs/experiments.md index 4346e02bc..03f2053dd 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15795,6 +15795,29 @@ cmake --build --preset release --target startup_stream_consumer ctest --preset release --no-tests=error -R '^startup_(copied_vertex_srv|address_buffer_srv|frame_copy)_(warp|hardware)$' -V ``` +### Direct indexed draws after CPU writes + +For a direct translated draw with no vertex-stream SRVs, the shim binds a +live placed index-buffer alias when the drawn range and alignment are known. +The recording holds the desktop resource. The draw can then consume CPU +changes completed before submission, as required for CPU-accessible buffers +by [ID3D12Resource::Map](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12resource-map#advanced-usage-models). +Draws that slice and rebase a vertex stream still use the recording-time +index snapshot together with the stream range computed from it. + +`startup_direct_index_late_write` reuses the source-built #2714 repro. It +draws a visible or fully clipped triangle and compares all 32 pixels after +the fence. Unchanged controls, both directions of a pre-submit rewrite, and +a 32-bit index view with one leading decoy element distinguish the requested +range and the time at which its contents are read. The fixture requires +support for opening existing heaps. It does not identify the index writer +or geometry used by an executable trace. + +```powershell +cmake --build --preset release --target startup_stream_consumer +ctest --preset release --no-tests=error -R '^startup_direct_index_late_write_(warp|hardware)$' -V +``` + ```powershell cmake --build --preset release --target startup_memory_srv_report_check startup_stream_consumer d3d12_xs_shim ctest --preset release --no-tests=error -R '^(startup_memory_srv_report|startup_address_srv_)' -V diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index abb29f224..f40b9f42c 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -2173,12 +2173,34 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI // The shader adds the "base vertex" entry value to the vertex index, so that value is biased by // -vertex_first and each stream's view starts at vertex_first. const UINT index_bytes = pass.ib.Format == DXGI_FORMAT_R16_UINT ? 2 : 4; - const u64 index_address = pass.ib.BufferLocation + u64{start} * index_bytes; + const u64 index_start = u64{start} * index_bytes; + const u64 index_address = pass.ib.BufferLocation + index_start; const std::size_t index_total = std::size_t{count} * index_bytes; const bool indices_ok = indexed && !indirect && pass.ib.BufferLocation && readable_window(index_address, index_total) >= index_total; + D3D12_INDEX_BUFFER_VIEW live_indices{}; + ID3D12Resource* live_index_resource = nullptr; + // A vertex-stream SRV uses the recording-time index scan to size and rebase its view. + // For other draws, a live alias lets IA observe legal CPU writes made before submission. + if (indices_ok && index_total && index_address >= pass.ib.BufferLocation && + (pass.ib.Format == DXGI_FORMAT_R16_UINT || pass.ib.Format == DXGI_FORMAT_R32_UINT) && + index_address % index_bytes == 0 && index_start <= pass.ib.SizeInBytes && + index_total <= pass.ib.SizeInBytes - index_start && + std::none_of(tr->srvs.begin(), tr->srvs.end(), [](const Translation::Srv& srv) { return srv.source == 1; })) { + const auto placed = placed_buffer_range(self->own().list_device, index_address, index_total); + if (!placed.reject && placed.alias && InterlockedCompareExchange(&placed.owner->own().refs, 0, 0)) { + const auto base = reinterpret_cast(placed.owner->own().title_memory); + const auto offset = index_address - base; + const auto gpu = placed.alias->GetGPUVirtualAddress(); + if (gpu && offset <= ~u64{} - gpu && (gpu + offset) % index_bytes == 0 && + retain_with_recording(self, x2w_startup::ComPtr(placed.alias))) { + live_indices = {gpu + offset, static_cast(index_total), pass.ib.Format}; + live_index_resource = placed.alias; + } + } + } INT vertex_first = indexed ? 0 : static_cast(start); UINT vertex_count = indexed ? 0 : count; - if (indices_ok) { + if (indices_ok && !live_index_resource) { std::uint32_t low = ~0u, high = 0; for (UINT k = 0; k < count; ++k) { const std::uint32_t value = index_bytes == 2 ? reinterpret_cast(index_address)[k] @@ -2546,11 +2568,14 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI drawn = true; } else if (indexed) { u64 offset = 0; - const u64 address = index_address; - const std::size_t bytes = index_total; - if (indices_ok && frame_copy(address, bytes, &offset)) { - const D3D12_INDEX_BUFFER_VIEW view{upload_ring->GetGPUVirtualAddress() + offset, static_cast(bytes), - index_bytes == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT}; + auto view = live_indices; + if (live_index_resource) { + require_state(self, live_index_resource, D3D12_RESOURCE_STATE_INDEX_BUFFER); + } else if (indices_ok && frame_copy(index_address, index_total, &offset)) { + view = {upload_ring->GetGPUVirtualAddress() + offset, static_cast(index_total), + index_bytes == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT}; + } + if (view.BufferLocation) { list->IASetIndexBuffer(&view); const auto red_samples = red_producer_draw_before(self, list, "translated-draw", tr->key); list->DrawIndexedInstanced(count, instances ? instances : 1, 0, 0, start_instance); diff --git a/tests/startup_direct_index_late_write_check.py b/tests/startup_direct_index_late_write_check.py new file mode 100644 index 000000000..1c567925c --- /dev/null +++ b/tests/startup_direct_index_late_write_check.py @@ -0,0 +1,56 @@ +"""A translated direct indexed draw uses the aliased view's pre-submit contents.""" +from pathlib import Path +import re +import subprocess +import sys +import tempfile + +from startup_address_srv_check import prepare_draw_cache + +VERTEX = """ +float4 main(uint vertex : SV_VertexID) : SV_Position { + uint corner = vertex % 3; + float2 xy = float2(corner == 1 ? 3.0 : -1.0, corner == 2 ? -3.0 : 1.0); + return float4(xy.x + (vertex >= 3 ? 8.0 : 0.0), xy.y, 0.5, 1.0); +} +""" +PIXEL = "float4 main() : SV_Target { return float4(1, 0, 0, 1); }" +VISIBLE = bytes((255, 0, 0, 255)) +CLIPPED = bytes((0, 0, 255, 255)) +CASES = ( + ("visible", VISIBLE), + ("clipped", CLIPPED), + ("late-visible", VISIBLE), + ("late-clipped", CLIPPED), + ("late-visible-r32", VISIBLE), +) + + +def check(directory, consumer, backend): + env, args, output = prepare_draw_cache(directory, consumer, PIXEL, {}, "", vertex_hlsl=VERTEX) + env["X2W_D3D12_DEBUG"] = "1" + for mode, color in CASES: + output.unlink(missing_ok=True) + result = subprocess.run([*args, backend, output], env={**env, "X2W_TEST_INDEX_PROBE": mode}, + capture_output=True, text=True, errors="replace", timeout=20) + if result.returncode == 77: + print(result.stdout, result.stderr) + return 77 + if result.returncode or re.search(r"x2w-d3d12-debug [^\n]*sev=[01]\b", result.stderr): + raise RuntimeError(f"{mode} failed ({result.returncode})\n{result.stdout}\n{result.stderr[-4000:]}") + if not re.search(r"slot133[^\n]*-> 0x00000000 aliased gpuva=", result.stderr): + raise AssertionError(f"{mode}: index buffer was not aliased\n{result.stderr[-4000:]}") + if not re.search(r"indexed\(3, 1, start [01], base 0\)[^\n]*-> drawn;", result.stderr): + raise AssertionError(f"{mode}: translated indexed draw was not recorded\n{result.stderr[-4000:]}") + pixels = output.read_bytes() + if pixels != color * 32: + raise AssertionError(f"{mode}: got {pixels.hex()}, expected 32 pixels of {color.hex()}") + adapter = next(line for line in result.stdout.splitlines() if line.startswith("adapter=")) + debug_layer = "enabled" if "debug layer: 0x00000000 enabled" in result.stderr else "unavailable" + print(f"{mode}: 32 exact pixels, {adapter}, debug layer {debug_layer}") + return 0 + + +if __name__ == "__main__": + with tempfile.TemporaryDirectory() as temporary: + sys.exit(check(Path(temporary), *sys.argv[1:])) diff --git a/tests/startup_stream_draw.cpp b/tests/startup_stream_draw.cpp index a99e0c19a..f8d331add 100644 --- a/tests/startup_stream_draw.cpp +++ b/tests/startup_stream_draw.cpp @@ -307,7 +307,46 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* auto* queue = frame.queue; auto* fence = frame.fence; if (export_word) invoke(list, 40, 0, 1, arg(&export_word), 0); - if (GetEnvironmentVariableW(L"X2W_TEST_LOGICAL_VIEW", nullptr, 0)) { + char index_probe[32]{}; + GetEnvironmentVariableA("X2W_TEST_INDEX_PROBE", index_probe, sizeof(index_probe)); + void* index_resource = nullptr; + if (index_probe[0]) { + bool initial_visible = false, final_visible = false; + const bool wide_indices = !std::strcmp(index_probe, "late-visible-r32"); + if (!std::strcmp(index_probe, "visible")) initial_visible = final_visible = true; + else if (!std::strcmp(index_probe, "late-visible") || wide_indices) final_visible = true; + else if (!std::strcmp(index_probe, "late-clipped")) initial_visible = true; + else if (std::strcmp(index_probe, "clipped")) return 70; + D3D12_FEATURE_DATA_EXISTING_HEAPS capability{}; + if (FAILED(desktop->CheckFeatureSupport(D3D12_FEATURE_EXISTING_HEAPS, &capability, sizeof(capability))) || !capability.Supported) + return 77; + void* index_memory = VirtualAlloc(nullptr, 65536, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + if (!index_memory) return 71; + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, 256, 1, 1, 1, + DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; + if (FAILED(static_cast(invoke(guest, 133, arg(index_memory), arg(&desc), + D3D12_RESOURCE_STATE_COMMON, 0, arg(&__uuidof(ID3D12Resource)), arg(&index_resource)))) || + !index_resource || invoke(index_resource, 11) != arg(index_memory)) return 72; + const auto write = [&](bool visible) { + const UINT first = visible ? 0 : 3; + if (wide_indices) { + auto* words = static_cast(index_memory); + words[0] = 9; // Not part of the draw. A binding that misses the start offset sees this index. + for (UINT i = 0; i < 3; ++i) words[i + 1] = first + i; + } else { + auto* words = static_cast(index_memory); + for (UINT i = 0; i < 3; ++i) words[i] = static_cast(first + i); + } + }; + write(initial_visible); + const D3D12_INDEX_BUFFER_VIEW index_view{arg(index_memory), wide_indices ? 16u : 6u, + wide_indices ? DXGI_FORMAT_R32_UINT : DXGI_FORMAT_R16_UINT}; + const D3D12_RECT full{0, 0, static_cast(width), static_cast(height)}; + invoke(list, 22, 1, arg(&full)); + invoke(list, 47, arg(&index_view)); + invoke(list, 13, 3, 1, wide_indices ? 1 : 0, 0, 0); + write(final_visible); + } else if (GetEnvironmentVariableW(L"X2W_TEST_LOGICAL_VIEW", nullptr, 0)) { if (int result = draw_logical_tables(desktop.Get(), guest, list)) return result; } else if (GetEnvironmentVariableW(L"X2W_TEST_PLACED_VERTEX", nullptr, 0)) { extern int draw_placed_vertices(ID3D12Device*, void*, void*); @@ -498,6 +537,7 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* last = 2; } if (const int rc = submit(last)) return rc; + if (index_resource) invoke(index_resource, 2); // The backing heap can outlive the resource. if (GetEnvironmentVariableW(L"X2W_TEST_PIXEL_UAV", nullptr, 0)) { extern int report_pixel_uavs(const char*); if (const int rc = report_pixel_uavs(pixels)) return rc; From 1c3abf59aa8948d67dbef752c3382ca622025d27 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?As=C4=B1m=20Mirza=20=C3=87iftler?= <113895866+Asimmimx@users.noreply.github.com> Date: Thu, 26 Nov 2026 07:25:34 +0300 Subject: [PATCH 130/240] runtime: validate ApuAlloc outputs and synchronize AcpHal heap range queries (#1902) * runtime: validate ApuAlloc outputs and synchronize AcpHal heap range queries * runtime: refuse ApuCreateHeap sizes above the 4 GiB APU range Co-Authored-By: Claude Sonnet 5.5 --------- Co-authored-by: tedin7 Co-authored-by: Claude Sonnet 5.5 --- docs/startup-runtime.md | 14 +++-- src/startup_stubs/acphal.cpp | 99 ++++++++++++++++++++++++------- tests/startup_acphal_apu_free.cpp | 55 +++++++++++++++++ 3 files changed, 141 insertions(+), 27 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 78047747d..bd7ab3f18 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -2736,14 +2736,18 @@ longer exhausts the heap. While nothing has been freed the offsets are the ones - A block is aligned in address (a power of two, 16 at least; 0, anything below 16 and a value that is not a power of two all mean 16). Size and alignment are 32 bits. `ApuCreateHeap` creates and publishes the heap under one lock, so - competing first calls cannot reset a heap that already has live blocks. -- Null output is `E_POINTER`; size 0 is `E_INVALIDARG`; no - room, or a full extent table, is `E_OUTOFMEMORY`. A refused call leaves the heap and the optional - APU-address output as they were, and writes null to the virtual-address output when non-null. + competing first calls cannot reset a heap that already has live blocks. A heap whose 64 KiB-rounded size + exceeds 4 GiB is refused with `E_INVALIDARG` without committing memory, so every block fits the APU range. +- Null or non-writable output (`virtual_address` or optional `apu_address`) is `E_POINTER` without + allocating; size 0 is `E_INVALIDARG`; no room, an offset past 32 bits, or a full extent table is + `E_OUTOFMEMORY`. A refused call leaves the heap and the optional APU-address output as they were, + and writes null to the virtual-address output when writable. - A block that is reused is zeroed, as fresh heap memory is. - `ApuFree(NULL)` is `S_OK`. An address that does not start a live block (never allocated, inside a block, already freed) is `E_INVALIDARG` and changes nothing. -- `ApuIsVirtualAddressValid` and the two map calls still test the whole heap range, not live blocks. +- `ApuIsVirtualAddressValid` and the two map calls read the published heap bounds under the heap lock and + test the allocatable 32-bit APU range `[0x10000, min(heap_bytes, 4 GiB))` (excluding the unused guard + range below `0x10000`), not live blocks. The shape-context allocation (`AcpHalAllocateShapeContexts`, types other than 4) returns `E_NOTIMPL`, rolling back any already allocated XMA block and zeroing its output pointer and APU address. The source-built diff --git a/src/startup_stubs/acphal.cpp b/src/startup_stubs/acphal.cpp index c6c25a4fe..455394d5f 100644 --- a/src/startup_stubs/acphal.cpp +++ b/src/startup_stubs/acphal.cpp @@ -24,6 +24,7 @@ bool permissive() noexcept { return x2w_local::env_on("X2W_AUDIO_PERMISSIVE"); } // a freed extent is merged with free neighbours. The table is static: when it is full a request that // needs a split fails like an exhausted heap. All state is guarded by heap_lock. constexpr u64 heap_start = 0x10000; // APU address 0 stays unused +constexpr u64 heap_max_bytes = 0x100000000ull; // the APU address space: 4 GiB constexpr std::size_t max_extents = 4096; struct Extent { u64 start, size; @@ -43,6 +44,28 @@ void heap_reset() noexcept high_water = heap_start; } +void heap_snapshot(unsigned char*& base, u64& bytes) noexcept +{ + AcquireSRWLockShared(&heap_lock); + base = heap_base; + bytes = heap_bytes; + ReleaseSRWLockShared(&heap_lock); +} + +// The allocatable 32-bit APU range [heap_start, min(heap_bytes, 4 GiB)). +bool in_apu_range(const void* virtual_address, u64& offset_out) noexcept +{ + unsigned char* base = nullptr; + u64 bytes = 0; + heap_snapshot(base, bytes); + const auto address = reinterpret_cast(virtual_address); + const auto base_addr = reinterpret_cast(base); + const u64 limit = bytes > 0x100000000ull ? 0x100000000ull : bytes; + if (!base || limit <= heap_start || address < base_addr + heap_start || address - base_addr >= limit) return false; + offset_out = static_cast(address - base_addr); + return true; +} + // bytes and alignment (a power of two) are checked by the callers; both stay far below 2^63. unsigned char* heap_take(u64 bytes, u64 alignment) { @@ -154,8 +177,12 @@ extern "C" __declspec(noinline) long ApuCreateHeap(u64 rcx, u64 rdx, u64 r8, u64 AcquireSRWLockExclusive(&heap_lock); if (!heap_base) { const u64 bytes = ((cached + non_cached) + 0xFFFF) & ~u64{0xFFFF}; - void* memory = VirtualAlloc(nullptr, bytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); - if (memory) { + // The whole heap must be APU-addressable (offsets below 4 GiB), so every extent, tail included, is + // representable. A larger request is refused up front without committing memory. + void* memory = bytes > heap_max_bytes ? nullptr : VirtualAlloc(nullptr, bytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); + if (bytes > heap_max_bytes) { + hr = static_cast(0x80070057); // E_INVALIDARG + } else if (memory) { heap_bytes = bytes; heap_reset(); heap_base = static_cast(memory); @@ -210,7 +237,10 @@ extern "C" __declspec(noinline) long AcpHalAllocateShapeContexts(u64 rcx, u64 rd rollback(); return static_cast(0x8007000E); } - const u64 offset = static_cast(memory - heap_base); + unsigned char* base = nullptr; + u64 total_bytes = 0; + heap_snapshot(base, total_bytes); + const u64 offset = static_cast(memory - base); if (offset > 0xFFFFFFFFull) { heap_give(memory); rollback(); @@ -230,13 +260,12 @@ extern "C" __declspec(noinline) long AcpHalCreate(u64 rcx, u64 rdx, u64 r8, u64 { if (!permissive()) x2w_trap::fire(X2W_TRAP_MODULE, X2W_TRAP_MODULE_ID, "AcpHalCreate", 1, rcx, rdx, r8, r9, _ReturnAddress()); - static auto table = hal_table(std::make_index_sequence<48>{}); - static bool ready = false; - if (!ready) { - table[0] = reinterpret_cast(&hal_connect); - table[2] = reinterpret_cast(&hal_submit); - ready = true; - } + static const auto table = [] { + auto slots = hal_table(std::make_index_sequence<48>{}); + slots[0] = reinterpret_cast(&hal_connect); + slots[2] = reinterpret_cast(&hal_submit); + return slots; + }(); static void* const* const object = table.data(); if (!rcx || !x2w_local::writable(reinterpret_cast(rcx), sizeof(void*))) return static_cast(0x80004003); *reinterpret_cast(rcx) = &object; @@ -247,7 +276,9 @@ extern "C" __declspec(noinline) long AcpHalCreate(u64 rcx, u64 rdx, u64 r8, u64 // ApuAlloc(&virtualAddress, apuAddress* or null, size, alignment, flags) -> HRESULT (first call: // size 0x222e00, alignment 0x800, null APU-address output). Size and alignment are taken as 32 bits. // First fit; ApuFree returns blocks, and a reused block is zeroed as fresh heap memory is. -// A null output is E_POINTER, size 0 is E_INVALIDARG; an alignment below 16 or not a power of two means 16, and no room is E_OUTOFMEMORY; a failure leaves the heap as it was. +// A null or non-writable output is E_POINTER, size 0 is E_INVALIDARG; an alignment below 16 or not a +// power of two means 16, and no room (or an offset past 32 bits) is E_OUTOFMEMORY; a failure leaves +// the heap as it was. extern "C" __declspec(noinline) long ApuAlloc(void** virtual_address, std::uint32_t* apu_address, u64 size, u64 alignment, u64 flags) { @@ -257,11 +288,33 @@ extern "C" __declspec(noinline) long ApuAlloc(void** virtual_address, std::uint3 const u64 bytes = static_cast(size); u64 align = static_cast(alignment); if (align < 16 || (align & (align - 1))) align = 16; - const bool valid = bytes != 0; - unsigned char* memory = virtual_address && valid ? heap_take(bytes, align) : nullptr; - const long hr = memory ? 0 : static_cast(!virtual_address ? 0x80004003 : valid ? 0x8007000E : 0x80070057); - if (virtual_address) *virtual_address = memory; - if (memory && apu_address) *apu_address = static_cast(memory - heap_base); + const bool virtual_ok = virtual_address && x2w_local::writable(virtual_address, sizeof(void*)); + const bool apu_ok = !apu_address || x2w_local::writable(apu_address, sizeof(std::uint32_t)); + unsigned char* memory = nullptr; + u64 offset = 0; + long hr = 0; + if (!virtual_ok || !apu_ok) { + hr = static_cast(0x80004003); // E_POINTER + } else if (!bytes) { + hr = static_cast(0x80070057); // E_INVALIDARG + } else { + memory = heap_take(bytes, align); + if (memory) { + unsigned char* base = nullptr; + u64 total_bytes = 0; + heap_snapshot(base, total_bytes); + offset = static_cast(memory - base); + if (offset > 0xFFFFFFFFull) { + heap_give(memory); + memory = nullptr; + hr = static_cast(0x8007000E); // E_OUTOFMEMORY + } + } else { + hr = static_cast(0x8007000E); // E_OUTOFMEMORY + } + } + if (virtual_ok) *virtual_address = memory; + if (memory && apu_address) *apu_address = static_cast(offset); static LONG calls; if (FAILED(hr) || x2w_local::first_calls(calls, 8)) x2w_local::logf("x2w-audio ApuAlloc size=0x%llx align=0x%llx flags=0x%llx apu_out=%p -> 0x%08lx %p", bytes, align, @@ -292,8 +345,8 @@ extern "C" __declspec(noinline) int ApuIsVirtualAddressValid(void* virtual_addre if (!permissive()) x2w_trap::fire(X2W_TRAP_MODULE, X2W_TRAP_MODULE_ID, "ApuIsVirtualAddressValid", 6, reinterpret_cast(virtual_address), 0, 0, 0, _ReturnAddress()); - auto* p = static_cast(virtual_address); - const int valid = heap_base && p >= heap_base && p < heap_base + heap_bytes; + u64 offset = 0; + const int valid = in_apu_range(virtual_address, offset) ? 1 : 0; static LONG calls; if (x2w_local::first_calls(calls, 4)) x2w_local::logf("x2w-audio ApuIsVirtualAddressValid %p -> %d", virtual_address, valid); return valid; @@ -303,8 +356,11 @@ extern "C" __declspec(noinline) void* ApuMapApuAddress(u64 apu_address) { if (!permissive()) x2w_trap::fire(X2W_TRAP_MODULE, X2W_TRAP_MODULE_ID, "ApuMapApuAddress", 7, apu_address, 0, 0, 0, _ReturnAddress()); + unsigned char* base = nullptr; + u64 bytes = 0; + heap_snapshot(base, bytes); const u64 offset = static_cast(apu_address); - void* result = heap_base && offset && offset < heap_bytes ? heap_base + offset : nullptr; + void* result = base && offset >= heap_start && offset < bytes ? base + offset : nullptr; static LONG calls; if (x2w_local::first_calls(calls, 4)) x2w_local::logf("x2w-audio ApuMapApuAddress 0x%llx -> %p", offset, result); return result; @@ -315,9 +371,8 @@ extern "C" __declspec(noinline) std::uint32_t ApuMapVirtualAddress(void* virtual if (!permissive()) x2w_trap::fire(X2W_TRAP_MODULE, X2W_TRAP_MODULE_ID, "ApuMapVirtualAddress", 8, reinterpret_cast(virtual_address), 0, 0, 0, _ReturnAddress()); - auto* p = static_cast(virtual_address); - const std::uint32_t result = heap_base && p >= heap_base && p < heap_base + heap_bytes - ? static_cast(p - heap_base) : 0; + u64 offset = 0; + const std::uint32_t result = in_apu_range(virtual_address, offset) ? static_cast(offset) : 0; static LONG calls; if (x2w_local::first_calls(calls, 4)) x2w_local::logf("x2w-audio ApuMapVirtualAddress %p -> 0x%x", virtual_address, result); return result; diff --git a/tests/startup_acphal_apu_free.cpp b/tests/startup_acphal_apu_free.cpp index 960ff5fbe..181268c97 100644 --- a/tests/startup_acphal_apu_free.cpp +++ b/tests/startup_acphal_apu_free.cpp @@ -161,6 +161,23 @@ void bad_requests() std::uint32_t apu = 0xDEADBEEF; check(free_fn(nullptr) == ok, "free(null) is a no-op"); check(take(nullptr, 64) == no_pointer, "null output"); + if (void* ro = VirtualAlloc(nullptr, 0x1000, MEM_COMMIT | MEM_RESERVE, PAGE_READONLY)) { + auto* ro_ptr = static_cast(ro); + auto* ro_apu = static_cast(ro); + check(take(ro_ptr, 64, 16, &apu) == no_pointer && apu == 0xDEADBEEF, + "read-only virtual_address returns E_POINTER and leaves apu unchanged"); + out = const_cast(sentinel); + check(take(&out, 64, 16, ro_apu) == no_pointer && !out, + "read-only apu_address returns E_POINTER and zeroes virtual_address"); + out = const_cast(sentinel); + check(take(&out, 0, 16, ro_apu) == no_pointer && !out, + "read-only apu_address with size 0 returns E_POINTER"); + VirtualFree(ro, 0, MEM_RELEASE); + } else { + check(false, "VirtualAlloc PAGE_READONLY for ApuAlloc negative control"); + } + check_empty("unwritable ApuAlloc outputs"); + out = const_cast(sentinel); check(take(&out, usable + 16, 16, &apu) == no_memory && !out && apu == 0xDEADBEEF, "larger than the heap"); out = const_cast(sentinel); check(take(&out, 0xFFFFFFFFull, 16, &apu) == no_memory && !out, "size near 2^32"); @@ -283,6 +300,12 @@ void concurrent() // block that overlaps a live one, or leave a live block unfreeable. void first_creation(CreateFn create) { + // A heap that would cross 4 GiB by one byte (rounded up to 64 KiB) is refused before any memory is + // committed and leaves no heap behind; the creations below still succeed. + check(create(0xFFFFFFFFull, 2) == invalid, "heap crossing 4 GiB by one byte is refused"); + check(create(0xFFFFFFFFull, 0xFFFFFFFFull) == invalid, "two maximal 32-bit sizes are refused"); + void* refused = nullptr; + check(take(&refused, 64) == no_memory && !refused, "refused ApuCreateHeap leaves no heap"); constexpr unsigned callers = 4; std::atomic go{false}; std::atomic bad{0}; @@ -376,6 +399,23 @@ void hal_and_address_mapping() } void* hal = nullptr; check(hal_create_fn(&hal) == ok && hal != nullptr, "AcpHalCreate returns stand-in object"); + { + constexpr unsigned callers = 4; + std::atomic go{false}; + std::atomic bad{0}; + void* objects[callers] = {}; + std::vector threads; + for (unsigned id = 0; id < callers; ++id) + threads.emplace_back([&, id] { + while (!go.load()) std::this_thread::yield(); + if (hal_create_fn(&objects[id]) != ok || !objects[id]) ++bad; + }); + go = true; + for (auto& t : threads) t.join(); + check(bad.load() == 0, "concurrent AcpHalCreate calls succeed"); + for (unsigned i = 0; i < callers; ++i) + check(objects[i] == hal, "concurrent AcpHalCreate returns the same stand-in object"); + } if (hal) { auto* const* vtable = *reinterpret_cast(hal); auto connect = reinterpret_cast(vtable[0]); @@ -401,12 +441,27 @@ void hal_and_address_mapping() check(valid_fn(nullptr) == 0, "ApuIsVirtualAddressValid(null) is 0"); check(valid_fn(&failures) == 0, "ApuIsVirtualAddressValid(foreign) is 0"); check(valid_fn(heap_base - 1) == 0, "ApuIsVirtualAddressValid(before heap) is 0"); + check(valid_fn(heap_base) == 0, "ApuIsVirtualAddressValid(reserved offset 0) is 0"); + check(valid_fn(heap_base + 0x100) == 0, "ApuIsVirtualAddressValid(inside reserved guard) is 0"); + check(valid_fn(heap_base + first_offset - 1) == 0, "ApuIsVirtualAddressValid(last reserved byte) is 0"); + check(valid_fn(heap_base + first_offset) != 0, "ApuIsVirtualAddressValid(first allocatable byte) is 1"); + check(valid_fn(heap_base + heap_size - 1) != 0, "ApuIsVirtualAddressValid(last heap byte) is 1"); check(valid_fn(heap_base + heap_size) == 0, "ApuIsVirtualAddressValid(at heap end) is 0"); check(map_fn(nullptr) == 0, "ApuMapVirtualAddress(null) is 0"); check(map_fn(&failures) == 0, "ApuMapVirtualAddress(foreign) is 0"); check(map_fn(heap_base - 1) == 0, "ApuMapVirtualAddress(before heap) is 0"); + check(map_fn(heap_base) == 0, "ApuMapVirtualAddress(reserved offset 0) is 0"); + check(map_fn(heap_base + 0x100) == 0, "ApuMapVirtualAddress(inside reserved guard) is 0"); + check(map_fn(heap_base + first_offset - 1) == 0, "ApuMapVirtualAddress(last reserved byte) is 0"); + check(map_fn(heap_base + first_offset) == first_offset, "ApuMapVirtualAddress(first allocatable byte)"); + check(map_fn(heap_base + heap_size - 1) == heap_size - 1, "ApuMapVirtualAddress(last heap byte)"); check(map_fn(heap_base + heap_size) == 0, "ApuMapVirtualAddress(at heap end) is 0"); check(map_apu_fn(0) == nullptr, "ApuMapApuAddress(0) is null"); + check(map_apu_fn(1) == nullptr, "ApuMapApuAddress(1 in reserved guard) is null"); + check(map_apu_fn(0x100) == nullptr, "ApuMapApuAddress(0x100 in reserved guard) is null"); + check(map_apu_fn(first_offset - 1) == nullptr, "ApuMapApuAddress(last reserved byte) is null"); + check(map_apu_fn(first_offset) == heap_base + first_offset, "ApuMapApuAddress(first allocatable byte)"); + check(map_apu_fn(heap_size - 1) == heap_base + heap_size - 1, "ApuMapApuAddress(last heap byte)"); check(map_apu_fn(heap_size) == nullptr, "ApuMapApuAddress(heap_size) is null"); check(map_apu_fn(heap_size + 0x1000) == nullptr, "ApuMapApuAddress(past end) is null"); From 1226f02e9849c19a991eff7725c4c713ade8fe8c Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Thu, 26 Nov 2026 05:28:00 +0100 Subject: [PATCH 131/240] startup: accept compute execz live definitions whose reads are proven (#2557) * startup: prove exec writes over every path of a compute execz block A block that s_cbranch_execz skips per lane kept every exec write refused unless the block was straight-line. The check now runs a forward pass over the block: for each instruction the wave can reach from the branch it keeps the scalar words in which a skipped lane's bit is known clear on every path, branches and loops inside the block included, with the wave half each fact holds for. An exec write is accepted when it leaves exec among them. That accepts an if/else whose arms have their own s_cbranch_execz, the s_or_saveexec/s_xor switch, s_andn2_wrexec, loops, and masks built from a zero literal, when every restore reads a mask saved inside the block. A block entered by a branch from outside, a mask from before the block or from only some paths, the forms the pass does not follow and a copy of the other exec half stay refused. Case M runs an if/else block on a D3D12 device; a control that drops the switch to the else arm must mismatch. Refs #2274 Co-Authored-By: Claude Fable 5.2 * startup: accept execz live definitions whose reads exec absorbs A compute block that s_cbranch_execz skips was refused when a definition in it was live at the join. With the block's exec writes proven, a lane that skipped the block has its exec bit clear at the join, in the wave and in the one-lane model. While exec is unchanged since the join on every path, W & exec, exec & W, ~(W & exec) and W | ~exec give that lane a result independent of W. Accept the definition when every read of it from the join on, until W is written again, is such a read; otherwise keep the refusal and name the first read that is not proven. Case N runs the join form `s_and_b32 S, vcc_lo, exec_lo` on the GPU path, with control n-unmasked dropping the AND. Co-Authored-By: Claude Opus 5.5 * gfx2hlsl: cache instruction parsing in the exec-write dataflow The exec-write pass parsed the same instruction text once per visit and join_writes rescanned every instruction for every branch. Cache the parse and the clear shape per text, and compute the written registers once. Three large compute requests: 19.1 s -> 8.4 s, same refusals. Co-Authored-By: Claude Fable 5.2 * startup: accept execz live masks the block only narrows by clear lanes A mask W defined in a compute execz block and read after the join was refused. When every write of W in the block is `s_andn2 W, W, X` and the exec-write pass proves X clear, at that instruction and on every path from the branch, for a lane that skipped the block, the lane keeps its bit of W, so W at the join holds the model's bit. Accept reads after the join that take bit n of the result from bit n of W in the same wave half and write it to that half's exec word or back to W. Copies, data reads, other writes of W and blocks entered from outside stay refused. Case O narrows the saved mask in the block and restores exec from it at the join, with control o-mask-kept dropping the narrowing. Co-Authored-By: Claude Opus 5.5 * startup: refuse a narrowed execz mask written again in the block Add the negative control that turns red when the narrowed-mask rule joins the kept halves of a word's writes by union instead of intersection, and leave the new device controls unpinned like case M's until a dispatch records their first mismatch. Co-Authored-By: Claude Opus 5.5 * startup: keep the execz live-read proof cheap on large programs The live-read proof walked the whole program for every live word and recomputed the exec-unchanged map for every join, which more than doubled the time spent in execz_refusals on large compute programs. Compute each word's verdict only when an instruction needs it, stop the search at the first read that is not proven, skip kept_halves for writes that are not s_andn2, and replace the exec-unchanged map with a check that the read ends a straight run from the join, which only the block enters, with no exec write in it. That check is narrower than the map; the measured join shapes all read at or right after the join. A loop that re-enters the join after the exec restore is a new negative control. Co-Authored-By: Claude Opus 5.5 * docs: tidy the execz live-definition wording Co-Authored-By: Claude Opus 5.5 * tests: pin the joined numeric-use refusal after the EXEC proof * tests: rename this change's compute fixture N to NM (clashes with the waterfall fixture from main) * shader: track the vcc_hi write of a wave64 compare and refuse 32-bit reads of vcc_hi in the execz lane rules --------- Co-authored-by: Claude Fable 5.2 Co-authored-by: Royoo <3230853833@qq.com> Co-authored-by: tedin7 --- CMakeLists.txt | 3 +- docs/experiments.md | 31 ++- tests/startup_gfx2hlsl_compute_check.py | 196 ++++++++++++++++++- tests/startup_gfx2hlsl_join_symbols_check.py | 13 +- tools/startup/gfx2hlsl.py | 128 +++++++++++- 5 files changed, 348 insertions(+), 23 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index dbd01e826..9d345680f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4143,7 +4143,8 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(startup_gfx2hlsl_compute_mbcnt_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) foreach(control IN ITEMS swapped-axes dropped-store b-offset c-unpredicated f-peer f-broadcast g-swapped-offsets g-overlap - j-scalar-dropped h-inner-unpredicated k-block-entered m-else-unswitched n-dropped-broadcast) + j-scalar-dropped h-inner-unpredicated k-block-entered m-else-unswitched n-unmasked o-mask-kept + n-dropped-broadcast) add_test(NAME startup_gfx2hlsl_compute_${control}_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_compute_check.py" control ${control} "${DXC_EXECUTABLE}" "$" ${adapter}) diff --git a/docs/experiments.md b/docs/experiments.md index 03f2053dd..7c6a5415d 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15320,6 +15320,28 @@ covers a nested `if`, an `if`/`else` whose arms have their own `s_cbranch_execz` restore reads a mask saved inside the block. The proof starts at the branch, so it is not run for a block that a branch from outside enters. +A definition of an SGPR or `vcc` that is live at the join is still accepted when exec absorbs every read of +it. With the block's exec writes proven, a skipped lane's exec bit is clear at the join, in the wave and in +the model. In the straight run that starts at the join, which only the block enters, and before any exec +write in it, `W & exec` and `exec & W` (`s_and`) give that lane 0, and `~(W & exec)` (`s_nand`) and +`W | ~exec` (`s_orn2` with exec second) give it 1, whatever the block left in W. The search follows every path +from the join until W is written again. Any other read keeps the refusal: a copy, a data read, a branch on +`vccz`, an absorbed form after an exec write or a branch target, or one at a join that a loop re-enters. The +reason names the first such read the search meets. `m0` and SCC have implicit readers and are not accepted +this way. Case N runs a compare in a block whose join computes `s_and_b32 s23, vcc_lo, exec_lo` before it restores +exec; its control `n-unmasked` drops the AND, so the two lanes that skip the block store with a stale `vcc`. +`s_nand` on a lane mask is still refused by the lane-mask lowering itself. + +A mask that the block only narrows is also accepted. When every write of W in the block is +`s_andn2 W, W, X` and the exec-write pass shows X clear for a skipped lane at that instruction, on every path +from the branch, the lane keeps its bit of W, so W at the join holds the model's bit. A read after the join is +then proven when it is a bitwise mask operation that takes bit n of its result from bit n of W, in the same +half of the wave, and writes that result to the exec word of that half or back to W, such as the restore +`s_mov_b32 exec_lo, W`. A copy of W into another register, a data read, a write of W of another form, X not +known clear, or a block that a branch from outside enters keeps the refusal. Case O narrows the saved mask +with `s_andn2_b32 s0, s0, exec_lo` in the block and the join moves s0 into exec; its control `o-mask-kept` +drops the narrowing, so the lanes the block handled store again. + Each instruction's reads and writes come from its printed operands, checked against the repository decoder's spelling: - `v_cmpx` prints no destination (its e64 form prints an unused SDST field), so all of its operands are reads; @@ -15327,7 +15349,7 @@ decoder's spelling: - `v_div_fmas` reads `vcc`; - the high half of a mask is tracked apart from the low half. -One live definition is accepted, the lane mask of the compiler's if-conversion: a 32-bit mask M (`vcc_lo` or one +A third live definition is accepted, the lane mask of the compiler's if-conversion: a 32-bit mask M (`vcc_lo` or one SGPR) that `s_mov_b32 M, 0` zeroes before the branch, with only straight-line code between the zeroing and the branch, and that the block sets only with `s_mov_b32 M, exec_lo` or `s_and_b32 M, X, exec_lo` (either operand order). Exec only narrows in the block, so each such write leaves the bit of a lane whose exec bit is clear at 0. @@ -15338,9 +15360,10 @@ be the lane select of `v_cndmask`, the carry-in of `v_addc`, `v_subb`, `v_add_co as a data operand see the other lanes' bits, which the one-lane model does not have, and keep the refusal. The block is still refused in these cases: -- a definition that is live at the join, other than the lane mask above (or one of its conditions fails: zeroing - with a value other than 0 or missing, a branch or a branch target between the zeroing and the branch, a write - of M that is not from exec, a `vcc_hi` or 64-bit write, a whole-mask read after the join); +- a definition that is live at the join, unless the absorbed-read or narrowed-mask rule proves every read of it + or it is the lane mask above; a lane mask with a failed condition stays refused (zeroing with a value other + than 0 or missing, a branch or a branch target between the zeroing and the branch, a write of M that is not + from exec, a `vcc_hi` or 64-bit write, a whole-mask read after the join); - any other exec write: exec set from a compare alone, restored from a mask saved before the block or on only some of the paths, written by a form the pass does not follow (`s_orn2`, `s_nand`, `s_nor`, `s_xnor`, `s_not`, the other saveexec and wrexec forms), written in a block that a branch from outside enters (a proven diff --git a/tests/startup_gfx2hlsl_compute_check.py b/tests/startup_gfx2hlsl_compute_check.py index 82b5921ec..7bc8f20a1 100644 --- a/tests/startup_gfx2hlsl_compute_check.py +++ b/tests/startup_gfx2hlsl_compute_check.py @@ -4,7 +4,7 @@ binary reassemble the fixture sources and compare them with the words below dispatch translate, compile with DXC cs_6_0, dispatch and compare every word - control + control the same dispatch with a mutated translation, which must mismatch The fixtures are source-built gfx1013 compute programs. The root signature puts two root constants (key, stride) @@ -31,6 +31,10 @@ - case M is case H with an if/else in the skipped block: each arm has its own s_cbranch_execz, s_andn2_b32 of the saved mask switches to the else arm and s_mov_b32 restores it. Lanes tid.x < 3 store the first word, lanes 3-5 the second, the rest none. +- case N skips a block that only sets vcc from a compare; the join ANDs vcc with exec before it restores exec, and + the result selects the storing lanes. Lanes tid.x < 3 store one word; lanes 6 and 7 skip the block with vcc set. +- case O removes the lanes tid.x < 3 from the saved mask with s_andn2_b32 s0, s0, exec_lo inside the skipped block, + and the join moves s0 into exec. Lanes 3-7 store one word; lanes 6 and 7 skip the block and keep their bit. - case G reads two independently offset LDS dwords with the address in the first destination VGPR. - cases L-uint and L-unorm use the same formatted load with native descriptor stride and word 3 supplied by the harness. The descriptor selects unaligned UINT16 pairs or an UNORM8 field and permutes the outputs. @@ -277,6 +281,67 @@ def tidig(components): '6a03febe' '0e0088bf' '07051693' '16041680' '16060a3a' '8300887d' '6a3c80be' '020088bf' '001070e004050480' '007e7e8a' '030088bf' '056f0c7e' '041070e004060480' '0003febe' '1503febe' '000081bf') +# Case NM skips a block that only sets vcc from a compare (lanes tid.x < 3 of the lanes tid.x < 6 that enter it); +# the join masks vcc with exec (s_and_b32 s23, vcc_lo, exec_lo) before it restores exec, and s23 later selects +# the lanes that store. vcc is all ones before the branch, so lanes 6 and 7, which skip the block, hold a stale +# vcc that only the exec mask removes. +SOURCE_NM = """\ +s_mov_b32 s10, s6 +s_mov_b32 s11, 0 +s_load_dwordx8 s[12:19], s[10:11], 0x0 +s_waitcnt lgkmcnt(0) +s_lshl_b32 s20, s7, 3 +v_add_nc_u32 v3, s20, v0 +v_lshlrev_b32 v4, 2, v3 +s_mov_b32 s21, exec_lo +v_cmp_gt_u32 vcc_lo, 6, v0 +s_and_saveexec_b32 s0, vcc_lo +s_mov_b32 vcc_lo, -1 +s_cbranch_execz 1 +v_cmp_gt_u32 vcc_lo, 3, v0 +s_and_b32 s23, vcc_lo, exec_lo +s_or_b32 exec_lo, exec_lo, s0 +v_xor_b32 v5, s4, v3 +s_mov_b32 exec_lo, s23 +buffer_store_dword v5, v4, s[16:19], 0 offen +s_mov_b32 exec_lo, s21 +s_endpgm +""" +WORDS_NM = bytes.fromhex( + '06038abe' '80038bbe' '05030cf4000000fa' '7fc08cbf' '0783148f' '1400064a' '82060834' '7e0395be' '8600887d' + '6a3c80be' 'c103eabe' '010088bf' '8300887d' '6a7e1787' '7e007e88' '04060a3a' '1703febe' '001070e004050480' + '1503febe' '000081bf') + +# Case O enters the block with the lanes tid.x < 6 (s_and_saveexec_b32 s0 saves all eight), narrows exec to the +# lanes tid.x < 3 and removes them from the saved mask with s_andn2_b32 s0, s0, exec_lo inside the block; the join +# moves s0 into exec. Lanes 3-5 lose their bit nowhere and lanes 6 and 7 skip the block with theirs, so lanes 3-7 +# store one word. +SOURCE_O = """\ +s_mov_b32 s10, s6 +s_mov_b32 s11, 0 +s_load_dwordx8 s[12:19], s[10:11], 0x0 +s_waitcnt lgkmcnt(0) +s_lshl_b32 s20, s7, 3 +v_add_nc_u32 v3, s20, v0 +v_lshlrev_b32 v4, 2, v3 +s_mov_b32 s21, exec_lo +v_cmp_gt_u32 vcc_lo, 6, v0 +s_and_saveexec_b32 s0, vcc_lo +s_cbranch_execz 3 +v_cmp_gt_u32 vcc_lo, 3, v0 +s_and_b32 exec_lo, exec_lo, vcc_lo +s_andn2_b32 s0, s0, exec_lo +s_mov_b32 exec_lo, s0 +v_xor_b32 v5, s4, v3 +buffer_store_dword v5, v4, s[16:19], 0 offen +s_mov_b32 exec_lo, s21 +s_endpgm +""" +WORDS_O = bytes.fromhex( + '06038abe' '80038bbe' '05030cf4000000fa' '7fc08cbf' '0783148f' '1400064a' '82060834' '7e0395be' '8600887d' + '6a3c80be' '030088bf' '8300887d' '7e6a7e87' '007e008a' '0003febe' '04060a3a' '001070e004050480' '1503febe' + '000081bf') + def saveexec_fixture(): # RDNA 2 ISA, SOP1: D takes old EXEC, then EXEC takes the bitwise result and SCC reports nonzero. # A single-thread group makes the lane bit the whole participating wave mask. @@ -459,6 +524,8 @@ def saveexec_fixture(): 'J': (SOURCE_J, WORDS_J, USER7 | TGID_X | tidig(1), (8, 1, 1), (4, 1, 1)), 'H': (SOURCE_H, WORDS_H, USER7 | TGID_X | tidig(1), (8, 1, 1), (4, 1, 1)), 'M': (SOURCE_M, WORDS_M, USER7 | TGID_X | tidig(1), (8, 1, 1), (4, 1, 1)), + 'NM': (SOURCE_NM, WORDS_NM, USER7 | TGID_X | tidig(1), (8, 1, 1), (4, 1, 1)), + 'O': (SOURCE_O, WORDS_O, USER7 | TGID_X | tidig(1), (8, 1, 1), (4, 1, 1)), 'K': (SOURCE_K, WORDS_K, USER7 | TGID_X | tidig(1), (8, 1, 1), (4, 1, 1)), 'G': (SOURCE_G, WORDS_G, USER7 | TGID_X | (1 << 15), (64, 1, 1), (2, 1, 1)), **{name: (SOURCE_L, WORDS_L, USER7, (16, 1, 1), (1, 1, 1)) for name in L_WORD3}, @@ -728,6 +795,14 @@ def expected(name): out[2 * i] = value elif tx < 6: # the else arm; lanes 6 and 7 skip the block out[2 * i + 1] = ~value & MASK + elif name == 'NM': + i = gx * 8 + tx + if tx < 3: # vcc & exec: the compare's lanes; lanes 6 and 7 skip it with vcc set + out[i] = i ^ KEY + elif name == 'O': + i = gx * 8 + tx + if tx >= 3: # the saved mask less the lanes the block kept; 6 and 7 skip it + out[i] = i ^ KEY elif name == 'J': i = gx * 8 + tx if tx < 3: # the lanes the compare leaves active; the others skip the block @@ -1382,6 +1457,123 @@ def block(*lines): } } ''') + # A definition live where the block joins whose reads are all absorbed by exec. The block's exec writes are + # proven, so a lane that skipped it has its exec bit clear at the join in the wave as in the model; while exec is + # unchanged since the join, W & exec and exec & W give that lane 0 and ~(W & exec) and W | ~exec give it 1, + # whatever W holds. Accepted at the join (case N runs the first on the GPU), and when the read overwrites W. + SPLICE.update({ + 's_and_b32 s23, vcc_lo, exec_lo': '6a7e1787', 's_and_b32 s23, exec_lo, vcc_lo': '7e6a1787', + 's_nand_b32 s23, vcc_lo, exec_lo': '6a7e178c', 's_orn2_b32 s23, vcc_lo, exec_lo': '6a7e178b', + 's_and_b32 vcc_lo, vcc_lo, exec_lo': '6a7e6a87', 's_orn2_b32 s23, exec_lo, vcc_lo': '7e6a178b', + 's_mov_b32 s23, vcc_lo': '6a0397be', 's_and_b32 s23, vcc_lo, exec_hi': '6a7f1787', 's_and_b32 s23, vcc_hi, exec_lo': '6b7e1787', + 's_cbranch_scc1 65533': 'fdff85bf'}) + compare = ['s_cbranch_execz 1', 'v_cmp_gt_u32 vcc_lo, 3, v0'] + for read in ('s_and_b32 s23, vcc_lo, exec_lo', 's_and_b32 s23, exec_lo, vcc_lo', 's_orn2_b32 s23, vcc_lo, exec_lo', + 's_and_b32 vcc_lo, vcc_lo, exec_lo'): + translate('A', code=splice(*enter, *compare, read, *leave, 's_cbranch_vccz 1', 'v_mov_b32 v5, s20') + if read.startswith('s_and_b32 vcc') else splice(*enter, *compare, read, *leave)).hlsl_cs() + assert translate('NM').hlsl_cs().endswith('''\ + if (pc == 1) { + vcc = (exec & ((0x00000003u > v0) ? 1u : 0u)); + pc = 2; + } + if (pc == 2) { + s23 = (vcc & exec) & 1; + scc = s23 != 0; + exec = (exec | s0) & 1; + scc = exec != 0; + if (exec & 1) v5 = ud0 ^ v3; + exec = (s23) & 1; + a = (v4 + 0) & 0xfffffffcu; + if (exec & 1) u0.Store(a, v5); + exec = (s21) & 1; + pc = 0xffffu; + } +} +''') + # Refused: a read once exec has been restored, a copy, exec | ~vcc (vcc decides), exec_hi in the low half, the + # vcc branch after an absorbed read, and an absorbed read at the join that a loop re-enters after the restore + # (exec is no longer the join's there). The reason names the first read that is not proven. + live = 'v_cmp_gt_u32_e32 inside a block s_cbranch_execz skips per lane: definition of vcc, live where the block joins' + for before, after, name in (([], ['s_and_b32 s23, vcc_lo, exec_lo'], 's_and_b32'), + (['s_mov_b32 s23, vcc_lo'], [], 's_mov_b32'), + (['s_orn2_b32 s23, exec_lo, vcc_lo'], [], 's_orn2_b32'), + (['s_and_b32 s23, vcc_lo, exec_hi'], [], 's_and_b32'), + (['s_and_b32 s23, vcc_lo, exec_lo'], ['s_cbranch_vccz 1', 'v_mov_b32 v5, s20'], + 's_cbranch_vccz'), + (['s_and_b32 s23, vcc_lo, exec_lo'], ['s_cbranch_scc1 65533'], 's_and_b32')): + refused('%s: read by %s after the join' % (live, name), lambda before=before, after=after: translate( + 'A', code=splice(*enter, *compare, *before, *leave, *after)).hlsl_cs()) + # Wave64: the compare writes vcc_hi too (its decoded text names vcc_lo only). A 32-bit read of vcc_hi after the join + # is not lane-wise against exec_lo, so it is refused where the same read of vcc_lo above is accepted. + refused('v_cmp_gt_u32_e32 inside a block s_cbranch_execz skips per lane: definition of vcc_hi, live where the block ' + 'joins: read by s_and_b32 after the join', + lambda: translate('A', code=splice(*enter, *compare, *leave, 's_and_b32 s23, vcc_hi, exec_lo')).hlsl_cs()) + assert G.exec_absorbs('s_and_b32', 's_and_b32 s2, vcc_hi, exec_lo', 'vcc_hi') is False + # The rule on its own: which reads exec absorbs for a word. + for line, word, absorbed in (('s_and_b32 s2, s3, exec_lo', 's3', True), ('s_and_b64 s[2:3], exec, s[4:5]', 's5', True), + ('s_nand_b32 s2, exec_lo, s3', 's3', True), ('s_orn2_b32 s2, s3, exec_lo', 's3', True), + ('s_orn2_b32 s2, exec_lo, s3', 's3', False), ('s_or_b32 s2, s3, exec_lo', 's3', False), + ('s_and_b32 s2, s3, s3', 's3', False), ('s_and_b64 s[2:3], s[4:5], exec', 's4', True), + ('s_and_b64 s[2:3], s[4:5], s[4:5]', 's4', False), ('s_and_b32 s2, s3, exec_hi', 's3', False), + ('s_and_b64 s[2:3], s[4:5], exec_lo', 's4', False)): + assert G.exec_absorbs(line.split()[0], line, word) == absorbed, line + # A mask the block only narrows by lanes whose exec bit is clear for a skipped lane: `s_andn2 R, R, X` with X + # clear for that lane (the exec-write proof's fact at that instruction) keeps its bit of R, so at the join it is + # the model's. Reads that take bit n of the result from bit n of R, for the same half, and write it to that exec + # word or back to R are then the model's too. Accepted on the restore after the block (case O runs it on the GPU). + SPLICE.update({'s_andn2_b32 s0, s0, exec_lo': '007e008a', 's_andn2_b32 s0, s0, s21': '0015008a', + 's_mov_b32 s1, s0': '000381be', 's_add_u32 s23, s0, 1': '00811780'}) + save = ['s_mov_b32 s21, exec_lo', 'v_cmp_gt_u32 vcc_lo, 1, v0', 's_and_saveexec_b32 s0, vcc_lo'] + translate('A', code=splice(*save, 's_cbranch_execz 1', 's_andn2_b32 s0, s0, exec_lo', 's_mov_b32 exec_lo, s0', + *leave)).hlsl_cs() + assert translate('O').hlsl_cs().endswith('''\ + if (pc == 1) { + vcc = (exec & ((0x00000003u > v0) ? 1u : 0u)); + exec = (exec & vcc) & 1; + scc = exec != 0; + s0 = (s0 & ~exec) & 1; + scc = s0 != 0; + pc = 2; + } + if (pc == 2) { + exec = (s0) & 1; + if (exec & 1) v5 = ud0 ^ v3; + a = (v4 + 0) & 0xfffffffcu; + if (exec & 1) u0.Store(a, v5); + exec = (s21) & 1; + pc = 0xffffu; + } +} +''') + # Refused: X not clear (the mask saved before the block), another write of s0 in the block, alone or after the + # narrowing, a copy and a data read after the join, and a block that a branch from outside enters (the fact is + # not proven there). + kept = ' inside a block s_cbranch_execz skips per lane: definition of s0, live where the block joins: read by %s ' \ + 'after the join' + for prefix, body, join, inner, name in ( + ([], ['s_andn2_b32 s0, s0, s21'], [], 's_andn2_b32', 's_mov_b32'), + ([], ['s_mov_b32 s0, 4'], [], 's_mov_b32', 's_mov_b32'), + ([], ['s_andn2_b32 s0, s0, exec_lo', 's_mov_b32 s0, 4'], [], 's_andn2_b32', 's_mov_b32'), + ([], ['s_andn2_b32 s0, s0, exec_lo'], ['s_mov_b32 s1, s0'], 's_andn2_b32', 's_mov_b32'), + ([], ['s_andn2_b32 s0, s0, exec_lo'], ['s_add_u32 s23, s0, 1'], 's_andn2_b32', 's_add_u32'), + (['s_cbranch_scc1 1'], ['s_andn2_b32 s0, s0, exec_lo'], [], 's_andn2_b32', 's_mov_b32')): + refused(inner + kept % name, lambda prefix=prefix, body=body, join=join: translate('A', code=splice( + *save, *prefix, 's_cbranch_execz %d' % len(body), *body, *join, 's_mov_b32 exec_lo, s0', *leave)).hlsl_cs()) + # The rule's steps on their own: the halves a write keeps, and the reads that keep the lane's bit. + for line, word, clear, halves in (('s_andn2_b32 s0, s0, exec_lo', 's0', start, {0}), + ('s_andn2_b64 s[0:1], s[0:1], exec', 's1', start, {1}), + ('s_andn2_b64 s[0:1], s[0:1], exec', 's1', {('exec', 0)}, set()), + ('s_andn2_b32 s0, s0, exec_hi', 's0', start, {1}), + ('s_andn2_b32 s0, s1, exec_lo', 's0', start, set()), + ('s_or_b32 s0, s0, exec_lo', 's0', start, set())): + assert G.kept_halves(line.split()[0], line, word, clear) == halves, line + for line, word, halves, ok in (('s_mov_b32 exec_lo, s0', 's0', {0}, True), ('s_mov_b32 exec_lo, s0', 's0', {1}, False), + ('s_mov_b64 exec, s[0:1]', 's1', {1}, True), ('s_mov_b64 exec, s[0:1]', 's1', {0}, False), + ('s_andn2_b32 s0, s0, exec_lo', 's0', {0}, True), ('s_mov_b32 s1, s0', 's0', {0}, False), + ('s_and_b32 exec_lo, s0, exec_hi', 's0', {0}, False), + ('s_mov_b32 exec_hi, s0', 's0', {1}, False)): + assert G.lane_read(line.split()[0], line, word, halves) == ok, line # The compiler's i1-phi lane mask: M is zeroed before the branch, set from exec in the block, and read per lane # after the join. For a lane the model skips, the wave's M bit is 0 either way (exec only narrows in the block), # which is the model's M. Accepted for vcc_lo and for an sN, with a move or an s_and in either operand order. @@ -1500,6 +1692,8 @@ def check_binary(llvm_mc): 'j-scalar-dropped': ('J', ' s22 = s7 * ud1;\n', ''), 'h-inner-unpredicated': ('H', 'if (exec & 1) u0.Store(a, v5);', 'u0.Store(a, v5);'), 'm-else-unswitched': ('M', 'exec = (s0 & ~exec) & 1;', 'exec = (s0) & 1;'), # the then lanes run the else arm + 'n-unmasked': ('NM', 's23 = (vcc & exec) & 1;', 's23 = (vcc) & 1;'), # lanes 6 and 7 store with their stale vcc + 'o-mask-kept': ('O', 's0 = (s0 & ~exec) & 1;', 's0 = (s0) & 1;'), # lanes 0-2 keep their bit and store 'k-block-entered': ('K', 'pc = ((exec & 1) == 0) ? 2 : 1;', 'pc = 1; exec = 1;'), # skipped waves run it 'g-swapped-offsets': ('G', 'v6 = lds[(a + 20u) >> 2];\n v7 = lds[(a + 144u) >> 2];', 'v6 = lds[(a + 144u) >> 2];\n v7 = lds[(a + 20u) >> 2];'), diff --git a/tests/startup_gfx2hlsl_join_symbols_check.py b/tests/startup_gfx2hlsl_join_symbols_check.py index cda6bc966..ff5d2f224 100644 --- a/tests/startup_gfx2hlsl_join_symbols_check.py +++ b/tests/startup_gfx2hlsl_join_symbols_check.py @@ -362,8 +362,8 @@ def rhs(text): exec_join_refused(JOINED_S16, and_s16, **only_skips) # a plain run-time number on every path is no joined register: the read is the ordinary one; assert ' s16 = (s16 & exec) & 1;' in exec_join_hlsl(and_s16, before=cmp_ne(16, 0)) - # a compute stage is left out: the pre-pass refuses a definition inside the skipped block that the target reads, - # and with the pre-pass out of the way the target's read is refused as it was, not absorbed. + # The compute pre-pass can now prove the lane absorption, but the scalar value is still a + # joined descriptor/number, so lowering must still refuse its numeric use. cs = (bytes.fromhex('06038abe80038bbe05030cf4000000fa7fc08cbf') + cmp_ne(30, 0) + sop2(S_AND_B64, EXEC, EXEC, 30) + sopp(EXECZ, 2) + cmp_ne(12, 0) + sop2(S_AND_B64, 12, 12, EXEC) + bytes.fromhex('0c02027e000081bf')) import startup_gfx2hlsl_compute_check as C @@ -374,13 +374,8 @@ def refusal_of_cs(): except G.Unsupported as reason: return str(reason) raise AssertionError('compute accepted') - assert 'definition of s12, live where the block joins' in refusal_of_cs() - pre_pass = G.Stage.execz_refusals - G.Stage.execz_refusals = lambda self: {} - try: - assert refusal_of_cs() == 'numeric use of s12 holding joined at a branch target', refusal_of_cs() - finally: - G.Stage.execz_refusals = pre_pass + reason = refusal_of_cs() + assert reason == 'numeric use of s12 holding joined at a branch target', reason # Without the lowering every accepted form is refused where it reads s16. absorbed = G.Stage.exec_absorbed_source G.Stage.exec_absorbed_source = lambda self, base, srcs: None diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index e91368432..f33c70de3 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -750,6 +750,58 @@ def clear_after(name, asm, may, clear): return out | {(word, h) for word, held in writes for h in held} +def mask_lanes(name, asm): + """(operation, destination words, source word lists) of a bitwise scalar mask instruction, or None. Word p of + every operand holds the same lanes: wave half p of a 64-bit form.""" + m = re.fullmatch(r's_(mov|and|andn2|or|orn2|nand|nor|xor|xnor)_b(32|64)', re.sub(r'_e(32|64)$', '', name)) + if not m: + return None + words = [mask_words(op, 2 if m.group(2) == '64' else 1) for op in parse(asm)[1]] + if None in words or len(words) != (2 if m.group(1) == 'mov' else 3): + return None + return m.group(1), words[0], words[1:] + + +def high_half_of_b32(lanes, word): + """True for a 32-bit form that names the high half of a mask (vcc_hi): its bit n is lane 32 + n, which the word + position of a one-word operand (always the low half) does not say, so no lane-wise rule applies to it.""" + return word.endswith('_hi') and len(lanes[1]) == 1 + + +def exec_absorbs(name, asm, word): + """True when an instruction reads `word` only through an operation whose result bit is fixed while the exec bit + of the same lanes is clear: W & exec and exec & W give 0, ~(W & exec) and W | ~exec give 1.""" + lanes = mask_lanes(name, asm) + if not lanes or lanes[0] not in ('and', 'nand', 'orn2') or high_half_of_b32(lanes, word): + return False + a, c = lanes[2] + pairs = [(a, c)] if lanes[0] == 'orn2' else [(a, c), (c, a)] + return any(word in w and word not in e and all(e[p] == ('exec', 'exec_hi')[p] for p in range(len(w)) if w[p] == word) + for w, e in pairs) + + +def kept_halves(name, asm, word, clear): + """Wave halves whose lanes keep their bit of `word` through `s_andn2 R, R, X` when X is clear for them: R & ~X + keeps bit n of R when bit n of X is clear. Empty for any other write of `word`.""" + lanes = mask_lanes(name, asm) + if not lanes or lanes[0] != 'andn2' or lanes[1] != lanes[2][0]: + return set() + return {h for p, w in enumerate(lanes[1]) if w == word for key, h in clear if key == lanes[2][1][p]} + + +def lane_read(name, asm, word, halves): + """True when an instruction reads `word` as a lane mask, bit n of each result from bit n of the sources, with + `word` in a position whose lanes are in `halves`, any exec operand there the exec word of those lanes, and the + result there written to that exec word or back to `word`, not copied to another register.""" + lanes = mask_lanes(name, asm) + if not lanes or high_half_of_b32(lanes, word): + return False + _, dest, srcs = lanes + at = {p for src in srcs for p, w in enumerate(src) if w == word} + return bool(at) and at <= halves and all(dest[p] in (word, ('exec', 'exec_hi')[p]) for p in at) and all( + w == ('exec', 'exec_hi')[p] for src in srcs for p, w in enumerate(src) if p in at and w in EXEC_KEYS) + + def scalar_effects(name, asm): """(reads, must-writes, may-writes) of scalar state for one decoded instruction.""" base = re.sub(r'_e(32|64)$', '', name) @@ -781,6 +833,9 @@ def scalar_effects(name, asm): may |= EXEC_KEYS if (base in SCA and SCA[base][1]) or 'saveexec' in base or 'wrexec' in base: writes.add('scc') + # A wave64 compare or carry-out prints its mask destination in the 32-bit spelling vcc_lo but writes vcc_hi too. + if 'vcc' in writes and base.startswith(('v_cmp', 'v_add_co', 'v_sub_co', 'v_subrev_co', 'v_div_scale')): + may.add('vcc_hi') return reads, writes, writes | may | ({'scc'} if base.startswith('s_') else set()) # Forms with no scalar destination: their printed operands are all sources (v_cmpx writes only EXEC, which the @@ -2500,10 +2555,12 @@ def execz_refusals(self): the block (its branches and loops included), which masks have that lane's bit clear, and the write must leave exec among them. Such a lane's bit then stays clear at every instruction the wave runs in the block, so the wave changes nothing of that lane there and its exec at the join is the model's. The proof starts at - the branch, so a block that a branch from outside enters keeps its exec writes refused. A live definition, - an unproven exec write, a refused effect, a branch leaving the block or a backward s_cbranch_execz is - refused. - One live definition is accepted: the i1-phi lane mask of the compiler's if-conversion, a 32-bit M (vcc_lo + the branch, so a block that a branch from outside enters keeps its exec writes refused. A definition live at + the join is accepted when every read of it after the join is proven (execz_live_read), or when it has the + shape below. Any other live definition, an unproven exec write, a refused effect, a branch leaving the block + or a backward s_cbranch_execz is refused. + + The other accepted live definition is the i1-phi lane mask of the compiler's if-conversion, a 32-bit M (vcc_lo or one sN) zeroed before the branch (`s_mov_b32 M, 0`) and set in the block from exec only (`s_mov_b32 M, exec_lo`, `s_and_b32 M, X, exec_lo` in either operand order). Every write of M in the block yields a value whose bit is 0 for any lane whose exec bit is clear there: the clear-mask proof keeps exec clear for that lane, and a copy of exec, or X & exec, has that bit clear. M is 0 @@ -2544,7 +2601,9 @@ def execz_refusals(self): and self.ins[head][2] == 'v_readfirstlane_b32' and self.ins[close - 1][2] == 's_andn2_wrexec_b32'): self.waterfall_reads[target] = self.waterfall_refusal(head, close, effects, live_in, jumps) - refused = {} + refused, into = {}, {} + for k, target in jumps: + into.setdefault(index.get(target), []).append(k) for b, (off, n, name, asm) in enumerate(self.ins): if name != 's_cbranch_execz': continue @@ -2571,6 +2630,20 @@ def execz_refusals(self): not any(index.get(target) in range(b + 1, t) for target in targets) cand = {k for i in range(b + 1, t) for k in (effects[i][2] - EXEC_KEYS) & live if re.fullmatch(r'vcc|s\d+', k)} ok_masks = {k for k in cand if straight and self.phi_mask_ok(k, b, t, effects, succ, targets, index)} + # A live definition is still accepted when every read of it from the join on is proven (execz_live_read): + # the halves whose lanes keep their bit of the word through the block, and where exec is unchanged since + # the join on every path from it. + kept = {} + for i in range(b + 1, t): + for word in (effects[i][2] - EXEC_KEYS) & live: + if kept.get(word, True): # an empty set stays empty + andn2 = i in before and not entered and self.ins[i][2].startswith('s_andn2') + halves = kept_halves(*self.ins[i][2:], word, before[i]) if andn2 else set() + kept[word] = kept.get(word, halves) & halves + def quiet(j): # exec unchanged since the join on every path to j: a straight run from t, entered at t only + return t <= j and all(b <= k < t for k in into.get(t, ())) and not any( + effects[k][2] & EXEC_KEYS for k in range(t, j)) and not any(k in into for k in range(t + 1, j + 1)) + unread = {} for i in range(b + 1, t): at, _, inner, inner_asm = self.ins[i] may = effects[i][2] @@ -2583,13 +2656,52 @@ def execz_refusals(self): elif may & EXEC_KEYS and (entered or i in before and not entry <= clear_after(inner, inner_asm, may, before[i])): reason = 'exec write' - elif (may - EXEC_KEYS - ok_masks) & live: - reason = 'definition of %s, live where the block joins' % ', '.join( - sorted((may - EXEC_KEYS - ok_masks) & live)) + elif words := [word for word in sorted((may - EXEC_KEYS - ok_masks) & live) + if self.execz_live_read(t, word, kept[word], effects, succ, quiet, unread) is not None]: + named = [unread[word] for word in words if unread[word] >= 0] + reason = 'definition of %s, live where the block joins' % ', '.join(words) + ( + ': read by %s after the join' % self.ins[min(named)][2] if named else '') if reason: refused.setdefault(at, '%s inside a block s_cbranch_execz skips per lane: %s' % (inner, reason)) return refused + def execz_live_read(self, t, word, halves, effects, succ, quiet, unread): + """None when every read of `word` from the join t of an execz block on, until a write of it ends the block's + definition, gives a lane the model skipped the wave's result; else the first read that is not proven, or -1 + for m0 and SCC, which have implicit readers. + + Such a lane's exec bit is clear at the join, in the model and in the wave (execz_refusals proves the block's + exec writes), and the two differ there at most in `word`. A read is proven when: + - exec is unchanged on every path from the join to it (`quiet`: the read ends a straight run that starts at + the join, which only the block enters, with no exec write in it) and it reads `word` only as W & exec, + ~(W & exec) or W | ~exec, exec of the same lanes (exec_absorbs): the lane's bit of the result is fixed + whatever its bit of `word` is, so the result agrees, and when it overwrites `word` the definition ends; + - the block keeps the lane's bit of `word` for its half (kept_halves: every write of `word` in the block is + s_andn2 R, R, X with X clear for the lane, checked over every path from the branch) and the read is a lane + mask read of that half (lane_read): the lane's bit of `word` is the model's, so its bit of the result is + too, and `word` written back that way keeps the property. + Any other read, a data read or a copy into another register included, is not proven. The search stops at + the first such read, nearest the join; the result is kept in `unread` for the block.""" + if word in unread: + return unread[word] + if not re.fullmatch(r'vcc(_hi)?|s\d+', word): + unread[word] = -1 + return -1 + seen, work = {t}, [t] + for j in work: # breadth first: the list grows while it is read + name, asm = self.ins[j][2:] + kept_read = word in effects[j][0] and halves and lane_read(name, asm, word, halves) + if word in effects[j][0] and not kept_read and not (exec_absorbs(name, asm, word) and quiet(j)): + unread[word] = j + return j + if kept_read or word not in effects[j][1]: + for s in succ[j]: + if s not in seen: + seen.add(s) + work.append(s) + unread[word] = None + return None + def waterfall_refusal(self, head, close, effects, live_in, jumps): """Return None when the lane can pick its own key at the head of the waterfall. From 343dc04fe0fc6c395ba2ddb56e9e320878bb1d52 Mon Sep 17 00:00:00 2001 From: archielcqp-a11y <307535386+archielcqp-a11y@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:33:01 -0500 Subject: [PATCH 132/240] compute: lower group-shared LDS and s_barrier on gfx1013 (#1566) * compute: lower group-shared LDS and s_barrier on gfx1013 compute_store_aot had only the gfx1030 private-LDS profile, so every gfx1013 DS instruction and s_barrier was refused (issue #1541). With --cpu gfx1013 --lds-bytes N, LDS becomes groupshared uint lds[N / 4], shared by the whole group. Accepted: - ds_write/read_b32, _b64 and _b128; - write2/read2 and their st64 forms at b32 and b64; - the non-returning add, sub, and, or, xor, min_u32 and max_u32 updates, as Interlocked* operations; - s_barrier. Every DS instruction is followed by a group barrier. The group therefore sees DS operations in program order, as one wave does. Barriers need uniform control flow, so DS after a lane guard is refused. A word outside the allocation reads as zero and is not written. compute_store_aot_lds_shared runs eight 64-thread programs on one and two groups on WARP and hardware. They exchange words between lanes through every form, and a counter program checks the atomics. Three assembly mutations must mismatch at their first changed word. The controls cover the barrier count and the rejections, and the binary mode round-trips the programs through LLVM 15 for gfx1013. AI-assisted (Claude Code); reviewed and run locally. Co-Authored-By: Claude Opus 5.5 * compute: scope shared LDS to one guest wave and state its input contract A barrier after every DS instruction gives the group one wave's DS order. With several guest waves it would also order DS operations between waves before s_barrier, which the guest program does not guarantee. The shared LDS profile is therefore one guest wave per group: - at most 32 threads is one wave at either width and needs no statement; - 33 to 64 threads need --wave-size 64, now accepted only together with a gfx1013 shared LDS allocation; - larger groups, and more than 32 threads under --wave-size 32, are refused. The input contract is stated in the docstring and docs, and is not checked: accesses are in bounds and aligned, every word a read or atomic touches was written earlier in the group, and no two lanes of one non-atomic write store to the same word. The fixtures state wave64. New controls accept a 32-thread group without a statement and refuse 64 threads without one, 64 threads and a 32 x 2 group under wave32, 128 threads under wave64, and wave64 without a shared allocation or on gfx1030. Another control requires the allocation guard on every LDS access. The two-group isolation run is kept. Refs #1541 AI-assisted (Claude Code); reviewed and run locally. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: tedin7 --- CMakeLists.txt | 5 + docs/experiments.md | 82 ++++++++++++ tests/compute_store_check.py | 238 ++++++++++++++++++++++++++++++++++- tools/compute_store_aot.py | 149 +++++++++++++++++++++- 4 files changed, 465 insertions(+), 9 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 9d345680f..97d7158fe 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -10232,6 +10232,11 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(compute_store_aot_lds_private_${adapter} PROPERTIES TIMEOUT 45 SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/compute_store_aot_lds_private_${adapter}.txt") + add_test(NAME compute_store_aot_lds_shared_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/compute_store_check.py" draw-lds-shared "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(compute_store_aot_lds_shared_${adapter} PROPERTIES TIMEOUT 45 SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/compute_store_aot_lds_shared_${adapter}.txt") add_test(NAME compute_store_aot_lds_packed_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/compute_store_check.py" draw-lds-packed "${DXC_EXECUTABLE}" "$" ${adapter}) diff --git a/docs/experiments.md b/docs/experiments.md index 7c6a5415d..d7a67116d 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -5573,6 +5573,88 @@ because their per-lane regions can overlap. The fixtures compare every UAV word and detect a wrong qword offset, a missing data word, or reversed dual read offsets at word 0. +### Group-shared LDS on gfx1013 + +`--cpu gfx1013 --lds-bytes N` declares a group LDS allocation of N bytes (a multiple of 4, at most the +32 KiB D3D12 groupshared limit) and lowers LDS as `groupshared uint lds[N / 4]`, shared by every thread of +the group ([#1541](https://github.com/R0Y00/Xbox2Windows/issues/1541)). gfx1013 has no private LDS +profile, so the allocation alone selects this mode; without it, DS instructions and `s_barrier` are +refused as before. `v_lshlrev_b32 vD, k, vL` on a local-ID VGPR gives an address word +`local << k`, and the existing integer ALU subset combines address words. Each DS instruction reads its +byte address from a VGPR, adds the instruction offset (`offset0`/`offset1` in elements of the access +size, times 64 for the `st64` forms), and accesses word `(address >> 2) + i`. The accepted forms are: + +- `ds_write_b32`, `ds_read_b32`, `ds_write_b64`, `ds_read_b64`, `ds_write_b128` and `ds_read_b128`; +- `ds_write2_b32`, `ds_read2_b32`, `ds_write2st64_b32`, `ds_read2st64_b32`, `ds_write2_b64`, + `ds_read2_b64`, `ds_write2st64_b64` and `ds_read2st64_b64`, with two different offsets; +- the non-returning `ds_add_u32`, `ds_sub_u32`, `ds_and_b32`, `ds_or_b32`, `ds_xor_b32`, `ds_min_u32` and + `ds_max_u32`, as HLSL `Interlocked*` operations (`ds_sub_u32` adds the negated value); +- `s_barrier`. + +The profile is one guest wave per group. A group of at most 32 threads is one wave at either guest wave +width and needs no statement. A group of 33 to 64 threads needs `--wave-size 64`, the caller's statement that +the program runs as wave64; that statement is accepted only with a shared LDS allocation. Larger groups, and +groups of more than 32 threads under `--wave-size 32`, are several guest waves and are refused. + +Within that one wave, DS instructions take effect in program order: every DS instruction is followed by +`GroupMemoryBarrierWithGroupSync()`, so a read sees the writes of every earlier instruction from all lanes +and a later write cannot overtake an earlier read. The HLSL barrier waits for the whole group, which on the +desktop may run as several host waves; with one guest wave this reproduces the guest order. With several +guest waves the per-instruction barriers would also order DS operations between waves before `s_barrier`, +which the guest program does not guarantee, so that case is left until it has its own native comparison. +`s_barrier` becomes the same barrier and adds one only where no DS barrier precedes it. Barriers need +uniform control flow, so a DS instruction or `s_barrier` after a lane guard is refused. + +The caller guarantees the LDS input contract, which is not checked: +- every access is in bounds and aligned: b32 accesses to 4 bytes, wider ones to their size; +- every word that a read or an atomic touches was written earlier in the group; +- no two lanes of one non-atomic write store to the same word. + +Outside the contract, each access is still guarded by `index < N / 4`: a word past the allocation reads as +zero and is not written, and the low two address bits are dropped. That rule keeps an access from reaching +other words; it is not compared with hardware. Not lowered yet: the returning (`_rtn`) forms, whose results depend on the +order of lanes that update one word; `ds_write_b96`/`ds_read_b96`; byte, short and d16 accesses; signed +min/max; float atomics; and `ds_permute`/`ds_bpermute` and the other lane-routing forms on gfx1013. + +`compute_store_aot_lds_shared` runs eight 64-thread wave64 programs with a 1024-byte allocation on one and +two groups (one group for the four-word programs), and compares every UAV word with a CPU reference. Each lane +writes its own words, and after a barrier reads another lane's: +- the next lane's word and the mirrored lane's word (`63 - l`); +- pairs 64 words apart through `write2`/`read2` and `st64`; +- a qword and qword pairs, written with `ds_write2_b64` and read with `ds_read2st64_b64`, and the other way + round; +- a 16-byte record of the next lane. + +A counter program sets seven words, has every lane add, subtract, AND, OR, XOR, take the minimum and take +the maximum of its index or a mixed word, and reads them back. With two groups, each group's sums cover +only its own threads, which shows that each group has its own LDS. Three mutations of the programs must +mismatch at the first word they change: +- the next-but-one lane, at word 0; +- an `st64` read spelled as a plain `read2`, at word 1; +- `ds_min_u32` in place of `ds_max_u32`, at word 11. + +The translation controls check the barrier count, the `Interlocked*` methods, the allocation guard on every +access and the rejections listed above. The one-wave controls accept a 32-thread group without a statement +and refuse 64 threads without one, 64 threads and a 32 x 2 group under wave32, 128 threads under wave64, and +the wave64 statement without a shared allocation or on gfx1030. Every program is also assembled and disassembled with LLVM 15 for gfx1013, and the CLI must emit the +same HLSL. + +Measured on `b96960b` with this change, Windows 10 build 19045: + +| Adapter | Result | Debug layer | +|---|---|---| +| WARP 1.0.22 (the app-local `d3d10warp.dll`) | passed | enabled | +| NVIDIA GeForce RTX 3080, driver 32.0.15.9174 | passed | enabled | + +The mutations mismatched at their expected words on both adapters. Of the gfx1013 forms in +`tools/form_coverage.py`, the test adds only `s_barrier`, because the gfx1030 private-LDS fixtures already +record the DS mnemonics. + +```powershell +cmake --build --preset dev --target offscreen_check +ctest --preset dev --no-tests=error -R '^compute_store_aot_lds_shared_(warp|hardware)$' -V +``` + An optional `--constant-descriptor BYTE_OFFSET` binds a second table entry to b0. It must be distinct from the 16-byte u0 descriptor. The translator accepts aligned immediate `s_buffer_load_dword`, `s_buffer_load_dwordx2`, and diff --git a/tests/compute_store_check.py b/tests/compute_store_check.py index 8848bf567..1a26f7e5b 100644 --- a/tests/compute_store_check.py +++ b/tests/compute_store_check.py @@ -5107,17 +5107,19 @@ def lds_controls(): lines[:i + 1] + lines[i + 2:], 32, **LDS_BINDING) -def gfx1030_binary(directory, assembler, objcopy, library, cases, prefix, group=32): +def gfx1030_binary(directory, assembler, objcopy, library, cases, prefix, group=32, *, cpu="gfx1030", + features=DS_FEATURES): dims = aot.checked_group(group) + attributes = [f"-mattr={features}"] if features else [] for name, lines, binding in cases: src, obj, raw = (directory / f"{name}.{ext}" for ext in ("s", "o", "bin")) src.write_text("\n".join(lines) + "\n", encoding="ascii") - subprocess.run([assembler, "-triple=amdgcn--amdpal", "-mcpu=gfx1030", f"-mattr={DS_FEATURES}", + subprocess.run([assembler, "-triple=amdgcn--amdpal", f"-mcpu={cpu}", *attributes, "-filetype=obj", src, "-o", obj], check=True) subprocess.run([objcopy, "-O", "binary", "--only-section=.text", obj, raw], check=True) code = raw.read_bytes() - decoded = aot.labelled(disassemble(code, library, offsets=True, cpu=b"gfx1030", - features=DS_FEATURES.encode())) + decoded = aot.labelled(disassemble(code, library, offsets=True, cpu=cpu.encode(), + features=(features or "").encode())) assert [line for line in decoded if line.startswith(prefix)] == [ line for line in lines if line.startswith(prefix)] expected = aot.lower(lines, dims, **binding) @@ -5417,6 +5419,231 @@ def ds_draw(directory, compiler, renderer, backend, *, private=False, cases=None return 0 +# Group-shared LDS on gfx1013 (issue #1541): one 64-thread group per program, LDS words written by one lane and +# read by another. Lane l of group g has tid = 64 * g + l; v5 = l * 4 is its word address, v8 its index. +SHARED_PREFIX = ["s_mov_b32 s12, s7", "s_mov_b32 s13, 0", "s_load_dwordx4 s[20:23], s[12:13], 0x30", + "v_lshl_add_u32 v8, s11, 6, v0", "s_waitcnt lgkmcnt(0)", "v_lshlrev_b32_e32 v5, 2, v0"] +SHARED_BINDING = dict(table_reg=7, descriptor_offset=0x30, group_reg=11, stride=8, cpu="gfx1013", lds_bytes=1024, + wave_size=64) +# Without an allocation the wave64 statement is refused, so the no-LDS controls drop it. +SHARED_NO_LDS = {key: value for key, value in SHARED_BINDING.items() if key != "wave_size"} | {"lds_bytes": 0} +SHARED_WIDE_BINDING = SHARED_BINDING | {"stride": 16} +SHARED_MIRROR = "v_sub_nc_u32_e32 v9, 0xfc, v5" # (63 - l) * 4 +SHARED_DATA = ["v_add_nc_u32_e32 v6, 0x10000000, v8", "v_add_nc_u32_e32 v7, 0x20000000, v8"] +# The atomic operand: an odd multiplier spreads the lanes' bits over the word. +SHARED_MIX = 0x9e3779b1 +SHARED_PROGRAMS = { + # Own word, then the next lane's word and the mirrored lane's word. + "shared_exchange": (SHARED_BINDING, [ + "v_add_nc_u32_e32 v6, 0x12340000, v8", "ds_write_b32 v5, v6", "s_waitcnt lgkmcnt(0)", "s_barrier", + "v_add_nc_u32_e32 v7, 4, v5", "v_and_b32_e32 v7, 0xfc, v7", "ds_read_b32 v10, v7", "s_waitcnt lgkmcnt(0)", + SHARED_MIRROR, "ds_read_b32 v11, v9", "s_waitcnt lgkmcnt(0)", + "buffer_store_dwordx2 v[10:11], v8, s[20:23], 0 idxen"]), + # Two words per lane, 64 words apart, written and read as pairs of the mirrored lane. + "shared_pair_b32": (SHARED_BINDING, [ + *SHARED_DATA, "ds_write2_b32 v5, v6, v7 offset1:64", "s_waitcnt lgkmcnt(0)", "s_barrier", + SHARED_MIRROR, "ds_read2_b32 v[10:11], v9 offset1:64", "s_waitcnt lgkmcnt(0)", + "buffer_store_dwordx2 v[10:11], v8, s[20:23], 0 idxen"]), + # The same layout through st64: offset 1 is 64 elements. + "shared_pair_st64_b32": (SHARED_BINDING, [ + *SHARED_DATA, "ds_write2st64_b32 v5, v6, v7 offset1:1", "s_waitcnt lgkmcnt(0)", + SHARED_MIRROR, "ds_read2st64_b32 v[10:11], v9 offset1:1", "s_waitcnt lgkmcnt(0)", + "buffer_store_dwordx2 v[10:11], v8, s[20:23], 0 idxen"]), + # A qword per lane at l * 8, read back from the mirrored lane. + "shared_b64": (SHARED_BINDING, [ + *SHARED_DATA, "v_lshlrev_b32_e32 v4, 3, v0", "ds_write_b64 v4, v[6:7]", "s_waitcnt lgkmcnt(0)", + "v_sub_nc_u32_e32 v9, 0x1f8, v4", "ds_read_b64 v[10:11], v9", "s_waitcnt lgkmcnt(0)", + "buffer_store_dwordx2 v[10:11], v8, s[20:23], 0 idxen"]), + # Two qwords per lane 64 qwords apart, written with write2 and read with read2st64, and the other way round. + "shared_pair_b64": (SHARED_WIDE_BINDING, [ + *SHARED_DATA, "v_add_nc_u32_e32 v12, 0x30000000, v8", "v_add_nc_u32_e32 v13, 0x50000000, v8", + "v_lshlrev_b32_e32 v4, 3, v0", "ds_write2_b64 v4, v[6:7], v[12:13] offset1:64", "s_waitcnt lgkmcnt(0)", + "v_sub_nc_u32_e32 v9, 0x1f8, v4", "ds_read2st64_b64 v[14:17], v9 offset1:1", "s_waitcnt lgkmcnt(0)", + "buffer_store_dwordx4 v[14:17], v8, s[20:23], 0 idxen"]), + "shared_pair_st64_b64": (SHARED_WIDE_BINDING, [ + *SHARED_DATA, "v_add_nc_u32_e32 v12, 0x30000000, v8", "v_add_nc_u32_e32 v13, 0x50000000, v8", + "v_lshlrev_b32_e32 v4, 3, v0", "ds_write2st64_b64 v4, v[6:7], v[12:13] offset1:1", "s_waitcnt lgkmcnt(0)", + "v_sub_nc_u32_e32 v9, 0x1f8, v4", "ds_read2_b64 v[14:17], v9 offset1:64", "s_waitcnt lgkmcnt(0)", + "buffer_store_dwordx4 v[14:17], v8, s[20:23], 0 idxen"]), + # Four words per lane at l * 16, read back from the next lane. + "shared_b128": (SHARED_WIDE_BINDING, [ + "v_add_nc_u32_e32 v10, 0x10000000, v8", "v_add_nc_u32_e32 v11, 0x20000000, v8", + "v_add_nc_u32_e32 v12, 0x30000000, v8", "v_add_nc_u32_e32 v13, 0x50000000, v8", + "v_lshlrev_b32_e32 v4, 4, v0", "ds_write_b128 v4, v[10:13]", + "s_waitcnt lgkmcnt(0)", "v_add_nc_u32_e32 v9, 16, v4", "v_and_b32_e32 v9, 0x3f0, v9", + "ds_read_b128 v[14:17], v9", "s_waitcnt lgkmcnt(0)", + "buffer_store_dwordx4 v[14:17], v8, s[20:23], 0 idxen"]), + # Every lane sets the seven counters (same values, so the overlapping writes agree), then updates them; lane l + # reports counters l & 7 and (l + 1) & 7, where counter 7 holds a constant. + "shared_atomics": (SHARED_BINDING, [ + "v_mov_b32_e32 v4, 0", "v_mov_b32_e32 v20, 0", "v_mov_b32_e32 v21, -1", "v_mov_b32_e32 v23, 0x5a5a5a5a", + "ds_write2_b32 v4, v20, v20 offset1:1", "s_waitcnt lgkmcnt(0)", + "ds_write2_b32 v4, v21, v20 offset0:2 offset1:3", "s_waitcnt lgkmcnt(0)", + "ds_write2_b32 v4, v20, v21 offset0:4 offset1:5", "s_waitcnt lgkmcnt(0)", + "ds_write2_b32 v4, v20, v23 offset0:6 offset1:7", "s_waitcnt lgkmcnt(0)", "s_barrier", + f"v_mul_lo_u32 v22, 0x{SHARED_MIX:08x}, v8", + "ds_add_u32 v4, v8", "s_waitcnt lgkmcnt(0)", "ds_sub_u32 v4, v8 offset:4", "s_waitcnt lgkmcnt(0)", + "ds_and_b32 v4, v22 offset:8", "s_waitcnt lgkmcnt(0)", "ds_or_b32 v4, v22 offset:12", "s_waitcnt lgkmcnt(0)", + "ds_xor_b32 v4, v22 offset:16", "s_waitcnt lgkmcnt(0)", "ds_min_u32 v4, v22 offset:20", "s_waitcnt lgkmcnt(0)", + "ds_max_u32 v4, v22 offset:24", "s_waitcnt lgkmcnt(0)", "s_barrier", + "v_and_b32_e32 v24, 28, v5", "ds_read_b32 v10, v24", "s_waitcnt lgkmcnt(0)", + "v_add_nc_u32_e32 v25, 4, v5", "v_and_b32_e32 v25, 28, v25", "ds_read_b32 v11, v25", "s_waitcnt lgkmcnt(0)", + "buffer_store_dwordx2 v[10:11], v8, s[20:23], 0 idxen"]), +} +SHARED_CASES = [(name, SHARED_PREFIX + lines + ["s_endpgm"], binding) + for name, (binding, lines) in SHARED_PROGRAMS.items()] +SHARED_FORMS = {"ds_write_b32", "ds_read_b32", "ds_write_b64", "ds_read_b64", "ds_write_b128", "ds_read_b128", + "ds_write2_b32", "ds_read2_b32", "ds_write2st64_b32", "ds_read2st64_b32", "ds_write2_b64", + "ds_read2_b64", "ds_write2st64_b64", "ds_read2st64_b64", "ds_add_u32", "ds_sub_u32", "ds_and_b32", + "ds_or_b32", "ds_xor_b32", "ds_min_u32", "ds_max_u32", "s_barrier"} + + +def shared_counters(group): + tids = [64 * group + lane for lane in range(64)] + mixed = [tid * SHARED_MIX & 0xffffffff for tid in tids] + total = sum(tids) & 0xffffffff + a = mixed[0] + for value in mixed[1:]: + a &= value + o = x = 0 + for value in mixed: + o |= value + x ^= value + return [total, -total & 0xffffffff, a, o, x, min(mixed), max(mixed), 0x5a5a5a5a] + + +def shared_reference(name, groups): + words = [] + for group in range(groups): + def tid(lane): + return 64 * group + lane + counters = shared_counters(group) + for lane in range(64): + mirror = 63 - lane + if name == "shared_exchange": + words += [0x12340000 + tid((lane + 1) % 64), 0x12340000 + tid(mirror)] + elif name in ("shared_pair_b32", "shared_pair_st64_b32", "shared_b64"): + words += [0x10000000 + tid(mirror), 0x20000000 + tid(mirror)] + elif name in ("shared_pair_b64", "shared_pair_st64_b64"): + words += [base + tid(mirror) for base in (0x10000000, 0x20000000, 0x30000000, 0x50000000)] + elif name == "shared_b128": + words += [base + tid((lane + 1) % 64) for base in (0x10000000, 0x20000000, 0x30000000, 0x50000000)] + else: + words += [counters[lane & 7], counters[(lane + 1) & 7]] + return words + + +def shared_mutants(name, lines, binding): + """Assembly changes the reference must catch, with the first word they change.""" + if name == "shared_exchange": + # The next-but-one lane instead of the next one. + yield variant(lines, ("v_add_nc_u32_e32 v7, 4, v5", "v_add_nc_u32_e32 v7, 8, v5")), 0 + elif name == "shared_pair_st64_b32": + # offset1:1 as 4 bytes instead of 64 elements reads the next word, the mirrored lane's neighbour. + yield variant(lines, ("ds_read2st64_b32 v[10:11], v9 offset1:1", "ds_read2_b32 v[10:11], v9 offset1:1")), 1 + elif name == "shared_atomics": + # min in place of max: lane 5 reports counter 6 as its second word. + yield variant(lines, ("ds_max_u32 v4, v22 offset:24", "ds_min_u32 v4, v22 offset:24")), 11 + + +def shared_controls(): + for name, lines, binding in SHARED_CASES: + source = aot.lower(lines, 64, **binding) + assert f"groupshared uint lds[{binding['lds_bytes'] // 4}];" in source, name + # Every DS instruction is followed by one group barrier; s_barrier adds none after it. + steps = sum(line.startswith("ds_") for line in lines) + assert source.count("GroupMemoryBarrierWithGroupSync();") == steps, name + assert "uint3 local : SV_GroupThreadID" in source, name + # Out-of-range words are outside the input contract; every access stays guarded by the allocation size. + guard = f" < {binding['lds_bytes'] // 4}u" + assert all(guard in line for line in source.splitlines() if "lds[" in line and "groupshared" not in line), name + programs = {name: lines for name, lines, _ in SHARED_CASES} + atomics = aot.lower(programs["shared_atomics"], 64, **SHARED_BINDING) + for method in ("Add", "And", "Or", "Xor", "Min", "Max"): + assert f"Interlocked{method}(lds[" in atomics, method + assert "(0u - tid.x)" in atomics + lines = programs["shared_exchange"] + # A barrier with no DS instruction before it is kept. + assert aot.lower(SHARED_PREFIX + ["s_barrier"] + lines[len(SHARED_PREFIX):], 64, + **SHARED_BINDING).count("GroupMemoryBarrierWithGroupSync();") == 4 + write = "ds_write_b32 v5, v6" + for wrong, message in ( + ("ds_add_rtn_u32 v10, v5, v6", "Unsupported shared LDS instruction"), + ("ds_write_b96 v5, v[6:8]", "Unsupported shared LDS instruction"), + ("ds_write_b8 v5, v6", "Unsupported shared LDS instruction"), + ("ds_min_i32 v5, v6", "Unsupported shared LDS instruction"), + ("ds_write_b32 v5, v6 offset:65536", "Unverified shared LDS offset"), + ("ds_write_b32 v0, v6", "Unverified shared LDS address"), + ("ds_write_b32 v5, v0", "Shared LDS data is not a known word"), + ("ds_write_b64 v5, v[6:8]", "Unverified shared LDS register range"), + ("ds_write2_b32 v5, v6, v6 offset0:3 offset1:3", "Unverified shared LDS pair offsets"), + ("ds_write2_b32 v5, v6, v6 offset1:256", "Unverified shared LDS pair offsets")): + rejects(message, aot.lower, variant(lines, (write, wrong)), 64, **SHARED_BINDING) + # Barriers need uniform control flow: no DS instruction after a lane guard. + i = lines.index(write) + guarded = lines[:i] + ["v_cmp_gt_u32_e32 vcc_lo, 16, v8", "s_and_saveexec_b32 s5, vcc_lo"] + lines[i:] + rejects("Shared LDS access under a lane guard", aot.lower, guarded, 64, **SHARED_BINDING) + rejects("Expected immediate s_waitcnt lgkmcnt(0) after DS", aot.lower, + lines[:i + 1] + lines[i + 2:], 64, **SHARED_BINDING) + for size in (0x10004 // 2, 2, 6, 32772): + rejects("Invalid shared LDS allocation", aot.lower, lines, 64, **SHARED_BINDING | {"lds_bytes": size}) + # The profile is one guest wave. 32 threads are one wave at either width and need no statement; 64 threads + # need the wave64 statement, and are two waves under wave32; 128 threads are two wave64 waves. + unstated = {key: value for key, value in SHARED_BINDING.items() if key != "wave_size"} + half = variant(lines, ("v_lshl_add_u32 v8, s11, 6, v0", "v_lshl_add_u32 v8, s11, 5, v0")) + assert "groupshared uint lds[256];" in aot.lower(half, 32, **unstated) + for group, binding in ((64, unstated), (64, SHARED_BINDING | {"wave_size": 32}), (128, SHARED_BINDING), + ((32, 2, 1), SHARED_BINDING | {"wave_size": 32})): + rejects("Shared LDS requires a group of one guest wave", aot.lower, lines, group, **binding) + # wave64 is not a lane layout outside the shared LDS profile. + rejects("Unsupported wave size statement", aot.lower, lines, 64, **SHARED_NO_LDS | {"wave_size": 64}) + rejects("Unsupported wave size statement", aot.lower, lines, 64, **SHARED_BINDING | {"cpu": "gfx1030"}) + # Without an allocation gfx1013 keeps refusing the local-ID address, DS and s_barrier. + rejects("Unverified dispatch byte offset", aot.lower, lines, 64, **SHARED_NO_LDS) + rejects("Unverified private LDS write", aot.lower, SHARED_PREFIX[:5] + lines[len(SHARED_PREFIX):], 64, + **SHARED_NO_LDS) + rejects("Unsupported compute instruction: s_barrier", aot.lower, + SHARED_PREFIX[:5] + ["s_barrier", "buffer_store_dword v8, v8, s[20:23], 0 idxen", "s_endpgm"], 64, + **SHARED_NO_LDS | {"stride": 4}) + # The CPU references differ from the mutants'. + for name, lines, binding in SHARED_CASES: + for _, first in shared_mutants(name, lines, binding): + assert first < len(shared_reference(name, 1)), name + assert {line.split()[0] for _, lines, _ in SHARED_CASES for line in lines} >= SHARED_FORMS + + +def shared_draw(directory, compiler, renderer, backend): + shared_controls() + accepted = set() + for name, lines, binding in SHARED_CASES: + source = aot.lower(lines, 64, **binding) + src, cso, case = (directory / f"{name}.{ext}" for ext in ("hlsl", "cso", "case")) + src.write_text(source, encoding="ascii") + compile = [compiler, "-T", "cs_6_0", "-E", "main", "-Fo", cso, src] + subprocess.run(compile, check=True) + run = [renderer, backend, "--compute-store-case", cso, case] + # Two groups show that each group has its own LDS; four words per lane leave room for one. + for groups in (1,) if binding["stride"] == 16 else (1, 2): + words = shared_reference(name, groups) + case.write_bytes(struct.pack("<321I", groups, *(words + [SENTINEL] * (320 - len(words))))) + execution = subprocess.run(run) + if execution.returncode: + return execution.returncode + for mutated, mismatched_word in shared_mutants(name, lines, binding): + src.write_text(aot.lower(mutated, 64, **binding), encoding="ascii") + subprocess.run(compile, check=True) + bad = subprocess.run(run, capture_output=True, text=True) + if bad.returncode != 1 or f"word={mismatched_word} expected=" not in bad.stderr: + raise AssertionError(f"{name}: shared LDS mutation escaped detection\n{bad.stderr}") + print(bad.stderr, end="") + accepted.update(line.split()[0] for line in lines) + if record := os.environ.get("FORM_COVERAGE_RECORD"): + path = Path(record) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("".join(f"{op}\n" for op in sorted(accepted)), encoding="utf-8") + return 0 + + MUBUF_STORE_VALUE = 0x12345678 MUBUF_SUBWORD_STORES = { "buffer_store_byte": (1, 0, 5), @@ -6197,6 +6424,8 @@ def binary(directory, assembler, objcopy, library): ds_controls() lds_controls() ds_binary(directory, assembler, objcopy, library) + shared_controls() + gfx1030_binary(directory, assembler, objcopy, library, SHARED_CASES, "ds_", 64, cpu="gfx1013", features=None) mtbuf_load_controls() mimg_load_binary(directory, assembler, objcopy, library) mimg_resinfo_controls() @@ -9549,6 +9778,7 @@ def descriptor_store_draw(directory, compiler, renderer, backend): "draw-lds-wide-replacement": lambda d, *a: ds_draw(d, *a, private=True, cases=LDS_WIDE_REPLACEMENT_CASES), "draw-lds-f32": lambda d, *a: ds_draw(d, *a, private=True, cases=LDS_FLOAT_CASES), "draw-lds-private": lambda d, *a: ds_draw(d, *a, private=True), + "draw-lds-shared": shared_draw, "draw-lds-packed": lambda d, *a: ds_draw(d, *a, private=True, cases=LDS_PACKED_CASES), "draw-lds-arithmetic": lambda d, *a: ds_draw(d, *a, private=True, cases=LDS_ARITHMETIC_CASES), "draw-lds-replacement": lambda d, *a: ds_draw(d, *a, private=True, cases=LDS_REPLACEMENT_CASES), diff --git a/tools/compute_store_aot.py b/tools/compute_store_aot.py index f5c274c7b..088f3b06e 100644 --- a/tools/compute_store_aot.py +++ b/tools/compute_store_aot.py @@ -243,6 +243,110 @@ "ds_max_u32": "max({0}, {1})", } +# Group-shared LDS on gfx1013 (issue #1541): the D3D12 groupshared limit, the barrier after every DS step, and the +# non-returning updates as HLSL Interlocked methods on `lds` (all are order-independent within an instruction). +LDS_SHARED_LIMIT = 32768 +LDS_BARRIER = " GroupMemoryBarrierWithGroupSync();" +LDS_SHARED_ATOMICS = {"add_u32": "Add", "sub_u32": "Add", "and_b32": "And", "or_b32": "Or", "xor_b32": "Xor", + "min_u32": "Min", "max_u32": "Max"} +LDS_SHARED_FORMS = ( + r"ds_(?Pwrite|read)_b(?P32|64|128) (?Pv\d+|v\[\d+:\d+\]), (?Pv\d+|v\[\d+:\d+\])" + r"(?: offset:(?P\d+))?", + r"ds_(?Pwrite2|write2st64)_b(?P32|64) (?Pv\d+), (?Pv\d+|v\[\d+:\d+\]), (?Pv\d+|v\[\d+:\d+\])" + r"(?: offset0:(?P\d+))?(?: offset1:(?P\d+))?", + r"ds_(?Pread2|read2st64)_b(?P32|64) (?Pv\[\d+:\d+\]), (?Pv\d+)" + r"(?: offset0:(?P\d+))?(?: offset1:(?P\d+))?", + rf"ds_(?P{'|'.join(LDS_SHARED_ATOMICS)}) (?Pv\d+), (?Pv\d+)(?: offset:(?P\d+))?", +) + + +def vgpr_range(token, count): + """The VGPR numbers of `token` (vN or v[a:b]), which must name exactly `count` registers below v256.""" + m = re.fullmatch(r"v(\d+)|v\[(\d+):(\d+)\]", token) + first, last = (int(m[1]), int(m[1])) if m[1] else (int(m[2]), int(m[3])) + if last - first + 1 != count or last > 255 or (m[1] is None and count == 1): + raise ValueError("Unverified shared LDS register range") + return list(range(first, last + 1)) + + +def shared_lds_step(line, step, vector, words): + """HLSL statements for one gfx1013 DS instruction on `groupshared uint lds[]`; updates `vector` for reads. + + The byte address is the address VGPR plus the instruction offset (offset0/offset1 in elements of the access + size, times 64 for st64), and word i of the access is lds[(address >> 2) + i]. + + Input contract, not checked: every access is in bounds and aligned (b32 to 4 bytes, wider forms to their + size); every word a read or an atomic touches was written earlier in the group; and no two lanes of one + non-atomic write store to the same word. Outside the contract a word past the allocation reads as zero and + is not written, and the low two address bits are dropped. + """ + m = next((m for form in LDS_SHARED_FORMS if (m := re.fullmatch(form, line))), None) + if m is None: + raise ValueError(f"Unsupported shared LDS instruction: {line}") + op = m["op"] + # ds_read_bNN names its destination first; every other form names the address first. + addr, data = (m["b"], m["a"]) if op == "read" else (m["a"], m["b"]) + address = vector.get(int(addr[1:])) if re.fullmatch(r"v\d+", addr) else None + if not is_word(address) or int(addr[1:]) > 255: + raise ValueError("Unverified shared LDS address") + base = f"lds_a{step}" + statements = [] + + def place(offset): + statements.append(f" uint {base} = ({hlsl_word(address)} + {offset}u) >> 2u;") + + def words_of(token, count): + values = [vector.get(reg) for reg in vgpr_range(token, count)] + if not all(map(is_word, values)): + raise ValueError("Shared LDS data is not a known word") + return list(map(hlsl_word, values)) + + def write(index, word): + statements.append(f" if ({index} < {words}u) lds[{index}] = {word};") + + def read(index, reg, name): + statements.append(f" uint {name} = {index} < {words}u ? lds[{index}] : 0u;") + vector[reg] = ("alu", name) + + single = int(m["offset"] or 0) if "offset" in m.groupdict() else 0 + if single > 65535: + raise ValueError("Unverified shared LDS offset") + if op in LDS_SHARED_ATOMICS: + place(single) + (value,) = words_of(data, 1) + if op == "sub_u32": + value = f"(0u - {value})" + method = LDS_SHARED_ATOMICS[op] + statements.append(f" if ({base} < {words}u) Interlocked{method}(lds[{base}], {value});") + return "\n".join(statements) + count = int(m["bits"]) // 32 + if op in ("write", "read"): + place(single) + indices = [f"{base} + {i}u" if i else base for i in range(count)] + if op == "write": + for index, word in zip(indices, words_of(data, count)): + write(index, word) + else: + for i, (index, reg) in enumerate(zip(indices, vgpr_range(data, count))): + read(index, reg, f"lds_r{step}_{i}") + return "\n".join(statements) + # Paired forms: two elements of `count` words at offset0 and offset1, in elements (64 elements for st64). + offsets = [int(m["offset0"] or 0), int(m["offset1"] or 0)] + if max(offsets) > 255 or offsets[0] == offsets[1]: + raise ValueError("Unverified shared LDS pair offsets") + scale = count * (64 if op.endswith("st64") else 1) + place(0) + indices = [f"{base} + {offset * scale + i}u" if offset * scale + i else base + for offset in offsets for i in range(count)] + if op.startswith("write"): + for index, word in zip(indices, words_of(m["b"], count) + words_of(m["c"], count)): + write(index, word) + else: + for i, (index, reg) in enumerate(zip(indices, vgpr_range(m["b"], 2 * count))): + read(index, reg, f"lds_r{step}_{i}") + return "\n".join(statements) + + MUBUF_ATOMIC_METHODS = { "add": "Add", "sub": "Add", "and": "And", "or": "Or", "xor": "Xor", "smin": "Min", "umin": "Min", "smax": "Max", "umax": "Max", @@ -896,7 +1000,8 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N A full-mask 2D D16 image_store requires an RGBA16 FLOAT UAV. mubuf_d16_xyz_mode opts into a caller-verified W-preserving RGBA16 store. wave_size is the caller's statement that the program runs as wave32 (32). A lane index is only - derived for a group of more than 32 threads under that statement. + derived for a group of more than 32 threads under that statement. With group-shared LDS on gfx1013 + the statement may also be 64 (wave64), which lets a group of up to 64 threads count as one guest wave. image_descriptor is the table byte offset of the 8-dword image descriptor. image_format is the caller's statement of the image format inside it. The image binds to t0 for loads or u0 for writes, where image_uav_mip selects the writable subresource and replaces descriptor_offset. @@ -1021,8 +1126,6 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N if output_format is not None and (output_format not in MUBUF_OUTPUT_FORMATS or cpu != "gfx1030" or stride is None): raise ValueError("Unsupported formatted output binding") - if wave_size not in (None, 32): - raise ValueError("Unsupported wave size statement") if mubuf_d16_xyz_mode is not None and (mubuf_d16_xyz_mode != "preserve-w" or output_format != MUBUF_D16_OUTPUT_FORMATS[4] or cpu != "gfx1030"): raise ValueError("D16 XYZ mode requires a gfx1030 RGBA16 UINT output binding") @@ -1091,6 +1194,18 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N image_step_count = 0 image_uav_address = None lds_enabled = ds_group and 128 <= lds_bytes <= 65536 + # gfx1013 has no private LDS profile; an allocation there selects group-shared LDS. + shared_lds = cpu == "gfx1013" and lds_bytes != 0 + if shared_lds and not (4 <= lds_bytes <= LDS_SHARED_LIMIT and lds_bytes % 4 == 0): + raise ValueError("Invalid shared LDS allocation") + # wave64 is stated only for the one-wave shared LDS profile; elsewhere it is not a known lane layout. + if wave_size not in (None, 32) and not (wave_size == 64 and shared_lds): + raise ValueError("Unsupported wave size statement") + # Per-instruction group barriers give the group one wave's DS order. With several guest waves the order + # before s_barrier is not fixed by the program, so the profile is one wave: at most 32 threads is one wave + # of either width, and a larger group needs the wave64 statement. + if shared_lds and dims[0] * dims[1] * dims[2] > (wave_size or 32): + raise ValueError("Shared LDS requires a group of one guest wave") lds_word = None lds_strided_words = {} lds_strided_width = None @@ -1633,6 +1748,10 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N and not alu_data_word(vector.get(int(m[3])))): dst, shift, src = map(int, m.groups()) tag = vector.get(src) + if shared_lds and dst <= 255 and shift <= 31 and isinstance(tag, tuple) and tag[0] == "local": + # A shared LDS byte address from the local ID; it is data only to the DS instructions below. + vector[dst] = ("alu", f"(local.{AXES[tag[1]]} << {shift}u)") + continue if ds_group and dst <= 255 and shift == 2 and isinstance(tag, tuple) and tag[0] == "ds_lane": vector[dst] = ("ds_address", tag[1]) continue @@ -1650,6 +1769,21 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N if dst > 255 or not (isinstance(tag, tuple) and tag[0] == "thread"): raise ValueError("Unverified dispatch byte offset") vector[dst] = ("thread_bytes", tag[1], shift) + elif shared_lds and (line == "s_barrier" or line.startswith("ds_")): + # Group-shared LDS (issue #1541). Each DS instruction becomes HLSL statements on `lds`, followed by a + # group barrier, so the group observes DS operations in program order, as one wave does; s_barrier + # adds nothing beyond that and becomes the same barrier. Barriers need uniform control flow, so no + # DS instruction may follow a lane guard. + if guard_span is not None or guard is not None: + raise ValueError("Shared LDS access under a lane guard") + if line == "s_barrier": + if not staged_steps or not staged_steps[-1][1].endswith(LDS_BARRIER): + staged_steps.append((None, LDS_BARRIER)) + continue + text = shared_lds_step(line, ds_step_count, vector, lds_bytes // 4) + ds_step_count += 1 + staged_steps.append((None, text + "\n" + LDS_BARRIER)) + ds_wait = True elif m := re.fullmatch(r"ds_(b?permute)_b32 v(\d+), v(\d+), v(\d+)", line): op, dst, addr, src = m[1], *map(int, m.groups()[1:]) address = vector.get(addr) @@ -3211,6 +3345,10 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N cbuffer += "".join(f"groupshared uint {slot}[{dims[0]}];\n" for slot in shared) if shared: local = ", uint3 local : SV_GroupThreadID" + if "local." in body: + local = ", uint3 local : SV_GroupThreadID" + if shared_lds and ds_step_count: + cbuffer += f"groupshared uint lds[{lds_bytes // 4}];\n" if "gindex" in body: local += ", uint gindex : SV_GroupIndex" # Helpers are selected from the final body, so a float ALU result used only by a DS step still gets its definition. @@ -3301,8 +3439,9 @@ def main(): parser.add_argument("--buffer-float-domain", choices=("finite-normal",), help="Required for raw fixed-address buffer_atomic_fmin/fmax. Every stored word " "and the operand is finite-normal binary32, never NaN, subnormal or signed zero.") - parser.add_argument("--wave-size", type=int, choices=(32,), - help="Caller's statement that the program runs as wave32, for lane indices in larger groups") + parser.add_argument("--wave-size", type=int, choices=(32, 64), + help="Caller's statement of the wave width: 32 for lane indices in larger groups, " + "64 (gfx1013 shared LDS only) for a group of up to 64 threads as one wave") parser.add_argument("--gather-mips", type=int, help="Visible mip count of the matching native and desktop RGBA32 FLOAT 2D gather views") args = parser.parse_args() From 418f92450d9218fe615eaa81a36d0711e0e1a870 Mon Sep 17 00:00:00 2001 From: Chad Hyatt Date: Wed, 25 Nov 2026 22:36:25 -0600 Subject: [PATCH 133/240] runtime: guard memory SRV wrapper allocation failures (#2727) * runtime: guard memory SRV wrapper allocation failures After the nullable wrapper allocation change, these helpers should return no resource when allocation fails. Keep their existing ownership and caller refusal behavior. * tests: inject memory SRV wrapper allocation failures --------- Co-authored-by: Royoo <3230853833@qq.com> --- src/startup_stubs/d3d12_memory_srv.inl | 2 ++ tests/startup_address_buffer_srv_check.py | 10 +++++++--- tests/startup_address_srv.cpp | 17 ++++++++++++++++- 3 files changed, 25 insertions(+), 4 deletions(-) diff --git a/src/startup_stubs/d3d12_memory_srv.inl b/src/startup_stubs/d3d12_memory_srv.inl index f57e607db..1252190e8 100644 --- a/src/startup_stubs/d3d12_memory_srv.inl +++ b/src/startup_stubs/d3d12_memory_srv.inl @@ -412,6 +412,7 @@ Wrapper* unplaced_memory_buffer(Wrapper* device, u64 address, u64 span_bytes, co if (!native_resource) return nullptr; Wrapper* w = wrap(native_resource.Get(), resource_kind); + if (!w) return nullptr; w->own().title_memory = reinterpret_cast(page_start); D3D12_RESOURCE_DESC rdesc{}; rdesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; @@ -539,6 +540,7 @@ Wrapper* publish_tiled_texture(Wrapper* device, u64 address, const D3D12_RESOURC } } Wrapper* resource = wrap(nullptr, resource_kind); + if (!resource) return nullptr; resource->own().title_memory = reinterpret_cast(address); resource->own().tiled_address_srv = true; note_resource(resource, &desc, bytes); diff --git a/tests/startup_address_buffer_srv_check.py b/tests/startup_address_buffer_srv_check.py index c8ebc7c8f..31a2f6283 100644 --- a/tests/startup_address_buffer_srv_check.py +++ b/tests/startup_address_buffer_srv_check.py @@ -11,12 +11,16 @@ def check_refusal_lines(log): prefix = r"x2w-d3d12 Device::slot70 " - expected = [ + buffer_unavailable = ( prefix + r"unavailable buffer at the supplied address: reason=buffer_unavailable " + r"res\{dim=1 fmt=0 size=256x1x1 mips=1 layout=0x1 flags=0x0 align=0 samples=1/0\} " - + r"view\{dim=1 fmt=39 map=0x1688 first=0 count=4 stride=0 flags=0x1 \(buffer views are not supported\)\} " - + rf"dest={HEX} dest_in_view_heap=1 address={HEX} address_readable=1", + + r"view\{dim=1 fmt=39 map=0x1688 first=FIRST count=4 stride=0 flags=0x1 \(buffer views are not supported\)\} " + + rf"dest={HEX} dest_in_view_heap=1 address={HEX} address_readable=1" + ) + expected = [ + buffer_unavailable.replace("FIRST", "4"), # injected wrapper allocation failure + buffer_unavailable.replace("FIRST", "0"), # unaligned interior address prefix + r"unavailable acceleration structure at the supplied address: reason=as_wrong_state " + r"res\{dim=1 fmt=0 size=256x1x1 mips=1 layout=0x1 flags=0x0 align=0 samples=1/0\} " diff --git a/tests/startup_address_srv.cpp b/tests/startup_address_srv.cpp index 3f0211a19..589d1d290 100644 --- a/tests/startup_address_srv.cpp +++ b/tests/startup_address_srv.cpp @@ -12,6 +12,7 @@ using Word = std::uint64_t; Word invoke(void*, unsigned, Word = 0, Word = 0, Word = 0, Word = 0, Word = 0, Word = 0, Word = 0, Word = 0); extern "C" __declspec(dllimport) void x2w_d3d12_texture_written(void* base, unsigned long long bytes); extern "C" __declspec(dllimport) void x2w_d3d12_bc7_4k_s_written(void* base, UINT width, UINT height); +extern "C" __declspec(dllimport) void x2w_d3d12_fail_wraps(LONG count); namespace { template Word ptr(T* value) { return reinterpret_cast(value); } struct ViewAt { @@ -21,6 +22,17 @@ struct ViewAt { }; static_assert(offsetof(ViewAt, address) == 0x28 && sizeof(ViewAt) == 0x40); +bool failed_publication_keeps_view(void* guest, const D3D12_RESOURCE_DESC& desc, const ViewAt& view, Word cpu) +{ + const auto* slot = reinterpret_cast(cpu); + std::array previous; + std::memcpy(previous.data(), slot, previous.size()); + x2w_d3d12_fail_wraps(1); + invoke(guest, 70, ptr(&desc), ptr(&view), cpu); + x2w_d3d12_fail_wraps(0); + return std::memcmp(previous.data(), slot, previous.size()) == 0; +} + bool bind_view_table(void* guest, void* list, Word& cpu, UINT count = 1, Word address = 0, Word bytes = 0) { struct Extended { @@ -570,6 +582,7 @@ int draw_address_buffer_srvs(ID3D12Device* desktop, void* guest, void* list) raw.address = ptr(buf1); raw.view.Buffer.FirstElement = 4; + if (!failed_publication_keeps_view(guest, desc, raw, cpu)) return 54; invoke(guest, 70, ptr(&desc), ptr(&raw), cpu); draw(2); @@ -661,7 +674,9 @@ int draw_single_element_srvs(void* guest, void* list) const auto rgba = texel(DXGI_FORMAT_R8G8B8A8_UNORM, 0); publish(rgba, view_of(rgba, ptr(memory[0]))); draw(0); const auto swizzled = texel(DXGI_FORMAT_R8G8B8A8_UNORM, 0x105); - publish(swizzled, view_of(swizzled, ptr(memory[1]))); draw(1); + const auto second_view = view_of(swizzled, ptr(memory[1])); + if (!failed_publication_keeps_view(guest, swizzled, second_view, cpu)) return 54; + publish(swizzled, second_view); draw(1); std::memcpy(memory[0], c, 4); // rewritten, then published again at the same address publish(rgba, view_of(rgba, ptr(memory[0]))); draw(2); std::memcpy(memory[0], d, 4); // rewritten without a new publication: column 3 must read it From 434aa90db1acafe1478c6cbc246ca5ea7e8a46f6 Mon Sep 17 00:00:00 2001 From: RonLogic Date: Thu, 26 Nov 2026 06:45:02 +0200 Subject: [PATCH 134/240] shader: name the unsupported implicit gather mip level (#2735) Co-authored-by: RonLogic <307541314+RonLogic@users.noreply.github.com> Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- docs/experiments.md | 4 ++++ tests/startup_image_gather_lz_check.py | 2 +- tools/startup/gfx2hlsl.py | 3 +++ 3 files changed, 8 insertions(+), 1 deletion(-) diff --git a/docs/experiments.md b/docs/experiments.md index d7a67116d..84d3e5629 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14967,6 +14967,10 @@ with normalized clamp addressing, bilinear XY, point mip filtering, and zero minimum LOD and bias. Implicit, explicit-LOD, comparison, offset, and non-2D forms remain outside this slice. +Plain `image_gather4` reports `requires the guest implicit mip level`. +Translating it through the fixed-mip path could read a different level +because Direct3D gather uses the first visible mip of the bound view. + The sampler's Z address mode (`CLAMP_Z`, SQ_IMG_SAMP_WORD0 bits 8:6) is not checked: a 2D view has no third coordinate, and the Direct3D 11.3 functional spec (22.4.2, gather4) says only the sampler's addressing modes diff --git a/tests/startup_image_gather_lz_check.py b/tests/startup_image_gather_lz_check.py index 7282c36bc..b10961de1 100644 --- a/tests/startup_image_gather_lz_check.py +++ b/tests/startup_image_gather_lz_check.py @@ -81,7 +81,7 @@ def controls(llvm_mc): refused(shader(dst=0xff), 'four destination registers') # The explicit-LOD and fixed-mip comparison gathers are lowered by their own tests; the implicit, # biased and offset gathers stay refused here. - refused(shader(opcode=0x40), 'image_gather4') + refused(shader(opcode=0x40), 'image_gather4 requires the guest implicit mip level') refused(shader(opcode=0x45), 'image_gather4_b') refused(shader(opcode=0x54), 'image_gather4_l_o') refused(shader(opcode=0x48), 'image_gather4_c') diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index f33c70de3..1e8d70e31 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -6269,6 +6269,9 @@ def gather_2d_setup(self, name, ops, mods, addr_count, addr_label, *, mip_precla tex = self.pipe.resource(key, 'tex2d') return dst, addr, words, channels[masks[0]], tex + def op_image_gather4(self, ops, mods): + raise Unsupported('image_gather4 requires the guest implicit mip level') + def op_image_gather4_lz(self, ops, mods): dst, addr, words, (channel_name, _), tex = self.gather_2d_setup( 'image_gather4_lz', ops, mods, 2, 'two contiguous address registers', mip_preclamp=True) From a768ebe03d572cda3dd4364a38d9b44eb8713f24 Mon Sep 17 00:00:00 2001 From: JB2WIN Date: Thu, 26 Nov 2026 05:48:34 +0100 Subject: [PATCH 135/240] startup: lower s_bfm_b64 in gfx2hlsl (#2007) * startup: lower s_bfm_b64 in gfx2hlsl One of the refusals in the #1723 census (1 pair). RDNA 2 SOP2 opcode 37 gives D.u64 = ((1ULL << S0[5:0]) - 1) << S1[5:0] with SCC unchanged, the 64-bit counterpart of the existing s_bfm_b32 entry. The handler writes both words of the destination pair through the shl64 helper, masks width and offset to six bits, gives 0 for width 0 and folds constant sources. New device-free check startup_gfx2hlsl_bfm_b64, covering all 64x64 width/offset pairs against a bit-loop reference. AI-assisted (Claude Code). Co-Authored-By: Claude Opus 5.5 * startup: refuse mask sources before writing s_bfm_b64 and track its uniformity Read and check both sources (refuse a source SGPR in Stage.masks) before the destination mask flags or words change, so an aliased destination cannot hide a mask source. After #1931, prove both written words uniform only when both sources are, and drop any older proof for s[d], s[d+1]. Checks: compare-derived mask refusals with and without aliasing, and stale-proof tests through v_readfirstlane_b32. AI-assisted (Claude Code). Co-Authored-By: Claude Opus 5.5 * startup: read back s_bfm_b64 on WARP and hardware and cover the mask-high-word case Review of #2007: the CPU evaluator does not exercise the HLSL compiler's own treatment of shl64, the bw >= 32u selects and uint2. - startup_gfx2hlsl_bfm_b64_check.py draw: a translated pixel stage computes s_bfm_b64 s[20:21], s8, s9 and the swapped pair from root constants (the compiler cannot fold them) and exports the four words. Widths 0/1/31/32/33/63 against offsets 0/1/31/32/63 plus sources with bits above [5:0], compared with the bit-loop reference, FXC ps_5_1 and DXC ps_6_0. Negative controls shown in the draw: a reference without the cap at bit 63, and a mutated lowering (width 0 reads all ones). - startup_gfx2hlsl_bfm_b64_warp and _hardware (skip 77) registered. - --startup-flat-param takes optional entry constants (default all 0, so the existing callers are unchanged). - A lane mask in s[d+1] before the write is a number afterwards: accepted, and a mutation that drops self.masks.discard(d + 1) turns the check red. AI-assisted (Claude Code). Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: Royoo <3230853833@qq.com> Co-authored-by: Ybucaille <83926195+Ybucaille@users.noreply.github.com> --- .github/workflows/windows.yml | 1 + AGENTS.md | 1 + CMakeLists.txt | 12 + tests/desktop_gpu.h | 2 +- tests/offscreen_check.cpp | 12 +- tests/startup_flat_param.cpp | 9 +- tests/startup_gfx2hlsl_bfm_b64_check.py | 634 ++++++++++++++++++++++++ tools/startup/gfx2hlsl.py | 92 +++- 8 files changed, 737 insertions(+), 26 deletions(-) create mode 100644 tests/startup_gfx2hlsl_bfm_b64_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index db21607e1..e32bfd3ce 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -346,6 +346,7 @@ jobs: tests/startup_gfx2hlsl_sop2_complement_check.py \ tests/startup_gfx2hlsl_pack_absdiff_check.py \ tests/startup_gfx2hlsl_sopk_accum_check.py \ + tests/startup_gfx2hlsl_bfm_b64_check.py \ tests/startup_gfx2hlsl_f32_lg_check.py \ tests/startup_gfx2hlsl_f32_nan_check.py \ tests/startup_gfx2hlsl_f32_sdwa_check.py \ diff --git a/AGENTS.md b/AGENTS.md index e435d0cb9..d2a7de366 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -215,6 +215,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_int_med3_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_cselect_mask_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_mask_overwrite_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_bfm_b64_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_mask_data_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_image_get_lod_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_add_sub_co_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 97d7158fe..1502e2f8a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3486,6 +3486,9 @@ if(EXISTS "${INTAKE_PYTHON}") # Scalar sign-extends and conditional moves (batch 3 #2). add_test(NAME startup_gfx2hlsl_s_sext_cmov COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_sext_cmov_check.py") + # s_bfm_b64 (#1723). + add_test(NAME startup_gfx2hlsl_bfm_b64 COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_bfm_b64_check.py") # SDWA forms of the float-result conversions (#1727). add_test(NAME startup_gfx2hlsl_sdwa_cvt COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_sdwa_cvt_check.py") @@ -3902,6 +3905,15 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_gfx2hlsl_bit_alu_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) endforeach() + # s_bfm_b64 read back on a desktop adapter: widths 0/1/31/32/33/63 x offsets 0/1/31/32/63 from run-time root + # constants against the bit-loop reference (FXC 5_1 and DXC 6_0), with an uncapped reference and a mutated lowering + # that the draw must reject. The startup_gfx2hlsl_bfm_b64 test above holds the CPU controls. + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_bfm_b64_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_bfm_b64_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_bfm_b64_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl two- and one-source integer vector operations (VEC_U): translation controls, then the same draw # of the translated pairs with reference words and one mutated lowering per operation. add_test(NAME startup_gfx2hlsl_int_alu_controls COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/desktop_gpu.h b/tests/desktop_gpu.h index 6ec555f55..0f20e3872 100644 --- a/tests/desktop_gpu.h +++ b/tests/desktop_gpu.h @@ -34,7 +34,7 @@ int check_startup_image_store(ID3D12Device* device, const char* vertex_path, con void check_startup_flat_param(ID3D12Device* device, const char* vertex_path, const char* pixel_path, std::uint32_t* words, UINT width = 1, UINT height = 1, D3D12_CULL_MODE cull = D3D12_CULL_MODE_NONE, BOOL front_ccw = FALSE, - UINT vertices = 3); + UINT vertices = 3, const std::uint32_t* constants = nullptr); void check_startup_entry_words(ID3D12Device* device, const char* vertex_path, const char* pixel_path, const std::uint32_t* entry, UINT entry_count, std::uint32_t* words, UINT width = 1, UINT height = 1); diff --git a/tests/offscreen_check.cpp b/tests/offscreen_check.cpp index 7ed885fd3..b486ad2a9 100644 --- a/tests/offscreen_check.cpp +++ b/tests/offscreen_check.cpp @@ -1513,14 +1513,20 @@ OperationResult run_startup_pixel_words(const OperationContext& ctx) // --startup-flat-param : draws one pixel with a gfx2hlsl vertex and // pixel stage pair (tests/startup_flat_param.cpp). The expected value is four 8-digit hex words, -// comma separated. +// comma separated. An optional fourth argument sets the four entry constants (ud0..ud3) as four hex words; +// without it they are all 0. OperationResult run_startup_flat_param(const OperationContext& ctx) { std::uint32_t expected[4]{}; if (std::sscanf(ctx.argv[5], "%8x,%8x,%8x,%8x", &expected[0], &expected[1], &expected[2], &expected[3]) != 4) return {OutcomeKind::fail, "expected value is not four hex words"}; std::uint32_t words[4]{}; - check_startup_flat_param(ctx.device, ctx.argv[3], ctx.argv[4], words); + std::uint32_t constants[4]{}; + if (ctx.argc == 7 && std::sscanf(ctx.argv[6], "%8x,%8x,%8x,%8x", &constants[0], &constants[1], &constants[2], + &constants[3]) != 4) + return {OutcomeKind::fail, "entry constants are not four hex words"}; + check_startup_flat_param(ctx.device, ctx.argv[3], ctx.argv[4], words, 1, 1, + D3D12_CULL_MODE_NONE, FALSE, 3, ctx.argc == 7 ? constants : nullptr); if (std::memcmp(words, expected, sizeof(words)) != 0) { std::fprintf(stderr, "startup_flat_param mismatch expected=%08x,%08x,%08x,%08x actual=%08x,%08x,%08x,%08x\n", expected[0], expected[1], expected[2], expected[3], words[0], words[1], words[2], words[3]); @@ -1692,7 +1698,7 @@ const OperationSpec kOperations[] = { {"--startup-image-load-d16", 7, 7, nullptr, kNoGate, run_startup_image_load_d16}, {"--startup-packed-position", 5, 5, nullptr, kNoGate, run_startup_packed_position}, {"--startup-sharedexp-target", 3, 3, nullptr, kNoGate, run_startup_sharedexp_target}, - {"--startup-flat-param", 6, 6, nullptr, kNoGate, run_startup_flat_param}, + {"--startup-flat-param", 6, 7, nullptr, kNoGate, run_startup_flat_param}, {"--startup-entry-words", 7, 7, nullptr, kNoGate, run_startup_entry_words}, {"--startup-pixel-words", 8, 8, validate_pixel_words_args, kNoGate, run_startup_pixel_words}, {"--raster-reference", 10, 10, validate_raster_args, kNoGate, run_startup_pixel_words}, diff --git a/tests/startup_flat_param.cpp b/tests/startup_flat_param.cpp index 2fc2ae247..7c92eb02b 100644 --- a/tests/startup_flat_param.cpp +++ b/tests/startup_flat_param.cpp @@ -3,7 +3,7 @@ // Draws one pixel with a translated vertex and pixel stage and returns the four 32-bit words of // the colour. The entry constants (cbuffer entry : register(b0)) are visible to both stages, because // the translated vertex stage reads ud0, the rectangle-list switch; they are all 0 here (plain -// triangles). The target is R32G32B32A32_FLOAT, so the readback is the raw words the pixel stage +// triangles) unless the caller passes four words. The target is R32G32B32A32_FLOAT, so the readback is the raw words the pixel stage // exported. #include "desktop_gpu.h" @@ -33,7 +33,8 @@ std::vector read_blob(const char* path) void check_startup_flat_param(ID3D12Device* device, const char* vertex_path, const char* pixel_path, std::uint32_t* words, UINT width, UINT height, - D3D12_CULL_MODE cull, BOOL front_ccw, UINT vertices) + D3D12_CULL_MODE cull, BOOL front_ccw, UINT vertices, + const std::uint32_t* constants) { const auto vs = read_blob(vertex_path); const auto ps = read_blob(pixel_path); @@ -96,8 +97,8 @@ void check_startup_flat_param(ID3D12Device* device, const char* vertex_path, con auto* list = commands.list.Get(); list->ClearRenderTargetView(rtv, clear.Color, 0, nullptr); list->SetGraphicsRootSignature(root.Get()); - const std::uint32_t constants[entry_constants] = {0, 0, 0, 0}; - list->SetGraphicsRoot32BitConstants(0, entry_constants, constants, 0); + const std::uint32_t zeros[entry_constants] = {0, 0, 0, 0}; + list->SetGraphicsRoot32BitConstants(0, entry_constants, constants ? constants : zeros, 0); const D3D12_VIEWPORT viewport{0, 0, static_cast(width), static_cast(height), 0, 1}; const D3D12_RECT scissor{0, 0, static_cast(width), static_cast(height)}; list->RSSetViewports(1, &viewport); diff --git a/tests/startup_gfx2hlsl_bfm_b64_check.py b/tests/startup_gfx2hlsl_bfm_b64_check.py new file mode 100644 index 000000000..eefb41baa --- /dev/null +++ b/tests/startup_gfx2hlsl_bfm_b64_check.py @@ -0,0 +1,634 @@ +"""s_bfm_b64 in tools/startup/gfx2hlsl.py (census issue #1723). + +usage: startup_gfx2hlsl_bfm_b64_check.py [draw [fxc]] + + (no arguments) translation controls and the CPU evaluation of the emitted text, pure Python + draw additionally draw the translated pair on a desktop adapter (WARP or hardware), compile the pixel + stage with FXC ps_5_1 when given and with DXC ps_6_0, and compare the read-back words + +`s_bfm_b64` had no lowering and was refused. RDNA 2 ISA (SOP2 opcode 37, `isa/rdna2_isa.txt` "S_BFM_B64"): +`D.u64 = ((1ULL << S0.u[5:0]) - 1) << S1.u[5:0]`. Both sources are 32-bit and only their low six bits count; a +width of 0 gives 0; the mask is truncated to 64 bits, so bits shifted past bit 63 are dropped. The ISA lists no SCC +write for this opcode (the bitwise ops print `SCC = (D != 0)`), so SCC is left alone. + +The 64-bit scalar value is two words (s[d], s[d+1]) written together. The instruction bytes are constructed here +from the SOP2 layout the checked-in decoder reads (`tools/disasm_rdna2.py`: [31:30]=0b10, opcode [29:23], sdst +[22:16], ssrc1 [15:8], ssrc0 [7:0]). + +The emitted HLSL, including the real `shl64` helper from the generated preamble, is evaluated by a small integer +evaluator that rejects any 32-bit shift count of 32 or more (undefined in HLSL), and compared with a reference built +from a bit loop over the ISA description, not from the lowering's expressions. Mutations (no width mask, 31 instead of +63, offset masked to five bits, width 0 reading all ones) must read a wrong word and are applied to the translated +text only. + +The draw mode (review of #2007) takes the evaluator out of the loop: the compiler's own treatment of `shl64`, the +`bw >= 32u ? ... : ...` selects and `uint2` is read back from the render target. Width and offset are root constants +(s8 and s9 of the pixel stage), so neither compiler can fold them. One draw computes `s_bfm_b64 s[20:21], s8, s9` and +the swapped `s_bfm_b64 s[22:23], s9, s8` and exports the four words. The expected words are the bit-loop reference. +Two negative controls must show in the draw: a reference that wraps the bits past bit 63 instead of dropping them, +and a mutated lowering (width 0 reads all ones). The pixel stage is built from instruction words made with the +encoder below and read back through the decoder, so no assembler is needed. + +A source SGPR that holds a lane mask (a compare result) is refused before either destination word or its mask flag changes, +with and without the destination aliasing the source. After #1931 both written words are proven uniform only when both sources +are, and an older proof for s[d] or s[d+1] is dropped, so a later v_readfirstlane_b32 cannot use it. +""" +import os +import re +import struct +import sys +import types + +here = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(here, '..', 'tools')) +sys.path.insert(0, os.path.join(here, '..', 'tools', 'startup')) +import gfx2hlsl as G # noqa: E402 + +MASK = 0xffffffff +failures = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH'}") + if not condition: + failures.append(label) + if detail: + print(' ' + detail) + + +def reference(width, offset): + """The ISA mask as a bit loop: bit i is set when offset <= i < offset + width and i < 64.""" + width, offset = width & 63, offset & 63 + return sum(1 << i for i in range(64) if offset <= i < offset + width) + + +# ---- instruction construction ------------------------------------------------------------------------------ +SOP2_BFM_B64 = 37 + + +def encode(dst, src0, src1, literal=None): + w0 = 0x80000000 | (SOP2_BFM_B64 << 23) | (dst << 16) | (src1 << 8) | src0 + out = struct.pack('>|<=|>=|==|!=|\|\||&=|[-+*&|^~!<>?:(),.=])') +LEVELS = [['||'], ['|'], ['^'], ['&'], ['==', '!='], ['<', '>', '<=', '>='], ['<<', '>>'], ['+', '-'], ['*']] + + +class Interp: + def __init__(self, common): + self.funcs = {} + m = re.search(r'uint2 shl64\(([^)]*)\) \{(.*?)\}\s*(?=\'|uint2 shr64u|$)', common) + assert m, 'shl64 not found in the preamble' + self.funcs['shl64'] = ([p.split()[-1] for p in m.group(1).split(',')], m.group(2)) + + def tokens(self, text): + toks = TOKEN.findall(text) + assert ''.join(toks) == re.sub(r'\s+', '', text), text + return toks + + def expr(self, text, env): + self.t, self.p, self.env = self.tokens(text), 0, env + value = self.ternary() + assert self.p == len(self.t), text + return value + + def peek(self): + return self.t[self.p] if self.p < len(self.t) else None + + def take(self): + self.p += 1 + return self.t[self.p - 1] + + def ternary(self): + cond = self.binary(0) + if self.peek() != '?': + return cond + self.take() + yes = self.ternary() + assert self.take() == ':' + no = self.ternary() + return yes if cond else no + + def binary(self, level): + if level == len(LEVELS): + return self.unary() + node = self.binary(level + 1) + while self.peek() in LEVELS[level]: + op = self.take() + b = self.binary(level + 1) + a = node + if op in ('<<', '>>'): + assert 0 <= b < 32, 'HLSL shift count %d is not below 32' % b + node = (a << b) & MASK if op == '<<' else a >> b + elif op == '||': + node = int(bool(a or b)) + else: + node = {'|': a | b, '^': a ^ b, '&': a & b, '+': a + b, '-': a - b, '*': a * b, '==': int(a == b), + '!=': int(a != b), '<': int(a < b), '>': int(a > b), '<=': int(a <= b), + '>=': int(a >= b)}[op] + node &= MASK + return node + + def unary(self): + tok = self.take() + if tok == '~': + return ~self.unary() & MASK + if tok == '(': + v = self.ternary() + assert self.take() == ')' + return self.member(v) + if tok[0].isdigit(): + return int(tok.rstrip('u'), 0) + if self.peek() == '(': + self.take() + args = [self.ternary()] + while self.peek() == ',': + self.take() + args.append(self.ternary()) + assert self.take() == ')' + return self.member(self.call(tok, args)) + return self.member(self.env[tok]) + + def member(self, v): + while self.peek() == '.': + self.take() + v = v['xy'.index(self.take())] + return v + + def call(self, name, args): + if name == 'uint2': + return tuple(args) + params, body = self.funcs[name] + saved = (self.t, self.p, self.env) + env = dict(zip(params, args)) + result = self.run(body, env) + self.t, self.p, self.env = saved + return result + + def run(self, text, env): + """Run statements; returns the value of a `return`.""" + for stmt in [s.strip() for s in text.split(';') if s.strip()]: + stmt = stmt.strip('{} ') + if not stmt: + continue + if stmt.startswith('return '): + return self.expr(stmt[7:], env) + m = re.match(r'(uint2|uint)\s+(.*)$', stmt) + if m: + for part in re.split(r',\s*(?=\w+\s*=)', m.group(2)): + name, _, rhs = part.partition('=') + env[name.strip()] = self.expr(rhs, env) + continue + m = re.match(r'(\w+)\s*(&=|=)\s*(.*)$', stmt) + assert m, stmt + value = self.expr(m.group(3), env) + env[m.group(1)] = (env[m.group(1)] & value) if m.group(2) == '&=' else value + return None + + +def preamble(): + pipe = object.__new__(G.Pipeline) + pipe.uds, pipe.resources, pipe.samplers, pipe.uses_sampler_heap = [], {}, {}, False + return ' '.join(pipe.common()) + + +COMMON = preamble() + + +def evaluate(stage, env, common=COMMON): + """Run the emitted lines of `stage` and return the (s20, s21) words.""" + interp = Interp(common) + env = dict(env) + for line in stage.lines: + # one block of statements: '{ ...; s20 = t.x; s21 = t.y; }' + interp.run(line, env) + return env['s20'], env['s21'] + + +def pair(value): + return value & MASK, value >> 32 + + +# ---- 1. the encoder produces the form the decoder reads ----------------------------------------------------- +decoded = G.decode(encode(20, 2, 3)) +check('encodes and decodes the register form', [a for _o, _s, _n, a in decoded] == ['s_bfm_b64 s[20:21], s2, s3'], + repr(decoded)) +decoded = G.decode(encode(20, 128 + 33, 128 + 5)) +check('encodes and decodes inline constants', [a for _o, _s, _n, a in decoded] == ['s_bfm_b64 s[20:21], 33, 5'], + repr(decoded)) +decoded = G.decode(encode(20, 255, 3, literal=0x12345681)) +check('encodes and decodes a literal', [a for _o, _s, _n, a in decoded] == ['s_bfm_b64 s[20:21], 0x12345681, s3'], + repr(decoded)) + +# ---- 2. run-time sources: the whole width x offset grid, evaluated against the bit-loop reference ----------- +asm = 's_bfm_b64 s[20:21], s2, s3' +stage = translate(asm) +text = ' '.join(stage.lines) +check('run-time form writes both words and no SCC', + 's20 = t.x;' in text and 's21 = t.y;' in text and 'scc' not in text and 'shl64(' in text, text) +bad = [] +for w in range(64): + for o in range(64): + got = evaluate(stage, {'s2': w, 's3': o}) + if got != pair(reference(w, o)): + bad.append((w, o, got)) +check('all 64 x 64 width/offset pairs match the reference', not bad, repr(bad[:3])) +key = [(0, 0), (0, 63), (1, 0), (1, 63), (31, 0), (31, 31), (31, 32), (32, 0), (32, 31), (32, 32), (33, 0), + (33, 31), (33, 32), (33, 63), (63, 0), (63, 1), (63, 31), (63, 32), (63, 63), (0, 31), (1, 31), (1, 32)] +bad = [(w, o) for w, o in key if evaluate(stage, {'s2': w, 's3': o}) != pair(reference(w, o))] +check('named widths 0/1/31/32/33/63 against offsets 0/31/32/63', not bad, repr(bad)) +# hand-written anchors, so the reference is not the only witness +anchors = {(0, 0): 0, (0, 63): 0, (1, 63): 1 << 63, (63, 1): (1 << 64) - 2, (32, 32): 0xffffffff00000000, + (33, 31): 0xffffffff80000000, (63, 63): 1 << 63, (31, 32): 0x7fffffff00000000} +check('hand-computed anchors', all(reference(*k) == v and evaluate(stage, {'s2': k[0], 's3': k[1]}) == pair(v) + for k, v in anchors.items())) +# source bits above [5:0] are ignored +junk = [(w | hi, o | hj) for w in (0, 1, 31, 32, 33, 63) for o in (0, 31, 32, 63) + for hi, hj in ((0x40, 0), (0, 0x40), (0xffffffc0, 0xffffff80), (0x80000000, 0x80000040), (0x12345640, 0xabcdef00))] +bad = [(w, o) for w, o in junk if evaluate(stage, {'s2': w, 's3': o}) != pair(reference(w, o))] +check('bits above [5:0] of either source are ignored (%d inputs)' % len(junk), not bad, repr(bad[:3])) + +# ---- 3. inline and literal sources --------------------------------------------------------------------------- +stage = translate('s_bfm_b64 s[20:21], 33, s3') +check('an inline width with a run-time offset reads the constant', + '0x00000021u' in ' '.join(stage.lines) and all( + evaluate(stage, {'s3': o}) == pair(reference(33, o)) for o in range(64))) +stage = translate('s_bfm_b64 s[20:21], s2, 32') +check('a run-time width with an inline offset reads the constant', + all(evaluate(stage, {'s2': w}) == pair(reference(w, 32)) for w in range(64))) +stage = translate('s_bfm_b64 s[20:21], 0x12345681, s3') +check('a literal width keeps only its low six bits (0x81 & 63 = 1)', + all(evaluate(stage, {'s3': o}) == pair(reference(1, o)) for o in range(64))) + +# ---- 4. fully constant sources fold, with the same result ---------------------------------------------------- +bad = [] +for w, o in [(0, 0), (1, 0), (31, 0), (32, 0), (33, 0), (63, 0), (1, 63), (63, 63), (33, 32), (32, 31), (0, 63), (5, 3)]: + stage = translate('s_bfm_b64 s[20:21], %d, %d' % (w, o)) + if stage.sym.get(20) != ('const', pair(reference(w, o))[0]) or stage.sym.get(21) != ('const', pair(reference(w, o))[1]): + bad.append((w, o, stage.sym)) +check('inline constants fold to the reference words', not bad, repr(bad[:2])) +stage = translate('s_bfm_b64 s[20:21], 0x12345681, 0x7f') +check('literals fold and mask both sources', + (stage.sym.get(20), stage.sym.get(21)) == tuple(('const', x) for x in pair(reference(1, 63)))) +stage = translate('s_bfm_b64 s[20:21], s2, s3', {2: ('const', 33), 3: ('const', 31)}) +check('SGPRs holding known constants fold', + (stage.sym.get(20), stage.sym.get(21)) == tuple(('const', x) for x in pair(reference(33, 31)))) +stage = translate('s_bfm_b64 s[20:21], s2, s3', {2: ('const', 0x1000), 3: ('const', 0)}) +check('a known width whose low six bits are 0 folds to a zero pair', + (stage.sym.get(20), stage.sym.get(21)) == (('const', 0), ('const', 0))) + +# ---- 5. an in-place destination reads the original sources ---------------------------------------------------- +stage = translate('s_bfm_b64 s[2:3], s2, s3') +env = {'s2': 33, 's3': 31} +interp = Interp(COMMON) +for line in stage.lines: + interp.run(line, env) +check('the destination may be the source registers', (env['s2'], env['s3']) == pair(reference(33, 31)), repr(env)) + +# ---- 6. refusals --------------------------------------------------------------------------------------------- +check('odd, single, vector and mask destinations are refused', all(refused(a) for a in ( + 's_bfm_b64 s[21:22], s2, s3', 's_bfm_b64 s20, s2, s3', 's_bfm_b64 v[20:21], s2, s3', 's_bfm_b64 exec, s2, s3', + 's_bfm_b64 vcc, s2, s3', 's_bfm_b64 s[20:23], s2, s3', 's_bfm_b64 s[106:107], s2, s3', 's_bfm_b64 m0, s2, s3'))) +check('pair, vector and mask sources are refused', all(refused(a) for a in ( + 's_bfm_b64 s[20:21], s[2:3], s3', 's_bfm_b64 s[20:21], s2, s[4:5]', 's_bfm_b64 s[20:21], v2, s3', + 's_bfm_b64 s[20:21], s2, vcc', 's_bfm_b64 s[20:21], exec, s3', 's_bfm_b64 s[20:21], vcc_lo, s3'))) +check('wrong operand counts and modifiers are refused', all(refused(a) for a in ( + 's_bfm_b64 s[20:21], s2', 's_bfm_b64 s[20:21], s2, s3, s4', 's_bfm_b64 s[20:21]', 's_bfm_b64 s[20:21], s2, s3 clamp'))) +check('a source holding descriptor data is refused', + refused('s_bfm_b64 s[20:21], s2, s3', {2: ('desc', 0, 0, 0)})) +check('a well-formed pair is accepted (control for the refusals)', not refused('s_bfm_b64 s[20:21], s2, s3')) + +# ---- 7. mutations must read a wrong word ------------------------------------------------------------------------- +GRID = [(w, o) for w in (0, 1, 31, 32, 33, 63) for o in (0, 31, 32, 63)] + \ + [(0x40, 0), (0x41, 5), (0xffffffa1, 3), (32, 0x80), (3, 0x7f)] +base = translate('s_bfm_b64 s[20:21], s2, s3') + + +def mutated_wrong(stage_lines, common): + class S: + lines = stage_lines + return [(w, o) for w, o in GRID if evaluate(S, {'s2': w, 's3': o}, common) != pair(reference(w, o))] + + +line = base.lines[0] +check('control: the unmutated text has no wrong word on the mutation grid', not mutated_wrong(base.lines, COMMON)) +mutations = { + 'no mask on the width': ([re.sub(r'(uint bw = s2) & 63u', r'\1', line)], COMMON), + 'width masked with 31': ([line.replace('s2 & 63u', 's2 & 31u')], COMMON), + 'offset masked to five bits': (base.lines, COMMON.replace('sh &= 63u;', 'sh &= 31u;')), + 'width 0 reads all ones': ([line.replace('bw >= 32u ?', 'bw >= 32u || bw == 0u ?', 1)], COMMON), +} +for name, (lines, common) in mutations.items(): + changed = lines != base.lines or common != COMMON + wrong = mutated_wrong(lines, common) if changed else [] + check('mutation "%s" changes the text and reads a wrong word %s' % (name, wrong[:1]), changed and bool(wrong)) + +# ---- 8. lane-mask sources are refused before any destination state changes (maintainer review of #2007) ----------- +class TrackedStage(G.Stage): + """A stage with the #1931 uniformity state, driven instruction by instruction.""" + + def __init__(self): + self.lines, self.sym, self.masks = [], {}, set() + self.used_s, self.used_v = set(), set() + self.uniform_v, self.varying_s, self.scc_uniform = set(), set(), True + self.has_branches, self.exec_known = False, True + self.past_entry = False + self.uniform_expr = {} + self.defined_uniform_s, self.bad_sgprs = {4, 5}, set() + self.exports, self.attrs = {}, {} + self.pipe = Pipeline() + + def run(self, *instructions): + for asm in instructions: + self.one(asm.split()[0], asm) + return self + + +def snapshot(stage): + return (list(stage.lines), dict(stage.sym), set(stage.masks), set(stage.varying_s), set(stage.used_s)) + + +def refused_after(*instructions): + """True when the last instruction is refused after running the earlier ones on a tracked stage.""" + stage = TrackedStage().run(*instructions[:-1]) + try: + stage.run(instructions[-1]) + except G.Unsupported: + return True + return False + + +CMP = 'v_cmp_lt_f32_e64 %s, v0, v1' +for label, cmp_dst, bfm in ( + ('compare mask as width', 's2', 's_bfm_b64 s[20:21], s2, s3'), + ('compare mask as offset', 's3', 's_bfm_b64 s[20:21], s2, s3'), + ('compare mask as width, destination aliases it', 's20', 's_bfm_b64 s[20:21], s20, s3'), + ('compare mask as offset, destination aliases it', 's21', 's_bfm_b64 s[20:21], s2, s21'), + ('compare mask as both, destination aliases it', 's20', 's_bfm_b64 s[20:21], s20, s20')): + stage = TrackedStage().run(CMP % cmp_dst) + reg = int(cmp_dst[1:]) + before = snapshot(stage) + try: + stage.run(bfm) + refusal = None + except G.Unsupported as error: + refusal = str(error) + check('%s is refused' % label, refusal is not None and 'lane mask' in refusal, repr(refusal)) + check('%s: no HLSL, no state change' % label, snapshot(stage) == before and reg in stage.masks, + repr((before, snapshot(stage)))) +# Controls: the same shapes with a non-mask scalar are accepted, and the compare destination alone stays a mask. +for asm in ('s_bfm_b64 s[20:21], s2, s3', 's_bfm_b64 s[20:21], s20, s3', 's_bfm_b64 s[20:21], s2, s21'): + stage = TrackedStage().run(asm) + check('control: %s accepted without a mask source' % asm, 'shl64(' in ' '.join(stage.lines)) +# A mask destination (not a source) loses its flag: the pair is a number afterwards. +stage = TrackedStage().run(CMP % 's20', 's_bfm_b64 s[20:21], s2, s3') +check('a mask destination that is not a source loses its flag', 20 not in stage.masks and 21 not in stage.masks) + +# A lane mask in the high word of the destination pair is a number after the write (review of #2007, the survived +# mutation of `self.masks.discard(d + 1)`): s21 is a compare result, s_bfm_b64 overwrites s[20:21], and s21 is then +# read as a source. That read must be accepted and must use the word written by the first instruction. +stage = TrackedStage().run(CMP % 's21') +check('control: the compare result in s21 is a lane mask before the write', 21 in stage.masks) +check('control: reading s21 while it is still a lane mask is refused', refused_after(CMP % 's21', 's_bfm_b64 s[22:23], s2, s21')) +stage = TrackedStage().run(CMP % 's21', 's_bfm_b64 s[20:21], s2, s3') +check('a lane mask in s[d+1] loses its flag when s_bfm_b64 writes the pair', 21 not in stage.masks and 20 not in stage.masks, + repr(stage.masks)) +check('s21 is read as a number after the write', not refused_after(CMP % 's21', 's_bfm_b64 s[20:21], s2, s3', + 'v_mov_b32_e32 v7, s21', 's_bfm_b64 s[22:23], s2, s21')) +nit_stage = TrackedStage().run(CMP % 's21', 's_bfm_b64 s[20:21], s2, s3', 's_bfm_b64 s[22:23], s2, s21') +# The compare line is HLSL over vector registers; run only the two scalar blocks. +env, interp = {'s2': 33, 's3': 31}, Interp(COMMON) +for line in [l for l in nit_stage.lines if 'shl64(' in l]: + interp.run(line, env) +check('evaluated: s[22:23] = bfm(33, high word of bfm(33, 31))', + (env['s22'], env['s23']) == pair(reference(33, pair(reference(33, 31))[1])), repr(env)) +# The mutation itself: the same lowering without `self.masks.discard(d + 1)` keeps s21 a lane mask, so the read is +# refused. The patched source is executed as a separate module; the check fails if the mutation does not apply. +SOURCE = open(os.path.join(here, '..', 'tools', 'startup', 'gfx2hlsl.py'), encoding='utf-8').read() +DISCARD = ' self.masks.discard(d + 1)\n' +body = SOURCE[SOURCE.index('def op_s_bfm_b64'):] +body = body[:body.index('\n def ', 10)] +check('mutation applies: op_s_bfm_b64 holds exactly one discard of d + 1', body.count(DISCARD) == 1) +mutant_source = SOURCE.replace(body, body.replace(DISCARD, '')) +check('mutation changes the source', mutant_source != SOURCE) +mutant = types.ModuleType('gfx2hlsl_mutant') +mutant.__file__ = G.__file__ +exec(compile(mutant_source, 'gfx2hlsl_mutant.py', 'exec'), mutant.__dict__) + + +class MutantStage(mutant.Stage): + __init__ = TrackedStage.__init__ + run = TrackedStage.run + + +for label, module_stage, expect_refused in (('unmutated', TrackedStage, False), ('without discard(d + 1)', MutantStage, True)): + try: + module_stage().run(CMP % 's21', 's_bfm_b64 s[20:21], s2, s3', 's_bfm_b64 s[22:23], s2, s21') + got_refused = False + except (G.Unsupported, mutant.Unsupported): + got_refused = True + check('%s: the number read of s21 after the write is %s' % (label, 'refused' if expect_refused else 'accepted'), + got_refused == expect_refused) + +# ---- 9. both written words carry a fresh uniformity proof (#1931) ---------------------------------------------------- +READ = 'v_readfirstlane_b32 s9, v7' +REFUSAL = 'v_readfirstlane_b32 requires a proven uniform source' + + +def read_word(stage, word): + """Copy s into v7 and read it back: accepted only when the word is proven uniform.""" + try: + stage.run('v_mov_b32_e32 v7, s%d' % word, READ) + except G.Unsupported as error: + return str(error) + return 'accepted' + + +# `s_mov_b64 s[2:3], exec` leaves s2 a lane mask and s3 a varying number, a non-mask varying source. +VARYING = 's_mov_b64 s[2:3], exec' +PROVE = 's_bfm_b64 s[20:21], s4, s5' +stage = TrackedStage().run(PROVE) +check('uniform sources: both words are proven uniform', read_word(stage, 20) == 'accepted' and + read_word(TrackedStage().run(PROVE), 21) == 'accepted') +for label, bfm in (('width', 's_bfm_b64 s[20:21], s3, s5'), ('offset', 's_bfm_b64 s[20:21], s4, s3'), + ('width and offset', 's_bfm_b64 s[20:21], s3, s3')): + for word in (20, 21): + # control: the old proof exists, otherwise a refusal below would prove nothing + check('old proof for s%d exists before the %s overwrite' % (word, label), + read_word(TrackedStage().run(VARYING, PROVE), word) == 'accepted') + got = read_word(TrackedStage().run(VARYING, PROVE, bfm), word) + check('varying %s: the old proof for s%d is not used' % (label, word), got == REFUSAL, got) +# Destination aliasing a varying source: s21 is the varying high word of a saved exec. +for word in (20, 21): + got = read_word(TrackedStage().run('s_mov_b64 s[20:21], exec', 's_bfm_b64 s[20:21], s21, s5'), word) + check('aliased varying source: s%d is not proven uniform' % word, got == REFUSAL, got) +# A later uniform write brings the proof back, so the refusals above come from the writes. +for word in (20, 21): + got = read_word(TrackedStage().run(VARYING, 's_bfm_b64 s[20:21], s3, s5', PROVE), word) + check('control: a later uniform write re-proves s%d' % word, got == 'accepted', got) + stage = TrackedStage().run(VARYING, 's_bfm_b64 s[20:21], s3, s5', 's_bfm_b64 s[20:21], 5, 3') + check('control: constant sources re-prove s%d' % word, read_word(stage, word) == 'accepted') + +# ---- 10. desktop draw: the compiler's own shl64, select and uint2 handling, read back (review of #2007) ---------- +def container(parts): + """DXBC header (hash zeroed) followed by (fourcc, body) parts.""" + base = 32 + 4 * len(parts) + offsets, body = [], b'' + for fourcc, data in parts: + offsets.append(base + len(body)) + body += fourcc + struct.pack('> 64) + + +def wrapped_words(w, o): + return pair(wrapped_reference(w, o)) + pair(wrapped_reference(o, w)) + + +def text_of(values): + return ','.join('%08x' % v for v in values) + + +def draw_bfm(renderer, adapter, vs, ps, w, o, expected): + import subprocess + constants = {1: w & MASK, 2: o & MASK} # ud1, ud2 (ud0 is the rectangle switch and stays 0) + entry = text_of([constants.get(i, 0) for i in range(4)]) + run = subprocess.run([renderer, adapter, '--startup-flat-param', str(vs), str(ps), text_of(expected), entry], + capture_output=True, text=True) + if run.returncode == 77: + print(run.stdout + run.stderr) + sys.exit(77) + return run + + +def check_draw(dxc, renderer, adapter, fxc=None): + import tempfile + from pathlib import Path + sys.path.insert(0, here) + from startup_flat_param_check import compile_hlsl + pipe = G.Pipeline(VS_WORDS, ps_instructions(), ROOT) + check('draw: the entry constants sit at ud0 (rect) and ud1, ud2 (width, offset)', + pipe.uds[:3] == [('rect',), ('rootconst', 0, 0), ('rootconst', 0, 1)], repr(pipe.uds)) + vs_text, ps_text = pipe.hlsl_vs(), pipe.hlsl_ps() + mask_lines = [line for line in ps_text.splitlines() + if 'uint bw = ' in line and 'uint2 t = shl64(' in line] + check('draw: the pixel stage computes both pairs from run-time constants', + len(mask_lines) == 2 and 'bw = ud1 & 63u' in mask_lines[0] and ', ud2);' in mask_lines[0] + and 'bw = ud2 & 63u' in mask_lines[1] and ', ud1);' in mask_lines[1]) + mutated_text = ps_text.replace('bw >= 32u ?', 'bw >= 32u || bw == 0u ?') + check('draw: the mutated pixel stage differs from the translation', mutated_text != ps_text) + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + vs = compile_hlsl(compiler, kind, vs_text, 'vs_bfm_%s' % kind, vs_profile, directory) + good = compile_hlsl(compiler, kind, ps_text, 'ps_bfm_%s' % kind, ps_profile, directory) + bad = compile_hlsl(compiler, kind, mutated_text, 'ps_bfm_mutated_%s' % kind, ps_profile, directory) + for w, o in DRAW_CASES: + expected = words_of(w, o) + run = draw_bfm(renderer, adapter, vs, good, w, o, expected) + if run.returncode: + raise AssertionError('%s width %#x offset %#x expected %s\n%s\n%s' % ( + kind, w, o, text_of(expected), run.stdout, run.stderr)) + print('%s width %#x offset %#x: %s' % (kind, w, o, text_of(expected)), flush=True) + # Negative control 1: a reference without the cap at bit 63 must not match what the compiled code returns. + for w, o in ((33, 63), (63, 63), (33, 32), (63, 33)): + wrong = wrapped_words(w, o) + check('%s: the uncapped reference differs from the ISA reference for width %d offset %d' % (kind, w, o), + wrong != words_of(w, o)) + run = draw_bfm(renderer, adapter, vs, good, w, o, wrong) + real = 'actual=%s' % text_of(words_of(w, o)) + if run.returncode == 0 or real not in run.stderr: + raise AssertionError('%s uncapped reference was not rejected for width %d offset %d\n%s\n%s' % ( + kind, w, o, run.stdout, run.stderr)) + print('%s uncapped reference: fails as expected, reads %s' % (kind, text_of(words_of(w, o))), flush=True) + # Negative control 2: the mutated lowering (width 0 reads all ones) must read different words. + for w, o, got in ((0, 0, (0xffffffff, 0, 0xffffffff, 0)), (0, 5, (0xffffffe0, 0x1f, 0x1f, 0))): + run = draw_bfm(renderer, adapter, vs, bad, w, o, words_of(w, o)) + if run.returncode == 0 or 'actual=%s' % text_of(got) not in run.stderr: + raise AssertionError('%s mutated lowering did not read %s for width %d offset %d\n%s\n%s' % ( + kind, text_of(got), w, o, run.stdout, run.stderr)) + print('%s mutation (width 0 reads all ones): fails as expected, reads %s' % (kind, text_of(got)), flush=True) + + +if len(sys.argv) > 1: + if sys.argv[1] != 'draw' or len(sys.argv) not in (5, 6): + raise SystemExit(__doc__) + check_draw(*sys.argv[2:]) + +if failures: + print('FAIL') + for item in failures: + print(' ' + item) + sys.exit(1) +print('PASS') diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 1e8d70e31..c0282fe8e 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -2462,6 +2462,25 @@ def set_scc(self, expr, proof=None): self.scc_uniform = self.scalar_expr_uniform(expr if proof is None else proof) self.emit('scc = %s;' % expr) + def record_scalar_uniformity(self, n, uniform): + if uniform: + self.varying_s.discard(n) + if self.defined_uniform_s is not None: + self.defined_uniform_s.add(n) + if self._uniform_written is not None: + self._uniform_written.add(n) + else: + self.varying_s.add(n) + if self.defined_uniform_s is not None: + self.defined_uniform_s.discard(n) + if self._uniform_written is not None: + self._uniform_written.discard(n) + if self.bad_sgprs is not None: + self.bad_sgprs.add(n) + # Only a proved assignment can add an SGPR to since_join. Unmodelled writes drop any stale mark. + if getattr(self, 'since_join', None) is not None: + (self.since_join.add if uniform else self.since_join.discard)(n) + def set_s(self, n, expr, sym=None, scc=None, uniform=None): """Assign scalar register n at run time and/or symbolically. @@ -2470,24 +2489,7 @@ def set_s(self, n, expr, sym=None, scc=None, uniform=None): if self.tracks_uniformity() and (sym is None or sym[0] == 'const'): if uniform is None: uniform = self.scalar_expr_uniform(expr) - if uniform: - self.varying_s.discard(n) - if self.defined_uniform_s is not None: - self.defined_uniform_s.add(n) - if self._uniform_written is not None: - self._uniform_written.add(n) - else: - self.varying_s.add(n) - if self.defined_uniform_s is not None: - self.defined_uniform_s.discard(n) - if self._uniform_written is not None: - self._uniform_written.discard(n) - if self.bad_sgprs is not None: - self.bad_sgprs.add(n) - # Invariant: since_join gains an SGPR only here, when set_s proves it uniform; forget_writes drops any SGPR - # an instruction writes first, so a write through an unmodelled path never keeps a stale mark. - if getattr(self, 'since_join', None) is not None: - (self.since_join.add if uniform else self.since_join.discard)(n) + self.record_scalar_uniformity(n, uniform) getattr(self, 'masks', set()).discard(n) # unit probes build a Stage without __init__ getattr(self, 'float_const_s', {}).pop(n, None) if sym is not None: @@ -4929,6 +4931,60 @@ def op_s_bfm_b32(self, ops, mods): self.set_s(d, '(((1u << (%s & 31)) - 1) << (%s & 31))' % (self.u(ops[1]), self.u(ops[2]))) return None + def op_s_bfm_b64(self, ops, mods): + """s_bfm_b64: D.u64 = ((1ULL << S0.u[5:0]) - 1) << S1.u[5:0], SCC unchanged. + + Unlike the mask-style 64-bit scalar ops (which keep one lane bit), this is a real 64-bit value, so both + destination words are written. The width is masked to six bits here and the offset inside shl64, which + also drops the bits shifted past bit 63; every HLSL shift count stays below 32.""" + if mods: + raise Unsupported('s_bfm_b64 with %s' % (mods,)) + if len(ops) != 3: + raise Unsupported('s_bfm_b64 with %d operands, expected 3' % len(ops)) + dst = reg_range(ops[0]) + if not dst or dst[0] != 's' or dst[2] != dst[1] + 1 or dst[1] % 2 or dst[2] > 105: + raise Unsupported('s_bfm_b64 destination %s' % ops[0]) + vals = [] + for o in ops[1:]: + r = reg_range(o) + if o in ('exec', 'exec_lo', 'exec_hi', 'vcc', 'vcc_lo', 'vcc_hi') or ( + r and (r[0] != 's' or r[1] != r[2] or r[1] > 105)): + raise Unsupported('s_bfm_b64 source %s' % o) + if r and r[1] in self.masks: + # A lane mask is not a number. Every source is read and checked before any destination state + # changes, so a source aliasing the destination cannot lose its mask flag first. + raise Unsupported('s_bfm_b64 source %s holds a lane mask' % o) + if r: + vals.append(self.is_const(r[1])) + else: + try: + vals.append(int(o, 0)) + except ValueError: + vals.append(None) + d = dst[1] + if None in vals: + width, offset = self.u(ops[1]), self.u(ops[2]) # may refuse; still before any write + # Both words are uniform only if both sources are. Judged before the destination changes, so an aliased + # source is classified by its old value and an older proof for s[d] or s[d+1] cannot survive. + uniform = self.tracks_uniformity() and all(self.uniform_source(o) for o in ops[1:]) + self.masks.discard(d) + self.masks.discard(d + 1) + if None not in vals: + value = (((1 << (vals[0] & 63)) - 1) << (vals[1] & 63)) & 0xffffffffffffffff + for i, word in enumerate((value & 0xffffffff, value >> 32)): + self.set_s(d + i, '0x%08xu' % word, ('const', word)) + return None + # Both words come from locals computed before either destination is written, so a source may be the destination. + self.sym.pop(d, None) + self.sym.pop(d + 1, None) + if self.tracks_uniformity(): + for word in (d, d + 1): + self.record_scalar_uniformity(word, uniform) + self.used_s.update((d, d + 1)) + self.emit('{ uint bw = %s & 63u; uint2 t = shl64(bw >= 32u ? 0xffffffffu : (1u << (bw & 31u)) - 1u, ' + 'bw >= 32u ? (1u << (bw & 31u)) - 1u : 0u, %s); s%d = t.x; s%d = t.y; }' % (width, offset, d, d + 1)) + return None + def scalar_const(self, tok): """Value of a 32-bit scalar source that is known at translation time, else None.""" if tok == 'null': From 091c2a484de8d8df195a2870d3572afdd5b15409 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?As=C4=B1m=20Mirza=20=C3=87iftler?= <113895866+Asimmimx@users.noreply.github.com> Date: Thu, 26 Nov 2026 07:51:39 +0300 Subject: [PATCH 136/240] shader: lower compute VOP1 bfrev and ffbh_i32 (#1591) Refs #1546. The compute store profile now lowers v_bfrev_b32_e32 and v_ffbh_i32_e32 on one known word (VGPR, known SGPR, inline constant or 32-bit literal), with the operand checks, data-only results and 1024-character limit of the existing integer ALU subset. Semantics (AMD RDNA 2 ISA reference, VOP1 opcodes 56 and 59): - v_bfrev_b32 is reversebits(x). - v_ffbh_i32 is D = -1; for i in 1..31 the first i with S0[31 - i] != S0[31]. It is 0xffffffff for 0 and 0xffffffff, 31 for 1 and 0xfffffffe, 1 for 0x40000000 and 0x80000000. It lowers as v_ffbh_u32 of m = x ^ (x >> 31, arithmetic), spelled firstbitlow(reversebits(m)), which is 31 - firstbithigh(m) and 0xffffffff for m = 0, so the source is named twice. The _e64, SDWA and DPP forms, source and output modifiers, register ranges, neighbouring opcodes and the scalar forms stay refused. Verification: tests/compute_alu_vop1_check.py lowers a guarded read-compute-write fixture with a 16-byte element per lane, compares the exact HLSL, and checks each refusal by message. The draw mode dispatches it on WARP for no active lane, a split wave and 70 active lanes, and compares all 320 words with Python bit loops written from the ISA text. Seven wrong references and seven wrong HLSL templates must each fail. New CTest: compute_store_aot_alu_vop1_(warp|hardware). Co-authored-by: tedin7 Co-authored-by: Royoo <3230853833@qq.com> --- CMakeLists.txt | 5 + docs/experiments.md | 12 ++ tests/compute_alu_vop1_check.py | 292 ++++++++++++++++++++++++++++++++ tools/compute_store_aot.py | 18 ++ 4 files changed, 327 insertions(+) create mode 100644 tests/compute_alu_vop1_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 1502e2f8a..64a689420 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -9934,6 +9934,11 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(compute_store_aot_mubuf_subword_${adapter} PROPERTIES TIMEOUT 45 SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/compute_store_aot_mubuf_subword_${adapter}.txt") + add_test(NAME compute_store_aot_alu_vop1_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/compute_alu_vop1_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(compute_store_aot_alu_vop1_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/compute_store_aot_alu_vop1_${adapter}.txt") add_test(NAME compute_store_aot_f32_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/compute_store_check.py" draw-f32 "${DXC_EXECUTABLE}" "$" ${adapter}) diff --git a/docs/experiments.md b/docs/experiments.md index 84d3e5629..68ce4b4f4 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -6654,6 +6654,18 @@ The fixture in `tests/compute_alu_med3_check.py` keeps the guarded read and stor The translator rejects `clamp`, `op_sel`, neg and abs on a source, which LLVM does not accept for these opcodes. It also rejects the 16-bit and binary32 medians, a register range, an unknown, pending or descriptor SGPR, an unknown VGPR and a literal wider than 32 bits, each with `Unsupported compute instruction`. A destination past `v255` gets `Unverified ALU operand`. A result used as a store address or as a guard operand is rejected, and so is a chain of medians whose expression exceeds the limit. Run `ctest --preset dev --no-tests=error -R '^compute_store_aot_alu_med3_(warp|hardware)$' -V`. Without Windows, `tests/compute_alu_med3_check.py controls` runs the exact-text and rejection checks. +#### VOP1 bit reverse and signed leading-bit count + +Two VOP1 forms lower on one known word, with the same sources, data-only results and 1024-character limit as the forms above: + +| Instruction | Result | +|---|---| +| `v_bfrev_b32_e32 vD, a` | `reversebits(a)`: bit i of the result is bit 31 - i of `a` | +| `v_ffbh_i32_e32 vD, a` | the position of the first bit that differs from the sign bit, counting from the MSB with the sign bit as position 0; 0xffffffff for 0 and 0xffffffff | + +`v_ffbh_i32` follows the RDNA 2 ISA definition (`D = -1; for i in 1..31, the first i with S0[31 - i] != S0[31]`), so 1 and 0xfffffffe give 31, and 0x40000000 and 0x80000000 give 1. It lowers as `v_ffbh_u32` of `m = a ^ (a >> 31)`, with an arithmetic shift, spelled `firstbitlow(reversebits(m))`. That is `31 - firstbithigh(m)` and reads 0xffffffff for `m = 0`, and it names `a` only twice. The `_e64`, SDWA and DPP forms, source and output modifiers, register ranges, `v_ffbh_u32`, `v_ffbl_b32` and the scalar `s_brev_b32` and `s_flbit_i32` stop the lowering with `Unsupported compute instruction`. An unknown, pending or descriptor source fails with `Unverified ALU operand`. + +The fixture is the read-compute-write kernel above with a 16-byte element per lane. For the source word `w`, it stores `bfrev(w)`, `ffbh_i32(w << (w & 31))`, `ffbh_i32(ashr(bfrev(w), (w >> 5) & 31))` and `((bfrev(gid) ^ ffbh_i32(cap)) + ffbh_i32(-1)) ^ bfrev(0x12345678)`, with `cap = params[0].y = 0xfffffffe`. Over the 70 active lanes, the scanned words have both signs, include 0 and 0xffffffff, and give every result from 1 to 30 except 14 and 16. The cap gives 31. The expected words come from Python bit loops written from the ISA text, not from the lowering. The WARP readback compares all 320 words for no active lane, a split wave and three groups with 70 active lanes. On the last dispatch, each of these must fail at the first word where it differs: a reference with one word off, lane 70 also writing, `ffbh_u32` for `ffbh_i32`, a count that leaves out the sign bit, an LSB-first index, 32 for 0 and -1, and `bfrev` as a copy. So must recompiled HLSL with `bfrev` as a copy or a complement, and `ffbh_i32` as `ffbh_u32`, with a logical sign fold, as an LSB-first index, as 32 for 0 and -1, or as the count minus one. Run `python -B tests/compute_alu_vop1_check.py controls` for the translator checks only, or `ctest --preset dev --no-tests=error -R '^compute_store_aot_alu_vop1_(warp|hardware)$' -V`. #### Signed 24-bit multiply-add `v_mad_i32_i24 vD, a, b, c` (VOP3 opcode 0x142) is the signed counterpart of `v_mad_u32_u24`: each multiplicand is the signed integer in bits [23:0] of its word, and `c` is a whole word, so the result is `sext24(a) * sext24(b) + c`, modulo 2^32. It takes the same sources as `v_mad_u32_u24`. The lowering sign-extends with `asuint(asint(x << 8u) >> 8u)` and multiplies and adds as `uint`, which gives the same low 32 bits as the signed product. `clamp`, the text forms `-v` and `|v|` (LLVM rejects them for this opcode), a source that is not a known word, a byte offset (which stays a row pitch only for `v_mad_u32_u24`) and a destination past v255 each stop the lowering. `v_mul_i32_i24` and `v_mad_i64_i32` are still outside the subset. diff --git a/tests/compute_alu_vop1_check.py b/tests/compute_alu_vop1_check.py new file mode 100644 index 000000000..ab9853eb0 --- /dev/null +++ b/tests/compute_alu_vop1_check.py @@ -0,0 +1,292 @@ +"""Check the compute VOP1 bit forms v_bfrev_b32 and v_ffbh_i32 between a guarded read and its store. + +Modes: + controls translator only: exact output and rejections + draw translate, dispatch and compare the full UAV readback +""" +from pathlib import Path +from unittest.mock import patch +import os +import struct +import subprocess +import sys +import tempfile + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools")) +import compute_store_check as base # noqa: E402 + +aot = base.aot +MASK = 0xffffffff + +# The read-compute-write fixture of compute_store_check.py (READ_COMPUTE) with its four ALU lines replaced by the +# two VOP1 forms, written by hand in the LLVM 15 spelling, and a 16-byte element per lane. With w the source word: +# out[4 * gid + 0] = bfrev(w) +# out[4 * gid + 1] = ffbh_i32(w << (w & 31)) +# out[4 * gid + 2] = ffbh_i32(ashr(bfrev(w), (w >> 5) & 31)) +# out[4 * gid + 3] = ((bfrev(gid) ^ ffbh_i32(cap)) + ffbh_i32(-1)) ^ bfrev(0x12345678) +# The shifted words give both signs and leading runs of 1 to 30 bits (the cap gives 31), and the arithmetic shift +# also gives 0 and 0xffffffff. The sources cover a VGPR read from t0, a computed VGPR, the dispatch index, an SGPR (cap = +# params[0].y), an inline constant and a literal. +VOP1_CHAIN = ("v_bfrev_b32_e32 v2, v1\n" + "v_lshlrev_b32_e32 v3, v1, v1\nv_ffbh_i32_e32 v3, v3\n" + "v_lshrrev_b32_e32 v4, 5, v1\nv_ashrrev_i32_e32 v4, v4, v2\nv_ffbh_i32_e32 v4, v4\n" + "v_bfrev_b32_e32 v5, v0\nv_ffbh_i32_e32 v6, s0\nv_xor_b32_e32 v5, v6, v5\n" + "v_ffbh_i32_e32 v6, -1\nv_add_nc_u32_e32 v5, v6, v5\n" + "v_bfrev_b32_e32 v6, 0x12345678\nv_xor_b32_e32 v5, v6, v5") +READ_VOP1 = base.variant( + base.READ_COMPUTE, + ("v_and_b32_e32 v2, 0xffff, v1", VOP1_CHAIN), + ("v_lshrrev_b32_e32 v1, 16, v1", ""), + ("v_mad_u32_u24 v1, v2, v1, v0", ""), + ("v_min_u32_e32 v1, s0, v1", ""), + ("buffer_store_dword v1, v0, s[8:11], 0 idxen", "buffer_store_dwordx4 v[2:5], v0, s[8:11], 0 idxen"), +) +VOP1_BINDING = base.READ_BINDING | dict(stride=16) +LOAD = base.READ_LOADS["read_copy"] + + +def bfrev_text(x): + return f"reversebits({x})" + + +def ffbh_text(x): + return f"firstbitlow(reversebits({x} ^ asuint(asint({x}) >> 31u)))" + + +SHIFTED = f"({LOAD} << ({LOAD} & 31u))" +SPREAD = f"asuint(asint({bfrev_text(LOAD)}) >> (({LOAD} >> (0x00000005u & 31u)) & 31u))" + + +def vop1_store(index="tid.x", cap="params[0].y", inline="0xffffffffu"): + """The guarded store, with the sources of the three word-3 instructions that take a known word.""" + constant = f"({bfrev_text('0x12345678u')} ^ ({ffbh_text(inline)} + ({ffbh_text(cap)} ^ {bfrev_text(index)})))" + return (f" outputData.Store4(tid.x * 16u + 0u, uint4({bfrev_text(LOAD)}, {ffbh_text(SHIFTED)}, " + f"{ffbh_text(SPREAD)}, {constant}));") + + +def bfrev(x): + """Bit i of the result is bit 31 - i of x.""" + return int(f"{x:032b}"[::-1], 2) + + +def ffbh_i32(x): + """AMD RDNA 2 ISA, V_FFBH_I32: D = -1; for i in 1..31, the first i with S0[31 - i] != S0[31] is D.""" + for i in range(1, 32): + if (x >> (31 - i)) & 1 != x >> 31: + return i + return MASK + + +def ffbh_u32(x): + """V_FFBH_U32, the unsigned scan: the MSB-first index of the first set bit, -1 for zero.""" + return next((i for i in range(32) if (x >> (31 - i)) & 1), MASK) + + +def ashr(x, n): + return ((x - (1 << 32) if x >> 31 else x) >> (n & 31)) & MASK + + +# Wrong models of the two forms for the reference controls. Each must differ from the right one on the fixture. +WRONG_MODELS = { + "ffbh_u32 for ffbh_i32": dict(ffbh=ffbh_u32), + "ffbh counting after the sign bit": dict(ffbh=lambda x: ffbh_i32(x) - 1 if ffbh_i32(x) != MASK else MASK), + "ffbh as an LSB-first index": dict(ffbh=lambda x: 31 - ffbh_i32(x) if ffbh_i32(x) != MASK else MASK), + "ffbh 32 for 0 and -1": dict(ffbh=lambda x: 32 if ffbh_i32(x) == MASK else ffbh_i32(x)), + "bfrev as a copy": dict(reverse=lambda x: x), +} +VOP1_CAP = 0xfffffffe # ffbh_i32 = 31: only bit 0 differs from the sign bit +# (groups, bound): no lane passes, a split wave, and three groups with 70 active lanes, 280 of the 320 words. +VOP1_RUNS = ((1, 0), (1, 17), (3, 70)) + + +def lane_words(gid, *, reverse=bfrev, ffbh=ffbh_i32): + """Independent CPU reference of one lane's four words.""" + w = base.source_word(gid) + shifted = (w << (w & 31)) & MASK + spread = ashr(reverse(w), w >> 5) + constant = (((reverse(gid) ^ ffbh(VOP1_CAP)) + ffbh(MASK)) & MASK) ^ reverse(0x12345678) + return [reverse(w), ffbh(shifted), ffbh(spread), constant] + + +def vop1_words(groups, bound, **model): + words = [base.SENTINEL] * 320 + for gid in range(min(32 * groups, bound)): + words[4 * gid:4 * gid + 4] = lane_words(gid, **model) + return words + + +def reference_controls(): + """The CPU model against hand-worked ISA cases, and the fixture's coverage of them.""" + for x, expected in ((0, MASK), (MASK, MASK), (1, 31), (0xfffffffe, 31), (0x80000000, 1), (0x7fffffff, 1), + (0x40000000, 1), (0xbfffffff, 1), (0x3fffffff, 2), (0xc0000000, 2), (0x0000ffff, 16), + (0xffe0c0de, 11)): + assert ffbh_i32(x) == expected, (hex(x), ffbh_i32(x)) + for x, expected in ((0, 0), (1, 0x80000000), (0x80000000, 1), (0x12345678, 0x1e6a2c48), (0xf0000000, 0xf)): + assert bfrev(x) == expected, (hex(x), hex(bfrev(x))) + groups, bound = VOP1_RUNS[-1] + lanes = [base.source_word(gid) for gid in range(bound)] + inputs = [(w << (w & 31)) & MASK for w in lanes] + [ashr(bfrev(w), w >> 5) for w in lanes] + [VOP1_CAP] + # Both signs, both all-equal words, the shortest and the longest run. + assert {0, MASK} <= set(inputs) and any(x >> 31 and x != MASK for x in inputs) + assert any(0 < x < 1 << 31 for x in inputs) + assert {1, 31} <= {ffbh_i32(x) for x in inputs} + expected = vop1_words(groups, bound) + for label, model in WRONG_MODELS.items(): + assert vop1_words(groups, bound, **model) != expected, f"{label} would go unseen" + + +def controls(): + """Translator only: exact output, then one rejection per form or operand outside the subset.""" + reference_controls() + + def vop1(*changes, **binding): + return aot.lower(base.variant(READ_VOP1, *changes), 32, **(VOP1_BINDING | binding)).splitlines() + + lines = vop1() + assert lines[:3] == ["cbuffer Constants : register(b0) { uint4 params[4]; };", + "ByteAddressBuffer inputData : register(t0);", + "RWByteAddressBuffer outputData : register(u0);"], lines + assert lines[-4:] == [base.GUARD_IF, vop1_store(), " }", "}"], lines[-4:] + # A copy of a result is the same program. + assert vop1(("v_bfrev_b32_e32 v2, v1", "v_bfrev_b32_e32 v7, v1\nv_mov_b32_e32 v2, v7")) == lines + # Each source kind prints as its own word. + for source, word in (("s0", "params[0].y"), ("-16", "0xfffffff0u"), ("0x80000000", "0x80000000u"), + ("v0", "tid.x"), ("v1", LOAD)): + assert vop1(("v_ffbh_i32_e32 v6, -1", f"v_ffbh_i32_e32 v6, {source}"))[-3] == vop1_store(inline=word) + assert vop1(("v_ffbh_i32_e32 v6, s0", f"v_ffbh_i32_e32 v6, {source}"))[-3] == vop1_store(cap=word) + assert vop1(("v_bfrev_b32_e32 v5, v0", f"v_bfrev_b32_e32 v5, {source}"))[-3] == vop1_store(index=word) + unsupported, operand = "Unsupported compute instruction: ", "Unverified ALU operand" + for message, changes in ( + # The VOP3, SDWA and DPP encodings of both forms, source and output modifiers, and a register range. + (unsupported + "v_bfrev_b32_e64", (("v_bfrev_b32_e32 v2, v1", "v_bfrev_b32_e64 v2, v1"),)), + (unsupported + "v_ffbh_i32_e64", (("v_ffbh_i32_e32 v3, v3", "v_ffbh_i32_e64 v3, v3"),)), + (unsupported + "v_ffbh_i32_e64", (("v_ffbh_i32_e32 v3, v3", "v_ffbh_i32_e64 v3, -v3"),)), + (unsupported + "v_bfrev_b32_sdwa", (("v_bfrev_b32_e32 v2, v1", "v_bfrev_b32_sdwa v2, v1 dst_sel:DWORD " + "dst_unused:UNUSED_PAD src0_sel:WORD_1"),)), + (unsupported + "v_ffbh_i32_sdwa", (("v_ffbh_i32_e32 v3, v3", "v_ffbh_i32_sdwa v3, v3 dst_sel:DWORD " + "dst_unused:UNUSED_PAD src0_sel:BYTE_0"),)), + (unsupported + "v_ffbh_i32_dpp", (("v_ffbh_i32_e32 v3, v3", "v_ffbh_i32_dpp v3, v3 quad_perm:[1,0,3,2] " + "row_mask:0xf bank_mask:0xf"),)), + (unsupported + "v_bfrev_b32_e32", (("v_bfrev_b32_e32 v2, v1", "v_bfrev_b32_e32 v2, -v1"),)), + (unsupported + "v_bfrev_b32_e32", (("v_bfrev_b32_e32 v2, v1", "v_bfrev_b32_e32 v2, |v1|"),)), + (unsupported + "v_ffbh_i32_e32", (("v_ffbh_i32_e32 v3, v3", "v_ffbh_i32_e32 v3, v3 clamp"),)), + (unsupported + "v_bfrev_b32_e32", (("v_bfrev_b32_e32 v2, v1", "v_bfrev_b32_e32 v2, v[1:2]"),)), + # Neighbouring opcodes outside the family, and the scalar forms. + (unsupported + "v_ffbh_u32_e32", (("v_ffbh_i32_e32 v3, v3", "v_ffbh_u32_e32 v3, v3"),)), + (unsupported + "v_ffbl_b32_e32", (("v_ffbh_i32_e32 v3, v3", "v_ffbl_b32_e32 v3, v3"),)), + (unsupported + "v_not_b32_e32", (("v_bfrev_b32_e32 v2, v1", "v_not_b32_e32 v2, v1"),)), + (unsupported + "s_brev_b32", (("v_ffbh_i32_e32 v6, s0", "s_brev_b32 s16, s0\nv_ffbh_i32_e32 v6, s16"),)), + (unsupported + "s_flbit_i32", (("v_ffbh_i32_e32 v6, s0", "s_flbit_i32 s16, s0\nv_ffbh_i32_e32 v6, s16"),)), + # Sources that are not known words: an unknown VGPR, an unwritten, descriptor, saved exec-mask, pending or + # out-of-range SGPR, a literal wider than 32 bits and a byte offset. Also a destination past v255. + (operand, (("v_ffbh_i32_e32 v3, v3", "v_ffbh_i32_e32 v3, v9"),)), + (operand, (("v_ffbh_i32_e32 v6, s0", "v_ffbh_i32_e32 v6, s20"),)), + (operand, (("v_ffbh_i32_e32 v6, s0", "v_ffbh_i32_e32 v6, s8"),)), + (operand, (("v_ffbh_i32_e32 v6, s0", "v_ffbh_i32_e32 v6, s2"),)), + (operand, (("v_ffbh_i32_e32 v6, s0", "s_buffer_load_dword s20, s[4:7], 0x8\nv_ffbh_i32_e32 v6, s20"),)), + (operand, (("v_ffbh_i32_e32 v6, s0", "v_ffbh_i32_e32 v6, s106"),)), + (operand, (("v_bfrev_b32_e32 v6, 0x12345678", "v_bfrev_b32_e32 v6, 0x112345678"),)), + (operand, (("v_bfrev_b32_e32 v5, v0", "v_lshlrev_b32_e32 v7, 2, v0\nv_bfrev_b32_e32 v5, v7"),)), + (operand, (("v_bfrev_b32_e32 v2, v1", "v_bfrev_b32_e32 v256, v1"),)), + ("Vector load result used or overwritten before s_waitcnt vmcnt(0)", (("s_waitcnt vmcnt(0)", ""),)), + # A result is data only: not a store or read address and not a lane-guard operand. + ("Unsupported store address", (("v[2:5], v0, s[8:11]", "v[2:5], v3, s[8:11]"),)), + ("Unsupported read address", (("buffer_store_dwordx4", "buffer_load_dword v7, v4, s[12:15], 0 offen\n" + "buffer_store_dwordx4"),)), + ("Unverified lane guard compare", (("buffer_store_dwordx4", "v_cmp_gt_u32_e32 vcc_lo, s3, v3\n" + "buffer_store_dwordx4"),)), + # ffbh_i32 names its source twice, so a chain of them is refused once it passes the limit. + ("ALU expression too large", (("v_ffbh_i32_e32 v4, v4", "v_ffbh_i32_e32 v4, v4" + + "\nv_ffbh_i32_e32 v4, v4" * 2),)), + ): + base.rejects(message, vop1, *changes) + # With the x8 descriptor load moved before the guard, a result computed under the guard is unknown after the + # restore, and one computed after it is known. + restored = (("s_load_dwordx8 s[8:15], s[0:1], 0x0", ""), + ("s_and_saveexec_b32 s2, vcc_lo", "s_load_dwordx8 s[8:15], s[0:1], 0x0\ns_waitcnt lgkmcnt(0)\n" + "s_and_saveexec_b32 s2, vcc_lo"), + ("s_cbranch_execz .LBB0_2", ""), (".LBB0_2:", ""), + ("buffer_store_dwordx4 v[2:5], v0, s[8:11], 0 idxen", + "buffer_store_dwordx3 v[2:4], v0, s[8:11], 0 idxen\ns_or_b32 exec_lo, exec_lo, s2\n" + "buffer_store_dword v5, v0, s[8:11], 0 idxen offset:12")) + base.rejects("Store data is not a known word", vop1, *restored) + after = vop1(*restored[:-1], (restored[-1][0], restored[-1][1].replace( + "\nbuffer_store_dword v5", "\nv_bfrev_b32_e32 v5, 1\nbuffer_store_dword v5"))) + assert after[-3:] == [" }", " outputData.Store(tid.x * 16u + 12u, reversebits(0x00000001u));", "}"], after + return 0 + + +# Translations that a wrong template would produce; each must fail on the GPU. +TEMPLATE_MUTATIONS = ( + ("bfrev as a copy", "v_bfrev_b32_e32", "({0})"), + ("bfrev as a complement", "v_bfrev_b32_e32", "(~{0})"), + ("ffbh_i32 as ffbh_u32", "v_ffbh_i32_e32", "firstbitlow(reversebits({0}))"), + ("logical sign fold", "v_ffbh_i32_e32", "firstbitlow(reversebits({0} ^ ({0} >> 31u)))"), + ("LSB-first index", "v_ffbh_i32_e32", "firstbithigh({0} ^ asuint(asint({0}) >> 31u))"), + ("32 for 0 and -1", "v_ffbh_i32_e32", "(31u - firstbithigh({0} ^ asuint(asint({0}) >> 31u)))"), + ("count after the sign bit", "v_ffbh_i32_e32", "(firstbitlow(reversebits({0} ^ asuint(asint({0}) >> 31u))) - 1u)"), +) + + +def draw(directory, compiler, renderer, backend): + controls() + src, cso, case = (directory / f"vop1.{ext}" for ext in ("hlsl", "cso", "case")) + compile_hlsl = [compiler, "-T", "cs_6_0", "-E", "main", "-Fo", cso, src] + run = [renderer, backend, "--compute-store-case", cso, case] + constants = [0x5eed0000 + i for i in range(16)] + constants[1] = VOP1_CAP + + def write(groups, bound, words): + case.write_bytes(struct.pack("<337I", groups, *words, bound, *constants[1:])) + + source = aot.lower(READ_VOP1, 32, **VOP1_BINDING) + src.write_text(source, encoding="ascii") + subprocess.run(compile_hlsl, check=True) + for groups, bound in VOP1_RUNS: + print(f"read_vop1: groups={groups} bound={bound}", flush=True) + write(groups, bound, vop1_words(groups, bound)) + result = subprocess.run(run) + if result.returncode: + return result.returncode + groups, bound = VOP1_RUNS[-1] + expected = vop1_words(groups, bound) + # Reference controls: one word off, the first lane past the bound writing, and each wrong model. + off = list(expected) + off[4 * bound - 1] ^= 1 + for label, reference in (("one word off", off), ("lane past the bound", vop1_words(groups, bound + 1)), + *((label, vop1_words(groups, bound, **model)) for label, model in WRONG_MODELS.items())): + word = next(i for i, (a, b) in enumerate(zip(expected, reference)) if a != b) + write(groups, bound, reference) + bad = subprocess.run(run, capture_output=True, text=True) + if bad.returncode != 1 or f"word={word} expected=" not in bad.stderr: + raise AssertionError(f"read_vop1: reference '{label}' escaped detection\n{bad.stdout}\n{bad.stderr}") + print(f"read_vop1: reference '{label}' fails at word {word}", flush=True) + write(groups, bound, expected) + mutated_src, mutated_cso = directory / "mutated.hlsl", directory / "mutated.cso" + for label, op, template in TEMPLATE_MUTATIONS: + with patch.dict(aot.VOP1_ALU, {op: template}): + mutated = aot.lower(READ_VOP1, 32, **VOP1_BINDING) + if mutated == source: + raise AssertionError(f"read_vop1: mutation '{label}' did not change the source") + mutated_src.write_text(mutated, encoding="ascii") + subprocess.run([compiler, "-T", "cs_6_0", "-E", "main", "-Fo", mutated_cso, mutated_src], check=True) + bad = subprocess.run([*run[:3], mutated_cso, case], capture_output=True, text=True) + if bad.returncode != 1 or "Compute readback differs" not in bad.stderr: + raise AssertionError(f"read_vop1: mutation '{label}' escaped detection\n{bad.stdout}\n{bad.stderr}") + print(f"read_vop1: mutation '{label}' fails", flush=True) + if record := os.environ.get("FORM_COVERAGE_RECORD"): + path = Path(record) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("v_bfrev_b32_e32\nv_ffbh_i32_e32\n", encoding="utf-8") + return 0 + + +if __name__ == "__main__": + mode, *args = sys.argv[1:] + if mode == "controls" and not args: + sys.exit(controls()) + if mode == "draw" and len(args) == 3: + with tempfile.TemporaryDirectory() as tmp: + sys.exit(draw(Path(tmp), *args)) + sys.exit(f"usage: {Path(__file__).name} controls | draw ") diff --git a/tools/compute_store_aot.py b/tools/compute_store_aot.py index 088f3b06e..2ad1f06c1 100644 --- a/tools/compute_store_aot.py +++ b/tools/compute_store_aot.py @@ -79,6 +79,14 @@ "v_mul_lo_u32": INTEGER["mul_lo_u32"][1], "v_mad_u32_u24": "((({0} & 0xffffffu) * ({1} & 0xffffffu)) + {2})", } +# The VOP1 bit subset on one known word (AMD RDNA 2 ISA reference, VOP1 opcodes 56 and 59). v_bfrev_b32 reverses +# the 32 bits. v_ffbh_i32 counts from the sign bit (bit 31 is position 0) to the first bit that differs from it, +# and is 0xffffffff for 0 and 0xffffffff: v_ffbh_u32 of m = x ^ (x >> 31, arithmetic). firstbitlow(reversebits(m)) +# is 31 - firstbithigh(m) and 0xffffffff for m = 0, so the source appears only twice. +VOP1_ALU = { + "v_bfrev_b32_e32": "reversebits({0})", + "v_ffbh_i32_e32": "firstbitlow(reversebits({0} ^ asuint(asint({0}) >> 31u)))", +} # The scalar ALU subset, on known words only: s_ sD, a, b with two scalar sources (an SGPR holding a known # word, an integer inline constant or a 32-bit literal). The carry out of s_add_u32 and s_sub_u32 and the # nonzero flag of the logic forms go to SCC, which no accepted instruction reads. s_lshr_b32 is a logical @@ -2455,6 +2463,16 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N if len(expression) > ALU_EXPRESSION_LIMIT: raise ValueError("ALU expression too large") vector[dst] = ("alu", expression) + elif m := re.fullmatch(rf"(v_(?:bfrev_b32|ffbh_i32)_e32) v(\d+), {ALU_SOURCE}", line): + # VOP1 src0 is any source. The VOP3, SDWA and DPP spellings and source modifiers do not match. + op, dst = m[1], int(m[2]) + word = alu_word(m[3], scalar, vector, pending) + if dst > 255 or word is None: + raise ValueError("Unverified ALU operand") + expression = VOP1_ALU[op].format(hlsl_word(word)) + if len(expression) > ALU_EXPRESSION_LIMIT: + raise ValueError("ALU expression too large") + vector[dst] = ("alu", expression) elif ((m := re.fullmatch(rf"(v_sub(?:rev)?_co_u32) v(\d+), (vcc_lo|s\d+), {ALU_SOURCE}, {ALU_SOURCE}", line)) or (m := re.fullmatch(rf"(v_sub(?:rev)?_co_ci_u32_e32) v(\d+), (vcc_lo), {ALU_SOURCE}, (v\d+), (vcc_lo)", line)) or (m := re.fullmatch(rf"(v_sub(?:rev)?_co_ci_u32_e64) v(\d+), (vcc_lo|s\d+), {ALU_SOURCE}, {ALU_SOURCE}, (vcc_lo|s\d+)", line))): From a766f287625121c981f734aeecc0b140d4ad55ba Mon Sep 17 00:00:00 2001 From: triggered02 <153171514+triggered02@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:22:03 +0530 Subject: [PATCH 137/240] shader: lower v_sad_hi_u8 and v_msad_u8 in gfx2hlsl (#2733) * shader: lower v_sad_hi_u8 and v_msad_u8 in startup gfx2hlsl The gfx1013 VOP3A forms 0x15b (347) and 0x171 (369) join the v_sad_u8 lowering in VEC_U, with the same three-source integer operand rules and encoding guards as the other SAD forms. Both are lowered from the tools/pixel_aot.py table so the two translators agree: sad_hi_u8 = (sad4_u8(a, b, false) << 16u) + c msad_u8 = sad4_u8(a, b, true) + c sad4_u8 is the four-lane absolute-difference sum of the existing sad_u8 helper, factored into an on-demand helper whose masked argument leaves out each byte lane whose src1 byte is zero (v_msad_u8's reference rule). The existing sad_u8/sad_u16/sad_u32 helper text is unchanged. Refs #2732 * tests: cover v_sad_hi_u8 and v_msad_u8 in startup gfx2hlsl tests/startup_gfx2hlsl_sad_hi_msad_check.py decodes synthetic gfx1013 VOP3A bytes via G.decode() only, checks that each new form emits sad4_u8 plus only its own wrapper (and that the unchanged v_sad_u8 output does not pull sad4_u8 in), and evaluates the emitted HLSL against the tools/pixel_aot.py formulas: 864 edge/grid triples per form plus pinned normal, zero-src1-byte and 2^32-carry rows, with modifier, encoding, arity and unlowered refusals. The check joins the smart-preset regex, the Python Linux CI list and the AGENTS.md pure-Python list, and the shared sad evaluator gains the bool masked literal and && operators the accounting helper needs. Refs #2732 * docs: record the v_sad_hi_u8 and v_msad_u8 lowerings Extend the startup translator SAD section with the two VOP3A forms, the shared sad4_u8 helper and its zero-src1-byte rule for v_msad_u8, the new fixture, and what is not established (the semantics are pinned to the AOT reference, not measured on a console). Refs #2732 * shader: accept the empty SAD tracking tuple in the shared preamble --------- Co-authored-by: Royoo <3230853833@qq.com> --- .github/workflows/windows.yml | 1 + AGENTS.md | 1 + CMakeLists.txt | 4 + CMakePresets.json | 2 +- docs/experiments.md | 5 +- tests/startup_gfx2hlsl_sad_check.py | 12 +- tests/startup_gfx2hlsl_sad_hi_msad_check.py | 346 ++++++++++++++++++++ tools/startup/gfx2hlsl.py | 27 +- 8 files changed, 392 insertions(+), 6 deletions(-) create mode 100644 tests/startup_gfx2hlsl_sad_hi_msad_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index e32bfd3ce..f93130f2a 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -354,6 +354,7 @@ jobs: tests/startup_gfx2hlsl_sopk_signext_check.py \ tests/startup_gfx2hlsl_mul_hi_check.py \ tests/startup_gfx2hlsl_sad_check.py \ + tests/startup_gfx2hlsl_sad_hi_msad_check.py \ tests/startup_gfx2hlsl_scalar_brev_fold_check.py \ tests/startup_gfx2hlsl_s_bit_scan_check.py \ tests/startup_gfx2hlsl_pack_b32_f16_check.py \ diff --git a/AGENTS.md b/AGENTS.md index d2a7de366..0cc3a2c16 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -272,6 +272,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_getpc_refusal_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_image_arity_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_sad_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_sad_hi_msad_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_cvt_pk_int16_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_scalar_null_check.py ``` diff --git a/CMakeLists.txt b/CMakeLists.txt index 64a689420..d68404580 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4305,6 +4305,10 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_gfx2hlsl_sad_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl v_sad_hi_u8 (0x15b) and v_msad_u8 (0x171): the shared sad4_u8 helper, value evaluation against the + # tools/pixel_aot.py formulas (zero-src1-byte and 2^32 carry cases), refusals and the unchanged v_sad_u8 output. + add_test(NAME startup_gfx2hlsl_sad_hi_msad_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_sad_hi_msad_check.py") add_test(NAME startup_xg_bc_tiling COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_xg_bc_tiling_check.py" "$") set_tests_properties(startup_xg_bc_tiling PROPERTIES TIMEOUT 30 ENVIRONMENT "X2W_D3D12_PERMISSIVE=1") diff --git a/CMakePresets.json b/CMakePresets.json index 861add0bc..19a646b00 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -42,7 +42,7 @@ "displayName": "Windows pull request smoke tests", "filter": { "include": { - "name": "^(desktop_root_signature|era_heap_(allocation|failure)|xmem_shim_mapped_pages|cpu_aot_fuzz_smoke|cpu_archive_texture_gpu_warp|dual_uav_warp|spirv_.*_warp|static_exe_intake|descriptor_heap_paging(_swapped)?_warp|startup_launch|startup_tools_lint|startup_gfx2hlsl_cvt_off_f32_i4_controls|startup_indirect_(dispatch|count_split|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|counts_control)_warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_shader_cache_key)$" + "name": "^(desktop_root_signature|era_heap_(allocation|failure)|xmem_shim_mapped_pages|cpu_aot_fuzz_smoke|cpu_archive_texture_gpu_warp|dual_uav_warp|spirv_.*_warp|static_exe_intake|descriptor_heap_paging(_swapped)?_warp|startup_launch|startup_tools_lint|startup_gfx2hlsl_cvt_off_f32_i4_controls|startup_gfx2hlsl_sad_hi_msad_controls|startup_indirect_(dispatch|count_split|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|counts_control)_warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_shader_cache_key)$" } } }, diff --git a/docs/experiments.md b/docs/experiments.md index 68ce4b4f4..c197e5082 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -16655,7 +16655,7 @@ The checks are `tests/startup_gfx2hlsl_handler_arity_check.py`, `…_image_arity `…_operand_count_check.py` and `…_scalar_arity_check.py`. They run on Linux and Windows without D3D12 or game data, because a refusal is observable at the `Stage` entry point. -## Startup translator: v_sad_u8, v_sad_u16 and v_sad_u32 +## Startup translator: v_sad_u8, v_sad_hi_u8, v_msad_u8, v_sad_u16 and v_sad_u32 [`tools/startup/gfx2hlsl.py`](../tools/startup/gfx2hlsl.py) now lowers the gfx1013 VOP3A unsigned sum-of-absolute-differences instructions `v_sad_u8` (`0x15a`), `v_sad_u16` (`0x15c`) and `v_sad_u32` (`0x15d`) in `VEC_U` to three on-demand preamble helpers emitted in `Pipeline.common()` only when referenced by a stage (`sad_u8`, `sad_u16`, `sad_u32`): @@ -16664,10 +16664,13 @@ data, because a refusal is observable at the `Stage` entry point. - `sad_u32(uint a, uint b, uint c)` computes `(a > b ? a - b : b - a) + c` using unsigned comparison rather than signed `int` subtraction. - Output modifiers (`clamp`, `omod`), `op_sel`, the per-source `abs` bits (VOP3A `w0[10:8]`) and `neg` bits (`w1[31:29]`), and wrong operand counts remain refused: `check_encoding` refuses the `abs`/`neg` bits in the raw word so `neg` on an inline integer cannot print as `-N` and be read as a negative constant, and `Stage.u` refuses the printed `|vN|` and `-vN` forms, the modifier tokens and a wrong operand count. +`v_sad_hi_u8` (`0x15b`, 347) and `v_msad_u8` (`0x171`, 369) reuse that four-lane sum through a shared on-demand helper `sad4_u8(uint a, uint b, bool masked)`, emitted only when one of them is referenced: `v_msad_u8` leaves out each byte lane whose `src1` byte is zero (`sad4_u8(a, b, true) + c`), while `v_sad_hi_u8` keeps every lane and shifts the sum before adding `src2` (`(sad4_u8(a, b, false) << 16u) + c`), both modulo 2^32. Those are the formulas of the `tools/pixel_aot.py` table, so the two translators agree, and the existing `sad_u8`, `sad_u16` and `sad_u32` helpers and their emitted text are unchanged. [`tests/startup_gfx2hlsl_sad_hi_msad_check.py`](../tests/startup_gfx2hlsl_sad_hi_msad_check.py) decodes synthetic gfx1013 VOP3A bytes via `G.decode()` only (no game data), checks that each form emits `sad4_u8` plus only its own wrapper and that the unchanged `v_sad_u8` output does not pull in `sad4_u8`, evaluates the emitted HLSL against the AOT formulas over 864 edge/grid triples per form plus pinned normal, zero-`src1`-byte and 2^32-carry rows, and checks the modifier/arity/encoding and unlowered refusals. The semantics are pinned to the AOT reference, not measured on a console: the only hardware draws of these two forms are those of `tests/pixel_aot_check.py`, and what `v_sad_hi_u8` leaves in the high half on Scarlett is not measured here. + [`tests/startup_gfx2hlsl_sad_check.py`](../tests/startup_gfx2hlsl_sad_check.py) decodes synthetic gfx1013 VOP3A bytes via `G.decode()` only (no game data), verifies on-demand helper emission across `Pipeline` and `ComputePipeline`, evaluates the emitted HLSL across 600 edge/grid triples for `v_sad_u8`, 600 for `v_sad_u16` and 605 for `v_sad_u32` (covering `0xffffffff`, `0x80000000`, `0x7fffffff`, byte/halfword boundary carries and `S2` wraparound), checks all modifier/arity/unlowered refusals, and runs mutated-HLSL negative controls (dropped high byte, dropped high halfword, signed `int` subtraction). The encoding guard is pinned per source slot: one row each for `abs` on sources 0, 1 and 2, one for `neg` on each of them, and the same six again with the modifier on an inline `1` (36 rows), and each row reads the refusal back from `G.decode()`'s refusals list and asserts the exact `v_sad_* with neg/abs` reason. That matters because a narrowed mask still ends up refused, just later and by a different guard: with `w0 & 0x700` narrowed to `w0 & 0x100` the `abs` word decodes to `|v1|` and `Stage.u` refuses it, so the pipeline-level control alone passes; the reason check fails, as does the `w1 & 0xe0000000` → `w1 & 0x20000000` narrowing (which silently accepts `neg` on an inline `1` as `-1`). In `draw` mode on Microsoft WARP (`10.0.26100.9818`, DXC `ps_6_0` and FXC `10.0.26100` `ps_5_1`), all 18 good draws (9 per compiler) matched the Python reference and all 6 mutated draws (3 per compiler) produced the exact mutated readback words; the same 18 good and 6 mutated draws also pass on the NVIDIA GeForce GTX 1660 SUPER (driver 32.0.16.1074, Windows build 26200), where the debug layer is not installed and so the `_debug1` variants skip with exit 77. ```powershell ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_sad_(controls|warp|hardware)$' -V +ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_sad_hi_msad_controls$' -V ## Startup translator: signed 4-bit offset conversion (`v_cvt_off_f32_i4`) `tools/startup/gfx2hlsl.py` lowers `v_cvt_off_f32_i4` in VOP1 `_e32` (`0x0e`) and VOP3A `_e64` (`0x18e`) via diff --git a/tests/startup_gfx2hlsl_sad_check.py b/tests/startup_gfx2hlsl_sad_check.py index f89588c73..09d63fe62 100644 --- a/tests/startup_gfx2hlsl_sad_check.py +++ b/tests/startup_gfx2hlsl_sad_check.py @@ -178,8 +178,10 @@ def mut_sad_u32(a, b, c): # ---- 32-bit HLSL expression evaluator (supports uint/int, abs(), and sad_u* helpers) ------------------------- -TOKEN = re.compile(r'\s*(0x[0-9a-fA-F]+u?|\d+u?|[A-Za-z_]\w*|<<|>>|<=|>=|==|!=|\|\||[-+*&|^~!<>?:(),])') -LEVELS = [['||'], ['|'], ['^'], ['&'], ['==', '!='], ['<', '>', '<=', '>='], ['<<', '>>'], ['+', '-'], ['*']] +# `&&` and the `true`/`false` literals are what the bool `masked` argument of the shared sad4_u8 helper needs +# (tests/startup_gfx2hlsl_sad_hi_msad_check.py); no existing sad_u* helper uses them. +TOKEN = re.compile(r'\s*(0x[0-9a-fA-F]+u?|\d+u?|[A-Za-z_]\w*|<<|>>|<=|>=|==|!=|\|\||&&|[-+*&|^~!<>?:(),])') +LEVELS = [['&&'], ['||'], ['|'], ['^'], ['&'], ['==', '!='], ['<', '>', '<=', '>='], ['<<', '>>'], ['+', '-'], ['*']] class HlslExpr: @@ -217,6 +219,8 @@ def binary(self, level): return node def unary(self): + if self.peek() in ('true', 'false'): + return ('bool', self.take() == 'true') token = self.take() if token in ('~', '-', '!'): return ('u' + token, self.unary()) @@ -239,6 +243,8 @@ def unary(self): def run(self, env, node=None): node = node or self.tree kind = node[0] + if kind == 'bool': + return int(node[1]), False if kind == 'num': return node[1] & MASK, node[2] if kind == 'var': @@ -260,6 +266,8 @@ def run(self, env, node=None): return int({'==': x == y, '!=': x != y, '<': x < y, '>': x > y, '<=': x <= y, '>=': x >= y}[kind]), True if kind == '||': return int(bool(a or b)), True + if kind == '&&': + return int(bool(a) and bool(b)), True return {'|': a | b, '^': a ^ b, '&': a & b, '+': a + b, '-': a - b, '*': a * b}[kind] & MASK, both def call(self, name, args): diff --git a/tests/startup_gfx2hlsl_sad_hi_msad_check.py b/tests/startup_gfx2hlsl_sad_hi_msad_check.py new file mode 100644 index 000000000..bf9ec1f1e --- /dev/null +++ b/tests/startup_gfx2hlsl_sad_hi_msad_check.py @@ -0,0 +1,346 @@ +"""High-half and masked unsigned sum-of-absolute-differences in tools/startup/gfx2hlsl.py. + + (no arguments) translation controls: on-demand helpers, value evaluation against the + tools/pixel_aot.py formulas, the zero-src1-byte and 2^32 carry cases, and + refusals; pure Python + +`v_sad_hi_u8` (VOP3A opcode 0x15b, 347) and `v_msad_u8` (0x171, 369) are lowered like `v_sad_u8`, but the reference +is the AOT table in `tools/pixel_aot.py` so the two translators agree: + + "sad_hi_u8": (3, "(sad4_u8({0}, {1}, false) << 16u) + {2}"), + "msad_u8": (3, "sad4_u8({0}, {1}, true) + {2}"), + +where `sad4_u8(a, b, masked)` sums ABSDIFF over the four byte lanes and, when masked, leaves out each byte lane whose +src1 byte is zero ("Components where the reference value in S1 are zero are not included in the sum"). Both results +are modulo 2^32. The fixture decodes synthetic gfx1013 VOP3A bytes via G.decode() only (no game data) and evaluates +the emitted HLSL with the evaluator of tests/startup_gfx2hlsl_sad_check.py. +""" +import re +import struct +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import root_blob # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import ( # noqa: E402 + MASK, + POST_WORDS, + PRE_WORDS, + Probe, + check, + refused, + vs_words, + words_text, +) +from startup_gfx2hlsl_sad_check import HlslExpr, vop3a # noqa: E402 + +OPCODES = { + 'v_sad_hi_u8': 0x15b, + 'v_msad_u8': 0x171, +} + +# The helper names the two instructions ask Pipeline.common() for. +HELPERS = { + 'v_sad_hi_u8': 'sad_hi_u8', + 'v_msad_u8': 'msad_u8', +} + +BODY_WORDS = { + op: b''.join(vop3a(code, 12 + lane, 256 + lane, 256 + 4 + lane, 256 + 8 + lane) for lane in range(4)) + for op, code in OPCODES.items() +} +# The unchanged v_sad_u8 body of tests/startup_gfx2hlsl_sad_check.py, used only for the no-regression text check. +BODY_WORDS_U8 = b''.join(vop3a(0x15a, 12 + lane, 256 + lane, 256 + 4 + lane, 256 + 8 + lane) for lane in range(4)) + + +def ps_words(op): + return PRE_WORDS + BODY_WORDS[op] + POST_WORDS + + +# ---- the AOT reference (tools/pixel_aot.py SAD FORMS), evaluated in Python ------------------------------------ +def sad4_u8(a, b, masked): + """Sums |x - y| over the four byte lanes; a masked lane with a zero src1 byte contributes nothing.""" + total = 0 + for shift in (0, 8, 16, 24): + x, y = (a >> shift) & 0xff, (b >> shift) & 0xff + if masked and y == 0: + continue + total += abs(x - y) + return total + + +# The two formula strings above, with {0} = a, {1} = b, {2} = c and the 32-bit wraparound of the destination. +AOT_REFERENCE = { + 'v_sad_hi_u8': lambda a, b, c: ((sad4_u8(a, b, False) << 16) + c) & MASK, + 'v_msad_u8': lambda a, b, c: (sad4_u8(a, b, True) + c) & MASK, +} + +# Word grids with every interesting byte boundary. 1,728 grid triples in total; src1 = 0 and the words with zero +# bytes exercise the masking rule on msad_u8, and S2 = 0xffffffff / 0xfffffc04 exercise the << 16 + S2 wrap. +U8_WORDS = ( + 0x00000000, 0x01020304, 0x04030201, 0x7f80ff00, 0x807f00ff, + 0x00010000, 0x0000ffff, 0x7fffffff, 0x80000000, 0xffffffff, + 0x00ff00ff, 0xff00ff00, +) +U8_ADDENDS = (0, 1, 0x7fffffff, 0x80000000, 0xfffffc04, 0xffffffff) +GRID = {op: [(a, b, c) for a in U8_WORDS for b in U8_WORDS for c in U8_ADDENDS] for op in OPCODES} + +# Explicit cases with hand-computed results: (a, b, c, v_sad_hi_u8, v_msad_u8). The msad_u8 entries are where the +# skip-zero-src1-byte rule changes the sum; the carry rows are where (sum << 16) + S2 wraps 2^32. +CASES = [ + # normal: byte lane 3 differs by 0xe0 and the others match; both forms add c unshifted (msad does not shift). + (0x10203040, 0xf0203040, 5, 0x00e00005, 0x000000e5), + # every src1 byte is zero: v_msad_u8 adds only c, v_sad_hi_u8 keeps all four lanes. + (0x01020304, 0x00000000, 5, 0x000a0005, 0x00000005), + # lanes 0, 2 and 3 are skipped and lane 1 contributes |0x30 - 0x20| = 0x10. + (0x10203040, 0x00002000, 0, 0x00800000, 0x00000010), + # b = 0x000000ff: lane 0 matches and contributes nothing, lanes 1 to 3 are skipped (each would add 0xff). + (0xffffffff, 0x000000ff, 0, 0x02fd0000, 0x00000000), + # 1020 << 16 = 0x03fc0000; adding 0xffffffff wraps 2^32. msad skips every lane and adds c. + (0xffffffff, 0x00000000, 0xffffffff, 0x03fbffff, 0xffffffff), + # (0xfe << 16) + 0xffffffff wraps as well; lane 3 is the only lane not skipped by msad (0xfe + 0xffffffff wraps). + (0xff000000, 0x01000000, 0xffffffff, 0x00fdffff, 0x000000fd), + # The addend of the v_sad_u8 carry control; msad adds it to a skipped-lane sum of zero. + (0xffffffff, 0x00000000, 0xfffffc04, 0x03fbfc04, 0xfffffc04), +] + +# The emitted helper text, pinned exactly (the same style as the inlined sad_u8 helper: a single return statement). +SAD4_U8_HELPER = ( + 'uint sad4_u8(uint a, uint b, bool masked) {' + ' return (masked && ((b & 0xffu) == 0u) ? 0u : uint(abs(int(a & 0xffu) - int(b & 0xffu))))' + ' + (masked && (((b >> 8) & 0xffu) == 0u) ? 0u : uint(abs(int((a >> 8) & 0xffu) - int((b >> 8) & 0xffu))))' + ' + (masked && (((b >> 16) & 0xffu) == 0u) ? 0u : uint(abs(int((a >> 16) & 0xffu) - int((b >> 16) & 0xffu))))' + ' + (masked && (((b >> 24) & 0xffu) == 0u) ? 0u : uint(abs(int((a >> 24) & 0xffu) - int((b >> 24) & 0xffu)))); }') +EXPECTED_HELPER = { + 'v_sad_hi_u8': 'uint sad_hi_u8(uint a, uint b, uint c) { return (sad4_u8(a, b, false) << 16u) + c; }', + 'v_msad_u8': 'uint msad_u8(uint a, uint b, uint c) { return sad4_u8(a, b, true) + c; }', +} + +# The unchanged inline helper of the existing v_sad_u8 lowering, which must stay byte for byte as it was. +SAD_U8_HELPER = ( + 'uint sad_u8(uint a, uint b, uint c) {' + ' return uint(abs(int(a & 0xffu) - int(b & 0xffu)))' + ' + uint(abs(int((a >> 8) & 0xffu) - int((b >> 8) & 0xffu)))' + ' + uint(abs(int((a >> 16) & 0xffu) - int((b >> 16) & 0xffu)))' + ' + uint(abs(int((a >> 24) & 0xffu) - int((b >> 24) & 0xffu))) + c; }') + + +def translate(op): + pipe = G.Pipeline(vs_words([(0, 0, 0)] * 4), ps_words(op), root_blob()) + return pipe, pipe.hlsl_ps() + + +def extract_helpers(hlsl_text): + """Parse emitted helpers into 32-bit evaluators. sad4_u8 has the bool `masked` argument of the AOT helper.""" + helpers = {} + m = re.search(r'^uint sad4_u8\(uint a, uint b, bool masked\) \{ return (.*); \}$', hlsl_text, re.M) + if m: + expr = HlslExpr(m.group(1)) + helpers['sad4_u8'] = lambda a, b, masked, e=expr: e.run({'a': a, 'b': b, 'masked': 1 if masked else 0})[0] + for name in ('sad_hi_u8', 'msad_u8'): + m = re.search(r'^uint %s\(uint a, uint b, uint c\) \{ return (.*); \}$' % name, hlsl_text, re.M) + if m: + expr = HlslExpr(m.group(1), helpers) + helpers[name] = lambda a, b, c, e=expr: e.run({'a': a, 'b': b, 'c': c})[0] + return helpers + + +def lane_evaluators(hlsl_text): + helpers = extract_helpers(hlsl_text) + found = re.findall(r'^\s*v(1[2-5]) = (.*);$', hlsl_text, re.M) + assert [r for r, _ in found] == ['12', '13', '14', '15'], found + return helpers, [HlslExpr(rhs, helpers) for _, rhs in found] + + +def eval_lane(expr, lane, triple): + a, b, c = triple + return expr.run({'v%d' % lane: a, 'v%d' % (4 + lane): b, 'v%d' % (8 + lane): c})[0] + + +def mentions(hlsl_text, name): + """True when `name` is defined or called in the text, without matching another name's suffix (msad_u8/sad_u8).""" + return re.search(r'(? low 16 bits, src1 -> high 16 bits. 'v_cvt_pk_u16_u32': (2, 'min({0}, 0xffffu) | (min({1}, 0xffffu) << 16u)'), @@ -8685,6 +8690,24 @@ def common(self): out.append( 'uint sad_u32(uint a, uint b, uint c) {' ' return (a > b ? a - b : b - a) + c; }') + # v_sad_hi_u8 and v_msad_u8 share the four-lane absolute-difference sum of sad_u8, so it is factored into + # sad4_u8, whose `masked` argument leaves out each byte lane whose src1 byte is zero (v_msad_u8's reference + # rule). The table formulas match tools/pixel_aot.py exactly: sad_hi_u8 is (sad4_u8(a, b, false) << 16) + c + # and msad_u8 is sad4_u8(a, b, true) + c, both modulo 2^32. sad_u8 above keeps its inlined four-term form so + # a translation that uses only v_sad_u8 is unchanged. + if 'v_sad_hi_u8' in self.uses_sad or 'v_msad_u8' in self.uses_sad: + out.append( + 'uint sad4_u8(uint a, uint b, bool masked) {' + ' return (masked && ((b & 0xffu) == 0u) ? 0u : uint(abs(int(a & 0xffu) - int(b & 0xffu))))' + ' + (masked && (((b >> 8) & 0xffu) == 0u) ? 0u : uint(abs(int((a >> 8) & 0xffu) - int((b >> 8) & 0xffu))))' + ' + (masked && (((b >> 16) & 0xffu) == 0u) ? 0u : uint(abs(int((a >> 16) & 0xffu) - int((b >> 16) & 0xffu))))' + ' + (masked && (((b >> 24) & 0xffu) == 0u) ? 0u : uint(abs(int((a >> 24) & 0xffu) - int((b >> 24) & 0xffu)))); }') + if 'v_sad_hi_u8' in self.uses_sad: + out.append( + 'uint sad_hi_u8(uint a, uint b, uint c) { return (sad4_u8(a, b, false) << 16u) + c; }') + if 'v_msad_u8' in self.uses_sad: + out.append( + 'uint msad_u8(uint a, uint b, uint c) { return sad4_u8(a, b, true) + c; }') if self.uses_store_format_xyzw: legacy = [' %sif (field == %du) fmt = %du;' % ('' if i == 0 else 'else ', field, code) for i, (field, code) in enumerate(sorted(STORE_FORMAT_XYZW_LEGACY_FORMATS.items()))] From 6bf9bf1a58dddef2f7988f64736b50cf091a63f6 Mon Sep 17 00:00:00 2001 From: tedin7 <110300616+tedin7@users.noreply.github.com> Date: Thu, 26 Nov 2026 05:56:59 +0100 Subject: [PATCH 138/240] tests: replay the compiled gfx2hlsl compute cases in the GPU check package (#2728) * tests: replay the compiled gfx2hlsl compute cases in the GPU check package The package carries the compiled DXC cs_6_0 objects and case files of tests/startup_gfx2hlsl_compute_check.py (23 cases, 22 mutation controls); Run-GpuCheck.ps1 dispatches them on the selected adapter and reports one gfx2hlsl_shaders section. * tests: fail GPU package replay on a missing or empty manifest --------- Co-authored-by: Royoo <3230853833@qq.com> --- CMakeLists.txt | 4 ++ tests/gpu_case_recorder_check.py | 45 +++++++++++++++++++ tests/hardware_reports_check.py | 23 +++++++++- tools/gpu-check/README.md | 2 + tools/gpu-check/Run-GpuCheck.ps1 | 74 +++++++++++++++++++++++++++++++- tools/package-gpu-check.ps1 | 17 +++++++- tools/record_gpu_cases.py | 67 +++++++++++++++++++++++++++++ 7 files changed, 229 insertions(+), 3 deletions(-) create mode 100644 tests/gpu_case_recorder_check.py create mode 100644 tools/record_gpu_cases.py diff --git a/CMakeLists.txt b/CMakeLists.txt index d68404580..262966cb5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4145,6 +4145,10 @@ if(EXISTS "${INTAKE_PYTHON}") # gfx2hlsl compute stage: entry registers, numthreads and the offen buffer store, dispatched on a plain device (#1412). add_test(NAME startup_gfx2hlsl_compute_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_compute_check.py") + # The GPU check package replays these cases on a contributor's adapter (tools/record_gpu_cases.py). + add_test(NAME gpu_case_recorder COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/gpu_case_recorder_check.py" "${DXC_EXECUTABLE}") + set_tests_properties(gpu_case_recorder PROPERTIES TIMEOUT 300) foreach(adapter IN ITEMS warp hardware) add_test(NAME startup_gfx2hlsl_compute_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_compute_check.py" dispatch "${DXC_EXECUTABLE}" diff --git a/tests/gpu_case_recorder_check.py b/tests/gpu_case_recorder_check.py new file mode 100644 index 000000000..f5f076879 --- /dev/null +++ b/tests/gpu_case_recorder_check.py @@ -0,0 +1,45 @@ +"""tools/record_gpu_cases.py writes what the GPU check package replays: python gpu_case_recorder_check.py [dxc].""" +import shutil +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path[:0] = [str(ROOT / 'tools'), str(ROOT / 'tests')] +import record_gpu_cases as recorder # noqa: E402 +import startup_gfx2hlsl_compute_check as check # noqa: E402 + + +def main(dxc): + with tempfile.TemporaryDirectory() as tmp: + out = Path(tmp) + rows = recorder.record(dxc, out) + assert [r[0] for r in rows if r[2] == 'pass'] == ['gfx2hlsl_compute/' + n for n in check.CASES], rows + controls = {r[0]: r for r in rows if r[2] == 'fail'} + assert sorted(controls) == sorted('gfx2hlsl_compute/control-' + m for m in check.CONTROLS), sorted(controls) + manifest = [line.split('\t') for line in (out / 'manifest.tsv').read_text(encoding='ascii').splitlines()] + assert manifest == [list(r) for r in rows], 'manifest rows differ from the recorded cases' + for ident, compiler, expect, mismatch in manifest: + assert compiler == 'dxc' and expect in ('pass', 'fail'), ident + cso, case = (out / ('%s.%s' % (ident, ext)) for ext in ('cso', 'case')) + assert cso.read_bytes()[:4] == b'DXBC', ident + # group counts, WORDS expected words, 16 root constants, then any formatted input + assert len(case.read_bytes()) >= 4 + 4 * check.WORDS + 64, ident + for mutation, (name, _, _) in check.CONTROLS.items(): + base = out / ('gfx2hlsl_compute/%s.cso' % name) + ctrl = out / ('gfx2hlsl_compute/control-%s.cso' % mutation) + assert base.read_bytes() != ctrl.read_bytes(), 'control %s compiled to the unmutated shader' % mutation + pinned = controls['gfx2hlsl_compute/control-' + mutation][3] + assert pinned == check.CONTROL_MISMATCH.get(mutation, ''), mutation + print('recorded %d gfx2hlsl compute cases and %d controls' % (len(check.CASES), len(check.CONTROLS))) + return 0 + + +if __name__ == '__main__': + if len(sys.argv) > 2: + sys.exit(__doc__) + found = sys.argv[1] if len(sys.argv) == 2 else shutil.which('dxc') + if not found: + print('skip: no dxc on PATH and none given') + sys.exit(77) + sys.exit(main(found)) diff --git a/tests/hardware_reports_check.py b/tests/hardware_reports_check.py index 1727eb5cc..baabffa4d 100644 --- a/tests/hardware_reports_check.py +++ b/tests/hardware_reports_check.py @@ -45,7 +45,8 @@ def table_row(*cells): def report(adapter="Example GPU 100", device="1111", driver="1.0", backend="hardware", lanes=32, - lane_range="32..32", model="0x66", wave64="SKIP", tier=11, bvh="PASS", debug="unavailable"): + lane_range="32..32", model="0x66", wave64="SKIP", tier=11, bvh="PASS", debug="unavailable", + shaders=None): """Return a report in the layout that tools/gpu-check/Run-GpuCheck.ps1 writes.""" head = [f"backend={backend} debug_layer={debug}", f"adapter={adapter} vendor=10de device={device}", f"driver={driver}"] @@ -60,6 +61,14 @@ def report(adapter="Example GPU 100", device="1111", driver="1.0", backend="hard ("bvh_wave64", wave64, head + w64), ("bvh_differential", bvh, head + diff), ] + if shaders: + # The replayed shader cases are one section; the runner lists every case in its block. + verdict = "1 fail" if shaders == "FAIL" else "0 fail" + cases.append(("gfx2hlsl_shaders", shaders, [ + "translated compute shaders replayed from the package (compiler, case, result)", + f"cases: 2 pass, {verdict}, 0 skip of 2", + "dxc gfx2hlsl_compute/A PASS", + "dxc gfx2hlsl_compute/control-dropped-store " + ("FAIL: control not rejected: exit 0" if shaders == "FAIL" else "PASS: control rejected")])) lines = ["## Xbox2Windows GPU report", "", f"Source commit: {COMMIT}", "Windows build: 26100.1000", f"Backend: {backend}", "", "### Summary", "", f"- Adapter: {adapter} (vendor=10de device={device})", f"- Driver: {driver}", @@ -172,6 +181,18 @@ def test_matches_rows_by_device_and_the_software_adapter(self): row = hardware_reports.matching_row(only_report(body), rows) self.assertEqual(row.adapter if row else None, expected) + def test_replayed_shader_cases_are_one_section_that_can_fail(self): + """The shader section changes the pass and failure counts and nothing else in the report cells.""" + plain = hardware_reports.summarize([comment(410, report())], README) + passing = hardware_reports.summarize([comment(411, report(shaders="PASS"))], README) + failing = hardware_reports.summarize([comment(412, report(shaders="FAIL"))], README) + entry = lambda summary: summary["unrecorded"][0] + cells = lambda summary: {k: v for k, v in entry(summary)["cells"].items() if k != "evidence"} + self.assertEqual(entry(passing)["passed"], entry(plain)["passed"] + 1) + self.assertEqual(cells(passing), cells(plain)) + self.assertEqual(entry(failing)["failed"], ["gfx2hlsl_shaders"]) + self.assertEqual(cells(failing), cells(plain)) + def test_markdown_lists_failed_and_skipped_separately(self): """A skipped test is not a failed one, and both are named on the one Tests line. diff --git a/tools/gpu-check/README.md b/tools/gpu-check/README.md index 95286748f..8e4e26e44 100644 --- a/tools/gpu-check/README.md +++ b/tools/gpu-check/README.md @@ -14,4 +14,6 @@ These synthetic Direct3D 12 tests run on x64 Windows with a D3D12 adapter. The r The hardware run uses the high-performance D3D12 adapter selected by DXGI. Check the adapter name in the output, especially on multi-GPU systems. To test another GPU, pass part of its name, for example `.\Run-GpuCheck.ps1 -Adapter Radeon`. The report records the filter, and each test prints the adapter it used. A name that matches no D3D12 hardware adapter fails every test rather than skipping it. To run Microsoft's software renderer separately, use `.\Run-GpuCheck.ps1 -Backend warp`. The runner prints the output and saves `gpu-report-hardware.md` or `gpu-report-warp.md` beside the executable. A reported failure gives exit code 1. An unsupported capability gives a named SKIP and remains visible in the report. +The package also carries compiled copies of the translated compute shader tests (the `cases` folder, 23 cases and 22 mutation controls from `tests/startup_gfx2hlsl_compute_check.py`, built with DXC `cs_6_0`). The runner dispatches each one on the selected adapter and compares every output word, so the report gets one `gfx2hlsl_shaders` section with a line per case. A control passes when the adapter rejects the deliberately wrong shader; a control that reproduces the unmutated output is reported as a failure. They need no compiler. Use `.\Run-GpuCheck.ps1 -NoShaders` to skip them. The recorded cases do not read any game data and nothing leaves your machine. + Review the report, then paste its full contents as a comment on the [hardware coverage thread (#1)](https://github.com/R0Y00/Xbox2Windows/issues/1). Do not open a new GitHub issue. The report includes a summary of the adapter, driver, lane range, per-test results and the shader-visible CBV/SRV/UAV descriptor heap limit when the runtime reports it. If you would like a name or handle displayed in the coverage table, say so in your comment. Reports are shared manually. No game startup or frame rate is measured. diff --git a/tools/gpu-check/Run-GpuCheck.ps1 b/tools/gpu-check/Run-GpuCheck.ps1 index 03af93bee..914203981 100644 --- a/tools/gpu-check/Run-GpuCheck.ps1 +++ b/tools/gpu-check/Run-GpuCheck.ps1 @@ -4,7 +4,8 @@ param( [ValidateSet('hardware', 'warp')] [string]$Backend = 'hardware', [string]$ReportPath, - [Alias('Adapter')][string]$AdapterFilter + [Alias('Adapter')][string]$AdapterFilter, + [switch]$NoShaders ) $ErrorActionPreference = 'Stop' @@ -12,6 +13,12 @@ if (-not $ReportPath) { $ReportPath = Join-Path $PSScriptRoot "gpu-report-$Backe $binary = (Get-Item -LiteralPath (Join-Path $PSScriptRoot 'offscreen_check.exe')).FullName $revision = (Get-Content -Raw -LiteralPath (Join-Path $PSScriptRoot 'SOURCE_COMMIT.txt')).Trim() if ($revision -notmatch '^[0-9a-f]{40}$') { throw 'The package is missing a valid source revision.' } +$manifest = Join-Path $PSScriptRoot 'cases/manifest.tsv' +if (-not $NoShaders) { + if (-not (Test-Path -LiteralPath $manifest -PathType Leaf)) { throw 'The package is missing cases/manifest.tsv.' } + $rows = @(Get-Content -LiteralPath $manifest | Where-Object { -not [string]::IsNullOrWhiteSpace($_) }) + if (-not $rows.Count) { throw 'The shader case manifest is empty.' } +} $windows = Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' $threadUrl = 'https://github.com/R0Y00/Xbox2Windows/issues/1' @@ -72,6 +79,71 @@ foreach ($test in 'dual-uav', 'texture-mips', 'bvh-waves', 'bvh-wave64', 'bvh-di }) } +function Invoke-ShaderCase { + param([string]$Id, [string]$Expect, [string]$Mismatch) + $files = foreach ($extension in 'cso', 'case') { Join-Path $PSScriptRoot "cases/$Id.$extension" } + foreach ($file in $files) { + if (-not (Test-Path -LiteralPath $file)) { return [pscustomobject]@{ Status = 'FAIL'; Note = "missing $file" } } + } + $process = [System.Diagnostics.Process]::new() + $process.StartInfo.FileName = $binary + $process.StartInfo.Arguments = "$Backend --compute-store-case `"$($files[0])`" `"$($files[1])`"" + $process.StartInfo.UseShellExecute = $false + $process.StartInfo.CreateNoWindow = $true + $process.StartInfo.RedirectStandardOutput = $true + $process.StartInfo.RedirectStandardError = $true + try { + if ($AdapterFilter -and $Backend -eq 'hardware') { $process.StartInfo.EnvironmentVariables['XBOX2WINDOWS_ADAPTER'] = $AdapterFilter } + [void]$process.Start() + $stdout = $process.StandardOutput.ReadToEndAsync() + $stderr = $process.StandardError.ReadToEndAsync() + if (-not $process.WaitForExit(60000)) { + $process.Kill() + $process.WaitForExit() + return [pscustomobject]@{ Status = 'FAIL'; Note = 'timed out after 60 seconds' } + } + $code = $process.ExitCode + # Adapter enumeration notices are not diagnostics of the case. + $lines = @(($stderr.Result -split "`r?`n") | Where-Object { $_ -and -not $_.StartsWith('XBOX2WINDOWS_ADAPTER: skipping ') }) + } catch { + return [pscustomobject]@{ Status = 'FAIL'; Note = $_.Exception.Message } + } finally { + $process.Dispose() + } + if ($code -eq 77) { return [pscustomobject]@{ Status = 'SKIP'; Note = 'capability skip (exit 77)' } } + $first = if ($lines.Count) { $lines[0] } else { '' } + if ($Expect -eq 'pass') { + if ($code -eq 0 -and -not $lines.Count) { return [pscustomobject]@{ Status = 'PASS'; Note = '' } } + return [pscustomobject]@{ Status = 'FAIL'; Note = "exit $code $first" } + } + # A mutation control must be rejected: a card that reproduces the unmutated result would hide a real difference. + $rejected = $code -eq 1 -and ($lines | Where-Object { $_ -like '*expected=*' }) -and (-not $Mismatch -or $first -eq $Mismatch) + if ($rejected) { return [pscustomobject]@{ Status = 'PASS'; Note = 'control rejected' } } + return [pscustomobject]@{ Status = 'FAIL'; Note = "control not rejected: exit $code $first" } +} + +# Compiled gfx2hlsl compute cases recorded by tools/record_gpu_cases.py: each one is dispatched on this adapter and +# its output words are compared inside offscreen_check. They need no compiler here. One report section sums them up. +if (-not $NoShaders) { + $shaderLines = [System.Collections.Generic.List[string]]::new() + $counts = @{ PASS = 0; FAIL = 0; SKIP = 0 } + $shaderLines.Add('translated compute shaders replayed from the package (compiler, case, result)') + foreach ($row in $rows) { + $field = $row -split "`t" + $result = Invoke-ShaderCase -Id $field[0] -Expect $field[2] -Mismatch $field[3] + $counts[$result.Status]++ + $shaderLines.Add(("{0} {1} {2}{3}" -f $field[1], $field[0], $result.Status, $(if ($result.Note) { ": $($result.Note)" } else { '' }))) + } + $shaderLines.Insert(1, "cases: $($counts.PASS) pass, $($counts.FAIL) fail, $($counts.SKIP) skip of $($rows.Count)") + $shaderStatus = if ($counts.FAIL) { 'FAIL' } elseif ($counts.PASS) { 'PASS' } else { 'SKIP' } + if ($shaderStatus -eq 'FAIL') { $failed = $true } + $cases.Add([pscustomobject]@{ + Name = "gfx2hlsl_shaders_${Backend}" + Status = $shaderStatus + Details = ($shaderLines -join [Environment]::NewLine) + }) +} + $blocks = @($cases | ForEach-Object { $_.Details }) $adapter = Get-GpuField $blocks '(?m)^adapter=(.+?)\s+vendor=' $vendor = Get-GpuField $blocks '(?m)^adapter=.+?\s+vendor=([0-9A-Fa-f]+)\s+device=' diff --git a/tools/package-gpu-check.ps1 b/tools/package-gpu-check.ps1 index 42eef6353..53697514f 100644 --- a/tools/package-gpu-check.ps1 +++ b/tools/package-gpu-check.ps1 @@ -18,7 +18,19 @@ try { $stage = New-Item -ItemType Directory -Force -Path "$build/package" Copy-Item -LiteralPath "$build/offscreen_check.exe", "$PSScriptRoot/gpu-check/Run-GpuCheck.ps1", "$PSScriptRoot/gpu-check/README.md", 'LICENSE' -Destination $stage Set-Content -LiteralPath "$stage/SOURCE_COMMIT.txt" -Value $revision -Encoding ascii - $files = 'offscreen_check.exe', 'Run-GpuCheck.ps1', 'README.md', 'LICENSE', 'SOURCE_COMMIT.txt' | + + # Compile the gfx2hlsl compute cases here so the package needs no Python or DXC on the user's machine. + $dxcLine = Select-String -LiteralPath "$build/CMakeCache.txt" -Pattern '^DXC_EXECUTABLE:[A-Z]+=(.+)$' | Select-Object -First 1 + if (-not $dxcLine) { throw 'DXC_EXECUTABLE is not in the CMake cache.' } + $dxc = $dxcLine.Matches[0].Groups[1].Value + $python = Join-Path $root 'out/pe-env/Scripts/python.exe' + if (-not (Test-Path -LiteralPath $python)) { throw "Missing $python. Create out/pe-env and install requirements-dev.txt before packaging." } + $cases = Join-Path $stage 'cases' + if (Test-Path -LiteralPath $cases) { Remove-Item -LiteralPath $cases -Recurse -Force } + & $python -B tools/record_gpu_cases.py $dxc $cases + if ($LASTEXITCODE -ne 0) { throw 'Recording the shader cases failed.' } + + $files = 'offscreen_check.exe', 'Run-GpuCheck.ps1', 'README.md', 'LICENSE', 'SOURCE_COMMIT.txt', 'cases' | ForEach-Object { Join-Path $stage $_ } $name = 'Xbox2Windows-GpuCheck-win-x64.zip' $zip = Join-Path $output $name @@ -36,6 +48,9 @@ try { $report -notmatch "$_ - PASS" -and $report -notmatch "(?s)### $_ - SKIP[^#]*skip: fixture requires Shader Model 6\.5" } + if ($report -notmatch 'gfx2hlsl_shaders_warp - PASS' -or $report -notmatch 'cases: ([1-9][0-9]*) pass, 0 fail, 0 skip of \1\b') { + throw 'The extracted package did not replay every recorded shader case on WARP.' + } if ($report -notmatch 'dual_uav_warp - PASS' -or $report -notmatch 'texture_mips_warp - PASS' -or $sm65Missing -or $report -notmatch 'bvh_root_roundtrip_warp - PASS' -or $report -notmatch [regex]::Escape($revision) -or diff --git a/tools/record_gpu_cases.py b/tools/record_gpu_cases.py new file mode 100644 index 000000000..5ff1c888b --- /dev/null +++ b/tools/record_gpu_cases.py @@ -0,0 +1,67 @@ +"""Record the compiled gfx2hlsl compute cases for the GPU check package. + + python -B tools/record_gpu_cases.py + +For every case and every mutation control of tests/startup_gfx2hlsl_compute_check.py this writes the DXC cs_6_0 +object and the case file that `offscreen_check --compute-store-case ` reads, plus a +manifest the package's Run-GpuCheck.ps1 replays on the user's own adapter. The cases are built by the same +run_case() the dispatch tests use, so the bytes are the ones those tests dispatch. Nothing here talks to a GPU: +run_case() is given a runner that does nothing. + +manifest.tsv, one row per case, tab separated, no header: + id compiler expect mismatch + id gfx2hlsl_compute/ or gfx2hlsl_compute/control-; the files are .cso and .case + compiler dxc (cs_6_0) + expect pass: exit 0 and no diagnostics; fail: exit 1 and a `word=... expected=...` diagnostic (a mutation + control that PASSES on a card is the failure) + mismatch for fail rows with a pinned first bad word, that diagnostic line; otherwise empty +""" +import argparse +import os +import shutil +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path[:0] = [str(ROOT / 'tests'), str(ROOT / 'tools'), str(ROOT / 'tools' / 'startup')] +import startup_gfx2hlsl_compute_check as check # noqa: E402 + +COMPILER = 'dxc' +GROUP = 'gfx2hlsl_compute' + + +def record(dxc, output, cases=None, controls=None): + """Write the cases and the manifest into `output`; return the manifest rows.""" + output = Path(output) + target = output / GROUP + target.mkdir(parents=True, exist_ok=True) + rows = [] + jobs = [(name, None) for name in (check.CASES if cases is None else cases)] + jobs += [(check.CONTROLS[m][0], m) for m in (check.CONTROLS if controls is None else controls)] + for name, mutation in jobs: + ident = '%s/%s' % (GROUP, 'control-' + mutation if mutation else name) + with tempfile.TemporaryDirectory() as tmp: + # The runner is only started to be refused: python rejects the adapter word as a script name. + check.run_case(name, dxc, sys.executable, 'warp', Path(tmp), mutation) + for ext in ('cso', 'case'): + shutil.copyfile(Path(tmp) / ('%s.%s' % (name, ext)), output / ('%s.%s' % (ident, ext))) + rows.append((ident, COMPILER, 'fail' if mutation else 'pass', check.CONTROL_MISMATCH.get(mutation, '') if mutation else '')) + with open(output / 'manifest.tsv', 'w', newline='\n', encoding='ascii') as manifest: + for row in rows: + manifest.write('\t'.join(row) + '\n') + return rows + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('dxc') + parser.add_argument('output') + args = parser.parse_args() + rows = record(args.dxc, args.output) + print('recorded %d cases (%d controls) into %s' % (len(rows), sum(r[2] == 'fail' for r in rows), args.output)) + return 0 + + +if __name__ == '__main__': + sys.exit(main()) From 2a9c252f34d78c9dee0ba77c82ac91151964848a Mon Sep 17 00:00:00 2001 From: tedin7 <110300616+tedin7@users.noreply.github.com> Date: Thu, 26 Nov 2026 06:02:34 +0100 Subject: [PATCH 139/240] test: run startup_resource_address_index without MSVC Debug iterator checks (#2633) --- CMakeLists.txt | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index 262966cb5..d65922489 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -742,6 +742,9 @@ set_tests_properties(startup_placement_publish_shrink_control PROPERTIES WILL_FA add_executable(startup_resource_address_index_check tests/startup_resource_address_index_check.cpp) target_compile_features(startup_resource_address_index_check PRIVATE cxx_std_17) target_include_directories(startup_resource_address_index_check PRIVATE src) +# The 180000 lookups walk std::multimap and std::map nodes; MSVC Debug iterator checks (level 2) made that take +# minutes. The test checks the lookup answers, not iterator validity, so this one target runs without them. +target_compile_definitions(startup_resource_address_index_check PRIVATE $<$,$>:_ITERATOR_DEBUG_LEVEL=0>) add_test(NAME startup_resource_address_index COMMAND startup_resource_address_index_check) add_test(NAME startup_resource_address_index_skip_control COMMAND startup_resource_address_index_check --mutate skip) add_test(NAME startup_resource_address_index_unsync_control COMMAND startup_resource_address_index_check --mutate unsync) From b408241e715736743c59385cfc2ce8b6cfe3be26 Mon Sep 17 00:00:00 2001 From: RonLogic Date: Thu, 26 Nov 2026 07:02:38 +0200 Subject: [PATCH 140/240] test: cover wrapper allocation failures for placed resources (#2740) Co-authored-by: RonLogic <307541314+RonLogic@users.noreply.github.com> --- CMakeLists.txt | 2 +- tests/startup_wrap_allocation.cpp | 28 ++++++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index d65922489..4ef958b1c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1458,7 +1458,7 @@ foreach(backend IN ITEMS warp hardware) endforeach() # #2653: a failed wrapper allocation returns E_OUTOFMEMORY with a null output from device creation and slots 8, 9, 14, -# 16, 55, 73 and 127. `control` never arms the failure, so the fixture must report it. +# 16, 55, 73, 127 and both paths through slot 133. `control` never arms the failure. add_executable(startup_wrap_allocation tests/startup_wrap_allocation.cpp) target_compile_features(startup_wrap_allocation PRIVATE cxx_std_17) target_link_libraries(startup_wrap_allocation PRIVATE d3d12_xs_shim d3d12 dxgi) diff --git a/tests/startup_wrap_allocation.cpp b/tests/startup_wrap_allocation.cpp index 6aa966ce2..c2d0b02ec 100644 --- a/tests/startup_wrap_allocation.cpp +++ b/tests/startup_wrap_allocation.cpp @@ -14,6 +14,7 @@ #include #include #include +#include using Microsoft::WRL::ComPtr; @@ -169,6 +170,33 @@ int main(int argc, char** argv) reinterpret_cast(out)); }); + const auto free_backing = [](void* ptr) { VirtualFree(ptr, 0, MEM_RELEASE); }; + const std::unique_ptr backing( + VirtualAlloc(nullptr, 4096, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE), free_backing); + if (!backing) { + std::puts("FAIL: could not allocate slot 133 fixture backing"); + return 3; + } + auto* base = static_cast(backing.get()); + buffer.Width = 256; + D3D12_RESOURCE_DESC texture{}; + texture.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + texture.Width = texture.Height = 4; + texture.DepthOrArraySize = texture.MipLevels = texture.SampleDesc.Count = 1; + texture.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + texture.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; + + const auto check_placement = [&](const char* name, void* address, const D3D12_RESOURCE_DESC& desc) { + check(name, [&](IUnknown** out) { + return invoke(device.Get(), 133, address, &desc, static_cast(D3D12_RESOURCE_STATE_COMMON), + static_cast(nullptr), &__uuidof(ID3D12Resource), reinterpret_cast(out)); + }); + }; + // The unaligned buffer address selects the desktop stand-in. Slot 133 also has a separate + // texture path, which creates a committed desktop texture before trying to wrap it. + check_placement("Device::slot133 placed buffer", base + 4, buffer); + check_placement("Device::slot133 placed texture", base + 2048, texture); + if (failures) { std::printf("FAIL: %d check(s)\n", failures); return 1; From fd0330461c3cb3b445fb2b4bfbc1c8e5b09c2fd8 Mon Sep 17 00:00:00 2001 From: tedin7 <110300616+tedin7@users.noreply.github.com> Date: Thu, 26 Nov 2026 06:03:01 +0100 Subject: [PATCH 141/240] tests: make startup_run_ps1_check stable under parallel load (#2721) * test: join a wrapped Write-Warning line in startup_run_ps1_check * test: unwrap only when the launcher warning is expected --- tests/startup_run_ps1_check.py | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/tests/startup_run_ps1_check.py b/tests/startup_run_ps1_check.py index 775d1dc3c..2f90f43b4 100644 --- a/tests/startup_run_ps1_check.py +++ b/tests/startup_run_ps1_check.py @@ -93,6 +93,19 @@ WARNING_PREFIXES = {} +def unwrap_first_line(printed, want): + """Join the leading lines of `printed` that PowerShell wrapped at its host width back into `want`. + + The host wraps a long Write-Warning at the console width it finds (80 columns when it is not + attached to a wide console, which depends on load and on the parent), so the one warning can + arrive as two lines. Only a split of exactly `want` is joined; any other text is left as printed. + """ + for count in range(1, len(printed) + 1): + if " ".join(printed[:count]) == want: + return [want, *printed[count:]] + return printed + + def warning_prefix(shell, env): """Return the prefix this shell puts before a Write-Warning message, such as "WARNING: ". @@ -189,6 +202,7 @@ def run_case(shell, script, code, work, translate=False, switches=(), passed=(), want_output = STUB_LINES[:HEAD_LINES] if not fake_user_env and "-FakeUser" not in switches: want_output = [warning_prefix(shell, env) + FAKE_USER_WARNING, *want_output] + printed = unwrap_first_line(printed, want_output[0]) if printed != want_output: found.append(f"stub exit {code}: printed {printed}, expected {want_output} " f"(stderr: {error_text!r})") @@ -345,6 +359,21 @@ def shell_failures(shell, script, tmp): return failures +def unwrap_problems(): + """Controls for unwrap_first_line: a wrapped warning joins, any other text is left alone.""" + want = "WARNING: Without -FakeUser, user API calls go to the host gaming runtime (docs/x.md)." + head = "WARNING: Without -FakeUser, user API calls go to the host gaming runtime" + cases = [ + ("one line", [want, "a"], [want, "a"]), + ("wrapped at 80 columns", [head, "(docs/x.md).", "a"], [want, "a"]), + ("different text", [head, "(docs/other.md).", "a"], [head, "(docs/other.md).", "a"]), + ("missing warning", ["a"], ["a"]), + ] + return [f"unwrap_first_line {name}: got {got}, expected {expected}" + for name, printed, expected in cases + if (got := unwrap_first_line(printed, want)) != expected] + + def main(): if sys.argv[1:] not in ([], ["--text-only"]): sys.exit("usage: startup_run_ps1_check.py [--text-only]") @@ -359,7 +388,7 @@ def main(): mode = "executed with " + ", ".join(Path(shell).stem.lower() for shell in shells) if not shells: mode = "text only: no PowerShell found" - failures = [] + failures = unwrap_problems() with tempfile.TemporaryDirectory() as tmp: # Each shell works in its own scratch dirs, so PowerShell 5.1 and 7 run side by side. with ThreadPoolExecutor(max_workers=len(shells) or 1) as pool: From 8ece26495ee0fbbd1025d3bcff1a87a3bf202f8c Mon Sep 17 00:00:00 2001 From: SimSalabimse <83839581+SimSalabimse@users.noreply.github.com> Date: Thu, 26 Nov 2026 06:11:43 +0100 Subject: [PATCH 142/240] shader: lower s_quadmask_b64 in gfx2hlsl (#1723) (#2678) * shader: lower s_quadmask_b64 in gfx2hlsl (#1723) Port the pixel_aot 64-bit nibble collapse (sixteen bits in D.lo, D.hi = 0). SCC follows the full result. Lane masks, descriptors, and odd pairs refused. Co-authored-by: SimSalabimse * test: allow s_mul_hi_* own-arity templates in scalar table check #2405 added s_mul_hi_i32 (and an early arity refuse for both mul_hi forms). The negative control still expected only one non-IndexError survivor. Co-authored-by: SimSalabimse --------- Co-authored-by: Cursor Agent Co-authored-by: SimSalabimse Co-authored-by: Royoo <3230853833@qq.com> --- .github/workflows/windows.yml | 1 + AGENTS.md | 1 + CMakeLists.txt | 3 + docs/experiments.md | 12 ++ .../startup_gfx2hlsl_s_quadmask_b64_check.py | 173 ++++++++++++++++++ tools/startup/gfx2hlsl.py | 58 +++++- 6 files changed, 247 insertions(+), 1 deletion(-) create mode 100644 tests/startup_gfx2hlsl_s_quadmask_b64_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index f93130f2a..afed1e583 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -328,6 +328,7 @@ jobs: tests/startup_compute_translate_check.py \ tests/startup_gfx2hlsl_swap_check.py \ tests/startup_gfx2hlsl_s_abs_check.py \ + tests/startup_gfx2hlsl_s_quadmask_b64_check.py \ tests/startup_gfx2hlsl_s_ff0_check.py \ tests/startup_gfx2hlsl_s_bitset_check.py \ tests/startup_gfx2hlsl_s_flbit_check.py \ diff --git a/AGENTS.md b/AGENTS.md index 0cc3a2c16..402377e16 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -176,6 +176,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_compute_translate_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_swap_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_s_abs_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_s_quadmask_b64_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_s_ff0_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_s_bitset_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_s_flbit_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 4ef958b1c..273621831 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3374,6 +3374,9 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(startup_gfx2hlsl_s_abs_dispatch_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl lowers s_quadmask_b64 (SOP1, #1723): CPU evaluation and refusals. + add_test(NAME startup_gfx2hlsl_s_quadmask_b64 COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_quadmask_b64_check.py") # gfx2hlsl lowers s_ff0_i32_b32 (SOP1, #1723): CPU evaluation and refusals. add_test(NAME startup_gfx2hlsl_s_ff0 COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_ff0_check.py") diff --git a/docs/experiments.md b/docs/experiments.md index c197e5082..3c35fc0fd 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -8319,6 +8319,18 @@ word (plus an SCC-dependent branch token) against the same reference: `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_s_abs_dispatch_warp$' -V`. [Refs #1723](https://github.com/R0Y00/Xbox2Windows/issues/1723). +**Scalar 64-bit quad mask.** Startup translation lowers `s_quadmask_b64` so each +output bit is the OR of one four-bit group of the 64-bit source: sixteen nibbles +become bits 0..15 of `D.lo`, `D.hi` is 0, and `SCC = (D.lo | D.hi) != 0`, matching +`pixel_aot`. Integer inline constants are interpreted at 64 bits. +An encoded 32-bit literal zero-extends to 64 bits. +Lane masks, descriptor-bearing SGPRs, and odd-aligned pairs are refused. Run +`ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_s_quadmask_b64$' -V` +(or `python3 -B tests/startup_gfx2hlsl_s_quadmask_b64_check.py`). The fixture is +CPU-only and compares negative inline constants with 32-bit literals that +have the same low word. +[Refs #1723](https://github.com/R0Y00/Xbox2Windows/issues/1723). + **Scalar find-first-zero.** Startup translation lowers `s_ff0_i32_b32` to `firstbitlow(~S0)` (0xffffffff when every bit is set), matching `pixel_aot` / `ff0_i32_b32`. SCC is unchanged. Lane masks and descriptor-bearing sources are diff --git a/tests/startup_gfx2hlsl_s_quadmask_b64_check.py b/tests/startup_gfx2hlsl_s_quadmask_b64_check.py new file mode 100644 index 000000000..ff92fa5ae --- /dev/null +++ b/tests/startup_gfx2hlsl_s_quadmask_b64_check.py @@ -0,0 +1,173 @@ +"""s_quadmask_b64 in tools/startup/gfx2hlsl.py (#1723). + +usage: startup_gfx2hlsl_s_quadmask_b64_check.py + +RDNA 2 ISA SOP1: each output bit is the OR of one four-bit group of the 64-bit +source. Sixteen nibbles collapse into bits 0..15 of D.lo; D.hi is 0. +SCC = (D.lo | D.hi) != 0. Matches pixel_aot. Negative integer inline constants +extend to 64 bits and 32-bit literals zero-extend. Lane masks and descriptor sources are refused. +The reference is plain Python; the translated text is evaluated on the CPU. +""" +import re +import struct +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import disasm_rdna2 as D # noqa: E402 +import gfx2hlsl as G # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import Expr # noqa: E402 + +MASK = 0xffffffff +SOP1 = {name: op for op, (name, _) in D.SOP1_OPS.items()} +# (lo, hi) pairs: null, low nibble, high bit of low word, high-word nibble, both halves, all ones. +PAIRS = ( + (0x00000000, 0x00000000), + (0x0000000f, 0x00000000), + (0x80000000, 0x00000000), + (0x00000000, 0x0000000f), + (0x000f0000, 0x00f00000), + (0xffffffff, 0xffffffff), + (0x12345678, 0x9abcdef0), + (0xf0f0f0f0, 0x0f0f0f0f), +) +VCC_LO, EXEC_LO = 106, 126 + +failures = [] + + +def check(label, ok, detail=''): + print('%s: %s' % (label, 'ok' if ok else 'MISMATCH'), flush=True) + if not ok: + failures.append(label) + if detail: + print(' ' + detail) + + +def sop1(name, sdst, ssrc, literal=None): + words = struct.pack('> (4 * group)) & 0xf) != 0) << group for group in range(8)) + + +def quadmask64(lo, hi): + return quadmask32(lo) | (quadmask32(hi) << 8) + + +class Probe(G.Stage): + def __init__(self): + self.lines, self.sym = [], {} + self.used_s, self.used_v, self.uniform_v = set(), set(), set() + self.masks = set() + self.exec_known = True + + +def translate(words, masks=(), sym=None): + decoded = G.decode(words) + assert len(decoded) == 1 and decoded[0][1] == len(words), decoded + stage = Probe() + stage.masks = set(masks) + if sym: + stage.sym.update(sym) + try: + stage.one(decoded[0][2], decoded[0][3]) + except G.Unsupported as error: + stage.lines = ['refused: %s' % error] + return stage.lines, stage.sym + + +def run(lines, env): + env = dict(env) + for line in lines: + m = re.fullmatch(r'(\w+) = (.*);', line) + assert m, line + env[m.group(1)] = Expr(m.group(2)).run(env)[0] + return env + + +def controls(): + bad = None + lines, _ = translate(sop1('s_quadmask_b64', 4, 2)) + assert lines and not lines[0].startswith('refused'), lines + for lo, hi in PAIRS: + out = run(lines, {'s2': lo, 's3': hi, 'scc': 0}) + want_lo = quadmask64(lo, hi) + want = (want_lo, 0, int(want_lo != 0)) + if (out['s4'], out['s5'], int(bool(out['scc']))) != want: + bad = ((hex(lo), hex(hi)), (out['s4'], out['s5'], out['scc']), want) + break + check('s_quadmask_b64 SGPR pair source', bad is None, str(bad)) + + bad = None + for word in (0x00000000, 0x0000000f, 0x80000000, 0x000f0000, 0xffffffff, 0x12345678): + lines, _ = translate(sop1('s_quadmask_b64', 4, 255, word)) + if lines[0].startswith('refused'): + bad = ('refused %s for %s' % (lines[0], hex(word)),) + break + out = run(lines, {'scc': 0}) + want_lo = quadmask64(word, 0) + if (out['s4'], out['s5'], int(bool(out['scc']))) != (want_lo, 0, int(want_lo != 0)): + bad = (hex(word), (out['s4'], out['s5'], out['scc']), (want_lo, 0, int(want_lo != 0))) + break + check('s_quadmask_b64 zero-extended literal', bad is None, str(bad)) + + # SSRC 193 and 208 decode as the inline integers -1 and -16. The same + # low DWORD encoded as a literal must leave the upper eight result bits clear. + for ssrc, want in ((193, 0xffff), (208, 0xfffe)): + lines, _ = translate(sop1('s_quadmask_b64', 4, ssrc)) + out = run(lines, {'scc': 0}) + actual = (out['s4'], out['s5'], int(bool(out['scc']))) + check('s_quadmask_b64 negative inline SSRC %d' % ssrc, actual == (want, 0, 1), str(actual)) + + lines, sym = translate(sop1('s_quadmask_b64', 4, 2), + sym={2: ('const', 0x000f0000), 3: ('const', 0x00f00000)}) + # nibble 4 of lo -> bit 4; nibble 5 of hi -> bit 8+5 = bit 13 + want = quadmask64(0x000f0000, 0x00f00000) + check('s_quadmask_b64 folds a constant pair', + lines[0].startswith('s4 = 0x%08xu;' % want) + and any(line.startswith('s5 = 0u;') or line.startswith('s5 = 0x00000000u;') for line in lines) + and sym.get(4) == ('const', want) + and sym.get(5) == ('const', 0), + str((lines, sym.get(4), sym.get(5), want))) + + refused = [] + for words, masks, sym in ( + (sop1('s_quadmask_b64', VCC_LO, 2), (), None), + (sop1('s_quadmask_b64', 4, VCC_LO), (), None), + (sop1('s_quadmask_b64', 4, 2), (2,), None), + (sop1('s_quadmask_b64', 4, 2), (), {2: ('desc', 0, 0, 0)}), + (sop1('s_quadmask_b64', 3, 2), (), None), # odd destination + (sop1('s_quadmask_b64', 4, 1), (), None), # odd source + ): + lines, _ = translate(words, masks=masks, sym=sym) + refused.append(lines[0]) + check('s_quadmask_b64 refuses lane masks, descriptors, and odd pairs', + all(r.startswith('refused:') for r in refused), str(refused)) + + # Negative control: leave the high-word nibble bits unshifted (<< 0 instead of << 8). + lines, _ = translate(sop1('s_quadmask_b64', 4, 2)) + mutated = [lines[0].replace('<< 8u', '<< 0u', 1)] + lines[1:] + diverged = False + for lo, hi in ((0x00000000, 0x0000000f), (0x000f0000, 0x00f00000)): + good = run(lines, {'s2': lo, 's3': hi, 'scc': 0})['s4'] + bad_out = run(mutated, {'s2': lo, 's3': hi, 'scc': 0})['s4'] + if good != bad_out: + diverged = True + break + check('mutation that drops the high-word shift diverges', diverged, str(mutated[0])) + + +if __name__ == '__main__': + controls() + if failures: + print('FAILED: %s' % ', '.join(failures)) + sys.exit(1) + print('all ok') diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index da7bf4768..ed6f64ddc 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -6658,12 +6658,68 @@ def op_s_flbit_i32_b32(self, ops, mods): self.set_s(dst[1], '(%s == 0u ? 0xffffffffu : 31u - firstbithigh(%s))' % (src_u, src_u)) return None + def op_s_quadmask_b64(self, ops, mods): + """Collapse each nibble of a 64-bit source into bits of D.lo; D.hi = 0 (#1723). + + RDNA 2 ISA SOP1 / pixel_aot: bit g of D.lo is 1 iff nibble g of the 64-bit source is + nonzero (sixteen nibbles → bits 0..15). SCC = (D.lo | D.hi) != 0. + Integer inline constants are 64-bit; 32-bit literals zero-extend. + Lane masks and descriptor SGPRs are refused. + """ + if mods or len(ops) != 2: + raise Unsupported('s_quadmask_b64 with %d operands, expected 2 unmodified' % len(ops)) + dst = reg_range(ops[0]) + if not dst or dst[0] != 's' or dst[2] != dst[1] + 1 or dst[2] > 105 or dst[1] % 2: + raise Unsupported('s_quadmask_b64 destination %s' % ops[0]) + if any(r in self.masks for r in range(dst[1], dst[2] + 1)) or self.is_lane_mask(ops[0]): + raise Unsupported('s_quadmask_b64 on a lane mask') + + def nibble_mask(word): + folded = 0 + for group in range(8): + if word & (0xf << (group * 4)): + folded |= 1 << group + return folded + + def nibble_expr(src_u): + return '(%s)' % ' | '.join( + '((%s & 0x%xu) != 0u ? %du : 0u)' % (src_u, 0xf << (g * 4), 1 << g) + for g in range(8)) + + imm = re.fullmatch(r'0x[0-9a-fA-F]{1,8}|-?\d+', ops[1]) + if imm: + value = int(ops[1], 0) & 0xffffffffffffffff + folded = nibble_mask(value & 0xffffffff) | (nibble_mask(value >> 32) << 8) + self.set_s(dst[1], '0x%08xu' % folded, ('const', folded), scc='$ != 0') + self.set_s(dst[1] + 1, '0u', ('const', 0)) + return None + src = reg_range(ops[1]) + if src is None or src[0] != 's' or src[2] > 105 or src[2] - src[1] != 1 or src[1] % 2: + raise Unsupported('s_quadmask_b64 source %s' % ops[1]) + if any(r in self.masks for r in range(src[1], src[2] + 1)): + raise Unsupported('s_quadmask_b64 on a lane mask') + for n in range(src[1], src[2] + 1): + sym = self.sym.get(n) + if sym and sym[0] not in ('const', 'ud', 'fixed_buffer_word'): + raise Unsupported('s_quadmask_b64 on %s data' % sym[0]) + lo_sym, hi_sym = self.sym.get(src[1]), self.sym.get(src[2]) + if (lo_sym and lo_sym[0] == 'const' and hi_sym and hi_sym[0] == 'const'): + folded = nibble_mask(lo_sym[1] & 0xffffffff) | (nibble_mask(hi_sym[1] & 0xffffffff) << 8) + self.set_s(dst[1], '0x%08xu' % folded, ('const', folded), scc='$ != 0') + self.set_s(dst[1] + 1, '0u', ('const', 0)) + return None + lo_u, hi_u = self.S(src[1]), self.S(src[2]) + # Low 8 bits from the low word; next 8 bits from the high word. High result word is 0. + expr = '((%s) | ((%s) << 8u))' % (nibble_expr(lo_u), nibble_expr(hi_u)) + self.set_s(dst[1], expr, scc='$ != 0') + self.set_s(dst[1] + 1, '0u', ('const', 0)) + return None def op_s_quadmask_b32(self, ops, mods): """Collapse each nibble of S0 to one bit of D; SCC = result != 0 (#1723). RDNA 2 ISA SOP1 / pixel_aot: bit g of D is 1 iff nibble g of S0 is nonzero. - Lane masks and descriptor-bearing SGPRs are refused. The 64-bit form stays out of scope. + Lane masks and descriptor-bearing SGPRs are refused. """ if mods or len(ops) != 2: raise Unsupported('s_quadmask_b32 with %d operands, expected 2 unmodified' % len(ops)) From 83331487b478ad8f0dfd211dd8d5d5cfd3b39d43 Mon Sep 17 00:00:00 2001 From: tedin7 <110300616+tedin7@users.noreply.github.com> Date: Thu, 26 Nov 2026 06:13:19 +0100 Subject: [PATCH 143/240] feat: accept key-independent body scalars read after a compute waterfall (#2737) * feat: accept key-independent body scalars read after a compute readfirstlane waterfall A body scalar written from loop-invariant inputs holds one value in every pass, so the last pass's value is each lane's own. Scalars that read the key stay refused. Extends the waterfall fixture with accepted/refused controls and a WARP dispatch case. * docs: document key-independent live-out scalars in compute waterfalls --- docs/experiments.md | 7 +++++-- tests/startup_compute_waterfall.py | 18 +++++++++++++++--- tools/startup/gfx2hlsl.py | 10 +++++++++- 3 files changed, 29 insertions(+), 6 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 3c35fc0fd..b2b022890 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15852,9 +15852,12 @@ The same checks exercise a [four-thread resource-index waterfall](../tests/start `v_readfirstlane_b32` selects a key and the following `v_cmpx_eq_i32` enables the lanes sharing that key. A saved copy of `exec_lo`, `s_andn2_wrexec_b32` and a backward `s_cbranch_scc1` serve the remaining lanes. Each participating lane can execute one visit with its own key when the body performs proven lane-local operations and its temporary -scalars are dead at exit. The fixtures vary the active count from zero to four, restore EXEC, and check both an +scalars are dead at exit, or are live at exit only when they are key-independent: a scalar written from constants or +other loop-invariant inputs, without reading the key or a key-dependent scalar, holds the same value in every pass. The fixtures vary the active count from zero to four, restore EXEC, and check both an arithmetic result and a key-dependent byte offset in one fixed raw buffer. A read of the group's active mask, -a store inside the loop, a live scalar or a key-selected descriptor keeps an instruction-specific refusal. +a store inside the loop, a live-out scalar that depends on the key (or is computed from it) or a key-selected +descriptor keeps an instruction-specific refusal. The fixtures include a key-independent live-out read after the loop +(accepted, checked against a D3D12 WARP readback) and key-dependent live-outs (refused). ## Desktop audio render sink diff --git a/tests/startup_compute_waterfall.py b/tests/startup_compute_waterfall.py index 1646999c6..ce8e00ab2 100644 --- a/tests/startup_compute_waterfall.py +++ b/tests/startup_compute_waterfall.py @@ -19,6 +19,8 @@ HEAD = ('v_readfirstlane_b32 s22, v5', '05052c7e') COMPARE = ('v_cmpx_eq_i32_e32 s22, v5', '160a247d') ADD = ('s_add_u32 s23, s22, 17', '16911780') +CONST = ('s_mov_b32 s23, 17', '910397be') +USE_CONST = ('v_add_nc_u32 v7, s23, v7', '170e0e4a') XOR = ('v_xor_b32_e32 v7, s23, v0', '17000e3a') CLOSE = ('s_andn2_wrexec_b32 s21, s21', '154795be') RESTORE = ('s_mov_b32 exec_lo, s26', '1a03febe') @@ -54,6 +56,11 @@ def controls(llvm_mc=None): (program(body=(('s_mov_b32 s23, s22', '160397be'), ('s_lshl_b32 s23, s23, 1', '1781178f'), ('s_or_b32 s23, s23, 1', '17811788'), ('s_and_b32 s23, s23, 31', '179f1787'), ('v_add_nc_u32_e32 v7, s23, v0', '17000e4a'))), None), + # A body scalar that does not depend on the key holds one value in every iteration: read after the loop. + (program(body=(CONST, XOR), after_restore=(USE_CONST,)), None), + (program(body=(CONST, ('s_add_u32 s23, s23, s22', '17161780'), XOR), after_restore=(USE_CONST,)), + 'body scalar is live'), + (program(body=(CONST, XOR), after_restore=(('v_mov_b32_e32 v7, s22', '16020e7e'),)), 'body scalar is live'), (program(body=(STORE,)), 'body instruction buffer_store_dword'), (program(body=(('v_mbcnt_lo_u32_b32 v7, exec_lo, 0', '070065d77e000100'),)), 'body instruction v_mbcnt'), (program(after_restore=(live,)), 'body scalar is live'), @@ -79,9 +86,10 @@ def controls(llvm_mc=None): def dispatch(directory, dxc, runner, adapter): - for label, body in (('arithmetic', (ADD, XOR)), ('fixed-buffer', FIXED_LOAD)): + for label, body in (('arithmetic', (ADD, XOR)), ('fixed-buffer', FIXED_LOAD), ('invariant', (CONST, XOR))): src, shader = directory / 'waterfall.hlsl', directory / 'waterfall.cso' - src.write_text(translate(program(body=body)), encoding='ascii') + after = (USE_CONST,) if label == 'invariant' else () + src.write_text(translate(program(body=body, after_restore=after)), encoding='ascii') subprocess.run([dxc, '-T', 'cs_6_0', '-E', 'main', '-Fo', shader, src], check=True) cases = [] inputs = [(n, (64, 32, 64, 96)) for n in range(5)] @@ -93,12 +101,16 @@ def dispatch(directory, dxc, runner, adapter): output = [13] * 4 for lane, key in enumerate(keys[:active]): output[lane] = (((key + 17) & MASK) ^ lane) if label == 'arithmetic' else source[key // 4] + if label == 'invariant': # the body scalar is 17 in every pass: v7 = (17 ^ lane) + 17 + output[lane] = (17 ^ lane) + 17 + if label == 'invariant': + output = [o if i < active else 13 + 17 for i, o in enumerate(output)] # the add runs for every lane case = directory / ('waterfall-%d.case' % len(cases)) words = [1, *output, *([SENTINEL] * (WORDS - 4)), active, *([0] * 15), *source] case.write_bytes(struct.pack('<%dI' % len(words), *words)) cases.append((case, 'keys %s, %d active' % (keys, active), None)) if active == 4 and keys[0] != keys[1]: - wrong = (output[0] ^ 1) if label == 'arithmetic' else output[0] + wrong = (output[0] ^ 1) if label != 'fixed-buffer' else output[0] words[2] = wrong # lane 1 using lane 0's key case = directory / 'waterfall-wrong.case' case.write_bytes(struct.pack('<%dI' % len(words), *words)) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index ed6f64ddc..eaddb40f4 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -2748,6 +2748,7 @@ def waterfall_refusal(self, head, close, effects, live_in, jumps): descriptor_inputs, buffer_descriptors = set(), set() reads_before_write = set() defined = {key} + keyed = {key} # scalars whose value depends on the key (so on the iteration) after the instructions so far for j in range(head + 2, close - 1): base, ops, mods = parse(ins[j][3]) base = re.sub(r'_e(32|64)$', '', base) @@ -2773,6 +2774,10 @@ def waterfall_refusal(self, head, close, effects, live_in, jumps): reads_before_write.update(reads - defined) defined.update(writes) body_writes.update(may_write) + if (reads & keyed) or base == 'buffer_load_dword': + keyed.update(may_write) + else: + keyed -= writes if reads_before_write & body_writes: return 'body reads loop-carried scalar state' # The data byte offset can use the key. Loading or modifying the resource descriptor @@ -2781,7 +2786,10 @@ def waterfall_refusal(self, head, close, effects, live_in, jumps): return 'per-lane descriptor selection requires a proven bound heap range' # The close leaves EXEC and SCC zero. The last physical pass's other scalar # values can differ per lane in this model and must be dead on every successor. - if close + 1 < len(ins) and (body_writes - {'scc'}) & live_in[close + 1]: + # A scalar written from loop-invariant inputs only (no read of the key or of a key-dependent scalar, no + # load through a body address) holds the same value in every iteration, so the last pass's value is each + # lane's own: it may be live. The key and anything computed from it may not. + if close + 1 < len(ins) and (body_writes - {'scc'}) & live_in[close + 1] & (keyed | {key}): return 'body scalar is live at the loop exit' if any(name.startswith('s_movrel') for _, _, name, _ in ins): return 'relative scalar indexing can observe a loop register' From 7f2ed4cec2b3c9b5f2a29a484d1064ddaf42216f Mon Sep 17 00:00:00 2001 From: Royoo <3230853833@qq.com> Date: Thu, 26 Nov 2026 13:13:53 +0800 Subject: [PATCH 144/240] tests: distinguish two copied raw vertex SRVs in one table (#2743) --- docs/experiments.md | 8 ++++ tests/startup_address_srv.cpp | 48 ++++++++++++++++++++++++ tests/startup_copied_vertex_srv_check.py | 39 +++++++++++++++++-- tests/startup_stream_consumer.cpp | 1 + tests/startup_stream_draw.cpp | 3 ++ tests/startup_stream_setup.cpp | 5 ++- 6 files changed, 98 insertions(+), 6 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index b2b022890..350d50a6b 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15926,6 +15926,14 @@ words again after copying the full view back. This covers the copy and lookup sequence through slot 24 for #2695. The descriptor producer in the executable's diagnostic run remains unidentified. +The same test also copies views of two independent placed buffers into one +table. It checks both guest records after each copy, then reads the same +byte offset of each buffer in one vertex shader. Swapping the two views +exchanges the red and green channels, and restoring them restores both +channels. As a control, both manifest bindings name the first record. +That makes both channels match the first record in all 32 pixels while the +guest records remain distinct. + ```powershell cmake --build --preset release --target startup_stream_consumer ctest --preset release --no-tests=error -R '^startup_(copied_vertex_srv|address_buffer_srv|frame_copy)_(warp|hardware)$' -V diff --git a/tests/startup_address_srv.cpp b/tests/startup_address_srv.cpp index 589d1d290..183f25d0a 100644 --- a/tests/startup_address_srv.cpp +++ b/tests/startup_address_srv.cpp @@ -532,6 +532,54 @@ int draw_copied_vertex_buffer_srv(void* guest, void* list) return 0; } +int draw_copied_vertex_srv_pair(void* guest, void* list) +{ + constexpr UINT bytes = 512; + constexpr Word record_bytes = 32; + static std::uint8_t inputs[2][65536 + bytes]{}; + constexpr std::uint32_t values[]{181, 211}; + const D3D12_RESOURCE_DESC buffer{D3D12_RESOURCE_DIMENSION_BUFFER, 0, bytes, 1, 1, 1, + DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; + const Word stride = invoke(guest, 15, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + alignas(64) static std::array descriptors{}; + Word cpu = 0; + if (stride < record_bytes || stride > descriptors.size() / 4 || + !bind_view_table(guest, list, cpu, 4, ptr(descriptors.data()), 4 * stride) || + cpu != ptr(descriptors.data())) return 42; + + ViewAt view{}; + view.view.Format = DXGI_FORMAT_R32_TYPELESS; + view.view.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + view.view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + view.view.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + view.view.Buffer.NumElements = bytes / sizeof(std::uint32_t); + for (Word i = 0; i < 2; ++i) { + void* placed = nullptr; + view.address = (ptr(inputs[i]) + 0xffff) & ~Word{0xffff}; + reinterpret_cast(view.address)[288 / sizeof(std::uint32_t)] = values[i]; + if (FAILED(static_cast(invoke(guest, 133, view.address, ptr(&buffer), D3D12_RESOURCE_STATE_COMMON, + 0, ptr(&__uuidof(ID3D12Resource)), ptr(&placed))))) return 47; + invoke(guest, 70, ptr(&buffer), ptr(&view), cpu + (2 + i) * stride); + } + auto* const records = descriptors.data(); + if (std::memcmp(records + 2 * stride, records + 3 * stride, record_bytes) == 0) return 54; + + const auto draw = [&](Word first, Word second, LONG left, LONG right) { + invoke(guest, 24, 1, cpu, cpu + first * stride, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + invoke(guest, 24, 1, cpu + stride, cpu + second * stride, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + // The shader reads fixed-width guest records. Copy via the reported descriptor stride first. + std::memmove(records + record_bytes, records + stride, record_bytes); + if (std::memcmp(records, records + first * stride, record_bytes) != 0 || + std::memcmp(records + record_bytes, records + second * stride, record_bytes) != 0) return false; + const D3D12_RECT strip{left, 0, right, 4}; + invoke(list, 22, 1, ptr(&strip)); + invoke(list, 12, 3, 1); + return true; + }; + if (!draw(2, 3, 0, 2) || !draw(3, 2, 2, 6) || !draw(2, 3, 6, 8)) return 55; + return 0; +} + int draw_address_buffer_srvs(ID3D12Device* desktop, void* guest, void* list) { static std::array raw_buf0{}; diff --git a/tests/startup_copied_vertex_srv_check.py b/tests/startup_copied_vertex_srv_check.py index 48e0ca0fd..2db2d8ced 100644 --- a/tests/startup_copied_vertex_srv_check.py +++ b/tests/startup_copied_vertex_srv_check.py @@ -5,8 +5,8 @@ from startup_address_srv_check import draw_texture -VERTEX = """ -ByteAddressBuffer records : register(t0); +VERTEX_SHADER = """ +%s struct Vertex { float4 position : SV_Position; nointerpolation uint2 values : TEXCOORD0; @@ -15,11 +15,20 @@ const float2 corners[3] = {float2(-1, 1), float2(3, 1), float2(-1, -3)}; Vertex output; output.position = float4(corners[id], 0.5, 1); - output.values = uint2(records.Load(224), records.Load(288)); + output.values = uint2(%s); return output; } """ +VERTEX = VERTEX_SHADER % ( + "ByteAddressBuffer records : register(t0);", + "records.Load(224), records.Load(288)", +) +PAIR_VERTEX = VERTEX_SHADER % ( + "ByteAddressBuffer first : register(t0);\nByteAddressBuffer second : register(t1);", + "first.Load(288), second.Load(288)", +) + PIXEL = """ float4 main(float4 position : SV_Position, nointerpolation uint2 values : TEXCOORD0) : SV_Target { return float4(float2(values) / 255.0, 0, 1); @@ -42,6 +51,28 @@ def check(directory, consumer, backend): return 0 +def check_pair(directory, consumer, backend): + for name, offset in (("distinct", 32), ("collapsed", 0)): + folder = directory / name + folder.mkdir() + pixels = draw_texture(folder, consumer, backend, PIXEL, + {"X2W_TEST_COPIED_VERTEX_SRV_PAIR": "1"}, + binding=f"srv 0 buf table 0 0\nsrv 1 buf table 0 {offset}", vertex_hlsl=PAIR_VERTEX) + if pixels is None: + return 77 + first = bytes((181, 181 if offset == 0 else 211, 0, 255)) + swapped = bytes((211, 211 if offset == 0 else 181, 0, 255)) + expected = (first * 2 + swapped * 4 + first * 2) * 4 + if pixels != expected: + raise AssertionError(f"{backend}: {name} vertex SRVs got {pixels.hex()}, expected {expected.hex()}") + print(f"{backend}: 32 pixels matched {name} vertex table offsets after swap and restore") + return 0 + + if __name__ == "__main__": with tempfile.TemporaryDirectory() as temporary: - sys.exit(check(Path(temporary), *sys.argv[1:])) + result = check(Path(temporary), *sys.argv[1:]) + if result: + sys.exit(result) + with tempfile.TemporaryDirectory() as temporary: + sys.exit(check_pair(Path(temporary), *sys.argv[1:])) diff --git a/tests/startup_stream_consumer.cpp b/tests/startup_stream_consumer.cpp index 120634bbb..c1bbef00f 100644 --- a/tests/startup_stream_consumer.cpp +++ b/tests/startup_stream_consumer.cpp @@ -484,6 +484,7 @@ int main(int argc, char** argv) GetEnvironmentVariableW(L"X2W_TEST_FORMATTED_BUFFER", nullptr, 0) != 0 || GetEnvironmentVariableW(L"X2W_TEST_FORMATTED_VIEW", nullptr, 0) != 0 || GetEnvironmentVariableW(L"X2W_TEST_JOINED_TABLE", nullptr, 0) != 0 || + GetEnvironmentVariableW(L"X2W_TEST_COPIED_VERTEX_SRV_PAIR", nullptr, 0) != 0 || GetEnvironmentVariableW(L"X2W_TEST_PIXEL_UAV", nullptr, 0) != 0; if (const int rc = prepare_stream_pipeline(argv[1], argv[2], argv[3], hardware, textured, adapter, device, pso)) return rc; diff --git a/tests/startup_stream_draw.cpp b/tests/startup_stream_draw.cpp index f8d331add..d3cdb8910 100644 --- a/tests/startup_stream_draw.cpp +++ b/tests/startup_stream_draw.cpp @@ -377,6 +377,9 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* } else if (GetEnvironmentVariableW(L"X2W_TEST_COPIED_VERTEX_SRV", nullptr, 0)) { extern int draw_copied_vertex_buffer_srv(void*, void*); if (const int result = draw_copied_vertex_buffer_srv(guest, list)) return result; + } else if (GetEnvironmentVariableW(L"X2W_TEST_COPIED_VERTEX_SRV_PAIR", nullptr, 0)) { + extern int draw_copied_vertex_srv_pair(void*, void*); + if (const int result = draw_copied_vertex_srv_pair(guest, list)) return result; } else if (GetEnvironmentVariableW(L"X2W_TEST_ADDRESS_BUFFER_SRV", nullptr, 0)) { extern int draw_address_buffer_srvs(ID3D12Device*, void*, void*); if (const int result = draw_address_buffer_srvs(desktop.Get(), guest, list)) return result; diff --git a/tests/startup_stream_setup.cpp b/tests/startup_stream_setup.cpp index 0ae81cfa5..929f4d3e2 100644 --- a/tests/startup_stream_setup.cpp +++ b/tests/startup_stream_setup.cpp @@ -131,13 +131,14 @@ int prepare_stream_pipeline(const char* vs_path, const char* ps_path, const char D3D12_ROOT_SIGNATURE_DESC root_desc{}; const bool joined_table = GetEnvironmentVariableW(L"X2W_TEST_JOINED_TABLE", nullptr, 0) != 0; - const D3D12_DESCRIPTOR_RANGE srv{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, joined_table ? 2u : 1u, 0, 0, 0}; + const bool vertex_srv_pair = GetEnvironmentVariableW(L"X2W_TEST_COPIED_VERTEX_SRV_PAIR", nullptr, 0) != 0; + const D3D12_DESCRIPTOR_RANGE srv{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, joined_table || vertex_srv_pair ? 2u : 1u, 0, 0, 0}; D3D12_ROOT_PARAMETER textured_parameters[2]{}; if (textured) { D3D12_ROOT_PARAMETER& table = textured_parameters[0]; table.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; table.DescriptorTable = {1, &srv}; - table.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + table.ShaderVisibility = vertex_srv_pair ? D3D12_SHADER_VISIBILITY_VERTEX : D3D12_SHADER_VISIBILITY_PIXEL; root_desc.NumParameters = 1; root_desc.pParameters = textured_parameters; if (joined_table || GetEnvironmentVariableW(L"X2W_TEST_ROOT_RESET", nullptr, 0)) { From caa24ad76d282693ddc09c6936dd434704fbac0a Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Thu, 26 Nov 2026 06:14:49 +0100 Subject: [PATCH 145/240] startup: copy descriptor words into vcc as the upper half of s[104:107] (#2669) s_mov_b64 vcc, s[n:n+1] where both registers hold descriptor words is how the compiler assembles a buffer descriptor whose upper half sits in s106/s107, which vcc aliases. Record the two words as the symbols of s106/s107, emit no code, and mark vcc lost the way the #2057 path does for a descriptor s_load into s[104:107], so any later read of vcc as a mask before it is redefined is refused. A descriptor operand s[104:107] whose s104 holds a descriptor word must now hold four consecutive words of the same descriptor. exec from descriptor data, and other vcc writes from descriptor data, stay refused. AI-assisted. Co-authored-by: tedin7 Co-authored-by: Royoo <3230853833@qq.com> --- .github/workflows/windows.yml | 1 + CMakeLists.txt | 6 + docs/experiments.md | 17 +++ tests/startup_gfx2hlsl_desc_vcc_check.py | 148 +++++++++++++++++++++++ tools/startup/gfx2hlsl.py | 55 ++++++++- 5 files changed, 221 insertions(+), 6 deletions(-) create mode 100644 tests/startup_gfx2hlsl_desc_vcc_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index afed1e583..8b166156b 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -283,6 +283,7 @@ jobs: tests/startup_translator_check.py \ tests/startup_gfx2hlsl_int3_alu_check.py \ tests/startup_gfx2hlsl_smem_offset_check.py \ + tests/startup_gfx2hlsl_desc_vcc_check.py \ tests/startup_gfx2hlsl_sload_const_offset_check.py \ tests/startup_archive_requests_check.py \ tests/startup_gfx2hlsl_refusals_check.py \ diff --git a/CMakeLists.txt b/CMakeLists.txt index 273621831..16951c774 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4270,6 +4270,10 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_sload_s104_check.py" draw "${DXC_EXECUTABLE}" "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_gfx2hlsl_sload_s104_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + add_test(NAME startup_gfx2hlsl_desc_vcc_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_desc_vcc_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_desc_vcc_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() # gfx2hlsl dual-offset/stride-64 32-bit LDS ops and 32-bit LDS atomics (Refs #1541, #2274). add_test(NAME startup_compute_lds_dual_atomics_controls COMMAND "${INTAKE_PYTHON}" -B @@ -4663,6 +4667,8 @@ if(EXISTS "${INTAKE_PYTHON}") # Startup shader translator: s_load descriptor into s[104:107] (vcc is s106/s107) (#1723). add_test(NAME startup_gfx2hlsl_sload_s104 COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_sload_s104_check.py") + add_test(NAME startup_gfx2hlsl_desc_vcc COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_desc_vcc_check.py") # Startup shader translator: scalar constants are dropped at a branch join that another path writes (loop counters). add_test(NAME startup_gfx2hlsl_loop_constants COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_loop_constants_check.py") diff --git a/docs/experiments.md b/docs/experiments.md index 350d50a6b..2135953ea 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15774,6 +15774,23 @@ ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_refusals$' -V python -B tools/startup/gfx2hlsl.py --refusals out/startup/shader_cache ``` +## Startup translator descriptor words in VCC + +An `s_load_dwordx4` from a descriptor table can end at `s[104:107]` +because the translator tracks the four words symbolically (#2057). The same +tracking applies when `s_mov_b64 vcc, s[n:n+1]` copies two descriptor words +from an even-aligned pair into s106/s107. The source registers can then be +overwritten. A load through `s[104:107]` requires four consecutive words of +the same descriptor. Reading VCC as a mask before a new VCC definition is +refused, including on a branch path that bypasses the definition. + +`startup_gfx2hlsl_desc_vcc` checks the symbol copy, descriptor validation, and +mask refusals. The WARP and hardware variants assemble a direct and an aliased +pixel shader and compare both readbacks with the same four words. The +flat-parameter runner binds only entry constants, so the fixture supplies the +buffer bytes through an HLSL load function after checking the translated +resource key and load calls. + ## Startup translator: SMEM offset operands `tools/startup/gfx2hlsl.py` accepts these offset operands for the scalar memory loads ([issue #1674](https://github.com/R0Y00/Xbox2Windows/issues/1674)): diff --git a/tests/startup_gfx2hlsl_desc_vcc_check.py b/tests/startup_gfx2hlsl_desc_vcc_check.py new file mode 100644 index 000000000..ca1601f90 --- /dev/null +++ b/tests/startup_gfx2hlsl_desc_vcc_check.py @@ -0,0 +1,148 @@ +"""Check descriptor words moved into vcc, with optional WARP/hardware pixel readback. + +usage: startup_gfx2hlsl_desc_vcc_check.py [draw [fxc]] +""" +import struct +import sys +import tempfile +from pathlib import Path + +from startup_gfx2hlsl_sload_s104_check import ( + G, TABLE_ROOT, compile_hlsl, draw, translate, vs_words, words_text, +) +from startup_gfx2hlsl_bit_alu_check import POST_WORDS + + +LOAD = 's_load_dwordx4 s[40:43], s[4:5], 0x20' +LOW = 's_mov_b64 s[104:105], s[40:41]' +COPY = 's_mov_b64 vcc, s[42:43]' +CLOBBER = 's_buffer_load_dwordx4 s[40:43], s[40:43], 0x10' +FETCH = 's_buffer_load_dwordx4 s[12:15], s[104:107], 0' +DIRECT = 's_buffer_load_dwordx4 s[12:15], s[40:43], 0' +END = 's_endpgm' +MASK_READ = 'vcc read after a descriptor load into s106/s107' + + +def refuse(message, *instructions): + try: + translate(*instructions, END) + except G.Unsupported as error: + assert message in str(error), (instructions, error) + else: + raise AssertionError(('accepted', instructions)) + + +def smem(op, dst, base, offset): + return (0xf4000000 | op << 18 | dst << 6 | base // 2, 0xfa000000 | offset) + + +def mov64(dst, src): + return 0xbe800400 | dst << 16 | src + + +def pixel_words(alias): + # s_load x4 into s[40:43] from the root table at s[8:9], then wait for the descriptor. + words = [*smem(2, 40, 8, 0x20), 0xbf8c0000] + if alias: + words += [mov64(104, 40), mov64(106, 42), *smem(10, 40, 40, 0x10), 0xbf8c0000] + words += [*smem(10, 12, 104 if alias else 40, 0), 0xbf8c0000] + # v_mov_b32_e32 v12..v15 from s12..s15, then export the four words. + words += [0x7e000200 | reg << 17 | reg for reg in range(12, 16)] + return struct.pack('<%dI' % len(words), *words) + POST_WORDS + + +def main(): + stage = translate(LOAD, LOW, COPY, CLOBBER, FETCH, END) + # Manual mutant: dropping the symbol copy must fail the positive alias or this symbol check. + assert stage.sym[106] == ('desc', ('table', 0), 0x20, 2) + assert stage.sym[107] == ('desc', ('table', 0), 0x20, 3) + assert all(stage.sym[i] == ('fixed_buffer_word',) for i in range(40, 44)) + assert stage.blocks[0][1][-4:] == translate(LOAD, DIRECT, END).blocks[0][1][-4:] + assert not any('vcc =' in line for _, lines, _ in stage.blocks for line in lines) + decoded = [asm for _, _, _, asm in G.decode(pixel_words(True))] + assert COPY in decoded and LOW in decoded, decoded + + # Manual mutant: dropping the vcc_lost marking must fail the straight-line mask refusals. + for read in ( + 'v_cndmask_b32_e32 v0, 0, 1', + 'v_add_co_ci_u32_e32 v0, vcc_lo, 0, 1, vcc_lo', + 'v_sub_co_ci_u32_e64 v0, vcc_lo, 0, 1, vcc_lo', + 'v_subrev_co_ci_u32_e64 v0, vcc_lo, 0, 1, vcc_lo', + 'v_div_fmas_f32_e64 v0, v1, v2, v3', + 'v_cmp_eq_u32_e64 s20, vcc_lo, v1', + 'v_cmp_eq_u32_e32 vcc, v1', + 'v_cmp_eq_u32_sdwa s20, vcc_hi, v1 src0_sel:DWORD src1_sel:DWORD', + 'v_add_u32_e64 v0, vcc, v1', + 's_and_saveexec_b64 s[20:21], vcc', + 's_mov_b32 s20, vcc_lo', + ): + refuse(MASK_READ, LOAD, COPY, read) + for branch in ('s_cbranch_vccz', 's_cbranch_vccnz'): + refuse(MASK_READ, LOAD, COPY, branch + ' label_000C') + compare = 'v_cmp_eq_u32_e32 0, v1' + select = 'v_cndmask_b32_e32 v0, 0, 1' + translate(LOAD, COPY, compare, select, END) + refuse(MASK_READ, LOAD, COPY, 's_cbranch_scc0 label_0010', compare, select) + refuse(MASK_READ, LOAD, COPY, 's_cbranch_scc0 label_000C', 'v_div_fmas_f32_e64 v0, v1, v2, v3') + refuse('overlaps a redefined vcc', LOAD, LOW, COPY, compare, FETCH) + refuse('without a matching load on every path', + LOAD, LOW, 's_cbranch_scc0 label_0010', COPY, FETCH) + + for operation in ( + 's_mov_b64 exec, s[42:43]', + 's_mov_b32 vcc_lo, s42', + 's_and_b64 vcc, s[42:43], -1', + 's_mov_b64 vcc, s[41:42]', + ): + refuse('mask from descriptor data', LOAD, operation) + refuse('even pair of descriptor words', LOAD, 's_mov_b32 s43, 0', COPY) + refuse('even pair of descriptor words', LOAD, 's_mov_b32 s42, 0', COPY) + + # Manual mutant: skipping the consistency check must accept these malformed descriptors. + message = 'needs four consecutive words of the same descriptor' + refuse(message, LOAD, 's_load_dwordx4 s[48:51], s[4:5], 0x30', + 's_mov_b64 s[104:105], s[48:49]', COPY, FETCH) + refuse(message, LOAD, LOW, 's_mov_b32 s105, s40', COPY, FETCH) + overlapping_load = 's_load_dwordx4 s[104:107], s[4:5], 0x20' + translate(overlapping_load, FETCH, END) + refuse(message, overlapping_load, 's_mov_b32 s105, 0', FETCH) + print('ok') + + +def check_draw(dxc, renderer, adapter, fxc=None): + main() + compilers = ([('fxc', fxc, '5_1')] if fxc else []) + [('dxc', dxc, '6_0')] + vs_code = vs_words([(0, 0, 0)] * 4) + payload = [0x3f100000, 0x3f200000, 0x3f300000, 0x3f400000] + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + for alias in (False, True): + pipe = G.Pipeline(vs_code, pixel_words(alias), TABLE_ROOT) + source = pipe.hlsl_ps() + assert set(pipe.resources) == {(('table', 0), 0x20)}, pipe.resources + assert source.count('ByteAddressBuffer r0 : register(t0);') == 1 + assert source.count('r0.Load(') == (8 if alias else 4) + # The flat-param runner only binds b0. Supply the test SRV's bytes in HLSL while + # keeping the translated load addresses, scalar assignments and export in the draw. + fixture = ('uint fixture_load(uint address) {\n' + ' const uint words[8] = {%s, 0u, 0u, 0u, 0u};\n' + ' return words[address >> 2];\n' + '}' % ', '.join('0x%08xu' % word for word in payload)) + source = source.replace('ByteAddressBuffer r0 : register(t0);', fixture) + source = source.replace('r0.Load(', 'fixture_load(') + for kind, compiler, profile in compilers: + vs = compile_hlsl(compiler, kind, pipe.hlsl_vs(), 'vs_%s_%d' % (kind, alias), + 'vs_' + profile, directory) + ps = compile_hlsl(compiler, kind, source, 'ps_%s_%d' % (kind, alias), + 'ps_' + profile, directory) + result = draw(renderer, adapter, vs, ps, words_text(payload)) + assert result.returncode == 0, (kind, alias, result.stdout, result.stderr) + + +if __name__ == '__main__': + if len(sys.argv) == 1: + main() + elif sys.argv[1] == 'draw': + check_draw(*sys.argv[2:]) + else: + raise SystemExit(__doc__) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index eaddb40f4..1388c741f 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -2340,6 +2340,13 @@ def read_vcc(self): elif getattr(self, 'vcc_lost', False): raise Unsupported('vcc read after a descriptor load into s106/s107') + def mark_vcc_descriptor(self): + self.vcc_lost = True + self.vcc_descriptor_overwritten = False + if getattr(self, 'has_branches', False): + value = tuple(self.sym[i] for i in (106, 107)) + self.vcc_events.setdefault(self.pc, []).append(('load_descriptor', value)) + def emit(self, text): if 'vcc' in text: assignment = re.match(r'vcc = (.*);$', text) @@ -2513,6 +2520,10 @@ def descriptor(self, tok): self.vcc_events.setdefault(self.pc, []).append(('read_descriptor', expected)) elif getattr(self, 'vcc_descriptor_overwritten', False): raise Unsupported('descriptor operand %s overlaps a redefined vcc' % tok) + if r == ('s', 104, 107) and s and s[0] == 'desc' and ( + s[3] % 4 or + any(self.sym.get(104 + i) != desc_word(s, s[3] + i) for i in range(1, 4))): + raise Unsupported('descriptor operand %s needs four consecutive words of the same descriptor' % tok) if s and s[0] == 'desc': # A descriptor can start inside a wider load (s_load_dwordx16 fetches two image # descriptors): its offset is the load's offset plus the first register's dword index. @@ -3125,6 +3136,7 @@ def translate(self): self.has_branches = bool(targets) self.spill_slots = {} # (vgpr, lane) -> (sym, uniform) for constant-lane SGPR spills self.vcc_events = {} + self.vcc_lost = self.vcc_descriptor_overwritten = False self.entry_table_pointers = { reg: sym[1] for reg, sym in init_sym.items() if isinstance(reg, int) and sym[0] == 'ptr' and sym[1][0] == 'table' @@ -3315,6 +3327,16 @@ def translate(self): term = ('branch', '!wave_any', term[2]) except Unsupported as reason: if refusals is None: + if self.has_branches and ('read_vcc', None) in self.vcc_events.get(off, ()): + # Some operand handlers refuse VCC before emitting code. Check whether + # a path to this instruction has already overwritten the mask. + self.blocks.append((start, self.lines, None)) + try: + self.check_vcc_paths() + except Unsupported as vcc_reason: + reason = vcc_reason + finally: + self.blocks.pop() if not hasattr(reason, 'instruction'): reason.instruction = name # for fail_reason(); the message itself is unchanged raised_unsupported = reason @@ -3507,6 +3529,19 @@ def uniform_source(self, tok): def one(self, name, asm): _, ops, mods = parse(asm) + if (getattr(self, 'vcc_lost', False) or + (getattr(self, 'has_branches', False) and + ('vcc' in asm or name.startswith(IMPLICIT_VCC_READ)))): + # Read operands even in handlers that refuse a mask as numeric data before calling u(). + # VOPC's two-operand spelling has an implicit destination, and v_cmpx e64 prints an unused SDST. + if name.startswith('v_cmpx') and name.endswith('_e64') and len(ops) == 3: + reads = scalar_tokens(' '.join(ops[1:])) + elif name.startswith('v_cmp') and len(ops) == 2: + reads = scalar_tokens(' '.join(ops)) + else: + reads, _, _ = scalar_effects(name, asm) + if reads & {'vcc', 'vcc_hi'}: + self.read_vcc() if name.endswith('_e32') and name[:-4] in VOP3_ONLY_VEC_U: raise Unsupported(name) base = re.sub(r'_e(32|64)$', '', name) @@ -4296,6 +4331,18 @@ def src_sym(t): r = reg_range(t) return self.sym.get(r[1]) if r and r[0] == 's' else None syms = [src_sym(t) for t in srcs] + mask_dest = dname in ('exec', 'vcc', 'exec_lo', 'vcc_lo', 'exec_hi', 'vcc_hi') + if base == 's_mov_b64' and ops[0] == 'vcc' and len(ops) == 2: + source = reg_range(ops[1]) + if source and source[0] == 's': + words = (syms[0], self.sym.get(source[2])) + if any(word and word[0] == 'desc' for word in words): + if (source[1] % 2 or source[2] != source[1] + 1 or + any(not word or word[0] != 'desc' for word in words)): + raise Unsupported('mask from descriptor data: vcc needs an even pair of descriptor words') + self.sym[106], self.sym[107] = words + self.mark_vcc_descriptor() + return None tg_srcs = [ reg for tok in ops[1:] for r in (reg_range(tok),) if r and r[0] == 's' for reg in range(r[1], r[2] + 1) if self.sym.get(reg) == ('tg_size',) @@ -4330,7 +4377,7 @@ def src_sym(t): raise Unsupported('scc from descriptor data') self.sym['m0'] = syms[0] if base == 's_mov_b32' else ('descnum',) return None - if dname in ('exec', 'vcc', 'exec_lo', 'vcc_lo'): + if mask_dest: raise Unsupported('mask from descriptor data') if dname == 'null': raise Unsupported('scc from descriptor data' if (scc or base in SCC_UNMODELLED) @@ -4840,11 +4887,7 @@ def op_s_load_dwordx4(self, ops, mods, count=4): for i in range(count): self.sym[dst[1] + i] = ('desc', p[1], base_off + off, i) + load if into_vcc: - self.vcc_lost = True - self.vcc_descriptor_overwritten = False - if getattr(self, 'has_branches', False): - value = tuple(self.sym.get(i) for i in (106, 107)) - self.vcc_events.setdefault(self.pc, []).append(('load_descriptor', value)) + self.mark_vcc_descriptor() return if into_vcc: raise Unsupported('s_load destination %s for %d dwords' % (ops[0], count)) From 601eb6210fd1d962db6a75acdced346d36699750 Mon Sep 17 00:00:00 2001 From: tedin7 <110300616+tedin7@users.noreply.github.com> Date: Thu, 26 Nov 2026 06:32:49 +0100 Subject: [PATCH 146/240] shader: lower v_bfm_b32 and missing VOP2/VOP3 ops in gfx2hlsl (Part of #1723) (#2087) * shader: lower v_bfm_b32 in gfx2hlsl Part of #1723 * docs: record v_bfm_b32 lowering and its control command * test: draw v_bfm_b32 on the adapter through the bit ALU suite (#1723) * fix: refuse the VOP2 spelling of v_bfm_b32, which only exists as VOP3 (#1723) --- docs/experiments.md | 11 ++++++++++- tests/startup_gfx2hlsl_bit_alu_check.py | 11 +++++++++++ tools/startup/gfx2hlsl.py | 5 ++++- 3 files changed, 25 insertions(+), 2 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 2135953ea..5646a5544 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15278,7 +15278,7 @@ against an integer reference on the CPU and separately checks refusal of lane masks and the discard destination. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_s_lshl_add$' -V`. -`tools/startup/gfx2hlsl.py` now lowers six gfx1013 per-lane bit operations that it used to refuse: `v_bfe_i32`, `v_bcnt_u32_b32`, `v_ffbl_b32`, `v_ffbh_u32`, `v_ffbh_i32` and `v_bfrev_b32`. They become single HLSL expressions, so no helper function is added to the output: `countbits(a) + b`, `firstbitlow(a)`, `reversebits(a)`, and, for the two high scans, `a == 0u ? 0xffffffffu : 31u - firstbithigh(a)` (the signed form scans `~a` for a negative value and reads 0xffffffff for 0 and -1). `v_bfe_i32` takes the offset from bits 4:0 of source 1 and the width from bits 4:0 of source 2, reads 0 for a width of 0, and sign-extends the field from its top bit; when offset plus width passes 32, the bits above bit 31 repeat bit 31, which is an arithmetic shift of the whole word. The formulas and edge cases are the ones `tools/pixel_aot.py` already draws on WARP. `v_bfe_i32` and `v_bcnt_u32_b32` exist only as VOP3 on gfx1013 (llvm-mc 19 rejects `_e32`); the other four assemble in both `_e32` and `_e64`. Source modifiers, `clamp`, output modifiers, `op_sel` and a wrong operand count are refused with `Unsupported`; the operand count is now checked for every integer operation in this table, where a missing operand used to raise `IndexError`. Not lowered here: the 64-bit carry forms, `v_bfm_b32`, the 24-bit multiplies and `v_alignbit_b32`. +`tools/startup/gfx2hlsl.py` now lowers six gfx1013 per-lane bit operations that it used to refuse: `v_bfe_i32`, `v_bcnt_u32_b32`, `v_ffbl_b32`, `v_ffbh_u32`, `v_ffbh_i32` and `v_bfrev_b32`. They become single HLSL expressions, so no helper function is added to the output: `countbits(a) + b`, `firstbitlow(a)`, `reversebits(a)`, and, for the two high scans, `a == 0u ? 0xffffffffu : 31u - firstbithigh(a)` (the signed form scans `~a` for a negative value and reads 0xffffffff for 0 and -1). `v_bfe_i32` takes the offset from bits 4:0 of source 1 and the width from bits 4:0 of source 2, reads 0 for a width of 0, and sign-extends the field from its top bit; when offset plus width passes 32, the bits above bit 31 repeat bit 31, which is an arithmetic shift of the whole word. The formulas and edge cases are the ones `tools/pixel_aot.py` already draws on WARP. `v_bfe_i32` and `v_bcnt_u32_b32` exist only as VOP3 on gfx1013 (llvm-mc 19 rejects `_e32`); the other four assemble in both `_e32` and `_e64`. Source modifiers, `clamp`, output modifiers, `op_sel` and a wrong operand count are refused with `Unsupported`; the operand count is now checked for every integer operation in this table, where a missing operand used to raise `IndexError`. Not lowered here: the 64-bit carry forms, the 24-bit multiplies and `v_alignbit_b32` (`v_bfm_b32` is lowered separately, see the next entry). `tests/startup_gfx2hlsl_bit_alu_check.py` translates a source-built pixel stage that applies each operation to four lanes (the VOP1 operations alternate `_e32` and `_e64`) and evaluates the generated text with a small 32-bit HLSL evaluator against a reference written from the ISA description with bit loops, string reversal and integer arithmetic. The grid holds 17,459 inputs for `v_bfe_i32` (every offset and width 0 to 31 for 17 base words, plus offsets and widths above 31), 324 for `v_bcnt_u32_b32` and 81 for each scan. Each lowering also has a mutation that must read a wrong word: no sign extension, a subtracted addend, 0 instead of 0xffffffff for zero, no `31u -`, a negative value scanned unchanged, and no bit reversal. On `origin/main` the check fails with `Unsupported: v_bfe_i32`. `binary ` reassembles the fixtures (llvm-mc 19 here; the CI job passes llvm-mc 15). The `draw` mode compiles the translated pair with FXC and DXC and draws one pixel per four input sets through `offscreen_check --startup-flat-param`; the inputs travel as flat vertex parameters so the compilers cannot fold them. It also draws the first set of each operation with the mutated lowering and requires the mutated words in the readback. The evaluator and reference results above come from Linux. The draw mode passed at `48d9571d` on Windows 11 build 26300.9974 with DXC 1.8.2502.11 and the Windows SDK 10.0.26100 FXC, with the debug layer on and 0 errors and 0 warnings. It passed on WARP 10.0.26100.9818 and on an AMD Radeon RX 6600 (driver 32.0.21045.29003). On each adapter, all 34 draws (17 through FXC `ps_5_1` and 17 through DXC `ps_6_0`) matched the reference words, and all 12 mutated draws read their mutated words. Tests: `startup_gfx2hlsl_bit_alu_controls`, `startup_gfx2hlsl_bit_alu_warp` and `startup_gfx2hlsl_bit_alu_hardware`. [AMD RDNA 2 ISA reference](https://docs.amd.com/v/u/en-US/rdna2-shader-instruction-set-architecture) `v_xor3_b32` (`D = S0 ^ S1 ^ S2`, the LLVM 15 and RDNA 2 definition, as in the compute lowering of #1573) joins the same check with 729 grid inputs and three draw sets whose three sources differ in every byte (0x13579bdf, 0x2468ace0, 0xfedcba98 and their rotations); its mutation drops the third operand and reads `src0 ^ src1`. Source modifiers, `clamp`, `op_sel` and a wrong operand count stay refused. `binary` matches the xor3 words with llvm-mc 23; the draw has not run on Windows for it yet. @@ -16546,6 +16546,15 @@ The [MASM fixture](../tests/cpu/switch_sal.asm) emits explicit `/6` byte sequenc Not covered by this experiment: `SAL` outside leaf/switch-lifted functions, and title CPU code execution. +### Startup shader translator: `v_bfm_b32` + +`tools/startup/gfx2hlsl.py` now lowers the gfx1013 bit-field mask `v_bfm_b32` (a VOP3-only instruction: the bare and `_e64` spellings translate, `_e32` is refused) that it used to refuse. The result is a mask of S0[4:0] ones shifted left by S1[4:0], emitted as `(((1u << (a & 31)) - 1) << (b & 31))`, so a width of 0 gives 0 and a shift past the top drops the bits. `v_bfm_b32` is a row of `tests/startup_gfx2hlsl_bit_alu_check.py`: the emitted text runs on its integer evaluator over 1368 width/offset pairs against a plain-integer reference, a swapped width/offset mutation must read other words, and the `draw` mode renders the translated pixel stage on the adapter (FXC 5_1 and DXC 6_0) and reads the words back. Source modifiers, `clamp` and output modifiers are refused with `Unsupported`, as for the sibling integer operations. The WARP draw of the same formula is the existing `pixel_aot_bfm_` test. + +```bash +python3 -B tests/startup_gfx2hlsl_bit_alu_check.py +ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_bit_alu_(controls|warp)$' -V +``` + ## Startup list Dispatch Command-list slot 14 (`Dispatch`) is recorded on the desktop list only when the list is open and direct or compute, a desktop compute pipeline and a desktop compute root signature are bound, the compute root declares no static samplers and only root SRV parameters (slot 43), the compute pipeline was built against that same root signature, every root SRV the root declares was set since the root was bound (a rejected or unaligned replacement clears its binding), and every group count is at most 65535. Zero groups on an axis is forwarded and runs nothing. A root with other parameters is refused with `compute root arguments are not forwarded`, a pipeline from another root with `compute pipeline was built against another root signature`, an unset or rejected root SRV with `a compute root SRV is not bound`. Of the compute root arguments, only root SRVs (slot 43) reach the desktop list: slot 35 records descriptor tables without setting them, and slots 37, 39, 41 and 45 have no handler yet, so a dispatch under any other argument would run with it unset. The first 16 refusals in a process are logged as `x2w-render Dispatch(x, y, z) refused: `. diff --git a/tests/startup_gfx2hlsl_bit_alu_check.py b/tests/startup_gfx2hlsl_bit_alu_check.py index 75f4e5e2a..be2399c57 100644 --- a/tests/startup_gfx2hlsl_bit_alu_check.py +++ b/tests/startup_gfx2hlsl_bit_alu_check.py @@ -54,6 +54,7 @@ def ref_ffbh_i32(x): 'v_ffbh_u32': (1, True, lambda x: next((k for k in range(32) if x >> (31 - k) & 1), MASK)), 'v_ffbh_i32': (1, True, ref_ffbh_i32), 'v_bfrev_b32': (1, True, lambda x: int('{:032b}'.format(x)[::-1], 2)), + 'v_bfm_b32': (2, False, lambda w, o: (((1 << (w & 31)) - 1) << (o & 31)) & MASK), # D.u = ((1 << S0[4:0]) - 1) << S1[4:0] 'v_xor3_b32': (3, False, lambda x, y, z: x ^ y ^ z), # LLVM 15 VOP3 v_xor3_b32: D.u = S0.u ^ S1.u ^ S2.u } # mnemonic -> (pattern in the translated text, replacement): a wrong lowering of the same operation @@ -64,6 +65,8 @@ def ref_ffbh_i32(x): 'v_ffbh_u32': (r'31u - firstbithigh', 'firstbithigh'), # counts from the low end 'v_ffbh_i32': (r'asint\((v\d+)\) < 0 \? ~v\d+ : v\d+', r'\1'), # negative values scanned as is 'v_bfrev_b32': (r'reversebits\((v\d+)\)', r'\1'), # not reversed + 'v_bfm_b32': (r'\(\(\(1u << \((v\d+) & 31\)\) - 1\) << \((v\d+) & 31\)\)', + r'(((1u << (\2 & 31)) - 1) << (\1 & 31))'), # width and offset swapped 'v_xor3_b32': (r'(v\d+) \^ (v\d+) \^ v\d+', r'\1 ^ \2'), # the third operand is dropped } # mnemonic -> the word the mutated lowering must produce, defined from the mutation and the inputs with plain integer @@ -75,6 +78,7 @@ def ref_ffbh_i32(x): 'v_ffbh_u32': lambda x: MASK if x == 0 else x.bit_length() - 1, 'v_ffbh_i32': lambda x: MASK if x in (0, MASK) else 32 - x.bit_length(), 'v_bfrev_b32': lambda x: x, + 'v_bfm_b32': lambda w, o: (((1 << (o & 31)) - 1) << (w & 31)) & MASK, 'v_xor3_b32': lambda x, y, z: x ^ y, } SPECIAL = [0, 1, 2, 3, 0x7f, 0x80, 0xff, 0x7fffffff, 0x80000000, 0x80000001, 0xfffffffe, MASK, 0x55555555, @@ -85,6 +89,7 @@ def ref_ffbh_i32(x): 'v_bfe_i32': [(x, off, w) for x in SPECIAL for off in range(32) for w in range(32)] + [(x, off, w) for x in SPECIAL for off, w in ((32, 33), (63, 0xffffffe5), (0x25, 0x1f))], 'v_bcnt_u32_b32': [(x, y, 0) for x in BITS for y in (0, 1, 32, MASK)], + 'v_bfm_b32': [(w, o, 0) for w in list(range(34)) + [0x3f, 0x40, 0xffffffe0, MASK] for o in list(range(34)) + [0x3f, MASK]], 'v_xor3_b32': [(x, y, z) for x in XOR3_WORDS for y in XOR3_WORDS for z in XOR3_WORDS], } for _name, (_arity, _vop1, _ref) in OPS.items(): @@ -98,6 +103,7 @@ def ref_ffbh_i32(x): (0x55555555, 0, 0), (0, MASK, 0), (0xf0f0f0f0, 7, 0), (0x00010000, 0x80000000, 0)], # Three different sources in every byte (13/24/fe, 57/68/dc, 9b/ac/ba, df/e0/98), so dropping any one source, # or OR, AND or an add for the XOR, reads a different word; the other sets check zero, all ones and a repeat. + 'v_bfm_b32': [(8, 4, 0), (31, 1, 0), (32, 5, 0), (33, 31, 0), (0, 0, 0), (1, 31, 0), (0x25, 0x3f, 0), (MASK, MASK, 0)], 'v_xor3_b32': [(0x13579bdf, 0x2468ace0, 0xfedcba98), (0x2468ace0, 0xfedcba98, 0x13579bdf), (0xfedcba98, 0x13579bdf, 0x2468ace0), (0x0f0f0f0f, 0xa5c30f96, 0x80000001), (0, 0, 0), (MASK, MASK, MASK), (0x13579bdf, 0x13579bdf, 0x2468ace0), (0, 0xdeadbeef, MASK)], @@ -123,6 +129,8 @@ def ref_ffbh_i32(x): '0077187e0d00bbd50101000002771c7e0f00bbd503010000'), 'v_bfrev_b32': bytes.fromhex( '0071187e0d00b8d50101000002711c7e0f00b8d503010000'), + 'v_bfm_b32': bytes.fromhex( + '0c0063d7000902000d0063d7010b02000e0063d7020d02000f0063d7030f0200'), 'v_xor3_b32': bytes.fromhex( '0c0078d5000922040d0078d5010b26040e0078d5020d2a040f0078d5030f2e04'), } @@ -360,6 +368,9 @@ def controls(): check('the same forms without a modifier or operand error translate', not any(refused(a) for a in ( 'v_ffbh_i32_e64 v1, v2', 'v_bfe_i32 v1, v2, v3, v4', 'v_bcnt_u32_b32 v1, v2, v3', 'v_bfrev_b32 v1, v2', 'v_xor3_b32 v1, v2, v3, v4'))) + check('v_bfm_b32 has no VOP2 spelling: _e32 refused, _e64 and the bare name translate', + refused('v_bfm_b32_e32 v1, v2, v3') and not refused('v_bfm_b32_e64 v1, v2, v3') + and not refused('v_bfm_b32 v1, v2, v3')) check('modifiers refused', all(refused(a) for a in ( 'v_ffbh_u32_e64 v1, v2 clamp', 'v_bfe_i32 v1, v2, v3, v4 clamp', 'v_bcnt_u32_b32 v1, v2, v3 clamp', 'v_ffbl_b32_e64 v1, v2 mul:2', 'v_bfrev_b32_e64 v1, -v2', 'v_ffbh_i32_e64 v1, |v2|', diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 1388c741f..fff5ef947 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -3542,7 +3542,8 @@ def one(self, name, asm): reads, _, _ = scalar_effects(name, asm) if reads & {'vcc', 'vcc_hi'}: self.read_vcc() - if name.endswith('_e32') and name[:-4] in VOP3_ONLY_VEC_U: + # v_bfm_b32 exists only as VOP3 (opcode 0x363); a VOP2 spelling is not an instruction. + if name.endswith('_e32') and (name[:-4] in VOP3_ONLY_VEC_U or name[:-4] == 'v_bfm_b32'): raise Unsupported(name) base = re.sub(r'_e(32|64)$', '', name) # Compute the proof before lowering, since a destination can also be a source. @@ -8128,6 +8129,8 @@ def declarations(self): 'v_or3_b32': (3, '{0} | {1} | {2}'), 'v_xor3_b32': (3, '{0} ^ {1} ^ {2}'), 'v_and_or_b32': (3, '({0} & {1}) | {2}'), 'v_lshl_or_b32': (3, '({0} << ({1} & 31)) | {2}'), 'v_xad_u32': (3, '({0} ^ {1}) + {2}'), 'v_bfi_b32': (3, '({0} & {1}) | (~{0} & {2})'), 'v_mul_u32_u24': (2, '({0} & 0xffffffu) * ({1} & 0xffffffu)'), + # v_bfm_b32: a mask of S0[4:0] ones shifted left by S1[4:0] (same field rule as s_bfm_b32). + 'v_bfm_b32': (2, '(((1u << ({0} & 31)) - 1) << ({1} & 31))'), 'v_mul_i32_i24': (2, 'asuint(asint({0} << 8) >> 8) * asuint(asint({1} << 8) >> 8)'), # Per-lane bit operations (AMD RDNA 2 ISA reference). The bitscan results count from the most significant # bit for the "h" forms and read 0xffffffff when no bit qualifies; firstbitlow(0) is already 0xffffffff. From 786970ac04a663137e0e02d8b5c0896d1d94eb85 Mon Sep 17 00:00:00 2001 From: tedin7 <110300616+tedin7@users.noreply.github.com> Date: Thu, 26 Nov 2026 06:35:08 +0100 Subject: [PATCH 147/240] startup: record a UAV of a resource without unordered access as not created (#2710) * startup: record a UAV of a resource without unordered access as not created A view the desktop does not create for lack of the unordered access flag left no record since the skipped-view rework, so a translated compute Dispatch saw no view token and refused with another reason than the one startup_compute_dispatch_texture expects. Record it as not created again; skips for a mismatched dimension keep leaving the previous record alone. * fix: keep a live UAV when a later creation at its handle is refused * fix: keep a copied UAV token and update the pixel UAV denial reason * test: copy the live UAV token from a distinct descriptor slot --- src/startup_stubs/d3d12_capture.inl | 20 +++++++++++++++ src/startup_stubs/d3d12_xs_device.cpp | 10 +++++++- .../startup_compute_dispatch_texture_check.py | 12 +++++++++ tests/startup_pixel_uav_check.py | 4 +-- tests/startup_stream_consumer.cpp | 25 ++++++++++++++++--- 5 files changed, 65 insertions(+), 6 deletions(-) diff --git a/src/startup_stubs/d3d12_capture.inl b/src/startup_stubs/d3d12_capture.inl index 2b51942e8..108e8a883 100644 --- a/src/startup_stubs/d3d12_capture.inl +++ b/src/startup_stubs/d3d12_capture.inl @@ -119,6 +119,26 @@ bool title_backed(u64 title_handle, u64 bytes) ReleaseSRWLockShared(&descriptor_lock); return inside; } +// True when the descriptor already holds a view created on the desktop: by its desktop shadow entry, or by a +// materialized token the title copied into title memory with its own memory copy. +bool descriptor_has_live_view(u64 desktop_handle, u64 title_handle) +{ + AcquireSRWLockShared(¬e_lock); + const std::uint32_t* slot = shadow_slot(desktop_handle); + std::uint32_t id = slot ? *slot : 0; + bool live = id && id - 1 < view_records().size() && view_materialized()[id - 1]; + ReleaseSRWLockShared(¬e_lock); + if (live || title_handle == desktop_handle || !title_backed(title_handle, 32) || + !x2w_local::readable(reinterpret_cast(title_handle), 32)) + return live; + std::uint32_t words[8]; + std::memcpy(words, reinterpret_cast(title_handle), sizeof(words)); + if (words[0] != view_token_magic) return false; + AcquireSRWLockShared(¬e_lock); + live = words[1] < view_records().size() && view_materialized()[words[1]]; + ReleaseSRWLockShared(¬e_lock); + return live; +} void note_pipeline(Wrapper* w, int path, const void* base, const void* desc, std::size_t bytes, Translation* translation = nullptr, const D3D12_BLEND_DESC* blend = nullptr, diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 37ac888e7..c32abf992 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -4438,11 +4438,15 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) }; const char* skip = nullptr; bool default_view = false; + bool uav_denied = false; // a UAV of a resource without unordered access: recorded as not created, as before #2649 if (N == 17) skip = "constant buffer view (title GPU address)"; if (N >= 18 && N <= 21 && args[0]) { const UINT flags = reinterpret_cast(args[0])->GetDesc().Flags; if (N == 18 && (flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE)) skip = "resource denies shader resource views"; - if (N == 19 && !(flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) skip = "resource lacks unordered access"; + if (N == 19 && !(flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { + skip = "resource lacks unordered access"; + uav_denied = true; + } if (N == 20 && !(flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET)) skip = "resource lacks render target"; if (N == 21 && !(flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) skip = "resource lacks depth stencil"; // Every view description of slots 18-21 starts with Format, then ViewDimension. @@ -4491,6 +4495,10 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) record_view(false); } else if constexpr (N == 17) { record_view(false); // Translated constant-buffer views use only the descriptor record. + } else if constexpr (N == 19) { + // A translated compute Dispatch tells this refusal from a descriptor that holds no view by the record. + // A refused creation leaves a descriptor that still holds a live view as it is. + if (uav_denied && !descriptor_has_live_view(args[D], title_dest)) record_view(false); } }; if (skip) { diff --git a/tests/startup_compute_dispatch_texture_check.py b/tests/startup_compute_dispatch_texture_check.py index 4ec3eb508..d317d036a 100644 --- a/tests/startup_compute_dispatch_texture_check.py +++ b/tests/startup_compute_dispatch_texture_check.py @@ -100,6 +100,18 @@ def store(directory, consumer, dxc, env): refused = lines(result, 'refused: ') assert len(refused) == 1 and 'an output texture view was not created on the desktop' in refused[0], result.stderr[-3000:] + # A refused creation over a descriptor that holds a live view keeps that view: the Dispatch still writes the texture. + got, result = run(directory, consumer, env, 'texture-store-occupied', layout) + wrong = [i for i in range(halves) if got[i] != expected[i]] + assert not wrong, 'occupied slot: half=%d (%d halves differ)\n%s' % (wrong[0], len(wrong), result.stderr[-3000:]) + assert len(lines(result, 'Dispatch(2, 1, 1) translated')) == 1, result.stderr[-3000:] + + # The same when the live token reached the slot by a memory copy in title memory instead of a creation there. + got, result = run(directory, consumer, env, 'texture-store-copied', layout) + wrong = [i for i in range(halves) if got[i] != expected[i]] + assert not wrong, 'copied token: half=%d (%d halves differ)\n%s' % (wrong[0], len(wrong), result.stderr[-3000:]) + assert len(lines(result, 'Dispatch(2, 1, 1) translated')) == 1, result.stderr[-3000:] + # Refusals the runtime already had, each with its one logged reason and an untouched texture: an integer view # format, another manifest version, another stage, and (with a manifest line added here for a view the consumer # creates) the output texture named as an input too. diff --git a/tests/startup_pixel_uav_check.py b/tests/startup_pixel_uav_check.py index 4d02c50f1..df0d13f92 100644 --- a/tests/startup_pixel_uav_check.py +++ b/tests/startup_pixel_uav_check.py @@ -45,8 +45,8 @@ 'b': (1, 1, None, None), 'missing': (4, None, 'uav 0 refused: table entry holds no view', None), 'srv': (5, None, 'uav 0 refused: table entry is not an unordered-access view', None), - # The device skips a UAV over a resource without ALLOW_UNORDERED_ACCESS (#2649): no view is recorded, so the draw sees an empty entry. - 'no-ua': (2, None, 'uav 0 refused: table entry holds no view', None), + # The device skips a UAV over a resource without ALLOW_UNORDERED_ACCESS and records it as not created, so the draw names the resource. + 'no-ua': (2, None, 'uav 0 refused: resource lacks ALLOW_UNORDERED_ACCESS', None), 'uint': (3, None, 'uav 0 refused: integer format for a float view', None), 'mip1': (6, None, 'uav 0 refused: view names a mip other than 0', None), 'array': (7, None, 'uav 0 refused: view is not a 2D texture view', None), diff --git a/tests/startup_stream_consumer.cpp b/tests/startup_stream_consumer.cpp index c1bbef00f..1d7afbf74 100644 --- a/tests/startup_stream_consumer.cpp +++ b/tests/startup_stream_consumer.cpp @@ -164,7 +164,7 @@ static void* desktop_pipeline(void* device) // stateb-unreadable, desc-unreadable // dispatch, dispatch-swapped, dispatch-none, dispatch-sampled, dispatch-sampled-unbound, dispatch-heap, // dispatch-heap-outside: one creation, then dispatch_slot67 below -// texture-store, texture-store-none, texture-store-denied: one creation, then texture_slot67 below +// texture-store, texture-store-none, texture-store-denied, texture-store-occupied, texture-store-copied: one creation, then texture_slot67 below // The unreadable cases point at a PAGE_NOACCESS page; code-past-end ends the code on the last byte before one. static void* slot67_pipeline; static void* slot67_root; @@ -306,7 +306,8 @@ static int dispatch_slot67(void* device, const std::string& mode) // three root constants, Dispatch of 2x1x1 groups, and the texture copied to a readback buffer whose 1024 halves go // to X2W_TEST_DISPATCH_OUT. texture-store-none records no Dispatch; texture-store-denied creates the texture // without unordered access, so the stand-in records its view as not created. texture-store-uint makes the texture -// and its view RGBA16_UINT; texture-store-self also creates a shader resource view of the texture at table byte 0. +// and its view RGBA16_UINT; texture-store-occupied then asks for a view of a texture without unordered access at the same +// handle, which keeps the first view; texture-store-self also creates a shader resource view of the texture at table byte 0. static int texture_slot67(void* device, const std::string& mode) { constexpr UINT width = 32, height = 8, pitch = width * 8, bytes = pitch * height; @@ -342,7 +343,25 @@ static int texture_slot67(void* device, const std::string& mode) const StreamWord cpu = invoke(heap, 9), gpu = invoke(heap, 10); if (!cpu || !gpu) return 73; const D3D12_UNORDERED_ACCESS_VIEW_DESC view{format, D3D12_UAV_DIMENSION_TEXTURE2D}; - invoke(device, 19, word(texture), 0, word(&view), cpu + 64); + if (mode != "texture-store-copied") invoke(device, 19, word(texture), 0, word(&view), cpu + 64); + if (mode == "texture-store-copied") { + // The view is created at another handle and its token copied into this slot by memcpy, as a title does; a + // refused creation at this slot then keeps that copied token. + invoke(device, 19, word(texture), 0, word(&view), cpu); + std::memcpy(reinterpret_cast(cpu + 64), reinterpret_cast(cpu), 32); + D3D12_RESOURCE_DESC plain = texture_desc; + plain.Flags = D3D12_RESOURCE_FLAG_NONE; + void* const other = make(D3D12_HEAP_TYPE_DEFAULT, plain, D3D12_RESOURCE_STATE_COMMON); + if (!other) return 79; + invoke(device, 19, word(other), 0, word(&view), cpu + 64); + } else if (mode == "texture-store-occupied") { + // A second creation at the same handle, over a texture without unordered access, is refused and leaves the first view. + D3D12_RESOURCE_DESC plain = texture_desc; + plain.Flags = D3D12_RESOURCE_FLAG_NONE; + void* const other = make(D3D12_HEAP_TYPE_DEFAULT, plain, D3D12_RESOURCE_STATE_COMMON); + if (!other) return 79; + invoke(device, 19, word(other), 0, word(&view), cpu + 64); + } D3D12_SHADER_RESOURCE_VIEW_DESC read{format, D3D12_SRV_DIMENSION_TEXTURE2D, D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; read.Texture2D.MipLevels = 1; if (mode == "texture-store-self") invoke(device, 18, word(texture), word(&read), cpu); From 651577a07f1d7122b21bf6f0010ee0903272b14c Mon Sep 17 00:00:00 2001 From: tedin7 <110300616+tedin7@users.noreply.github.com> Date: Thu, 26 Nov 2026 06:35:26 +0100 Subject: [PATCH 148/240] feat: keep wave-uniformity through pure integer VALU ops in gfx2hlsl (#2722) * feat: keep wave-uniformity through pure integer VALU ops in gfx2hlsl Integer add/sub/logic/shift/mul/min/max of uniform sources is uniform, so a v_readfirstlane past the entry block can recompute it. Extends the compute readfirstlane fixture with a WARP readback case and thread-id / lane-mask negative controls. * test: a shift of a constant-overwritten v0 is a uniform integer chain The case was a refusal only because integer shifts were not uniform; with pure integer ops uniform, 200 >> 6 is the same in every lane. * test: WARP readback of a constant-overwritten VGPR shifted and read with v_readfirstlane Adds the 60 >> 2 shape and a wrong-value control to the compute readfirstlane fixture. * fix: bound the uniform expression of integer chains; document the integer uniform sources A VGPR used as both operands doubled its recompute text on every instruction (30 doublings exhausted memory). The expression is dropped past UNIFORM_EXPR_LIMIT; entry-block reads still copy the VGPR. Documents the integer ops in docs/experiments.md. --- docs/experiments.md | 2 ++ tests/startup_compute_readfirstlane_check.py | 30 +++++++++++++++---- ...up_gfx2hlsl_readfirstlane_uniform_check.py | 23 +++++++++++++- tools/startup/gfx2hlsl.py | 12 ++++++++ 4 files changed, 60 insertions(+), 7 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 5646a5544..e9c56c5ec 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15843,6 +15843,8 @@ The startup shaders are compiled with FXC (shader model 5), which has no wave in In straight-line code with a known `exec`, the proof follows `v_cvt_u32_f32`, `v_cvt_i32_f32`, `v_cvt_f32_u32`, `v_cvt_f32_ubyte0`, `v_mul_f32`, `v_fma_f32`, `v_fmaak_f32`, `v_rcp_f32`, `v_med3_f32`, and `v_mov_b32`, including e32 and e64 forms. Every source must be uniform. The float operations that lower operands as floats accept negation and absolute-value source modifiers. The float-result forms accept the modeled output modifiers `clamp`, `mul:2`, `mul:4`, and `div:2`. +The proof also follows pure 32-bit integer vector ops: `v_add_nc_u32`, `v_sub_nc_u32`, `v_subrev_nc_u32`, `v_and_b32`, `v_or_b32`, `v_xor_b32`, `v_not_b32`, `v_lshlrev_b32`, `v_lshrrev_b32`, `v_ashrrev_i32`, `v_mul_lo_u32`, `v_mul_u32_u24`, `v_min_u32`, `v_max_u32`, `v_min_i32` and `v_max_i32`. Each lane computes the result from its own sources only (no carry-out, lane ID or cross-lane read), so uniform sources give a uniform result and a first-lane read of the chain (for example `(s27 + s27) << 1`, or a VGPR overwritten by a constant and then shifted) translates. A chain from the thread id or from a lane-mask scalar stays refused with `v_readfirstlane_b32 requires a proven uniform source`. The recomputed expression of a VGPR is kept only up to `UNIFORM_EXPR_LIMIT` (4096) characters, because a register used as both operands (`v10 = v10 + v10`) doubles the text each time; a chain past the limit has no recomputable expression, while an entry-block read still copies the VGPR. `tests/startup_compute_readfirstlane_check.py` reads the integer chain and the constant shift back on the GPU with pinned `dropped-int-read` and `dropped-const-shift` controls, and `tests/startup_gfx2hlsl_readfirstlane_uniform_check.py` covers the refused sources and the bounded doubling chain. + Uniform sources include inline constants and literals, SGPRs holding constants, user data or fixed buffer words, other SGPRs tracked as uniform, and VGPRs with an existing proof. A scalar result is tracked as varying when its expression depends on `vcc`, `exec`, `m0`, a varying scalar register, a VGPR without a proof, or a varying `scc`. Descriptor, pointer, and sampler symbols, and SGPRs holding a lane mask (a compare result, even from uniform operands), are treated as non-uniform sources. A 64-bit move proves its high word only from the source high word as it was before the move, never when the destination overlaps it, and a descriptor-path move carries a high-word symbol only when that symbol does not depend on the register's run-time contents. SCC follows the same dependency tracking, with saveexec and wrexec marking it varying. A scalar write to `m0` that also sets SCC judges SCC from the write's sources, so `s_and_b32 m0, vcc_lo, -1` makes it varying while a write from uniform scalars makes it uniform. Instructions whose SCC result is not modelled (`s_add`, `s_sub`, `s_min` and `s_max`, `s_wqm`, and scalar ops on symbolic descriptor words, which emit nothing) mark SCC varying. Scalar buffer loads track the original offset across every destination word, including when the emitted code saves it in a temporary. An overwrite clears the destination's old proof unless the new value is proven uniform. This applies to SDWA forms and all three interpolation forms (`v_interp_p1_f32`, `v_interp_p2_f32`, and `v_interp_mov_f32`). Either WQM form, and restoring `exec` from a saved copy, clears all existing VGPR proofs because they can activate helper lanes. The read takes no modifiers. In straight-line code and in the entry block of a program with branches (before the first branch target and before the first terminator), the proof and the read require known `exec` and the read copies the VGPR; past the entry block the read recomputes the definition instead (below). Every path reaches those instructions through the same instructions, so the program-order tracking is exact there. A branch back to the first instruction ends the entry block at the first instruction, because a loop re-enters it. It now explicitly checks for a single SGPR destination and a single VGPR source. diff --git a/tests/startup_compute_readfirstlane_check.py b/tests/startup_compute_readfirstlane_check.py index f7326e1f7..486de594c 100644 --- a/tests/startup_compute_readfirstlane_check.py +++ b/tests/startup_compute_readfirstlane_check.py @@ -35,6 +35,8 @@ ONE_PATH_LINE = 's25 = uint(max(F((U(2.0 * F((U(float(s20))))))), 0.0));' LOOP_LINE = 's24 = uint(max(F((U(2.0 * F((U(float(s22))))))), 0.0));' POST_LOOP_LINE = 's26 = s22;' +CONST_SHIFT_LINE = 's29 = (0x0000003cu) >> (0x00000002u & 31);' +INT_LINE = 's28 = (s27 + (s27)) << (0x00000001u & 31);' def opcode(table, name): @@ -93,8 +95,14 @@ def build_words(): ws += sopp('s_cbranch_scc1', loop_idx - (len(ws) + 1)) ws += vop1('v_mov_b32_e32', 'v9', 's22') + vop1('v_readfirstlane_b32', 's26', 'v9') ws += sop2('s_lshl_b32', 's27', 's7', 2) + vop2('v_add_nc_u32_e32', 'v4', 's27', 'v0') + # Pure integer ops on a uniform scalar, read past the entry block: (s27 + s27) << 1 (RF1). + ws += (vop1('v_mov_b32_e32', 'v10', 's27') + vop2('v_add_nc_u32_e32', 'v10', 's27', 'v10') + + vop2('v_lshlrev_b32_e32', 'v10', 1, 'v10') + vop1('v_readfirstlane_b32', 's28', 'v10')) + # A VGPR overwritten by a constant, then shifted: 60 >> 2 is the same in every lane (RF1). + ws += (vop1('v_mov_b32_e32', 'v11', 60) + vop2('v_lshrrev_b32_e32', 'v11', 2, 'v11') + + vop1('v_readfirstlane_b32', 's29', 'v11')) ws += sop2('s_add_u32', 's25', 's25', 's21') + sop2('s_add_u32', 's25', 's25', 's23') - ws += sop2('s_add_u32', 's25', 's25', 's26') + ws += sop2('s_add_u32', 's25', 's25', 's26') + sop2('s_add_u32', 's25', 's25', 's28') + sop2('s_add_u32', 's25', 's25', 's29') ws += vop2('v_add_nc_u32_e32', 'v5', 's25', 'v4') + vop2('v_lshlrev_b32_e32', 'v4', 2, 'v4') # buffer_store_dword v5, v4, s[16:19], 0 offen; s_endpgm ws += list(struct.unpack('<2I', bytes.fromhex('001070e004050480'))) + sopp('s_endpgm') @@ -120,6 +128,13 @@ def pack_hex(*ws): ('loop counter updated from lane mask', [(pack_hex(*sop2('s_add_u32', 's22', 's22', 1)), pack_hex(*sop1('s_mov_b32', 's22', 'vcc_lo')))], 'v_readfirstlane_b32 requires a proven uniform source'), + # RF1 negative controls: the integer chain stays refused when a source differs between lanes. + ('integer chain from the thread id', + [(pack_hex(*vop1('v_mov_b32_e32', 'v10', 's27')), pack_hex(*vop1('v_mov_b32_e32', 'v10', 'v0')))], + 'v_readfirstlane_b32 requires a proven uniform source'), + ('integer chain with a lane-mask scalar', + [(pack_hex(*vop2('v_add_nc_u32_e32', 'v10', 's27', 'v10')), pack_hex(*vop2('v_add_nc_u32_e32', 'v10', 'vcc_lo', 'v10')))], + 'v_readfirstlane_b32 requires a proven uniform source'), ) @@ -136,7 +151,8 @@ def expected(): s21 = 9 if gx == 0 else 5 s23 = 0 + 2 + 4 + 6 # sum over uniform loop iterations i=0..3 s26 = 4 - combined = (s25 + s21 + s23 + s26) & MASK + s28 = ((gx * 4) * 2) << 1 + combined = (s25 + s21 + s23 + s26 + s28 + (60 >> 2)) & MASK for tx in range(LOCAL[0]): idx = gx * LOCAL[0] + tx out[idx] = (combined + idx) & MASK @@ -184,7 +200,7 @@ def check_binary(llvm_mc): def controls(llvm_mc=None): pipe = translate() hlsl = pipe.hlsl_cs() - for snippet in (ONE_PATH_LINE, LOOP_LINE, POST_LOOP_LINE, 'u0.Store(a, v5);'): + for snippet in (ONE_PATH_LINE, LOOP_LINE, POST_LOOP_LINE, INT_LINE, CONST_SHIFT_LINE, 'u0.Store(a, v5);'): assert hlsl.count(snippet) == 1, (snippet, hlsl) assert 'uav 0 table 1 16' in pipe.manifest().splitlines(), pipe.manifest() @@ -201,9 +217,11 @@ def controls(llvm_mc=None): CONTROLS = { - 'dropped-one-path': (ONE_PATH_LINE, 's25 = 0u;', 'word=0 expected=0000008b actual=00000019'), - 'dropped-loop-read': (LOOP_LINE, 's24 = 0u;', 'word=0 expected=0000008b actual=0000007f'), - 'dropped-post-loop': (POST_LOOP_LINE, 's26 = 0u;', 'word=0 expected=0000008b actual=00000087'), + 'dropped-one-path': (ONE_PATH_LINE, 's25 = 0u;', 'word=0 expected=0000009a actual=00000028'), + 'dropped-loop-read': (LOOP_LINE, 's24 = 0u;', 'word=0 expected=0000009a actual=0000008e'), + 'dropped-int-read': (INT_LINE, 's28 = 0u;', 'word=4 expected=000000ac actual=0000009c'), + 'dropped-const-shift': (CONST_SHIFT_LINE, 's29 = 0u;', 'word=0 expected=0000009a actual=0000008b'), + 'dropped-post-loop': (POST_LOOP_LINE, 's26 = 0u;', 'word=0 expected=0000009a actual=00000096'), } diff --git a/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py b/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py index eb64bd759..518e72355 100644 --- a/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py +++ b/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py @@ -271,6 +271,9 @@ def run(*instructions, exec_known=True, kind=None, group=None): check(f'wave index of a group of {size} accepted', got[-1] == 's9 = v1;', repr(got)) got = run(WAVE, 's_cbranch_scc0 label_0010', READ1, 's_endpgm', 's_endpgm', kind='cs', group=(64, 1, 1)) check('wave index read past the entry block recomputed as zero', got[-1] == 's9 = 0u;', repr(got)) +# v0 overwritten by a constant is no thread id: the shift of a uniform value is itself uniform (200 >> 6). +got = run('v_mov_b32_e32 v0, 200', WAVE, READ1, kind='cs', group=(64, 1, 1)) +check('shift of an overwritten v0 is a uniform integer chain', got[-1] == 's9 = v1;' and 'v1 = v0 >> (0x00000006u & 31);' in got, repr(got)) for label, instructions, kind, group in ( ('wave index of a group of 65', (WAVE, READ1), 'cs', (65, 1, 1)), ('wave index of a group of 128', (WAVE, READ1), 'cs', (128, 1, 1)), @@ -279,7 +282,6 @@ def run(*instructions, exec_known=True, kind=None, group=None): ('wave index in a graphics stage', (WAVE, READ1), 'ps', (64, 1, 1)), ('wave index without a stage kind', (WAVE, READ1), None, (64, 1, 1)), ('wave index of v1', ('v_lshrrev_b32_e32 v1, 6, v1', READ1), 'cs', (64, 1, 1)), - ('wave index after v0 is overwritten', ('v_mov_b32_e32 v0, 200', WAVE, READ1), 'cs', (64, 1, 1)), ('wave index after v0 is loaded', ('buffer_load_dword v[0:1], off, s[4:7], s2', WAVE, READ1), 'cs', (64, 1, 1)), ('wave index after v0 is swapped', ('v_swap_b32 v2, v0', WAVE, READ1), 'cs', (64, 1, 1)), ('wave index with an output modifier', ('v_lshrrev_b32_e64 v1, 6, v0 clamp', READ1), 'cs', (64, 1, 1)), @@ -338,5 +340,24 @@ def run(*instructions, exec_known=True, kind=None, group=None): finally: G.UNIFORM_VALU = original +# A uniform VGPR used as both operands doubles its recomputation text each time: the text stays bounded (a chain of +# 22 doublings would otherwise grow to megabytes per instruction). The entry-block read copies the VGPR, so it needs no +# expression; only a read past the entry block recomputes, and past the limit that chain has none. +DOUBLE = 'v_add_nc_u32_e32 v7, v7, v7' +got = run(MOVE, *[DOUBLE] * 3, READ, kind='cs', group=(64, 1, 1)) +check('short doubling chain stays readable', isinstance(got, list) and got[-1] == 's9 = v7;', repr(got)[:200]) +stage = G.Stage.__new__(G.Stage) +stage.pipe, stage.lines, stage.attrs = Pipe(), [], {} +stage.pipe.group = (64, 1, 1) +stage.sym = {4 + i: ('desc', ('table', 0), 0, i) for i in range(4)} +stage.sym[3] = ('fixed_buffer_word',) +stage.used_s, stage.used_v, stage.masks, stage.exec_known, stage.kind = set(), set(), set(), True, 'cs' +stage.ins = [(4 * i, 4, a.split()[0], a) for i, a in enumerate([MOVE] + [DOUBLE] * 22)] +stage.translate() +longest = max(map(len, stage.uniform_expr.values()), default=0) +check('long doubling chain keeps a bounded recompute expression', longest <= 2 * G.UNIFORM_EXPR_LIMIT, str(longest)) +got = run(MOVE, *[DOUBLE] * 22, READ, kind='cs', group=(64, 1, 1)) +check('entry-block read of a long doubling chain copies the VGPR', isinstance(got, list) and got[-1] == 's9 = v7;', repr(got)[:200]) + print('Readfirstlane uniformity checks: %d failed' % len(failures)) sys.exit(1 if failures else 0) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index fff5ef947..34cc84c0e 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -846,6 +846,9 @@ def scalar_effects(name, asm): TWO_SCALAR_DESTINATIONS = ('v_add_co', 'v_sub_co', 'v_subrev_co', 'v_div_scale', 'v_mad_u64_u32', 'v_mad_i64_i32') # Symbols whose register also holds the value at run time: constants are assigned when set, entry root constants are # assigned at entry when a join needs it, and the others are assigned when tracked. +# Longest uniform HLSL expression a VGPR keeps for a first-lane read: a chain past it is no longer recomputable. +UNIFORM_EXPR_LIMIT = 4096 + RUN_TIME_SYMBOLS = ('const', 'ud', 'execcopy', 'fixed_buffer_word') @@ -968,6 +971,11 @@ def smem_mods(mods): 'v_cvt_u32_f32', 'v_cvt_i32_f32', 'v_cvt_f32_u32', 'v_cvt_f32_ubyte0', 'v_cvt_off_f32_i4', 'v_cvt_pk_u16_u32', 'v_cvt_pk_i16_i32', 'v_mul_f32', 'v_fma_f32', 'v_fmaak_f32', 'v_rcp_f32', 'v_med3_f32', 'v_mov_b32', + # Pure 32-bit integer ALU: each lane computes the result from its own sources only, so equal sources give + # equal results in every lane (no carry-out, no lane ID, no cross-lane read). + 'v_add_nc_u32', 'v_sub_nc_u32', 'v_subrev_nc_u32', 'v_and_b32', 'v_or_b32', 'v_xor_b32', 'v_not_b32', + 'v_lshlrev_b32', 'v_lshrrev_b32', 'v_ashrrev_i32', 'v_mul_lo_u32', 'v_mul_u32_u24', + 'v_min_u32', 'v_max_u32', 'v_min_i32', 'v_max_i32', )) UNIFORM_LOAD_WORDS = {'buffer_load_dword': 1, 'buffer_load_dwordx2': 2, 'buffer_load_dwordx3': 3, 'buffer_load_dwordx4': 4, @@ -3627,6 +3635,10 @@ def one(self, name, asm): self.uniform_expr[dst] = shifted elif expr is None or loaded or any(n not in self.uniform_expr for n in vs): self.uniform_expr.pop(dst, None) + elif sum(len(self.uniform_expr[n]) for n in vs) > UNIFORM_EXPR_LIMIT: + # A VGPR used as both operands (v10 = v10 + v10) doubles the text each time: past the limit the + # chain has no recomputable expression, so a first-lane read of it is refused. + self.uniform_expr.pop(dst, None) else: self.uniform_expr[dst] = re.sub(r'\bv(\d+)\b', lambda m: '(%s)' % self.uniform_expr[int(m[1])], expr) From a5817910e84df11dcbab9952061effebc9423141 Mon Sep 17 00:00:00 2001 From: tedin7 <110300616+tedin7@users.noreply.github.com> Date: Thu, 26 Nov 2026 06:39:50 +0100 Subject: [PATCH 149/240] shader: add a WARP readback for src_scc (#2725) * test: add a WARP readback for src_scc * docs: document the src_scc WARP readback --- .github/workflows/windows.yml | 1 + CMakeLists.txt | 8 ++ docs/experiments.md | 4 + tests/startup_gfx2hlsl_src_scc_check.py | 108 ++++++++++++++++++++++++ 4 files changed, 121 insertions(+) diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 8b166156b..bcec8358c 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -334,6 +334,7 @@ jobs: tests/startup_gfx2hlsl_s_bitset_check.py \ tests/startup_gfx2hlsl_s_flbit_check.py \ tests/startup_gfx2hlsl_s_ff1_check.py \ + tests/startup_gfx2hlsl_src_scc_check.py \ tests/startup_gfx2hlsl_s_quadmask_check.py \ tests/startup_gfx2hlsl_fma_mix_check.py \ tests/startup_gfx2hlsl_shift64_check.py \ diff --git a/CMakeLists.txt b/CMakeLists.txt index 16951c774..6da3af3c8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3447,6 +3447,14 @@ if(EXISTS "${INTAKE_PYTHON}") # The src_scc scalar source (#1820). add_test(NAME startup_gfx2hlsl_src_scc COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_src_scc_check.py") + # D3D12 UAV readback of s_cmp_eq_u32 + s_mov_b32 sX, src_scc on WARP/hardware vs the CPU reference, + # with a mutated-lowering negative control (same dispatch pattern as s_ff1). + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_src_scc_dispatch_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_src_scc_check.py" dispatch "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_gfx2hlsl_src_scc_dispatch_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() # src_scc at a branch target that one uniform SCC write reaches on every path. add_test(NAME startup_gfx2hlsl_src_scc_join COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_src_scc_join_check.py") diff --git a/docs/experiments.md b/docs/experiments.md index e9c56c5ec..5da2bbd28 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -17072,3 +17072,7 @@ or `scalar_wide_op()`). Reads where incoming SCC is unverified are refused: at s control-flow joins/branch targets, after descriptor-elided SCC writes, and after unmodeled SCC writers in `SCC_UNMODELLED` such as `s_add_u32` (after `s_add_u32` finishes reading its own sources). Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_src_scc$' -V`. +The `_dispatch_warp` and `_dispatch_hardware` tests run `s_cmp_eq_u32` then `s_mov_b32 sX, src_scc` on a D3D12 +UAV dispatch and compare each lane with the CPU reference (SCC 0 and SCC 1, distinct per-case data). A copy of the +lowering mutated to `(scc ? 0u : 1u)` must read back wrong. Run +`ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_src_scc_dispatch_warp$' -V`. diff --git a/tests/startup_gfx2hlsl_src_scc_check.py b/tests/startup_gfx2hlsl_src_scc_check.py index e97bb0595..9a6c64a91 100644 --- a/tests/startup_gfx2hlsl_src_scc_check.py +++ b/tests/startup_gfx2hlsl_src_scc_check.py @@ -1,6 +1,7 @@ """The `src_scc` scalar source in tools/startup/gfx2hlsl.py (issue #1820). usage: startup_gfx2hlsl_src_scc_check.py + startup_gfx2hlsl_src_scc_check.py dispatch The census contained `s_mul_i32 s28, 1.0, src_scc`, refused as `operand 'src_scc'` (#870, issue #1820). Source code 253 reads the SCC bit as the integer value 0 or 1; the generated shader carries SCC as a @@ -18,7 +19,10 @@ """ import os import struct +import subprocess import sys +import tempfile +from pathlib import Path here = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.join(here, '..', 'tools')) @@ -106,6 +110,110 @@ def refused_reason(code): return None +MASK = 0xFFFFFFFF +SOP1_MOV_B32 = 0x03 +# (a, b) pairs: s_cmp_eq_u32 sets SCC = (a == b), then s_mov_b32 s3, src_scc stores it. +DISPATCH_CASES = ((0, 0), (1, 1), (0xFFFFFFFF, 0xFFFFFFFF), (0x12345678, 0x12345678), + (0, 1), (1, 0), (0x80000000, 0x00000001), (0xFFFFFFFF, 0xFFFFFFFE)) + + +def encode_sop1(op, sdst, ssrc): + return struct.pack(' Date: Thu, 26 Nov 2026 06:40:07 +0100 Subject: [PATCH 150/240] startup: lower constant-lane SGPR spills on wave64 lanes and in vertex stages in gfx2hlsl (Part of #1723) (#2712) * feat: lower SGPR spills on wave64 lanes and in vertex stages Symptom: the constant-lane spill idiom v_writelane_b32 vN, sM, k / v_readlane_b32 sD, vN, k was refused for k >= 32 ("lane 40 outside 0..31") and in every vertex stage ("lowered in pixel stages only"), although a wave64 program spills into lanes 0..63 and a vertex stage uses the same idiom. Root cause: the slot model (one scalar per (VGPR, lane)) was limited to wave32 lanes and pixel stages. Neither limit is needed by the model: the two instructions touch only lane k and ignore EXEC in every stage. Change: lanes 0..63 and vertex stages are accepted. The translator does not know the wave size and a wave32 program takes the lane select modulo 32, so a spill VGPR whose lanes include k and k + 32 (one slot in wave32, two in wave64) is refused by name. Lane 64+, compute stages, register lanes, branches (open #2524 territory) stay refused. Test: tests/startup_gfx2hlsl_spill_wave64_check.py (controls fail before: lanes 32..63 and the vertex stage refused). The existing sgpr_spill controls now expect lane 64 and the k/k+32 pair refused and the vertex stage accepted. Win2025 WARP dev and release, DXC and FXC: the pixel draw matches the slot reference on 256/256 pixels, the vertex draw exports the reference param0, and all five wrong-lane/ignored-overwrite mutations fail. (cherry picked from commit c7fe3e44b10ffb4ebdf40caab7d8306926b3a881) * fix: apply the k / k + 32 spill lane rule to pixel and vertex stages only, slot 57 mesh is always wave64 --- CMakeLists.txt | 9 + docs/experiments.md | 2 + tests/startup_gfx2hlsl_sgpr_spill_check.py | 9 +- tests/startup_gfx2hlsl_spill_wave64_check.py | 300 +++++++++++++++++++ tests/startup_mesh57_lane_spill_check.py | 12 + tools/startup/gfx2hlsl.py | 36 ++- 6 files changed, 359 insertions(+), 9 deletions(-) create mode 100644 tests/startup_gfx2hlsl_spill_wave64_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 6da3af3c8..5c188f5a3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3996,6 +3996,15 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_gfx2hlsl_sgpr_spill_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) endforeach() + # The same spill slots on wave64 lanes 32..63 and in a vertex stage (k and k + 32 on one VGPR refused). + add_test(NAME startup_gfx2hlsl_spill_wave64_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_spill_wave64_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_spill_wave64_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_spill_wave64_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_spill_wave64_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl 24-bit multiplies, v_xnor_b32 and the funnel shifts: CPU evaluation of the translated text # against an independent reference built from unbounded integers. add_test(NAME startup_gfx2hlsl_mul24_align COMMAND "${INTAKE_PYTHON}" -B diff --git a/docs/experiments.md b/docs/experiments.md index 5da2bbd28..3831d690b 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15290,6 +15290,8 @@ The startup pixel stage lowers constant-lane SGPR spills (#2125 item E): `v_writ The same slots are lowered in pixel stages with branches. The slot variable is assigned on the pixel's own path, while the hardware lane holds the last write on the wave's path; the two differ only inside the region of a branch not proven uniform (`s_cbranch_execz`/`_vccz` and their `nz` forms, or an SCC branch on varying data: the blocks between the branch and its immediate post-dominator, or the loop range of a backward branch), where the wave also runs blocks the pixel skips. A forward must-dataflow over the basic blocks (intersection at joins, fixed point through loops) gives, for each `v_readlane_b32`, the writes of its (VGPR, lane) that can supply it. One write: every path into the read ran it, so it is accepted unless the write lies in such a region and the read is outside it (a loop or arm the wave can run after the pixel left it). Several writes: accepted only when none lies in such a region; the reload keeps a constant only if every write stored it and is not claimed uniform. Refused, each by name: no write on some path (including another lane on another path), a write later in a loop that reaches the read through the back edge, a single write in a non-uniform region the read is outside, joined writes with one in a non-uniform region, and a reaching write that was itself refused. The lane-mask, descriptor, lane-range and vector-use refusals above are unchanged; the lane-mask test still follows program order, not the joins. On a local set of 79 vertex/pixel requests whose first refusal was the straight-line requirement under a development translator, 32 reach that refusal on main; with this change all 32 pass it and stop next at a lane-mask or descriptor spill source (30) or a spill VGPR also used as a vector (2). The other 47 stop earlier on main (`v_fma_mix_f32` 39, a joined symbol 8). `tests/startup_gfx2hlsl_spill_branches_check.py` (`startup_gfx2hlsl_spill_branches`) translates synthetic programs through `Stage.translate()`: six accepted shapes with their exact emitted lines, seven refusals with their exact reasons, and six translator mutations (union at joins, one pass instead of the fixed point, lanes keyed by their spelling, each region rule removed, every branch counted uniform) that must each turn a control red. One whole pixel stage is also generated: the slot is declared once and assigned on both arms of a uniform branch before the read after the join. The same file also draws it (`startup_gfx2hlsl_spill_branches_warp`/`_hardware`, FXC 5_1 and DXC 6_0): two uniform SCC choices write different binary32 words to one slot, the join reloads it and exports it OR-ed with the packed screen position, and the readback of all 16x16 pixels must equal the selected arm; the opposite arm's reference must mismatch. +Wave64 lanes and vertex stages: the same slot model now accepts lanes 0..63 and vertex stages. A wave32 program takes the lane select modulo 32, so lanes `k` and `k + 32` of one VGPR would be one slot there and two in wave64; the translator does not know the wave size and refuses that pair. Lane 64 and above, compute stages and register-selected lanes stay refused. `tests/startup_gfx2hlsl_spill_wave64_check.py` draws a pixel program with slots on lanes 32, 33, 40 and 63 (16 x 16 pixels) and a vertex program with slots on lanes 0 and 48 whose reloads reach a flat parameter (one pixel), each compared with a reference replayed from the slot rule; wrong-lane and ignored-overwrite translations must fail. Run `ctest --preset dev --no-tests=error -R "^startup_gfx2hlsl_spill_wave64" -V`. + The binary32 table (`VEC_F`) applies the same operand-count rule. Before this change, a form one source short (`v_add_f32 v1, v2`) raised `IndexError` in `Stage.one` instead of `Unsupported`. A form with one source too many (`v_med3_f32 v1, v2, v3, v4, v5`) translated with the extra source dropped. `tests/startup_gfx2hlsl_operand_count_check.py` (`startup_gfx2hlsl_operand_count`) checks every operation of both tables: one source fewer and one source more are refused, and the exact count translates. It also checks that the constant and accumulator forms (`v_fmac_f32`, `v_mac_f32`, `v_fmamk_f32`, `v_fmaak_f32`, `v_madmk_f32`, `v_madak_f32`) keep translating with their usual operands. As a control, it loads the translator with the new `VEC_F` guard removed and requires both old failures to come back. ## Startup translator: binary32 rounding diff --git a/tests/startup_gfx2hlsl_sgpr_spill_check.py b/tests/startup_gfx2hlsl_sgpr_spill_check.py index 5f4d8ef9d..6ef33105f 100644 --- a/tests/startup_gfx2hlsl_sgpr_spill_check.py +++ b/tests/startup_gfx2hlsl_sgpr_spill_check.py @@ -165,7 +165,9 @@ def controls(): ('read of a lane nothing wrote', ['v_writelane_b32 v10, s0, 3', 'v_readlane_b32 s1, v10, 4']), ('read of another VGPR at the written lane', ['v_writelane_b32 v10, s0, 3', 'v_readlane_b32 s1, v11, 3']), ('lane chosen by an SGPR', ['v_writelane_b32 v10, s0, s2', 'v_readlane_b32 s1, v10, 3']), - ('lane 32', ['v_writelane_b32 v10, s0, 32']), + ('lane 64', ['v_writelane_b32 v10, s0, 64']), + ('lanes 8 and 40 of one VGPR (one slot in wave32, two in wave64)', + ['v_writelane_b32 v10, s0, 8', 'v_writelane_b32 v10, s1, 40', 'v_readlane_b32 s2, v10, 8']), ('lane mask value (vcc_lo)', ['v_writelane_b32 v10, vcc_lo, 3']), ('lane mask value (exec_lo)', ['v_writelane_b32 v10, exec_lo, 3']), ('destination outside the plain SGPRs', ['v_writelane_b32 v10, s0, 3', 'v_readlane_b32 vcc_lo, v10, 3']), @@ -178,7 +180,10 @@ def controls(): for label, program in cases: reason = refused(program) check('refused: %s (%s)' % (label, reason), reason is not None) - check('refused: vertex stage (%s)' % refused(ok, kind='vs'), refused(ok, kind='vs') is not None) + check('a vertex stage is accepted', refused(ok, kind='vs') is None, str(refused(ok, kind='vs'))) + check('refused: compute stage (%s)' % refused(ok, kind='cs'), refused(ok, kind='cs') is not None) + wave64 = ['v_writelane_b32 v10, s0, 40', 'v_writelane_b32 v10, s1, 63', 'v_readlane_b32 s2, v10, 40'] + check('wave64 lanes 40 and 63 are accepted', refused(wave64) is None, str(refused(wave64))) check('refused: a shader with branches (%s)' % refused(ok, branches=True), refused(ok, branches=True) is not None) # 5. The reload keeps the constant the write stored, so later scalar folding sees the same word. diff --git a/tests/startup_gfx2hlsl_spill_wave64_check.py b/tests/startup_gfx2hlsl_spill_wave64_check.py new file mode 100644 index 000000000..fefc80dec --- /dev/null +++ b/tests/startup_gfx2hlsl_spill_wave64_check.py @@ -0,0 +1,300 @@ +"""SGPR spills to VGPR lanes 32..63 (wave64) and in vertex stages, tools/startup/gfx2hlsl.py, read back from a real +D3D12 draw. + + (no arguments) translation controls and refusals, pure Python + binary assemble the fixture sources with LLVM (gfx1013) and compare with the words here + draw [fxc] + compile the translated stages with DXC (and FXC when given), draw and compare + every exported word with the slot reference below + +`v_writelane_b32 vN, sM, k` writes SGPR sM into lane k of vN and `v_readlane_b32 sD, vN, k` reads lane k back (AMD +RDNA 2 ISA reference, VOP3 lane operations). Both ignore EXEC and touch only lane k, so with a constant k and a VGPR +no other instruction names, vN is a table of scalar slots (tests/startup_gfx2hlsl_sgpr_spill_check.py has the +lanes 0..31 pixel case). A wave64 program spills into lanes 0..63, and a vertex stage spills the same way. The +translator does not know the wave size: a wave32 program takes the lane select modulo 32, so lanes k and k + 32 of one +VGPR are one slot there and two in wave64, and that pair is refused; lane 64 and above stay refused. + +Fixtures: + PS pixel stage, slots v10[40], v10[63], v11[32], v12[33]; the SGPRs are clobbered, reloaded (v10[40] after a + second write) and ORed into the packed screen position, 16 x 16 pixels compared word by word. + VS vertex stage, slots v40[0], v40[48], v41[0]; reloads (v40[48] after a second write) go to param0, which the + flat pixel stage FLATPS exports; one pixel compared. +The reference is the last value written to (VGPR, lane), computed here by replaying the lane writes on a dictionary. +Mutations of the translated text (lane 63 read as lane 40, the overwrite ignored, another VGPR's slot) must fail. +""" +import re +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import assemble, draw as draw_flat # noqa: E402 +from startup_image_3d_check import FULLSCREEN_VS, VS_WORDS, compile_hlsl, root_blob # noqa: E402 + +WIDTH = HEIGHT = 16 +PACKED = (0x8000, 0x8000) # SPI_PS_INPUT_ENA/ADDR: the packed screen position only, in v0 +failures = [] + +PS_TEXT = '''s_mov_b32 s0, 0x40200000 +s_mov_b32 s1, 0x40400000 +s_mov_b32 s2, 4.0 +v_writelane_b32 v10, s0, 40 +v_writelane_b32 v10, s1, 63 +v_writelane_b32 v11, s2, 32 +s_or_b32 s8, s0, s1 +v_writelane_b32 v12, s8, 33 +s_mov_b32 s0, 0 +s_mov_b32 s1, 0 +s_mov_b32 s2, 0 +s_mov_b32 s8, 0 +v_readlane_b32 s3, v10, 40 +v_readlane_b32 s4, v10, 63 +v_readlane_b32 s5, v11, 32 +v_writelane_b32 v10, s5, 40 +v_readlane_b32 s6, v10, 40 +v_readlane_b32 s9, v12, 33 +v_or_b32_e32 v1, s3, v0 +v_or_b32_e32 v2, s4, v0 +v_or_b32_e32 v3, s6, v0 +v_or_b32_e32 v4, s9, v0 +exp mrt0 v1, v2, v3, v4 done vm +s_endpgm +''' +PS_WORDS = bytes.fromhex( + 'ff0380be00002040ff0381be00004040f60382be0a0061d7005001000a0061d7017e01000b0061d702400100000108880c0061d708420100' + '800380be800381be800382be800388be030060d70a510100040060d70a7f0100050060d70b4101000a0061d705500100060060d70a510100' + '090060d70c430100030002380400043806000638090008380f1800f801020304000081bf') +VS_TEXT = '''v_mov_b32_e32 v3, 0x40400000 +v_mov_b32_e32 v10, 0xc0400000 +v_cmp_eq_u32_e32 vcc_lo, 1, v0 +v_cndmask_b32_e32 v1, -1.0, v3, vcc_lo +v_cmp_eq_u32_e32 vcc_lo, 2, v0 +v_cndmask_b32_e32 v2, 1.0, v10, vcc_lo +v_mov_b32_e32 v4, 1.0 +v_mov_b32_e32 v5, 0 +s_mov_b32 s20, 0x12345678 +s_mov_b32 s21, 0x9abcdef0 +v_writelane_b32 v40, s20, 0 +v_writelane_b32 v40, s21, 48 +v_writelane_b32 v41, s21, 0 +s_mov_b32 s20, 0 +s_mov_b32 s21, 0 +v_readlane_b32 s22, v40, 0 +v_readlane_b32 s23, v40, 48 +v_readlane_b32 s24, v41, 0 +v_writelane_b32 v40, s22, 48 +v_readlane_b32 s25, v40, 48 +v_mov_b32_e32 v11, s22 +v_mov_b32_e32 v12, s23 +v_mov_b32_e32 v13, s24 +v_mov_b32_e32 v14, s25 +exp pos0 v1, v2, v5, v4 done +exp param0 v11, v12, v13, v14 +s_endpgm +''' +VS_FIXTURE = bytes.fromhex( + 'ff02067e00004040ff02147e000040c08100847df30602028200847df2140402f202087e80020a7eff0394be78563412ff0395bef0debc9a' + '280061d714000100280061d715600100290061d715000100800394be800395be160060d728010100170060d728610100180060d729010100' + '280061d716600100190060d7286101001602167e1702187e18021a7e19021c7ecf0800f8010205040f0200f80b0c0d0e000081bf') +FLAT_PS_TEXT = '''s_mov_b32 m0, s2 +v_interp_mov_f32_e32 v0, p0, attr0.x +v_interp_mov_f32_e32 v1, p0, attr0.y +v_interp_mov_f32_e32 v2, p0, attr0.z +v_interp_mov_f32_e32 v3, p0, attr0.w +exp mrt0 v0, v1, v2, v3 done vm +s_endpgm +''' +FLAT_PS_WORDS = bytes.fromhex('0203fcbe020002c8020106c802020ac802030ec80f1800f800010203000081bf') + + +def check(label, ok, detail=''): + print('%s: %s' % (label, 'ok' if ok else 'MISMATCH ' + str(detail)[:1500])) + if not ok: + failures.append(label) + + +# ---- reference: replay the lane writes and reads on a dictionary ------------------------------------------------------ +def replay(text, outputs): + lanes, scalars = {}, {} + for line in text.splitlines(): + op, _, rest = line.partition(' ') + args = [a.strip() for a in rest.split(',')] + if op == 's_mov_b32': + scalars[args[0]] = 0x40800000 if args[1] == '4.0' else int(args[1], 0) + elif op == 's_or_b32': + scalars[args[0]] = scalars[args[1]] | scalars[args[2]] + elif op == 'v_writelane_b32': + lanes[(args[0], int(args[2]))] = scalars[args[1]] + elif op == 'v_readlane_b32': + scalars[args[0]] = lanes[(args[1], int(args[2]))] + return [scalars[r] for r in outputs] + + +PS_SLOTS = replay(PS_TEXT, ('s3', 's4', 's6', 's9')) +VS_SLOTS = replay(VS_TEXT, ('s22', 's23', 's24', 's25')) + + +def ps_image(): + return [(x | y << 16) | value for y in range(HEIGHT) for x in range(WIDTH) for value in PS_SLOTS] + + +def ps_text(): + return G.Pipeline(VS_WORDS, PS_WORDS, root_blob(), ps_hw_inputs=PACKED).hlsl_ps() + + +def vs_pipeline(): + return G.Pipeline(VS_FIXTURE, FLAT_PS_WORDS, root_blob()) + + +def mutate(text, old, new): + mutated = re.sub(old, new, text) + assert mutated != text, old + return mutated + + +# Each wrong lowering, written on the folded text (a constant slot folds into the export). +PS_MUTATIONS = { + 'lane 63 reads lane 40 of the same VGPR': (r'v2 = 0x40400000u', 'v2 = 0x40200000u'), + 'the overwritten slot keeps its first value': (r'sp10_40 = s5;', 'sp10_40 = sp10_40;'), + 'v11 lane 32 reads v10 lane 40': (r'= sp11_32;', '= sp10_40;'), +} +VS_MUTATIONS = { + 'lane 48 reads lane 0 of the same VGPR': (r'v12 = 0x9abcdef0u', 'v12 = 0x12345678u'), + 'the overwritten slot keeps its first value': (r'v14 = 0x12345678u', 'v14 = 0x9abcdef0u'), +} + + +# ---- controls --------------------------------------------------------------------------------------------------------- +def refused(program, kind='ps'): + stage = G.Stage.__new__(G.Stage) + stage.kind, stage.lines, stage.sym = kind, [], {} + stage.used_s, stage.used_v, stage.uniform_v, stage.varying_s = set(), set(), set(), set() + stage.scc_uniform, stage.exec_known, stage.has_branches, stage.blocks, stage.masks = True, True, False, [], set() + stage.ins = [(4 * i, 1, re.sub(r'_e(32|64)$', '', a.split(' ', 1)[0]), a) for i, a in enumerate(program)] + for _, _, name, asm in stage.ins: + try: + stage.one(name, asm) + except G.Unsupported as reason: + return str(reason) + return None + + +def controls(): + check('pixel reference: v10[40], v10[63], v10[40] after the overwrite with v11[32], and the derived word', + PS_SLOTS == [0x40200000, 0x40400000, 0x40800000, 0x40600000], [hex(v) for v in PS_SLOTS]) + check('vertex reference: v40[0], v40[48], v41[0], v40[48] after the overwrite', + VS_SLOTS == [0x12345678, 0x9abcdef0, 0x9abcdef0, 0x12345678], [hex(v) for v in VS_SLOTS]) + for label, text, words in (('PS', PS_TEXT, PS_WORDS), ('VS', VS_TEXT, VS_FIXTURE), ('FLATPS', FLAT_PS_TEXT, + FLAT_PS_WORDS)): + got = [re.sub(r'_e(32|64)\b', '', asm) for _o, _n, _m, asm in G.decode(words)] + want = [re.sub(r'_e(32|64)\b', '', line) for line in text.splitlines()] + check('%s fixture decodes to its source' % label, got == want, '%s\n%s' % (got, want)) + try: + text = ps_text() + check('wave64 pixel slots translate to one scalar per (VGPR, lane)', + all(re.search(r'\b%s = 0' % s, text) for s in ('sp10_40', 'sp10_63', 'sp11_32', 'sp12_33')), text) + for label, (old, new) in PS_MUTATIONS.items(): + check('PS mutation "%s" changes the text' % label, mutate(text, old, new) != text) + except G.Unsupported as reason: + check('wave64 pixel slots translate', False, str(reason)) + try: + text = vs_pipeline().hlsl_vs() + check('vertex stage slots translate', all(re.search(r'\b%s = 0' % s, text) for s in ('sp40_0', 'sp40_48', 'sp41_0')), + text) + for label, (old, new) in VS_MUTATIONS.items(): + check('VS mutation "%s" changes the text' % label, mutate(text, old, new) != text) + except G.Unsupported as reason: + check('vertex stage slots translate', False, str(reason)) + for label, program, kind in ( + ('lane 64', ['v_writelane_b32 v10, s0, 64'], 'ps'), + ('lanes 8 and 40 of one VGPR', ['v_writelane_b32 v10, s0, 8', 'v_writelane_b32 v10, s1, 40'], 'ps'), + ('lanes 63 and 31 of one VGPR in a vertex stage', + ['v_writelane_b32 v10, s0, 63', 'v_readlane_b32 s1, v10, 31'], 'vs'), + ('a compute stage', ['v_writelane_b32 v10, s0, 40'], 'cs'), + ('a lane chosen by an SGPR', ['v_writelane_b32 v10, s0, s2'], 'vs')): + reason = refused(program, kind) + check('refused: %s (%s)' % (label, reason), reason is not None) + apart = ['v_writelane_b32 v10, s0, 8', 'v_writelane_b32 v11, s1, 40', 'v_readlane_b32 s2, v11, 40'] + check('lanes 8 and 40 of two different VGPRs are accepted', refused(apart) is None, str(refused(apart))) + + +# ---- draw ------------------------------------------------------------------------------------------------------------- +def draw_pixels(renderer, adapter, vs, ps, expected): + run = subprocess.run([renderer, adapter, '--startup-pixel-words', str(vs), str(ps), str(WIDTH), str(HEIGHT), + str(expected)], capture_output=True, text=True) + if run.returncode == 77: + print(run.stdout + run.stderr) + sys.exit(1 if failures else 77) + return run + + +def check_draw(dxc, renderer, adapter, fxc=None): + compilers = [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + ps_source = ps_text() + pipe = vs_pipeline() + vs_source, flat_source = pipe.hlsl_vs(), pipe.hlsl_ps() + expected_vs = ','.join('%08x' % v for v in VS_SLOTS) + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + reference = directory / 'reference.bin' + reference.write_bytes(struct.pack('<%dI' % (WIDTH * HEIGHT * 4), *ps_image())) + for kind, compiler, vs_profile, ps_profile in compilers: + vs = compile_hlsl(compiler, kind, FULLSCREEN_VS, 'vs_' + kind, vs_profile, directory) + ps = compile_hlsl(compiler, kind, ps_source, 'ps_' + kind, ps_profile, directory) + run = draw_pixels(renderer, adapter, vs, ps, reference) + check('%s %s PS: all %d pixels equal the slot reference' % (adapter, kind, WIDTH * HEIGHT), + run.returncode == 0 and 'all %d pixels matched' % (WIDTH * HEIGHT) in run.stdout, + run.stdout + run.stderr) + for label, (old, new) in PS_MUTATIONS.items(): + bad = compile_hlsl(compiler, kind, mutate(ps_source, old, new), 'bad_ps_%s_%d' % (kind, len(old)), + ps_profile, directory) + run = draw_pixels(renderer, adapter, vs, bad, reference) + check('%s %s PS mutation "%s" fails' % (adapter, kind, label), + run.returncode != 0 and 'pixel mismatch' in run.stderr, run.stdout + run.stderr) + vs2 = compile_hlsl(compiler, kind, vs_source, 'vs_spill_' + kind, vs_profile, directory) + flat = compile_hlsl(compiler, kind, flat_source, 'ps_flat_' + kind, ps_profile, directory) + run = draw_flat(renderer, adapter, vs2, flat, expected_vs) + check('%s %s VS: exported param0 equals the slot reference %s' % (adapter, kind, expected_vs), + run.returncode == 0, run.stdout + run.stderr) + for label, (old, new) in VS_MUTATIONS.items(): + bad = compile_hlsl(compiler, kind, mutate(vs_source, old, new), 'bad_vs_%s_%d' % (kind, len(old)), + vs_profile, directory) + run = draw_flat(renderer, adapter, bad, flat, expected_vs) + check('%s %s VS mutation "%s" fails' % (adapter, kind, label), run.returncode not in (0, 77), + run.stdout + run.stderr) + + +def check_binary(llvm_mc): + for label, text, words in (('PS', PS_TEXT, PS_WORDS), ('VS', VS_TEXT, VS_FIXTURE), + ('FLATPS', FLAT_PS_TEXT, FLAT_PS_WORDS)): + check('llvm-mc assembles the %s fixture to the same words' % label, assemble(llvm_mc, text) == words) + + +def main(): + if len(sys.argv) == 1: + controls() + else: + mode, *args = sys.argv[1:] + if mode == 'binary': + check_binary(*args) + elif mode == 'draw': + controls() + check_draw(*args) + else: + raise SystemExit(__doc__) + if failures: + print('FAIL') + for text in failures: + print(' ' + text) + sys.exit(1) + print('PASS') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_mesh57_lane_spill_check.py b/tests/startup_mesh57_lane_spill_check.py index ea1f94db6..66091ef85 100644 --- a/tests/startup_mesh57_lane_spill_check.py +++ b/tests/startup_mesh57_lane_spill_check.py @@ -93,6 +93,18 @@ def controls(): expect('reload feeds the SGPR', 's40 = sp30_3' in text, True) expect('spill VGPR is not a vector temporary', not re.search(r'\bv30\b', text), True) + # Slot 57 mesh is always wave64: lanes 3 and 35 of one VGPR are two slots there (the k / k + 32 pair rule of the + # pixel and vertex stages, whose wave size is unknown, must not refuse them). + with tempfile.TemporaryDirectory() as tmp: + pair = (MESH[:POST_COUNT] + ['bea803f2'] + writelane(30, 40, 3) + ['bea80380'] + + ['bea90391'] + writelane(30, 41, 35) + ['bea90380'] + readlane(41, 30, 35) + + readlane(40, 30, 3) + ['7e0e0228'] + MESH[POST_COUNT:]) + key, result = request(tmp, pair) + expect('mesh lanes 3 and 35 of one VGPR are two slots', result, 'ok') + if result == 'ok': + text = (Path(tmp) / ('%016x.ms57.hlsl' % key)).read_text() + expect('both slots are declared', 'sp30_3' in text and 'sp30_35' in text, True) + refusals = ( ('unwritten spill slot', MESH[:POST_COUNT] + ['bea803f2'] + writelane(30, 40, 3) + ['bea80380'] diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 34cc84c0e..ffbae1c4c 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -6946,7 +6946,10 @@ def op_v_readfirstlane_b32(self, ops, mods): # AMDGPU spill lowering). Both ignore EXEC. With a constant k and a VGPR that no other instruction # touches, vN is only a table of scalar slots, so one scalar variable per (vN, k) is an exact model # and no other lane is ever read. Anything else keeps the one-lane model out of reach and is refused. - # Pixel stages are wave32 (lanes 0..31). Slot 57 mesh is wave64 (lanes 0..63), matching #2127. + # Lanes 0..63 cover a wave64 program. A wave32 program uses only bits 4:0 of the lane select (RDNA 2 ISA, + # v_readlane/v_writelane: the lane is taken modulo the wave size), so k and k + 32 name one slot there and two in + # wave64; the translator does not know the wave size, so a VGPR whose lanes include such a pair is refused. + # Slot 57 mesh is wave64 (#2127). Vertex stages use the same model: the two instructions touch no other lane and no stage input. # # With branches the slot variable is assigned on the pixel's own path, while the hardware slot holds the last # write on the wave's path. The two paths differ only inside the region of a branch not proven uniform (an @@ -6956,7 +6959,8 @@ def op_v_readfirstlane_b32(self, ops, mods): # the write lies in such a region that the read is outside (a loop or arm the wave can run after this pixel # left it). Several writes: the value is chosen by the path, so every write must lie outside every such region; # the reload then keeps a constant only if all of them stored it, and is not claimed uniform. - SPILL_LANES = 32 + SPILL_LANES = 64 + SPILL_STAGES = ('ps', 'vs', 'ms') def spill_reaching(self, cfg): """Instruction index of each v_readlane_b32 -> the v_writelane_b32 indices that can supply its (VGPR, lane), or @@ -7036,17 +7040,35 @@ def spill_operands(self, name, ops, mods): except ValueError: raise Unsupported('%s requires a constant lane, got %s' % (name, ops[2])) from None kind = getattr(self, 'kind', None) - lanes = 64 if kind == 'ms' else self.SPILL_LANES - if not 0 <= lane < lanes: - raise Unsupported('%s lane %d outside 0..%d' % (name, lane, lanes - 1)) - if kind not in ('ps', 'ms'): - raise Unsupported('%s is lowered in pixel and mesh stages only' % name) + if not 0 <= lane < self.SPILL_LANES: + raise Unsupported('%s lane %d outside 0..%d' % (name, lane, self.SPILL_LANES - 1)) + if kind not in self.SPILL_STAGES: + raise Unsupported('%s is lowered in pixel, vertex and mesh stages only' % name) if not self.tracks_uniformity() or (getattr(self, 'has_branches', True) and (kind != 'ps' or getattr(self, 'spill_reach', None) is None)): raise Unsupported('%s needs straight-line code to prove write-before-read' % name) self.require_spill_only(vreg[1], name) + if kind in ('ps', 'vs'): # the wave size is unknown there; slot 57 mesh is always wave64, so k and k + 32 are two slots + self.require_spill_lanes_apart(vreg[1], name) return vreg[1], sreg, lane + def require_spill_lanes_apart(self, n, name): + """Refuse when two lanes of spill VGPR v differ by 32: one slot in wave32, two in wave64.""" + lanes = set() + for _, _, op, asm in getattr(self, 'ins', ()): + if re.sub(r'_e(32|64)$', '', op) not in ('v_writelane_b32', 'v_readlane_b32'): + continue + ops = parse(asm)[1] + if len(ops) == 3 and n in [r[1] for r in map(reg_range, ops[:2]) if r and r[0] == 'v']: + try: + lanes.add(int(ops[2], 0)) + except ValueError: + continue # a register lane is refused where it is read + for lane in lanes: + if lane + 32 in lanes: + raise Unsupported('%s: v%d lanes %d and %d are one slot in wave32 and two in wave64' + % (name, n, lane, lane + 32)) + def require_spill_only(self, n, name): """Refuse unless every instruction naming v is a lane write or read of it.""" # Mesh: scan the pre-skeleton program. The accepted group-memory exchanges rewrite to From 1ec01d7037d30fbdc383d48dceb43ad8c48e0f0b Mon Sep 17 00:00:00 2001 From: tedin7 <110300616+tedin7@users.noreply.github.com> Date: Thu, 26 Nov 2026 06:42:48 +0100 Subject: [PATCH 151/240] startup: lower DPP quad reads in pixel programs with uniform branches and loops (Part of #1723) (#2705) * feat: lower DPP quad reads in pixel programs with uniform branches and loops Symptom: a DPP16 quad read (quad swap, quad broadcast, pair broadcast) in a pixel program with any branch or loop was refused ("requires a straight-line pixel shader with entry EXEC" / "outside straight-line pixel code"), so every program that also has a loop failed even when the loop is a plain scalar counter. Root cause: the one-lane model runs each guest lane as its own HLSL thread through the pc dispatch, and the quad intrinsics only see a neighbour when the four threads of a quad reach them together. The old check required straight-line code instead of proving that. Change: Stage.quad_flow_refusals proves it over the whole program after translation: the s_wqm exec, exec runs before every branch and target, no other EXEC write can reach the read (CFG reachability, back edges included), and every conditional branch that can reach the read is wave-uniform (SCC proven uniform by the existing pass; execz/execnz under the whole-quad mask). vccz/vccnz loops, SCC from a lane mask, an EXEC write inside the loop and a late s_wqm are refused with the offset that breaks the proof. No wave size is assumed (SM 6.0 quad operations need only the 2x2 quad). Test: tests/startup_gfx2hlsl_dpp_quad_flow_check.py (controls fail before: LOOP refused, the four refusal reasons absent). Win2025 WARP (DXC ps_6_0) dev and release: LOOP draws 256/256 pixels equal to the CPU reference, the three wrong-lane mutations each fail; dpp_pair draws still pass. (cherry picked from commit 82d1b1d7786e8012494782d13eeefafd88b6a4c8) * fix: let the whole-program quad proof replace the entry-prefix test of DPP quad reads, keep unit probes on the entry prefix * fix: quad flow proof tolerates a dead read in a branch-free program --- CMakeLists.txt | 12 + docs/startup-runtime.md | 11 +- tests/startup_gfx2hlsl_dpp_quad_flow_check.py | 297 ++++++++++++++++++ tools/startup/gfx2hlsl.py | 97 +++++- 4 files changed, 411 insertions(+), 6 deletions(-) create mode 100644 tests/startup_gfx2hlsl_dpp_quad_flow_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 5c188f5a3..be634595a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3519,6 +3519,10 @@ if(EXISTS "${INTAKE_PYTHON}") # refusals of every other DPP control. The draws are registered below. add_test(NAME startup_gfx2hlsl_dpp_pair COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_dpp_pair_check.py") + # DPP16 quad reads in a pixel program with a uniform loop and branch: the whole-program convergence proof and its + # refusals (vccz loop, SCC from a lane mask, EXEC write reaching the read, late s_wqm). The draws are below. + add_test(NAME startup_gfx2hlsl_dpp_quad_flow COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_dpp_quad_flow_check.py") # DPP16 quad broadcasts quad_perm:[k,k,k,k] (#2125): lowered to QuadReadLaneAt, so the pixel stage compiles as # ps_6_0; the controls and refusals run here, the draws below compare every pixel with a CPU reference. add_test(NAME startup_gfx2hlsl_dpp_quad_broadcast COMMAND "${INTAKE_PYTHON}" -B @@ -3978,6 +3982,14 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_gfx2hlsl_dpp_pair_${adapter} PROPERTIES TIMEOUT 180 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl DPP16 quad reads (swap, broadcast, pair) inside a uniform scalar loop with an if: 16 x 16 pixels against + # a CPU reference of the per-pass neighbour words; a read taking the wrong lane must fail. DXC ps_6_0 only. + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_dpp_quad_flow_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_dpp_quad_flow_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_gfx2hlsl_dpp_quad_flow_${adapter} PROPERTIES TIMEOUT 180 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl lowers DPP16 quad swaps (quad_perm [1,0,3,2], [2,3,0,1], [3,2,1,0]) in a pixel stage to QuadReadAcross*. add_test(NAME startup_gfx2hlsl_dpp_quad_swap_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_dpp_quad_swap_check.py") diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index bd7ab3f18..4ca94467d 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -2078,7 +2078,7 @@ These are measured on one executable; treat them as hypotheses for others. `row_mask:0xf bank_mask:0xf`, and `bound_ctrl` since no source lane is disabled) lower on any VOP1 or VOP2 whose first source is a VGPR. The four lanes of the quad are read with the shader model 6.0 `QuadReadLaneAt` and the lane `quad_perm` names is selected by the parity of `SV_Position`; a stage that uses it compiles with DXC `ps_6_0` (`X2W_DXC`), and the result goes through a scratch register so a second source naming the same register keeps the pixel's own word. The form needs the four lanes of a quad to run together, as in a pixel - shader with helper lanes, proved by `s_wqm_b64 exec, exec` on the entry mask (a restored exact mask loses the proof): vertex stages, branches and a changed EXEC are refused, as are `row_*`, `wave_*`, partial masks and `fi`. Run + shader with helper lanes, proved by `s_wqm_b64 exec, exec` on the entry mask (a restored exact mask loses the proof): vertex stages and a changed EXEC are refused (branches and loops: see below), as are `row_*`, `wave_*`, partial masks and `fi`. Run `ctest --preset dev --no-tests=error -R "^startup_gfx2hlsl_dpp_pair"`: the controls model a quad on the CPU, and the draws on WARP and hardware compare 16 x 16 pixels of every pattern with a reference written from the lane table, with wrong-lane, own-lane, transposed-lane-index and permuted-second-source translations as failing controls. @@ -2094,6 +2094,15 @@ These are measured on one executable; treat them as hypotheses for others. check the translation and every refusal, and the draws on WARP and hardware compare all 256 pixels of two fixtures with a CPU reference, with wrong-lane and own-lane translations as failing controls. [#2125](https://github.com/R0Y00/Xbox2Windows/issues/2125) +- **DPP quad reads in branches and loops.** The quad swaps, broadcasts and pair broadcasts above also lower in a pixel + program with branches or loops when a whole-program check proves that the four threads of the quad reach the read + together: the `s_wqm exec, exec` runs before every branch and target, no other EXEC write can reach the read (an + exact-mask restore after the last read is fine), and every conditional branch that can reach it is wave-uniform + (SCC proven uniform; `s_cbranch_execz`/`execnz` under the whole-quad mask). A `vccz`/`vccnz` loop, SCC taken from a + lane mask, an EXEC write inside the loop and a late `s_wqm` are refused with the offset that breaks the proof. No + wave size is assumed. Run `ctest --preset dev --no-tests=error -R "^startup_gfx2hlsl_dpp_quad_flow"`: the draws on + WARP and hardware run swap, broadcast and pair reads inside a five-pass scalar loop with an `if`, compare 16 x 16 + pixels with a CPU reference, and require wrong-lane translations to fail. - **Soft asserts.** Retail code keeps `int3` instructions followed by a continuation. Without a debugger the title's handler steps over them; under the startup debugger use `-ContinueAsserts N`. One of them fires about ten times a second in the texture-streaming path diff --git a/tests/startup_gfx2hlsl_dpp_quad_flow_check.py b/tests/startup_gfx2hlsl_dpp_quad_flow_check.py new file mode 100644 index 000000000..27377b320 --- /dev/null +++ b/tests/startup_gfx2hlsl_dpp_quad_flow_check.py @@ -0,0 +1,297 @@ +"""DPP16 quad reads in a pixel program with branches and loops (tools/startup/gfx2hlsl.py), read back from a real +D3D12 draw. + + (no arguments) translation controls and refusals, pure Python + binary assemble the fixture sources with LLVM (gfx1013) and compare with the words here + draw [fxc] + compile the translated pixel stage with DXC ps_6_0 (quad reads need shader + model 6.0; the optional fxc argument is accepted and ignored), draw 16 x 16 + pixels and compare every pixel with the CPU reference below + +The translator runs each guest lane as its own HLSL thread and turns branches into a pc dispatch loop. A quad read +(QuadReadAcross*, QuadReadLaneAt) gives the neighbour's word only when the four threads of the quad reach it together +with the words the four guest lanes hold. The guest wave runs as one, so this holds when every branch on a path to +the read is wave-uniform and EXEC is still the whole-quad mask of the entry s_wqm exec, exec. The translator proves +that over the whole program after translation (Stage.quad_flow_refusals) and refuses the read otherwise: a vccz/vccnz +loop, an SCC taken from a lane mask, an EXEC write that can reach the read (also around a loop back edge), and an +s_wqm that does not run before every branch. No wave size is assumed: the quad operations need only the 2 x 2 quad. + +The draw fixture LOOP is the shape of a uniform loop over a scalar counter with an if inside it: + s_mov_b64 s[4:5], exec ; s_wqm_b64 exec, exec entry: save the exact mask, whole quads on + v1 = (x | y << 16) * 0x9b5d ; v2 = v3 = v5 = 0 ; s0 = 0 + loop: k = s0 = 0 .. 4 + v2 += quad_perm:[1,0,3,2] v1 the pixel at x ^ 1 + v3 += quad_perm:[2,2,2,2] v1 lane 2 of the quad, pixel (x & ~1, y | 1) + if (s0 != 2) { v4 = quad_perm:[0,0,2,2] v1 ; v5 ^= v4 } pixel (x & ~1, y), skipped on pass 2 + v1 += 0x101 ; s0 += 1 ; loop while s0 < 5 + s_and_b64 exec, exec, s[4:5] ; exp mrt0 v2, v3, v5, v1 +So the neighbour word read on pass k is w(neighbour) + k * 0x101 and the reference below sums or XORs it with plain +integers. The EXEC restore after the loop does not reach any read and is allowed. Mutations of the translated text +(each of the three reads taking the wrong lane) must fail the same draw. +""" +import re +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import assemble # noqa: E402 +from startup_image_3d_check import FULLSCREEN_VS, VS_WORDS, compile_hlsl, root_blob # noqa: E402 + +MASK = 0xffffffff +WIDTH = HEIGHT = 16 +MULTIPLIER = 0x9b5d +STEP, PASSES, SKIPPED = 0x101, 5, 2 +PACKED = (0x8000, 0x8000) # SPI_PS_INPUT_ENA/ADDR: the packed screen position only, in v0 +failures = [] + +# name -> (source with numeric branch offsets, words assembled by llvm-mc 19 for gfx1013) +FIXTURES = { + 'LOOP': ('''s_mov_b64 s[4:5], exec +s_wqm_b64 exec, exec +v_mul_u32_u24_e32 v1, 0x9b5d, v0 +v_mov_b32_e32 v2, 0 +v_mov_b32_e32 v3, 0 +v_mov_b32_e32 v5, 0 +s_mov_b32 s0, 0 +v_add_nc_u32_dpp v2, v1, v2 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf +v_add_nc_u32_dpp v3, v1, v3 quad_perm:[2,2,2,2] row_mask:0xf bank_mask:0xf +s_cmp_eq_u32 s0, 2 +s_cbranch_scc1 3 +v_mov_b32_dpp v4, v1 quad_perm:[0,0,2,2] row_mask:0xf bank_mask:0xf +v_xor_b32_e32 v5, v4, v5 +v_add_nc_u32_e32 v1, 0x101, v1 +s_add_u32 s0, s0, 1 +s_cmp_lt_u32 s0, 5 +s_cbranch_scc1 -14 +s_and_b64 exec, exec, s[4:5] +exp mrt0 v2, v3, v5, v1 done vm +s_endpgm +''', '7e0484be7e0afebeff0002165d9b00008002047e8002067e80020a7e800380befa04044a01b100fffa06064a01aa00ff008206bf030085bf' + 'fa02087e01a000ff040b0a3aff02024a010100000081008000850abff2ff85bf7e04fe870f1800f802030501000081bf'), + 'VCC_LOOP': ('''s_wqm_b64 exec, exec +v_mul_u32_u24_e32 v1, 0x9b5d, v0 +v_mov_b32_e32 v2, 0 +v_add_nc_u32_dpp v2, v1, v2 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf +v_add_nc_u32_e32 v1, 3, v1 +v_cmp_gt_u32_e32 vcc_lo, 0x100, v1 +s_cbranch_vccnz -6 +exp mrt0 v2, v1, v0, v0 done vm +s_endpgm +''', '7e0afebeff0002165d9b00008002047efa04044a01b100ff8302024aff02887d00010000faff87bf0f1800f802010000000081bf'), + 'MASK_SCC_LOOP': ('''s_wqm_b64 exec, exec +v_mul_u32_u24_e32 v1, 0x9b5d, v0 +v_mov_b32_e32 v2, 0 +v_add_nc_u32_dpp v2, v1, v2 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf +v_add_nc_u32_e32 v1, 3, v1 +v_cmp_gt_u32_e32 vcc_lo, 0x100, v1 +s_and_b64 s[2:3], vcc, exec +s_cbranch_scc1 -7 +exp mrt0 v2, v1, v0, v0 done vm +s_endpgm +''', '7e0afebeff0002165d9b00008002047efa04044a01b100ff8302024aff02887d000100006a7e8287f9ff85bf0f1800f802010000000081bf'), + 'EXEC_IN_LOOP': ('''s_wqm_b64 exec, exec +v_mul_u32_u24_e32 v1, 0x9b5d, v0 +v_mov_b32_e32 v2, 0 +s_mov_b32 s0, 0 +v_add_nc_u32_dpp v2, v1, v2 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf +v_cmp_gt_u32_e32 vcc_lo, 0x100, v1 +s_and_saveexec_b64 s[4:5], vcc +v_add_nc_u32_e32 v1, 3, v1 +s_or_b64 exec, exec, s[4:5] +s_add_u32 s0, s0, 1 +s_cmp_lt_u32 s0, 4 +s_cbranch_scc1 -10 +exp mrt0 v2, v1, v0, v0 done vm +s_endpgm +''', '7e0afebeff0002165d9b00008002047e800380befa04044a01b100ffff02887d000100006a2484be8302024a7e04fe880081008000840abf' + 'f6ff85bf0f1800f802010000000081bf'), + 'WQM_AFTER_BRANCH': ('''s_mov_b32 s0, 0 +s_cmp_eq_u32 s0, 0 +s_cbranch_scc1 1 +v_mov_b32_e32 v0, 1 +s_wqm_b64 exec, exec +v_mul_u32_u24_e32 v1, 0x9b5d, v0 +v_mov_b32_dpp v2, v1 quad_perm:[0,0,0,0] row_mask:0xf bank_mask:0xf +exp mrt0 v2, v1, v0, v0 done vm +s_endpgm +''', '800380be008006bf010085bf8102007e7e0afebeff0002165d9b0000fa02047e010000ff0f1800f802010000000081bf'), +} +REFUSALS = { + 'VCC_LOOP': 's_cbranch_vccnz at +0x24 is not proven wave-uniform', + 'MASK_SCC_LOOP': 's_cbranch_scc1 at +0x28 is not proven wave-uniform', + 'EXEC_IN_LOOP': 'the EXEC write at +0x24 reaches it', + 'WQM_AFTER_BRANCH': 'the s_wqm exec, exec does not run before every branch', +} + + +def check(label, ok, detail=''): + print('%s: %s' % (label, 'ok' if ok else 'MISMATCH ' + detail[:2000])) + if not ok: + failures.append(label) + + +def words(name): + return bytes.fromhex(FIXTURES[name][1]) + + +def translate(name): + try: + return G.Pipeline(VS_WORDS, words(name), root_blob(), ps_hw_inputs=PACKED).hlsl_ps(), None + except G.Unsupported as reason: + return None, str(reason) + + +# ---- CPU reference ---------------------------------------------------------------------------------------------------- +def word(x, y): + return ((x | (y << 16)) * MULTIPLIER) & MASK + + +def image(): + out = [] + for y in range(HEIGHT): + for x in range(WIDTH): + swap = sum(word(x ^ 1, y) + k * STEP for k in range(PASSES)) & MASK + broadcast = sum(word(x & ~1, y | 1) + k * STEP for k in range(PASSES)) & MASK + pair = 0 + for k in range(PASSES): + if k != SKIPPED: + pair ^= (word(x & ~1, y) + k * STEP) & MASK + out += [swap, broadcast, pair, (word(x, y) + PASSES * STEP) & MASK] + return out + + +# ---- mutations of the translated text --------------------------------------------------------------------------------- +def replace_once(text, old, new): + assert text.count(old) == 1, old + return text.replace(old, new) + + +def swap_own(text): + return replace_once(text, 'QuadReadAcrossX(v1)', 'v1') + + +def broadcast_lane1(text): + return replace_once(text, 'QuadReadLaneAt(v1, 2u)', 'QuadReadLaneAt(v1, 1u)') + + +def pair_own(text): + chain = re.compile(r'x2w_lane == 0u \? x2w_q\d : x2w_lane == 1u \? x2w_q\d : x2w_lane == 2u \? x2w_q\d : x2w_q\d;') + assert len(chain.findall(text)) == 1 + return chain.sub('x2w_lane == 0u ? x2w_q0 : x2w_lane == 1u ? x2w_q1 : x2w_lane == 2u ? x2w_q2 : x2w_q3;', text) + + +MUTATIONS = {'swap reads its own lane': swap_own, 'broadcast reads lane 1': broadcast_lane1, + 'pair keeps every lane': pair_own} + + +# ---- controls --------------------------------------------------------------------------------------------------------- +def controls(): + text, reason = translate('LOOP') + check('LOOP translates (uniform scalar loop and if, quad reads inside)', text is not None, str(reason)) + if text is not None: + check('LOOP keeps the pc dispatch loop', '[loop] for' in text, text) + check('LOOP reads the quad: X swap, lane-2 broadcast, four-lane pair read', + 'QuadReadAcrossX(v1)' in text and 'QuadReadLaneAt(v1, 2u)' in text and text.count('QuadReadLaneAt(v1, ') == 5, + text) + for how, mutate in MUTATIONS.items(): + check('LOOP %s mutation changes the text' % how, mutate(text) != text) + for name, expected in REFUSALS.items(): + text, reason = translate(name) + check('%s refused: %s' % (name, expected), text is None and reason is not None and expected in reason, + str(reason)) + reference = image() + own = [v for y in range(HEIGHT) for x in range(WIDTH) + for v in (sum(word(x, y) + k * STEP for k in range(PASSES)) & MASK,) * 2 + (0, 0)] + check('reference differs from a lane-local reading', reference[0::4] != own[0::4] and reference[1::4] != own[1::4]) + # A dead quad read behind an early s_endpgm in a branch-free program has no branch to prove: no crash. + dead = bytes.fromhex('7e0afebeff0002165d9b00008002047e000081bffa04044a01b100fffa02087e01a000ff000081bf') + try: + G.Pipeline(VS_WORDS, dead, root_blob(), ps_hw_inputs=PACKED).hlsl_ps() + check('dead quad read after s_endpgm translates without a crash', True) + except G.Unsupported as reason: + check('dead quad read after s_endpgm translates without a crash', True, str(reason)) + except Exception as error: # noqa: BLE001 - the regression is an unexpected exception type + check('dead quad read after s_endpgm translates without a crash', False, repr(error)) + # A straight-line program with the same reads still translates as before. + straight = bytes.fromhex('7e0afebeff0002165d9b0000fa02047e01b100ff0f1800f802010000000081bf') + try: + G.Pipeline(VS_WORDS, straight, root_blob(), ps_hw_inputs=PACKED).hlsl_ps() + check('straight-line quad swap still translates', True) + except G.Unsupported as reason: + check('straight-line quad swap still translates', False, str(reason)) + + +# ---- draw ------------------------------------------------------------------------------------------------------------- +def words_file(directory, name, values): + path = directory / ('%s.bin' % name) + path.write_bytes(struct.pack('<%dI' % len(values), *values)) + return path + + +def draw(renderer, adapter, vs, ps, expected): + run = subprocess.run([renderer, adapter, '--startup-pixel-words', str(vs), str(ps), str(WIDTH), str(HEIGHT), + str(expected)], capture_output=True, text=True) + if run.returncode == 77: + print(run.stdout + run.stderr) + sys.exit(1 if failures else 77) + return run + + +def check_draw(dxc, renderer, adapter, fxc=None): + text, reason = translate('LOOP') + if text is None: + check('LOOP translates for the draw', False, str(reason)) + return + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + vs = compile_hlsl(dxc, 'dxc', FULLSCREEN_VS, 'vs_dxc', 'vs_6_0', directory) + reference = words_file(directory, 'reference', image()) + ps = compile_hlsl(dxc, 'dxc', text, 'ps_loop', 'ps_6_0', directory) + run = draw(renderer, adapter, vs, ps, reference) + print(' ' + ' '.join(ln for ln in run.stdout.splitlines() + if ln.startswith(('backend=', 'adapter=', 'driver=', 'debug_errors=')))) + check('dxc %s LOOP: all %d pixels match the reference' % (adapter, WIDTH * HEIGHT), + run.returncode == 0 and 'all %d pixels matched' % (WIDTH * HEIGHT) in run.stdout, run.stdout + run.stderr) + for how, mutate in MUTATIONS.items(): + bad = compile_hlsl(dxc, 'dxc', mutate(text), 'ps_' + how.replace(' ', '_'), 'ps_6_0', directory) + run = draw(renderer, adapter, vs, bad, reference) + lines = [ln for ln in run.stderr.splitlines() if 'pixel' in ln] + check('dxc %s LOOP %s mutation fails against the reference: %s' % (adapter, how, ' / '.join(lines)), + run.returncode != 0 and bool(lines) and lines[0].startswith('pixel mismatch'), run.stdout + run.stderr) + + +def check_binary(llvm_mc): + for name, (source, hexwords) in FIXTURES.items(): + check('llvm-mc assembles the %s fixture to the same words' % name, + assemble(llvm_mc, source) == bytes.fromhex(hexwords)) + + +def main(): + if len(sys.argv) == 1: + controls() + else: + mode, *args = sys.argv[1:] + if mode == 'binary': + check_binary(*args) + elif mode == 'draw': + controls() + check_draw(*args) + else: + raise SystemExit(__doc__) + if failures: + print('FAIL') + for text in failures: + print(' ' + text) + sys.exit(1) + print('PASS') + + +if __name__ == '__main__': + main() diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index ffbae1c4c..529c03a3a 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -3142,6 +3142,9 @@ def translate(self): self.whole_read_v = set() # VGPRs read outside a proven low-16-bit consumer self.float_const_s = {} # SGPR -> 32-bit pattern from s_mov_b32 of an inline float constant self.has_branches = bool(targets) + self.quad_flow_reads = [] # (offset, mnemonic) of DPP quad reads lowered in a program with branches + self.divergent_branches = {} # s_cbranch offset -> mnemonic, for branches not proven wave-uniform + self.wqm_set_at = None # offset of the s_wqm exec, exec that proved whole-quad EXEC first self.spill_slots = {} # (vgpr, lane) -> (sym, uniform) for constant-lane SGPR spills self.vcc_events = {} self.vcc_lost = self.vcc_descriptor_overwritten = False @@ -3320,6 +3323,7 @@ def translate(self): if not cond_uniform: # Divergent CF: later SampleBias / CalculateLevelOfDetail would see uneven quads. self.uniform_cf = False + self.divergent_branches[off] = base b_target = int(parse(asm)[1][0].split('_')[1], 16) regs, affected = div_targets.get(off, (set(), set())) regs = {r for r in regs if isinstance(r, int)} @@ -3387,6 +3391,12 @@ def translate(self): refusals.append((reason, self.kind)) if self.lines: self.blocks.append((start, self.lines, None)) + for at, reason in self.quad_flow_refusals(branches, targets): + if refusals is None: + error = Unsupported(reason) + error.instruction = names[at] + raise error + refusals.append((reason, self.kind)) self.materialized = materialize # declarations() assigns these before the body (and before any loop) if set(scc_effects.values()) - {'emitted'}: for kind, name in self.descriptor_scc_reads(dict(branches), scc_effects): @@ -3644,6 +3654,78 @@ def one(self, name, asm): expr) return term + def quad_flow_straight(self): + """Whether a DPP quad read sits in straight-line code (the quad intrinsics then run in uniform flow).""" + return not getattr(self, 'has_branches', True) and not getattr(self, 'blocks', []) + + def quad_flow_allowed(self): + """Whether a DPP quad read in a pixel program with branches or loops may be lowered now and proven over the + whole program after translation (Stage.quad_flow_refusals). Unit probes without translate() cannot.""" + return getattr(self, 'kind', None) == 'ps' and getattr(self, 'quad_flow_reads', None) is not None + + def note_quad_flow(self, base): + if not self.quad_flow_straight() and getattr(self, 'quad_flow_reads', None) is not None: + self.quad_flow_reads.append((self.pc, base)) + + def quad_flow_refusals(self, branches, targets): + """[(offset, reason)] for DPP quad reads lowered in a pixel program with branches or loops. + + The one-lane model runs each lane as its own HLSL thread through the pc dispatch, so the QuadReadLaneAt / + QuadReadAcross* of a lane reads its neighbours only when all four threads of the quad reach that statement + together (same block, same pass of the dispatch loop) with the word the guest lanes hold. The guest runs + the wave as one: its scalar branches are wave-wide, and the quad is whole when EXEC is the s_wqm mask. A + read is kept when, on every path to it: + - the s_wqm exec, exec that proved whole-quad EXEC ran first: it sits before every branch and target; + - no other instruction that can write EXEC reaches it (so EXEC is still that mask and every VGPR write ran + on all four lanes, helper lanes included); + - every conditional branch that reaches it is wave-uniform (SCC proven uniform by the translator), or an + execz/execnz branch, whose EXEC is the whole-quad mask by the rule above and so never taken. A vccz/vccnz + branch, or SCC from lane data, can split a quad, and the read is refused. + Then the four threads ran the same branch outcomes, so they are in the same block on the same dispatch + pass. No wave size is assumed: the SM 6.0 quad operations need only the 2x2 quad of four lanes.""" + reads = getattr(self, 'quad_flow_reads', []) + if not reads: + return [] + index, block_of, succ, _dom, _writes, _reached = self.flow + after = {} + + def reaches(src, dst): + a, b = index[src], index[dst] + if block_of[a] == block_of[b] and a < b: + return True + start = block_of[a] + if start not in after: + seen, todo = set(), list(succ[start]) + while todo: + blk = todo.pop() + if blk not in seen: + seen.add(blk) + todo += succ[blk] + after[start] = seen + return block_of[b] in after[start] + # No branch or target (a dead read behind an early s_endpgm): nothing for the s_wqm to precede. + first = min([off for off, _ in branches] + list(targets), default=float('inf')) + writers = [off for off, _n, name, asm in self.ins if writes_exec(name, parse(asm)[1]) + and not (re.sub(r'_e(32|64)$', '', name) in ('s_wqm_b32', 's_wqm_b64') + and parse(asm)[1] in (['exec', 'exec'], ['exec_lo', 'exec_lo']))] + out = [] + for at, base in reads: + if self.wqm_set_at is None or self.wqm_set_at >= first: + out.append((at, '%s_dpp quad read at +0x%x in a program with branches: the s_wqm exec, exec does not ' + 'run before every branch' % (base, at))) + continue + writer = next((w for w in writers if reaches(w, at)), None) + if writer is not None: + out.append((at, '%s_dpp quad read at +0x%x in a program with branches: the EXEC write at +0x%x reaches ' + 'it' % (base, at, writer))) + continue + split = next((b for b, name in sorted(self.divergent_branches.items()) + if name not in ('s_cbranch_execz', 's_cbranch_execnz') and reaches(b, at)), None) + if split is not None: + out.append((at, '%s_dpp quad read at +0x%x in a program with branches: %s at +0x%x is not proven ' + 'wave-uniform' % (base, at, self.divergent_branches[split], split))) + return out + def dpp_pair(self, base, asm, ops, mods): """A DPP16 spelling whose SRC0 is a quad pair broadcast (#2125 item C). @@ -3667,7 +3749,7 @@ def dpp_pair(self, base, asm, ops, mods): perm = tuple(int(c) for c in re.findall(r'\d', perms[0])) if perm not in DPP_PAIR: raise Unsupported('%s_dpp with %s' % (base, perms[0])) - if (self.kind != 'ps' or getattr(self, 'has_branches', True) or not getattr(self, 'exec_known', False) or + if (self.kind != 'ps' or not (self.quad_flow_straight() or self.quad_flow_allowed()) or not getattr(self, 'exec_known', False) or not getattr(self, 'wqm_exec', False) or getattr(self, 'fetched', False)): raise Unsupported('%s_dpp %s outside straight-line pixel code with a whole-quad exec mask (s_wqm exec, exec)' % (base, perms[0])) @@ -3679,6 +3761,7 @@ def dpp_pair(self, base, asm, ops, mods): if not src: raise Unsupported('%s_dpp source %s' % (base, ops[1])) word = self.u('v%s' % src.group(2)) # records the original source as a used VGPR + self.note_quad_flow(base) self.needs_sm6 = True self.used_v.add(DPP_SCRATCH) self.uniform_v.discard(DPP_SCRATCH) @@ -3741,6 +3824,8 @@ def lower(self, base, asm, ops, mods): if base in ('s_wqm_b32', 's_wqm_b64'): if ops[0] in ('exec', 'exec_lo') and ops[1:] == ops[:1] and getattr(self, 'exec_known', False): self.wqm_exec = True # every lane of a touched quad is now active, helper lanes included + if getattr(self, 'wqm_set_at', False) is None: + self.wqm_set_at = getattr(self, 'pc', None) # where the quad-read flow proof starts if hasattr(self, 'uniform_v'): self.uniform_v.clear() if hasattr(self, 'scc_uniform'): @@ -3980,8 +4065,9 @@ def dpp_broadcast(self, base, ops, mods): if self.kind != 'ps': raise Unsupported('%s_dpp outside a straight-line pixel stage with the entry EXEC mask' % base) # A branch to offset zero also makes the nominal entry block re-entrant. - if (getattr(self, 'past_entry', bool(getattr(self, 'blocks', ()))) or - not getattr(self, 'exec_known', False)): + # The whole-program proof (quad_flow_refusals) replaces the entry-prefix test once translate() runs it. + if (not getattr(self, 'exec_known', False) or + (not self.quad_flow_allowed() and getattr(self, 'past_entry', bool(getattr(self, 'blocks', ()))))): raise Unsupported('%s_dpp outside the entry prefix of a pixel stage with the entry EXEC mask' % base) if not getattr(self, 'wqm_exec', False): # The entry EXEC can leave out lanes of a partly covered quad, and the guest then reads an inactive @@ -4003,6 +4089,7 @@ def dpp_broadcast(self, base, ops, mods): rewritten = 'v%d' % self.DPP_TEMP rewritten = '|%s|' % rewritten if absolute else rewritten rewritten = '-' + rewritten if neg else rewritten + self.note_quad_flow(base) self.needs_sm6 = True self.set_v(self.DPP_TEMP, 'QuadReadLaneAt(%s, %su)' % (self.u(token), lanes.group(1))) operands = [ops[0], rewritten] + ops[2:] @@ -4065,12 +4152,12 @@ def dpp(self, base, ops, mods): src_neg_abs.append((neg, absolute, base_tok)) elif len(ops) != arity + 1 or any(not re.fullmatch(r'v\d+', o) for o in ops): raise Unsupported('%s_dpp needs VGPR operands without modifiers' % base) - if (getattr(self, 'kind', None) != 'ps' or getattr(self, 'has_branches', True) or getattr(self, 'blocks', True) - or not getattr(self, 'exec_known', False)): + if getattr(self, 'kind', None) != 'ps' or not (self.quad_flow_straight() or self.quad_flow_allowed()) or not getattr(self, 'exec_known', False): raise Unsupported('%s_dpp requires a straight-line pixel shader with entry EXEC' % base) if not getattr(self, 'wqm_exec', False): raise Unsupported('%s_dpp requires whole-quad EXEC (s_wqm of exec first): a partly covered quad has ' 'inactive source lanes that the hardware masks and QuadReadAcross does not' % base) + self.note_quad_flow(base) self.needs_sm6 = True # src0 is the exchanged lane; a VOP2 src1 stays this lane's own register. if kind == 'f': From 2462ab37a1dbaeb6f7c1fa353e178191ab65a2e5 Mon Sep 17 00:00:00 2001 From: tedin7 <110300616+tedin7@users.noreply.github.com> Date: Thu, 26 Nov 2026 06:47:38 +0100 Subject: [PATCH 152/240] shader: lower v_mad_u64_u32 and v_mad_i64_i32 in gfx2hlsl (Part of #1723) (#2047) * feat: lower v_mad_u64_u32 and v_mad_i64_i32 in gfx2hlsl Part of #1723. The unsigned form writes the carry-out of the 64-bit add to a lane mask; the signed form is accepted only with the null destination. Adds startup_gfx2hlsl_mad64, which fails on main and passes here. * test: draw v_mad_u64_u32 and v_mad_i64_i32 on D3D12 WARP and hardware against a 64-bit reference * fix: derive the v_mad_u64_u32 carry-out without comparing against a wrapped sum * fix: build the v_mad_u64_u32 carry-out from two select words * test: export the mad64 carry-out as 1.0f so the render target cannot flush it; restore the original carry formula * fix: refuse lane masks as integer inputs of v_mad_u64_u32 and v_mad_i64_i32 * fix: mark the v_mad_u64_u32 SGPR carry mask varying and run its checks in CI --- .github/workflows/windows.yml | 2 + CMakeLists.txt | 10 + tests/startup_gfx2hlsl_mad64_check.py | 287 ++++++++++++++++++++++++++ tools/startup/gfx2hlsl.py | 67 ++++++ 4 files changed, 366 insertions(+) create mode 100644 tests/startup_gfx2hlsl_mad64_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index bcec8358c..cb71ae8c5 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -144,6 +144,7 @@ jobs: (["tests/startup_gfx2hlsl_swap_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_dpp_quad_swap_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_shift64_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_gfx2hlsl_mad64_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_mul_hi_i32_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_mul_mad_i24_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_cube_check.py", "binary", "llvm-mc-15"], {}), @@ -338,6 +339,7 @@ jobs: tests/startup_gfx2hlsl_s_quadmask_check.py \ tests/startup_gfx2hlsl_fma_mix_check.py \ tests/startup_gfx2hlsl_shift64_check.py \ + tests/startup_gfx2hlsl_mad64_check.py \ tests/startup_gfx2hlsl_cmp_class_f16_sdwa_check.py \ tests/startup_gfx2hlsl_mul_hi_i32_check.py \ tests/startup_gfx2hlsl_mul_mad_i24_check.py \ diff --git a/CMakeLists.txt b/CMakeLists.txt index be634595a..01038e677 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4203,6 +4203,16 @@ if(EXISTS "${INTAKE_PYTHON}") PASS_REGULAR_EXPRESSION "control ${control}: rejected at word=[0-9]+ ") endforeach() endforeach() + # gfx2hlsl v_mad_u64_u32 / v_mad_i64_i32: helper math against a 64-bit reference, carry-out mask, refusals (Part of #1723). + add_test(NAME startup_gfx2hlsl_mad64 COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_mad64_check.py") + set_tests_properties(startup_gfx2hlsl_mad64 PROPERTIES TIMEOUT 60) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_mad64_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_mad64_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_mad64_${adapter} PROPERTIES TIMEOUT 180 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl bounded 64-bit LDS exchanges (ds_write_b64, ds_read_b64) across s_barrier (Refs #2274, #1541). add_test(NAME startup_compute_lds_b64_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_compute_lds_b64_check.py") diff --git a/tests/startup_gfx2hlsl_mad64_check.py b/tests/startup_gfx2hlsl_mad64_check.py new file mode 100644 index 000000000..f19d83219 --- /dev/null +++ b/tests/startup_gfx2hlsl_mad64_check.py @@ -0,0 +1,287 @@ +"""v_mad_u64_u32 and v_mad_i64_i32 in tools/startup/gfx2hlsl.py (Part of #1723). + +D = S0 * S1 + S2 modulo 2^64 with two 32-bit factors and a 64-bit S2, written to a VGPR pair. The unsigned form +also writes the carry-out of the 64-bit add to a lane mask; the signed form is accepted only with `null`. + + (no arguments) pure Python controls described below + binary reassemble the pixel fixtures and compare them with the words below + draw [fxc] + compile the translated pixel shaders (FXC ps_5_1 when given, DXC ps_6_0), + draw one pixel per input and compare mrt0 with the 64-bit reference + +Draw pixel: v0 = S0, v1 = S1, v[2:3] = the 64-bit S2. The unsigned shader exports (lo, hi, 1.0f when carry else 0, 0), the signed +shader exports (lo, hi, 0, 0). A mutation that drops the low-word carry into the high word must read the exact +mutated words, so the draw cannot pass by accident. + +Controls: translate each form, evaluate the emitted helpers in 32-bit arithmetic against an independent +Python 64-bit reference over a value grid, and check the refusals. Pure Python, no GPU and no assembler. +""" +import re +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import assemble, compile_hlsl, draw, root_blob # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import ( # noqa: E402 + MASK, POST_SOURCE, POST_WORDS, PRE_SOURCE, PRE_WORDS, Expr, Probe, check, vs_source, vs_words, words_text) + +M64 = (1 << 64) - 1 +VALUES = (0, 1, 2, 0xffff, 0x10000, 0x7fffffff, 0x80000000, 0x89abcdef, 0xfffffffe, 0xffffffff) +ADDENDS = (0, 1, M64, 1 << 63, 0x00000001ffffffff, 0xfedcba9876543210, 0x7fffffffffffffff) + +BODY_SOURCE = { + False: ('v_mad_u64_u32 v[12:13], vcc_lo, v0, v1, v[2:3]\n' + 'v_cndmask_b32_e64 v14, 0, 1.0, vcc_lo\nv_mov_b32 v15, 0\n'), + True: 'v_mad_i64_i32 v[12:13], null, v0, v1, v[2:3]\nv_mov_b32 v14, 0\nv_mov_b32 v15, 0\n', +} +BODY_WORDS = { + False: bytes.fromhex('0c6a76d500030a040e0001d580e4a90180021e7e'), + True: bytes.fromhex('0c7d77d500030a0480021c7e80021e7e'), +} +# (S0, S1, S2): carry out of the low word, carry out of the 64-bit add, negative factors, the largest products. +DRAWS = ( + (0xffffffff, 0xffffffff, 0xffffffffffffffff), + (0x89abcdef, 0x76543210, 0xfedcba9876543210), + (0xffffffff, 0x00000002, 0x00000001ffffffff), + (0x80000000, 0x80000000, 0x8000000000000000), + (0x80000000, 0x7fffffff, 0x7fffffffffffffff), + (0xfffffffe, 0x00010001, 0x00000000ffff0000), + (0x0000ffff, 0x0000ffff, 0), + (0x00000003, 0x00000005, 0x000000000000000f), +) + + +def signed32(x): + return x - (1 << 32) if x >> 31 else x + + +def reference(signed, a, b, c): + """(result, carry) from plain Python integers: the exact product plus the 64-bit addend.""" + product = (signed32(a) * signed32(b) if signed else a * b) & M64 + total = product + c + return total & M64, int(total > M64) + + +class Evaluator: + """Runs the emitted mulhi32/mad64u/mad64i helpers with the 32-bit evaluator of the bit-ALU check.""" + + def __init__(self, text): + self.helpers = {} + for name in ('mulhi32', 'mad64u', 'mad64i'): + m = re.search(r'uint3? %s\((.*?)\) \{ (.*?) \}$' % name, text, re.M) + assert m, '%s missing from the generated HLSL' % name + self.helpers[name] = ([p.split()[1] for p in m.group(1).split(',')], m.group(2)) + self.original_call = Expr.call + Expr.call = staticmethod(self.call) + + def close(self): + Expr.call = staticmethod(self.original_call) + + def call(self, name, args): + if name == 'mulhi32': + return self.run('mulhi32', [a[0] for a in args])[0], False + return self.original_call(name, args) + + def run(self, name, values): + params, body = self.helpers[name] + env = dict(zip(params, values)) + stmts = [s.strip() for s in body.split(';') if s.strip()] + for stmt in stmts[:-1]: + for item in re.split(r',\s*(?=\w+ = )', stmt[len('uint '):]): + var, rhs = [x.strip() for x in item.split('=', 1)] + env[var] = Expr(rhs).run(env)[0] + ret = stmts[-1] + inner = re.fullmatch(r'return (?:uint3\((.*)\)|(.*))', ret) + if inner.group(2) is not None: + return [Expr(inner.group(2)).run(env)[0]] + parts, depth, start = [], 0, 0 + text = inner.group(1) + for i, ch in enumerate(text): + depth += ch == '(' + depth -= ch == ')' + if ch == ',' and depth == 0: + parts.append(text[start:i]) + start = i + 1 + parts.append(text[start:]) + return [Expr(p).run(env)[0] for p in parts] + + +def translate(asm): + probe = Probe() + probe.masks, probe.varying_s = set(), set() + probe.one(asm.split(' ', 1)[0], asm) + return probe + + +def refused(asm): + try: + translate(asm) + except G.Unsupported: + return True + return False + + +def helper_source(): + """The helpers as a pixel stage emits them (a program that only exports).""" + return G.Pipeline(vs_words([(0, 0, 0)] * 4), PRE_WORDS + POST_WORDS, root_blob()).hlsl_ps() + + +def controls(): + ev = Evaluator(helper_source()) + try: + for signed, name in ((False, 'mad64u'), (True, 'mad64i')): + bad = None + for a in VALUES: + for b in VALUES: + for c in ADDENDS: + lo, hi, carry = ev.run(name, [a, b, c & MASK, c >> 32]) + want, want_carry = reference(signed, a, b, c) + if (hi << 32 | lo) != want or (not signed and carry != want_carry): + bad = bad or (hex(a), hex(b), hex(c), hex(hi << 32 | lo), hex(want), carry) + check('%s: %d inputs match the 64-bit reference' % (name, len(VALUES) ** 2 * len(ADDENDS)), bad is None) + finally: + ev.close() + + u = translate('v_mad_u64_u32 v[12:13], vcc_lo, v18, v19, v[20:21]') + check('unsigned form writes the pair and vcc', + u.lines == ['{ uint3 r = mad64u(v18, v19, v20, v21);', 'v12 = r.x;', 'v13 = r.y;', 'vcc = r.z;', '}']) + s = translate('v_mad_u64_u32 v[12:13], s60, v18, v19, -1') + check('inline S2 is sign-extended and an SGPR mask is tracked', + s.lines[0] == '{ uint3 r = mad64u(v18, v19, 4294967295u, 4294967295u);' and 60 in s.masks) + i = translate('v_mad_i64_i32 v[12:13], null, v18, v19, s[46:47]') + check('signed form with null writes only the pair', + i.lines == ['{ uint3 r = mad64i(v18, v19, s46, s47);', 'v12 = r.x;', 'v13 = r.y;', '}']) + overlap = translate('v_mad_u64_u32 v[20:21], s60, v18, v19, v[20:21]') + check('a destination overlapping S2 reads S2 before it writes', overlap.lines[0].endswith('v20, v21);')) + + for asm in ('v_mad_u64_u32 v[14:15], vcc_lo, s60, 1, 0', + 'v_mad_u64_u32 v[14:15], vcc_lo, vcc_lo, 1, 0', + 'v_mad_u64_u32 v[14:15], vcc_lo, v18, v19, s[60:61]', + 'v_mad_u64_u32 v[14:15], vcc_lo, v18, v19, s[59:60]'): + masked = Probe() + masked.masks, masked.varying_s = {60}, set() + try: + masked.one('v_mad_u64_u32', asm) + ok = False + except G.Unsupported: + ok = True + check('refused lane-mask input: %s' % asm, ok) + unmasked = Probe() + unmasked.masks, unmasked.varying_s = {60}, set() + unmasked.one('v_mad_u64_u32', 'v_mad_u64_u32 v[14:15], vcc_lo, s58, 1, s[56:57]') + check('a scalar that is not a lane mask is still accepted', bool(unmasked.lines)) + tracked = Probe() + tracked.masks, tracked.varying_s = set(), set() + tracked.uniform_v, tracked.scc_uniform = set(), True + tracked.one('v_mad_u64_u32', 'v_mad_u64_u32 v[12:13], s60, v18, v19, v[20:21]') + check('an SGPR carry mask is marked varying, not uniform', + 60 in tracked.masks and 60 in tracked.varying_s and not tracked.uniform_source('s60')) + for asm in ('v_mad_i64_i32 v[12:13], vcc_lo, v18, v19, v[20:21]', + 'v_mad_u64_u32 v[12:13], null, v18, v19, v[20:21]', + 'v_mad_u64_u32 v[12:13], vcc_lo, v18, v19, v[20:21] clamp', + 'v_mad_u64_u32 v12, vcc_lo, v18, v19, v[20:21]', + 'v_mad_u64_u32 v[12:13], vcc_lo, v[18:19], v19, v[20:21]', + 'v_mad_u64_u32 v[12:13], vcc_lo, v18, v19', + 'v_mad_u64_u32 v[12:13], vcc_lo, v18, v19, v20'): + check('refused: %s' % asm, refused(asm)) + + +def pack_draw(a, b, c): + return [(a, 0, 0), (b, 0, 0), (c & MASK, 0, 0), (c >> 32, 0, 0)] + + +def ps_words(signed): + return PRE_WORDS + BODY_WORDS[signed] + POST_WORDS + + +def pixel_text(signed, mutate=False): + text = G.Pipeline(vs_words(pack_draw(0, 0, 0)), ps_words(signed), root_blob()).hlsl_ps() + if mutate: + helper = 'mad64i' if signed else 'mad64u' + # Drop the low-word carry into the high word, in the helper this shader calls. + mutated = re.sub(r'(uint3 %s\(.*?\) \{.*?)(?:hi = hs \+ c0|\+ \(lo < pl \? 1u : 0u\))' % helper, + lambda m: m.group(1) + ('hi = hs + 0u' if not signed else '+ 0u'), text, count=1) + assert mutated != text, helper + text = mutated + return text + + +def expected_words(signed, a, b, c): + result, carry = reference(signed, a, b, c) + return [result & MASK, result >> 32, 0 if signed else (0x3f800000 if carry else 0), 0] + + +def mutated_words(signed, a, b, c): + """The same reference with the low-word carry dropped from the high word (the carry-out stays exact).""" + product = (signed32(a) * signed32(b) if signed else a * b) & M64 + low = (product & MASK) + (c & MASK) + hi = ((product >> 32) + (c >> 32)) & MASK + total = product + c + return [low & MASK, hi, 0 if signed else (0x3f800000 if total > M64 else 0), 0] + + +def check_binary(llvm_mc): + for signed in (False, True): + built = assemble(llvm_mc, BODY_SOURCE[signed]) + if built != BODY_WORDS[signed]: + raise AssertionError('signed=%s: assembled %s, recorded %s' % (signed, built.hex(), BODY_WORDS[signed].hex())) + for name, source, words in (('prologue', PRE_SOURCE, PRE_WORDS), ('export', POST_SOURCE, POST_WORDS)): + if assemble(llvm_mc, source) != words: + raise AssertionError('%s fixture differs from llvm-mc' % name) + for draw_inputs in DRAWS: + chunk = pack_draw(*draw_inputs) + if assemble(llvm_mc, vs_source(chunk)) != vs_words(chunk): + raise AssertionError('vertex fixture for %s differs from llvm-mc' % (draw_inputs,)) + print('fixture words match llvm-mc') + + +def check_draw(dxc, renderer, adapter, fxc=None): + controls() + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + for signed in (False, True): + label = 'i64' if signed else 'u64' + good_ps = compile_hlsl(compiler, kind, pixel_text(signed), 'ps_mad_%s_%s' % (label, kind), + ps_profile, directory) + for index, inputs in enumerate(DRAWS): + vs = compile_hlsl(compiler, kind, + G.Pipeline(vs_words(pack_draw(*inputs)), ps_words(signed), root_blob()).hlsl_vs(), + 'vs_mad_%s_%d_%s' % (label, index, kind), vs_profile, directory) + expected = words_text(expected_words(signed, *inputs)) + run = draw(renderer, adapter, vs, good_ps, expected) + if run.returncode: + raise AssertionError('%s %s inputs %s\n%s\n%s' % (kind, label, inputs, run.stdout, run.stderr)) + print('%s %s draw %d: %s' % (kind, label, index, expected), flush=True) + if index: + continue + wrong = words_text(mutated_words(signed, *inputs)) + bad_ps = compile_hlsl(compiler, kind, pixel_text(signed, True), 'mutated_mad_%s_%s' % (label, kind), + ps_profile, directory) + run = draw(renderer, adapter, vs, bad_ps, expected) + if run.returncode == 0 or 'actual=%s' % wrong not in run.stderr: + raise AssertionError('%s %s mutation did not read %s\n%s\n%s' + % (kind, label, wrong, run.stdout, run.stderr)) + print('%s %s mutation: fails as expected, reads %s' % (kind, label, wrong), flush=True) + + +def main(): + if len(sys.argv) == 1: + controls() + return + mode, *args = sys.argv[1:] + if mode == 'binary': + check_binary(*args) + elif mode == 'draw': + check_draw(*args) + else: + raise SystemExit(__doc__) + + +if __name__ == '__main__': + main() diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 529c03a3a..320adf539 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -7749,6 +7749,60 @@ def op_v_lshrrev_b64(self, ops, mods): def op_v_ashrrev_i64(self, ops, mods): self.shift64(ops, mods, 'shr64i') + + def mad64(self, ops, mods, signed): + """v_mad_u64_u32 / v_mad_i64_i32: D = S0 * S1 + S2 modulo 2^64, two 32-bit factors, 64-bit S2. + + The unsigned form also writes the carry-out of the 64-bit add to a lane mask. The signed carry-out + is not established, so the signed form is accepted only with the discarding null destination.""" + name = 'v_mad_i64_i32' if signed else 'v_mad_u64_u32' + if mods: + raise Unsupported('%s with %s' % (name, mods)) + if len(ops) != 5: + raise Unsupported('%s with %d operands, expected 5' % (name, len(ops))) + dst = reg_range(ops[0]) + if not dst or dst[0] != 'v' or dst[2] != dst[1] + 1 or dst[2] > 255: + raise Unsupported('%s destination %s' % (name, ops[0])) + mask = ops[1] + mask_reg = reg_range(mask) + if signed: + if mask != 'null': + raise Unsupported('%s carry-out %s: only null is lowered' % (name, mask)) + elif mask not in ('vcc', 'vcc_lo') and not ( + mask_reg and mask_reg[0] == 's' and mask_reg[1] == mask_reg[2] and mask_reg[1] <= 105): + raise Unsupported('%s carry-out %s' % (name, mask)) + for tok in ops[2:4]: + r = reg_range(tok) + if tok in FLOATS or tok in ('exec', 'exec_lo') or ( + r and (r[1] != r[2] or (r[0] == 'v' and r[1] > 255) or (r[0] == 's' and r[1] > 105))): + raise Unsupported('%s factor %s' % (name, tok)) + for tok in ops[2:5]: + r = reg_range(tok) + if tok in ('vcc', 'vcc_lo', 'vcc_hi') or (r and r[0] == 's' and any( + w in self.masks for w in range(r[1], r[2] + 1))): + # u() would supply the per-lane 0/1 projection, not the architectural 32-bit mask. + raise Unsupported('%s reads the lane mask %s as an integer' % (name, tok)) + low, high = self.i64_words(ops[4]) + self.emit('{ uint3 r = %s(%s, %s, %s, %s);' % ('mad64i' if signed else 'mad64u', + self.u(ops[2]), self.u(ops[3]), low, high)) + self.set_v(dst[1], 'r.x') + self.set_v(dst[2], 'r.y') + if not signed: + expr = 'r.z' if self.exec_known else '(exec & r.z)' + if mask in ('vcc', 'vcc_lo'): + self.emit('vcc = %s;' % expr) + else: + # The carry is a per-lane bit: never a uniform scalar, whatever the scratch name hides. + self.set_s(mask_reg[1], expr, uniform=False) + self.masks.add(mask_reg[1]) + self.emit('}') + + def op_v_mad_u64_u32(self, ops, mods): + self.mad64(ops, mods, False) + + def op_v_mad_i64_i32(self, ops, mods): + self.mad64(ops, mods, True) + def op_v_cvt_pkrtz_f16_f32(self, ops, mods): if len(ops) != 3: raise Unsupported('v_cvt_pkrtz_f16_f32 with %d operands, expected 3' % len(ops)) @@ -8748,6 +8802,19 @@ def common(self): 'uint2 shr64i(uint lo, uint hi, uint sh) { sh &= 63u; uint sb = sh & 31u, sc = (32u - sb) & 31u;' ' uint cy = sb == 0u ? 0u : (hi << sc); uint h = asuint(asint(hi) >> sb);' ' return uint2(sh < 32u ? ((lo >> sb) | cy) : h, sh < 32u ? h : asuint(asint(hi) >> 31u)); }', + # v_mad_u64_u32 / v_mad_i64_i32: a * b + (chi:clo) from 16-bit partial products, so no 64-bit type. + # z is the carry of the 64-bit add (the unsigned form's lane-mask carry-out). + 'uint mulhi32(uint a, uint b) {' + ' uint a0 = a & 0xffffu, a1 = a >> 16, b0 = b & 0xffffu, b1 = b >> 16;' + ' uint p00 = a0 * b0, p01 = a0 * b1, p10 = a1 * b0, p11 = a1 * b1;' + ' uint mid = (p00 >> 16) + (p01 & 0xffffu) + (p10 & 0xffffu);' + ' return p11 + (p01 >> 16) + (p10 >> 16) + (mid >> 16); }', + 'uint3 mad64u(uint a, uint b, uint clo, uint chi) {' + ' uint ph = mulhi32(a, b), pl = a * b, lo = pl + clo, c0 = lo < pl ? 1u : 0u, hs = ph + chi, hi = hs + c0;' + ' return uint3(lo, hi, (hs < ph || hi < hs) ? 1u : 0u); }', + 'uint3 mad64i(uint a, uint b, uint clo, uint chi) {' + ' uint ph = mulhi32(a, b) - (asint(a) < 0 ? b : 0u) - (asint(b) < 0 ? a : 0u), pl = a * b, lo = pl + clo;' + ' return uint3(lo, ph + chi + (lo < pl ? 1u : 0u), 0u); }', 'uint2 bfe64(uint lo, uint hi, uint s1, uint sg) { uint w = min((s1 >> 16u) & 127u, 64u - (s1 & 63u)); uint2 e = shr64u(lo, hi, s1);' ' e = uint2(e.x & (w >= 32u ? 0xffffffffu : ((1u << (w & 31u)) - 1u)),' ' e.y & (w >= 64u ? 0xffffffffu : (w > 32u ? ((1u << ((w - 32u) & 31u)) - 1u) : 0u)));' From fe5cf85d97dcc0976f32a270b8fd509d7094871e Mon Sep 17 00:00:00 2001 From: tedin7 <110300616+tedin7@users.noreply.github.com> Date: Thu, 26 Nov 2026 06:47:57 +0100 Subject: [PATCH 153/240] gfx2hlsl: lower v_pk_mul_f16, v_pk_add_f16 and v_pk_fma_f16 (#2738) * feat: lower v_pk_mul_f16, v_pk_add_f16 and v_pk_fma_f16 in gfx2hlsl Two binary16 lanes per VGPR, selected by op_sel (low result) and op_sel_hi (high result), each rounded once. neg_lo, neg_hi, clamp, inline constants, literals and non-VGPR sources stay refused. * fix: no ':' in the f16 draw check temp file names (invalid on Windows) --- tests/f16_packed_model.py | 127 ++++++++++++++++ tests/startup_gfx2hlsl_f16_alu_check.py | 60 +++++++- tests/startup_gfx2hlsl_f16_alu_draw_check.py | 152 +++++++++++++++++-- tools/startup/gfx2hlsl.py | 42 +++++ 4 files changed, 370 insertions(+), 11 deletions(-) create mode 100644 tests/f16_packed_model.py diff --git a/tests/f16_packed_model.py b/tests/f16_packed_model.py new file mode 100644 index 000000000..f788b40af --- /dev/null +++ b/tests/f16_packed_model.py @@ -0,0 +1,127 @@ +"""Independent CPU model of v_pk_mul_f16 / v_pk_add_f16 / v_pk_fma_f16 (Part of #1723). Pure Python, no GPU. + +Per RDNA 2 VOP3P: result low half = op(source i half op_sel[i], ...), result high half = op(source i half +op_sel_hi[i], ...); absent modifiers mean op_sel [0,..] and op_sel_hi [1,..]. Each half is an IEEE binary16 +operation rounded once to nearest even. Finite operands use exact rational arithmetic; infinities and NaNs use +float64 (exact for those cases). Any NaN result is reported as the canonical quiet NaN 0x7e00 (its class is what +is compared: the payload of a generated NaN is not fixed by the format). +""" +import math +import random +import struct +from fractions import Fraction + +# 0, -0, smallest denormal, largest denormal, 1, -1, 65504, -65504, inf, -inf, quiet NaN, signalling NaN, NaN with payload +GRID = [0x0000, 0x8000, 0x0001, 0x03ff, 0x3c00, 0xbc00, 0x7bff, 0xfbff, 0x7c00, 0xfc00, 0x7e00, 0x7d00, 0x7e01] +# Extra finite words: 1/3, a tie between two binary16 values (1 + 2^-11 + 1 ulp pattern), 0.1, -2.5, 65519.9 region, min normal +EXTRA = [0x3555, 0x3c01, 0x2e66, 0xc100, 0x7bfe, 0x0400, 0x8400, 0x1400, 0x4900, 0x5640] + + +def h2f(bits): + return struct.unpack('> 15 & 1 + + +def round_exact(x): + """Binary16 encoding of a nonzero rational, nearest even, overflow to infinity (exact, no intermediate float).""" + neg = 0x8000 if x < 0 else 0 + x = abs(x) + e = max(x.numerator.bit_length() - x.denominator.bit_length() - 1, -14) + while Fraction(2) ** (e + 1) <= x: + e += 1 + while Fraction(2) ** e > x and e > -14: + e -= 1 + q = x / Fraction(2) ** (e - 10) + n = int(q) + if q - n > Fraction(1, 2) or (q - n == Fraction(1, 2) and n & 1): + n += 1 + if n == 0: + return neg + if n == 0x800: + n, e = 0x400, e + 1 + if e > 15: + return neg | 0x7c00 + return neg | (n if e == -14 and n < 0x400 else ((e + 15) << 10) | (n & 0x3ff)) + + +def half_op(op, a, b, c=0): + """One binary16 lane: op is 'mul', 'add' or 'fma' (a * b + c).""" + words = (a, b, c) if op == 'fma' else (a, b) + if any(is_nan(w) for w in words): + return 0x7e00 + if any(is_inf(w) for w in words): + x, y = h2f(a), h2f(b) + with_nan = (op == 'mul' and (math.isinf(x) or math.isinf(y)) and (x == 0 or y == 0)) + v = x * y if op != 'add' else x + y + if op == 'fma': + if (x == 0 and math.isinf(y)) or (y == 0 and math.isinf(x)): + with_nan = True + v = x * y + h2f(c) if not with_nan else math.nan + if with_nan or math.isnan(v): + return 0x7e00 + return 0x7c00 if v > 0 else 0xfc00 + fa, fb, fc = Fraction(h2f(a)), Fraction(h2f(b)), Fraction(h2f(c)) + exact = fa * fb if op == 'mul' else fa + fb if op == 'add' else fa * fb + fc + if exact != 0: + return round_exact(exact) + # An exact zero: the sign rules of IEEE 754 round-to-nearest. + if op == 'mul': + return (sign(a) ^ sign(b)) << 15 + if op == 'add': + return 0x8000 if (a == 0x8000 and b == 0x8000) else 0 + product_zero = fa * fb == 0 + psign = sign(a) ^ sign(b) + return 0x8000 if product_zero and fc == 0 and psign and sign(c) else 0 + + +def pick(word, high): + return (word >> 16 if high else word) & 0xffff + + +def packed(op, words, op_sel, op_sel_hi): + """Result word of v_pk__f16 over 32-bit source words.""" + n = len(words) + lo = half_op(op, *[pick(words[i], op_sel[i]) for i in range(n)]) + hi = half_op(op, *[pick(words[i], op_sel_hi[i]) for i in range(n)]) + return (hi << 16) | lo + + +def same(a, b): + """Word equality where every NaN half of one equals every NaN half of the other.""" + return all(x == y or (is_nan(x) and is_nan(y)) for x, y in ((a & 0xffff, b & 0xffff), (a >> 16, b >> 16))) + + +def combos(arity): + """(op_sel, op_sel_hi) selector pairs: all of them for two sources, a covering sample of 16 of the 64 for three.""" + def bits(v): + return [v >> i & 1 for i in range(arity)] + if arity == 2: + return [(bits(s), bits(h)) for s in range(4) for h in range(4)] + return [(bits(s), bits(h)) for s, h in + [(s, (5 * s + 3) % 8) for s in range(8)] + [((3 * s + 1) % 8, s) for s in range(8)]] + + +def all_combos(arity): + def bits(v): + return [v >> i & 1 for i in range(arity)] + return [(bits(s), bits(h)) for s in range(1 << arity) for h in range(1 << arity)] + + +def sample(seed, count, arity): + """count tuples of arity 32-bit words whose halves come from the grid, the finite extras and random words.""" + rng = random.Random(seed) + pool = GRID + EXTRA + def half(): + return rng.choice(pool) if rng.random() < 0.8 else rng.randrange(0x10000) + return [tuple(half() | half() << 16 for _ in range(arity)) for _ in range(count)] diff --git a/tests/startup_gfx2hlsl_f16_alu_check.py b/tests/startup_gfx2hlsl_f16_alu_check.py index 98a93969f..f67e20ff6 100644 --- a/tests/startup_gfx2hlsl_f16_alu_check.py +++ b/tests/startup_gfx2hlsl_f16_alu_check.py @@ -18,6 +18,8 @@ sys.path.insert(0, os.path.join(here, '..', 'tools')) sys.path.insert(0, os.path.join(here, '..', 'tools', 'startup')) import gfx2hlsl as G # noqa: E402 +sys.path.insert(0, here) +import f16_packed_model as M # noqa: E402 failures = [] @@ -45,6 +47,10 @@ def fma16o(a, b, c): with_nan = a * b + c if not (math.isinf(a * b) and math.isinf(c) and (a * b > 0) != (c > 0)) else math.nan return with_nan exact = Fraction(a) * Fraction(b) + Fraction(c) + if exact == 0: + # IEEE round-to-nearest: -0 only when the product and the addend are both negative zeros, else +0. + both_neg = math.copysign(1, a) * math.copysign(1, b) < 0 and math.copysign(1, c) < 0 and a * b == 0 and c == 0 + return -0.0 if both_neg else 0.0 return h2f(f2h_exact(exact)) @@ -86,7 +92,7 @@ def run(asm, regs): dst, expr = re.fullmatch(r'(v\d+) = (.*);', s.lines[0]).groups() env = {f'v{i}': v for i, v in enumerate(regs)} env.update( - f16tof32=lambda x: h2f(x), fma16o=fma16o, f16rn=lambda x: f2h(x) if abs(x) < 65520.0 else (0xfc00 if x < 0 else 0x7c00), saturate=lambda x: min(max(x, 0.0), 1.0), + f16tof32=lambda x: h2f(x), fma16o=fma16o, f16rn=lambda x: 0x7e00 if x != x else f2h(x) if abs(x) < 65520.0 else (0xfc00 if x < 0 else 0x7c00), saturate=lambda x: min(max(x, 0.0), 1.0), abs=abs, min=min, max=max, clamp=lambda x, lo, hi: min(max(x, lo), hi), trunc=lambda x: float(int(x)), isnan=math.isnan, asint=lambda x: x - (1 << 32) if x >> 31 else x, float=float, uint=lambda x: int(x) & 0xffffffff, int=int) @@ -142,6 +148,58 @@ def run(asm, regs): except G.Unsupported: check('refuses ' + asm, True) +# v_pk_{mul,add,fma}_f16: the lowering is evaluated over every selector pair and a value set built from NaN, inf, -0, +# denormals, the binary16 limits and random words, and compared with the independent model in f16_packed_model.py. +SEL = {2: ('v_pk_mul_f16', 'mul'), 3: ('v_pk_fma_f16', 'fma')} +for name, op, arity in (('v_pk_mul_f16', 'mul', 2), ('v_pk_add_f16', 'add', 2), ('v_pk_fma_f16', 'fma', 3)): + samples = M.sample(arity, 150, arity) + bad = [] + seen = {'swap': 0, 'zero_hi': 0, 'default_hi': 0} + for sel, hi in M.all_combos(arity): + mods = ' op_sel:[%s] op_sel_hi:[%s]' % (','.join(map(str, sel)), ','.join(map(str, hi))) + asm = '%s v3, %s%s' % (name, ', '.join('v%d' % i for i in range(arity)), mods) + for words in samples: + _, got = run(asm, list(words) + [0] * (4 - arity)) + want = M.packed(op, words, sel, hi) + if not M.same(got, want): + bad.append((asm, [hex(w) for w in words], hex(got), hex(want))) + # The model must tell a wrong lowering from the right one: swapped lanes, zeroed high lane, default selectors. + swapped = (want & 0xffff) << 16 | want >> 16 + seen['swap'] += not M.same(got, swapped) + seen['zero_hi'] += not M.same(got, want & 0xffff) + seen['default_hi'] += not M.same(got, M.packed(op, words, sel, [0] * arity)) + check('%s matches the independent model on every selector pair (%d pairs x %d value sets)' + % (name, len(M.all_combos(arity)), len(samples)), not bad, str(bad[:2])) + check('%s: the value sets tell a swapped-lane, zeroed-high-lane or wrong-op_sel_hi lowering from the right one' % name, + all(seen.values()), str(seen)) + # Default selectors (no modifier printed) are op_sel [0..] and op_sel_hi [1..]. + plain = '%s v3, %s' % (name, ', '.join('v%d' % i for i in range(arity))) + check('%s with no modifier uses the default selectors' % name, + all(M.same(run(plain, list(w) + [0] * (4 - arity))[1], M.packed(op, w, [0] * arity, [1] * arity)) + for w in samples)) +# Hand-checked words: 2*3 + 1 per lane, a high lane that reads the low half, inf*0 is NaN, overflow, -0. +PK = [ + ('v_pk_mul_f16 v3, v0, v1', [0x4000 | THREE << 16, 0x4200 | TWO << 16], 0x46004600), + ('v_pk_add_f16 v3, v0, v1 op_sel_hi:[0,1]', [ONE | THREE << 16, ONE | TWO << 16], f2h(2.0) | f2h(3.0) << 16), + ('v_pk_fma_f16 v3, v0, v1, v2', [TWO | TWO << 16, THREE | HALF << 16, ONE | ONE << 16], f2h(7.0) | f2h(2.0) << 16), + ('v_pk_mul_f16 v3, v0, v1', [0x7bff | 0x8000 << 16, 0x4000 | 0x3c00 << 16], 0x7c00 | 0x8000 << 16), + ('v_pk_mul_f16 v3, v0, v1', [0x8000 | 0x0000 << 16, 0x3c00 | 0xbc00 << 16], 0x80008000), +] +for asm, regs, expected in PK: + got = run(asm, regs + [0] * (4 - len(regs)))[1] + check(asm + ' ' + str([hex(r) for r in regs]), got == expected, 'got %#x want %#x' % (got, expected)) +check('inf * 0 is NaN in both lanes', M.is_nan(run('v_pk_mul_f16 v3, v0, v1', [0x7c00 | 0xfc00 << 16, 0 | 0x8000 << 16, 0, 0])[1] & 0xffff) + and M.is_nan(run('v_pk_mul_f16 v3, v0, v1', [0x7c00 | 0xfc00 << 16, 0 | 0x8000 << 16, 0, 0])[1] >> 16)) +for asm in ('v_pk_mul_f16 v3, v0, v1 neg_lo:[1,0]', 'v_pk_mul_f16 v3, v0, v1 neg_hi:[0,1]', 'v_pk_add_f16 v3, v0, v1 clamp', + 'v_pk_mul_f16 v3, 2.0, v1 op_sel_hi:[0,1]', 'v_pk_mul_f16 v3, v0, 0x4000', 'v_pk_add_f16 v3, s0, v1', + 'v_pk_mul_f16 v3, v0, v1 op_sel:[1]', 'v_pk_fma_f16 v3, v0, v1 op_sel:[0,0]', 'v_pk_mul_f16 v3, v0, v1 op_sel:[2,0]', + 'v_pk_mul_f16 v3, -v0, v1', 'v_pk_fma_f16 v3, v0, v1, v2 mul:2', 'v_pk_mul_f16 v[3:4], v0, v1'): + try: + stage().one(asm.split()[0], asm) + check('refuses ' + asm, False) + except G.Unsupported: + check('refuses ' + asm, True) + if failures: print('FAILED: ' + ', '.join(failures)) sys.exit(1) diff --git a/tests/startup_gfx2hlsl_f16_alu_draw_check.py b/tests/startup_gfx2hlsl_f16_alu_draw_check.py index 49a5e674c..d19eda21e 100644 --- a/tests/startup_gfx2hlsl_f16_alu_draw_check.py +++ b/tests/startup_gfx2hlsl_f16_alu_draw_check.py @@ -11,6 +11,10 @@ the pixel stage cannot fold them. Every source word carries garbage in its upper half: the 16-bit operations read the low half only and write a result whose upper half is zero. +The v_pk_{mul,add,fma}_f16 keys (name:half:group) draw four selector pairs per key and isolate one half of the result; +their reference is tests/f16_packed_model.py (exact rationals, NaN/inf/-0/denormal/overflow/tie values), and one +wrong expected word per run must be rejected. + The expected words come from an exact rational model of binary16 arithmetic (Fraction, then one round to binary16), not from the lowering's expressions. """ @@ -26,6 +30,7 @@ sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) sys.path.insert(0, str(HERE)) import gfx2hlsl as G # noqa: E402 +import f16_packed_model as M # noqa: E402 from startup_flat_param_check import assemble, compile_hlsl, draw, root_blob # noqa: E402 from startup_gfx2hlsl_bit_alu_check import ( # noqa: E402 POST_WORDS, PRE_WORDS, vs_source, vs_words, words_text) @@ -130,7 +135,67 @@ def sets(pairs, accumulators=None): enumerate(FMAC_DOUBLE_ROUNDING)] + DRAW['v_fmac_f16'][4:] +# v_pk_{mul,add,fma}_f16 keys 'name:half:group'. One key draws four lanes, each with its own op_sel / op_sel_hi pair +# (every pair for mul and add, a covering sample of sixteen for fma), then isolates the low or the high half of the +# result with an integer op, so the readback word is a 16-bit value (tagged below like the integer conversions). +PK_OPS = {'v_pk_mul_f16': ('mul', 2), 'v_pk_add_f16': ('add', 2), 'v_pk_fma_f16': ('fma', 3)} + + +def pk_parse(key): + name, half, group = key.split(':') + kind, arity = PK_OPS[name] + pairs = M.combos(arity)[int(group) * 4:int(group) * 4 + 4] + return name, kind, arity, half, pairs + + +def pk_lane_ok(kind, words, sel, hi, half): + """A lane whose result half is a NaN must get it from a positive NaN operand: the sign of a NaN made by inf * 0 or + inf - inf differs between adapters, so such a lane could not be compared word for word.""" + picks = [M.pick(w, (hi if half == 'hi' else sel)[i]) for i, w in enumerate(words)] + result = M.half_op(kind, *picks) + if not M.is_nan(result): + return True + return any(M.is_nan(h) for h in picks) and not any(M.is_nan(h) and M.sign(h) for h in picks) + + +def pk_lanes(key): + name, kind, arity, half, pairs = pk_parse(key) + seeds = M.sample(sum(map(ord, key)), 400, arity) + lanes = [] + for i in range(8): + sel, hi = pairs[i % 4] + word = next(w for w in seeds if pk_lane_ok(kind, w, sel, hi, half) and w not in lanes) + lanes.append(word) + seeds = [w for w in seeds if w != word] + return [tuple(w) + (0,) * (3 - arity) for w in lanes] + + +PK_KEYS = ['%s:%s:%d' % (n, h, g) for n in PK_OPS for g in range(4) for h in ('lo', 'hi')] +for _key in PK_KEYS: + DRAW[_key] = pk_lanes(_key) + + +def pk_reference(key, x, lane): + name, kind, arity, half, pairs = pk_parse(key) + sel, hi = pairs[lane % 4] + word = M.packed(kind, x[:arity], sel, hi) + return word >> 16 if half == 'hi' else word & 0xffff + + +def pk_body_source(key): + name, kind, arity, half, pairs = pk_parse(key) + lines = [] + for lane, (sel, hi) in enumerate(pairs): + dst = 12 + lane + srcs = ', '.join('v%d' % (lane + 4 * i) for i in range(arity)) + lines.append('%s v%d, %s op_sel:[%s] op_sel_hi:[%s]\n' % (name, dst, srcs, ','.join(map(str, sel)), ','.join(map(str, hi)))) + lines.append('v_and_b32 v%d, 0xffff, v%d\n' % (dst, dst) if half == 'lo' else 'v_lshrrev_b32 v%d, 16, v%d\n' % (dst, dst)) + return ''.join(lines) + + def body_source(op): + if op in PK_KEYS: + return pk_body_source(op) arity, vop1, _ = OPS[op] lines = [] for lane in range(4): @@ -179,11 +244,66 @@ def body_source(op): } +# Recorded llvm-mc (gfx1013) encodings of the v_pk_*_f16 fixtures (see pk_body_source). +BODY_WORDS.update({ + 'v_pk_mul_f16:lo:0': bytes.fromhex( + '0c4010cc00090200ff181836ffff00000d4010cc010b0208ff1a1a36ffff00000e4010cc020d0210ff1c1c36ffff00000f4010cc030f0218ff1e1e36ffff0000'), + 'v_pk_mul_f16:hi:0': bytes.fromhex( + '0c4010cc000902009018182c0d4010cc010b0208901a1a2c0e4010cc020d0210901c1c2c0f4010cc030f0218901e1e2c'), + 'v_pk_mul_f16:lo:1': bytes.fromhex( + '0c4810cc00090200ff181836ffff00000d4810cc010b0208ff1a1a36ffff00000e4810cc020d0210ff1c1c36ffff00000f4810cc030f0218ff1e1e36ffff0000'), + 'v_pk_mul_f16:hi:1': bytes.fromhex( + '0c4810cc000902009018182c0d4810cc010b0208901a1a2c0e4810cc020d0210901c1c2c0f4810cc030f0218901e1e2c'), + 'v_pk_mul_f16:lo:2': bytes.fromhex( + '0c5010cc00090200ff181836ffff00000d5010cc010b0208ff1a1a36ffff00000e5010cc020d0210ff1c1c36ffff00000f5010cc030f0218ff1e1e36ffff0000'), + 'v_pk_mul_f16:hi:2': bytes.fromhex( + '0c5010cc000902009018182c0d5010cc010b0208901a1a2c0e5010cc020d0210901c1c2c0f5010cc030f0218901e1e2c'), + 'v_pk_mul_f16:lo:3': bytes.fromhex( + '0c5810cc00090200ff181836ffff00000d5810cc010b0208ff1a1a36ffff00000e5810cc020d0210ff1c1c36ffff00000f5810cc030f0218ff1e1e36ffff0000'), + 'v_pk_mul_f16:hi:3': bytes.fromhex( + '0c5810cc000902009018182c0d5810cc010b0208901a1a2c0e5810cc020d0210901c1c2c0f5810cc030f0218901e1e2c'), + 'v_pk_add_f16:lo:0': bytes.fromhex( + '0c400fcc00090200ff181836ffff00000d400fcc010b0208ff1a1a36ffff00000e400fcc020d0210ff1c1c36ffff00000f400fcc030f0218ff1e1e36ffff0000'), + 'v_pk_add_f16:hi:0': bytes.fromhex( + '0c400fcc000902009018182c0d400fcc010b0208901a1a2c0e400fcc020d0210901c1c2c0f400fcc030f0218901e1e2c'), + 'v_pk_add_f16:lo:1': bytes.fromhex( + '0c480fcc00090200ff181836ffff00000d480fcc010b0208ff1a1a36ffff00000e480fcc020d0210ff1c1c36ffff00000f480fcc030f0218ff1e1e36ffff0000'), + 'v_pk_add_f16:hi:1': bytes.fromhex( + '0c480fcc000902009018182c0d480fcc010b0208901a1a2c0e480fcc020d0210901c1c2c0f480fcc030f0218901e1e2c'), + 'v_pk_add_f16:lo:2': bytes.fromhex( + '0c500fcc00090200ff181836ffff00000d500fcc010b0208ff1a1a36ffff00000e500fcc020d0210ff1c1c36ffff00000f500fcc030f0218ff1e1e36ffff0000'), + 'v_pk_add_f16:hi:2': bytes.fromhex( + '0c500fcc000902009018182c0d500fcc010b0208901a1a2c0e500fcc020d0210901c1c2c0f500fcc030f0218901e1e2c'), + 'v_pk_add_f16:lo:3': bytes.fromhex( + '0c580fcc00090200ff181836ffff00000d580fcc010b0208ff1a1a36ffff00000e580fcc020d0210ff1c1c36ffff00000f580fcc030f0218ff1e1e36ffff0000'), + 'v_pk_add_f16:hi:3': bytes.fromhex( + '0c580fcc000902009018182c0d580fcc010b0208901a1a2c0e580fcc020d0210901c1c2c0f580fcc030f0218901e1e2c'), + 'v_pk_fma_f16:lo:0': bytes.fromhex( + '0c000ecc0009221cff181836ffff00000d080ecc010b2604ff1a1a36ffff00000e500ecc020d2a0cff1c1c36ffff00000f180ecc030f2e14ff1e1e36ffff0000'), + 'v_pk_fma_f16:hi:0': bytes.fromhex( + '0c000ecc0009221c9018182c0d080ecc010b2604901a1a2c0e500ecc020d2a0c901c1c2c0f180ecc030f2e14901e1e2c'), + 'v_pk_fma_f16:lo:1': bytes.fromhex( + '0c600ecc0009221cff181836ffff00000d680ecc010b2604ff1a1a36ffff00000e300ecc020d2a0cff1c1c36ffff00000f780ecc030f2e14ff1e1e36ffff0000'), + 'v_pk_fma_f16:hi:1': bytes.fromhex( + '0c600ecc0009221c9018182c0d680ecc010b2604901a1a2c0e300ecc020d2a0c901c1c2c0f780ecc030f2e14901e1e2c'), + 'v_pk_fma_f16:lo:2': bytes.fromhex( + '0c080ecc00092204ff181836ffff00000d200ecc010b260cff1a1a36ffff00000e380ecc020d2a14ff1c1c36ffff00000f100ecc030f2e1cff1e1e36ffff0000'), + 'v_pk_fma_f16:hi:2': bytes.fromhex( + '0c080ecc000922049018182c0d200ecc010b260c901a1a2c0e380ecc020d2a14901c1c2c0f100ecc030f2e1c901e1e2c'), + 'v_pk_fma_f16:lo:3': bytes.fromhex( + '0c680ecc00092204ff181836ffff00000d400ecc010b260cff1a1a36ffff00000e580ecc020d2a14ff1c1c36ffff00000f700ecc030f2e1cff1e1e36ffff0000'), + 'v_pk_fma_f16:hi:3': bytes.fromhex( + '0c680ecc000922049018182c0d400ecc010b260c901a1a2c0e580ecc020d2a14901c1c2c0f700ecc030f2e1c901e1e2c'), +}) + + def ps_words(op): return PRE_WORDS + BODY_WORDS[op] + POST_WORDS -def reference(op, x): +def reference(op, x, lane=0): + if op in PK_KEYS: + return pk_reference(op, x, lane) return OPS[op][2](*x) & 0xffffffff @@ -194,7 +314,7 @@ def translate(op): # The target is R32G32B32A32_FLOAT, so a small integer result is a binary32 denormal and FXC drops it when it comes # from a float to integer conversion. The integer-result operations therefore set bit 30 on the way out of the pixel # stage and in the expected word; the translated statements themselves are unchanged. -INTEGER_RESULT = ('v_cvt_i16_f16', 'v_cvt_u16_f16') +INTEGER_RESULT = ('v_cvt_i16_f16', 'v_cvt_u16_f16', *PK_KEYS) TAG = 0x40000000 @@ -203,8 +323,8 @@ def draw_text(op): return re.sub(r'F\(v(1[2-5])\)', r'F(v\1 | 0x%xu)' % TAG, text) if op in INTEGER_RESULT else text -def draw_word(op, x): - return reference(op, x) | (TAG if op in INTEGER_RESULT else 0) +def draw_word(op, x, lane=0): + return reference(op, x, lane) | (TAG if op in INTEGER_RESULT else 0) def controls(): @@ -232,8 +352,15 @@ def check(label, ok): check('%s: every draw reference has a zero upper half' % op, all(reference(op, x) >> 16 == 0 for x in DRAW[op])) check('%s: draw sets cover two draws of four lanes' % op, len(DRAW[op]) == 8) + for key in PK_KEYS: + check('%s: every draw reference has a zero upper half' % key, + all(reference(key, x, i) >> 16 == 0 for i, x in enumerate(DRAW[key]))) + check('%s: draw sets cover two draws of four lanes' % key, len(DRAW[key]) == 8) + check('%s: no lane is a generated NaN' % key, + all(pk_lane_ok(pk_parse(key)[1], x[:pk_parse(key)[2]], *pk_parse(key)[4][i % 4], pk_parse(key)[3]) + for i, x in enumerate(DRAW[key]))) if BODY_WORDS: - for op in OPS: + for op in (*OPS, *PK_KEYS): try: text = translate(op) except G.Unsupported as e: @@ -246,11 +373,11 @@ def check(label, ok): def check_binary(llvm_mc): - for op in OPS: + for op in (*OPS, *PK_KEYS): built = assemble(llvm_mc, body_source(op)) if built != BODY_WORDS[op]: raise AssertionError('%s: assembled %s, recorded %s' % (op, built.hex(), BODY_WORDS[op].hex())) - for op in OPS: + for op in DRAW: for i in range(0, 8, 4): if assemble(llvm_mc, vs_source(DRAW[op][i:i + 4])) != vs_words(DRAW[op][i:i + 4]): raise AssertionError('vertex fixture for %s differs from llvm-mc' % op) @@ -265,13 +392,18 @@ def check_draw(dxc, renderer, adapter, fxc=None): directory = Path(tmp) for kind, compiler, vs_profile, ps_profile in compilers: for op, lanes in DRAW.items(): - ps = compile_hlsl(compiler, kind, draw_text(op), 'ps_%s_%s' % (op, kind), ps_profile, directory) + ps = compile_hlsl(compiler, kind, draw_text(op), 'ps_%s_%s' % (op.replace(':', '_'), kind), ps_profile, directory) for index in range(0, len(lanes), 4): chunk = lanes[index:index + 4] vs = compile_hlsl(compiler, kind, G.Pipeline(vs_words(chunk), ps_words(op), root_blob()).hlsl_vs(), - 'vs_%s_%d_%s' % (op, index, kind), vs_profile, directory) - expected = words_text(draw_word(op, x) for x in chunk) + 'vs_%s_%d_%s' % (op.replace(':', '_'), index, kind), vs_profile, directory) + expected = words_text(draw_word(op, x, index + n) for n, x in enumerate(chunk)) run = draw(renderer, adapter, vs, ps, expected) + if op == PK_KEYS[0] and index == 0: + # A wrong expected word must be reported: the comparison is not vacuous. + wrong = words_text([draw_word(op, chunk[0], 0) ^ 1] + [draw_word(op, x, n + 1) for n, x in enumerate(chunk[1:])]) + if not draw(renderer, adapter, vs, ps, wrong).returncode: + failures.append('%s %s wrong-value control accepted' % (kind, op)) if run.returncode: failures.append('%s %s set %d' % (kind, op, index // 4)) print('%s %s set %d MISMATCH inputs %s\n%s' % (kind, op, index // 4, chunk, run.stderr.strip()), diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 320adf539..01f2b3c4a 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -7542,6 +7542,48 @@ def op_v_fma_mixlo_f16(self, ops, mods): def op_v_fma_mixhi_f16(self, ops, mods): self.mix(ops, mods, 'hi') + def packed_half(self, base, arity, text, ops, mods): + """v_pk_{mul,add,fma}_f16: the same binary16 operation on two lanes of a VGPR pair of halves. + + Result low half = op(source i half op_sel[i], ...); high half = op(source i half op_sel_hi[i], ...). Absent + modifiers mean op_sel [0,0,0] and op_sel_hi [1,1,1] (LLVM VOP3P defaults). Both lanes are written (no zeroing). + Not modelled, so refused: neg_lo, neg_hi, clamp, any other modifier, and a source that is not a plain VGPR + (an inline constant or a literal reaches the high lane in a way that is not proven; hold it in a VGPR first). + """ + if len(ops) != arity + 1: + raise Unsupported('%s with %d operands, expected %d' % (base, len(ops), arity + 1)) + sel = {'op_sel': [0] * arity, 'op_sel_hi': [1] * arity} + for m in mods: + key, _, value = m.partition(':') + if key not in sel or not (value.startswith('[') and value.endswith(']')): + raise Unsupported('%s with %s' % (base, m)) + bits = value[1:-1].split(',') + if len(bits) != arity or any(b not in ('0', '1') for b in bits): + raise Unsupported('%s with %s' % (base, m)) + sel[key] = [int(b) for b in bits] + for tok in ops: + r = reg_range(tok) + if not r or r[0] != 'v' or r[1] != r[2] or tok != 'v%d' % r[1]: + raise Unsupported('%s operand %s is not a single VGPR' % (base, tok)) + lanes = [] + for picks in (sel['op_sel'], sel['op_sel_hi']): + args = [] + for tok, hi, both in zip(ops[1:], picks, zip(sel['op_sel'], sel['op_sel_hi'])): + word = self.u(tok, low16_only=not any(both)) + args.append('f16tof32(%s)' % ('(%s >> 16) & 0xffffu' % word if hi else '%s & 0xffffu' % word)) + lanes.append('f16rn(%s)' % text.format(*args)) + d = reg_range(ops[0])[1] + self.set_v(d, '%s | (%s << 16)' % tuple(lanes)) + + def op_v_pk_mul_f16(self, ops, mods): + self.packed_half('v_pk_mul_f16', 2, '{0} * {1}', ops, mods) + + def op_v_pk_add_f16(self, ops, mods): + self.packed_half('v_pk_add_f16', 2, '{0} + {1}', ops, mods) + + def op_v_pk_fma_f16(self, ops, mods): + self.packed_half('v_pk_fma_f16', 3, 'fma16o({0}, {1}, {2})', ops, mods) + def cube(self, kind, ops, mods): """v_cube{id,sc,tc,ma}_f32: LLVM's ConstantFoldAMDGCNCubeIntrinsic. From 594bb3ce639be18bd8b28cf950f362506d275b66 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Thu, 26 Nov 2026 06:50:39 +0100 Subject: [PATCH 154/240] startup: bind a compute heap record whose index is read from a table buffer (#2580) * feat: record the compute root signature and descriptor tables (slots 33 and 35) Header-only state in list_compute_root.h with a Linux-testable check. Dispatch (slot 14) is not handled here; the state is exposed through ready() and table() for it. Refs #870. * feat: record compute descriptor tables (slot 35) and clear them on a root or heap change * startup: record SetComputeRoot32BitConstant(s) (list slots 37, 39) Compute root constants are kept per list next to the graphics ones, in a shared 16 x 8 word store that refuses parameter >= 16 and offset >= 8. A new compute root signature clears them. * feat: record command-list slot 14 Dispatch on the desktop list Part of #870. Forward Dispatch only with a desktop compute pipeline and root bound and group counts within 65535 per axis; refuse otherwise. * startup: refuse Dispatch under a compute root with unforwarded arguments, document slot 14 * startup: gate Dispatch on bound compute root SRVs and a pipeline built against the bound root Slot 43 clears a parameter's binding when a replacement is rejected, slot 33 clears all bindings, and the compute pipeline records its root so a mismatched pair is refused. * startup: record SetComputeRoot32BitConstant(s) (list slots 37, 39) Compute root constants are kept per list next to the graphics ones, in a shared 16 x 8 word store that refuses parameter >= 16 and offset >= 8. A new compute root signature clears them. * feat: record command-list slot 14 Dispatch on the desktop list Part of #870. Forward Dispatch only with a desktop compute pipeline and root bound and group counts within 65535 per axis; refuse otherwise. * startup: refuse Dispatch under a compute root with unforwarded arguments, document slot 14 * startup: gate Dispatch on bound compute root SRVs and a pipeline built against the bound root Slot 43 clears a parameter's binding when a replacement is rejected, slot 33 clears all bindings, and the compute pipeline records its root so a mismatched pair is refused. * fix: pass pipeline root out-param in slot86 mesh cached pipeline build * fix: track which compute root constant words were set; drop slot 40 claim * Dispatch translated compute programs with raw table buffers A device slot 67 placeholder keeps the key of its published request. At list slot 14 the stand-in loads the stage cs manifest and compiled program for that key and records the dispatch: raw buffer inputs and outputs from hardware descriptors in the recorded compute tables, entry values from the recorded compute root constants. Other manifest lines leave the pipeline untranslated; a dispatch that cannot be bound completely is refused with one logged reason and records nothing. startup_compute_dispatch_{warp,hardware} drives a source-built program through the stand-in list and reads the output back, with controls before translation, without a Dispatch and for a refused output. Co-Authored-By: Claude Fable 5.2 * Log untranslated compute dispatches on their own line budget Dispatches that arrive before the offline translation no longer use up the lines kept for refusals at bind time. Co-Authored-By: Claude Fable 5.2 * Count compute dispatches per key with their first refusal The per-call refusal lines share one small budget, so a run cannot rank keys by dispatch count. Each key now keeps its Dispatch count, the calls recorded and the reason and table descriptor of its first refusal; the periodic totals are followed by the refused dispatches per reason and the 40 keys with the most dispatches. A manifest that exists but cannot be bound is counted apart from an absent one ("not modelled"). Co-Authored-By: Claude Fable 5.2 * Dispatch translated compute programs that store to 2D textures A `uav tex2d float table channels 4` manifest line is bound from the token of the unordered access view the title created in its descriptor memory. Everything else is refused with its own reason: an entry that is no such token, a view the desktop did not create, a view that is not 2D, a format a float4 store cannot target, and a texture bound to two slots of one dispatch. Programs without entry values, inputs or outputs load too: the translated root no longer emits an empty range or drops the table when only outputs exist. The fixture stores through the stand-in's own list into a 32x8 RGBA16_FLOAT texture and reads it back with CopyTextureRegion. Co-Authored-By: Claude Fable 5.2 * Dispatch translated compute programs that read 2D textures A `srv tex2d table ` manifest line is bound from the token of the shader resource view the title created, through the texture the draw path samples for that resource, uploaded first when the title filled it in memory. `smp` lines become static samplers of the translated root. A dispatch is refused, never bound to a null view, when the entry is no such token, the resource has no desktop texture, the view is not 2D or names a packed format, or the upload fails. Sampler heaps, comparison samplers and other texture kinds keep the translation unavailable. The fixture samples a 1x1 texture into the stored words of the raw buffer case; without a view the dispatch is refused and the output is untouched. Co-Authored-By: Claude Fable 5.2 * Check a compute manifest without entry values at Dispatch Co-Authored-By: Claude Fable 5.2 * Document texture views and the census of translated compute Dispatch Co-Authored-By: Claude Fable 5.2 * Check the device on every 64th translated Dispatch and drop a liveness test The device check drains the debug layer; a draw runs it on every 64th call and the queue's execute drains the rest. A view token whose resource the caller released is the caller's misuse, as on the draw path. Co-Authored-By: Claude Fable 5.2 * Compute dispatch: allow two outputs of one texture, refuse packed outputs, print every census key A texture is refused only when the same call reads and writes it; two outputs of one texture share the unordered access state. A packed output view format gets its own refusal reason. The census prints every dispatched key instead of the first 40, and the wording on refused calls says what may already be recorded (an input texture upload). Co-Authored-By: Claude Fable 5.2 * startup: compute input named by a resource heap record a root constant indexes gfx2hlsl.py lowers one form of a register-offset load through the directly indexed resource heap pointer of a compute root signature: s_lshl_b32 R, , 5 s_load_dwordx4 D, s[H:H+1], R ; s[H+1] a constant zero, no offset: with no write of R and no branch target in between. D is a buffer descriptor and the manifest names it `srv buf heap rootconst `. Every other form keeps a refusal that names it, including an index read from a buffer. The stand-in records the title memory of the list's view heap on every slot 32 call (it kept only the sampler heap and, for oversized heaps, the wrapper) and a Dispatch reads the 16-byte descriptor at byte `word << 5` of that memory, then binds it through the path a table record takes. A record outside the heap refuses the dispatch and binds nothing. Checks: tests/startup_gfx2hlsl_heap_record_check.py (manifest and HLSL exact, 19 refused controls, one translator mutation, LLVM 15 reassembly) and tests/startup_compute_dispatch_heap_check.py on WARP and a physical adapter. Refs #2274 Co-Authored-By: Claude Fable 5.2 * startup: drop a heap record control whose branch target was inside an instruction The second positive case of startup_gfx2hlsl_heap_record_check.py branched to the second dword of the two-dword heap load. The case with a branch target before the shift already covers the form outside the entry block. The experiments entry now says that WARP's descriptor increment is not 32 bytes. Refs #2274 Co-Authored-By: Claude Fable 5.2 * startup: read the stage kind as the other handlers do in the heap load A check added on main calls op_s_load_dwordx8 on a stage built without a kind; the heap record branch read self.kind directly. Co-Authored-By: Claude Fable 5.2 * startup: avoid calling the compute driver after process termination begins The slot 67 cache owns desktop COM objects until module teardown. During process termination, the driver can already be shut down when static destructors run. Keep normal reference release on explicit unload and skip driver calls only during process termination. AI-assisted with Codex (GPT-6.2 Astra, xhigh). * Repair a broken line in the dispatch check Co-Authored-By: Claude Fable 5.2 * Pin four existing texture dispatch refusals: integer view format, manifest version, stage, output also an input Co-Authored-By: Claude Fable 5.2 * startup: bind a compute heap record whose index is a table buffer word at a dispatch-constant offset A compute program that reads its heap record index with s_buffer_load from an unmodified table buffer, at a literal byte offset or at a root constant word times a literal plus a literal (dword-aligned), then shifts it left by 5 for the heap s_load, is translated: the manifest names the word as `srv buf heap word table at [rootconst times ]`. At Dispatch the runtime reads that word from the recording's upload memory, where no GPU command writes, and binds the record it indexes. A word outside the buffer or outside upload memory refuses the dispatch with one reason. Every other index source keeps the buffer refusal. Co-Authored-By: Claude Opus 5.5 * docs: a compute heap record whose index is read from a table buffer Co-Authored-By: Claude Opus 5.5 * docs: state the measured first refusals and the heap-record ceiling exactly Co-Authored-By: Claude Opus 5.5 * Drop the repeated compute root reset left by merging two slot 14 snapshots list_compute_root cleared compute_srv_bound and recomputed compute_root_has_arguments twice; the second copy came from the second #1974 snapshot merge and changed nothing. Co-Authored-By: Claude Opus 5.5 * startup: keep the descriptor load tag when checking the index word's table buffer Co-Authored-By: Claude Fable 5.2 * startup: read the pipe's modified set tolerantly in the heap index word check Three existing checks build a stage on a bare pipe object without it. Co-Authored-By: Claude Fable 5.2 --------- Co-authored-by: tedin7 Co-authored-by: tedin7 Co-authored-by: Claude Fable 5.2 Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> Co-authored-by: RavenCurseBurg <360931527+RavenCurseBurg@users.noreply.github.com> --- .github/workflows/windows.yml | 2 + AGENTS.md | 1 + CMakeLists.txt | 8 +- docs/experiments.md | 15 +- src/startup_stubs/d3d12_compute_dispatch.inl | 51 +++++- ...tartup_compute_dispatch_heap_word_check.py | 94 ++++++++++ tests/startup_gfx2hlsl_heap_record_check.py | 16 +- tests/startup_gfx2hlsl_heap_word_check.py | 160 ++++++++++++++++++ tests/startup_stream_consumer.cpp | 23 ++- tools/startup/gfx2hlsl.py | 86 ++++++++-- 10 files changed, 420 insertions(+), 36 deletions(-) create mode 100644 tests/startup_compute_dispatch_heap_word_check.py create mode 100644 tests/startup_gfx2hlsl_heap_word_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index cb71ae8c5..7ba2eed9d 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -110,6 +110,7 @@ jobs: (["tests/startup_compute_image_store_d16_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_compute_readfirstlane_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_heap_record_check.py", "--llvm-mc", "llvm-mc-15"], {}), + (["tests/startup_gfx2hlsl_heap_word_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_compute_gather_l_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_compute_buffer_atomics_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_compute_store_d16_x_check.py", "binary", "llvm-mc-15"], {}), @@ -306,6 +307,7 @@ jobs: tests/startup_gfx2hlsl_readfirstlane_recompute_check.py \ tests/startup_compute_readfirstlane_check.py \ tests/startup_gfx2hlsl_heap_record_check.py \ + tests/startup_gfx2hlsl_heap_word_check.py \ tests/startup_gfx2hlsl_calculated_target_check.py \ tests/startup_triage_run_check.py \ tests/startup_run_ps1_check.py \ diff --git a/AGENTS.md b/AGENTS.md index 402377e16..bf2d22898 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -173,6 +173,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_compute_image_store_d16_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_heap_record_check.py ./out/pe-env/bin/python -B tests/startup_compute_store_format_xyzw_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_heap_word_check.py ./out/pe-env/bin/python -B tests/startup_compute_translate_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_swap_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_s_abs_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 01038e677..e87c5b2f0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3290,6 +3290,8 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_image_store_d16_check.py") add_test(NAME startup_gfx2hlsl_heap_record COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_heap_record_check.py") + add_test(NAME startup_gfx2hlsl_heap_word COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_heap_word_check.py") add_test(NAME startup_compute_readfirstlane COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_readfirstlane_check.py") add_test(NAME startup_compute_gather_l COMMAND "${INTAKE_PYTHON}" -B @@ -4467,11 +4469,15 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME startup_compute_dispatch_heap_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_dispatch_heap_check.py" "$" "${DXC_EXECUTABLE}" ${adapter}) + add_test(NAME startup_compute_dispatch_heap_word_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_dispatch_heap_word_check.py" "$" + "${DXC_EXECUTABLE}" ${adapter}) add_test(NAME startup_compute_live_retry_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_live_retry_check.py" "$" "${DXC_EXECUTABLE}" ${adapter}) set_tests_properties(startup_compute_dispatch_${adapter} startup_compute_dispatch_texture_${adapter} - startup_compute_dispatch_heap_${adapter} startup_compute_live_retry_${adapter} + startup_compute_dispatch_heap_${adapter} startup_compute_dispatch_heap_word_${adapter} + startup_compute_live_retry_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() add_test(NAME startup_stream_adapter_filter COMMAND "${INTAKE_PYTHON}" -B diff --git a/docs/experiments.md b/docs/experiments.md index 3831d690b..e69fadc8f 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -16654,7 +16654,7 @@ ctest --preset dev --no-tests=error -R "^startup_compute_dispatch_" -V A compute root signature that indexes the resource heap directly (root flag 0x400) passes the heap pointer in one SGPR after the root parameters. `gfx2hlsl.py` lowers one form of a load through that pointer: `s_lshl_b32 R, , 5`, then, with no write of `R` and no branch target in between, `s_load_dwordx4 D, s[H:H+1], R` with a constant zero in `s[H+1]` and no `offset:` modifier. `D` is then a buffer descriptor, and the manifest names it `srv buf heap rootconst `. Slot 32 now records the title memory of the list's view heap on every call; at Dispatch the stand-in reads the 16-byte descriptor at byte `word << 5` (32-bit arithmetic, as the program computes it) of that memory and binds the buffer through the path a `table` record takes. A record outside the heap refuses the dispatch (`a heap record is outside the list's view heap`) and binds nothing. -Every other form keeps a refusal that names it: another shift or index, an index register written again, a branch target between the shift and the load, a high word that is not a constant zero, an `offset:` modifier, eight dwords (an image record), and an index read from a buffer (`s_load of a resource heap record whose index is read from a buffer`). A formatted load or a store through such a record, and the graphics stages, are refused as before. +Every other form keeps a refusal that names it: another shift or index, an index register written again, a branch target between the shift and the load, a high word that is not a constant zero, an `offset:` modifier, eight dwords (an image record), and an index read from a buffer in any form other than the one below (`s_load of a resource heap record whose index is read from a buffer other than a table buffer at a dispatch-constant offset`). A formatted load or a store through such a record, and the graphics stages, are refused as before. `tests/startup_gfx2hlsl_heap_record_check.py` compares the manifest and the HLSL of a source-built gfx1013 program whole, runs 19 refused controls and one translator mutation (without the write tracking, a refused control translates), and with `--llvm-mc` reassembles every instruction. `tests/startup_compute_dispatch_heap_check.py` dispatches that program through the stand-in's list on WARP and on a physical adapter (exit 77 without one): the input descriptor is only in heap record 2, records 0 and 1 hold the output's descriptor, and all 320 output words must match; before translation and for a record outside the heap every word keeps its sentinel. Changing the runtime's shift to 4, or ignoring the index, makes the dispatch test fail (`an output buffer is also an input`). @@ -16686,6 +16686,19 @@ python -B tests/startup_compute_lds_dual_atomics_check.py binary llvm-mc-15 Not covered here: `llvm-mc-15` assembly step on Linux CI (`binary`), signed 32-bit (`ds_min_i32`/`ds_max_i32`), `ds_xor_b32`, `ds_sub_u32`/`ds_rsub_u32`, float LDS atomics, and 64-bit LDS dual/atomic forms. +#### A heap record index read from a table buffer + +The index can also be a word of a table buffer. `gfx2hlsl.py` accepts `s_buffer_load_dword(xN)` from a table buffer descriptor that no instruction modified, at a literal byte offset or at ` * k + c` built with `s_mul_i32`, `s_mulk_i32`, `s_add_u32`, `s_add_i32` or `s_addk_i32` and literals (plus any `offset:` modifier), dword-aligned, with no branch target between the arithmetic and the load or between the load and the shift. The manifest names the word as `srv buf heap word table at [rootconst times ]`. At Dispatch the stand-in reads the table record, computes the byte offset in 32-bit arithmetic, reads the index word from the buffer's memory and binds the heap record it names as above. The read is made at record time, so it is sound only when the GPU does not write the word: the stand-in reads it only when the buffer lies in the recording's upload memory (list slot 148), which no GPU command writes. A buffer elsewhere refuses the dispatch (`a heap index word is not in the list's upload memory`), and so does a word past the buffer's `stride * num_records` bytes (`a heap index word is outside its table buffer`). An index from a per-thread value, a group ID, another buffer word, a register sum or a modified descriptor keeps the refusal. + +`tests/startup_gfx2hlsl_heap_word_check.py` compares the manifest and the HLSL of a source-built program whole, with six more accepted forms and ten refused controls, and with `--llvm-mc` reassembles every new instruction. `tests/startup_compute_dispatch_heap_word_check.py` dispatches it on WARP and on a physical adapter: only the word at `288 + 336 * ` names the input's record, every other word names an output record, and all 320 output words must match; a record outside the heap, a buffer that ends before the word and a buffer outside upload memory each refuse with one reason and leave every output word at its sentinel. Ignoring the scale, the byte offset or the read word, or dropping the upload or range check, makes the dispatch test fail; dropping the alignment, descriptor, register-offset or branch-target checks makes a translator control fail. + +Measured on one synthetic program. That the title leaves the upload memory unchanged between recording and execution is a hypothesis, the same one the heap record read relies on, and which memory the real index buffers live in has not been measured. In a local set of 158 compute requests that hold such a load, 153 stopped first at the buffer-read index. All 153 change their first refusal and none translates fully yet: 145 now stop at a later instruction (82 at a per-lane `vcc` live at an `s_cbranch_execz` join, 24 at `v_fma_mix_f32`, 14 at `src_scc` in `s_mul_i32`, 25 at others), 6 at a buffer read in another form and 2 at an 8-dword record. 145 programs hold a heap load that now lowers, but 120 of the 158 still hold a refused heap-record load somewhere: 101 a buffer read in another form, 32 an offset that is not a root constant shifted by 5, 2 an 8-dword record (this counts every refusal site, including sites after an earlier refusal). Most of the buffer-form sites compute the offset or read the word before a branch target, which ends the marks because another path into the join may hold a different word; in about 97 programs an 8-dword (image) heap record would stay refused even past that. + +```powershell +python -B tests/startup_gfx2hlsl_heap_word_check.py --llvm-mc llvm-mc-15 +ctest --preset dev --no-tests=error -R "^startup_compute_dispatch_heap_word_" -V +``` + ## Startup translator: a short operand list is refused, never a translator crash The batch translator records any non-`Unsupported` exception from a handler as diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index dffee3996..618ad9976 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -11,8 +11,15 @@ struct ComputeTranslation { // Root parameter and byte offset (views), or parameter and word (entry values). A heap view names the root - // constant (parameter and word) that indexes its 32-byte record in the list's view heap. - struct Slot { int a, b; bool texture, heap; }; + // constant (parameter and word) that indexes its 32-byte record in the list's view heap, or, with word_param + // set, the table buffer (word_param, word_byte) whose word at byte at + root constant (a, b) * times (a < 0: + // at alone) is the index. + struct Slot { + int a, b; + bool texture, heap; + int word_param = -1, word_byte = 0; + std::uint32_t at = 0, times = 0; + }; u64 key = 0; int state = 0; // 0 not loaded, 1 ready, 2 unavailable ULONGLONG retry_manifest_at = 0; // only an absent manifest can become ready later @@ -81,7 +88,7 @@ const char* load_compute_translation(ComputeTranslation& tr) continue; } unsigned i = 0, x = 0, y = 0, z = 0, w = 0; - int a = 0, b = 0, used = 0; + int a = 0, b = 0, c = 0, d = 0, used = 0; const auto whole = [&] { return used == static_cast(line.size()); }; if (line.empty() || (std::sscanf(line.c_str(), "group %u %u %u%n", &x, &y, &z, &used) == 3 && whole())) continue; if (std::sscanf(line.c_str(), "ud %u%n", &declared_uds, &used) == 1 && whole()) continue; @@ -92,6 +99,12 @@ const char* load_compute_translation(ComputeTranslation& tr) else if (std::sscanf(line.c_str(), "srv %u buf heap rootconst %d %d%n", &i, &a, &b, &used) == 3 && whole() && i == tr.srvs.size()) tr.srvs.push_back({a, b, false, true}); + else if (std::sscanf(line.c_str(), "srv %u buf heap word table %d %d at %u%n", &i, &a, &b, &x, &used) == 4 && whole() && + i == tr.srvs.size()) + tr.srvs.push_back({-1, 0, false, true, a, b, x}); + else if (std::sscanf(line.c_str(), "srv %u buf heap word table %d %d at %u rootconst %d %d times %u%n", &i, &a, &b, &x, + &c, &d, &y, &used) == 7 && whole() && i == tr.srvs.size()) + tr.srvs.push_back({c, d, false, true, a, b, x, y}); else if (std::sscanf(line.c_str(), "uav %u table %d %d%n", &i, &a, &b, &used) == 3 && whole() && i == tr.uavs.size()) tr.uavs.push_back({a, b}); else if (std::sscanf(line.c_str(), "uav %u tex2d float table %d %d channels 4%n", &i, &a, &b, &used) == 3 && whole() && @@ -174,12 +187,34 @@ bool dispatch_translated(Wrapper* self, UINT x, UINT y, UINT z) for (std::size_t i = 0; i < count && !reason; ++i) { const bool output = i >= inputs; const ComputeTranslation::Slot slot = output ? tr->uavs[i - inputs] : tr->srvs[i]; - // A heap record sits at the 32-bit byte offset the program computes, the root constant word shifted left by - // 5, in the title memory of the list's view heap: a literal byte offset, as a table's is. - const u64 entry = slot.a < 0 || slot.b < 0 ? 0 - : slot.heap ? pass.title_view_heap.record(std::uint32_t{pass.compute_constants.word(slot.a, slot.b)} << 5, 16) - : pass.compute_tables.table(slot.a).record(static_cast(slot.b), slot.texture ? 32 : 16); + std::uint32_t index = slot.a < 0 || slot.b < 0 ? 0 : pass.compute_constants.word(slot.a, slot.b); std::memset(words, 0, sizeof(words)); + if (slot.word_param >= 0) { + // The index word is read now from the recording's upload memory, where the title wrote it (no GPU command + // writes there), at the dword-aligned 32-bit byte offset the program reads it at. + const u64 table_entry = pass.compute_tables.table(slot.word_param).record(static_cast(slot.word_byte), 16); + if (!table_entry || !x2w_local::readable(reinterpret_cast(table_entry), 16)) { + reason = "a table descriptor is not bound"; + break; + } + std::memcpy(words, reinterpret_cast(table_entry), 16); + const std::uint32_t at = slot.at + index * slot.times; + const u64 address = words[0] | (u64{words[1] & 0xffff} << 32); + const UINT stride = (words[1] >> 16) & 0x3fff; + if (words[0] == view_token_magic || !list_upload_range(self, address + at, 4).resource) { + reason = "a heap index word is not in the list's upload memory"; + break; + } + if (u64{at} + 4 > u64{stride ? stride : 1} * words[2]) { + reason = "a heap index word is outside its table buffer"; + break; + } + std::memcpy(&index, reinterpret_cast(address + at), 4); + } + // A heap record sits at the 32-bit byte offset the program computes, the index shifted left by 5, in the + // title memory of the list's view heap: a literal byte offset, as a table's is. + const u64 entry = slot.heap ? (slot.word_param >= 0 || slot.a >= 0 ? pass.title_view_heap.record(std::uint32_t{index << 5}, 16) : 0) + : slot.a < 0 || slot.b < 0 ? 0 : pass.compute_tables.table(slot.a).record(static_cast(slot.b), slot.texture ? 32 : 16); const std::size_t entry_bytes = slot.texture ? 32 : 16; if (!entry || !x2w_local::readable(reinterpret_cast(entry), entry_bytes)) { reason = slot.heap ? "a heap record is outside the list's view heap" : "a table descriptor is not bound"; diff --git a/tests/startup_compute_dispatch_heap_word_check.py b/tests/startup_compute_dispatch_heap_word_check.py new file mode 100644 index 000000000..4ddb8ad31 --- /dev/null +++ b/tests/startup_compute_dispatch_heap_word_check.py @@ -0,0 +1,94 @@ +"""A translated compute program whose input is the resource heap record a word of a table buffer indexes (slot 14). + +usage: startup_compute_dispatch_heap_word_check.py + +The consumer creates the program of startup_gfx2hlsl_heap_word_check.py as a device slot 67 pipeline and records it +as startup_compute_dispatch_heap_check.py does, with root constant word 2 set to 1 and a buffer in the recording's +upload memory (list slot 148) at table byte 96. Word 288 + 336 * 1 of that buffer is 2, the heap record of the +input. Heap records 0 and 1 hold the output's descriptor and every other word of the buffer names one of them, so +a dispatch that ignores the word, the root constant, its scale or the byte offset is refused instead of passing. +Runs sharing one cache: + +1. before translation: the request is published and the Dispatch is refused with "no translation"; +2. after gfx2hlsl.py --pending with DXC: the manifest names the word and all 320 words equal the expectation of + case A of startup_gfx2hlsl_compute_check.py; +3. dispatch-heap-word-outside (the word is 0x07ffffff, a record past the heap), dispatch-heap-word-past (the + buffer ends at the word) and dispatch-heap-word-placed (the buffer is the placed input, not upload memory): + each refused with one logged reason, every output word keeps the sentinel and the input is unchanged. +Exit 77 when the adapter is not available. +""" +import os +from pathlib import Path +import subprocess +import sys +import tempfile + +import startup_gfx2hlsl_compute_check as C +import startup_gfx2hlsl_heap_record_check as H +import startup_gfx2hlsl_heap_word_check as W +from startup_compute_dispatch_check import dispatch, lines +from startup_compute_request_check import DATA, prepare +from startup_compute_translate_check import state_a +from startup_stream_check import gfx2hlsl as G + +CONTROLS = ( + ('dispatch-heap-word-outside', "a heap record is outside the list's view heap"), + ('dispatch-heap-word-past', 'a heap index word is outside its table buffer'), + ('dispatch-heap-word-placed', "a heap index word is not in the list's upload memory"), +) + + +def main(consumer, dxc, adapter): + with tempfile.TemporaryDirectory() as temporary: + directory = Path(temporary) + cache, env = prepare(directory) + env.update(X2W_D3D12_LIST_NOOP='1', X2W_D3D12_DEBUG='1') # guest lists; debug-layer messages go to the log + if adapter == 'hardware': + env['X2W_TEST_DISPATCH_HARDWARE'] = '1' + (directory / 'compute_root').write_bytes(H.root_blob(table_range=True)) + env['X2W_TEST_COMPUTE_ROOT'] = str(directory / 'compute_root') + assert H.GROUPS == (3, 2, 2) and W.FORM == '288 rootconst 0 2 times 336', 'the consumer hard-codes these' + (directory / 'program').write_bytes(W.WORDS) + (directory / 'data').write_bytes(DATA) + (directory / 'state').write_bytes(state_a(H.GROUP, H.RSRC2)) + untouched, expected = [C.SENTINEL] * C.WORDS, C.expected('A') + assert expected != untouched + + got, result = dispatch(directory, consumer, env, 'dispatch-heap-word') + print(result.stdout, end='') + assert got == untouched, 'a Dispatch without a translation wrote the output' + assert len(lines(result, 'Dispatch(3, 2, 2) refused: no translation')) == 1, result.stderr[-3000:] + published = lines(result, 'x2w-draw compute request') + assert published and ' published ' in published[0], result.stderr[-3000:] + key = int(published[0].split()[3], 16) + + out = subprocess.run([sys.executable, '-B', G.__file__, '--pending', cache], check=True, capture_output=True, + text=True, env=dict(os.environ, X2W_DXC=dxc)).stdout + assert f'{key:016x}: ok' in out, out + assert (cache / f'{key:016x}.txt').read_text() == W.MANIFEST % W.FORM + + got, result = dispatch(directory, consumer, env, 'dispatch-heap-word') + wrong = [i for i in range(C.WORDS) if got[i] != expected[i]] + assert not wrong, 'word=%d got=%08x expected=%08x (%d words differ)\n%s' % ( + wrong[0], got[wrong[0]], expected[wrong[0]], len(wrong), result.stderr[-3000:]) + assert len(lines(result, 'Dispatch(3, 2, 2) translated')) == 1 and not lines(result, 'refused'), result.stderr[-3000:] + layer = lines(result, 'x2w-d3d12 debug layer: ') + errors = [line for line in lines(result, 'x2w-d3d12-debug ') if ' sev=0 ' in line or ' sev=1 ' in line] + assert not errors, errors[0] + print('debug layer: ' + ('enabled, no error message' if layer and '0x00000000' in layer[0] else 'unavailable')) + + for mode, reason in CONTROLS: + got, result = dispatch(directory, consumer, env, mode) + assert got == untouched, '%s: a refused Dispatch wrote the output' % mode + refused = lines(result, 'refused: ') + census = lines(result, 'x2w-render compute census') + assert len(refused) == 1 and reason in refused[0], '%s:\n%s' % (mode, result.stderr[-3000:]) + assert len(census) == 3 and census[1].endswith(f'reason "{reason}": 1 keys, 1 dispatches'), (mode, census) + print(f'startup_compute_dispatch_heap_word: PASS on {adapter} (all {C.WORDS} words match through the index word; ' + f'untouched before translation and for {len(CONTROLS)} refused controls)') + + +if __name__ == '__main__': + if len(sys.argv) != 4 or sys.argv[3] not in ('warp', 'hardware'): + sys.exit(__doc__) + main(*sys.argv[1:]) diff --git a/tests/startup_gfx2hlsl_heap_record_check.py b/tests/startup_gfx2hlsl_heap_record_check.py index 0ea857586..ff517ffc8 100644 --- a/tests/startup_gfx2hlsl_heap_record_check.py +++ b/tests/startup_gfx2hlsl_heap_record_check.py @@ -13,8 +13,9 @@ dispatch reads the 32-byte heap record that root constant word 2 indexes. The HLSL and the manifest are compared whole. Every other form keeps a refusal: another shift, another index, an index register written again, a branch target between the shift and the load, a high word that is not a constant zero, an offset -modifier, eight dwords, an index read from a buffer (named as such), a formatted load or a store through the -record, and the graphics stages. --llvm-mc reassembles every instruction used here and compares the words. +modifier, eight dwords, an index read from a buffer at an offset that differs between groups (named as such; +startup_gfx2hlsl_heap_word_check.py covers the buffer forms that are accepted), a formatted load or a store through +the record, and the graphics stages. --llvm-mc reassembles every instruction used here and compares the words. """ import argparse import struct @@ -52,7 +53,8 @@ 's_load_dwordx8 s[16:23], s[8:9], s6': '04040cf40000000c', 's_load_dwordx4 s[16:19], s[8:9], s5': '040408f40000000a', 's_load_dwordx4 s[16:19], s[8:9], m0': '040408f4000000f8', 's_add_u32 s6, s6, 0': '06800680', 's_load_dwordx4 s[28:31], s[12:13], 0x20': '060708f4200000fa', - 's_buffer_load_dword s6, s[28:31], 0x0': '8e0120f4000000fa', 's_buffer_load_dword s26, s[28:31], 0x0': '8e0620f4000000fa', + 's_buffer_load_dword s6, s[28:31], 0x0': '8e0120f4000000fa', 's_buffer_load_dword s6, s[28:31], s14': '8e0120f40000001c', + 's_buffer_load_dword s26, s[28:31], s14': '8e0620f40000001c', 's_lshl_b32 s6, s26, 5': '1a85068f', 's_cmp_eq_u32 s4, 0': '048006bf', 's_cbranch_scc0 1': '010084bf', 's_nop 0': '000080bf', 'buffer_load_format_xyzw v[5:8], v4, s[16:19], 0 offen': '00100ce004050480', 'buffer_store_dword v5, v4, s[16:19], 0 offen': '001070e004050480', @@ -166,10 +168,10 @@ def check_refusals(): ('index register loaded from a buffer after the shift', {SHIFT: (SHIFT, TABLE_LOAD, 's_buffer_load_dword s6, s[28:31], 0x0')}, not_shifted), ('branch target between the shift and the load', {SHIFT: (SHIFT,) + JUMP}, not_shifted), - ('index read from a buffer', {SHIFT: (TABLE_LOAD, 's_buffer_load_dword s26, s[28:31], 0x0', 's_lshl_b32 s6, s26, 5')}, - from_buffer), - ('index read from a buffer into the shifted register', - {SHIFT: (TABLE_LOAD, 's_buffer_load_dword s6, s[28:31], 0x0', SHIFT)}, from_buffer), + ('index read from a buffer at a group-ID offset', + {SHIFT: (TABLE_LOAD, 's_buffer_load_dword s26, s[28:31], s14', 's_lshl_b32 s6, s26, 5')}, from_buffer), + ('index read from a buffer at a group-ID offset into the shifted register', + {SHIFT: (TABLE_LOAD, 's_buffer_load_dword s6, s[28:31], s14', SHIFT)}, from_buffer), ('high word 1', {CLEAR: ('s_mov_b32 s9, 1',)}, high), ('high word a root constant', {CLEAR: ('s_mov_b32 s9, s5',)}, high), ('high word left as the group ID', {CLEAR: ()}, high), diff --git a/tests/startup_gfx2hlsl_heap_word_check.py b/tests/startup_gfx2hlsl_heap_word_check.py new file mode 100644 index 000000000..68578488d --- /dev/null +++ b/tests/startup_gfx2hlsl_heap_word_check.py @@ -0,0 +1,160 @@ +"""A compute program whose resource heap record index is a word it reads from a table buffer. + +usage: startup_gfx2hlsl_heap_word_check.py [--llvm-mc ] + +The program of startup_gfx2hlsl_heap_record_check.py with its index no longer the root constant itself: root constant +word 2 picks the byte offset of a word in the buffer of table byte 96, and that word is the index: + + s_load_dwordx4 s[28:31], s[12:13], 0x60 + s_mulk_i32 s6, 0x150 + s_add_u32 s6, s6, 0x120 + s_buffer_load_dword s6, s[28:31], s6 + s_lshl_b32 s6, s6, 5 + s_load_dwordx4 s[16:19], s[8:9], s6 + +gfx2hlsl.py names that input `srv 1 buf heap word table 1 96 at 288 rootconst 0 2 times 336`: the dispatch reads the +word at byte 288 + 336 * (root constant word 2) of that buffer, then the 32-byte heap record it indexes. The byte +offset is the same for every thread of the dispatch. A literal byte offset, an offset modifier, s_mul_i32 and +s_addk_i32 and a later word of a wider load give the same line with their own numbers; the HLSL and the manifest of +the first form are compared whole. Every other form keeps a refusal: an offset from the group ID, an offset read +from a buffer, a scale or a byte offset that is not a multiple of 4, a register added after the arithmetic, a +modified descriptor, and a branch target between the arithmetic and the load. --llvm-mc reassembles every +instruction used here and compares the words. +""" +import argparse + +import startup_gfx2hlsl_heap_record_check as H +from startup_gfx2hlsl_compute_check import G, assemble, refused + +TABLE = 's_load_dwordx4 s[28:31], s[12:13], 0x60' +SCALE, ADD = 's_mulk_i32 s6, 0x150', 's_add_u32 s6, s6, 0x120' +READ_INDEX = 's_buffer_load_dword s6, s[28:31], s6' +WAIT = 's_waitcnt lgkmcnt(0)' +INDEX = (TABLE, SCALE, ADD, WAIT, READ_INDEX, WAIT, H.SHIFT) +# Every instruction added here, recorded from llvm-mc 15. +ENCODED = { + TABLE: '060708f4600000fa', SCALE: '500106b8', ADD: '06ff068020010000', READ_INDEX: '8e0120f40000000c', + 's_buffer_load_dwordx2 s[26:27], s[28:31], s6': '8e0624f40000000c', 's_lshl_b32 s6, s27, 5': '1b85068f', + 's_buffer_load_dword s6, s[28:31], 0x40': '8e0120f4400000fa', 's_buffer_load_dword s6, s[28:31], s14': '8e0120f40000001c', + 's_mulk_i32 s6, 0x152': '520106b8', 's_add_u32 s6, s6, 0x122': '06ff068022010000', + 's_and_b32 s29, s29, 0xffff': '1dff1d87ffff0000', 's_add_u32 s6, s6, s14': '060e0680', + 's_mul_i32 s6, s6, s5': '06050693', 's_mul_i32 s6, s6, 0x150': '06ff069350010000', 's_addk_i32 s6, 0x120': '200186b7', + 's_buffer_load_dword s6, s[28:31], s6 offset:0x10': '8e0120f41000000c', +} +ALL = {**H.ENCODED, **ENCODED} + +MANIFEST = """\ +x2w-manifest 2 +stage cs +group 2 3 4 +ud 3 +udsrc 0 rootconst 0 0 +udsrc 1 rootconst 0 1 +udsrc 2 rootconst 0 2 +srv 0 buf table 1 96 +srv 1 buf heap word table 1 96 at %s +uav 0 table 1 16 +""" +FORM = '288 rootconst 0 2 times 336' +BINDINGS = """\ +cbuffer entry : register(b0) { uint ud0; uint ud1; uint ud2; }; +ByteAddressBuffer r0 : register(t0); +ByteAddressBuffer r1 : register(t1); +RWByteAddressBuffer u0 : register(u0); +""" +# The heap record program's body with the index read through r0 (the table buffer) and the input through r1. +MAIN = H.MAIN.replace(' s6 = ud2 << (0x00000005u & 31);\n', """\ + s6 = ud2 * 0x00000150u; + s6 = s6 + 0x00000120u; + s6 = r0.Load(s6 + 0); + s6 = s6 << (0x00000005u & 31); +""").replace('v5 = r0.Load(a + 0);', 'v5 = r1.Load(a + 0);') +assert MAIN.count('r0.Load') == 1 and MAIN.count('r1.Load') == 1 + + +def words(index=INDEX): + """The heap record program with the index lines in place of its shift.""" + return b''.join(bytes.fromhex(ALL[line]) for original in H.PROGRAM + for line in (index if original == H.SHIFT else (original,))) + + +WORDS = words() + + +def pipeline(index=INDEX): + return G.ComputePipeline(words(index), H.root_blob(), H.RSRC2, H.GROUP) + + +def replace(old, *new): + assert old in INDEX + return tuple(line for original in INDEX for line in (new if original == old else (original,))) + + +def check_lowering(): + pipe = pipeline() + hlsl = pipe.hlsl_cs() + assert pipe.manifest() == MANIFEST % FORM, pipe.manifest() + assert hlsl.endswith(BINDINGS + MAIN), hlsl[hlsl.index('cbuffer'):] + forms = ( + ('literal byte offset', (TABLE, WAIT, 's_buffer_load_dword s6, s[28:31], 0x40', WAIT, H.SHIFT), '64'), + ('offset modifier', replace(READ_INDEX, 's_buffer_load_dword s6, s[28:31], s6 offset:0x10'), + '304 rootconst 0 2 times 336'), + ('s_mul_i32 and s_addk_i32', replace(ADD, 's_addk_i32 s6, 0x120'), FORM), + ('s_mul_i32 by a literal', replace(SCALE, 's_mul_i32 s6, s6, 0x150'), FORM), + ('second word of a wider load', replace(H.SHIFT, 's_lshl_b32 s6, s27, 5')[:4] + ( + 's_buffer_load_dwordx2 s[26:27], s[28:31], s6', WAIT, 's_lshl_b32 s6, s27, 5'), '292 rootconst 0 2 times 336'), + # A branch target before the arithmetic changes nothing. + ('branch target before the arithmetic', (TABLE,) + H.JUMP + INDEX[1:], FORM), + ) + for name, index, form in forms: + got = pipeline(index).manifest() + assert got == MANIFEST % form, '%s:\n%s' % (name, got) + return len(forms) + + +def check_refusals(): + other = ('s_load of a resource heap record whose index is read from a buffer other than a table buffer at a ' + 'dispatch-constant offset') + controls = ( + ('offset from the group ID', replace(READ_INDEX, 's_buffer_load_dword s6, s[28:31], s14')), + ('offset read from a buffer', replace(READ_INDEX, 's_buffer_load_dword s6, s[28:31], 0x40', WAIT, READ_INDEX)), + ('scale not a multiple of 4', replace(SCALE, 's_mulk_i32 s6, 0x152')), + ('byte offset not a multiple of 4', replace(ADD, 's_add_u32 s6, s6, 0x122')), + ('a register added after the arithmetic', replace(ADD, ADD, 's_add_u32 s6, s6, s14')), + ('scaled by a register', replace(SCALE, 's_mul_i32 s6, s6, s5')), + ('modified descriptor', replace(TABLE, TABLE, WAIT, 's_and_b32 s29, s29, 0xffff')), + ('branch target between the arithmetic and the load', replace(ADD, ADD, *H.JUMP)), + ) + for name, index in controls: + try: + refused(other, lambda: pipeline(index).manifest()) + except AssertionError as error: + raise AssertionError('%s: %s' % (name, error)) from None + # A branch target between the load and the shift ends the word's mark, as for a root constant. + refused('whose offset is not a root constant shifted left by 5', + lambda: pipeline(replace(READ_INDEX, READ_INDEX, *H.JUMP)).manifest()) + # Only a buffer read is named in the manifest; another kind through such a record is refused there. + pipe = pipeline() + key = next(k for k in pipe.resources if k[0][:2] == ('resheap', 'word')) + pipe.resources[key]['kind'] = 'tex2d' + refused("resource through ('resheap', 'word'", pipe.manifest) + return len(controls) + 2 + + +def check_binary(llvm_mc): + for line, encoded in ENCODED.items(): + assert assemble(llvm_mc, line + '\n') == bytes.fromhex(encoded), line + text = [line for original in H.PROGRAM for line in (INDEX if original == H.SHIFT else (original,))] + assert assemble(llvm_mc, '\n'.join(text) + '\n') == WORDS + print('heap word fixture: %d instructions reassembled to the recorded words' % len(ENCODED)) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--llvm-mc') + args = parser.parse_args() + if args.llvm_mc: + check_binary(args.llvm_mc) + forms = check_lowering() + count = check_refusals() + print('startup_gfx2hlsl_heap_word: PASS (manifest and HLSL exact; %d more forms; %d refused controls)' % (forms, count)) diff --git a/tests/startup_stream_consumer.cpp b/tests/startup_stream_consumer.cpp index 1d7afbf74..fa1d9a2b2 100644 --- a/tests/startup_stream_consumer.cpp +++ b/tests/startup_stream_consumer.cpp @@ -163,7 +163,7 @@ static void* desktop_pipeline(void* device) // code-zero, data-zero, no-root, code-unreadable, code-past-end, data-unreadable, state-unreadable, // stateb-unreadable, desc-unreadable // dispatch, dispatch-swapped, dispatch-none, dispatch-sampled, dispatch-sampled-unbound, dispatch-heap, -// dispatch-heap-outside: one creation, then dispatch_slot67 below +// dispatch-heap-outside, dispatch-heap-word*: one creation, then dispatch_slot67 below // texture-store, texture-store-none, texture-store-denied, texture-store-occupied, texture-store-copied: one creation, then texture_slot67 below // The unreadable cases point at a PAGE_NOACCESS page; code-past-end ends the code on the last byte before one. static void* slot67_pipeline; @@ -196,6 +196,10 @@ static void* make_committed(void* device, D3D12_HEAP_TYPE type, const D3D12_RESO // 32-byte heap record that holds the input descriptor (heap byte 64). Heap bytes 0 and 32 hold the output's // descriptor, so an index that is ignored or scaled by 16 names a buffer the dispatch refuses as an input. // dispatch-heap-outside sets the constant to 0x07ffffff, whose record is past any heap. +// dispatch-heap-word runs the program of startup_gfx2hlsl_heap_word_check.py: the constant is 1 and picks the word +// of the upload buffer at table byte 96 that holds the index, 2. dispatch-heap-word-outside makes that word +// 0x07ffffff, dispatch-heap-word-past ends the buffer at that word, and dispatch-heap-word-placed names the placed +// input buffer instead of upload memory. // Controls on the recorded state: dispatch-missing-word leaves out the slot 37 call; dispatch-root-changed sets // another compute root and the first one again after the constants, dispatch-same-root sets the same root again; // dispatch-reset closes and resets the list after the constants; dispatch-wrong-root records under the other @@ -243,7 +247,8 @@ static int dispatch_slot67(void* device, const std::string& mode) if (heap_record) for (const UINT at : {0u, 32u, 64u}) std::memcpy(reinterpret_cast(cpu + at), descriptors[at != 64], sizeof(descriptors[0])); - const UINT constants[3] = {0x01234567, 0x9e3779b9, mode == "dispatch-heap-outside" ? 0x07ffffffu : 2u}; + const bool heap_word = mode.rfind("dispatch-heap-word", 0) == 0; + const UINT constants[3] = {0x01234567, 0x9e3779b9, mode == "dispatch-heap-outside" ? 0x07ffffffu : heap_word ? 1u : 2u}; const UINT graphics[2] = {0xdeadbeef, 0xfeedface}; const auto bind = [&] { invoke(list, 32, 1, word(&heap)); @@ -281,6 +286,20 @@ static int dispatch_slot67(void* device, const std::string& mode) bind(); } if (heap_record) invoke(list, 39, 0, 1, word(&constants[2]), 2); + if (heap_word) { + // The index buffer of table byte 96, in this recording's upload memory (list slot 148). Byte 288 + 336 * 1 + // holds the index, 2; every other word names record 0 or 1, the output's descriptor. + constexpr UINT bytes = 0x400, at = 0x270; + auto* const index = static_cast(reinterpret_cast(invoke(list, 148, bytes, 256))); + if (!index) return 81; + std::memset(index, 0, bytes); + index[0x120 / 4] = index[0x150 / 4] = 1; + index[at / 4] = mode == "dispatch-heap-word-outside" ? 0x07ffffffu : 2u; + const UINT64 address = reinterpret_cast(mode == "dispatch-heap-word-placed" ? buffers[0] : index); + const UINT view[4] = {static_cast(address), static_cast(address >> 32), + mode == "dispatch-heap-word-past" ? at : mode == "dispatch-heap-word-placed" ? words * 4 : bytes, 0}; + std::memcpy(reinterpret_cast(cpu + 96), view, sizeof(view)); + } invoke(list, 35, 1, gpu); if (mode != "dispatch-none") invoke(list, 14, 3, 2, 2); if (FAILED(static_cast(invoke(list, 9)))) return 75; diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 01f2b3c4a..60e9f8be7 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -4646,15 +4646,8 @@ def known(tok): self.scc_effect = 'a lane-mask complement' if self.tracks_uniformity(): self.scc_uniform = False - if (base == 's_lshl_b32' and hasattr(self, 'heap_index') and re.fullmatch(r'0x[0-9a-f]+|[0-9]+', srcs[1]) - and int(srcs[1], 0) == 5): - # index << 5 is the byte offset of a 32-byte resource-heap record. The index is named only when it is a - # root constant word (the dispatch knows it) or a word an s_buffer_load wrote (refused by name). - r = reg_range(srcs[0]) - if syms[0] and syms[0][0] == 'ud' and self.pipe.uds[syms[0][1]][0] == 'rootconst': - self.heap_index[d] = self.pipe.uds[syms[0][1]] - elif r and r[0] == 's' and {**self.heap_index, **self.heap_index_was}.get(r[1]) == ('bufword',): - self.heap_index[d] = ('buffer',) + if hasattr(self, 'heap_index'): + self.mark_heap_index(base, d, srcs, syms) if is_mask: self.masks.add(d) if pair and base != 's_mov_b64': @@ -4663,6 +4656,38 @@ def known(tok): self.set_s(d + 1, self.S(high) if high is not None else '0u', uniform=high_uniform) return None + def heap_word_offset(self, tok, sym): + """(param, word, scale, add) when tok, whose symbol before this instruction is sym, holds root constant word + (param, word) times scale plus add, modulo 2^32 (see mark_heap_index); else None.""" + if sym and sym[0] == 'ud' and self.pipe.uds[sym[1]][0] == 'rootconst': + return self.pipe.uds[sym[1]][1:] + (1, 0) + r = reg_range(tok) + mark = {**self.heap_index, **self.heap_index_was}.get(r[1]) if r and r[0] == 's' and r[1] == r[2] else None + return mark[1:] if mark and mark[0] == 'rc' else None + + def mark_heap_index(self, base, d, srcs, syms): + """Marks of SGPR d for heap_record. index << 5 is the byte offset of a 32-byte resource-heap record; the index + is named when it is a root constant word (the dispatch knows it) or a word an s_buffer_load wrote (see + op_s_buffer_load_dword). A root constant word times a literal plus a literal ('rc') is the byte offset such a + load may read the index word at: the same for every thread of the dispatch.""" + lit = [int(t, 0) & 0xffffffff if re.fullmatch(r'0x[0-9a-f]+|[0-9]+', t) else None for t in srcs] + r = reg_range(srcs[0]) + if base == 's_lshl_b32' and lit[1:] == [5]: + word = {**self.heap_index, **self.heap_index_was}.get(r[1]) if r and r[0] == 's' else None + if syms[0] and syms[0][0] == 'ud' and self.pipe.uds[syms[0][1]][0] == 'rootconst': + self.heap_index[d] = self.pipe.uds[syms[0][1]] + elif word and word[0] == 'bufword': + self.heap_index[d] = ('buffer',) + word[1:] + elif base in ('s_add_u32', 's_add_i32', 's_mul_i32') and len(srcs) == 2: + for i in (0, 1): + k = lit[1 - i] + offset = self.heap_word_offset(srcs[i], syms[i]) if k is not None else None + if offset: + p, w, scale, add = offset + self.heap_index[d] = (('rc', p, w, scale * k & 0xffffffff, add * k & 0xffffffff) if base == 's_mul_i32' + else ('rc', p, w, scale, add + k & 0xffffffff)) + break + def set_exec_scc(self, expr): self.exec_known = False self.scc_effect = 'emitted' @@ -4757,6 +4782,11 @@ def scalar_accumulate(self, base, ops, mods): self.set_s(d, '0x%08xu' % value, ('const', value)) else: self.set_s(d, result) + offset = self.heap_word_offset(ops[0], sym) if hasattr(self, 'heap_index') else None + if offset: + p, w, scale, plus = offset + self.heap_index[d] = ('rc', p, w, scale, plus + imm & 0xffffffff) if add else ( + 'rc', p, w, scale * imm & 0xffffffff, plus * imm & 0xffffffff) self.masks.discard(d) return None @@ -5020,16 +5050,19 @@ def op_s_load_dwordx4(self, ops, mods, count=4): raise Unsupported('s_load with a register offset through %s' % (p[1],)) def heap_record(self, dst, base, token, imm, count): - """s_load_dwordx4 D, , R in a compute program, where R is a root constant word - shifted left by 5 with no later write of R and no branch target in between: D is the buffer descriptor in - the 32-byte heap record that the root constant indexes. The manifest names the root constant; the dispatch - reads the record. Only this exact form is modelled.""" + """s_load_dwordx4 D, , R in a compute program, where R is an index shifted left by 5 + with no later write of R and no branch target in between: D is the buffer descriptor in the 32-byte heap + record that the index names. The index is a root constant word, or a word an s_buffer_load read from an + unmodified table buffer at a literal byte offset or at a root constant word times a literal plus a literal + (the marks, see mark_heap_index, end at a branch target). The manifest names the root constant or where the + word is; the dispatch reads the word and the record. Only these exact forms are modelled.""" what = 's_load of a resource heap record' r = reg_range(token) index = getattr(self, 'heap_index', {}).get(r[1]) if r and r[0] == 's' and r[1] == r[2] else None if index == ('buffer',): - raise Unsupported('%s whose index is read from a buffer' % what) - if not index or index[0] != 'rootconst': + raise Unsupported('%s whose index is read from a buffer other than a table buffer at a dispatch-constant ' + 'offset' % what) + if not index or index[0] not in ('rootconst', 'buffer'): raise Unsupported('%s whose offset is not a root constant shifted left by 5 since the last branch target' % what) if count != 4: raise Unsupported('%s of %d dwords' % (what, count)) @@ -5037,8 +5070,9 @@ def heap_record(self, dst, base, token, imm, count): raise Unsupported('%s with offset:%#x' % (what, imm)) if self.sym.get(base[2]) != ('const', 0): raise Unsupported('%s through a pointer whose high word is not a constant zero' % what) + source = ('resheap',) + index[1:] if index[0] == 'rootconst' else ('resheap', 'word') + index[1:] for i in range(count): - self.sym[dst[1] + i] = ('desc', ('resheap',) + index[1:], 0, i) + self.sym[dst[1] + i] = ('desc', source, 0, i) def op_s_bfm_b32(self, ops, mods): """Fold constant bitfield masks: titles build inline sampler words with them.""" @@ -5262,6 +5296,19 @@ def op_s_buffer_load_dword(self, ops, mods, count=1): if sreg and offset == ('s%d' % sreg[1]) and dst[1] <= sreg[1] < dst[2]: self.emit('a = %s;' % offset) offset = 'a' + # A word read from an unmodified table buffer at a literal offset or at a root constant word times a literal + # plus a literal is the same for the whole dispatch: heap_record names it by (table parameter, table byte, + # root constant parameter and word or None, scale, byte offset). Any other buffer word is only marked. + where = () + if hasattr(self, 'heap_index'): + key, r, sreg = self.descriptor(ops[1]), reg_range(ops[1]), reg_range(token) + first = self.sym.get(r[1]) + at = (None, None, 0, val) if is_lit else self.heap_word_offset( + token, self.sym.get(sreg[1]) if sreg and sreg[0] == 's' else None) + if (at and at[2] % 4 == 0 and (at[3] + extra) % 4 == 0 # a dword-aligned word for any root constant + and first[0] == 'desc' and key[0][0] == 'table' and key not in getattr(self.pipe, 'modified', ()) # probes build a bare pipe + and all(self.sym.get(r[1] + n) == first[:3] + (first[3] + n,) + first[4:] for n in range(4))): + where = key[0][1:] + key[1:] + at[:3] + (at[3] + extra,) # All words use the original offset, even when a destination overwrites its register. uniform = self.tracks_uniformity() and self.uniform_source(token) for i in range(count): @@ -5269,7 +5316,7 @@ def op_s_buffer_load_dword(self, ops, mods, count=1): if is_lit: self.sym[dst[1] + i] = ('fixed_buffer_word',) if hasattr(self, 'heap_index'): - self.heap_index[dst[1] + i] = ('bufword',) + self.heap_index[dst[1] + i] = ('bufword',) + (where[:5] + ((where[5] + 4 * i) & 0xffffffff,) if where else ()) def op_s_buffer_load_dwordx2(self, ops, mods): self.op_s_buffer_load_dword(ops, mods, 2) @@ -9294,6 +9341,11 @@ def manifest(self): where = 'root %d' % source[1] elif source[0] == 'resheap' and len(source) == 3 and r['kind'] == 'buf': where = 'heap rootconst %d %d' % source[1:] # the 32-byte heap record that root constant word indexes + elif source[0] == 'resheap' and source[1] == 'word' and r['kind'] == 'buf': + # The record the word at byte `at` (+ root constant word * `times`) of table buffer indexes. + table, byte, param, word, scale, at = source[2:] + where = 'heap word table %d %d at %d' % (table, byte, at) + ( + '' if param is None else ' rootconst %d %d times %d' % (param, word, scale)) else: raise Unsupported('resource through %s' % (source,)) lines.append('srv %d %s %s' % (r['index'], r['kind'], where)) From 5f27d8cf658cf11ea720fca8149e4f6cce6b7517 Mon Sep 17 00:00:00 2001 From: tedin7 <110300616+tedin7@users.noreply.github.com> Date: Thu, 26 Nov 2026 06:57:37 +0100 Subject: [PATCH 155/240] shader: lower SDWA binary16 add, sub, subrev and mul in gfx2hlsl (#2739) * feat: lower SDWA binary16 add, sub, subrev and mul in gfx2hlsl Part of #1723. Selected-half sources, WORD_0/WORD_1 destination with PAD or PRESERVE; dst_sel DWORD, bytes, clamp and omod stay refused. Extends the f16 alu check and the D3D12 draw check. * fix: tag SDWA binary16 draw words so the float target keeps them A result that fits in 16 bits read back as binary32 zero or subnormal under FXC. Export and expected words are XORed with 0x60000000, checked to stay finite normal floats on every lane. * docs: document binary16 SDWA add, sub, subrev and mul lowering --------- Co-authored-by: R0Y00 --- CMakeLists.txt | 2 +- docs/startup-runtime.md | 11 +- tests/startup_gfx2hlsl_f16_alu_check.py | 76 +++++- tests/startup_gfx2hlsl_f16_alu_draw_check.py | 273 +++++++++++++++++++ tools/startup/gfx2hlsl.py | 57 ++++ 5 files changed, 415 insertions(+), 4 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index e87c5b2f0..89f79d14a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4050,7 +4050,7 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME startup_gfx2hlsl_f16_alu_draw_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_f16_alu_draw_check.py" draw "${DXC_EXECUTABLE}" "$" ${adapter} $<$:${STARTUP_FXC}>) - set_tests_properties(startup_gfx2hlsl_f16_alu_draw_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + set_tests_properties(startup_gfx2hlsl_f16_alu_draw_${adapter} PROPERTIES TIMEOUT 900 SKIP_RETURN_CODE 77) endforeach() # gfx2hlsl v_cmpx_le_i32_sdwa on a sign-extended byte decides which of 16 x 16 pixels survive, checked # pixel by pixel (#1906); translations without the select or without sext() must fail the same draw. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 4ca94467d..84d33ad03 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -2062,9 +2062,18 @@ These are measured on one executable; treat them as hypotheses for others. and the low bits of the result are placed in the destination field, with `UNUSED_PAD` zeroing the others and `UNUSED_PRESERVE` keeping them. The selection helpers match `tools/pixel_aot.py`, which already lowers the same forms. The VOP2 select `v_cndmask_b32_sdwa` lowers the same way, with VCC as - its mask (`startup_gfx2hlsl_sdwa_cndmask`, drawn on WARP and hardware). Float SDWA forms and a + its mask (`startup_gfx2hlsl_sdwa_cndmask`, drawn on WARP and hardware). Most float SDWA forms and a `dst_unused:UNUSED_SEXT` destination still stop translation rather than translating to something inexact. [#1141](https://github.com/R0Y00/Xbox2Windows/issues/1141) + The one float exception is the binary16 arithmetic set `v_add_f16`, `v_sub_f16`, `v_subrev_f16` and + `v_mul_f16` (`_sdwa`). `src0_sel`/`src1_sel` accept `WORD_0`, `WORD_1` or `DWORD` (`DWORD` reads the + low half, as the 16-bit operation does); sources are single VGPRs, with `abs` and `neg`. The result + is rounded once to binary16 and written to `dst_sel:WORD_0` or `WORD_1`, with `UNUSED_PAD` zeroing the + other half (the default) and `UNUSED_PRESERVE` keeping the old one. Refused: `dst_sel:DWORD` and byte + selects, `sext()`, `clamp`, output modifiers, `UNUSED_SEXT`, and non-VGPR sources. Run + `ctest --preset dev --no-tests=error -R "^startup_gfx2hlsl_f16_alu"`: the check covers the accepted and + refused forms, and the draws on WARP and hardware read back every selector and unused mode against a + CPU binary16 reference. The VOPC SDWA compares (`v_cmp_*_sdwa`, `v_cmpx_*_sdwa`) of the existing 32-bit compare table lower too: i32 and u32 sources take their `src0_sel`/`src1_sel` field, sign-extended under `sext()`, and the compare reads the extended value as its type. f32 SDWA compares stay refused (#1920). The diff --git a/tests/startup_gfx2hlsl_f16_alu_check.py b/tests/startup_gfx2hlsl_f16_alu_check.py index f67e20ff6..2cafb0c00 100644 --- a/tests/startup_gfx2hlsl_f16_alu_check.py +++ b/tests/startup_gfx2hlsl_f16_alu_check.py @@ -92,7 +92,7 @@ def run(asm, regs): dst, expr = re.fullmatch(r'(v\d+) = (.*);', s.lines[0]).groups() env = {f'v{i}': v for i, v in enumerate(regs)} env.update( - f16tof32=lambda x: h2f(x), fma16o=fma16o, f16rn=lambda x: 0x7e00 if x != x else f2h(x) if abs(x) < 65520.0 else (0xfc00 if x < 0 else 0x7c00), saturate=lambda x: min(max(x, 0.0), 1.0), + f16tof32=lambda x: h2f(x), fma16o=fma16o, f16rn=lambda x: 0x7e00 if math.isnan(x) else (f2h(x) if abs(x) < 65520.0 else (0xfc00 if x < 0 else 0x7c00)), asuint=lambda x: x, saturate=lambda x: min(max(x, 0.0), 1.0), abs=abs, min=min, max=max, clamp=lambda x, lo, hi: min(max(x, lo), hi), trunc=lambda x: float(int(x)), isnan=math.isnan, asint=lambda x: x - (1 << 32) if x >> 31 else x, float=float, uint=lambda x: int(x) & 0xffffffff, int=int) @@ -134,14 +134,86 @@ def run(asm, regs): ('v_cvt_i16_f16 v3, v0', [f2h(60000.0)], 0x7fff), ('v_cvt_u16_f16 v3, v0', [f2h(2.75) | HIGH], 2), ('v_cvt_u16_f16 v3, v0', [f2h(-1.5)], 0), + # SDWA binary16: a selected half of each source, the result in one half of the destination. v3 holds the old + # value 0x5a5a1234 where the other half is preserved. + ('v_add_f16_sdwa v3, v0, v1 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:WORD_0', + [ONE | HIGH, TWO | HIGH, 0, 0x5a5a1234], THREE), + ('v_add_f16_sdwa v3, v0, v1 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_1 src1_sel:WORD_0', + [0x3c00 << 16 | 0xabcd, TWO, 0, 0x5a5a1234], THREE), + ('v_add_f16_sdwa v3, v0, v1 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:DWORD src1_sel:WORD_1', + [ONE | HIGH, 0x4000 << 16 | 0x1234, 0, 0x5a5a1234], THREE), + ('v_add_f16_sdwa v3, v0, v1 dst_sel:WORD_1 dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:WORD_0', + [ONE | HIGH, TWO | HIGH, 0, 0x5a5a1234], THREE << 16), + ('v_add_f16_sdwa v3, v0, v1 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0 src1_sel:WORD_0', + [ONE | HIGH, TWO | HIGH, 0, 0x5a5a1234], THREE << 16 | 0x1234), + ('v_add_f16_sdwa v3, v0, v1 dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0 src1_sel:WORD_0', + [ONE | HIGH, TWO | HIGH, 0, 0x5a5a1234], 0x5a5a0000 | THREE), + ('v_sub_f16_sdwa v3, v0, v1 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_1 src1_sel:WORD_0', + [THREE << 16, ONE, 0, 0], TWO), + ('v_subrev_f16_sdwa v3, v0, v1 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:WORD_1', + [ONE, THREE << 16, 0, 0], TWO), + ('v_mul_f16_sdwa v3, v0, v1 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_1 src1_sel:WORD_1', + [THREE << 16, TWO << 16, 0, 0], f2h(6.0)), + ('v_add_f16_sdwa v3, -v0, |v1| dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:WORD_0', + [ONE, f2h(-3.0), 0, 0], TWO), + # inf - inf is NaN: the lane keeps a NaN class in the selected half. + ('v_sub_f16_sdwa v3, v0, v1 dst_sel:WORD_1 dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:WORD_0', + [0x7c00, 0x7c00, 0, 0], 0x7e00 << 16), ] for asm, regs, expected in CASES: dst, got = run(asm, regs + [0] * (4 - len(regs))) check(asm + ' ' + str(regs), got == expected, 'got %#x want %#x' % (got, expected)) +# The statement the lowering emits, evaluated over every lane of the SDWA draw fixtures (edge values, NaN, infinity, +# signed zero, denormals, both halves, PAD and PRESERVE) against the exact-rational reference of the draw check. A NaN +# has no portable sign or payload, so both sides compare the NaN class (the draw canonicalises the same way). +sys.path.insert(0, here) +import startup_gfx2hlsl_f16_alu_draw_check as D # noqa: E402 +for cfg, lanes in D.SDWA_DRAW.items(): + op, s0, s1, dsel, unused, m0, m1 = cfg[:7] + asm = '%s_sdwa v3, %s, %s dst_sel:%s dst_unused:%s src0_sel:%s src1_sel:%s' % ( + op, D.sdwa_operand(m0, 0), D.sdwa_operand(m1, 1), dsel, unused, s0, s1) + bad = [(x, D.sdwa_reference(cfg, x), run(asm, [x[0], x[1], 0, x[2]])[1]) for x in lanes] + bad = [(x, want, got) for x, want, got in bad if D.canon_word(got) != want] + check('sdwa %s over %d lanes' % (D.sdwa_name(cfg), len(lanes)), not bad, + ' '.join('%08x,%08x,%08x want %08x got %08x' % (*x, want, got) for x, want, got in bad[:2])) + + +def low16_stage(): + s = stage() + s.low16_only_v, s.pinned_low16_v = {3}, set() # v3 holds a d16 load: its upper half is undefined + return s + + +SDWA = 'v_add_f16_sdwa v3, v0, v1 dst_sel:%s dst_unused:%s src0_sel:%s src1_sel:WORD_0' +for sel, unused, src0, still_low16, label in ( + ('WORD_0', 'UNUSED_PRESERVE', 'WORD_0', True, 'keeping the undefined upper half leaves it undefined'), + ('WORD_1', 'UNUSED_PRESERVE', 'WORD_0', False, 'a WORD_1 write over a defined low half is fully defined'), + ('WORD_0', 'UNUSED_PAD', 'WORD_0', False, 'UNUSED_PAD zeroes the upper half')): + s = low16_stage() + s.one('v_add_f16_sdwa', SDWA % (sel, unused, src0)) + check('SDWA binary16 ' + label, (3 in s.low16_only_v) == still_low16) +try: + low16_stage().one('v_add_f16_sdwa', 'v_add_f16_sdwa v4, v3, v1 dst_sel:WORD_0 dst_unused:UNUSED_PAD ' + 'src0_sel:WORD_1 src1_sel:WORD_0') + check('SDWA binary16 refuses the undefined upper half of a d16 load as a source', False) +except G.Unsupported: + check('SDWA binary16 refuses the undefined upper half of a d16 load as a source', True) check('clamp saturates the binary16 result', run('v_add_f16 v3, v0, v1 clamp', [THREE, TWO, 0, 0])[1] == ONE) for asm in ('v_add_f16 v3, v0, v1 op_sel:[1,0]', 'v_cvt_i16_f16 v3, v0 clamp', 'v_add_f16 v3, v0', - 'v_fmaak_f16 v3, v0, v1', 'v_mul_f16 v3, v0, v1 mul:2'): + 'v_fmaak_f16 v3, v0, v1', 'v_mul_f16 v3, v0, v1 mul:2', + # SDWA binary16: whole-word destination, byte fields, clamp, omod, integer sext and a constant + # source stay refused. + 'v_add_f16_sdwa v3, v0, v1 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:WORD_0', + 'v_add_f16_sdwa v3, v0, v1 dst_sel:BYTE_0 dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:WORD_0', + 'v_add_f16_sdwa v3, v0, v1 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:BYTE_1 src1_sel:WORD_0', + 'v_add_f16_sdwa v3, v0, v1 dst_sel:WORD_0 dst_unused:UNUSED_SEXT src0_sel:WORD_0 src1_sel:WORD_0', + 'v_add_f16_sdwa v3, v0, v1 clamp dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:WORD_0', + 'v_add_f16_sdwa v3, v0, v1 mul:2 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:WORD_0', + 'v_add_f16_sdwa v3, sext(v0), v1 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:WORD_0', + 'v_add_f16_sdwa v3, 1.0, v1 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:WORD_0', + 'v_add_f16_sdwa v3, v0, v1 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0', + 'v_min_f16_sdwa v3, v0, v1 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:WORD_0'): try: stage().one(asm.split()[0], asm) check('refuses ' + asm, False) diff --git a/tests/startup_gfx2hlsl_f16_alu_draw_check.py b/tests/startup_gfx2hlsl_f16_alu_draw_check.py index d19eda21e..b7158b0f6 100644 --- a/tests/startup_gfx2hlsl_f16_alu_draw_check.py +++ b/tests/startup_gfx2hlsl_f16_alu_draw_check.py @@ -301,6 +301,233 @@ def ps_words(op): return PRE_WORDS + BODY_WORDS[op] + POST_WORDS +# ---- SDWA binary16 arithmetic (v_add/sub/subrev/mul_f16_sdwa) ------------------------------------------------------- +# One configuration per draw group: four lanes run the same instruction (src0_sel, src1_sel, dst_sel, dst_unused and +# the abs/neg spelling of the sources) over different words. Lane i reads v and v<4+i>; the old value of the +# destination is the third parameter word, copied into v<12+i> first so that UNUSED_PRESERVE has something to keep. +# Every source word carries a different, non-NaN value in the half that is not selected. +SDWA_BASE = ('WORD_0', 'UNUSED_PAD') +SDWA_CONFIGS = [(op, s0, s1) + SDWA_BASE + ('', '') for op in ('v_add_f16',) for s0 in ('DWORD', 'WORD_0', 'WORD_1') + for s1 in ('DWORD', 'WORD_0', 'WORD_1')] +SDWA_CONFIGS += [('v_add_f16', 'WORD_1', 'WORD_0', d, u, '', '') for d, u in + (('WORD_1', 'UNUSED_PAD'), ('WORD_0', 'UNUSED_PRESERVE'), ('WORD_1', 'UNUSED_PRESERVE'))] +SDWA_CONFIGS += [(op, 'WORD_1', 'WORD_0', 'WORD_1', 'UNUSED_PRESERVE', '', '') + for op in ('v_sub_f16', 'v_subrev_f16', 'v_mul_f16')] +SDWA_CONFIGS += [('v_add_f16', 'WORD_0', 'WORD_1', 'WORD_0', 'UNUSED_PRESERVE', '-', '|'), + ('v_sub_f16', 'WORD_1', 'WORD_0', 'WORD_1', 'UNUSED_PAD', '-|', ''), + ('v_mul_f16', 'WORD_0', 'WORD_0', 'WORD_0', 'UNUSED_PAD', '|', '-')] +# Edge values of binary16 (zeros of both signs, the smallest and largest denormal, the smallest normal, the largest +# finite value, infinities, quiet and signalling NaN, a NaN with payload) and the roundings that matter. +EDGE_PAIRS = [(0x0000, 0x0000), (0x8000, 0x8000), (0x8000, 0x0000), (0x0001, 0x0001), (0x03ff, 0x0001), + (0x7bff, 0x7bff), (0x0000, 0x7c00), (0xfbff, 0xfbff), (0x7c00, 0x7c00), (0x7c00, 0xfc00), + (0x7e00, 0x3c00), (0x3c00, 0x7c01), (0x7fff, 0x7fff), (0x3c00, 0x1000), (0x3c01, 0x1000), + (0x0400, 0x8001)] +SDWA_EDGE_CONFIGS = [(op, 'WORD_1', 'WORD_0', 'WORD_1', 'UNUSED_PRESERVE', '', '') + for op in ('v_add_f16', 'v_sub_f16', 'v_subrev_f16', 'v_mul_f16')] +GARBAGE = (0xabcd, 0x5a5a, 0xdead, 0x1234) +OLD = (0x5a5a1234, 0xdead5678, 0x1234abcd, 0x2bcd3456) +NAN_HALF = 0x7e00 +# The target is a float format: a result that fits in 16 bits reads back as binary32 zero or a subnormal and FXC drops it. +# Both the drawn word and the expected word are XORed with a tag that keeps every lane a finite normal float (0x3f800000 would turn some 0x4000-class upper halves into infinity or NaN; the control below checks every lane). +SDWA_TAG = 0x60000000 + + +def sdwa_place(value, selection, lane, salt): + """A register word holding value in the selected half and a different non-NaN value in the other.""" + other = GARBAGE[(lane + salt) % 4] + return (value << 16) | other if selection == 'WORD_1' else (other << 16) | value + + +def sdwa_lanes(cfg, pairs): + _op, s0, s1 = cfg[:3] + return [(sdwa_place(a, s0, i, 0), sdwa_place(b, s1, i, 1), OLD[i % 4]) for i, (a, b) in enumerate(pairs)] + + +SDWA_DRAW = {} +for _k, _cfg in enumerate(SDWA_CONFIGS): + SDWA_DRAW[_cfg] = sdwa_lanes(_cfg, [ARITH[(_i + _k) % 8] for _i in range(4)]) +for _cfg in SDWA_EDGE_CONFIGS: + SDWA_DRAW[_cfg + ('edge',)] = sdwa_lanes(_cfg, EDGE_PAIRS) + + +def sdwa_name(cfg): + return '_'.join(p.lower().replace('unused_', '') for p in cfg[:5]) + ''.join( + '_' + {'-': 'neg', '|': 'abs', '-|': 'negabs', '': 'plain'}[m] for m in cfg[5:7]) + ( + '_edge' if len(cfg) > 7 else '') + + +def sdwa_operand(modifier, reg): + return {'': 'v%d', '-': '-v%d', '|': '|v%d|', '-|': '-|v%d|'}[modifier] % reg + + +def sdwa_body_source(cfg): + op, s0, s1, dsel, unused, m0, m1 = cfg[:7] + lines = [] + for lane in range(4): + dst = 12 + lane + lines.append('v_mov_b32 v%d, v%d\n' % (dst, 8 + lane)) + lines.append('%s_sdwa v%d, %s, %s dst_sel:%s dst_unused:%s src0_sel:%s src1_sel:%s\n' % ( + op, dst, sdwa_operand(m0, lane), sdwa_operand(m1, 4 + lane), dsel, unused, s0, s1)) + return ''.join(lines) + + +def half_special(op, a, b): + """Reference binary16 result word of a op b over words, from exact rationals and the IEEE special cases.""" + def nan(x): + return (x & 0x7fff) > 0x7c00 + + def inf(x): + return (x & 0x7fff) == 0x7c00 + if op == 'v_subrev_f16': + op, a, b = 'v_sub_f16', b, a + if op == 'v_sub_f16': + op, b = 'v_add_f16', b ^ 0x8000 + if nan(a) or nan(b): + return NAN_HALF + sign_a, sign_b = a & 0x8000, b & 0x8000 + if op == 'v_mul_f16': + if (inf(a) and (b & 0x7fff) == 0) or (inf(b) and (a & 0x7fff) == 0): + return NAN_HALF + if inf(a) or inf(b): + return 0x7c00 | (sign_a ^ sign_b) + value = exact(a) * exact(b) + return round_half(value) if value else (sign_a ^ sign_b) + if inf(a) and inf(b): + return NAN_HALF if sign_a != sign_b else a + if inf(a) or inf(b): + return a if inf(a) else b + value = exact(a) + exact(b) + if value == 0: + return 0x8000 if (a & 0x7fff) == 0 and (b & 0x7fff) == 0 and sign_a and sign_b else 0 + return round_half(value) + + +def sdwa_half_of(word, selection, modifier): + half = word >> 16 if selection == 'WORD_1' else word & 0xffff + if 'abs' in modifier or '|' in modifier: + half &= 0x7fff + if modifier.startswith('-'): + half ^= 0x8000 + return half + + +def sdwa_reference(cfg, lane, selection_swap=False, keep_swap=False, half_swap=False): + """Expected register word. The three flags build the deliberately wrong readings of the control mutants.""" + op, s0, s1, dsel, unused, m0, m1 = cfg[:7] + w0, w1, old = lane + if selection_swap: + s0, s1 = ('WORD_0' if sel == 'WORD_1' else 'WORD_1' for sel in (s0, s1)) + result = half_special(op, sdwa_half_of(w0, s0, m0), sdwa_half_of(w1, s1, m1)) + if half_swap: + dsel = 'WORD_0' if dsel == 'WORD_1' else 'WORD_1' + if keep_swap: + unused = 'UNUSED_PAD' if unused == 'UNUSED_PRESERVE' else 'UNUSED_PRESERVE' + shift = 16 if dsel == 'WORD_1' else 0 + kept = (old & ~(0xffff << shift)) & 0xffffffff if unused == 'UNUSED_PRESERVE' else 0 + return canon_word(kept | (result << shift)) + + +def canon_half(h): + return NAN_HALF if (h & 0x7fff) > 0x7c00 else h + + +def canon_word(word): + return canon_half(word & 0xffff) | (canon_half(word >> 16) << 16) + + +# A NaN carries no portable sign or payload, so the drawn pair canonicalises every NaN half to 0x7e00 on both sides. +NAN_HLSL = ('uint nanh(uint h) { return (h & 0x7fffu) > 0x7c00u ? 0x7e00u : h; }\n' + 'uint nanc(uint w) { return nanh(w & 0xffffu) | (nanh(w >> 16u) << 16u); }\n') + + +def sdwa_draw_text(cfg): + text = G.Pipeline(vs_words([(0, 0, 0)] * 4), sdwa_ps_words(cfg), root_blob()).hlsl_ps() + return NAN_HLSL + re.sub(r'F\(v(1[2-5])\)', r'F(nanc(v\1) ^ 0x%xu)' % SDWA_TAG, text) + + +# Recorded llvm-mc (gfx1013) encodings of sdwa_body_source(cfg), by configuration name; `binary ` compares. +SDWA_BODY_WORDS = { + 'v_add_f16_dword_dword_word_0_pad_plain_plain': bytes.fromhex( + '0803187ef90818640004060609031a7ef90a1a64010406060a031c7ef90c1c64020406060b031e7ef90e1e6403040606'), + 'v_add_f16_dword_word_0_word_0_pad_plain_plain': bytes.fromhex( + '0803187ef90818640004060409031a7ef90a1a64010406040a031c7ef90c1c64020406040b031e7ef90e1e6403040604'), + 'v_add_f16_dword_word_1_word_0_pad_plain_plain': bytes.fromhex( + '0803187ef90818640004060509031a7ef90a1a64010406050a031c7ef90c1c64020406050b031e7ef90e1e6403040605'), + 'v_add_f16_word_0_dword_word_0_pad_plain_plain': bytes.fromhex( + '0803187ef90818640004040609031a7ef90a1a64010404060a031c7ef90c1c64020404060b031e7ef90e1e6403040406'), + 'v_add_f16_word_0_word_0_word_0_pad_plain_plain': bytes.fromhex( + '0803187ef90818640004040409031a7ef90a1a64010404040a031c7ef90c1c64020404040b031e7ef90e1e6403040404'), + 'v_add_f16_word_0_word_1_word_0_pad_plain_plain': bytes.fromhex( + '0803187ef90818640004040509031a7ef90a1a64010404050a031c7ef90c1c64020404050b031e7ef90e1e6403040405'), + 'v_add_f16_word_1_dword_word_0_pad_plain_plain': bytes.fromhex( + '0803187ef90818640004050609031a7ef90a1a64010405060a031c7ef90c1c64020405060b031e7ef90e1e6403040506'), + 'v_add_f16_word_1_word_0_word_0_pad_plain_plain': bytes.fromhex( + '0803187ef90818640004050409031a7ef90a1a64010405040a031c7ef90c1c64020405040b031e7ef90e1e6403040504'), + 'v_add_f16_word_1_word_1_word_0_pad_plain_plain': bytes.fromhex( + '0803187ef90818640004050509031a7ef90a1a64010405050a031c7ef90c1c64020405050b031e7ef90e1e6403040505'), + 'v_add_f16_word_1_word_0_word_1_pad_plain_plain': bytes.fromhex( + '0803187ef90818640005050409031a7ef90a1a64010505040a031c7ef90c1c64020505040b031e7ef90e1e6403050504'), + 'v_add_f16_word_1_word_0_word_0_preserve_plain_plain': bytes.fromhex( + '0803187ef90818640014050409031a7ef90a1a64011405040a031c7ef90c1c64021405040b031e7ef90e1e6403140504'), + 'v_add_f16_word_1_word_0_word_1_preserve_plain_plain': bytes.fromhex( + '0803187ef90818640015050409031a7ef90a1a64011505040a031c7ef90c1c64021505040b031e7ef90e1e6403150504'), + 'v_sub_f16_word_1_word_0_word_1_preserve_plain_plain': bytes.fromhex( + '0803187ef90818660015050409031a7ef90a1a66011505040a031c7ef90c1c66021505040b031e7ef90e1e6603150504'), + 'v_subrev_f16_word_1_word_0_word_1_preserve_plain_plain': bytes.fromhex( + '0803187ef90818680015050409031a7ef90a1a68011505040a031c7ef90c1c68021505040b031e7ef90e1e6803150504'), + 'v_mul_f16_word_1_word_0_word_1_preserve_plain_plain': bytes.fromhex( + '0803187ef908186a0015050409031a7ef90a1a6a011505040a031c7ef90c1c6a021505040b031e7ef90e1e6a03150504'), + 'v_add_f16_word_0_word_1_word_0_preserve_neg_abs': bytes.fromhex( + '0803187ef90818640014142509031a7ef90a1a64011414250a031c7ef90c1c64021414250b031e7ef90e1e6403141425'), + 'v_sub_f16_word_1_word_0_word_1_pad_negabs_plain': bytes.fromhex( + '0803187ef90818660005350409031a7ef90a1a66010535040a031c7ef90c1c66020535040b031e7ef90e1e6603053504'), + 'v_mul_f16_word_0_word_0_word_0_pad_abs_neg': bytes.fromhex( + '0803187ef908186a0004241409031a7ef90a1a6a010424140a031c7ef90c1c6a020424140b031e7ef90e1e6a03042414'), + 'v_add_f16_word_1_word_0_word_1_preserve_plain_plain_edge': bytes.fromhex( + '0803187ef90818640015050409031a7ef90a1a64011505040a031c7ef90c1c64021505040b031e7ef90e1e6403150504'), + 'v_sub_f16_word_1_word_0_word_1_preserve_plain_plain_edge': bytes.fromhex( + '0803187ef90818660015050409031a7ef90a1a66011505040a031c7ef90c1c66021505040b031e7ef90e1e6603150504'), + 'v_subrev_f16_word_1_word_0_word_1_preserve_plain_plain_edge': bytes.fromhex( + '0803187ef90818680015050409031a7ef90a1a68011505040a031c7ef90c1c68021505040b031e7ef90e1e6803150504'), + 'v_mul_f16_word_1_word_0_word_1_preserve_plain_plain_edge': bytes.fromhex( + '0803187ef908186a0015050409031a7ef90a1a6a011505040a031c7ef90c1c6a021505040b031e7ef90e1e6a03150504'), +} + + +def sdwa_ps_words(cfg): + return PRE_WORDS + SDWA_BODY_WORDS[sdwa_name(cfg)] + POST_WORDS + + +def sdwa_controls(check): + check('sdwa model: 1 + 2 = 3', half_special('v_add_f16', F['1'], F['2']) == F['3']) + check('sdwa model: -0 + -0 is -0, -0 + +0 is +0, x - x is +0', + (half_special('v_add_f16', 0x8000, 0x8000), half_special('v_add_f16', 0x8000, 0), + half_special('v_sub_f16', F['1'], F['1'])) == (0x8000, 0, 0)) + check('sdwa model: inf - inf, 0 * inf and NaN input give the NaN class', + (half_special('v_sub_f16', 0x7c00, 0x7c00), half_special('v_mul_f16', 0, 0x7c00), + half_special('v_add_f16', 0x7c01, F['1'])) == (NAN_HALF,) * 3) + check('sdwa model: 65504 + 65504 overflows to inf; the smallest denormal survives an add of zero', + (half_special('v_add_f16', 0x7bff, 0x7bff), half_special('v_add_f16', 0x0001, 0)) == (0x7c00, 0x0001)) + check('sdwa model: ties to even (1 + 2^-11 stays, 1.0009765625 + 2^-11 rounds up)', + (half_special('v_add_f16', 0x3c00, 0x1000), half_special('v_add_f16', 0x3c01, 0x1000)) == (0x3c00, 0x3c02)) + check('sdwa model: the smallest denormals add and a mixed product underflows to a signed zero', + (half_special('v_add_f16', 0x0001, 0x0001), half_special('v_mul_f16', 0x0001, 0x8001)) == (0x0002, 0x8000)) + for cfg, lanes in SDWA_DRAW.items(): + name = sdwa_name(cfg) + check('sdwa %s: four or sixteen lanes in groups of four' % name, len(lanes) % 4 == 0 and len(lanes) >= 4) + refs = [sdwa_reference(cfg, x) for x in lanes] + check('sdwa %s: every tagged word is a normal finite binary32' % name, + all(0 < ((r ^ SDWA_TAG) >> 23) & 0xff < 0xff for r in refs)) + # A wrong lowering must change at least one lane of this configuration (the value-is-wrong control). + for label, flags in (('the other half of the sources', {'selection_swap': True}), + ('the other destination half', {'half_swap': True}), + ('preserve and pad exchanged', {'keep_swap': True})): + detected = any(sdwa_reference(cfg, x, **flags) != r for x, r in zip(lanes, refs)) + check('sdwa %s: control "%s" detects a wrong lowering' % (name, label), detected) + check('sdwa draw: every configuration has an assembled body', + all(sdwa_name(cfg) in SDWA_BODY_WORDS for cfg in SDWA_DRAW) or not SDWA_BODY_WORDS) + + def reference(op, x, lane=0): if op in PK_KEYS: return pk_reference(op, x, lane) @@ -368,6 +595,17 @@ def check(label, ok): continue check('%s: translates to four lane results' % op, all(('v%d = ' % r) in text for r in range(12, 16))) + sdwa_controls(check) + for cfg in SDWA_DRAW: + try: + text = sdwa_draw_text(cfg) + except G.Unsupported as e: + check('sdwa %s: translates (%s)' % (sdwa_name(cfg), e), False) + continue + check('sdwa %s: the four exports carry the float-target tag' % sdwa_name(cfg), + text.count('^ 0x%xu' % SDWA_TAG) == 4) + check('sdwa %s: translates to four lane results' % sdwa_name(cfg), + all(('v%d = ' % r) in text for r in range(12, 16))) if failures: raise SystemExit('FAILED: ' + ', '.join(failures)) @@ -381,6 +619,14 @@ def check_binary(llvm_mc): for i in range(0, 8, 4): if assemble(llvm_mc, vs_source(DRAW[op][i:i + 4])) != vs_words(DRAW[op][i:i + 4]): raise AssertionError('vertex fixture for %s differs from llvm-mc' % op) + for cfg in SDWA_DRAW: + built = assemble(llvm_mc, sdwa_body_source(cfg)) + if built != SDWA_BODY_WORDS[sdwa_name(cfg)]: + raise AssertionError('%s: assembled %s, recorded %s' % (sdwa_name(cfg), built.hex(), + SDWA_BODY_WORDS[sdwa_name(cfg)].hex())) + for i in range(0, len(SDWA_DRAW[cfg]), 4): + if assemble(llvm_mc, vs_source(SDWA_DRAW[cfg][i:i + 4])) != vs_words(SDWA_DRAW[cfg][i:i + 4]): + raise AssertionError('vertex fixture for %s differs from llvm-mc' % sdwa_name(cfg)) print('fixture words match llvm-mc') @@ -410,6 +656,33 @@ def check_draw(dxc, renderer, adapter, fxc=None): flush=True) continue print('%s %s set %d: %s' % (kind, op, index // 4, expected), flush=True) + for cfg, lanes in SDWA_DRAW.items(): + name = sdwa_name(cfg) + ps = compile_hlsl(compiler, kind, sdwa_draw_text(cfg), 'ps_sdwa_%s_%s' % (name, kind), ps_profile, + directory) + for index in range(0, len(lanes), 4): + chunk = lanes[index:index + 4] + vs = compile_hlsl(compiler, kind, + G.Pipeline(vs_words(chunk), sdwa_ps_words(cfg), root_blob()).hlsl_vs(), + 'vs_sdwa_%s_%d_%s' % (name, index, kind), vs_profile, directory) + expected = words_text(sdwa_reference(cfg, x) ^ SDWA_TAG for x in chunk) + run = draw(renderer, adapter, vs, ps, expected) + if run.returncode: + failures.append('%s sdwa %s set %d' % (kind, name, index // 4)) + print('%s sdwa %s set %d MISMATCH inputs %s\n%s' % (kind, name, index // 4, chunk, + run.stderr.strip()), flush=True) + continue + print('%s sdwa %s set %d: %s' % (kind, name, index // 4, expected), flush=True) + # Wrong-value control: a drawn word that differs by one bit must be reported as a mismatch. + cfg = SDWA_CONFIGS[0] + chunk = SDWA_DRAW[cfg][:4] + ps = compile_hlsl(compiler, kind, sdwa_draw_text(cfg), 'ps_sdwa_control_%s' % kind, ps_profile, directory) + vs = compile_hlsl(compiler, kind, G.Pipeline(vs_words(chunk), sdwa_ps_words(cfg), root_blob()).hlsl_vs(), + 'vs_sdwa_control_%s' % kind, vs_profile, directory) + wrong = [sdwa_reference(cfg, x) ^ SDWA_TAG for x in chunk] + wrong[0] ^= 0x10000 + if not draw(renderer, adapter, vs, ps, words_text(wrong)).returncode: + failures.append('%s sdwa wrong-value control was accepted' % kind) if failures: raise AssertionError('draw mismatches: ' + ', '.join(failures)) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 60e9f8be7..90f86b692 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -4224,7 +4224,64 @@ def half_alu(self, base, ops, mods): # v_mov_b32 is the same path with the selected source as its result, v_cndmask_b32 selects with VCC, # VEC_U_TO_F conversions apply output modifiers before dst_sel, VEC_F forms stay refused, and # dst_unused UNUSED_SEXT has no lowering. + def sdwa_half(self, base, ops, mods): + """SDWA binary16 add, sub, subrev and mul: a selected half of each source, one rounding, one half written back. + + Sources: src0_sel/src1_sel WORD_0 or WORD_1 pick the half; DWORD reads the low half, as the 16-bit + operation does. Destination: dst_sel WORD_0 or WORD_1 with dst_unused UNUSED_PAD (other half zero) or + UNUSED_PRESERVE (other half of the old register kept). dst_sel DWORD stays refused: the upper half of a + 16-bit result is not claimed (an open question, see the low-16-only contract), and a byte selection, sext(), + clamp and the output modifiers have no lowering here. Sources are VGPRs with the abs/neg modifiers. + """ + _arity, _kind, text, _result = VEC_H[base] + fields = {} + for m in mods: + key, _, value = m.partition(':') + if key in ('src0_sel', 'src1_sel', 'dst_sel', 'dst_unused') and value and key not in fields: + fields[key] = value + else: + raise Unsupported('%s SDWA with modifier %s' % (base, m)) + if len(ops) != 3: + raise Unsupported('%s SDWA with %d operands, expected 3' % (base, len(ops))) + args = [] + for index in range(2): + selection = fields.get('src%d_sel' % index) + if selection not in ('DWORD', 'WORD_0', 'WORD_1'): + raise Unsupported('%s SDWA src%d_sel %s' % (base, index, selection)) + neg, token = self.split_neg(ops[1 + index]) + absolute = False + while True: + if token.startswith('|') and token.endswith('|') and len(token) > 2: + token = token[1:-1] + elif token.startswith('abs(') and token.endswith(')'): + token = token[len('abs('):-1] + else: + break + absolute = True + reg = reg_range(token) + if not reg or reg[0] != 'v' or reg[1] != reg[2]: + raise Unsupported('%s SDWA source %s: expected a single VGPR' % (base, ops[1 + index])) + word = self.u(token, low16_only=selection != 'WORD_1') + half = '(%s >> 16u)' % word if selection == 'WORD_1' else '(%s & 0xffffu)' % word + value = 'f16tof32(%s)' % half + if absolute: + value = 'abs(%s)' % value + args.append('(-%s)' % value if neg else value) + select = fields.get('dst_sel') + unused = fields.get('dst_unused', 'UNUSED_PAD') + if select not in ('WORD_0', 'WORD_1'): + raise Unsupported('%s SDWA dst_sel %s' % (base, select)) + if unused not in ('UNUSED_PAD', 'UNUSED_PRESERVE'): + raise Unsupported('%s SDWA dst_unused %s' % (base, unused)) + destination = reg_range(ops[0])[1] + result = '(f16rn(%s))' % text.format(*args) + # Keeping the old high half of a register whose high half is undefined leaves it undefined. + keep_low16 = select == 'WORD_0' and unused == 'UNUSED_PRESERVE' and destination in self.low16_only_v + self.set_v(destination, sdwa_dest(result, select, unused, 'v%d' % destination), low16_only=keep_low16) + def sdwa(self, base, ops, mods): + if base in ('v_add_f16', 'v_sub_f16', 'v_subrev_f16', 'v_mul_f16'): + return self.sdwa_half(base, ops, mods) if base in ('v_cvt_off_f32_i4', *VOP3_ONLY_VEC_U): raise Unsupported('SDWA form of %s' % base) fields = {} From 6f696d48a020fa47440c50ce68914509a0bc2f19 Mon Sep 17 00:00:00 2001 From: brainbudt <32467201+brainbudt@users.noreply.github.com> Date: Thu, 26 Nov 2026 07:02:03 +0100 Subject: [PATCH 156/240] shader: lower two disjoint LDS dword fills before a compute barrier (#2751) --- CMakeLists.txt | 2 +- docs/experiments.md | 14 +++++++-- tests/startup_gfx2hlsl_compute_check.py | 39 +++++++++++++++++++++++-- tools/startup/gfx2hlsl.py | 34 ++++++++++++++------- 4 files changed, 71 insertions(+), 18 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 89f79d14a..49bbec1d4 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4195,7 +4195,7 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_compute_check.py" control mbcnt "${DXC_EXECUTABLE}" "$" ${adapter}) set_tests_properties(startup_gfx2hlsl_compute_mbcnt_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) - foreach(control IN ITEMS swapped-axes dropped-store b-offset c-unpredicated f-peer f-broadcast g-swapped-offsets g-overlap + foreach(control IN ITEMS swapped-axes dropped-store b-offset c-unpredicated f-peer f-broadcast f-second-fill g-swapped-offsets g-overlap j-scalar-dropped h-inner-unpredicated k-block-entered m-else-unswitched n-unmasked o-mask-kept n-dropped-broadcast) add_test(NAME startup_gfx2hlsl_compute_${control}_${adapter} COMMAND "${INTAKE_PYTHON}" -B diff --git a/docs/experiments.md b/docs/experiments.md index e69fadc8f..cf03ec27e 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15700,8 +15700,16 @@ and produces a predictable wrong word. A second control swaps the two offsets. The RDNA 2 ISA describes a single access when the offsets coincide. This slice requires distinct offsets. [AMD RDNA 2 ISA, §10.4, LDS Access](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) -The startup translator accepts one straight-line, full-EXEC fill in a 1D -group, one group barrier, and reads from that initialized span. The fill +Case F-two-fills adds a second consecutive `ds_write_b32` using the same +address VGPR and a disjoint byte range. It writes `4 * X` at byte +`320 + 4 * X`. After the barrier, the peer read uses the first bank and +the broadcast reads 148 from the second bank. On WARP all 320 words matched. +Writing zero in the second store changed 128 words, first at word 1 (148 to +zero). The host check rejects a missing second store and a read in the gap. + +The startup translator accepts one straight-line, full-EXEC fill or two such +consecutive dword fills in a 1D group, one group barrier, and reads whose +individual accesses fit entirely inside an initialized span. The dword fill address is the entry X ID shifted left by two. Read addresses come from an immediately preceding literal move or AND with an aligned literal mask. The bounds check includes the instruction's byte offset. The LDS allocation @@ -15712,7 +15720,7 @@ the 32 KiB groupshared limit. The barrier becomes an unconditional and [HLSL group barrier](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/groupmemorybarrierwithgroupsync). ```powershell -ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_compute_(controls|(f-peer_|f-broadcast_|g-swapped-offsets_|g-overlap_)?(warp|hardware))$' -V +ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_compute_(controls|(f-peer_|f-broadcast_|f-second-fill_|g-swapped-offsets_|g-overlap_)?(warp|hardware))$' -V python -B tests/startup_gfx2hlsl_compute_check.py binary llvm-mc-15 ``` diff --git a/tests/startup_gfx2hlsl_compute_check.py b/tests/startup_gfx2hlsl_compute_check.py index 7bc8f20a1..ba9ccb498 100644 --- a/tests/startup_gfx2hlsl_compute_check.py +++ b/tests/startup_gfx2hlsl_compute_check.py @@ -414,6 +414,15 @@ def saveexec_fixture(): '7fc08cbf00008abfff08103a80000000ff101036fc0000001000d8d8080000067fc08cbf8002107e' 'a400d8d8080000077fc08cbf0786158f1500124a83121234001074e009060480000081bf') +# Case F-two-fills keeps the first bank and writes each lane's byte address to a second bank. +# Broadcast lane 37 from the second bank while the peer read still addresses the first. +SOURCE_F2 = SOURCE_F.replace('ds_write_b32 v4, v5 offset:16', + 'ds_write_b32 v4, v5 offset:16\nds_write_b32 v4, v4 offset:320').replace( + 'v8 offset:164', 'v8 offset:468') +WORDS_F2 = WORDS_F.replace(bytes.fromhex('100034d804050000'), + bytes.fromhex('100034d804050000400134d804040000')).replace( + bytes.fromhex('a400d8d808000007'), bytes.fromhex('d401d8d808000007')) + SOURCE_G = """\ s_mov_b32 s10, s6 s_mov_b32 s11, 0 @@ -521,6 +530,7 @@ def saveexec_fixture(): 'D-wrap': (SOURCE_D_WRAP, WORDS_D_WRAP, USER7 | TGID_X | tidig(3), (4, 2, 4), (2, 1, 1)), 'E': (*saveexec_fixture(), USER7 | TGID_X | tidig(1), (1, 1, 1), (4, 1, 1)), 'F': (SOURCE_F, WORDS_F, USER7 | TGID_X | (1 << 15), (64, 1, 1), (2, 1, 1)), + 'F-two-fills': (SOURCE_F2, WORDS_F2, USER7 | TGID_X | (2 << 15), (64, 1, 1), (2, 1, 1)), 'J': (SOURCE_J, WORDS_J, USER7 | TGID_X | tidig(1), (8, 1, 1), (4, 1, 1)), 'H': (SOURCE_H, WORDS_H, USER7 | TGID_X | tidig(1), (8, 1, 1), (4, 1, 1)), 'M': (SOURCE_M, WORDS_M, USER7 | TGID_X | tidig(1), (8, 1, 1), (4, 1, 1)), @@ -747,11 +757,12 @@ def expected(name): index = 2 * (64 * group + lane) out[index:index + 2] = [stored[base + first], stored[base + second]] return out - if name == 'F': + if name in ('F', 'F-two-fills'): for group in range(2): for lane in range(64): index = (64 * group + lane) * 2 - out[index:index + 2] = [256 * group + (lane ^ 32), 256 * group + 37] + broadcast = 4 * 37 if name == 'F-two-fills' else 256 * group + 37 + out[index:index + 2] = [256 * group + (lane ^ 32), broadcast] return out if name == 'E': # Group IDs 0..3 encode (old EXEC, S0) = (0,0), (0,1), (1,0), (1,1). @@ -926,7 +937,7 @@ def check_lds(): ('82000834', '00cb087e82000834', 'unchanged entry local X'), # v_swap also writes its second operand ('82000834', '82020834', 'one bounded dword'), # use Y instead of X (store, '040134d804050000', 'one bounded dword'), # last lane exceeds the 512-byte allocation - (store, store + store, 'one bounded dword'), # overlapping fill + (store, store + store, 'disjoint'), # overlapping fill (wait + barrier, nop + barrier, 'completed fill'), (barrier, '01008abf', 'one barrier'), # nonzero reserved immediate (barrier, nop, 'after the fill barrier'), @@ -953,6 +964,26 @@ def check_lds(): assert 'lds[(v4 + 256u) >> 2] = v5;' in translate('F', code=at_end).hlsl_cs() assert 'groupshared uint lds[8192];' in translate('F', rsrc2=base | 64 << 15).hlsl_cs() + second = '400134d804040000' + second_read = 'd401d8d808000007' + hlsl = translate('F-two-fills').hlsl_cs() + assert hlsl.index('lds[(v4 + 320u) >> 2] = v4;') < hlsl.index(sync) < hlsl.index('v7 = lds[') + reversed_fills = patch(WORDS_F2, store + second, second + store) + assert 'v7 = lds[(v8 + 468u) >> 2];' in translate('F-two-fills', code=reversed_fills).hlsl_cs() + for old, new, reason in ( + (second, '', 'initialized span'), # omit the second fill + (second, '0c0134d804040000', 'disjoint'), # final word of the first bank + (second_read, '1001d8d808000007', 'initialized span'), # first word in the gap + (second, '040334d804040000', 'bounded'), # last lane exceeds allocation + (second, '400134d805040000', 'address'), # unproven address VGPR + (second, '400136d804040000', 'optional byte offset'), # GDS + (second, '400135d804040000', 'reserved bit'), # hidden encoding bit + (second, '400134d804040100', 'unused operand field'), # unused DATA1 + (second, second + '800234d804040000', 'two'), # third fill + (second, nop + second, 'bounded'), # address proof no longer adjacent + ): + refused(reason, lambda: translate('F-two-fills', code=patch(WORDS_F2, old, new))) + pair = '0524dcd806000006' # The first result overwrites v6. Both loads must use the address saved before that write. body = translate('G').hlsl_cs() @@ -1688,6 +1719,7 @@ def check_binary(llvm_mc): 'd-hi': ('D', 'v9 = v8;', f'v9 = v8 + {MBCNT_COUNT};'), 'd-exec': ('D', 'if (exec & 1) v10 =', 'v10 ='), 'f-peer': ('F', '0x00000080u ^ v4', 'v4'), + 'f-second-fill': ('F-two-fills', 'lds[(v4 + 320u) >> 2] = v4;', 'lds[(v4 + 320u) >> 2] = 0u;'), 'f-broadcast': ('F', 'lds[(v8 + 164u) >> 2]', 'lds[(v8 + 160u) >> 2]'), 'j-scalar-dropped': ('J', ' s22 = s7 * ud1;\n', ''), 'h-inner-unpredicated': ('H', 'if (exec & 1) u0.Store(a, v5);', 'u0.Store(a, v5);'), @@ -1706,6 +1738,7 @@ def check_binary(llvm_mc): # First bad word for controls with a pinned mismatch. CONTROL_MISMATCH = { + 'f-second-fill': 'word=1 expected=00000094 actual=00000000', 'd-mask': 'word=8 expected=00000008 actual=00000009', 'd-whole-mask': 'word=0 expected=00000007 actual=00000011', 'd-x-only': 'word=16 expected=00000009 actual=00000007', diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 90f86b692..f03e0eceb 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -1314,7 +1314,7 @@ def lds_byte_offsets(name, mods): def check_lds_exchange(ins, group, words): - """Prove one race-free 32/64/128-bit fill of a contiguous LDS span, one uniform barrier, then mixed-width reads of initialized dwords. + """Prove a race-free LDS fill (or two disjoint dword fills), one uniform barrier, then reads of initialized dwords. RDNA 2 ISA (Ch. 9 DS): ds_write_b32 / ds_read_b32 / ds_read2_b32 access 4-byte dwords, ds_write_b64 / ds_read_b64 access two contiguous little-endian dwords (v[n] at addr+offset, v[n+1] at addr+offset+4), and @@ -1324,7 +1324,7 @@ def check_lds_exchange(ins, group, words): """ if not 0 < words <= 8192 or group[0] < 1 or group[1:] != (1, 1): raise Unsupported('LDS exchange needs a 1D group and a nonzero allocation of at most 32 KiB') - fill_span = None + fill_spans = [] published = False read = False prev = (None, [], []) @@ -1335,7 +1335,7 @@ def check_lds_exchange(ins, group, words): or base == 's_endpgm' and i + 1 < len(ins)): raise Unsupported('LDS exchange needs straight-line code and entry EXEC') if base == 's_barrier': - if (fill_span is None or published or prev != ('s_waitcnt', ['lgkmcnt(0)'], []) + if (not fill_spans or published or prev != ('s_waitcnt', ['lgkmcnt(0)'], []) or mods or ops not in ([], ['0'], ['0x0'])): raise Unsupported('LDS exchange needs one barrier after a completed fill') published = True @@ -1359,10 +1359,22 @@ def check_lds_exchange(ins, group, words): offset, = offsets # The prefix below preserves the entry X ID in v0. Each lane writes exactly one distinct element. # 8-byte / 16-byte alignment is not required for LDS dword-addressed writes. - if (fill_span is not None or producer != 'v_lshlrev_b32' or args != [addr_op, shift, 'v0'] - or modifiers or offset % 4 or offset + group[0] * width > words * 4): + end = offset + group[0] * width + if (offset % 4 or end > words * 4 or published + or fill_spans and (base != 'ds_write_b32' or producer != 'ds_write_b32')): raise Unsupported('LDS exchange needs one bounded %s per local X ID' % unit_name) - fill_span = (offset, offset + group[0] * width) + if fill_spans: + if len(fill_spans) != 1: + raise Unsupported('LDS exchange allows at most two consecutive bounded dword fills') + # Consecutive DS writes preserve the proven address VGPR. + if addr_op != args[0]: + raise Unsupported('LDS dword fills must use the same byte address VGPR') + start0, end0 = fill_spans[0] + if offset < end0 and start0 < end: + raise Unsupported('LDS dword fills must be disjoint') + elif producer != 'v_lshlrev_b32' or args != [addr_op, shift, 'v0'] or modifiers: + raise Unsupported('LDS exchange needs one bounded %s per local X ID' % unit_name) + fill_spans.append((offset, end)) else: if not published or modifiers or not args or args[0] != addr_op: raise Unsupported('LDS read needs a bounded address after the fill barrier') @@ -1373,11 +1385,10 @@ def check_lds_exchange(ins, group, words): low, high = 0, int(args[1], 0) else: raise Unsupported('LDS read needs a literal or literal-masked byte address') - fill_start, fill_end = fill_span - # Every byte offset in [a + offset, a + offset + width) must be 4-byte aligned and inside the filled span. - # Mixed 32/64/128-bit reads share the same dword-indexed LDS array once all read dwords lie in [fill_start, fill_end). + # Each read must fit entirely within one initialized span, even when the banks have a gap. if (low % 4 or high % 4 - or any(offset % 4 or low + offset < fill_start or high + offset + width > fill_end + or any(offset % 4 or not any(start <= low + offset and high + offset + width <= end + for start, end in fill_spans) for offset in offsets)): raise Unsupported('LDS read outside the aligned, initialized span') if i + 1 >= len(ins) or ins[i + 1][3] != 's_waitcnt lgkmcnt(0)': @@ -1385,7 +1396,7 @@ def check_lds_exchange(ins, group, words): read = True elif base.startswith('ds_') or 'lds' in mods: raise Unsupported('LDS exchange does not cover ' + asm) - elif fill_span is None and not base.startswith('s_'): + elif not fill_spans and not base.startswith('s_'): # Simple VALU instructions only write their single destination. Other forms, e.g. v_swap_b32, # can also change a source. After the fill, each read proves its own address without the entry X ID. if (base not in VEC_U and base not in VEC_F and base != 'v_mov_b32' @@ -8380,6 +8391,7 @@ def declarations(self): # Unused w1 register field masks in RDNA 2 DS encoding (must be zero): # w1[7:0]=ADDR, w1[15:8]=DATA0, w1[23:16]=DATA1, w1[31:24]=VDST. LDS_UNUSED_W1_MASK = { + 'ds_write_b32': 0xffff0000, 'ds_write2_b32': 0xff000000, 'ds_write2st64_b32': 0xff000000, 'ds_read2st64_b32': 0x00ffff00, From 0498f937acf96b6f048f22871c33c5e7bcabef5d Mon Sep 17 00:00:00 2001 From: tedin7 <110300616+tedin7@users.noreply.github.com> Date: Thu, 26 Nov 2026 07:04:20 +0100 Subject: [PATCH 157/240] startup: fold s_mov_b32 copies of a constant SGPR so inline samplers translate (Part of #1723) (#2708) * fix: fold s_mov_b32 copies of a constant SGPR so llc-built inline samplers translate llc builds a zero sampler as s_mov_b32 s15, 0 then s_mov_b32 s12, s15. The copy kept no symbol, so the sampler operand held None and the shader was refused. The copy now keeps the constant. Extends startup_inline_sampler_check with a copied-constant sampler control. (cherry picked from commit da03456187fe80e5bf53c800f32766df5cb02504) * fix: copy folds only a plain constant; add negative controls for copied samplers Do not fold a copy of the tagged unassigned placeholder. Tests: placeholder copy, run-time source and a copy after the source was rewritten must not fold. (cherry picked from commit cbd9717507808d3110e71c3e5e3cd735b23d27e8) * test: draw the copied-constant inline sampler and its wrong-value control check_draw now also draws a shader whose sampler word 0 is built in s29 and copied into s24; it must read the clamped texel with its own sampler and mismatch with the wrap sampler. * fix: bump shader cache revision to 19 for the constant-copy fold, pin run-time write and join --------- Co-authored-by: c1 --- .github/workflows/windows.yml | 1 + AGENTS.md | 1 + CMakeLists.txt | 3 + docs/startup-runtime.md | 9 +- src/startup_stubs/d3d12_draw.inl | 4 +- .../startup_compute_request_offline_check.py | 4 +- tests/startup_gfx2hlsl_buffer_store_check.py | 4 +- .../startup_gfx2hlsl_const_copy_join_check.py | 96 +++++++++++++++++++ tests/startup_gfx2hlsl_fract_check.py | 4 +- tests/startup_indirect_draw_indexed.cpp | 2 +- tests/startup_inline_sampler_check.py | 91 ++++++++++++++++-- ...tartup_packed_position_provenance_check.py | 2 +- tests/startup_resource_retire_title.cpp | 2 +- tests/startup_shader_cache_key_check.py | 6 +- tools/startup/gfx2hlsl.py | 13 ++- 15 files changed, 216 insertions(+), 26 deletions(-) create mode 100644 tests/startup_gfx2hlsl_const_copy_join_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 7ba2eed9d..d012f049c 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -363,6 +363,7 @@ jobs: tests/startup_gfx2hlsl_sad_check.py \ tests/startup_gfx2hlsl_sad_hi_msad_check.py \ tests/startup_gfx2hlsl_scalar_brev_fold_check.py \ + tests/startup_gfx2hlsl_const_copy_join_check.py \ tests/startup_gfx2hlsl_s_bit_scan_check.py \ tests/startup_gfx2hlsl_pack_b32_f16_check.py \ tests/startup_inline_sampler_check.py \ diff --git a/AGENTS.md b/AGENTS.md index bf2d22898..f9549f584 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -268,6 +268,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_f32_nan_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_sopk_signext_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_scalar_brev_fold_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_const_copy_join_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_pack_b32_f16_check.py ./out/pe-env/bin/python -B tests/run_checks_parallel_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_handler_arity_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 49bbec1d4..723b1a2b4 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3496,6 +3496,9 @@ if(EXISTS "${INTAKE_PYTHON}") # s_brev_b32 of a known constant folds to a known word (a sampler built from it is a constant descriptor). add_test(NAME startup_gfx2hlsl_scalar_brev_fold COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_scalar_brev_fold_check.py") + # A copy of a plain constant scalar register still assigns at run time and drops its constant at a join. + add_test(NAME startup_gfx2hlsl_const_copy_join COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_const_copy_join_check.py") # v_pack_b32_f16 with op_sel and the neg/abs source modifiers, evaluated against a bit reference. add_test(NAME startup_gfx2hlsl_pack_b32_f16 COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_pack_b32_f16_check.py") diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 84d33ad03..b21794e46 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -208,9 +208,12 @@ The translation is refused when: - either header has another size; - the code reads an attribute the table does not list. -The shader cache revision is `x2w-startup-shader-18`. Revision 18 preserves the sign of zero in -floating-point min, max, min3, max3 and med3. The matching compute (`x2w-startup-shader-18cs`) and fixed -slot 57 mesh (`x2w-startup-mesh-57-3`) keys advance because those stages use the shared lowering. +The shader cache revision is `x2w-startup-shader-19`. Revision 19 folds `s_mov_b32` from a scalar register that +holds a plain constant, so later reads of the copy use the constant word. The matching compute +(`x2w-startup-shader-19cs`) key advances because that stage uses the shared lowering. The fixed slot 57 mesh +(`x2w-startup-mesh-57-3`) key stays, because that shader is not translated from guest code. +Revisions before 19 read a register copied from a constant as a run-time value. +Revision 18 preserves the sign of zero in floating-point min, max, min3, max3 and med3. Revisions before 17 lower `v_med3_f32` through a branchless median, which returns the smaller of the other two operands when a source is NaN. Revisions before 16 lower `v_fract_f32` through a bare `frac` instead of the clamped `fract32` helper. diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index f40b9f42c..0ebeb4580 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -353,7 +353,7 @@ Translation* cached_translation(const void* a, std::size_t a_bytes, const void* { // Keep pre-fix desktop bytecode and manifests out of this ABI's cache. // tools/startup/gfx2hlsl.py hashes the same bytes, without a trailing NUL. - constexpr char revision[] = "x2w-startup-shader-18"; + constexpr char revision[] = "x2w-startup-shader-19"; const u64 seed = fnv_bytes(revision, sizeof(revision) - 1); u64 key = fnv_bytes(root_blob.data(), root_blob.size(), fnv_bytes(b, b_bytes, fnv_bytes(a, a_bytes, seed))); // A stream's input layout (stream_input_layout) feeds the vertex fetch, so it is part of the key. @@ -474,7 +474,7 @@ u64 publish_compute_request(const void* desc) std::vector fields(sizeof(words)); words[0] = words[1] = words[3] = words[5] = words[7] = words[9] = words[10] = 0; std::memcpy(fields.data(), words, sizeof(words)); - constexpr char compute_revision[] = "x2w-startup-shader-18cs"; // tools/startup/gfx2hlsl.py compute_key + constexpr char compute_revision[] = "x2w-startup-shader-19cs"; // tools/startup/gfx2hlsl.py compute_key u64 key = fnv_bytes(compute_revision, sizeof(compute_revision) - 1); const std::vector* order[] = {&code, &data, &root_blob, &fields, &state_a, &state_b}; for (const auto* part : order) key = fnv_part(*part, key); diff --git a/tests/startup_compute_request_offline_check.py b/tests/startup_compute_request_offline_check.py index f2f0299a8..a834a0762 100644 --- a/tests/startup_compute_request_offline_check.py +++ b/tests/startup_compute_request_offline_check.py @@ -25,12 +25,12 @@ DESC = struct.pack('<12Q', 0, 0, 24, 0, 20, 0, len(CODE), 0, len(DATA), 0, 0, 11) STATE_A = struct.pack('<3Q', 1, 0x2c, 0xfff0000000000003) STATE_B = struct.pack('<5I', 0x1234abcd, 0xffff0000, 0, 0, 0) -KEY = 0x375fa7c3f8f4a3dd # framed key at revision 18cs +KEY = 0x63ac0aa21c46da1c # framed key at revision 19cs def framed_key(): h = 1469598103934665603 - for b in b'x2w-startup-shader-18cs': + for b in b'x2w-startup-shader-19cs': h = ((h ^ b) * 1099511628211) & 0xffffffffffffffff for part in (CODE, DATA, ROOT, DESC, STATE_A, STATE_B): for b in struct.pack(' translated_pipeline(ID3D12Device* guest, ID3D12RootSignature* r bool needs_start, bool table_buffer = false, bool indexed = false, bool rect = false) { // The opaque guest programs identify synthetic cache entries. The actual bound shaders are source-built DXBC. - constexpr char revision[] = "x2w-startup-shader-18"; + constexpr char revision[] = "x2w-startup-shader-19"; static std::uint32_t vertex_ids[]{0xe0000101, 0xe0000102, 0xe0000103}; static std::uint32_t pixel_ids[]{0xe0000202, 0xe0000203, 0xe0000204}; auto& vertex_id = vertex_ids[indexed ? 2 : needs_start]; diff --git a/tests/startup_inline_sampler_check.py b/tests/startup_inline_sampler_check.py index f73fe79b2..c0c700320 100644 --- a/tests/startup_inline_sampler_check.py +++ b/tests/startup_inline_sampler_check.py @@ -35,6 +35,11 @@ WRAP_SOURCE = CLAMP_SOURCE.replace('s_bfm_b32 s24, s28, 33', 's_bfm_b32 s24, 0, 33') WRAP_WORDS = CLAMP_WORDS.replace(bytes.fromhex('1ca11892'), bytes.fromhex('80a11892')) +# The clamp sampler with word 0 built in s29 and copied into s24 (s_mov_b32 s24, s29): only the copy fold lets +# the four words be read as constants, so the draw below depends on it. +COPY_CLAMP_SOURCE = CLAMP_SOURCE.replace('s_bfm_b32 s24, s28, 33', 's_bfm_b32 s29, s28, 33\ns_mov_b32 s24, s29') +COPY_CLAMP_WORDS = CLAMP_WORDS.replace(bytes.fromhex('1ca11892'), bytes.fromhex('1ca11d92' '1d0398be')) + # s9 is root constant 1. Overwrite a previously folded word to check that the # run-time write clears its constant value before the sampler is consumed. DYNAMIC_SOURCE = CLAMP_SOURCE.replace('v_mov_b32 v0,', 's_bfm_b32 s24, s9, 33\nv_mov_b32 v0,') @@ -74,12 +79,78 @@ def bare_stage(symbols=None): except AttributeError: pass +# llc builds a constant sampler by copying one zeroed SGPR into the other words (s_mov_b32 s25, s24). +COPY_WORDS = IMAGE_WORDS.replace( + bytes.fromhex('800398be' '800399be' '80039abe' '80039bbe'), + bytes.fromhex('800398be' '180399be' '18039abe' '18039bbe'), +) + + +def check_copied_constant_sampler(): + """A sampler word copied from a constant SGPR is that constant, not an unknown value.""" + assert COPY_WORDS != IMAGE_WORDS + expected = [l for l in translate(IMAGE_WORDS).manifest().splitlines() if l.startswith('smp ')] + got = [l for l in translate(COPY_WORDS).manifest().splitlines() if l.startswith('smp ')] + assert got == expected and got, (got, expected) + print('copied constant sampler folds to %s' % got[0]) + + +def copy_symbol(symbols, copy='s_mov_b32 s12, s15'): + """The symbol s12 holds after `copy` runs on a bare stage that starts with `symbols`.""" + class Pipe: + sampler_heap = False + + stage = G.Stage.__new__(G.Stage) + stage.pipe, stage.sym, stage.lines = Pipe(), dict(symbols), [] + stage.used_s, stage.used_v, stage.uniform_v, stage.exec_known = set(), set(), set(), True + stage.has_branches, stage.masks = False, set() + stage.one(copy.split()[0], copy) + return stage.sym.get(12) + + +def check_copy_only_folds_plain_constants(): + """Only a plain ('const', value) copies as a constant; every other source must not fold.""" + assert copy_symbol({15: ('const', 0)}) == ('const', 0) + # The default-sampler placeholder is tagged 'unassigned': a copy of it is no run-time constant. + assert copy_symbol({15: ('const', 0, 'unassigned')}) != ('const', 0) + # A register that holds a root constant or nothing known is not a constant. + assert copy_symbol({15: ('ud', 1)}) != ('const', 1) + assert copy_symbol({}) is None + # A copy of a plain constant takes that constant's value. + assert copy_symbol({15: ('const', 7)}) == ('const', 7) + print('copies fold only plain constants') + + +def check_copied_sampler_after_overwrite(): + """A sampler word copied after its source was rewritten by a run-time value or another constant.""" + prefix = bytes.fromhex('800398be') # s_mov_b32 s24, 0 + copies = bytes.fromhex('180399be' '18039abe' '18039bbe') + anchor = prefix + copies + assert anchor in COPY_WORDS + runtime = COPY_WORDS.replace(anchor, prefix + bytes.fromhex('090398be') + copies) # s24 = s9 (root constant) + try: + translate(runtime) + except G.Unsupported as error: + assert 'holds' in str(error), error + else: + raise AssertionError('a sampler copied from a run-time register was accepted') + # s28 = 0, then s28 = 1, then s27 = s28; s24..s26 stay literal zeros + one = COPY_WORDS.replace(anchor, bytes.fromhex('800398be' '800399be' '80039abe' '80039cbe' '81039cbe' '1c039bbe')) + smp = [l for l in translate(one).manifest().splitlines() if l.startswith('smp ')] + assert smp == ['smp 0 0x0 0x0 0x0 0x1'], smp + print('copy after overwrite: run-time source refused, new constant wins (%s)' % smp[0]) + + def controls(): check_compare_sampler_constant() + check_copied_constant_sampler() + check_copy_only_folds_plain_constants() + check_copied_sampler_after_overwrite() fixtures = [] for name, code, words in ( ('clamp', CLAMP_WORDS, (0x2, 0, 0x00100000, 0)), ('wrap', WRAP_WORDS, (0, 0, 0x00100000, 0)), + ('copied clamp', COPY_CLAMP_WORDS, (0x2, 0, 0x00100000, 0)), ): pipe = translate(code) manifest = pipe.manifest() @@ -98,8 +169,9 @@ def controls(): print('root-constant mask width: inline sampler refused (%s)' % error) else: raise AssertionError('run-time write to s24 was accepted as an inline sampler') - (clamp_ps, clamp_line), (_, wrap_line) = fixtures - return clamp_ps, clamp_line, wrap_line + (clamp_ps, clamp_line), (_, wrap_line), (copy_ps, copy_line) = fixtures + assert copy_line == clamp_line, (copy_line, clamp_line) + return clamp_ps, clamp_line, wrap_line, copy_ps def check_binary(llvm_mc): @@ -107,14 +179,15 @@ def check_binary(llvm_mc): ('clamp', CLAMP_SOURCE, CLAMP_WORDS), ('wrap', WRAP_SOURCE, WRAP_WORDS), ('root constant', DYNAMIC_SOURCE, DYNAMIC_WORDS), + ('copied clamp', COPY_CLAMP_SOURCE, COPY_CLAMP_WORDS), ): built = assemble(llvm_mc, source) assert built == recorded, '%s: assembled %s, recorded %s' % (name, built.hex(), recorded.hex()) - print('all three fixture programs match llvm-mc') + print('all four fixture programs match llvm-mc') def check_draw(dxc, renderer, adapter, fxc=None): - ps, clamp, wrap = controls() + ps, clamp, wrap, copy_ps = controls() expected_clamp = texel(1, 0, 0) expected_wrap = texel(0, 0, 0) compilers = [('dxc', dxc, 'vs_6_0', 'ps_6_0')] @@ -129,9 +202,13 @@ def check_draw(dxc, renderer, adapter, fxc=None): for kind, compiler, vs_profile, ps_profile in compilers: vs = compile_hlsl(compiler, kind, FULLSCREEN_VS, 'fullscreen', vs_profile, directory) shader = compile_hlsl(compiler, kind, ps, 'inline_sampler', ps_profile, directory) - command = [renderer, adapter, '--startup-image-3d', str(vs), str(shader), '0.25', expected_clamp] - # Hold shader, texture, and reference fixed. Only the manifest sampler changes. - for label, line, result in (('clamp', clamp, 0), ('wrap control', wrap, 1)): + copy_shader = compile_hlsl(compiler, kind, copy_ps, 'inline_sampler_copy', ps_profile, directory) + # Hold shader, texture, and reference fixed. Only the manifest sampler changes. The copied-word shader + # is drawn with its own sampler (must read the clamped texel) and with the wrap sampler (must mismatch). + for label, shader_path, line, result in (('clamp', shader, clamp, 0), ('wrap control', shader, wrap, 1), + ('copied-word clamp', copy_shader, clamp, 0), + ('copied-word wrap control', copy_shader, wrap, 1)): + command = [renderer, adapter, '--startup-image-3d', str(vs), str(shader_path), '0.25', expected_clamp] run = subprocess.run([*command, line], capture_output=True, text=True) print(run.stdout, end='', flush=True) if run.returncode == 77: diff --git a/tests/startup_packed_position_provenance_check.py b/tests/startup_packed_position_provenance_check.py index bd848f3db..fea8cc816 100644 --- a/tests/startup_packed_position_provenance_check.py +++ b/tests/startup_packed_position_provenance_check.py @@ -206,7 +206,7 @@ def refused(label, cache, key, reason): cache = Path(tmp) bare = G.pipeline_key(VS_WORDS, ps_words(4), root_blob()) check('without a description the key is unchanged', - bare == G.fnv(root_blob(), G.fnv(ps_words(4), G.fnv(VS_WORDS, G.fnv(b'x2w-startup-shader-18'))))) + bare == G.fnv(root_blob(), G.fnv(ps_words(4), G.fnv(VS_WORDS, G.fnv(b'x2w-startup-shader-19'))))) keys = [put_request(cache, ps_words(4), masks) for masks in (TARGET, SAME_V4, DECOY)] check('same stages, root and layout with three mask pairs: three request identities', len(set(keys)) == 3 and bare not in keys diff --git a/tests/startup_resource_retire_title.cpp b/tests/startup_resource_retire_title.cpp index 05f8f0a38..24c80d3b0 100644 --- a/tests/startup_resource_retire_title.cpp +++ b/tests/startup_resource_retire_title.cpp @@ -371,7 +371,7 @@ constexpr UINT draw_side = 4; // 4x4 R8G8B8A8_UNORM target constexpr UINT draw_covered = 3; // scissor leaves the last row and column untouched as the sentinel constexpr int draw_seed = 77; constexpr UINT draw_clear_pixel = 0xffff00ffu; // ClearRenderTargetView({1, 0, 1, 1}) in R8G8B8A8_UNORM -constexpr char draw_revision[] = "x2w-startup-shader-18"; // d3d12_draw.inl cached_translation +constexpr char draw_revision[] = "x2w-startup-shader-19"; // d3d12_draw.inl cached_translation constexpr char draw_vertex_shader[] = R"( struct Varying { float4 position : SV_Position; }; diff --git a/tests/startup_shader_cache_key_check.py b/tests/startup_shader_cache_key_check.py index 8de395820..a0d27d525 100644 --- a/tests/startup_shader_cache_key_check.py +++ b/tests/startup_shader_cache_key_check.py @@ -49,10 +49,10 @@ def check_request(blobs, key, diagnostic=None, rtv_request=None, layout=None): def main(): # Independently executed C++ runtime fnv_bytes/cached_translation known-answer vector. - # Revision x2w-startup-shader-18 excludes NUL. Stored order is a, b, root, then optional input layout. + # Revision x2w-startup-shader-19 excludes NUL. Stored order is a, b, root, then optional input layout. vector = (b"\x00VS\xff", b"PS\x00\x80", b"RTS0\x00") - assert gfx2hlsl.pipeline_key(*vector) == 0x8d1cb58fb148b30a - assert gfx2hlsl.pipeline_key(*vector, b"ia\x00\xfe") == 0xf9e74efdcb8283d2 + assert gfx2hlsl.pipeline_key(*vector) == 0xf3444b13fe09b4df + assert gfx2hlsl.pipeline_key(*vector, b"ia\x00\xfe") == 0x2039e248f9cad09f blobs = (VERTEX, PIXEL, ROOT) canonical = gfx2hlsl.pipeline_key(*blobs) check_request(blobs, canonical) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index f03e0eceb..58bda72bf 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -4664,6 +4664,15 @@ def src_sym(t): self.set_s(d + 1, '0x%08xu' % ((value >> 32) & 0xffffffff), ('const', (value >> 32) & 0xffffffff)) self.masks.discard(d) return None + if base == 's_mov_b32' and not pair and len(srcs) == 1 and reg_range(srcs[0]) and reg_range(srcs[0])[0] == 's' \ + and reg_range(srcs[0])[1] == reg_range(srcs[0])[2] and len(self.sym.get(reg_range(srcs[0])[1]) or ()) == 2 \ + and self.is_const(reg_range(srcs[0])[1]) is not None: + # A copy of an SGPR holding a plain known constant (not the tagged unassigned placeholder) is that constant (llc copies a zero into an inline + # sampler word: s_mov_b32 s12, s15 after s_mov_b32 s15, 0). + value = self.is_const(reg_range(srcs[0])[1]) + self.set_s(d, '0x%08xu' % value, ('const', value)) + self.masks.discard(d) + return None if base in SCALAR_CONST_FOLD: # Constant operands give a known word, so a descriptor built from them (an inline sampler from # s_movk_i32, s_bfm_b32, s_mov_b32 and s_brev_b32 into s[N:N+3]) is a constant descriptor. @@ -9468,7 +9477,7 @@ def pipeline_key(vs_code, ps_code, root_blob, layout=b'', ps_inputs=None): SPI_PS_INPUT_ENA and SPI_PS_INPUT_ADDR as little-endian u32. Two pipelines with the same stages, root signature and input layout but different masks are then two requests with their own results. Without a description the key is unchanged.""" - key = fnv(root_blob, fnv(ps_code, fnv(vs_code, fnv(b'x2w-startup-shader-18')))) + key = fnv(root_blob, fnv(ps_code, fnv(vs_code, fnv(b'x2w-startup-shader-19')))) key = fnv(layout, key) if layout else key return key if ps_inputs is None else fnv(b'psin1' + struct.pack(' Date: Thu, 26 Nov 2026 07:04:39 +0100 Subject: [PATCH 158/240] shader: support 64-bit source operands in gfx2hlsl (Part of #1723) (#2039) * feat: lower 32-bit hex literals as 64-bit source of 64-bit vector shifts Part of #1723 * docs: document 32-bit hex literal source of 64-bit vector shifts * fix: sign-extend 32-bit hex literal for s_ashr_i64 source * fix: sign-extend hex literal source of s_bfe_i64 * fix: keep hex literal refused for v_mad64 addend, align scanner and Linux CI --------- Co-authored-by: c1 --- .github/workflows/windows.yml | 1 + CMakeLists.txt | 2 + docs/experiments.md | 2 +- tests/rdna2_tools_check.py | 4 +- tests/startup_gfx2hlsl_shift64_check.py | 1 - .../startup_gfx2hlsl_shift64_literal_check.py | 60 +++++++++++++++++++ tools/scan_unsupported_shaders.py | 4 +- tools/startup/gfx2hlsl.py | 12 ++-- 8 files changed, 76 insertions(+), 10 deletions(-) create mode 100644 tests/startup_gfx2hlsl_shift64_literal_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index d012f049c..a1ee7367a 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -341,6 +341,7 @@ jobs: tests/startup_gfx2hlsl_s_quadmask_check.py \ tests/startup_gfx2hlsl_fma_mix_check.py \ tests/startup_gfx2hlsl_shift64_check.py \ + tests/startup_gfx2hlsl_shift64_literal_check.py \ tests/startup_gfx2hlsl_mad64_check.py \ tests/startup_gfx2hlsl_cmp_class_f16_sdwa_check.py \ tests/startup_gfx2hlsl_mul_hi_i32_check.py \ diff --git a/CMakeLists.txt b/CMakeLists.txt index 723b1a2b4..36e53d97f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4269,6 +4269,8 @@ if(EXISTS "${INTAKE_PYTHON}") # gfx2hlsl 64-bit VOP3 shifts: binary round-trip, overlap, guards and WARP/hardware draws (Refs #1723). add_test(NAME startup_gfx2hlsl_shift64_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_shift64_check.py") + add_test(NAME startup_gfx2hlsl_shift64_literal COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_shift64_literal_check.py") foreach(adapter IN ITEMS warp hardware) add_test(NAME startup_gfx2hlsl_shift64_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_shift64_check.py" draw "${DXC_EXECUTABLE}" diff --git a/docs/experiments.md b/docs/experiments.md index cf03ec27e..7faa600b9 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -8675,7 +8675,7 @@ The draws (`pixel_aot_cmp_f64_warp` and `_hardware`) run eight predicate groups ctest --preset dev --no-tests=error -R '^pixel_aot_cmp_f64_(warp|hardware)$' -V ``` -The 64-bit `VOP3` shifts `v_lshlrev_b64`, `v_lshrrev_b64` and `v_ashrrev_i64` (issue #928) follow the [AMD RDNA 2 ISA guide](https://gpuopen.com/download/rdna2-shader-instruction-set-architecture.pdf) §12.12 (opcodes 767-769): `D = S1 << S0[5:0]`, `S1 >> S0[5:0]` and `signext(S1) >> S0[5:0]`. The opcodes match the LLVM 15 gfx1013 encodings, and LLVM 15 folds an IR shift by `x & 63` into the bare instruction while keeping `x & 31`. The value uses the two-word representation of the 64-bit comparisons above, so the HLSL needs no 64-bit type: both source words are read into temporaries before the destination pair is written, so the in-place form keeps the original value, and the result is selected for amounts below and above 32, so no 32-bit HLSL shift receives a count of 32 or more. Only `v_ashrrev_i64` fills with the sign bit. The amount is a VGPR, an SGPR, an inline integer from -16 to 64 or a literal; the value is a VGPR pair, an SGPR pair or an inline integer, sign-extended to 64 bits as for the comparisons (assumed, not sourced). At most one source may be an SGPR or a literal (the ISA's one scalar broadcast constant; LLVM 15 refuses the others with `violates constant bus restrictions`). `_e32`, `clamp`, `op_sel` and source modifiers, a destination that is not a pair in `v0`..`v255` or has an outstanding image sample, float amounts and use inside a masked region are refused. The draw (`tests/pixel_aot_check.py draw-shift64`, tests `pixel_aot_shift64_warp` and `pixel_aot_shift64_hardware`) compiles three programs per instruction (register sources; the in-place pair next to the literal amount `0x41`, which wraps to 1; and an SGPR-pair value next to the inline `-1`) and reads the four result words back through `R32G32B32A32_UINT` for three values (one with a negative high word) and the amounts 0, 1, 31, 32, 33, 63, 64, 65, `0xffffffc1` and `0x80000020`, against a Python reference written from the ISA formulas. Three mutated `v_ashrrev_i64` shaders must each mismatch: the amount masked to five bits, the sign fill replaced with zeros, and the result words swapped. The LLVM 15 round trip covers the nine programs; the scanner accepts the same operand shapes and `tests/rdna2_tools_check.py` pins them. The draw pins the translator's model on a desktop adapter; it is not evidence for gfx1013 hardware. +The 64-bit `VOP3` shifts `v_lshlrev_b64`, `v_lshrrev_b64` and `v_ashrrev_i64` (issue #928) follow the [AMD RDNA 2 ISA guide](https://gpuopen.com/download/rdna2-shader-instruction-set-architecture.pdf) §12.12 (opcodes 767-769): `D = S1 << S0[5:0]`, `S1 >> S0[5:0]` and `signext(S1) >> S0[5:0]`. The opcodes match the LLVM 15 gfx1013 encodings, and LLVM 15 folds an IR shift by `x & 63` into the bare instruction while keeping `x & 31`. The value uses the two-word representation of the 64-bit comparisons above, so the HLSL needs no 64-bit type: both source words are read into temporaries before the destination pair is written, so the in-place form keeps the original value, and the result is selected for amounts below and above 32, so no 32-bit HLSL shift receives a count of 32 or more. Only `v_ashrrev_i64` fills with the sign bit. The amount is a VGPR, an SGPR, an inline integer from -16 to 64 or a literal; the value is a VGPR pair, an SGPR pair, an inline integer, sign-extended to 64 bits as for the comparisons (assumed, not sourced), or a 32-bit hex literal (`0x0` to `0xffffffff`, written in hex form). A literal fills the low word; the high word is zero for `v_lshlrev_b64` and `v_lshrrev_b64` and copies bit 31 for `v_ashrrev_i64`. The same hex literal is now also the 64-bit source of the scalar `s_lshl_b64`, `s_lshr_b64`, `s_ashr_i64`, `s_bfe_u64` and `s_bfe_i64`, which refused it before; the high word is zero for the unsigned operations and copies bit 31 for the signed ones (`s_ashr_i64`, `s_bfe_i64`). Only `s_mov_b64` zero-extended a hex literal before this change. The extension rule is an assumption, not sourced from the ISA text. A decimal literal outside -16 to 64, a hex literal wider than 32 bits and a literal as destination stay refused. `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_shift64_literal$' -V` checks six lowered vector forms and the scalar `s_ashr_i64`, `s_lshr_b64`, `s_bfe_i64` and `s_bfe_u64` (including `0x80000000` and `0xffffffff`, where the signed forms differ) and these refusals; it is pure Python and needs no adapter. At most one source may be an SGPR or a literal (the ISA's one scalar broadcast constant; LLVM 15 refuses the others with `violates constant bus restrictions`). `_e32`, `clamp`, `op_sel` and source modifiers, a destination that is not a pair in `v0`..`v255` or has an outstanding image sample, float amounts and use inside a masked region are refused. The draw (`tests/pixel_aot_check.py draw-shift64`, tests `pixel_aot_shift64_warp` and `pixel_aot_shift64_hardware`) compiles three programs per instruction (register sources; the in-place pair next to the literal amount `0x41`, which wraps to 1; and an SGPR-pair value next to the inline `-1`) and reads the four result words back through `R32G32B32A32_UINT` for three values (one with a negative high word) and the amounts 0, 1, 31, 32, 33, 63, 64, 65, `0xffffffc1` and `0x80000020`, against a Python reference written from the ISA formulas. Three mutated `v_ashrrev_i64` shaders must each mismatch: the amount masked to five bits, the sign fill replaced with zeros, and the result words swapped. The LLVM 15 round trip covers the nine programs; the scanner accepts the same operand shapes and `tests/rdna2_tools_check.py` pins them. The draw pins the translator's model on a desktop adapter; it is not evidence for gfx1013 hardware. The non-packed 16-bit integer `VOP3` ops (issue #669) `v_add_nc_u16`, `v_add_nc_i16`, `v_sub_nc_u16`, `v_sub_nc_i16`, `v_min_u16`, `v_max_u16`, `v_min_i16`, `v_max_i16`, `v_mul_lo_u16`, `v_lshlrev_b16`, `v_lshrrev_b16` and `v_ashrrev_i16` compute on the low 16 bits of two sources and reuse the lane arithmetic of the packed forms: results wrap modulo 2^16, signed min, max and shifts sign-extend the 16-bit value, and shift counts are masked to 4 bits (`& 15`, so a count of 16 shifts by 0). Only the low 16 bits of the result are defined and tracked: the lowering records the destination as `("low16", alu)`, a value whose HLSL variable holds the zero-extended result but whose upper half no accepted reader observes. The destination's previous value is not merged, so a destination may hold anything (a tracked value, an untracked register or another low16 result); a destination with an outstanding image sample is refused. The same applies to the unsuffixed and the `_e64` spelling. The readers that see a low16 value are the 12 ops themselves (a chain of two ops is accepted), the 16-bit integer compares `v_cmp_{eq,ne,lt,le,gt,ge}_{i16,u16}` and `v_mov_b32_sdwa` with `src0_sel:WORD_0`, `BYTE_0` or `BYTE_1` (also with `sext()`), which widens the low half into a fully defined word. Every whole-word or high-half reader is refused: 32-bit integer and float arithmetic, moves, `v_cndmask_b32` data operands, DPP, packed `VOP3P` forms, conversions (including `v_cvt_f32_f16`, which is out of scope for integer low16; binary16 arithmetic results use the distinct `half16` tag, below), dot products, class compares, packs, both export forms and image sample coordinates raise `Expected a numeric register`, `Expected a numeric VGPR in DPP`, `Unsupported pack operand`, `Unsupported export` or `Unsupported texture coordinate`; `v_cvt_f16_f32` into a low16 destination raises `Unsupported conversion destination`; and `v_mov_b32_sdwa` with `WORD_1`, `BYTE_2`, `BYTE_3` or `DWORD` on a low16 source, or with `dst_unused:UNUSED_PRESERVE` into a low16 destination, raises `Reads the undefined high half of a 16-bit result`. A source may be a VGPR in 0 to 255 that holds a tracked value, a tracked SGPR in 0 to 105, an integer inline constant from -16 to 64 or a literal up to `0xffff`. `op_sel`, `clamp`, source modifiers, DPP, SDWA, the f16 ops, float tokens, wider literals, inline integers outside -16 to 64 (llvm-mc would encode `-17` as the literal `0xffef`; the translator refuses it by policy, as for the 16-bit compares), an untracked source, a register out of range and a destination with an outstanding image sample are refused. `tests/form_coverage_check.py` asserts that the 12 unsuffixed forms are counted while the f16 neighbours are not. `tools/scan_unsupported_shaders.py` matches instructions syntactically and cannot see the low16 tags, so it can report a shader as supported that the translator then refuses at a whole-word reader. The binary fixtures (four programs; groups 0 to 2 widen all four results and group 3 its two low-half results with `v_mov_b32_sdwa ... src0_sel:WORD_0`) round-trip through LLVM 15.0.7, and the controls refuse every form above with its message. Reproduce with `ctest --preset dev --no-tests=error -R "^pixel_aot_int16_vop3_"`: groups 0 to 2 preload `v24` to `v27` with a `0xa5c3xxxx` sentinel, run four ops on constant words, widen each result into `v12` to `v15` with SDWA `WORD_0` and export through the bit-exact `R32G32B32A32_UINT` target against a Python reference written from the semantics that contains only the zero-extended low halves; group 3 chains `v_add_nc_u16` into `v_mul_lo_u16` and selects between whole words with `v_cmp_lt_u16` and `v_cmp_lt_i16` on low16 results. Six word sets cover `0x7fff` against `0x8000`, `0xffff + 1`, `0 - 1`, shift counts 15, 16, 17 and 31, a negative operand under `ashrrev`, signed and unsigned min and max that disagree, the overflow `0x1234 * 0x0567`, and sources whose high half differs from the low half. Five mutations of the generated shader must each report a pixel mismatch (a source read from bits 31:16, a shift mask of 31 instead of 15, `v_min_i16` replaced by `v_min_u16`, and a `>> 16u` read of a low16 result by the chained op and by the first compare), and a widening that selects `WORD_1` instead of `WORD_0` must be refused at lowering. The sentinel preloads do not detect a high-half leak, because every accepted reader skips the high half; that half is guarded only by the refusal controls. The binary round trip disassembles through libLLVM; `tools/disasm_rdna2.py` decodes the same encodings. [AMD RDNA 2 ISA reference](https://docs.amd.com/v/u/en-US/rdna2-shader-instruction-set-architecture) diff --git a/tests/rdna2_tools_check.py b/tests/rdna2_tools_check.py index 2aaaf9789..32ce96a37 100644 --- a/tests/rdna2_tools_check.py +++ b/tests/rdna2_tools_check.py @@ -6158,10 +6158,10 @@ def test_shift64_scanner_support(self): """Issue #928: the 64-bit VOP3 shifts are supported with at most one SGPR or literal source.""" for line in ("v_lshlrev_b64 v[12:13], v20, v[18:19]", "v_lshrrev_b64 v[2:3], s46, v[4:5]", "v_ashrrev_i64 v[2:3], 0x41, v[4:5]", "v_lshlrev_b64 v[2:3], v1, s[4:5]", - "v_ashrrev_i64 v[2:3], 3, -1", "v_lshlrev_b64_e64 v[2:3], v1, v[4:5]"): + "v_ashrrev_i64 v[2:3], 3, -1", "v_lshlrev_b64 v[2:3], v1, 0x41", "v_lshlrev_b64_e64 v[2:3], v1, v[4:5]"): self.assertTrue(is_instruction_supported(line), line) for line in ("v_lshlrev_b64 v[2:3], s4, s[4:5]", "v_lshlrev_b64 v[2:3], 0x41, s[4:5]", - "v_lshlrev_b64 v[2:3], v1, 0x41", "v_lshlrev_b64 v[2:3], v1, v[4:5] clamp", + "v_lshlrev_b64 v[2:3], s4, 0x41", "v_lshlrev_b64 v[2:3], v1, v[4:5] clamp", "v_lshlrev_b64_e32 v[2:3], v1, v[4:5]", "v_lshlrev_b64 v[2:3], -v1, v[4:5]"): self.assertFalse(is_instruction_supported(line), line) diff --git a/tests/startup_gfx2hlsl_shift64_check.py b/tests/startup_gfx2hlsl_shift64_check.py index 71a51c295..32c40fd08 100644 --- a/tests/startup_gfx2hlsl_shift64_check.py +++ b/tests/startup_gfx2hlsl_shift64_check.py @@ -313,7 +313,6 @@ def controls(): 'v_lshrrev_b64 v[0:1], v2, v[255:256]', 'v_lshrrev_b64 v[0:1], v2, vcc', 'v_lshrrev_b64 v[0:1], v2, exec', - 'v_lshrrev_b64 v[0:1], v2, 0x41', 'v_lshrrev_b64 v[0:1], v2, 65', 'v_lshrrev_b64 v[0:1], v2, -17', 'v_lshrrev_b64 v[0:1], v2, 1.0', diff --git a/tests/startup_gfx2hlsl_shift64_literal_check.py b/tests/startup_gfx2hlsl_shift64_literal_check.py new file mode 100644 index 000000000..c6abbcb27 --- /dev/null +++ b/tests/startup_gfx2hlsl_shift64_literal_check.py @@ -0,0 +1,60 @@ +"""32-bit hex literal as the 64-bit source of v_lshlrev_b64, v_lshrrev_b64 and v_ashrrev_i64 (Refs #1723). + +A literal fills the low word. The high word is zero for the unsigned shifts and copies bit 31 for the signed +shift (the rule of s_mov_b64; the scalar shifts and bitfield extracts take it from this change). Pure Python; run with no arguments. +""" +import struct +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import startup_gfx2hlsl_scalar_m0_check as M # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import Probe, check, refused # noqa: E402 + +# (operation, helper, literal, expected low word, expected high word) +CASES = ( + ('v_lshlrev_b64', 'shl64', '0x41', '65u', '0u'), + ('v_lshrrev_b64', 'shr64u', '0x80000000', '2147483648u', '0u'), + ('v_lshrrev_b64', 'shr64u', '0xffffffff', '4294967295u', '0u'), + ('v_ashrrev_i64', 'shr64i', '0x7fffffff', '2147483647u', '0u'), + ('v_ashrrev_i64', 'shr64i', '0x80000000', '2147483648u', '4294967295u'), + ('v_ashrrev_i64', 'shr64i', '0xffffffff', '4294967295u', '4294967295u'), +) + + +def lowered(op, literal): + probe = Probe() + probe.one(op, '%s v[0:1], v2, %s' % (op, literal)) + return probe.lines + + +def scalar_lowered(opcode): + """s_ s[20:21], 0xffffffff, s9 as encoded (SOP2, source 255 plus a literal dword).""" + stage = M.run_seq(M.encode_sop2(opcode, 20, 255, 9) + struct.pack(' dict: rf"\s+{INT16_SOURCE},\s+{INT16_SOURCE},\s+{INT16_SOURCE}" ) # 64-bit VOP3 shifts (issue #928): a VGPR-pair destination, a 32-bit amount (VGPR, SGPR, inline integer or -# literal) and a 64-bit value (VGPR pair, SGPR pair or inline integer), with at most one SGPR or literal source. +# literal) and a 64-bit value (VGPR pair, SGPR pair, inline integer or 32-bit hex literal), with at most one SGPR or literal source. # This matches syntax only; pixel_aot also checks the pair ranges and that the sources are tracked. SHIFT64_AMOUNT = r"(?:v\d+|-?\d+)" SHIFT64_VALUE = r"(?:v\[\d+:\d+\]|-?\d+)" SUPPORTED_INSTRUCTIONS_REGEX.append( r"v_(?:lshlrev_b64|lshrrev_b64|ashrrev_i64)(?:_e64)?\s+v\[\d+:\d+\],\s+" rf"(?:{SHIFT64_AMOUNT},\s+{SHIFT64_VALUE}|(?:s\d+|0x[0-9a-f]{{1,8}}),\s+{SHIFT64_VALUE}" - rf"|{SHIFT64_AMOUNT},\s+s\[\d+:\d+\])" + rf"|{SHIFT64_AMOUNT},\s+s\[\d+:\d+\]|{SHIFT64_AMOUNT},\s+0x[0-9a-f]{{1,8}})" ) for name, (arity, _) in PIXEL_INTEGER.items(): diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 58bda72bf..5621c2bd8 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -5281,7 +5281,7 @@ def scalar_wide_op(self, name, ops, mods, wide_src, wide_dst, helper, signed=Non r0 = reg_range(ops[1]) if r0 and r0[0] != 's': raise Unsupported('%s source %s' % (name, ops[1])) - low, high = self.i64_words(ops[1]) + low, high = self.i64_words(ops[1], helper == 'shr64i' or signed is True, True) known = [self.scalar_const('s%d' % r0[1]), self.scalar_const('s%d' % r0[2])] if r0 else [ int(low[:-1]), int(high[:-1])] else: @@ -7753,8 +7753,9 @@ def op_v_cubetc_f32(self, ops, mods): def op_v_cubema_f32(self, ops, mods): self.cube('ma', ops, mods) - def i64_words(self, tok): - """(low, high) uint expressions of a 64-bit integer source: a VGPR/SGPR pair or an inline int.""" + def i64_words(self, tok, signed=False, literal=False): + """(low, high) uint expressions of a 64-bit integer source: a VGPR/SGPR pair, an inline int or a + 32-bit hex literal when `literal` is set (zero-extended, sign-extended when the operation is signed).""" pair = reg_range(tok) if pair and pair[2] == pair[1] + 1: if pair[0] == 'v' and pair[2] <= 255: @@ -7765,6 +7766,9 @@ def i64_words(self, tok): if re.fullmatch(r'0|-?[1-9]\d*', tok) and -16 <= int(tok) <= 64: value = int(tok) & 0xffffffffffffffff return '%du' % (value & 0xffffffff), '%du' % (value >> 32) + if literal and re.fullmatch(r'0x[0-9a-f]{1,8}', tok): + word = int(tok, 16) + return '%du' % word, ('4294967295u' if signed and word >> 31 else '0u') raise Unsupported('64-bit source %s' % tok) def shift64(self, ops, mods, helper): @@ -7780,7 +7784,7 @@ def shift64(self, ops, mods, helper): or ops[1] in ('vcc', 'exec') or ops[1] in FLOATS): raise Unsupported('64-bit shift amount %s' % ops[1]) amount = self.u(ops[1]) - low, high = self.i64_words(ops[2]) + low, high = self.i64_words(ops[2], helper == 'shr64i', True) body = '{ uint2 t = %s(%s, %s, %s); v%d = t.x; v%d = t.y; }' % ( helper, low, high, amount, dst[1], dst[2]) if hasattr(self, 'uniform_v'): From 400c0c7626c222bafa7e303f4dda5193c81d70e4 Mon Sep 17 00:00:00 2001 From: Chad Hyatt Date: Thu, 26 Nov 2026 00:05:12 -0600 Subject: [PATCH 159/240] tooling: preserve form reference output permissions (#2752) - Keep existing POSIX report modes on atomic rewrites and use normal umask for new outputs. - Exercise both cases through the actual CLI. Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- tests/form_reference_cli_check.py | 40 +++++++++++++++++++++++++++++++ tools/form_reference.py | 16 ++++++++++++- 2 files changed, 55 insertions(+), 1 deletion(-) diff --git a/tests/form_reference_cli_check.py b/tests/form_reference_cli_check.py index fdcd38fed..9ae521fac 100644 --- a/tests/form_reference_cli_check.py +++ b/tests/form_reference_cli_check.py @@ -164,6 +164,46 @@ def test_atomic_overwrite_sys_argv_and_main_entrypoint(self) -> None: ) +@unittest.skipUnless(os.name == "posix", "POSIX permission modes only") +class FormReferencePermissionModeTests(unittest.TestCase): + def test_child_umask_modes_preserved_by_cli_rewrite(self) -> None: + with_mode = {"gfx1013.tsv": 0o600, "rdna2.tsv": 0o664, "x64_zen2.tsv": 0o644} + with TemporaryDirectory() as tmp: + root = Path(tmp) + docs = root / "docs" + _populate_docs_dir(docs) + + fresh_dir = root / "fresh" + replaced_dir = root / "replaced" + replaced_dir.mkdir() + for name, mode in with_mode.items(): + stale = replaced_dir / name + stale.write_text("stale\n", encoding="utf-8") + stale.chmod(mode) + for out_dir in (fresh_dir, replaced_dir): + proc = subprocess.run( + [sys.executable, "-B", str(TOOL), str(docs), "--out-dir", str(out_dir)], + capture_output=True, + text=True, + timeout=30, + umask=0o027, + ) + self.assertEqual(proc.returncode, 0, proc.stderr) + + self.assertEqual( + {p.name: p.stat().st_mode & 0o777 for p in fresh_dir.iterdir()}, + {name: 0o640 for name in form_reference.OUTPUT_TSV_NAMES}, + ) + self.assertEqual( + {p.name: p.stat().st_mode & 0o777 for p in replaced_dir.iterdir()}, + with_mode, + ) + for name in form_reference.OUTPUT_TSV_NAMES: + fresh = (fresh_dir / name).read_bytes() + self.assertTrue(fresh.startswith(b"# ")) + self.assertEqual((replaced_dir / name).read_bytes(), fresh) + + class FormReferenceCliNegativeTests(unittest.TestCase): def _assert_exit_1_clean(self, argv: list[str], *, fragment: str, check_subproc: bool = True) -> None: code, out, err = _run_main(argv) diff --git a/tools/form_reference.py b/tools/form_reference.py index f834c03b7..206036022 100644 --- a/tools/form_reference.py +++ b/tools/form_reference.py @@ -11,6 +11,7 @@ import os from pathlib import Path import re +import stat import sys import tempfile @@ -116,7 +117,7 @@ def _validate_out_dir_and_targets(out_dir): def _write_atomic(path, content): - """Write content via a sibling temp file and os.replace, unlinking temp files on error.""" + """Write via a sibling temp file, preserving POSIX output permissions.""" _validate_output_file(path) path.parent.mkdir(parents=True, exist_ok=True) tmp_path = None @@ -132,6 +133,12 @@ def _write_atomic(path, content): ) as handle: tmp_path = Path(handle.name) handle.write(content) + if os.name == "posix": + try: + mode = stat.S_IMODE(path.stat().st_mode) + except FileNotFoundError: + mode = 0o666 & ~_umask() + os.chmod(tmp_path, mode) os.replace(tmp_path, path) except BaseException: if tmp_path is not None: @@ -139,6 +146,13 @@ def _write_atomic(path, content): raise +def _umask(): + # Temporarily restrict permissions rather than relaxing the existing mask. + current = os.umask(0o777) + os.umask(current) + return current + + def write(name, source, forms, out_dir=OUT): body = "".join(f"{g}\t{f}\n" for g, f in sorted(forms)) content = (f"# {len(forms)} forms. Source: {source}. Regenerate: tools/form_reference.py\n" From d0093943a575d684194493c2a4f913310915bafd Mon Sep 17 00:00:00 2001 From: tedin7 <110300616+tedin7@users.noreply.github.com> Date: Thu, 26 Nov 2026 07:06:57 +0100 Subject: [PATCH 160/240] tests, docs: optional per-file fragments for test registration, checks and experiment notes (#2655) * tests, docs: optional per-file fragments for test registration, checks and experiment notes Adds tests/cmake/*.cmake (globbed by CMakeLists.txt), tests/checks//*.txt (read by tools/run_checks_parallel.py --from-dir) and docs/experiments/.md. Nothing existing moves. * fix: keep backslashes in Windows paths when splitting listed check lines * fix: keep quoted option values and spaced temp paths in check lists --- .github/workflows/windows.yml | 7 +- AGENTS.md | 4 +- CMakeLists.txt | 8 ++ CONTRIBUTING.md | 4 +- docs/experiments.md | 2 + docs/experiments/README.md | 9 ++ docs/non-windows-hosts.md | 1 + tests/checks/README.md | 19 ++++ tests/checks/pixel-binary/README.md | 10 ++ .../python-linux/run_checks_fragments.txt | 2 + tests/cmake/README.md | 9 ++ tests/run_checks_fragments_check.py | 100 +++++++++++++++++ tools/run_checks_parallel.py | 104 +++++++++++++++++- 13 files changed, 272 insertions(+), 7 deletions(-) create mode 100644 docs/experiments/README.md create mode 100644 tests/checks/README.md create mode 100644 tests/checks/pixel-binary/README.md create mode 100644 tests/checks/python-linux/run_checks_fragments.txt create mode 100644 tests/cmake/README.md create mode 100644 tests/run_checks_fragments_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index a1ee7367a..85ec0a3d8 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -167,8 +167,10 @@ jobs: (["tests/compute_dpp_row_shr_check.py", *COMMON_LLVM], {}), (["tests/startup_compute_lds_dual_atomics_check.py", "binary", "llvm-mc-15"], {}), ] - sys.exit(runpy.run_path("tools/run_checks_parallel.py", - run_name="run_checks_parallel")["run_checks"](CHECKS)) + runner = runpy.run_path("tools/run_checks_parallel.py", run_name="run_checks_parallel") + # Checks listed in tests/checks/pixel-binary/*.txt run after the inline list. + CHECKS = runner["merge_checks"](CHECKS, "tests/checks/pixel-binary") + sys.exit(runner["run_checks"](CHECKS)) PY python-linux: name: Run platform-independent Python checks on Linux @@ -188,6 +190,7 @@ jobs: - name: Run Python checks run: | python -B tools/run_checks_parallel.py \ + --from-dir tests/checks/python-linux \ tests/script_state_check.py \ tests/resource_root_check.py \ tests/pe_authentihash_check.py \ diff --git a/AGENTS.md b/AGENTS.md index f9549f584..29342a325 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -291,7 +291,9 @@ newer versions may print a different `exp` spelling. | `src/` | Windows runtime shims and shared shader helpers. | | `tools/` | Offline translators, PE/image probes and inventory tools. | | `tests/` | C++, HLSL, MASM and Python fixtures. `tests/cpu/` holds the PE fixtures. | -| `docs/experiments.md` | Measured results, assumptions and reproduction commands. | +| `docs/experiments.md` | Older measured results, assumptions and reproduction commands. New notes go in `docs/experiments/.md`. | +| `tests/cmake/` | One `.cmake` file per test family or pull request, included by `CMakeLists.txt` (see its README). | +| `tests/checks/` | Text files that add Python checks to the Linux CI jobs; see its README. | | `game-files/` | Local inputs; gitignored. Never commit or upload. | | `out/` | Build, generated sources and reports; gitignored. | diff --git a/CMakeLists.txt b/CMakeLists.txt index 36e53d97f..28eb7ad95 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -11244,6 +11244,14 @@ if(EXISTS "${INTAKE_PYTHON}") endforeach() endif() +# Per-family registration fragments (see tests/cmake/README.md). Included after every helper and +# target above and before the slow-test costs below, in name order. A new file re-runs configure. +file(GLOB X2W_TEST_FRAGMENTS CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/tests/cmake/*.cmake") +list(SORT X2W_TEST_FRAGMENTS) +foreach(x2w_fragment IN LISTS X2W_TEST_FRAGMENTS) + include("${x2w_fragment}") +endforeach() + # Start the slowest tests first so the ctest worker pool has no long tail at the end. # COST only changes scheduling order under `ctest --parallel`; no test, argument or assertion changes. # Costs are measured seconds (approx.) from the Windows CI ctest log taken when this list was added diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f960f92a1..c3a2bba76 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -27,7 +27,9 @@ Start with the [first build](README.md#first-build). Create the Python environme | `src/` | Windows runtime implementations and their observable behavior. | | `tests/` | C++, HLSL and generated-input fixtures. Tests ending in `_warp` use the software adapter. Those ending in `_hardware` use a physical GPU. | | `tools/` | Build setup and offline metadata tools. The PE fixtures live in `tests/intake/`. | -| `docs/experiments.md` | Measured results, assumptions and reproduction commands. | +| `docs/experiments.md` | Older measured results, assumptions and reproduction commands. New notes go in `docs/experiments/.md`. | +| `tests/cmake/` | One `.cmake` file per test family or pull request; [CMakeLists.txt](CMakeLists.txt) includes each. See [its README](tests/cmake/README.md). | +| `tests/checks/` | Text files that add Python checks to the Linux CI jobs without editing the workflow. See [its README](tests/checks/README.md). | On pull requests, `Build and test on Windows` builds the smoke-test targets with `cmake --build --preset pr` and runs `ctest --preset pr --no-tests=error`. The preset selects tests for CPU translation, PE startup, memory, archive decoding and WARP rendering, including the SPIR-V bridge checks. The bridge checks can skip locally if their tools are missing; hosted CI installs the pinned tools and requires the WARP bridge checks to pass. For a strict local run, run [the pinned tool setup](tools/setup-spirv-tools.ps1) (`.\tools\setup-spirv-tools.ps1` in PowerShell) before configuring or reconfiguring, then set `$env:X2W_REQUIRE_SPIRV_TOOLS = '1'` before running CTest. Run the tests for your specific change locally and include their results in the PR. diff --git a/docs/experiments.md b/docs/experiments.md index 7faa600b9..e036c4588 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -1,5 +1,7 @@ # Experiment notes and reproduction commands +New notes go in `docs/experiments/.md` (see [the folder guide](experiments/README.md)); this file keeps the older notes. + ## Desktop culling and front-face winding `raster_winding_warp` and `raster_winding_hardware` draw two mirrored triangles diff --git a/docs/experiments/README.md b/docs/experiments/README.md new file mode 100644 index 000000000..5b903b6c2 --- /dev/null +++ b/docs/experiments/README.md @@ -0,0 +1,9 @@ +# Experiment notes, one file per topic + +Write a new experiment note in `docs/experiments/.md` instead of appending to +[docs/experiments.md](../experiments.md), so two pull requests that each add a note do not edit +the same lines. The older notes stay in `docs/experiments.md`. + +A note follows the same rules as before: what was measured, the exact command, the result, the +environment, and what remains a hypothesis. Start the file with a `#` heading. Links in these +files are checked by `tests/docs_links_check.py`, like every tracked Markdown file. diff --git a/docs/non-windows-hosts.md b/docs/non-windows-hosts.md index fe66154ad..e868b1f2d 100644 --- a/docs/non-windows-hosts.md +++ b/docs/non-windows-hosts.md @@ -83,6 +83,7 @@ LLVM_LIB="$LLVM_PREFIX/lib/libLLVM-15.dylib" \ The [CI workflow](../.github/workflows/windows.yml) runs the platform-independent Python suite on Ubuntu 24.04 with Python 3.12 (`python-linux`) and the `gfx1013` machine-code checks on Ubuntu 22.04 with LLVM 15 (`pixel-binary`). Both jobs use `tools/run_checks_parallel.py`; the machine-code matrix supplies per-check LLVM arguments and environment overrides. +Besides the inline lists, both jobs also run the checks listed in `tests/checks/python-linux/*.txt` and `tests/checks/pixel-binary/*.txt` (`--from-dir`); a new check can go in its own file there, see [tests/checks/README.md](../tests/checks/README.md). The runner lists checks that exit 77 under `SKIPPED:` and other nonzero exits under `FAILED:`. Either summary makes the runner exit 1 so CI catches required checks that did not run. Open a skipped check's log group to see its output. On Debian/Ubuntu, install `python3-venv` first. Without it, `python3 -m venv` fails with `ensurepip is not available`: diff --git a/tests/checks/README.md b/tests/checks/README.md new file mode 100644 index 000000000..fc370f1e2 --- /dev/null +++ b/tests/checks/README.md @@ -0,0 +1,19 @@ +# CI check lists + +The inline lists in `.github/workflows/windows.yml` stay as they are. A new Python check can +instead go in a small text file here, so two pull requests that each add a check do not edit +the same lines. + +| Directory | Read by | One line holds | +|---|---|---| +| `python-linux/*.txt` | the `Run Python checks` step of the `python-linux` job | a script path, for example `tests/my_check.py` | +| `pixel-binary/*.txt` | the machine-code step of the `pixel-binary` job | a script path and its arguments, for example `tests/my_check.py binary llvm-mc-15` | + +Rules, enforced by `tools/run_checks_parallel.py`: + +- Use one file per topic or pull request, for example `python-linux/my_topic.txt`. +- Blank lines and lines starting with `#` are ignored. Files are read in name order. +- A script that does not exist, or a command listed twice across the files, fails the job. +- A command that is also in the inline list runs once. + +Windows jobs register their tests with CTest instead: see [tests/cmake](../cmake/README.md). diff --git a/tests/checks/pixel-binary/README.md b/tests/checks/pixel-binary/README.md new file mode 100644 index 000000000..3c1493c48 --- /dev/null +++ b/tests/checks/pixel-binary/README.md @@ -0,0 +1,10 @@ +# pixel-binary check lists + +Put one `.txt` file here for a check that needs LLVM 15. Each line is a script path plus +its arguments, written out in full (the inline `COMMON_LLVM` shortcut is not available here): + +``` +tests/my_check.py binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 +``` + +See [the check list rules](../README.md). diff --git a/tests/checks/python-linux/run_checks_fragments.txt b/tests/checks/python-linux/run_checks_fragments.txt new file mode 100644 index 000000000..1d836f9de --- /dev/null +++ b/tests/checks/python-linux/run_checks_fragments.txt @@ -0,0 +1,2 @@ +# Read by `tools/run_checks_parallel.py --from-dir tests/checks/python-linux` (see README.md). +tests/run_checks_fragments_check.py diff --git a/tests/cmake/README.md b/tests/cmake/README.md new file mode 100644 index 000000000..4800fd947 --- /dev/null +++ b/tests/cmake/README.md @@ -0,0 +1,9 @@ +# CTest registration fragments + +Every `tests/cmake/*.cmake` file is included by `CMakeLists.txt` after the existing test +registrations (in name order, and a new file triggers a re-configure). Put new `add_test` and +`set_tests_properties` calls for a family in `tests/cmake/.cmake`, one file per family +or pull request, so two pull requests do not edit the same lines of `CMakeLists.txt`. A +fragment sees the targets, the `INTAKE_PYTHON` variable and the `add_test` wrapper defined above +it, and can set a `COST` property for a test that is not in `X2W_SLOW_TEST_COSTS`. Existing +registrations stay where they are. diff --git a/tests/run_checks_fragments_check.py b/tests/run_checks_fragments_check.py new file mode 100644 index 000000000..cb1983bcf --- /dev/null +++ b/tests/run_checks_fragments_check.py @@ -0,0 +1,100 @@ +"""The parallel check runner also runs the checks listed in a directory of text files.""" +import os +import runpy +import subprocess +import sys +import tempfile + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +RUNNER = os.path.join(ROOT, "tools", "run_checks_parallel.py") + + +def run(*args): + return subprocess.run([sys.executable, "-B", RUNNER, "-j", "2", *args], + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) + + +def q(path): + """Quote a path for a listing line so a directory with spaces stays one word.""" + return '"' + path + '"' + + +def write(path, text): + with open(path, "w", encoding="utf-8") as handle: + handle.write(text) + + +with tempfile.TemporaryDirectory(prefix="x2w frag ") as tmp: + echo = os.path.join(tmp, "echo.py") + write(echo, "import sys\nprint('echo ran', *sys.argv[1:])\n") + lists = os.path.join(tmp, "lists") + os.mkdir(lists) + + # Files are read in name order; comments, blank lines and README files are ignored; a line may + # carry arguments; a command also given on the command line runs once. + write(os.path.join(lists, "b.txt"), f"# note\n\n{q(echo)} second\n") + write(os.path.join(lists, "a.txt"), f"{q(echo)} first\n{q(echo)}\n") + write(os.path.join(lists, "README.md"), f"{q(echo)} never\n") + ok = run("--from-dir", lists, echo) + assert ok.returncode == 0, ok.stdout + assert "all 3 checks passed" in ok.stdout, ok.stdout + assert ok.stdout.index("echo ran first") < ok.stdout.index("echo ran second"), ok.stdout + assert "never" not in ok.stdout, ok.stdout + + # The directory alone is enough, and an empty directory is a plain empty run. + only = run("--from-dir", lists) + assert only.returncode == 0 and "all 3 checks passed" in only.stdout, only.stdout + empty = os.path.join(tmp, "empty") + os.mkdir(empty) + assert run("--from-dir", empty).returncode == 0 + + # A listed failure fails the run like an inline one. + bad = os.path.join(tmp, "bad.py") + write(bad, "import sys\nsys.exit(3)\n") + bad_dir = os.path.join(tmp, "bad_dir") + os.mkdir(bad_dir) + write(os.path.join(bad_dir, "x.txt"), q(bad) + "\n") + failed = run("--from-dir", bad_dir) + assert failed.returncode == 1 and "FAILED: " + bad in failed.stdout, failed.stdout + + # Loud refusals: missing directory, missing script, duplicate, bad quoting, nothing to run. + missing_dir = run("--from-dir", os.path.join(tmp, "nope")) + assert missing_dir.returncode == 1 and "does not exist" in missing_dir.stdout, missing_dir.stdout + for name, body, needle in ( + ("missing", q(os.path.join(tmp, "gone.py")) + "\n", "x.txt:1"), + ("dup", f"{q(echo)} a\n{q(echo)} a\n", "duplicate of"), + ("quote", f"{q(echo)} 'a\n", "x.txt:1"), + ): + bad_list = os.path.join(tmp, "case_" + name) + os.mkdir(bad_list) + write(os.path.join(bad_list, "x.txt"), body) + refused = run("--from-dir", bad_list) + assert refused.returncode == 1 and needle in refused.stdout, (name, refused.stdout) + assert "echo ran" not in refused.stdout, (name, refused.stdout) + # The same command in two files is a duplicate too. + two = os.path.join(tmp, "case_two") + os.mkdir(two) + write(os.path.join(two, "a.txt"), f"{q(echo)}\n") + write(os.path.join(two, "b.txt"), f"{q(echo)}\n") + twice = run("--from-dir", two) + assert twice.returncode == 1 and "b.txt:1" in twice.stdout and "duplicate" in twice.stdout, twice.stdout + assert run().returncode == 2 + +# On Windows a listed path keeps its backslashes and quoted words lose their quotes; POSIX +# splitting would eat the backslashes (`C:\x2w\a.py` -> `C:x2wa.py`). +split = runpy.run_path(RUNNER)["split_command"] +assert split(r'C:\x2w\tests\a.py "b c" d', windows=True) == [r"C:\x2w\tests\a.py", "b c", "d"] +assert split(r'a.py --llvm="C:\Program Files\LLVM\x.dll" ""', windows=True) == [ + "a.py", r"--llvm=C:\Program Files\LLVM\x.dll", ""] +assert split('a.py --llvm="/opt/my llvm/x.so"', windows=False) == ["a.py", "--llvm=/opt/my llvm/x.so"] +assert split("tests/a.py 'b c' d", windows=False) == ["tests/a.py", "b c", "d"] + +# The lists committed to the repository only name scripts that exist, so CI cannot lose one. +for sub in ("python-linux", "pixel-binary"): + found = subprocess.run([sys.executable, "-B", "-c", + "import runpy,sys;r=runpy.run_path(sys.argv[1]);" + "print(len(r['read_check_files'](sys.argv[2])))", + RUNNER, os.path.join(ROOT, "tests", "checks", sub)], + cwd=ROOT, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) + assert found.returncode == 0, found.stdout +print("run_checks_fragments_check ok") diff --git a/tools/run_checks_parallel.py b/tools/run_checks_parallel.py index c6703aa63..d2fbffb12 100644 --- a/tools/run_checks_parallel.py +++ b/tools/run_checks_parallel.py @@ -1,7 +1,11 @@ """Run independent Python check scripts side by side and fail if any of them fails. Usage: - python tools/run_checks_parallel.py [-j N] tests/a_check.py tests/b_check.py ... + python tools/run_checks_parallel.py [-j N] [--from-dir DIR] tests/a_check.py tests/b_check.py ... + +`--from-dir DIR` also runs the commands listed in `DIR/*.txt` (see `read_check_files`), after +the scripts given on the command line. `merge_checks(inline, directory)` does the same for +the pairs passed to `run_checks`. Each script runs as `python -B