From 51fc8e0b13acad07cd05032d9d0cf2abe75f4e1f Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Thu, 26 Nov 2026 01:28:44 +0200 Subject: [PATCH 01/54] 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 02/54] 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 03/54] 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 04/54] 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 05/54] 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 06/54] 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 07/54] 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 08/54] 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 09/54] 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 10/54] 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 11/54] 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 12/54] 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 13/54] 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 14/54] 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 15/54] 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 16/54] 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 17/54] 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 18/54] 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 19/54] 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 20/54] 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 21/54] 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 22/54] 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 23/54] 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 24/54] 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 25/54] 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 26/54] 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 27/54] 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 28/54] 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 29/54] 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 30/54] 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 31/54] 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 32/54] 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 33/54] 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 34/54] 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 35/54] 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 36/54] 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 37/54] 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 38/54] 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 39/54] 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 40/54] 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 41/54] 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 42/54] 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 43/54] 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 44/54] 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 45/54] 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 46/54] 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 47/54] 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 48/54] 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 49/54] 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 50/54] 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 ea04dcedd050500aceb14bb20ca2c2505416836b Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 26 Nov 2026 00:04:15 +0000 Subject: [PATCH 51/54] 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 --- .github/workflows/windows.yml | 1 + AGENTS.md | 1 + CMakeLists.txt | 3 + tests/startup_gfx2hlsl_s_flbit_check.py | 151 ++++++++++++++++++++++++ tools/startup/gfx2hlsl.py | 37 ++++++ 5 files changed, 193 insertions(+) create mode 100644 tests/startup_gfx2hlsl_s_flbit_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 0a36fcd1a..ca6a38e69 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -299,6 +299,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 b7eb67ad7..7d8380330 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 68a025209..8f31d7ac9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3319,6 +3319,9 @@ 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 and refusals. + add_test(NAME startup_gfx2hlsl_s_flbit COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_flbit_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/tests/startup_gfx2hlsl_s_flbit_check.py b/tests/startup_gfx2hlsl_s_flbit_check.py new file mode 100644 index 000000000..dbe002619 --- /dev/null +++ b/tests/startup_gfx2hlsl_s_flbit_check.py @@ -0,0 +1,151 @@ +"""s_flbit_i32_b32 in tools/startup/gfx2hlsl.py (#1723). + +usage: startup_gfx2hlsl_s_flbit_check.py + +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. +""" +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, 0x00000001, 0x80000000, 0xffffffff, 0x00010020, 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(' 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') diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 1c20f5c68..e923c8ed6 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 946110c901c0085f060bb8aa7cb306775ab55223 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 26 Nov 2026 00:04:25 +0000 Subject: [PATCH 52/54] docs: note s_flbit_i32_b32 startup lowering (#1723) Co-authored-by: SimSalabimse --- docs/experiments.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/docs/experiments.md b/docs/experiments.md index 38fa8d0ff..72125d70c 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -8116,6 +8116,15 @@ 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 fixture is +CPU-only; Windows WARP/hardware draws are left for an independent retest. +[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 From 0e1071d621fd5101ee4d3d4d6131ad154c217766 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 26 Nov 2026 00:22:28 +0000 Subject: [PATCH 53/54] 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 --- CMakeLists.txt | 10 +- tests/startup_gfx2hlsl_s_flbit_check.py | 210 ++++++++++++++++-------- 2 files changed, 153 insertions(+), 67 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 8f31d7ac9..0da46240d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3319,9 +3319,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 and refusals. + # 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/tests/startup_gfx2hlsl_s_flbit_check.py b/tests/startup_gfx2hlsl_s_flbit_check.py index dbe002619..ee0b67850 100644 --- a/tests/startup_gfx2hlsl_s_flbit_check.py +++ b/tests/startup_gfx2hlsl_s_flbit_check.py @@ -1,15 +1,23 @@ """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 @@ -23,6 +31,7 @@ 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 @@ -77,75 +86,144 @@ def run(lines, env): return env -bad = None -lines, _ = translate(sop1('s_flbit_i32_b32', 3, 1)) -assert lines and not lines[0].startswith('refused'), lines -for word in WORDS: - out = run(lines, {'s1': word, 'scc': SCC_UNSET}) - want = (ref_flbit(word), SCC_UNSET) - if (out['s3'], out['scc']) != want: - bad = (hex(word), (out['s3'], out['scc']), want) - break -check('s_flbit_i32_b32 SGPR source', bad is None, str(bad)) +def controls(): + bad = None + lines, _ = translate(sop1('s_flbit_i32_b32', 3, 1)) + assert lines and not lines[0].startswith('refused'), lines + for word in WORDS: + out = run(lines, {'s1': word, 'scc': SCC_UNSET}) + want = (ref_flbit(word), SCC_UNSET) + if (out['s3'], out['scc']) != want: + bad = (hex(word), (out['s3'], out['scc']), want) + break + check('s_flbit_i32_b32 SGPR source', bad is None, str(bad)) + + bad = None + for word in WORDS: + stage = Probe() + try: + stage.one('s_flbit_i32_b32', 's_flbit_i32_b32 s3, %d' % word) + except G.Unsupported as error: + bad = ('refused %s' % error,) + break + out = run(stage.lines, {'scc': SCC_UNSET}) + want = (ref_flbit(word), SCC_UNSET) + if (out['s3'], out['scc']) != want: + bad = (hex(word), (out['s3'], out['scc']), want) + break + check('s_flbit_i32_b32 immediate source', bad is None, str(bad)) + + lines, sym = translate(sop1('s_flbit_i32_b32', 3, 1), sym={1: ('const', 0x10)}) + # 0x10 bit_length=5 -> 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)) -bad = None -for word in WORDS: stage = Probe() + stage.masks.add(1) try: - stage.one('s_flbit_i32_b32', 's_flbit_i32_b32 s3, %d' % word) + 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: - bad = ('refused %s' % error,) - break - out = run(stage.lines, {'scc': SCC_UNSET}) - want = (ref_flbit(word), SCC_UNSET) - if (out['s3'], out['scc']) != want: - bad = (hex(word), (out['s3'], out['scc']), want) - break -check('s_flbit_i32_b32 immediate source', bad is None, str(bad)) - -lines, sym = translate(sop1('s_flbit_i32_b32', 3, 1), sym={1: ('const', 0x10)}) -# 0x10 bit_length=5 -> 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)) + 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 = 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') - 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') + 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__) From 716001d8d0f0314a4dcfc9a821be4ec6b4f90c6c Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 26 Nov 2026 00:22:33 +0000 Subject: [PATCH 54/54] docs: note s_flbit_i32_b32 WARP dispatch ctest Document the UAV-readback filter next to the CPU-only command. Co-authored-by: SimSalabimse --- docs/experiments.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 72125d70c..39982aa9d 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -8121,8 +8121,11 @@ CPU-only; Windows WARP/hardware draws are left for an independent retest. `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 fixture is -CPU-only; Windows WARP/hardware draws are left for an independent retest. +(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