upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDadaCap <167002618+DadaCap@users.noreply.github.com>2026-11-24 21:09:02 +0100
committerDadaCap <167002618+DadaCap@users.noreply.github.com>2026-11-24 21:09:02 +0100
commitbc245e5046124941bbdc7bb5c3bd7c739da4e03e (patch)
tree5b780fbcbc1dd131ee635980dfe3e996ac72928f
parent30450e0e96e1df700bbfa9505433c9b9940e8694 (diff)
parent58be9cdf8df9a31bc7f6c068991f1aed381f7f4d (diff)
Merge remote-tracking branch 'origin/main' into vcc-tuple-resync
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
-rw-r--r--.github/workflows/runtime.yml15
-rw-r--r--AGENTS.md6
-rw-r--r--README.md28
-rw-r--r--docs/README.md4
-rw-r--r--docs/boot.md48
-rw-r--r--docs/boot_leads.md108
-rw-r--r--docs/d3d12_vulkan.md81
-rw-r--r--docs/design.md29
-rw-r--r--docs/gpu_test_results.md1
-rw-r--r--docs/multi_gpu_validation.md8
-rw-r--r--docs/progress_dashboard.md16
-rw-r--r--docs/related_projects.md6
-rw-r--r--docs/retail_boot_chain.md6
-rw-r--r--docs/runtime_imports.md76
-rw-r--r--docs/shader_library.md34
-rw-r--r--docs/shader_validation.md3
-rw-r--r--docs/testing.md43
-rw-r--r--docs/textures.md38
-rw-r--r--docs/world_census.md15
-rw-r--r--gpu-test-results/GraniteRidge-9950X3D.txt31
-rw-r--r--gpu-test-results/RTX2060SUPER.txt56
-rw-r--r--gpu-test-results/RTX3060Ti-Windows.txt55
-rw-r--r--gpu-test-results/RTX3080Ti-61692.txt46
-rw-r--r--gpu-test-results/RTX4060-Nobara-three-tests.txt49
-rw-r--r--gpu-test-results/RTX4070.txt24
-rw-r--r--gpu-test-results/RTX4080.txt29
-rw-r--r--gpu-test-results/RTX5090.txt31
-rw-r--r--gpu-test-results/RX5700XT.txt38
-rw-r--r--make_game.py44
-rw-r--r--runtime/CMakeLists.txt88
-rw-r--r--runtime/cmake/translator_deps.cmake9
-rw-r--r--runtime/shims/acphal.cpp873
-rw-r--r--runtime/shims/d3d12_com.h4
-rw-r--r--runtime/shims/d3d12_vulkan_device.cpp65
-rw-r--r--runtime/shims/d3d12_xs_device.cpp188
-rw-r--r--runtime/shims/d3d12_xs_device.h18
-rw-r--r--runtime/shims/library_loader.cpp2
-rw-r--r--runtime/shims/registry.cpp3
-rw-r--r--runtime/shims/ws2_offline.cpp949
-rw-r--r--runtime/shims/xbox_present.cpp57
-rw-r--r--runtime/shims/xbox_present.h13
-rw-r--r--runtime/shims/xgameruntime_offline.cpp144
-rw-r--r--runtime/src/cpu_emulation.h97
-rw-r--r--runtime/src/frame_pacer.h224
-rw-r--r--runtime/src/gfx10_descriptors.h6
-rw-r--r--runtime/src/mods.h4
-rw-r--r--runtime/src/retire_tickets.h16
-rw-r--r--runtime/src/shader_library.h23
-rw-r--r--runtime/src/statistics_sum.comp10
-rw-r--r--runtime/src/statistics_sum_spirv.h65
-rw-r--r--runtime/src/vulkan_backend.h97
-rw-r--r--runtime/src/vulkan_replay.h130
-rw-r--r--runtime/src/vulkan_scratch.h16
-rw-r--r--runtime/src/xdxr_build.h14
-rw-r--r--runtime/src/xdxr_descs.h7
-rw-r--r--runtime/test/acphal_test.cpp628
-rw-r--r--runtime/test/check_sparse_queue_family.py138
-rw-r--r--runtime/test/cpu_emulation_test.cpp77
-rw-r--r--runtime/test/d3d12_clear_test.cpp42
-rw-r--r--runtime/test/d3d12_dxr_validation_test.cpp26
-rw-r--r--runtime/test/d3d12_mesh_test.cpp31
-rw-r--r--runtime/test/d3d12_pipeline_library_host_test.cpp10
-rw-r--r--runtime/test/d3d12_pipeline_library_test.cpp9
-rw-r--r--runtime/test/d3d12_state_map_test.cpp8
-rw-r--r--runtime/test/d3d12_vulkan_device_test.cpp6
-rw-r--r--runtime/test/frame_pacer_test.cpp149
-rw-r--r--runtime/test/gfx10_descriptors_test.cpp13
-rw-r--r--runtime/test/loader_tls_test.cpp3
-rw-r--r--runtime/test/mods_test.cpp5
-rw-r--r--runtime/test/replay_copy_offset_test.cpp97
-rw-r--r--runtime/test/replay_query_edges_test.cpp90
-rw-r--r--runtime/test/replay_query_predication_test.cpp25
-rw-r--r--runtime/test/replay_uav_clear_offset_test.cpp12
-rw-r--r--runtime/test/retire_tickets_test.cpp18
-rw-r--r--runtime/test/shader_library_test.cpp9
-rw-r--r--runtime/test/shaders/build.py5
-rw-r--r--runtime/test/shaders/check.py42
-rw-r--r--runtime/test/shaders/cs_div_fmas_f64.asm3
-rw-r--r--runtime/test/shaders/cs_div_fmas_f64_rt.asm18
-rw-r--r--runtime/test/shaders/cs_imgatomic_ext.asm313
-rw-r--r--runtime/test/shaders/cs_imgload_d16_tfe.asm16
-rw-r--r--runtime/test/shaders/cs_imgload_tfe.asm19
-rw-r--r--runtime/test/shaders/cs_imgstore_cube.asm95
-rw-r--r--runtime/test/shaders/cs_w32_lds_subdword.asm7
-rw-r--r--runtime/test/shaders/cs_w32_shift64.asm29
-rw-r--r--runtime/test/shaders/mullit_readback.py122
-rw-r--r--runtime/test/vk_command_replay_test.cpp77
-rw-r--r--runtime/test/vk_compute_test.cpp26
-rw-r--r--runtime/test/vk_host_at_aliasing_test.cpp257
-rw-r--r--runtime/test/vk_queue_test.cpp59
-rw-r--r--runtime/test/vk_store_test.cpp110
-rw-r--r--runtime/test/vk_test_device.h11
-rw-r--r--runtime/test/vulkan_scratch_test.cpp21
-rw-r--r--runtime/test/ws2_offline_test.cpp547
-rw-r--r--runtime/test/xdxr_builder_validation_test.cpp183
-rw-r--r--runtime/test/xdxr_descs_test.cpp13
-rw-r--r--runtime/test/xgameruntime_offline_test.cpp83
-rw-r--r--runtime/test/xs_proxy_mock_test.cpp174
-rw-r--r--runtime/xma_decoder/README.md11
-rw-r--r--runtime/xma_decoder/leonida_xma2_decoder.h4
-rw-r--r--runtime/xma_decoder/src/lib.rs51
-rw-r--r--runtime/xma_decoder/tests/ffi_contract.rs22
-rw-r--r--scripts/build_runtime.ps14
-rw-r--r--scripts/check_no_game_data.py20
-rw-r--r--scripts/ci_expected_failures.py18
-rw-r--r--scripts/merge_check.py7
-rw-r--r--scripts/run_gpu_tests.py28
-rw-r--r--scripts/run_semantic_tests.py68
-rw-r--r--tests/semantic/README.md2
-rw-r--r--tests/semantic/f16_unary_cases.py6
-rw-r--r--tests/semantic/f64_translate.py43
-rw-r--r--tests/semantic/fixtures/disasm/cs_w32_lds_subdword.s4
-rw-r--r--tests/semantic/spirv_mini_interp.py35
-rw-r--r--tests/semantic/test_alu_div_fixup_f32.py33
-rw-r--r--tests/semantic/test_alu_f32_min_max.py9
-rw-r--r--tests/semantic/test_alu_min3_max3.py15
-rw-r--r--tests/semantic/test_alu_vop3_mods_hw.py3
-rw-r--r--tests/semantic/test_fma_khr_f64.py3
-rw-r--r--tests/semantic/test_mini_interp_f64.py112
-rw-r--r--tests/semantic/test_salu_scc_value.py116
-rw-r--r--tests/semantic/test_sload_vcc_base.py171
-rw-r--r--tests/semantic/test_sopc_validation.py151
-rw-r--r--tests/semantic/test_store_liveins.py18
-rw-r--r--tests/semantic/test_unary_f16_validation.py193
-rw-r--r--tests/semantic/test_valu_cvt_f32_f64.py33
-rw-r--r--tests/semantic/test_valu_f32_min3_max3_mad.py4
-rw-r--r--tests/semantic/test_valu_frexp_exp_i32_f64.py42
-rw-r--r--tests/semantic/test_valu_frexp_f64.py67
-rw-r--r--tests/semantic/test_valu_frexp_mant_f64.py61
-rw-r--r--tests/semantic/test_valu_rcp_f64.py34
-rw-r--r--tests/semantic/test_valu_rsq_f64.py34
-rw-r--r--tests/semantic/test_valu_sqrt_f64.py35
-rw-r--r--tests/semantic/test_vop3_clamp_nan.py137
-rw-r--r--tests/semantic/test_writelane_read_before_write.py82
-rw-r--r--tests/spirv_interp.py11
-rw-r--r--tests/test_awc_manifest.py2
-rw-r--r--tests/test_batch_glb.py25
-rw-r--r--tests/test_bink_play_cache_write.py87
-rw-r--r--tests/test_boot_trace.py50
-rw-r--r--tests/test_bvh_shaders_stage.py2
-rw-r--r--tests/test_check_no_game_data.py33
-rw-r--r--tests/test_check_sparse_queue_family.py190
-rw-r--r--tests/test_ci_expected_failures.py17
-rw-r--r--tests/test_cmake_translator_deps.py14
-rw-r--r--tests/test_d3d12_xs_surface.py27
-rw-r--r--tests/test_f64_conversion.py3
-rw-r--r--tests/test_fspx_shaders_stage.py4
-rw-r--r--tests/test_fssm_unpack.py55
-rw-r--r--tests/test_gallery.py36
-rw-r--r--tests/test_gpu_shift64.py96
-rw-r--r--tests/test_guest_scene_reference.py4
-rw-r--r--tests/test_hw_oracle_workdir_leak.py162
-rw-r--r--tests/test_make_game_destinations.py71
-rw-r--r--tests/test_make_game_pipelines.py5
-rw-r--r--tests/test_make_game_translator_flags.py2
-rw-r--r--tests/test_manifest_verifier.py107
-rw-r--r--tests/test_merge_check.py35
-rw-r--r--tests/test_native_pso_hashes.py149
-rw-r--r--tests/test_native_tool_paths.py10
-rw-r--r--tests/test_navmesh_nodes.py2
-rw-r--r--tests/test_progress_dashboard.py16
-rw-r--r--tests/test_rcp_iflag_mods.py3
-rw-r--r--tests/test_rpf9dump_exit_codes.py12
-rw-r--r--tests/test_run_gpu_tests_python_assembler.py39
-rw-r--r--tests/test_run_semantic_tests.py49
-rw-r--r--tests/test_semantic_mutants.py127
-rw-r--r--tests/test_semantic_translator_use.py34
-rw-r--r--tests/test_shader_build_fallbacks.py5
-rw-r--r--tests/test_shader_checks.py21
-rw-r--r--tests/test_shader_stage_resume.py46
-rw-r--r--tests/test_spirv_asm.py43
-rw-r--r--tests/test_stale_build.py143
-rw-r--r--tests/test_stale_build_include_dirs.py109
-rw-r--r--tests/test_user_sgpr_census.py10
-rw-r--r--tests/test_viewer_studio.cjs32
-rw-r--r--tests/test_vk_fuzz_run.py29
-rw-r--r--third_party/xma/NOTICE.md2
-rw-r--r--tools/batch_glb.py5
-rw-r--r--tools/bink_play.py17
-rw-r--r--tools/boot_trace.py45
-rw-r--r--tools/d3d12_xs_surface.py6
-rw-r--r--tools/exe_sha.py1
-rw-r--r--tools/fssm_unpack.py32
-rw-r--r--tools/gallery.py3
-rw-r--r--tools/hw_oracle/drm.py24
-rw-r--r--tools/hw_oracle/runner.py14
-rw-r--r--tools/manifest_verifier.py9
-rw-r--r--tools/native_pso_hashes.py122
-rw-r--r--tools/pr_conflict_label.py1
-rw-r--r--tools/progress_dashboard.py5
-rw-r--r--tools/rdna2spirv.py58
-rw-r--r--tools/semantic_mutants.py227
-rw-r--r--tools/shader_stage_manifest.py23
-rw-r--r--tools/spirv_asm.py6
-rw-r--r--tools/spirv_asm_tables.py48
-rw-r--r--tools/stale_build.py32
-rw-r--r--tools/vk_fuzz_run.py20
-rw-r--r--viewer/studio.html8
198 files changed, 10984 insertions, 1033 deletions
diff --git a/.github/workflows/runtime.yml b/.github/workflows/runtime.yml
index 004d5a692..5514452c0 100644
--- a/.github/workflows/runtime.yml
+++ b/.github/workflows/runtime.yml
@@ -35,12 +35,15 @@ on:
35 - "tools/lane_masks.py" 35 - "tools/lane_masks.py"
36 - "tools/mc_command.py" 36 - "tools/mc_command.py"
37 - "tools/mesh_compute_vs.py" 37 - "tools/mesh_compute_vs.py"
38 - "tools/native_pso_hashes.py"
38 - "tools/rdna2_decode.py" 39 - "tools/rdna2_decode.py"
39 - "tools/rdna2_isa_tables.py" 40 - "tools/rdna2_isa_tables.py"
40 - "tools/rdna2spirv.py" 41 - "tools/rdna2spirv.py"
41 - "tools/replace_retry.py" 42 - "tools/replace_retry.py"
42 - "tools/report_paths.py" 43 - "tools/report_paths.py"
43 - "tools/shader_carve.py" 44 - "tools/shader_carve.py"
45 - "tools/shader_carve_accel.py"
46 - "tools/shader_carve_native/**"
44 - "tools/shader_disasm.py" 47 - "tools/shader_disasm.py"
45 - "tools/shader_ir.py" 48 - "tools/shader_ir.py"
46 - "tools/shader_meta.py" 49 - "tools/shader_meta.py"
@@ -77,12 +80,15 @@ on:
77 - "tools/lane_masks.py" 80 - "tools/lane_masks.py"
78 - "tools/mc_command.py" 81 - "tools/mc_command.py"
79 - "tools/mesh_compute_vs.py" 82 - "tools/mesh_compute_vs.py"
83 - "tools/native_pso_hashes.py"
80 - "tools/rdna2_decode.py" 84 - "tools/rdna2_decode.py"
81 - "tools/rdna2_isa_tables.py" 85 - "tools/rdna2_isa_tables.py"
82 - "tools/rdna2spirv.py" 86 - "tools/rdna2spirv.py"
83 - "tools/replace_retry.py" 87 - "tools/replace_retry.py"
84 - "tools/report_paths.py" 88 - "tools/report_paths.py"
85 - "tools/shader_carve.py" 89 - "tools/shader_carve.py"
90 - "tools/shader_carve_accel.py"
91 - "tools/shader_carve_native/**"
86 - "tools/shader_disasm.py" 92 - "tools/shader_disasm.py"
87 - "tools/shader_ir.py" 93 - "tools/shader_ir.py"
88 - "tools/shader_meta.py" 94 - "tools/shader_meta.py"
@@ -108,7 +114,9 @@ concurrency:
108jobs: 114jobs:
109 windows: 115 windows:
110 runs-on: windows-latest 116 runs-on: windows-latest
111 timeout-minutes: 20 117 # A build with a cold sccache took 18.3 min (main, 24 Nov), which left a 20-minute job under 2 min for the
118 # whole ctest run. The ctest step bounds each test on its own, so a hung test no longer needs this to stop it.
119 timeout-minutes: 35
112 outputs: 120 outputs:
113 wine-artifact: ${{ steps.upload-wine-artifact.outcome }} 121 wine-artifact: ${{ steps.upload-wine-artifact.outcome }}
114 env: 122 env:
@@ -249,6 +257,7 @@ jobs:
249 -DCMAKE_BUILD_TYPE=RelWithDebInfo 257 -DCMAKE_BUILD_TYPE=RelWithDebInfo
250 -DLEONIDA_D3D12_SHIM_TESTS=ON 258 -DLEONIDA_D3D12_SHIM_TESTS=ON
251 -DLEONIDA_REQUIRE_VULKAN=ON 259 -DLEONIDA_REQUIRE_VULKAN=ON
260 -DLEONIDA_REQUIRE_XMA2_DECODER=ON
252 -DCMAKE_CXX_COMPILER_LAUNCHER=sccache 261 -DCMAKE_CXX_COMPILER_LAUNCHER=sccache
253 -DCMAKE_POLICY_DEFAULT_CMP0141=NEW 262 -DCMAKE_POLICY_DEFAULT_CMP0141=NEW
254 -DCMAKE_MSVC_DEBUG_INFORMATION_FORMAT=Embedded 263 -DCMAKE_MSVC_DEBUG_INFORMATION_FORMAT=Embedded
@@ -294,8 +303,10 @@ jobs:
294 runtime/build/windows-root.txt 303 runtime/build/windows-root.txt
295 retention-days: 7 304 retention-days: 7
296 if-no-files-found: error 305 if-no-files-found: error
306 # --timeout: a test without a TIMEOUT of its own fails after 5 min instead of the CTest default of 25, which
307 # is longer than the job. The slowest on Linux and macOS (xdxr_build_check) takes 50 and 106 s.
297 - name: CPU runtime tests 308 - name: CPU runtime tests
298 run: ctest --test-dir runtime/build --output-on-failure 309 run: ctest --test-dir runtime/build --output-on-failure --timeout 300
299 310
300 # Runs the Windows build's tests under Wine, so a change that breaks the loader on Linux (through Wine or Proton) 311 # Runs the Windows build's tests under Wine, so a change that breaks the loader on Linux (through Wine or Proton)
301 # shows up. The required ones are the loader and the stand-in game run end to end; the table in the job summary 312 # shows up. The required ones are the loader and the stand-in game run end to end; the table in the job summary
diff --git a/AGENTS.md b/AGENTS.md
index 11f868540..d6788158e 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -70,9 +70,9 @@ loader that maps the game's executable and resolves its imports to shims. Nothin
70 70
71## Test without the game first 71## Test without the game first
72 72
73None of these need game files. Most run in seconds - the translator suite takes a few minutes (433 files and 5 821 73None of these need game files. Most run in seconds - the translator suite takes a few minutes (465 files and 6 108
74tests in 224 s on 16 cores) and the two builds longer - so run one translator test file while you iterate and the 74tests in 297 s on 16 cores on Windows 11) and the two builds longer - so run one translator test file while you
75whole suite once before the pull request: 75iterate and the whole suite once before the pull request:
76 76
77```powershell 77```powershell
78python -m compileall -q make_game.py tools tests 78python -m compileall -q make_game.py tools tests
diff --git a/README.md b/README.md
index c423a2a42..da7408d8c 100644
--- a/README.md
+++ b/README.md
@@ -20,7 +20,8 @@
20 <a href="#want-to-help">Want to help?</a> | 20 <a href="#want-to-help">Want to help?</a> |
21 <a href="#credits">Credits</a> | 21 <a href="#credits">Credits</a> |
22 <a href="#license">License</a> | 22 <a href="#license">License</a> |
23 <a href="https://discord.gg/ETf4qj5acN">Discord</a> 23 <a href="https://discord.gg/ETf4qj5acN">Discord</a> |
24 <a href="https://t.me/mandyport">Telegram</a>
24</p> 25</p>
25 26
26Leonida is a static recompilation project. The Xbox Series CPU is x86-64 like a PC, so the game's code is loaded 27Leonida is a static recompilation project. The Xbox Series CPU is x86-64 like a PC, so the game's code is loaded
@@ -41,6 +42,8 @@ happens **on your PC, from your own copy of the game**.
41 42
42Discord: https://discord.gg/ETf4qj5acN 43Discord: https://discord.gg/ETf4qj5acN
43 44
45Telegram: https://t.me/mandyport
46
44Original author's Git Mirror: https://git.notrexed.dev/notrexed/Leonida 47Original author's Git Mirror: https://git.notrexed.dev/notrexed/Leonida
45<br> 48<br>
46 49
@@ -138,6 +141,29 @@ files in `work/shaders/dxbc/disasm` in place: the next run checks them against t
138disassembles the missing ones again (all of them for a folder whose `disasm.done` predates that list), then 141disassembles the missing ones again (all of them for a folder whose `disasm.done` predates that list), then
139translates every shader again. A `disasm` folder that is a symlink is refused when the stage has to clear it. 142translates every shader again. A `disasm` folder that is a symlink is refused when the stage has to clear it.
140 143
144**Disk space and drives:** the build uses three folders, and each can be on its own drive:
145
146| Folder | Flag | What is in it | Size | Read when playing |
147|---|---|---|---|---|
148| your package | `--game` | your copy of the game; only read, never written | as copied | yes, in place (`game_path.txt`) |
149| work | `--work` (default `<out>\work`) | `shaders` (carved, disassembled, translated) and `assets` (exports) | about 30 GB + about 370 GB | only `shaders\spirv` (`shader_path.txt`) |
150| port | `--out` (default `Documents\Leonida`) | `gta6rt.exe`, its DLL, the path files, the pipeline cache, `overlay` | small | yes |
151
152The free-space check before a build counts the `--work` drive only, because that is where the large files go.
153Nothing in `<work>\assets` is read by the game, so with a small SSD you can keep what the game loads on the SSD and
154put the exports on a hard drive, in two runs:
155
156```powershell
157# on the SSD: the package, the port and the translated shaders (about 30 GB of work files)
158python -I make_game.py --game "S:\Games\package" --out "S:\Games\Leonida" --work "S:\Games\Leonida\work" --stages check,shaders,runtime,pipelines
159# on the hard drive: the asset exports (about 370 GB), only for the asset tools
160python -I make_game.py --game "S:\Games\package" --out "S:\Games\Leonida" --work "H:\leonida-assets" --stages check,assets
161```
162
163The second run does not rebuild the runtime, so `shader_path.txt` keeps pointing at the SSD. Pass the same
164`--work` again for later runs of each stage so they resume. A single `--work "H:\leonida-work"` also works; the
165game then loads its translated shaders from that drive.
166
141**From a terminal**, with the same behaviour and more control: 167**From a terminal**, with the same behaviour and more control:
142 168
143```powershell 169```powershell
diff --git a/docs/README.md b/docs/README.md
index 6d34d575e..de581b865 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -10,12 +10,14 @@ method, scope and caveats. No game data is included.
10|---|---| 10|---|---|
11| [design.md](design.md) | Overall project design, asset status, translator contract and open blockers. | 11| [design.md](design.md) | Overall project design, asset status, translator contract and open blockers. |
12| [related_projects.md](related_projects.md) | Prior art we may read and the licence boundaries on it. | 12| [related_projects.md](related_projects.md) | Prior art we may read and the licence boundaries on it. |
13| [boot_leads.md](boot_leads.md) | Open leads that may move the retail boot further (TLS at module index 0, feature level at device creation, command-list replay, descriptor words, shader corpus count, frame pacing), each with where it lands, how to implement it and how to test it. Hypotheses, not measurements. |
13| [rpf.md](rpf.md) | RPF9 archive layout, the carve tools and the unreadable encrypted TOC. | 14| [rpf.md](rpf.md) | RPF9 archive layout, the carve tools and the unreadable encrypted TOC. |
14| [linux.md](linux.md) | Linux in one page: what runs natively and what runs under Wine or Proton, the Ubuntu packages, `Build.sh`, the runtime cross-build, and why there is no native Linux `gta6rt`. | 15| [linux.md](linux.md) | Linux in one page: what runs natively and what runs under Wine or Proton, the Ubuntu packages, `Build.sh`, the runtime cross-build, and why there is no native Linux `gta6rt`. |
15| [testing.md](testing.md) | Running the GPU tests on your own GPU: setup per OS, wave64 emulation, running without a GPU on Mesa llvmpipe, and known problems. | 16| [testing.md](testing.md) | Running the GPU tests on your own GPU: setup per OS, wave64 emulation, running without a GPU on Mesa llvmpipe, and known problems. |
16| [gpu_test_results.md](gpu_test_results.md) | Published GPU test results by hardware, driver and commit, with pass, skip and failure counts. | 17| [gpu_test_results.md](gpu_test_results.md) | Published GPU test results by hardware, driver and commit, with pass, skip and failure counts. |
17| [modding.md](modding.md) | The mod format: `mods/<folder>/mod.json`, checked and loaded in name order by `gta6rt`; a swap takes effect once the game's archetype lookup is hooked (needs the executable, RT-5). A mod names game models and holds no game data. | 18| [modding.md](modding.md) | The mod format: `mods/<folder>/mod.json`, checked and loaded in name order by `gta6rt`; a swap takes effect once the game's archetype lookup is hooked (needs the executable, RT-5). A mod names game models and holds no game data. |
18| [progress_dashboard.md](progress_dashboard.md) | A local page of what works, what changed since it last passed and what blocks next: unit and runtime tests, the translator contract by confirmation method, measured imports, corpus counts and, with `--github`, CI and the D3D- items (`tools/progress_dashboard.py`). | 19| [progress_dashboard.md](progress_dashboard.md) | A local page of what works, what changed since it last passed and what blocks next: unit and runtime tests, the translator contract by confirmation method, measured imports, corpus counts and, with `--github`, CI and the D3D- items (`tools/progress_dashboard.py`). |
20| [dev-tools.md](dev-tools.md) | The development CLI `scripts/dev.py`: `discover` (text or `--json`, schema version 1) lists the boot-trace analyzer and the guest-scene runner with their help commands and prerequisites, without running them; live attach, pause, step and screenshots are not available through it. |
19 21
20## Archives and assets 22## Archives and assets
21 23
@@ -79,6 +81,7 @@ method, scope and caveats. No game data is included.
79| [runtime_imports.md](runtime_imports.md) | The 16 shipped modules' measured imports and shim/host/unimplemented split. | 81| [runtime_imports.md](runtime_imports.md) | The 16 shipped modules' measured imports and shim/host/unimplemented split. |
80| [xmem_exe_calls.md](xmem_exe_calls.md) | How the retail executable calls `xmem.dll`: call sites and constant arguments per import (`tools/import_call_sites.py`), the 23 `XMemVirtualAlloc` calls that all pass an attribute word, and the inferred shape of the physical-page family. | 82| [xmem_exe_calls.md](xmem_exe_calls.md) | How the retail executable calls `xmem.dll`: call sites and constant arguments per import (`tools/import_call_sites.py`), the 23 `XMemVirtualAlloc` calls that all pass an attribute word, and the inferred shape of the physical-page family. |
81| [audio_hal_exe_calls.md](audio_hal_exe_calls.md) | How the retail executable calls the 22 audio coprocessor, texture layout and DirectStorage imports that have no shim: call sites, constant arguments, and the four calls with a negative-result branch. | 83| [audio_hal_exe_calls.md](audio_hal_exe_calls.md) | How the retail executable calls the 22 audio coprocessor, texture layout and DirectStorage imports that have no shim: call sites, constant arguments, and the four calls with a negative-result branch. |
84| [directstorage.md](directstorage.md) | Console DirectStorage: the DLL and ABI the title is expected to use (`DStorageGetFactory`, `dstorage_xs`, `XCRDAPI`), how sure that is and the evidence for it, and what `runtime/shims/dstorage.cpp` serves on the PC. The executable's own imports are unmeasured. |
82| [xcl_compare.md](xcl_compare.md) | XCL's synthetic test title under `gta6rt --run` and under XCL (`tools/xcl_compare.py`): 5 of 50 checks pass here, both hangs are the documented manual-queue terminate deadlock, and each other difference mapped to an open item or a lead. | 85| [xcl_compare.md](xcl_compare.md) | XCL's synthetic test title under `gta6rt --run` and under XCL (`tools/xcl_compare.py`): 5 of 50 checks pass here, both hangs are the documented manual-queue terminate deadlock, and each other difference mapped to an open item or a lead. |
83| [gameinput.md](gameinput.md) | The GameInput shim on SDL3: `GameInputCreate` and the v0 `IGameInput`/`IGameInputDevice`/`IGameInputReading`/`IGameInputDispatcher` surface on any SDL gamepad, DualSense adaptive-trigger approximation and lightbar, force-feedback motors and trigger haptics through SDL's haptic API; 261 checks on virtual joysticks and a fake haptic backend; by hand on an Xbox Series X pad (Bluetooth) and a DualSense (USB). 261 checks on virtual joysticks and a fake haptic backend, not yet tried on a real pad. | 86| [gameinput.md](gameinput.md) | The GameInput shim on SDL3: `GameInputCreate` and the v0 `IGameInput`/`IGameInputDevice`/`IGameInputReading`/`IGameInputDispatcher` surface on any SDL gamepad, DualSense adaptive-trigger approximation and lightbar, force-feedback motors and trigger haptics through SDL's haptic API; 261 checks on virtual joysticks and a fake haptic backend; by hand on an Xbox Series X pad (Bluetooth) and a DualSense (USB). 261 checks on virtual joysticks and a fake haptic backend, not yet tried on a real pad. |
84| [saves.md](saves.md) | Save containers: `JSAV` (index + JSON story save, byte-exact rebuild), `ASAV` header, `SLAYER1` packed copy (not decoded); `tools/saves.py` and import into the offline `XGameSave` folder; key hashes are case-sensitive joaat (`tools/save_keys.py`). | 87| [saves.md](saves.md) | Save containers: `JSAV` (index + JSON story save, byte-exact rebuild), `ASAV` header, `SLAYER1` packed copy (not decoded); `tools/saves.py` and import into the offline `XGameSave` folder; key hashes are case-sensitive joaat (`tools/save_keys.py`). |
@@ -86,6 +89,7 @@ method, scope and caveats. No game data is included.
86| [multi_gpu_validation.md](multi_gpu_validation.md) | Running disjoint shards on eight identical RDNA1/RADV GPUs: PCI-BDF pinning, base controls, per-card logs, the V540 farm's aggregate results and its known driver limitations. | 89| [multi_gpu_validation.md](multi_gpu_validation.md) | Running disjoint shards on eight identical RDNA1/RADV GPUs: PCI-BDF pinning, base controls, per-card logs, the V540 farm's aggregate results and its known driver limitations. |
87| [shader_validation.md](shader_validation.md) | Differential CPU/GPU validation design and the current CPU interpreter prototype. | 90| [shader_validation.md](shader_validation.md) | Differential CPU/GPU validation design and the current CPU interpreter prototype. |
88| [isa_coverage.md](isa_coverage.md) | RDNA2 ISA coverage of the translator against AMD's machine-readable XML: which of its 1,153 instructions have a rule, and which matched names are not RDNA2. | 91| [isa_coverage.md](isa_coverage.md) | RDNA2 ISA coverage of the translator against AMD's machine-readable XML: which of its 1,153 instructions have a rule, and which matched names are not RDNA2. |
92| [cpu_features.md](cpu_features.md) | CPU instructions in `game_scarlett_master.exe` that a host lacking the feature or privilege level faults on (SSE4a, CLZERO, MONITORX and others): counts per feature and how many sites lie inside `.pdata` function ranges, measured with `tools/cpu_feature_scan.py` on 1.0.2.1. Counts only. |
89| [buffer_bounds.md](buffer_bounds.md) | V# `OOB_SELECT` bounds measured natively: RDNA2 (gfx1036) follows Mesa's GFX11 column (729/732 cases), not GFX10; raw mode also counts `soffset`. | 93| [buffer_bounds.md](buffer_bounds.md) | V# `OOB_SELECT` bounds measured natively: RDNA2 (gfx1036) follows Mesa's GFX11 column (729/732 cases), not GFX10; raw mode also counts `soffset`. |
90| [buffer_formats.md](buffer_formats.md) | Every GFX10 buffer data format a V# or MTBUF can name, loaded and stored, measured on a Radeon 880M (RDNA3.5, not RDNA2): 1.33 million validated elements, 0 mismatches; SCALED stores convert as NORM, float stores round toward zero. | 94| [buffer_formats.md](buffer_formats.md) | Every GFX10 buffer data format a V# or MTBUF can name, loaded and stored, measured on a Radeon 880M (RDNA3.5, not RDNA2): 1.33 million validated elements, 0 mismatches; SCALED stores convert as NORM, float stores round toward zero. |
91| [fssm_crosscheck.md](fssm_crosscheck.md) | FSSM/RDNA2 facts cross-checked against SCARAB; code starts at `code_off + 0x28`. | 95| [fssm_crosscheck.md](fssm_crosscheck.md) | FSSM/RDNA2 facts cross-checked against SCARAB; code starts at `code_off + 0x28`. |
diff --git a/docs/boot.md b/docs/boot.md
index 1ff3fa2f4..31a7ba3d1 100644
--- a/docs/boot.md
+++ b/docs/boot.md
@@ -5,8 +5,9 @@ repository's test corpus does not contain `game_scarlett_master.exe` (RT-5); the
5separately maps it and leaves 30 imports unimplemented, and `--init` runs its TLS callbacks and the package DLLs' 5separately maps it and leaves 30 imports unimplemented, and `--init` runs its TLS callbacks and the package DLLs'
6`DllMain`s without an exception 6`DllMain`s without an exception
7([`runtime_imports.md`](runtime_imports.md#the-retail-executable-rt-5)), so this page is still the procedure and the 7([`runtime_imports.md`](runtime_imports.md#the-retail-executable-rt-5)), so this page is still the procedure and the
8trace tool for the first boot. The executable's `ws2_32.dll` imports bind to the host's, so run `--run` with the 8trace tool for the first boot. Outbound `ws2_32.dll` and `winhttp.dll` calls are restricted offline by the shims
9network off. Nothing here quotes game data; a real trace stays on the player's machine. 9(`ws2_offline.cpp` permits loopback only; `winhttp_offline.cpp` refuses all requests), though running with the network
10off remains good defence in depth. Nothing here quotes game data; a real trace stays on the player's machine.
10 11
11## 1. What the first boot produces 12## 1. What the first boot produces
12 13
@@ -28,8 +29,11 @@ Two traces are written independently:
28 29
29`tools/boot_trace.py` reads both and prints the triage units: modules, unimplemented calls and callers, 30`tools/boot_trace.py` reads both and prints the triage units: modules, unimplemented calls and callers,
30DllMain/TLS results, exceptions with their stack frames, the exit, and the D3D12 calls by outcome and first call 31DllMain/TLS results, exceptions with their stack frames, the exit, and the D3D12 calls by outcome and first call
31per method. The `[rt]` lines in the same stderr log carry the device parameters, feature ids and warnings; the 32per method. When `XboxPresentation` logs its teardown `[rt] present: pacing summary ...` line (BL-6), the D3D12
32summary leaves them as a count, so grep `^\[rt\]` for those. 33summary also reports the frame count, interval count, target interval, mean and drift against target, `p50`/`p95`/`p99`
34frame times, and `p50`/`p95`/`p99` origin-to-present latencies (and includes the numeric `frame_pacing` object in
35`--json` and `--counts-only`). The remaining `[rt]` lines in the same stderr log carry the device parameters, feature
36ids and warnings; the summary leaves them as a count, so grep `^\[rt\]` for those.
33 37
34For `xmem_physical_pages`, the shim records the first request for each distinct attribute word. The text and 38For `xmem_physical_pages`, the shim records the first request for each distinct attribute word. The text and
35JSON summaries list the API, raw attribute word, requested page count and caller for the first `--limit` 39JSON summaries list the API, raw attribute word, requested page count and caller for the first `--limit`
@@ -46,7 +50,8 @@ $exe = "C:\path\to\game_scarlett_master.exe"
46$pkg = "C:\path\to\the\package" 50$pkg = "C:\path\to\the\package"
47$trace = Join-Path $env:TEMP boot.jsonl 51$trace = Join-Path $env:TEMP boot.jsonl
48$log = Join-Path $env:TEMP d3d12.log 52$log = Join-Path $env:TEMP d3d12.log
49.\runtime\build\gta6rt.exe --run $exe --game-dir $pkg --trace $trace --trace-d3d12 2>&1 | 53& { $ErrorActionPreference = 'Continue'
54 .\runtime\build\gta6rt.exe --run $exe --game-dir $pkg --trace $trace --trace-d3d12 2>&1 } |
50 ForEach-Object { $_.ToString() } | 55 ForEach-Object { $_.ToString() } |
51 Out-File -LiteralPath $log -Width 4096 -Encoding utf8 56 Out-File -LiteralPath $log -Width 4096 -Encoding utf8
52python -I tools\boot_trace.py $trace --d3d12 $log 57python -I tools\boot_trace.py $trace --d3d12 $log
@@ -56,6 +61,13 @@ The capture pipeline writes each message as text to avoid PowerShell 5.1 wrappin
56narrow output width. The tool also reads existing UTF-16LE logs saved with `2>` in PowerShell 5.1 and recognizes 61narrow output width. The tool also reads existing UTF-16LE logs saved with `2>` in PowerShell 5.1 and recognizes
57the `program.exe : ` prefix on the first stderr line. 62the `program.exe : ` prefix on the first stderr line.
58 63
64The `& { ... }` block matters when the session (or a profile or script) has `$ErrorActionPreference = 'Stop'`:
65Windows PowerShell 5.1 then turns the first stderr line into a terminating error, the run stops there, and the log
66holds no `[d3d12-trace]` line, so it reads as a run with no D3D12 call. The block sets `Continue` for the run only
67(`scripts/first_look.ps1` captures its dry run the same way). Measured on 5.1.26100 with a stand-in that prints three
68trace lines to stderr and exits 37: without the block, all three with `Continue` and none with `Stop`; with it, all
69three with either, `$LASTEXITCODE` 37, and the session's preference unchanged.
70
59Linux under Wine (a cross build made with xwin, or the `runtime-windows` artifact; the backend must be Vulkan): 71Linux under Wine (a cross build made with xwin, or the `runtime-windows` artifact; the backend must be Vulkan):
60 72
61```sh 73```sh
@@ -66,10 +78,17 @@ wine runtime/build/windows/gta6rt.exe --run /path/to/game_scarlett_master.exe \
66python3 -I tools/boot_trace.py /tmp/boot.jsonl --d3d12 /tmp/d3d12.log 78python3 -I tools/boot_trace.py /tmp/boot.jsonl --d3d12 /tmp/d3d12.log
67``` 79```
68 80
81`runtime\build\gta6rt.exe` is where `scripts\build_runtime.ps1` (Ninja) puts it; the direct CMake path in
82[runtime/README.md](../runtime/README.md) uses the multi-config Visual Studio generator, which writes
83`runtime\build\RelWithDebInfo\gta6rt.exe` instead.
84
69`--trace FILE` **refuses an existing file** (exit 2): it is created before the loader reads anything, so use a 85`--trace FILE` **refuses an existing file** (exit 2): it is created before the loader reads anything, so use a
70fresh name or delete the old one. `LEONIDA_D3D12=vulkan` selects the Vulkan-backed device, the only backend that 86fresh name or delete the old one. `LEONIDA_D3D12=vulkan` selects the Vulkan-backed device, the only backend that
71writes the `[d3d12-trace]` lines; without it the layer uses the Windows D3D12 device and the trace has nothing to 87traces command lists, resources and pipelines; without it the layer uses the Windows D3D12 device, and the
72read. Keep the traces out of the repository: they can quote whatever the game prints. 88`[d3d12-trace]` lines are only what the Xbox-ABI proxy forwards (device creation, queue, fence and allocator
89calls), which `boot_trace.py` summarizes without complaint. A run on the Vulkan device prints
90`[rt] d3d12: Vulkan device: <name>`; check the log for it (a runtime built without the Vulkan headers accepts the
91variable and stays on the Windows device). Keep the traces out of the repository: they can quote whatever the game prints.
73 92
74Useful switches: 93Useful switches:
75 94
@@ -90,7 +109,8 @@ Useful switches:
90* `DISABLE_RTSS_LAYER=1` and `DISABLE_VULKAN_OBS_CAPTURE=1` when MSI Afterburner or OBS is installed; their 109* `DISABLE_RTSS_LAYER=1` and `DISABLE_VULKAN_OBS_CAPTURE=1` when MSI Afterburner or OBS is installed; their
91 implicit layers add swapchain usage that shows up as validation errors ([testing.md](testing.md), "Known 110 implicit layers add swapchain usage that shows up as validation errors ([testing.md](testing.md), "Known
92 problems"). 111 problems").
93* `--overlay DIR` sends the guest's writes to a private folder instead of the package. 112* `--overlay DIR` sends the guest's writes to DIR instead of the default `<game-dir>\overlay` (useful when the
113 package drive is read-only); the package itself is never written.
94 114
95## 3. Triage order 115## 3. Triage order
96 116
@@ -110,8 +130,9 @@ Read the startup trace first; the first event that is not the expected one is th
110 the final slot for the last observed exception. The trace also includes handled exceptions, so the last 130 the final slot for the last observed exception. The trace also includes handled exceptions, so the last
111 observation alone does not establish what caused the run to stop. 131 observation alone does not establish what caused the run to stop.
1125. **`exit` / `error`** — a clean exit is not a correct frame; continue to the D3D12 trace. 1325. **`exit` / `error`** — a clean exit is not a correct frame; continue to the D3D12 trace.
1136. **D3D12 trace** — the `failed`, `unsupported`, `refused` and `partial` lines name the method. A `partial` 1336. **D3D12 trace** — the `failed`, `unsupported` and `refused` lines name the method. A `failed`
114 submission ran the supported commands from a list. The runtime's `[rt]` diagnostic names the command it left out. 134 `ExecuteCommandLists` submitted nothing from its lists. (`boot_trace.py` also lists a `partial` outcome, a
135 submission that ran only the supported commands; the runtime does not write it yet.)
115 Compare the method's position with the public SDK vtable. An unknown slot is expected until the executable names it 136 Compare the method's position with the public SDK vtable. An unknown slot is expected until the executable names it
116 (Q2, Q6). The `[rt]` lines in the same log carry the 24 device words, feature IDs and warnings. 137 (Q2, Q6). The `[rt]` lines in the same log carry the 24 device words, feature IDs and warnings.
117 The summary expects `#1` first, then one more than the last observed number. It counts each mismatch once and 138 The summary expects `#1` first, then one more than the last observed number. It counts each mismatch once and
@@ -130,8 +151,8 @@ is `null`; if neither input yields a report, stdout is empty.
130 151
131## 4. The open questions, and the trace signal for each 152## 4. The open questions, and the trace signal for each
132 153
133The questions are in [`d3d12_vulkan.md`](d3d12_vulkan.md) §8.2; that table repeats 16, 19 and 20, and this one is 154The questions are in [`d3d12_vulkan.md`](d3d12_vulkan.md) §8.2; this table takes the same 1–22 in
134the de-duplicated 1–22. It maps each question to the event to look for; it does not answer them. 155order. It maps each question to the event to look for; it does not answer them.
135 156
136| # | Question | Signal in the first trace | 157| # | Question | Signal in the first trace |
137|---|---|---| 158|---|---|---|
@@ -172,5 +193,6 @@ the de-duplicated 1–22. It maps each question to the event to look for; it doe
172The retail executable is not in the package, so this page is untested against it; the tool and the trace formats 193The retail executable is not in the package, so this page is untested against it; the tool and the trace formats
173are tested on synthetic fixtures and on `tiny_game` (which has no D3D12 calls). The present slots (Q6) and the 194are tested on synthetic fixtures and on `tiny_game` (which has no D3D12 calls). The present slots (Q6) and the
174Xbox device parameters (Q1) remain the first things the executable itself has to name. The D3D12 trace needs the 195Xbox device parameters (Q1) remain the first things the executable itself has to name. The D3D12 trace needs the
175Vulkan backend; a build without it runs the game's calls through the PC device and records nothing. The runbook 196Vulkan backend; a build without it runs the game's calls through the PC device and records only the proxy's
197device, queue, fence and allocator calls. The runbook
176does not make the game boot; it makes the first real trace readable. 198does not make the game boot; it makes the first real trace readable.
diff --git a/docs/boot_leads.md b/docs/boot_leads.md
new file mode 100644
index 000000000..e949c0dc1
--- /dev/null
+++ b/docs/boot_leads.md
@@ -0,0 +1,108 @@
1# Boot leads: open findings and how to implement them
2
3Open leads that may move the retail boot further, each with where it lands in this repository and how to check it.
4Every item is a **hypothesis**: it has not been measured against this package or run in this runtime. Confirm it on
5your own copy or with a synthetic test before you build on it, and record the result in the document named under
6**Record it in**.
7
8## Rules
9
10- **No game data, no keys, no protection workarounds.** If a format turns out to be encrypted, write that down in
11 [design.md](design.md) and stop.
12- **Nothing online**: no Xbox Live or Rockstar services.
13- **Claim first.** Put the lead's ID (BL-1 …) in the coordination issue before you open a pull request (the search
14 link is in [CONTRIBUTING.md](../CONTRIBUTING.md)), and check the open pull requests for the same item.
15- A translator rule needs a row in the contract table in [design.md](design.md) with how it was confirmed, and a
16 hand-written `.asm` fixture in `tests/semantic/`.
17- In the pull request, say what you tested and on which GPU and driver.
18
19## BL-1: the title's code reads its TLS from module index 0
20
21- **Finding:** code built with `/GA` reads thread-local storage straight from `ThreadLocalStoragePointer[0]` and
22 assumes the executable's own TLS block sits at index 0. Static TLS has to be set up per mapped module, not once.
23- **Where:** the retail run on `main` ends in CRT startup with an access violation and 0 D3D12 calls, "the stop-4
24 shape (TLS from module index 0)" ([retail_boot_intel_host.md §1](retail_boot_intel_host.md)). The loader already
25 keeps one TLS host slot per mapped module (`runtime/src/pe_loader.cpp`, `runtime/src/tls_host.cpp`), and the
26 integration tree carries a fix for stop 4 that `main` does not
27 ([retail_boot_chain.md](retail_boot_chain.md), row 4).
28- **Implement:**
29 1. Find the stop-4 fix on the integration tree and compare it with `Loader::initialize_tls` on `main`.
30 2. Make the executable's slot resolve at index 0 of the thread's TLS array, and give every other mapped module that
31 has a TLS directory its own index.
32 3. Keep the per-thread copy and restore behaviour in `tls_host.cpp` (new threads get a copy; the helper's own block
33 is put back before the thread exits).
34- **Test:** extend `runtime/test/loader_tls_test.cpp` and `runtime/test/fixtures/tiny_game.cpp` with a synthetic image
35 whose code reads `gs:[58h]` index 0 and a second module with its own TLS variable. No game files needed. Then run
36 the retail `--run` to confirm the stop is cleared.
37- **Record it in:** [boot.md](boot.md) (the `tls_callback`/`dllmain` section) and the stop table in
38 [retail_boot_chain.md](retail_boot_chain.md).
39- **Needs:** none for the synthetic test; game files for the retail confirmation.
40
41## BL-2: feature level at device creation
42
43- **Finding:** device creation can fail with `E_INVALIDARG` (`0x80070057`) when asked for feature level 11.0 and
44 succeed when asked for 12.0.
45- **Where:** `CheckFeatureSupport` reports levels up to 12_1 (`runtime/shims/d3d12_vulkan_device.cpp`, the
46 `D3D12_FEATURE_FEATURE_LEVELS` case); the Xbox entry point is in `runtime/shims/d3d12_xs_device.cpp`.
47- **Implement:** read the level the title passes at creation and make the layer accept the full range it can
48 satisfy, returning the highest supported level through the feature-level query rather than failing creation on a
49 lower request. Report 12_2 only where mesh shaders and ray tracing are present
50 ([d3d12_vulkan.md](d3d12_vulkan.md), feature-level notes).
51- **Test:** a mock-device case in `runtime/test/xs_proxy_mock_test.cpp` creating at 11_0, 12_0, 12_1 and 12_2 and
52 asserting the result and the reported level for each.
53- **Record it in:** [d3d12_xs_surface.md](d3d12_xs_surface.md).
54- **Needs:** none for the mock test; a Wine or Proton host to reproduce the original failure.
55
56## BL-3: replay the console command list at Close or Execute
57
58- **Finding:** the console's command-list interface may be easier to serve by replaying the recorded commands when the
59 list is closed or executed than by translating each call as it is made.
60- **Where:** the "console list tail" listed as open in the README's D3D12 → Vulkan row and in
61 [d3d12_vulkan.md](d3d12_vulkan.md); call orders are in [d3d12_command_objects.md](d3d12_command_objects.md).
62- **Implement:** record the console-only calls into a per-list buffer, then translate them to Vulkan in order at
63 `Close`/`Execute`. Keep calls that must take effect immediately (those whose results the title reads back) out of
64 the buffer.
65- **Test:** a recorded-sequence unit test: the same call order through the immediate path and the replay path gives
66 the same Vulkan command stream. Add a GPU case only once the stream matches.
67- **Record it in:** [d3d12_vulkan.md](d3d12_vulkan.md), with the measured call order.
68- **Needs:** game files (call traces) to find which calls read results back; a GPU for the final check.
69
70## BL-4: descriptor words are 32-bit GPU addresses
71
72- **Finding:** a console descriptor word may be a 32-bit GPU address rather than a heap offset.
73- **Where:** the "descriptor-table record model" listed as open in [d3d12_vulkan.md](d3d12_vulkan.md), next to the
74 descriptor-heap start-handle convention in §7 of that page.
75- **Implement:** census the descriptor words the title writes (count how many are valid addresses inside the arena
76 and how many are not). If the census holds, translate a word to the buffer device address or bindless index it
77 stands for, the way root-descriptor addresses already go through the arena.
78- **Test:** a synthetic heap whose words are arena addresses, round-tripped through the translation.
79- **Record it in:** [d3d12_vulkan.md](d3d12_vulkan.md) with the census counts.
80- **Needs:** game files for the census.
81
82## BL-5: a possible gap in the shader corpus count
83
84- **Finding:** a count of 26,698 shader programs has been reported against this repository's 26,503. The difference,
85 195, equals the geometry-shader count here, which may mean a different way of counting, or programs the carve
86 misses.
87- **Where:** the carve and library tools (`make_game.py`, `tools/shader_carve.py`, `tools/shader_library.py`) and
88 [shader_library.md](shader_library.md).
89- **Implement:** list how programs are enumerated (per file, per container, per variant) and print a breakdown by
90 stage. If the 195 are a counting difference, document it. If they are real, find where the carve skips them and fix
91 that, not the count.
92- **Test:** a synthetic container with a geometry-stage program, so the count and the breakdown are checked without
93 game files.
94- **Record it in:** [shader_library.md](shader_library.md).
95- **Needs:** game files for the real corpus.
96
97## BL-6: frame pacing drift reporting
98
99- **Finding:** frame pacing can drift on a long-running screen, and per-frame percentile and input-to-present
100 figures make that visible.
101- **Where:** the frame pacer in `runtime/src/frame_pacer.h` and its `PresentX` wiring in
102 `runtime/shims/xbox_present.cpp`.
103- **Implement:** record frame times in a ring buffer and report p50, p95 and p99 plus the drift of the mean against
104 the target interval, in the run summary beside the existing D3D12 counts ([boot.md](boot.md)).
105- **Test:** extend `runtime/test/frame_pacer_test.cpp` with a fake clock feeding known intervals, asserting the
106 percentiles and the drift.
107- **Record it in:** [d3d12_vulkan.md](d3d12_vulkan.md) (presentation) and [boot.md](boot.md) (summary fields).
108- **Needs:** none for the reporting; game files and a GPU to see real numbers.
diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md
index 3ae29163e..3cd9d6d5e 100644
--- a/docs/d3d12_vulkan.md
+++ b/docs/d3d12_vulkan.md
@@ -2029,6 +2029,15 @@ without recorded inputs. In that case the runtime accepts any input layout when
2029 2029
2030### 3.6 Shader identity, PSOs and feature selection 2030### 3.6 Shader identity, PSOs and feature selection
2031 2031
2032The Xbox native graphics pipeline descriptor identifies stages by the digest in a DXBC HASH part (see
2033`docs/fspx.md`, kind 7). The shaders stage writes `<work>/shaders/spirv/native_hashes.txt` from the user's
2034carved DXBC containers and translation index. After the version header, each line contains the 16-byte digest
2035in lowercase hex, the translated stage and a container path relative to the index, separated by tabs.
2036Containers sharing a digest must agree on stage and FSSM hash. A collision fails the stage and preserves the
2037previous catalog. Rerunning the shaders stage checks its source fingerprint, including the catalog writer.
2038To add or refresh just the catalog in an existing translation, run
2039`python -I tools/native_pso_hashes.py "<work>/shaders/dxbc" "<work>/shaders/spirv"`.
2040
2032A D3D12 PSO carries DXBC containers, not SPIR-V. The layer identifies a shader by hashing the **FSSM payload** (the 2041A D3D12 PSO carries DXBC containers, not SPIR-V. The layer identifies a shader by hashing the **FSSM payload** (the
2033native RDNA2 program inside the container) and looking it up in a build-time table keyed by `(stage, hash)`. The 2042native RDNA2 program inside the container) and looking it up in a build-time table keyed by `(stage, hash)`. The
2034build emits that hash for every translation; the runtime extracts the FSSM chunk from the DXBC container the same 2043build emits that hash for every translation; the runtime extracts the FSSM chunk from the DXBC container the same
@@ -2067,9 +2076,12 @@ Pipeline creation:
2067 shader, root signature content or state, a changed byte, a truncated blob or a pointer with size 0 give 2076 shader, root signature content or state, a changed byte, a truncated blob or a pointer with size 0 give
2068 `E_INVALIDARG`; a null pointer with a size is ignored; another adapter gives `D3D12_ERROR_ADAPTER_NOT_FOUND` and 2077 `E_INVALIDARG`; a null pointer with a size is ignored; another adapter gives `D3D12_ERROR_ADAPTER_NOT_FOUND` and
2069 another driver `D3D12_ERROR_DRIVER_VERSION_MISMATCH`. `ID3D12PipelineLibrary` is an in-memory map plus the Vulkan 2078 another driver `D3D12_ERROR_DRIVER_VERSION_MISMATCH`. `ID3D12PipelineLibrary` is an in-memory map plus the Vulkan
2070 cache. Its arguments answer as the host's (`d3d12_pipeline_library_host_test`, 74 values from 46 calls that need no 2079 cache. `d3d12_pipeline_library_host_test` compares public argument checks with the host. It runs each host
2071 PSO, each run on the host in a process of its own, since a call it faults on leaves its runtime broken and the next 2080 call in a separate process because a fault can leave the device unusable. It reports serialized sizes and the
2072 one failing fast; RTX 3060, driver 610.88): 2081 result of flipping a trailing byte for each device's own format. `d3d12_pipeline_library_test` checks that the
2082 layer rejects a nonzero reserved field in its `LPL1` header. On Windows 11 build 26100 (RTX 5070 Ti,
2083 driver 610.74), all 72 public-argument comparisons matched. The previous 74-value run (RTX 3060, driver
2084 610.88) included the two results from the trailing-byte case.
2073 - `CreatePipelineLibrary`: a foreign, truncated or corrupt blob, the other device's blob, or a null pointer with a 2085 - `CreatePipelineLibrary`: a foreign, truncated or corrupt blob, the other device's blob, or a null pointer with a
2074 size is `E_INVALIDARG`, and `*ppPipelineLibrary` is left as it was. One of the layer's own blobs from another 2086 size is `E_INVALIDARG`, and `*ppPipelineLibrary` is left as it was. One of the layer's own blobs from another
2075 format version is `D3D12_ERROR_DRIVER_VERSION_MISMATCH`, the documented code for a cache from another driver. 2087 format version is `D3D12_ERROR_DRIVER_VERSION_MISMATCH`, the documented code for a cache from another driver.
@@ -2636,6 +2648,11 @@ The trace will enumerate them.
2636 stores `0x7fff` vs WARP `0x8000` (all on `main` before this change; same 1-ulp class as SRGB, not addressed here). 2648 stores `0x7fff` vs WARP `0x8000` (all on `main` before this change; same 1-ulp class as SRGB, not addressed here).
2637 `D32_FLOAT` and `D32_FLOAT_S8X24_UINT` match WARP. 2649 `D32_FLOAT` and `D32_FLOAT_S8X24_UINT` match WARP.
2638 This does not add typed-view reinterpretation of typeless resources. 2650 This does not add typed-view reinterpretation of typeless resources.
2651- **Depth clears.** Microsoft documents a `[0, 1]` clamp. On Windows 11 build 26100, both WARP and native D3D12 on
2652 an RTX 5070 Ti (610.74) preserved finite out-of-range `D32_FLOAT` values and quiet NaN in full and rectangle
2653 clears. Replay preserves those values when the Vulkan device has enabled `VK_EXT_depth_range_unrestricted`.
2654 With the extension disabled, replay clamps finite values to `[0, 1]` and uses zero for NaN. The UNORM depth
2655 format conversions still apply. [D3D12 reference](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12graphicscommandlist-cleardepthstencilview)
2639- `D3D12XBOX_RESOURCE_FLAG_FORCE_TEXTURE_COMPATIBILITY` (public release note) and DCC: ignore the flag, let the 2656- `D3D12XBOX_RESOURCE_FLAG_FORCE_TEXTURE_COMPATIBILITY` (public release note) and DCC: ignore the flag, let the
2640 Vulkan driver choose compression, and fail loudly if the game aliases a buffer over a compressed image or reads 2657 Vulkan driver choose compression, and fail loudly if the game aliases a buffer over a compressed image or reads
2641 raw DCC metadata. 2658 raw DCC metadata.
@@ -2679,7 +2696,11 @@ mapped stages/accesses, and if no single layout serves all uses, use `GENERAL` a
2679- Enhanced barriers (`D3D12_BARRIER_SYNC_*`, `D3D12_BARRIER_ACCESS_*`, `D3D12_BARRIER_LAYOUT_*`) map directly to 2696- Enhanced barriers (`D3D12_BARRIER_SYNC_*`, `D3D12_BARRIER_ACCESS_*`, `D3D12_BARRIER_LAYOUT_*`) map directly to
2680 `VkPipelineStageFlags2`, `VkAccessFlags2` and `VkImageLayout` (`vulkan_sync`, `vulkan_barrier_access`, 2697 `VkPipelineStageFlags2`, `VkAccessFlags2` and `VkImageLayout` (`vulkan_sync`, `vulkan_barrier_access`,
2681 `vulkan_layout`). Queue-specific layouts map like their generic forms; ray tracing, video and split scopes use 2698 `vulkan_layout`). Queue-specific layouts map like their generic forms; ray tracing, video and split scopes use
2682 `ALL_COMMANDS`; `LayoutBefore = UNDEFINED` or the discard flag becomes `oldLayout = UNDEFINED`. 2699 `ALL_COMMANDS`; `LayoutBefore = UNDEFINED` or the discard flag becomes `oldLayout = UNDEFINED`. `SYNC_COPY` is
2700 `COPY | CLEAR`, not `COPY` alone: `WriteBufferImmediate` is recorded as `vkCmdUpdateBuffer` and
2701 `ResolveQueryData`'s never-written queries as `vkCmdFillBuffer`, which synchronization2 runs in the `CLEAR` stage
2702 (D3D-838; `vk_command_replay_test` part K is a read-after-write hazard under synchronization validation without
2703 it).
2683- `DiscardResource` (D3D-26): each discarded image subresource gets a barrier from `oldLayout = UNDEFINED` to the 2704- `DiscardResource` (D3D-26): each discarded image subresource gets a barrier from `oldLayout = UNDEFINED` to the
2684 layout the tracker already has for it, so the driver may drop the contents while later commands see no layout 2705 layout the tracker already has for it, so the driver may drop the contents while later commands see no layout
2685 change. The other cases are no-ops, which "contents undefined" allows: buffers, discards with rectangles (only 2706 change. The other cases are no-ops, which "contents undefined" allows: buffers, discards with rectangles (only
@@ -2988,6 +3009,14 @@ queue they came on (one `VkQueue` behind all of them).
2988 keeps the app's sync interval. 3009 keeps the app's sync interval.
2989 `GetFrameStatisticsX` keeps the last 64 frames and reports the event, present and display times (not render; 3010 `GetFrameStatisticsX` keeps the last 64 frames and reports the event, present and display times (not render;
2990 `PercentScanned` only for a frame shown at once by `ImmediateThresholdPercent`, else 0); `S_FALSE` with count 0 for what it does not have. 3011 `PercentScanned` only for a frame shown at once by `ImmediateThresholdPercent`, else 0); `S_FALSE` with count 0 for what it does not have.
3012 *Pacing drift reporting (BL-6):* `FramePacer` keeps fixed-capacity ring buffers (`frame_pacing_window = 1024`) of
3013 present-to-present frame intervals and origin-to-present latencies (clearing the last-present anchor across
3014 `SuspendX`/`ResumeX` so suspended pauses are excluded), computing nearest-rank `p50`/`p95`/`p99` and the mean drift
3015 against the active target interval (`FramePacer::pacing_summary()`). On teardown after at least one present,
3016 `XboxPresentation` logs a single `[rt] present: pacing summary ...` line on stderr, which `tools/boot_trace.py`
3017 surfaces beside the D3D12 call counts. Confirmed on a fake clock by `frame_pacer_test` (known 100-frame distribution,
3018 positive and negative drift, ring-buffer wrap-around, suspend/resume exclusion, uncapped mode) and by
3019 `tests/test_boot_trace.py`.
2991- *`PresentX`*: 0 planes presents a black frame (no token needed). 1 plane blits plane 0's first resource (a 3020- *`PresentX`*: 0 planes presents a black frame (no token needed). 1 plane blits plane 0's first resource (a
2992 single-sample 2D colour texture in `PRESENT`) to the swapchain image, limited to `pSrcViewRects[0]` when set 3021 single-sample 2D colour texture in `PRESENT`) to the swapchain image, limited to `pSrcViewRects[0]` when set
2993 (bilinear, so the rectangle's outer texels blend with their neighbours). The blit converts between formats; an sRGB 3022 (bilinear, so the rectangle's outer texels blend with their neighbours). The blit converts between formats; an sRGB
@@ -3288,23 +3317,34 @@ Implemented (`QueryHeap` in `runtime/shims/d3d12_vulkan_device.cpp`, the query c
3288 recording. The resolve fallback is unchanged: only resolves needing dispatches are refused there. 3317 recording. The resolve fallback is unchanged: only resolves needing dispatches are refused there.
3289- **Mesh draws during a pipeline-statistics query** (D3D-291). D3D12 allows `DispatchMesh` inside a statistics query 3318- **Mesh draws during a pipeline-statistics query** (D3D-291). D3D12 allows `DispatchMesh` inside a statistics query
3290 and reads its input-assembly, vertex, geometry and tessellation fields as 0. Vulkan forbids `vkCmdDrawMeshTasksEXT` 3319 and reads its input-assembly, vertex, geometry and tessellation fields as 0. Vulkan forbids `vkCmdDrawMeshTasksEXT`
3291 while a query with those counters is active (`VUID-vkCmdDrawMeshTasksEXT-pipelineStatistics-07076`), and the heap's 3320 while a query with the input-assembly, vertex, geometry, tessellation or clipping counters is active
3292 pool has all eleven. So a statistics query that holds a mesh draw is split as above, and a split before a draw stays 3321 (`VUID-vkCmdDrawMeshTasksEXT-pipelineStatistics-07076`), and the heap's pool has all eleven. So a statistics query
3293 outside its rendering scope. A segment's first draw decides its pool: the submission's full pool, or a second pool 3322 that holds a mesh draw is split as above, and a split before a draw stays outside its rendering scope. A segment's first draw decides its pool: the submission's full pool, or a second pool
3294 with only clipping invocations and primitives, fragment and compute invocations. A later draw of the other kind ends 3323 with only the fragment and compute invocations, the two the VUID leaves allowed. A later draw of the other kind ends
3295 the segment and begins one of its own kind; dispatches and segments without draws use the full pool, and 3324 the segment and begins one of its own kind; dispatches and segments without draws use the full pool, and
3296 `ExecuteIndirect` draws count as vertex draws. The sum copies a mesh segment's four counters into fields 5 to 8 of 3325 `ExecuteIndirect` draws count as vertex draws. The sum copies a mesh segment's two counters into fields 7 and 8 of
3297 its record, and `statistics_sum.comp` adds them as `CInvocations`, `CPrimitives`, `PSInvocations` and 3326 its record, and `statistics_sum.comp` adds them as `PSInvocations` and `CSInvocations`, so the other fields get
3298 `CSInvocations`, so the other fields get nothing from it. A query that holds only mesh draws is one mesh segment, 3327 nothing from it. D3D12 counts the clipping invocations and primitives of a mesh pipeline, but Vulkan has no counter
3299 resolved through the same sum. Without the compute helper there is no segment pool and such a list is refused 3328 for them during a mesh draw, so `CInvocations` and `CPrimitives` read 0 for a mesh segment. A query that holds only
3300 (`unsupported`) rather than run unsplit; so is one on the single-list `replay()` (D3D-399), whose 3329 mesh draws is one mesh segment, resolved through the same sum. Without the compute helper there is no segment pool
3301 `create_segment_pool` gives no mesh pool. Overlapping statistics queries (D3D-252) split the same way inside their 3330 and such a list is refused (`unsupported`) rather than run unsplit; so is one on the single-list `replay()` (D3D-399),
3302 shared segments: a draw of the other kind than the open segment's opens a new one, so every query that segment 3331 whose `create_segment_pool` gives no mesh pool. Overlapping statistics queries (D3D-252) split the same way inside
3303 belongs to sums both kinds. `replay_query_predication_test` (cases 15 and 16) checks the split points, the segment 3332 their shared segments: a draw of the other kind than the open segment's opens a new one, so every query that segment
3304 kinds and the resolve plan on the CPU. `d3d12_mesh_test` resolves a query around a vertex, two mesh and a vertex 3333 belongs to sums both kinds. `replay_query_predication_test` (cases 15 to 17) checks the split points, the segment
3305 draw, one around a mesh draw and one around the two vertex draws: the vertex fields count only the two triangles, 3334 kinds, the resolve plan and the counters the mesh pool may enable on the CPU. `d3d12_mesh_test` resolves a query
3306 and the mixed query has more clipping and pixel-shader invocations than the vertex-only one. On the RX 9060 XT 3335 around a vertex, two mesh and a vertex draw, one around a mesh draw and one around the two vertex draws: the vertex
3307 (RADV), the clipping counts add up exactly (2 + 10 = 12). 3336 fields count only the two triangles, the mixed query has the same clipping count as the vertex-only one and more
3337 pixel-shader invocations, and the mesh-only query has no clipping count without the mesh-primitives query below.
3338- **The clipping invocations of a mesh segment** (D3D-MESH-CLIPPING-COUNTER). D3D-291 leaves `CInvocations` and
3339 `CPrimitives` of a mesh segment at 0, because Vulkan has no clipping counter during a mesh draw. Where the device
3340 has the `meshShaderQueries` feature of `VK_EXT_mesh_shader`, the number of primitives the mesh shader emitted
3341 comes from a `VK_QUERY_TYPE_MESH_PRIMITIVES_GENERATED_EXT` query instead: a third pool of the submission, begun
3342 and ended with each mesh segment, next to the two the statistics split needs. Its count is copied to field 5 of the
3343 segment's record and `statistics_sum.comp` adds it as `CInvocations`; `CPrimitives` stays 0, because Vulkan has
3344 no clipped-primitive counter and D3D12's `CPrimitives` is the clipper's output (0 when a triangle is dropped, 2
3345 when it is split). The count is not D3D12's number: Vulkan counts a primitive the mesh shader culled with
3346 `gl_CullPrimitiveEXT`, which D3D12 does not count, so a mesh segment's `CInvocations` can be higher than D3D12's.
3347 Without the feature the field reads 0, as in D3D-291.
3308- **Timestamps.** `GetTimestampFrequency` is `1e9 / timestampPeriod` (1 GHz on the test GPU). Every D3D12 queue 3348- **Timestamps.** `GetTimestampFrequency` is `1e9 / timestampPeriod` (1 GHz on the test GPU). Every D3D12 queue
3309 shares one `VkQueue` for now (question 12), so they share one frequency. 3349 shares one `VkQueue` for now (question 12), so they share one frequency.
3310- **Timestamp resolves on MoltenVK.** On Apple GPUs, MoltenVK delays every `vkCmdWriteTimestamp` to the end of 3350- **Timestamp resolves on MoltenVK.** On Apple GPUs, MoltenVK delays every `vkCmdWriteTimestamp` to the end of
@@ -3506,6 +3546,7 @@ to be recovered from call sites (or the NDA GDK headers, if a developer has acce
3506| DCC / texture compatibility | Public release note for `D3D12XBOX_RESOURCE_FLAG_FORCE_TEXTURE_COMPATIBILITY` | Let Vulkan choose compression; fail if the game aliases/reads raw compressed data. | 3546| DCC / texture compatibility | Public release note for `D3D12XBOX_RESOURCE_FLAG_FORCE_TEXTURE_COMPATIBILITY` | Let Vulkan choose compression; fail if the game aliases/reads raw compressed data. |
3507| PresentX / present planes / frame events | Public GDK samples (MIT/zlib), §4.5 | Likely the only present path of a GDKX title. Presenter + vblank-timed frame events; 1-2 planes composed into the Vulkan swapchain (placement, filter, alpha overlay, HDR10 conversions). Call shapes known; slots/layouts **Open**. | 3547| PresentX / present planes / frame events | Public GDK samples (MIT/zlib), §4.5 | Likely the only present path of a GDKX title. Presenter + vblank-timed frame events; 1-2 planes composed into the Vulkan swapchain (placement, filter, alpha overlay, HDR10 conversions). Call shapes known; slots/layouts **Open**. |
3508| Device slots 48/73/78/79/80 | Public HLE `Freminet`/`ScarlettX` (third-party, not Microsoft documentation) | `d3d12_xs_device.cpp` routes `CreateCommandQueueX` (48), `CreateCommandListX` (73), `SetFrameIntervalX` (78), `ScheduleFrameEventX` (79) and `WaitFrameEventX` (80) before it indexes the PC vtable. Queue and list creation use the existing create paths. The frame-event calls are a per-device token counter: `WaitFrameEventX` returns at once with a fresh non-zero token, because there is no vblank source before a presenter exists. The five indices can be moved with `LEONIDA_XS_QUEUE_X_SLOT`, `LEONIDA_XS_LIST_X_SLOT`, `LEONIDA_XS_FRAME_INTERVAL_SLOT`, `LEONIDA_XS_SCHEDULE_EVENT_SLOT` and `LEONIDA_XS_WAIT_EVENT_SLOT` (3..127; a value that names a slot the proxy already handles keeps that slot's handler); a trace that disagrees wins. | 3548| Device slots 48/73/78/79/80 | Public HLE `Freminet`/`ScarlettX` (third-party, not Microsoft documentation) | `d3d12_xs_device.cpp` routes `CreateCommandQueueX` (48), `CreateCommandListX` (73), `SetFrameIntervalX` (78), `ScheduleFrameEventX` (79) and `WaitFrameEventX` (80) before it indexes the PC vtable. Queue and list creation use the existing create paths. The frame-event calls are a per-device token counter: `WaitFrameEventX` returns at once with a fresh non-zero token, because there is no vblank source before a presenter exists. The five indices can be moved with `LEONIDA_XS_QUEUE_X_SLOT`, `LEONIDA_XS_LIST_X_SLOT`, `LEONIDA_XS_FRAME_INTERVAL_SLOT`, `LEONIDA_XS_SCHEDULE_EVENT_SLOT` and `LEONIDA_XS_WAIT_EVENT_SLOT` (3..127; a value that names a slot the proxy already handles keeps that slot's handler); a trace that disagrees wins. |
3549| Device slot 81, queue `PresentX`/`SuspendX`/`ResumeX` | XCL (GPL-2.0-only, third-party): `GetFrameStatisticsX` at device slot 81, `PresentX` at queue slot 30 (older runtime layout) or 32 (newer); `SuspendX`/`ResumeX` slots unmeasured | `set_presentation_handler` forwards 78-81 and the queue routes to a presenter (`attach_xbox_presentation`; `gta6rt` creates no `XboxPresentation` yet). Without one, slot 81 answers `S_FALSE` with a zero count (no statistics yet) and the queue slots stay refused. Moved with `LEONIDA_XS_FRAME_STATISTICS_SLOT` (3..127) and `LEONIDA_XS_PRESENT_X_SLOT` (default 30); `SuspendX` and `ResumeX` are routed only when `LEONIDA_XS_SUSPEND_X_SLOT` / `LEONIDA_XS_RESUME_X_SLOT` are set (queue slots 19..127; two routes on one slot are refused with a log). |
3509| VRS | Public `D3D12_SHADING_RATE` / `D3D12_AXIS_SHADING_RATE` | `VK_KHR_fragment_shading_rate`; `RSSetShadingRate`/image-based rate map to `vkCmdSetFragmentShadingRateKHR`. | 3550| VRS | Public `D3D12_SHADING_RATE` / `D3D12_AXIS_SHADING_RATE` | `VK_KHR_fragment_shading_rate`; `RSSetShadingRate`/image-based rate map to `vkCmdSetFragmentShadingRateKHR`. |
3510| Mesh shader tier | Public `D3D12_MESH_SHADER_TIER` | `VK_EXT_mesh_shader`; the 9,282 translated mesh shaders make this a hard requirement for any content that uses them. | 3551| Mesh shader tier | Public `D3D12_MESH_SHADER_TIER` | `VK_EXT_mesh_shader`; the 9,282 translated mesh shaders make this a hard requirement for any content that uses them. |
3511| Wave MMA | Public `D3D12_WAVE_MMA_TIER` | Not used: no shader sets `WAVE_MMA` in SFI0 and none contains `v_mfma`/`v_wmma` (all 26,503, `tools/feature_scan.py`). Answer the tier query truthfully; no cooperative-matrix mapping is needed. | 3552| Wave MMA | Public `D3D12_WAVE_MMA_TIER` | Not used: no shader sets `WAVE_MMA` in SFI0 and none contains `v_mfma`/`v_wmma` (all 26,503, `tools/feature_scan.py`). Answer the tier query truthfully; no cooperative-matrix mapping is needed. |
diff --git a/docs/design.md b/docs/design.md
index dd724a383..9dfb4c4b3 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -275,9 +275,10 @@ How the generated SPIR-V expects the runtime to work:
275| Piece | Contract | 275| Piece | Contract |
276|---|---| 276|---|---|
277| Null sources in 64-bit integer VALU compares | `v_cmp` and `v_cmpx` relations `eq`, `ne`, `lt`, `le`, `gt`, `ge` on `u64` and `i64` read `null` as the 64-bit value 0 in either source, like immediate `0`. Register pairs and immediates retain their existing semantics; `v_cmp` writes the active lane's comparison to VCC/SGPR, while `v_cmpx` narrows EXEC without changing VCC. Source: RDNA2 ISA special operand `null` reads zero; LLVM `llvm-mc -mcpu=gfx1013` accepts the encoding. CPU-checked by `tests/semantic/test_vcmp64_null_src.py` (both sources, signed/unsigned ordering, equality, e32/e64, EXEC and inactive lanes); **not GPU-verified, no corpus count**. | 277| Null sources in 64-bit integer VALU compares | `v_cmp` and `v_cmpx` relations `eq`, `ne`, `lt`, `le`, `gt`, `ge` on `u64` and `i64` read `null` as the 64-bit value 0 in either source, like immediate `0`. Register pairs and immediates retain their existing semantics; `v_cmp` writes the active lane's comparison to VCC/SGPR, while `v_cmpx` narrows EXEC without changing VCC. Source: RDNA2 ISA special operand `null` reads zero; LLVM `llvm-mc -mcpu=gfx1013` accepts the encoding. CPU-checked by `tests/semantic/test_vcmp64_null_src.py` (both sources, signed/unsigned ordering, equality, e32/e64, EXEC and inactive lanes); **not GPU-verified, no corpus count**. |
278| `s_load_dword*` with `vcc` 64-bit base pointer | SMEM `s_load_dword*` accepts `vcc` (`{vcc_lo, vcc_hi}`, hardware `s[106:107]`) as its 64-bit base pointer in `Gen.scalar_load`, loading `%vcc` as the low dword and `%vcc_hi` as the high dword; `s_buffer_load*` still requires a 4-dword V# and rejects 2-dword `vcc`. Source: RDNA2 ISA SMEM `SBASE` encoding (`sbase = 53` -> `s[106:107] = vcc`). Confirmed by corpus count over the 2,684-shader pipeline library compute corpus (79 shaders use `vcc` as the `s_load` base: 72 `s_load_dwordx4 sgpr, vcc`, 6 `s_load_dwordx8 sgpr, vcc`, 1 `s_load_dwordx4 slist, vcc`; all 79 translate and pass `spirv-val` under `--wave64-emulate`) and CPU-checked by `tests/semantic/test_sload_vcc_base.py` (`spirv-as` + `spirv-val`); **not GPU-verified**. |
278| Execution model | One invocation = one lane. Compute and mesh waves derive lanes from the workgroup-local index; other stages use the subgroup lane. A wave = a subgroup, so cross-lane ops (`ds_swizzle`, `v_permlane*`, `v_readlane`/`v_writelane`, `v_mbcnt`) become subgroup shuffles. Wave32 pixel shaders split a 64-lane physical subgroup into two logical waves: lane IDs are `SubgroupLocalInvocationId & 31`, shuffle sources retain the current half (`& 32`), and ballots/votes use that half's 32-bit word. A value the translator knows is uniform (the bindless descriptor index) is read from the half's first running lane, never from a fixed lane, which need not be running (SHADER-1016). Other stage/wave combinations still require subgroup size == wave size or wave64 emulation. **Requires subgroup size == wave size** (wave32 maps directly onto NVIDIA GPUs; wave64 shaders need a 64-wide subgroup or emulation). `v_readlane_b32`/`v_writelane_b32` mask the lane select with 63 in wave64 (`S1[5:0]`) and 31 in wave32 (`S1[4:0]`); until SHADER-52 both used 63, so a wave32 select ≥ 32 pointed past a 32-wide subgroup. GPU-checked with `cs_w32_lane_wrap.asm` (lane 40 → 8). For the fragment-half rule, `ps_bitmask_perm` produced 4096/4096 exact pixels on an AMD Radeon RX 5700 XT; Vulkan reported a default subgroup size of 64 (range 32..64), but does not permit pinning fragment subgroup size on this device. CPU semantic tests compare a 64-lane wave32 pixel subgroup against two 32-lane subgroups for reads/writes, permutations, ballots, and votes. | 279| Execution model | One invocation = one lane. Compute and mesh waves derive lanes from the workgroup-local index; other stages use the subgroup lane. A wave = a subgroup, so cross-lane ops (`ds_swizzle`, `v_permlane*`, `v_readlane`/`v_writelane`, `v_mbcnt`) become subgroup shuffles. Wave32 pixel shaders split a 64-lane physical subgroup into two logical waves: lane IDs are `SubgroupLocalInvocationId & 31`, shuffle sources retain the current half (`& 32`), and ballots/votes use that half's 32-bit word. A value the translator knows is uniform (the bindless descriptor index) is read from the half's first running lane, never from a fixed lane, which need not be running (SHADER-1016). Other stage/wave combinations still require subgroup size == wave size or wave64 emulation. **Requires subgroup size == wave size** (wave32 maps directly onto NVIDIA GPUs; wave64 shaders need a 64-wide subgroup or emulation). `v_readlane_b32`/`v_writelane_b32` mask the lane select with 63 in wave64 (`S1[5:0]`) and 31 in wave32 (`S1[4:0]`); until SHADER-52 both used 63, so a wave32 select ≥ 32 pointed past a 32-wide subgroup. GPU-checked with `cs_w32_lane_wrap.asm` (lane 40 → 8). For the fragment-half rule, `ps_bitmask_perm` produced 4096/4096 exact pixels on an AMD Radeon RX 5700 XT; Vulkan reported a default subgroup size of 64 (range 32..64), but does not permit pinning fragment subgroup size on this device. CPU semantic tests compare a 64-lane wave32 pixel subgroup against two 32-lane subgroups for reads/writes, permutations, ballots, and votes. |
279| DPP | VOP1/VOP2 `_dpp` applies to src0. DPP16 controls (`quad_perm`, `row_shl/shr/ror/share/xmask/mirror/half_mirror`) and DPP8 (`dpp8` + `fi`) select the source lane, then `row_mask` (one bit per 16-lane row) and `bank_mask` (one bit per 4-lane bank) decide which destination lanes update. A lane whose row/bank is off is not written. A source lane outside the row is invalid: `bound_ctrl` 1 uses 0 as src0, otherwise the lane is not written. A source lane inactive under EXEC is used when `fi` is 1; otherwise `bound_ctrl` decides. DPP8 always writes an enabled lane: `fi` 1 reads the inactive source, `fi` 0 uses 0. DPP16/8 never leaves its 16/8-lane group, so this is exact on every subgroup at least that wide; under `--wave64-emulate` the exchange goes through the workgroup buffer like the other cross-lane ops. GPU-checked with `runtime/test/shaders/cs_dpp*.asm` on an RTX 3070 and hardware-measured on an RX 6800. On an RX 6700 XT (gfx1031), `tools/crosslane_fuzz.py --dpp-sweep --oracle hw` checks every DPP16 control × `bound_ctrl` × `fi`, every `row_mask`/`bank_mask` pair and the DPP8 selects in wave32 and wave64: 14,412 cases, all matching these rules (BUILD-162, `docs/shader_validation.md` FUZZ-7). The ballot of the source lanes' EXEC bits and the shuffle are each stored to a Function variable of their own (`Gen.eager`): SPIRV-Cross (MoltenVK) inlines a single-use result into the expression that uses it, which put the ballot on the right of a short-circuiting `&&` and the shuffle in a ternary's arm, so lanes out of their row skipped the ballot and row_shr:1's lane 1 found lane 0 inactive (`cs_dpp_ops` on MoltenVK; SHADER-529). A store is a statement every lane runs. Checked in SPIRV-Cross 1.3.239's MSL for the `cs_dpp*` tests (each op is now its own statement) and by `tests/semantic/test_dpp_eager_subgroup.py`; not yet run on a Mac. Semantics from the RDNA2 ISA, AMD LLVM modifier syntax and the GPUOpen DPP notes. | 280| DPP | VOP1/VOP2 `_dpp` applies to src0. DPP16 controls (`quad_perm`, `row_shl/shr/ror/share/xmask/mirror/half_mirror`) and DPP8 (`dpp8` + `fi`) select the source lane, then `row_mask` (one bit per 16-lane row) and `bank_mask` (one bit per 4-lane bank) decide which destination lanes update. A lane whose row/bank is off is not written. A source lane outside the row is invalid: `bound_ctrl` 1 uses 0 as src0, otherwise the lane is not written. A source lane inactive under EXEC is used when `fi` is 1; otherwise `bound_ctrl` decides. DPP8 always writes an enabled lane: `fi` 1 reads the inactive source, `fi` 0 uses 0. DPP16/8 never leaves its 16/8-lane group, so this is exact on every subgroup at least that wide; under `--wave64-emulate` the exchange goes through the workgroup buffer like the other cross-lane ops. GPU-checked with `runtime/test/shaders/cs_dpp*.asm` on an RTX 3070 and hardware-measured on an RX 6800. On an RX 6700 XT (gfx1031), `tools/crosslane_fuzz.py --dpp-sweep --oracle hw` checks every DPP16 control × `bound_ctrl` × `fi`, every `row_mask`/`bank_mask` pair and the DPP8 selects in wave32 and wave64: 14,412 cases, all matching these rules (BUILD-162, `docs/shader_validation.md` FUZZ-7). The ballot of the source lanes' EXEC bits and the shuffle are each stored to a Function variable of their own (`Gen.eager`): SPIRV-Cross (MoltenVK) inlines a single-use result into the expression that uses it, which put the ballot on the right of a short-circuiting `&&` and the shuffle in a ternary's arm, so lanes out of their row skipped the ballot and row_shr:1's lane 1 found lane 0 inactive (`cs_dpp_ops` on MoltenVK; SHADER-529). A store is a statement every lane runs. Checked in SPIRV-Cross 1.3.239's MSL for the `cs_dpp*` tests (each op is now its own statement) and by `tests/semantic/test_dpp_eager_subgroup.py`; not yet run on a Mac. Semantics from the RDNA2 ISA, AMD LLVM modifier syntax and the GPUOpen DPP notes. |
280| EXEC | A per-invocation `active` flag. VALU writes and exports are masked by it, scalar ops aren't, and `v_cmpx`, saveexec and EXEC writes update it. A pixel lane still inactive at the end is discarded. Measured on native gfx1100 (8 threads): a `v_mov_b32` under `EXEC=0x0F` leaves the other lanes untouched, `EXEC=0` writes nothing, a store writes only active lanes and `v_cmpx_gt_u32` narrows EXEC (4 of 4 cases); note that AMD clang 20 rejects `v_add_co_u32`, `v_sub_co_u32`, `v_add_co_ci_u32` and `v_mad_u64_u32` for `gfx1100`, `gfx1101` and `gfx1102`, so this toolchain could not reproduce the RX 7600 result below, which leaves open whether those parts support the opcodes and says only that they could not be assembled here. **A pixel is written when its lane was on in EXEC at the last `exp ... vm` the path executed (if it executed one) and at the last export to the color target; a path with no export at all goes by EXEC at the end.** The `vm` half is the RDNA2 ISA reference guide's rule (30-November-2020, §11.1 and §11.2.1: EXEC at the export is the valid mask and the final one sent is used; an `exp null ... vm` carries only the mask). The color half is measured: an export sends data only for the lanes that are on, a later export to the same target replaces the earlier one for the whole wave, and a lane with no data from the last one is not written even when a later `exp null done vm` marks it valid. So `exp mrt0 done` (no `vm`) with every lane on, followed by an EXEC write, still writes every pixel, and EXEC off at that export and back on afterwards writes none. **Measured on RDNA2** (AMD Radeon iGPU, gfx1036, driver 26.10.1) with the pixel-shader oracle of #3061 (`ps_oracle.py`), hand-written ISA as the pixel shader of a real draw (wave64 stage): 18 programs that cut EXEC to half of the target before, between or after `exp mrt0` (with and without `vm` and `done`) and `exp null done vm`; all 18 fit the rule, 6 of them differed from the translator, which until 2026-11-23 discarded by EXEC at the end on a path without `vm` and kept the older export's value (or the output's initial value) for a lane that was off at the last color export. The latches (`%vm_mask`, `%col_mask_mrtN`) are only emitted where a path can write EXEC after a `vm` or color export; everywhere else EXEC at the end is the same mask and the SPIR-V is unchanged. With several color targets a pixel stays when any target got an export from its lane (Vulkan cannot skip one attachment per pixel; not measured, the oracle's pipeline has one target); `mrtz` is not part of the color mask (not measured). **Measuring exports needs `s_waitcnt expcnt(0)` after each one**: an export is asynchronous, and without the wait the hardware takes the data and the EXEC of a later moment (`v_mov v9, A; exp mrt0 v9 done vm; v_mov v9, B` shows B, and an EXEC write right after the export decides which pixels are written, which looks like "EXEC at the end decides"); 64 `s_nop 15` have the same effect as the wait. Checked on the CPU by `tests/semantic/test_export_valid_mask.py` and on the GPU by `runtime/test/shaders/ps_exp_color_mask.asm` (RTX 5080 and the Radeon). VALU scalar lane-mask destinations (`v_cmp_*`, `v_add_co_u32`, `v_add_co_ci_u32`, `v_sub_co_u32`, `v_sub_co_ci_u32`, `v_subrev_co_u32`, `v_subrev_co_ci_u32`, `v_mad_u64_u32`, `v_mad_i64_i32`) write 0 for lanes off in EXEC (`SDST[lane] = EXEC[lane] ? bit : 0`, AMD RDNA2 ISA). Until 2026-11-22 the six `*_co_*` ops and `v_mad_u64_u32`/`v_mad_i64_i32` did not AND the carry/sign bit with `active`, so inactive lanes leaked 1 bits into `VCC`/SGPR masks (`s_bcnt1`, `s_cbranch_vccz`, `v_cndmask_b32`). Checked on the CPU by `tests/semantic/test_carry_exec_mask.py` (wave32, wave64, and `--wave64-emulate` structure), and **hardware-verified on an AMD RX 7600 (gfx1102)** with `v_add_co_u32` and `v_add_co_ci_u32` carrying on every active lane: VCC reads `0xffffffff` with full EXEC, `0x0000ffff` for the mask `0x0000ffff` and `0xaaaaaaaa` for `0xaaaaaaaa` in wave32, `vcc_lo = 0x0000ffff` with `vcc_hi = 0x0000000f` for the same partial mask in wave64, and `0` when EXEC is 0 even with VCC preloaded to all ones; with one carrying lane under mask `0x0000ffff` VCC is `0x00000001`, and `v_sub_co_u32`/`v_subrev_co_u32` with a borrow under that mask give `0x0000ffff` too. The `*_co_ci_` forms, `v_mad_u64_u32` and `v_mad_i64_i32` share the same path but were not measured separately; it is also GPU-verified on native RDNA2 (gfx1036, AMD Radeon Graphics) with partial EXEC masks (inactive lanes write 0 in sdst for `v_add_co_u32` and `v_mad_u64_u32`). In a shader that writes EXEC, a run of two or more lane-local VALU instructions (no cross-lane read, no lane-mask, SCC, carry or EXEC write) sits inside one `if (active)` and writes its VGPRs directly, instead of an `OpSelect(active, new, old)` per write: the same result, but the driver predicates the run with its own EXEC instead of keeping both values live. On an RX 5700 XT (RADV) a pixel shader with 8 divergent if/else regions of `v_fma`/`v_mul`/`v_add`/`v_min`/`v_max` went from 0.85 ms to 0.69 ms (the same program as native SPIR-V: 0.65 ms). Not under `--wave64-emulate`. Checked by `tests/semantic/test_active_runs.py`. | 281| EXEC | A per-invocation `active` flag. VALU writes and exports are masked by it, scalar ops aren't, and `v_cmpx`, saveexec and EXEC writes update it. Measured on native gfx1100 (8 threads): a `v_mov_b32` under `EXEC=0x0F` leaves the other lanes untouched, `EXEC=0` writes nothing, a store writes only active lanes and `v_cmpx_gt_u32` narrows EXEC (4 of 4 cases); note that AMD clang 20 rejects `v_add_co_u32`, `v_sub_co_u32`, `v_add_co_ci_u32` and `v_mad_u64_u32` for `gfx1100`, `gfx1101` and `gfx1102`, so this toolchain could not reproduce the RX 7600 result below, which leaves open whether those parts support the opcodes and says only that they could not be assembled here. **A pixel is written when its lane was on in EXEC at the last `exp ... vm` the path executed (if it executed one) and at the last export to the color target; a path with no export at all goes by EXEC at the end.** The `vm` half is the RDNA2 ISA reference guide's rule (30-November-2020, §11.1 and §11.2.1: EXEC at the export is the valid mask and the final one sent is used; an `exp null ... vm` carries only the mask). The color half is measured: an export sends data only for the lanes that are on, a later export to the same target replaces the earlier one for the whole wave, and a lane with no data from the last one is not written even when a later `exp null done vm` marks it valid. So `exp mrt0 done` (no `vm`) with every lane on, followed by an EXEC write, still writes every pixel, and EXEC off at that export and back on afterwards writes none. **Measured on RDNA2** (AMD Radeon iGPU, gfx1036, driver 26.10.1) with the pixel-shader oracle of #3061 (`ps_oracle.py`), hand-written ISA as the pixel shader of a real draw (wave64 stage): 18 programs that cut EXEC to half of the target before, between or after `exp mrt0` (with and without `vm` and `done`) and `exp null done vm`; all 18 fit the rule, 6 of them differed from the translator, which until 2026-11-23 discarded by EXEC at the end on a path without `vm` and kept the older export's value (or the output's initial value) for a lane that was off at the last color export. The latches (`%vm_mask`, `%col_mask_mrtN`) are only emitted where a path can write EXEC after a `vm` or color export; everywhere else EXEC at the end is the same mask and the SPIR-V is unchanged. With several color targets a pixel stays when any target got an export from its lane (Vulkan cannot skip one attachment per pixel; not measured, the oracle's pipeline has one target); `mrtz` is not part of the color mask (not measured). **Measuring exports needs `s_waitcnt expcnt(0)` after each one**: an export is asynchronous, and without the wait the hardware takes the data and the EXEC of a later moment (`v_mov v9, A; exp mrt0 v9 done vm; v_mov v9, B` shows B, and an EXEC write right after the export decides which pixels are written, which looks like "EXEC at the end decides"); 64 `s_nop 15` have the same effect as the wait. Checked on the CPU by `tests/semantic/test_export_valid_mask.py` and on the GPU by `runtime/test/shaders/ps_exp_color_mask.asm` (RTX 5080 and the Radeon). VALU scalar lane-mask destinations (`v_cmp_*`, `v_add_co_u32`, `v_add_co_ci_u32`, `v_sub_co_u32`, `v_sub_co_ci_u32`, `v_subrev_co_u32`, `v_subrev_co_ci_u32`, `v_mad_u64_u32`, `v_mad_i64_i32`) write 0 for lanes off in EXEC (`SDST[lane] = EXEC[lane] ? bit : 0`, AMD RDNA2 ISA). Until 2026-11-22 the six `*_co_*` ops and `v_mad_u64_u32`/`v_mad_i64_i32` did not AND the carry/sign bit with `active`, so inactive lanes leaked 1 bits into `VCC`/SGPR masks (`s_bcnt1`, `s_cbranch_vccz`, `v_cndmask_b32`). Checked on the CPU by `tests/semantic/test_carry_exec_mask.py` (wave32, wave64, and `--wave64-emulate` structure), and **hardware-verified on an AMD RX 7600 (gfx1102)** with `v_add_co_u32` and `v_add_co_ci_u32` carrying on every active lane: VCC reads `0xffffffff` with full EXEC, `0x0000ffff` for the mask `0x0000ffff` and `0xaaaaaaaa` for `0xaaaaaaaa` in wave32, `vcc_lo = 0x0000ffff` with `vcc_hi = 0x0000000f` for the same partial mask in wave64, and `0` when EXEC is 0 even with VCC preloaded to all ones; with one carrying lane under mask `0x0000ffff` VCC is `0x00000001`, and `v_sub_co_u32`/`v_subrev_co_u32` with a borrow under that mask give `0x0000ffff` too. The `*_co_ci_` forms, `v_mad_u64_u32` and `v_mad_i64_i32` share the same path but were not measured separately; it is also GPU-verified on native RDNA2 (gfx1036, AMD Radeon Graphics) with partial EXEC masks (inactive lanes write 0 in sdst for `v_add_co_u32` and `v_mad_u64_u32`). In a shader that writes EXEC, a run of two or more lane-local VALU instructions (no cross-lane read, no lane-mask, SCC, carry or EXEC write) sits inside one `if (active)` and writes its VGPRs directly, instead of an `OpSelect(active, new, old)` per write: the same result, but the driver predicates the run with its own EXEC instead of keeping both values live. On an RX 5700 XT (RADV) a pixel shader with 8 divergent if/else regions of `v_fma`/`v_mul`/`v_add`/`v_min`/`v_max` went from 0.85 ms to 0.69 ms (the same program as native SPIR-V: 0.65 ms). Not under `--wave64-emulate`. Checked by `tests/semantic/test_active_runs.py`. |
281| `s_*_saveexec_b32/b64`, `s_andn1/andn2_wrexec_b32/b64` | RDNA2 ISA SOP1. saveexec: `D = EXEC; EXEC = f(S0, EXEC); SCC = (EXEC != 0)`. wrexec: `EXEC = f(S0, EXEC); D = EXEC`. `f` is one of `and`, `or`, `xor`, `andn1` (`~S0 & EXEC`), `andn2` (`S0 & ~EXEC`), `orn1` (`~S0 \| EXEC`), `orn2` (`S0 \| ~EXEC`), `nand`, `nor`, `xnor`, the table in `Gen.EXEC_LOGIC`. The definitions match `tools/cf_ref.py` `_SAVEEXEC`, the FUZZ-8 model. Each invocation holds its own lane's bit (0 or ~0), so `f` is the bitwise op on that bit. A lane EXEC had off becomes active when `f` gives 1 for it (`nand`, `nor`, `orn1`, `orn2`, `xnor`, ...), as on hardware, and SCC is the wave vote. Until 2026-11-22 only `and`/`or`/`andn2_saveexec` and `andn2_wrexec` were translated. CPU-checked by `tests/semantic/test_saveexec_variants.py` (all ten saveexec kinds in wave32 and wave64, both wrexec kinds, partial EXEC and S0, an empty result, every lane against `cf_ref._SAVEEXEC`) and by `tools/cf_diff.py` (300 programs × wave32/64 still pass). Hardware-verified on native RDNA2 (`gfx1036`, Windows 11, driver `32.0.21045.29003`, wave32 & wave64, 0 mismatches): all 10 `saveexec` kinds and both `wrexec` kinds (`andn1`/`andn2`) match bit-for-bit on non-symmetric masks (`src0 = 0x0F0F0F0F`, `exec = 0x33333333` in wave32; `0x0F0F0F0F_00FF00FF` / `0x33333333_55555555` in wave64), zero-result `SCC = 0`, wave64 upper-32-bit-only `new_exec = 0x00000001_00000000` setting `SCC = 1`, and `sdst == src0` register aliasing (`s4, s4` and `s[4:5], s[4:5]`) reading original `src0` before writing old `EXEC` to `sdst`. **Not GPU-verified** for the seven new kinds. Measured on native gfx1100 (single 8-lane workgroup, 36 programs): all ten `saveexec` kinds and both `wrexec` forms follow `f` for three `S0`/`EXEC` pairs, including lanes `EXEC` had off being switched back on (`nand` with `S0=0x03`, `EXEC=0x0F` leaves `0xFFFFFFFC`, activating lanes 4-7), `D` holding the old `EXEC` for `saveexec` and the new one for `wrexec`, and `SCC` the `EXEC != 0` vote. | 282| `s_*_saveexec_b32/b64`, `s_andn1/andn2_wrexec_b32/b64` | RDNA2 ISA SOP1. saveexec: `D = EXEC; EXEC = f(S0, EXEC); SCC = (EXEC != 0)`. wrexec: `EXEC = f(S0, EXEC); D = EXEC`. `f` is one of `and`, `or`, `xor`, `andn1` (`~S0 & EXEC`), `andn2` (`S0 & ~EXEC`), `orn1` (`~S0 \| EXEC`), `orn2` (`S0 \| ~EXEC`), `nand`, `nor`, `xnor`, the table in `Gen.EXEC_LOGIC`. The definitions match `tools/cf_ref.py` `_SAVEEXEC`, the FUZZ-8 model. Each invocation holds its own lane's bit (0 or ~0), so `f` is the bitwise op on that bit. A lane EXEC had off becomes active when `f` gives 1 for it (`nand`, `nor`, `orn1`, `orn2`, `xnor`, ...), as on hardware, and SCC is the wave vote. Until 2026-11-22 only `and`/`or`/`andn2_saveexec` and `andn2_wrexec` were translated. CPU-checked by `tests/semantic/test_saveexec_variants.py` (all ten saveexec kinds in wave32 and wave64, both wrexec kinds, partial EXEC and S0, an empty result, every lane against `cf_ref._SAVEEXEC`) and by `tools/cf_diff.py` (300 programs × wave32/64 still pass). Hardware-verified on native RDNA2 (`gfx1036`, Windows 11, driver `32.0.21045.29003`, wave32 & wave64, 0 mismatches): all 10 `saveexec` kinds and both `wrexec` kinds (`andn1`/`andn2`) match bit-for-bit on non-symmetric masks (`src0 = 0x0F0F0F0F`, `exec = 0x33333333` in wave32; `0x0F0F0F0F_00FF00FF` / `0x33333333_55555555` in wave64), zero-result `SCC = 0`, wave64 upper-32-bit-only `new_exec = 0x00000001_00000000` setting `SCC = 1`, and `sdst == src0` register aliasing (`s4, s4` and `s[4:5], s[4:5]`) reading original `src0` before writing old `EXEC` to `sdst`. **Not GPU-verified** for the seven new kinds. Measured on native gfx1100 (single 8-lane workgroup, 36 programs): all ten `saveexec` kinds and both `wrexec` forms follow `f` for three `S0`/`EXEC` pairs, including lanes `EXEC` had off being switched back on (`nand` with `S0=0x03`, `EXEC=0x0F` leaves `0xFFFFFFFC`, activating lanes 4-7), `D` holding the old `EXEC` for `saveexec` and the new one for `wrexec`, and `SCC` the `EXEC != 0` vote. |
282| Control flow | Reducible graphs use structured branches and natural loops. Irreducible graphs use the dispatch-loop form, which can also be forced with `--dispatch-loop` for comparisons. The control-flow unit test checks 18,228 generated graphs. Irreducible graphs use node splitting (`cfg_structure.split_irreducible`, up to `min(2*N, N+64)` blocks) and fall back to the dispatch-loop form when capped; it can also be forced with `--dispatch-loop` for comparisons. `cfg_structure.structure`, `cfg_structure.run`, and `rdna2spirv.assemble`'s structured emitter are iterative and hoist each guarded member's dominated tail continuation out of its enclosing guard (exact by strict dominance: no block outside the guard's subtree can target the continuation), keeping `OpSelectionMerge` nesting O(1) on sequential diamond/loop chains instead of nesting O(N) deep and hitting Python's recursion limit on multi-thousand-block shaders (e.g. 2,000 sequential diamonds nest to depth 2 instead of 2,000). The control-flow unit test (`tests/test_cfg_structure.py`) checks 20,000 generated graphs plus 2,000-diamond, 1,200-loop, and 1,500-early-exit chains. AMD A/B checks compare the two forms for selected pixel shaders with defined test inputs. For shaders that never export colour, the comparison checks pixel coverage. **Nesting is bounded (SHADER-299):** a tree deeper than `MAX_STRUCTURED_DEPTH` (16) is emitted in the dispatch-loop form instead, since `spirv-val` time grows roughly with the cube of the measured nesting depth. **Nesting is bounded (SHADER-299, SHADER-427):** a tree deeper than `MAX_STRUCTURED_DEPTH` (64; `--max-structured-depth N`, 0 = no bound) is emitted in the dispatch-loop form instead, since `spirv-val` time grows roughly with the cube of the measured nesting depth. Before #1904, over the 1.0.2.1 corpus (26,503 modules, `spirv-val` 2026.4): the deepest block of a module is nested 118 constructs deep, 12,963 modules are structured (median 15) and 6,000 of those are deeper than 16; an estimated 85% of the corpus's `spirv-val` time is in modules nested 20 or deeper. Median `spirv-val` time for the same module in each form: depth 20 181 -> 129 ms (1.4x), 30 507 -> 371 (1.4x), 50 1,712 -> 738 (2.3x), 64 2,692 -> 1,163 (2.3x), 77 5,122 -> 1,130 (4.5x), and the deepest (118) 13,683 -> 1,352 ms (10.1x). Depth 5-12 shows no gain (at depth 6 the flat form is slightly slower), which is why the bound first sat at 16. Since #1904 (`cfg_structure` hoists tails) the deepest tree in the corpus is 29: of 12,944 structured modules, 1,031 are deeper than 16 (747 CS, 284 PS), 57 deeper than 20, 24 deeper than 24. For those 1,031 the flat form saves only 12% of `spirv-val` time (1,235 -> 1,091 s summed, slowest module 8.3 -> 5.9 s), while on an RTX 5070 Ti (NVIDIA 621.24) it compiles slower: the 284 pixel shaders 1.67x (827 -> 1,382 s summed, two rounds), four compute modules at depth 19-24 2.0x (297 -> 591 s, 1.6-2.7x each), so the bound now sits above the corpus (SHADER-427). Both forms pass `spirv-val` on a 200-shader slice (200/200 each), and `gen.nesting` records the tree depth. AMD's Windows driver adds a reason to keep the structured form (SHADER-995): on a Radeon gfx1036 iGPU (32.0.21042.62) the dispatch-loop module of `XboxBvhBuilder.dll`'s `LeafRehydration` (tree depth 18, a 581-case switch) takes 34 minutes to create (XXDESIGN), where its structured module is created in 2.9 s; ten other programs of that DLL compile in the dispatch-loop form there in 0.4-40 s, 2.5-5x their structured time ([embedded_shaders.md](embedded_shaders.md), section 7). | 283| Control flow | Reducible graphs use structured branches and natural loops. Irreducible graphs use the dispatch-loop form, which can also be forced with `--dispatch-loop` for comparisons. The control-flow unit test checks 18,228 generated graphs. Irreducible graphs use node splitting (`cfg_structure.split_irreducible`, up to `min(2*N, N+64)` blocks) and fall back to the dispatch-loop form when capped; it can also be forced with `--dispatch-loop` for comparisons. `cfg_structure.structure`, `cfg_structure.run`, and `rdna2spirv.assemble`'s structured emitter are iterative and hoist each guarded member's dominated tail continuation out of its enclosing guard (exact by strict dominance: no block outside the guard's subtree can target the continuation), keeping `OpSelectionMerge` nesting O(1) on sequential diamond/loop chains instead of nesting O(N) deep and hitting Python's recursion limit on multi-thousand-block shaders (e.g. 2,000 sequential diamonds nest to depth 2 instead of 2,000). The control-flow unit test (`tests/test_cfg_structure.py`) checks 20,000 generated graphs plus 2,000-diamond, 1,200-loop, and 1,500-early-exit chains. AMD A/B checks compare the two forms for selected pixel shaders with defined test inputs. For shaders that never export colour, the comparison checks pixel coverage. **Nesting is bounded (SHADER-299):** a tree deeper than `MAX_STRUCTURED_DEPTH` (16) is emitted in the dispatch-loop form instead, since `spirv-val` time grows roughly with the cube of the measured nesting depth. **Nesting is bounded (SHADER-299, SHADER-427):** a tree deeper than `MAX_STRUCTURED_DEPTH` (64; `--max-structured-depth N`, 0 = no bound) is emitted in the dispatch-loop form instead, since `spirv-val` time grows roughly with the cube of the measured nesting depth. Before #1904, over the 1.0.2.1 corpus (26,503 modules, `spirv-val` 2026.4): the deepest block of a module is nested 118 constructs deep, 12,963 modules are structured (median 15) and 6,000 of those are deeper than 16; an estimated 85% of the corpus's `spirv-val` time is in modules nested 20 or deeper. Median `spirv-val` time for the same module in each form: depth 20 181 -> 129 ms (1.4x), 30 507 -> 371 (1.4x), 50 1,712 -> 738 (2.3x), 64 2,692 -> 1,163 (2.3x), 77 5,122 -> 1,130 (4.5x), and the deepest (118) 13,683 -> 1,352 ms (10.1x). Depth 5-12 shows no gain (at depth 6 the flat form is slightly slower), which is why the bound first sat at 16. Since #1904 (`cfg_structure` hoists tails) the deepest tree in the corpus is 29: of 12,944 structured modules, 1,031 are deeper than 16 (747 CS, 284 PS), 57 deeper than 20, 24 deeper than 24. For those 1,031 the flat form saves only 12% of `spirv-val` time (1,235 -> 1,091 s summed, slowest module 8.3 -> 5.9 s), while on an RTX 5070 Ti (NVIDIA 621.24) it compiles slower: the 284 pixel shaders 1.67x (827 -> 1,382 s summed, two rounds), four compute modules at depth 19-24 2.0x (297 -> 591 s, 1.6-2.7x each), so the bound now sits above the corpus (SHADER-427). Both forms pass `spirv-val` on a 200-shader slice (200/200 each), and `gen.nesting` records the tree depth. AMD's Windows driver adds a reason to keep the structured form (SHADER-995): on a Radeon gfx1036 iGPU (32.0.21042.62) the dispatch-loop module of `XboxBvhBuilder.dll`'s `LeafRehydration` (tree depth 18, a 581-case switch) takes 34 minutes to create (XXDESIGN), where its structured module is created in 2.9 s; ten other programs of that DLL compile in the dispatch-loop form there in 0.4-40 s, 2.5-5x their structured time ([embedded_shaders.md](embedded_shaders.md), section 7). |
283| User data | **Push constants, 144 bytes:** dwords 0–31 = initial s0–s31 (the user SGPRs the console driver loads from the root signature: descriptor-table pointers, constants and so on), dwords 32–33 = the 64-bit **heap base**, dwords 34–35 = the **code base**: the Xbox VA where the runtime uploaded this shader's whole FSSM blob. `--mesh-compute` modules add dwords 36–37, the output buffer address (152 bytes; see "Mesh shaders as compute"). `--pc-tail-ubo` keeps only dwords 0–31 here (128 bytes) and moves the rest to a uniform block (see "Push-constant tail as a uniform block"). The runtime has to reproduce the console driver's root-signature-to-user-SGPR mapping; that comes from the exe or driver behaviour. | 284| User data | **Push constants, 144 bytes:** dwords 0–31 = initial s0–s31 (the user SGPRs the console driver loads from the root signature: descriptor-table pointers, constants and so on), dwords 32–33 = the 64-bit **heap base**, dwords 34–35 = the **code base**: the Xbox VA where the runtime uploaded this shader's whole FSSM blob. `--mesh-compute` modules add dwords 36–37, the output buffer address (152 bytes; see "Mesh shaders as compute"). `--pc-tail-ubo` keeps only dwords 0–31 here (128 bytes) and moves the rest to a uniform block (see "Push-constant tail as a uniform block"). The runtime has to reproduce the console driver's root-signature-to-user-SGPR mapping; that comes from the exe or driver behaviour. |
@@ -371,7 +372,7 @@ How the generated SPIR-V expects the runtime to work:
371| Mixed flat and smooth f32 reads | A pixel shader may use `v_interp_mov_f32 p0` and `v_interp_p1/p2_f32` on the same input location. The translator declares it `PerVertexKHR`, takes vertex 0 for the MOV, and interpolates the smooth read with the triangle weights. The fallback modes without per-vertex inputs reject this combination. The synthetic `mixed_f32_varying.asm` fixture and the SPIR-V interpreter check both reads at two points of one triangle, and both fallback modes raise Unsupported (`test_p0_and_interpolated_read_of_one_f32_location` in `tests/semantic/test_interp_mov_flat.py`). [AMD RDNA 2 ISA, VINTRP instructions](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) | 372| Mixed flat and smooth f32 reads | A pixel shader may use `v_interp_mov_f32 p0` and `v_interp_p1/p2_f32` on the same input location. The translator declares it `PerVertexKHR`, takes vertex 0 for the MOV, and interpolates the smooth read with the triangle weights. The fallback modes without per-vertex inputs reject this combination. The synthetic `mixed_f32_varying.asm` fixture and the SPIR-V interpreter check both reads at two points of one triangle, and both fallback modes raise Unsupported (`test_p0_and_interpolated_read_of_one_f32_location` in `tests/semantic/test_interp_mov_flat.py`). [AMD RDNA 2 ISA, VINTRP instructions](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) |
372| Computed I/J barycentrics (SHADER-177) | `v_interp_p1/p2` weight the interpolation with the values their operand VGPRs hold at the two ops, not with the hardware's own pair. Vonsek's image evidence on a synthetic triangle (#1224): zeroed sources render P0 = (0,0) on all 4,096 pixels, and copies of the pair read in swapped order render (v,u) — both follow the two VINTRP equations in the RDNA2 ISA guide; the centre interpolation the single-lane model used to emit is wrong for both. When a write of the operand register reaches an interp site (earlier in its own basic block, or in any block a path runs through first — loops included; a write at the site itself, an interp whose destination is its own I/J register, happens after the operand is read), the attribute is read `PerVertexKHR` and both ops interpolate with the operand values loaded from `%vgpr`, which holds whatever the program computed: constants (snapped coordinates, 577 straight-line sites), copies and copy chains (575), arithmetic (8), multi-writer sequences (1,135). The p1 loads its I and keeps it for the p2, which loads its J fresh — the program often sets J up between the two ops (574 sites) — so the final value uses the I of the p1 with the J of the p2; the p1's own full-sum value is dead because nothing may read the partial between the ops. Pipodi's straight-line scan puts the upper bound at 213 PS (#1218 comment 7076614458; 2,290 v0/v1 sites plus one PS reading J through a copy, all branchy); the reaching-write analysis finds 207 with a write that can reach an interp, and 6 whose overwrites sit on paths that cannot (left pristine, `.spv` unchanged). The other 11,888 PS keep the interpolated-input read and a byte-identical `.spv`. Composes with the operand guards (row above, #1224): a pristine plain `v_mov` copy of the pair stays the guards' to model (centre interpolation, bit-identical `.spv`, including the corpus's one copy PS), an operand that is neither v0/v1 nor written stays the guards' role-naming refusal, and a computed site is exempt from `interp_pair_src` and modelled here — which relaxes exactly the guards' copy-based refusals whose operand a program write reaches: a twice-written register (`v_mov` then arithmetic — the load reads the value the later write left; value-proven by `test_copy_written_again_is_computed`), a copy of an already-overwritten v0/v1 (Vonsek's zero-before-copy row: hardware renders P0, which is exactly the loaded zeros), and a modified `v_mov_b32_dpp` source (any write of the operand is a `%vgpr` value; translation-only test). A pristine copy in the wrong role still refuses (no computed value to model). Over the corpus the relaxation is empty — every one of the 213 PS names v0/v1 (or the one qualified copy), so on main and on this branch alike the set translates 213/213 and passes `spirv-val` 213/213, and no shader changes class; the guards' refusals that relax are the synthetic ones the tests cover. Refused (naming the pattern): a computed pair whose p1 partial is rewritten or read between the ops (its hardware value P10·I would be observable), one whose ops are not in one basic block (the captured I would not dominate the p2), a dangling op without its partner, any computed pair under `--bary-fallback` or `--f16-interp-fallback` (neither has PerVertexKHR inputs; the latter's decoded-half read would otherwise drop the computed weights), and a computed 32-bit read of a 16-bit-flagged interpolant — every one empty over the corpus. Confirmed by `tests/semantic/test_interp_computed_ij.py` and `tests/semantic/test_interp_guards.py` (Vonsek's rows, the between-ops J, f16 pairs, the refusals, the relaxed classes) and the `ps_ij_computed` GPU test (RTX 5060 Ti: snapped quarter pair = 0.5, zeroed pair = P0 = 0, (i, j/2) halving the second weight with 0.0 max error over 4,096 pixels; the same fixture built on main is wrong on 4,096 of 4,096). | 373| Computed I/J barycentrics (SHADER-177) | `v_interp_p1/p2` weight the interpolation with the values their operand VGPRs hold at the two ops, not with the hardware's own pair. Vonsek's image evidence on a synthetic triangle (#1224): zeroed sources render P0 = (0,0) on all 4,096 pixels, and copies of the pair read in swapped order render (v,u) — both follow the two VINTRP equations in the RDNA2 ISA guide; the centre interpolation the single-lane model used to emit is wrong for both. When a write of the operand register reaches an interp site (earlier in its own basic block, or in any block a path runs through first — loops included; a write at the site itself, an interp whose destination is its own I/J register, happens after the operand is read), the attribute is read `PerVertexKHR` and both ops interpolate with the operand values loaded from `%vgpr`, which holds whatever the program computed: constants (snapped coordinates, 577 straight-line sites), copies and copy chains (575), arithmetic (8), multi-writer sequences (1,135). The p1 loads its I and keeps it for the p2, which loads its J fresh — the program often sets J up between the two ops (574 sites) — so the final value uses the I of the p1 with the J of the p2; the p1's own full-sum value is dead because nothing may read the partial between the ops. Pipodi's straight-line scan puts the upper bound at 213 PS (#1218 comment 7076614458; 2,290 v0/v1 sites plus one PS reading J through a copy, all branchy); the reaching-write analysis finds 207 with a write that can reach an interp, and 6 whose overwrites sit on paths that cannot (left pristine, `.spv` unchanged). The other 11,888 PS keep the interpolated-input read and a byte-identical `.spv`. Composes with the operand guards (row above, #1224): a pristine plain `v_mov` copy of the pair stays the guards' to model (centre interpolation, bit-identical `.spv`, including the corpus's one copy PS), an operand that is neither v0/v1 nor written stays the guards' role-naming refusal, and a computed site is exempt from `interp_pair_src` and modelled here — which relaxes exactly the guards' copy-based refusals whose operand a program write reaches: a twice-written register (`v_mov` then arithmetic — the load reads the value the later write left; value-proven by `test_copy_written_again_is_computed`), a copy of an already-overwritten v0/v1 (Vonsek's zero-before-copy row: hardware renders P0, which is exactly the loaded zeros), and a modified `v_mov_b32_dpp` source (any write of the operand is a `%vgpr` value; translation-only test). A pristine copy in the wrong role still refuses (no computed value to model). Over the corpus the relaxation is empty — every one of the 213 PS names v0/v1 (or the one qualified copy), so on main and on this branch alike the set translates 213/213 and passes `spirv-val` 213/213, and no shader changes class; the guards' refusals that relax are the synthetic ones the tests cover. Refused (naming the pattern): a computed pair whose p1 partial is rewritten or read between the ops (its hardware value P10·I would be observable), one whose ops are not in one basic block (the captured I would not dominate the p2), a dangling op without its partner, any computed pair under `--bary-fallback` or `--f16-interp-fallback` (neither has PerVertexKHR inputs; the latter's decoded-half read would otherwise drop the computed weights), and a computed 32-bit read of a 16-bit-flagged interpolant — every one empty over the corpus. Confirmed by `tests/semantic/test_interp_computed_ij.py` and `tests/semantic/test_interp_guards.py` (Vonsek's rows, the between-ops J, f16 pairs, the refusals, the relaxed classes) and the `ps_ij_computed` GPU test (RTX 5060 Ti: snapped quarter pair = 0.5, zeroed pair = P0 = 0, (i, j/2) halving the second weight with 0.0 max error over 4,096 pixels; the same fixture built on main is wrong on 4,096 of 4,096). |
373| Whole-wave masks | `tools/lane_masks.py` tracks per-lane mask bits through scalar registers, vector operations and saved EXEC spills. Whole-mask counts, first-set-lane queries, the leading-bit scans `s_flbit_i32_b32` / `s_flbit_i32` of `vcc_lo`/`exec_lo` (and `_hi`) and equality use subgroup operations (`tests/semantic/test_salu_flbit_lane_mask.py`; until then the flbit scans saw this lane's 0 / ~0). Whole-mask counts, first-set-lane queries and equality use subgroup operations. `cs_wavemask` checks all 64 lanes with a partially active EXEC mask. A physical 32-lane subgroup cannot directly exchange mask bits with the other half of a wave64, so `cs_wavemask` and the `cs_wave64_ballot` / `cs_wm_*` tests are exact only on 64-wide subgroups (AMD): on an RTX 4090 (subgroup 32) `s_bcnt1_i32_b64` of lanes 16–47 counts 16, one half (#101). `check.py` skips them where the GPU has no 64-wide compute subgroup. A mask copied into a VGPR with `v_mov_b32` goes through the normal EXEC-gated store, so inactive lanes keep the old VGPR (SHADER-21 part 2, #210); per-lane mask computations still store in all lanes, because whole-wave readers (`wave_mask`, `v_readfirstlane`) read every lane's bit. `cs_mask_vgpr_exec` checks it. Vector bitwise mask tracking (`VECTOR_BITWISE`) also includes `v_and_or_b32`, `v_xnor_b32` and `v_bfi_b32` when every source is a lane mask or `0`/`-1` (CPU-checked by `tests/test_lane_masks.py` and `tests/semantic/test_lane_masks_vector_bitwise.py`). | 374| Whole-wave masks | `tools/lane_masks.py` tracks per-lane mask bits through scalar registers, vector operations and saved EXEC spills. Whole-mask counts, first-set-lane queries, the leading-bit scans `s_flbit_i32_b32` / `s_flbit_i32` of `vcc_lo`/`exec_lo` (and `_hi`) and equality use subgroup operations (`tests/semantic/test_salu_flbit_lane_mask.py`; until then the flbit scans saw this lane's 0 / ~0). Whole-mask counts, first-set-lane queries and equality use subgroup operations. `cs_wavemask` checks all 64 lanes with a partially active EXEC mask. A physical 32-lane subgroup cannot directly exchange mask bits with the other half of a wave64, so `cs_wavemask` and the `cs_wave64_ballot` / `cs_wm_*` tests are exact only on 64-wide subgroups (AMD): on an RTX 4090 (subgroup 32) `s_bcnt1_i32_b64` of lanes 16–47 counts 16, one half (#101). `check.py` skips them where the GPU has no 64-wide compute subgroup. A mask copied into a VGPR with `v_mov_b32` goes through the normal EXEC-gated store, so inactive lanes keep the old VGPR (SHADER-21 part 2, #210); per-lane mask computations still store in all lanes, because whole-wave readers (`wave_mask`, `v_readfirstlane`) read every lane's bit. `cs_mask_vgpr_exec` checks it. Vector bitwise mask tracking (`VECTOR_BITWISE`) also includes `v_and_or_b32`, `v_xnor_b32` and `v_bfi_b32` when every source is a lane mask or `0`/`-1` (CPU-checked by `tests/test_lane_masks.py` and `tests/semantic/test_lane_masks_vector_bitwise.py`). |
374| Floating-point operations | Separate floating-point instructions carry `NoContraction` so the driver preserves their individual rounding. The instructions that fuse multiply-add (`v_fma_f32`, `v_fmac_f32`, `v_fmaak_f32`, `v_fmamk_f32`, `v_fma_mix*`) round **once** on RDNA2 (measured on gfx1150 by `tools/f32_fuzz.py --oracle hw`: 72 of 72 cancellation probes fused). SPIR-V has two ways to say that. `GLSL.std.450 Fma` is the default (`--fma glsl`), but the Vulkan SPIR-V environment gives it the precision "inherited from `OpFMul` followed by `OpFAdd`", so a driver may legally round twice; `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice — on Mesa RADV/ACO (Linux), `--fma glsl` splits a subset of the 7 f32 FMAs in `cs_fma_fused` depending on GPU, Mesa version, and shader execution modes (measured: 4 of 7 on RX 6800 / Mesa 26.2.6-arch3.1 and RX 7600 / Mesa 27.0.0-devel with `SignedZeroInfNanPreserve 32`, 5 of 7 on RX 6800 before float controls, and 7 of 7 on Radeon Pro V540 RDNA1 / Mesa 25.2.8), while `--fma khr` emits single-rounded `v_fma_f32` (8/8 exact). `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice. `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice — on an AMD Radeon RX 6800 (Mesa RADV 26.2.6-arch3.1, Linux), RADV/ACO actually splits 5 of the 7 f32 FMAs in `cs_fma_fused` under `--fma glsl` (folding/splitting against the live `v_mul_f32` product `a*a`) and emits single-rounded `v_fma_f32` (8/8 exact) under `--fma khr`. `--fma khr` emits `OpFmaKHR` (`SPV_KHR_fma`, capability `FMAKHR`; "correctly rounded"), which needs `VK_KHR_shader_fma` with `shaderFmaFloat32` on the device. The index then lists capability `FMAKHR`, extension `SPV_KHR_fma` and feature `shaderFmaFloat32` for exactly the shaders that use it, and the output of every shader without a fused multiply-add is byte-identical under both options. `khr` is not the default because a device without the extension would fail pipeline creation; a runtime that knows its device has `shaderFmaFloat32` should translate with `--fma khr`. A device that has neither can split `Fma`: the Intel UHD Graphics driver (Xe-LP, Windows 101.7088) does, `cs_fma_fused` words 0, 2, 3 and 5 coming out split, with no `VK_KHR_shader_fma` (SHADER-497). RADV (Mesa 26.3.1, RX 6700 XT) splits the same four words, measured in #3004's review, but it has `VK_KHR_shader_fma` since Mesa 26.2, so `--fma khr` covers it. For it, `--fma exact` (`Gen.fma_exact`, no extension; per multiply-add about 110 instructions more than `glsl`, plus 31 `NoContraction` decorations and 13 constants) builds the single rounding from `NoContraction` f32 operations, after Boldo and Melquiond (IEEE Transactions on Computers 57(4), 2008): Dekker's exact product with the factors split by masking their low 12 mantissa bits, a TwoSum of the addend and the product, the two error terms summed with round-to-odd, and one final rounding. Power-of-two scaling keeps every intermediate in the normal range: by 2^-64 when the product or the addend is at least 2^126, by 2^96 when both are tiny, and 2^64 traded between a factor below 2^-100 and one above 2^-20. Infinite or NaN operands, and a product beyond even the scaled range (the result is ±inf), take the plain `Fma`. Confirmed: `tests/semantic/test_fma_exact.py` runs the emitted instructions in the interpreter with its `Fma` split as on that driver and compares 700 random and 96 edge cases with an exact rational reference; a model of the same steps matched 399,989 of 399,989 cases with a normal or zero result, with f32 denormals kept and flushed; on the GPU, `cs_fma_fused` (and #2211's `cs_w32_fma_mix`) pass with `--fma exact` on that Intel UHD and on an RTX 3050 Laptop (617.42). Not exact: a result in the denormal range (scaled back with a second rounding) and denormal operands, which follow the driver's denormal mode as every f32 operation does here. The f16 forms (`v_fma_f16`, `v_fmac_f16`, `v_pk_fma_f16`) never use either: they are exact round-to-odd arithmetic built from `OpFMul`/`OpFAdd` with `NoContraction` (`Gen.fma_f16_odd`), so a fused f32 `Fma` would not change them (`v_fma_mixlo_f16`/`v_fma_mixhi_f16` under the toward-zero MODE are the exception: `fma_mix_odd` needs the exact product error `Fma(x, y, -p)`, which is only guaranteed with `OpFmaKHR`), and an f16 `OpFmaKHR` (`shaderFmaFloat16`) is not used. The f64 multiply-adds of `v_div_fmas_f64` (the plain `fma`, the pre-scaled one and the exact product error) are `GLSL.std.450 Fma` on doubles by default, and the Vulkan environment lets a driver round that twice too: NVIDIA's does (RTX 4090, driver 621.24, Windows 11: `runtime/test/shaders/cs_div_fmas_f64.asm`, `fma(a, a, c)` with a = 1 + 2^-30 and c = -(1 + 2^-29) gives the split 0 instead of 2^-60, while the f32 `cs_fma_fused` fuses 8/8). `--fma khr` emits them as `OpFmaKHR` on doubles, which needs `shaderFmaFloat64` (the index lists that feature, and `shaderFmaFloat32` only for a module with an f32 FMA; `vk_pipeline_check` checks each); on the RTX 4090 it gives the fused 2^-60. `--fma exact` has no f64 form and keeps `Fma`. Checked by `tests/semantic/test_fma_khr_f64.py` (emission, index features, `spirv-val`). | 375| Floating-point operations | Separate floating-point instructions carry `NoContraction` so the driver preserves their individual rounding. The instructions that fuse multiply-add (`v_fma_f32`, `v_fmac_f32`, `v_fmaak_f32`, `v_fmamk_f32`, `v_fma_mix*`) round **once** on RDNA2 (measured on gfx1150 by `tools/f32_fuzz.py --oracle hw`: 72 of 72 cancellation probes fused). SPIR-V has two ways to say that. `GLSL.std.450 Fma` is the default (`--fma glsl`), but the Vulkan SPIR-V environment gives it the precision "inherited from `OpFMul` followed by `OpFAdd`", so a driver may legally round twice; `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice — on Mesa RADV/ACO (Linux), `--fma glsl` splits a subset of the 7 f32 FMAs in `cs_fma_fused` depending on GPU, Mesa version, and shader execution modes (measured: 4 of 7 on RX 6800 / Mesa 26.2.6-arch3.1 and RX 7600 / Mesa 27.0.0-devel with `SignedZeroInfNanPreserve 32`, 5 of 7 on RX 6800 before float controls, and 7 of 7 on Radeon Pro V540 RDNA1 / Mesa 25.2.8), while `--fma khr` emits single-rounded `v_fma_f32` (8/8 exact). `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice. `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice — on an AMD Radeon RX 6800 (Mesa RADV 26.2.6-arch3.1, Linux), RADV/ACO actually splits 5 of the 7 f32 FMAs in `cs_fma_fused` under `--fma glsl` (folding/splitting against the live `v_mul_f32` product `a*a`) and emits single-rounded `v_fma_f32` (8/8 exact) under `--fma khr`. `--fma khr` emits `OpFmaKHR` (`SPV_KHR_fma`, capability `FMAKHR`; "correctly rounded"), which needs `VK_KHR_shader_fma` with `shaderFmaFloat32` on the device. The index then lists capability `FMAKHR`, extension `SPV_KHR_fma` and feature `shaderFmaFloat32` for exactly the shaders that use it, and the output of every shader without a fused multiply-add is byte-identical under both options. `khr` is not the default because a device without the extension would fail pipeline creation; a runtime that knows its device has `shaderFmaFloat32` should translate with `--fma khr`. A device that has neither can split `Fma`: the Intel UHD Graphics driver (Xe-LP, Windows 101.7088) does, `cs_fma_fused` words 0, 2, 3 and 5 coming out split, with no `VK_KHR_shader_fma` (SHADER-497). RADV (Mesa 26.3.1, RX 6700 XT) splits the same four words, measured in #3004's review, but it has `VK_KHR_shader_fma` since Mesa 26.2, so `--fma khr` covers it. For it, `--fma exact` (`Gen.fma_exact`, no extension; per multiply-add about 110 instructions more than `glsl`, plus 31 `NoContraction` decorations and 13 constants) builds the single rounding from `NoContraction` f32 operations, after Boldo and Melquiond (IEEE Transactions on Computers 57(4), 2008): Dekker's exact product with the factors split by masking their low 12 mantissa bits, a TwoSum of the addend and the product, the two error terms summed with round-to-odd, and one final rounding. Power-of-two scaling keeps every intermediate in the normal range: by 2^-64 when the product or the addend is at least 2^126, by 2^96 when both are tiny, and 2^64 traded between a factor below 2^-100 and one above 2^-20. Infinite or NaN operands, and a product beyond even the scaled range (the result is ±inf), take the plain `Fma`. Confirmed: `tests/semantic/test_fma_exact.py` runs the emitted instructions in the interpreter with its `Fma` split as on that driver and compares 700 random and 96 edge cases with an exact rational reference; a model of the same steps matched 399,989 of 399,989 cases with a normal or zero result, with f32 denormals kept and flushed; on the GPU, `cs_fma_fused` (and #2211's `cs_w32_fma_mix`) pass with `--fma exact` on that Intel UHD and on an RTX 3050 Laptop (617.42). Not exact: a result in the denormal range (scaled back with a second rounding) and denormal operands, which follow the driver's denormal mode as every f32 operation does here. The f16 forms (`v_fma_f16`, `v_fmac_f16`, `v_pk_fma_f16`) never use either: they are exact round-to-odd arithmetic built from `OpFMul`/`OpFAdd` with `NoContraction` (`Gen.fma_f16_odd`), so a fused f32 `Fma` would not change them (`v_fma_mixlo_f16`/`v_fma_mixhi_f16` under the toward-zero MODE are the exception: `fma_mix_odd` needs the exact product error `Fma(x, y, -p)`, which is only guaranteed with `OpFmaKHR`), and an f16 `OpFmaKHR` (`shaderFmaFloat16`) is not used. The f64 multiply-adds of `v_div_fmas_f64` (the plain `fma`, the pre-scaled one and the exact product error) are `GLSL.std.450 Fma` on doubles by default, and the Vulkan environment lets a driver round that twice too: NVIDIA's does on some GPUs when it folds an all-constant `Fma` while compiling the pipeline: `runtime/test/shaders/cs_div_fmas_f64.asm`, whose operands are literals, gives the split 0 instead of 2^-60 for `fma(a, a, c)` with a = 1 + 2^-30 and c = -(1 + 2^-29) on the RTX 4090 (621.24, Windows), RTX 3070 (621.01, Windows) and Quadro RTX 4000 (Turing, 615.71.09, Linux), and the fused result on an RTX 5060 Laptop (Blackwell, 621.24). `cs_div_fmas_f64_rt.asm` reads the same operands at run time from s4..s7 and is fused on the 4090, 3070 and 5060 (and on an RTX 4070, #4536); the f32 `cs_fma_fused` fuses 8/8 on the 4090. `--fma khr` emits them as `OpFmaKHR` on doubles, which needs `shaderFmaFloat64` (the index lists that feature, and `shaderFmaFloat32` only for a module with an f32 FMA; `vk_pipeline_check` checks each); on the RTX 4090 it gives the fused 2^-60. `--fma exact` has no f64 form and keeps `Fma`. Checked by `tests/semantic/test_fma_khr_f64.py` (emission, index features, `spirv-val`). |
375| `NoContraction` cost on MoltenVK (SHADER-234) | MoltenVK's SPIRV-Cross turns each `NoContraction` `OpFAdd`, `OpFSub` and `OpFMul` into a call to a `[[clang::optnone]]` helper (`spvFAdd`, `spvFSub`, `spvFMul`), and Metal does not inline it. MoltenVK 1.4.2 and `main` up to at least `5189f8de` are affected. SPIRV-Cross `98cbb7c0` inlines the helpers from MSL 3.2 with bit-identical output, and MoltenVK on macOS 26 or newer compiles MSL 4.0. On an Apple M3 Max, a translated compute shader of `v_mul_f32`, `v_add_f32` and `v_sub_f32` in a loop took 7.6 to 15.7 times as long on the GPU with the optnone helpers as with `98cbb7c0`. With independent operations and no `NoContraction`, it took two thirds of the `98cbb7c0` time, which is the cost of the decoration itself ([measurement](https://github.com/ItsNotRexed/Leonida/issues/1380#issuecomment-7078722086)). The same `spvFMul` helper drops the sign of a -0 product (SHADER-182, #1376). | 376| `NoContraction` cost on MoltenVK (SHADER-234) | MoltenVK's SPIRV-Cross turns each `NoContraction` `OpFAdd`, `OpFSub` and `OpFMul` into a call to a `[[clang::optnone]]` helper (`spvFAdd`, `spvFSub`, `spvFMul`), and Metal does not inline it. MoltenVK 1.4.2 and `main` up to at least `5189f8de` are affected. SPIRV-Cross `98cbb7c0` inlines the helpers from MSL 3.2 with bit-identical output, and MoltenVK on macOS 26 or newer compiles MSL 4.0. On an Apple M3 Max, a translated compute shader of `v_mul_f32`, `v_add_f32` and `v_sub_f32` in a loop took 7.6 to 15.7 times as long on the GPU with the optnone helpers as with `98cbb7c0`. With independent operations and no `NoContraction`, it took two thirds of the `98cbb7c0` time, which is the cost of the decoration itself ([measurement](https://github.com/ItsNotRexed/Leonida/issues/1380#issuecomment-7078722086)). The same `spvFMul` helper drops the sign of a -0 product (SHADER-182, #1376). |
376| `NoContraction` multiply on MoltenVK (SHADER-182) | On MoltenVK, a multiply whose exact product is a negative zero (`+0 × -1.5`, `-0 × 1.0`) returns +0 in f32, f16 and packed f16 (#1203). MoltenVK's SPIRV-Cross turns every `NoContraction` `OpFMul` into its `spvFMul` helper, which returns `fma(l, r, T(0))`. A -0 product plus +0 is +0. The f16 multiplies are `OpFMul` on `float` or `v2float`, so they take the same path. So does the product inside `fma_f16_odd`: `v_fma_f16`, `v_fmac_f16` and `v_pk_fma_f16` return +0 for a -0 product plus a -0 addend. SPIRV-Cross [300681bb](https://github.com/KhronosGroup/SPIRV-Cross/commit/300681bbcb8365a8d1eacdacdbdd0249bbf1d6b1) changes the addend to `T(-0.0)`. MoltenVK 1.4.2 has the old helper, and so does MoltenVK `main` at `5189f8de` (2026-10-13), which pins the parent commit `aa217aeb`. The translator does not change for this. `MVK_CONFIG_FAST_MATH_ENABLED=0` does not help, because the helper itself adds +0, and per #1203 neither does `SignedZeroInfNanPreserve` (#664). Measured on an Apple M3 Max (macOS 27.3): Metal keeps the sign for `a * b` and for `fma(a, b, -0.0)` with `MTLMathModeFast` and with `MTLMathModeSafe`, and loses it only with the +0 addend. With `valu_fuzz.py --family f16`, MoltenVK `5189f8de` as pinned matches 49/50 programs with `--seed 1 --wave 32`, 98/100 with `--seed 1 --emulate` and 98/100 with `--seed 4 --emulate`, and Homebrew MoltenVK 1.4.2 gives the same counts. Each mismatch is a -0 product read as +0. The same build with SPIRV-Cross `300681bb` matches 50/50, 100/100 and 100/100, as does KosmicKrisp (Mesa 26.3.1). For the FMA path, `--seed 330 --wave 32` with `--skip-op v_mul_f16 --skip-op v_pk_mul_f16` matches 49/50 with `aa217aeb` (a `v_fmac_f16` result) and 50/50 with `300681bb` and on KosmicKrisp. | 377| `NoContraction` multiply on MoltenVK (SHADER-182) | On MoltenVK, a multiply whose exact product is a negative zero (`+0 × -1.5`, `-0 × 1.0`) returns +0 in f32, f16 and packed f16 (#1203). MoltenVK's SPIRV-Cross turns every `NoContraction` `OpFMul` into its `spvFMul` helper, which returns `fma(l, r, T(0))`. A -0 product plus +0 is +0. The f16 multiplies are `OpFMul` on `float` or `v2float`, so they take the same path. So does the product inside `fma_f16_odd`: `v_fma_f16`, `v_fmac_f16` and `v_pk_fma_f16` return +0 for a -0 product plus a -0 addend. SPIRV-Cross [300681bb](https://github.com/KhronosGroup/SPIRV-Cross/commit/300681bbcb8365a8d1eacdacdbdd0249bbf1d6b1) changes the addend to `T(-0.0)`. MoltenVK 1.4.2 has the old helper, and so does MoltenVK `main` at `5189f8de` (2026-10-13), which pins the parent commit `aa217aeb`. The translator does not change for this. `MVK_CONFIG_FAST_MATH_ENABLED=0` does not help, because the helper itself adds +0, and per #1203 neither does `SignedZeroInfNanPreserve` (#664). Measured on an Apple M3 Max (macOS 27.3): Metal keeps the sign for `a * b` and for `fma(a, b, -0.0)` with `MTLMathModeFast` and with `MTLMathModeSafe`, and loses it only with the +0 addend. With `valu_fuzz.py --family f16`, MoltenVK `5189f8de` as pinned matches 49/50 programs with `--seed 1 --wave 32`, 98/100 with `--seed 1 --emulate` and 98/100 with `--seed 4 --emulate`, and Homebrew MoltenVK 1.4.2 gives the same counts. Each mismatch is a -0 product read as +0. The same build with SPIRV-Cross `300681bb` matches 50/50, 100/100 and 100/100, as does KosmicKrisp (Mesa 26.3.1). For the FMA path, `--seed 330 --wave 32` with `--skip-op v_mul_f16 --skip-op v_pk_mul_f16` matches 49/50 with `aa217aeb` (a `v_fmac_f16` result) and 50/50 with `300681bb` and on KosmicKrisp. |
377| MoltenVK fast-math (SHADER-234, NaN compares) | MoltenVK compiles every shader's MSL with Metal's fast-math on by default (`MVK_CONFIG_FAST_MATH_ENABLED`, default 1), and with it Metal folds an f32 compare of a NaN with itself as if the NaN were an ordinary number: `v_cmpx_eq_f32` and `v_cmpx_le_f32` on (NaN, NaN) give true where the ISA, AMD and NVIDIA give false (`ps_vcmpx_forms`, #1374: word 1 `0xf05e8e16`, want `0xf05e8a12`, bits 2 and 10; found by @zneel and @DomasUrbonas). The translation is not involved: the compare is `OpFOrdEqual` / `OpFOrdLessThanEqual`, and the MSL MoltenVK generates (`MVK_CONFIG_SHADER_DUMP_DIR`) is byte-identical with fast-math on and off, so it is Metal's compile option. `MVK_CONFIG_FAST_MATH_ENABLED=2` (on demand) does not help, because translated modules don't declare an execution mode that asks for IEEE behaviour; 0 does. The test tools (`runtime/test/vulkan_loader.h`, which every Vulkan test program uses to load MoltenVK) set `MVK_CONFIG_FAST_MATH_ENABLED=0` before MoltenVK reads its configuration, unless the variable is already set, so a user's own value still wins; the variable also reaches MoltenVK through the Vulkan loader. A runtime that loads MoltenVK on a Mac must do the same. Fast-math off does **not** remove the `[[clang::optnone]]` `spvFAdd`/`spvFSub`/`spvFMul` helpers SPIRV-Cross emits for `NoContraction` (11 calls in `ps_ops`'s MSL either way: their cost is the other part of SHADER-234), and it does not fix the row above (SHADER-182): `valu_fuzz.py --family f16 --seed 1` gives the same `v_mul_f16` +0 mismatch with fast-math on and off. Confirmed on an Apple A18 Pro (macOS 26.6.2, MoltenVK 1.4.2): `ps_vcmpx_forms` fails on all 4,096 pixels with fast-math on and matches all 4,096 with it off, natively and with wave64 emulation; no other `run_gpu_tests.py` result and none of the 25 `ctest` tests changes. | 378| MoltenVK fast-math (SHADER-234, NaN compares) | MoltenVK compiles every shader's MSL with Metal's fast-math on by default (`MVK_CONFIG_FAST_MATH_ENABLED`, default 1), and with it Metal folds an f32 compare of a NaN with itself as if the NaN were an ordinary number: `v_cmpx_eq_f32` and `v_cmpx_le_f32` on (NaN, NaN) give true where the ISA, AMD and NVIDIA give false (`ps_vcmpx_forms`, #1374: word 1 `0xf05e8e16`, want `0xf05e8a12`, bits 2 and 10; found by @zneel and @DomasUrbonas). The translation is not involved: the compare is `OpFOrdEqual` / `OpFOrdLessThanEqual`, and the MSL MoltenVK generates (`MVK_CONFIG_SHADER_DUMP_DIR`) is byte-identical with fast-math on and off, so it is Metal's compile option. `MVK_CONFIG_FAST_MATH_ENABLED=2` (on demand) does not help, because translated modules don't declare an execution mode that asks for IEEE behaviour; 0 does. The test tools (`runtime/test/vulkan_loader.h`, which every Vulkan test program uses to load MoltenVK) set `MVK_CONFIG_FAST_MATH_ENABLED=0` before MoltenVK reads its configuration, unless the variable is already set, so a user's own value still wins; the variable also reaches MoltenVK through the Vulkan loader. A runtime that loads MoltenVK on a Mac must do the same. Fast-math off does **not** remove the `[[clang::optnone]]` `spvFAdd`/`spvFSub`/`spvFMul` helpers SPIRV-Cross emits for `NoContraction` (11 calls in `ps_ops`'s MSL either way: their cost is the other part of SHADER-234), and it does not fix the row above (SHADER-182): `valu_fuzz.py --family f16 --seed 1` gives the same `v_mul_f16` +0 mismatch with fast-math on and off. Confirmed on an Apple A18 Pro (macOS 26.6.2, MoltenVK 1.4.2): `ps_vcmpx_forms` fails on all 4,096 pixels with fast-math on and matches all 4,096 with it off, natively and with wave64 emulation; no other `run_gpu_tests.py` result and none of the 25 `ctest` tests changes. |
@@ -392,7 +393,7 @@ How the generated SPIR-V expects the runtime to work:
392| Multiply-add with a literal | `v_fmamk_f32`/`v_madmk_f32` are D = S0 × K + S1 and `v_fmaak_f32`/`v_madak_f32` are D = S0 × S1 + K, K being the 32-bit literal. LLVM prints them `vdst, src0, K, vsrc1` and `vdst, src0, vsrc1, K`, so in print order all four are a[1] × a[2] + a[3] (fused for fmamk/fmaak). **Until 2026-11-21 fmamk and madmk computed S0 × S1 + K.** Source: RDNA2 ISA (V_FMAMK_F32, V_MADMK_F32) and the operand fields of the llvm-mc encoding. Checked by `tests/semantic` and GPU-checked with `runtime/test/shaders/ps_fma_literal.asm` on an NVIDIA GeForce RTX 2060 SUPER (Linux, driver 620.70.06): 4096/4096 pixels exact, and 4096/4096 differ with the old translator. | 393| Multiply-add with a literal | `v_fmamk_f32`/`v_madmk_f32` are D = S0 × K + S1 and `v_fmaak_f32`/`v_madak_f32` are D = S0 × S1 + K, K being the 32-bit literal. LLVM prints them `vdst, src0, K, vsrc1` and `vdst, src0, vsrc1, K`, so in print order all four are a[1] × a[2] + a[3] (fused for fmamk/fmaak). **Until 2026-11-21 fmamk and madmk computed S0 × S1 + K.** Source: RDNA2 ISA (V_FMAMK_F32, V_MADMK_F32) and the operand fields of the llvm-mc encoding. Checked by `tests/semantic` and GPU-checked with `runtime/test/shaders/ps_fma_literal.asm` on an NVIDIA GeForce RTX 2060 SUPER (Linux, driver 620.70.06): 4096/4096 pixels exact, and 4096/4096 differ with the old translator. |
393| Multiply-add and output modifiers | `v_mac_f32` is the VOP2 form of `v_mad_f32`, **not** of `v_fma_f32`: the product is rounded before the add (`OpFMul` + `OpFAdd`, both `NoContraction`). It used to emit `Fma`, one ULP off on some inputs. Source: LLVM `SIInstrInfo.cpp` `getNewFMAInst` (`V_MAC_F32` -> `V_MAD_F32_e64`, `V_FMAC_F32` -> `V_FMA_F32_e64`). VOP3 `clamp` and `mul:2`/`mul:4`/`div:2` now apply to `v_cvt_f32_i32`/`u32`/`ubyte0..3`, `v_cvt_f32_f16` and `v_rcp_iflag_f32` (they were dropped). Source: LLVM `VOPProfileI2F` (`Ins64 = $src0, $clamp, $omod`) and the float-source profiles. Found by `tools/f32_fuzz.py` (FUZZ-3: an exact-arithmetic model against the translated SPIR-V; 0 mismatches over 10,000 seeded programs after the fix) and pinned by `runtime/test/shaders/ps_f32_mods.asm` (`tests/semantic/test_f32_valu.py`); **GPU-checked** (TEST-298): `ps_f32_mods` gives the expected four words (`0xc0256a01 0x3f800000 0x41e00000 0x3fc00000`, so the `v_mac_f32` product is not fused and the `clamp`, `mul:4` and `div:2` on `v_cvt_f32_ubyte1`/`u32`/`f16` and `v_rcp_iflag_f32` apply) on an NVIDIA GeForce RTX 2060 SUPER (Linux, driver 615.78.08); `mul:2` on the conversions is not in that fixture. **not yet GPU-verified**. Still open: on some inputs the ISA defines a result but the emitted SPIR-V is undefined: `v_rcp_f32(±0)` (`OpFDiv` by zero), `v_rsq_f32`/`v_log_f32` of ±0 or a negative, `v_sqrt_f32` of a negative. `v_cvt_pk_u8_f32(NaN)` now selects +0 before `FClamp` (see "Float-to-byte pack"). `v_rcp_f32(±0)` (`OpFDiv` by zero), `v_rsq_f32`/`v_log_f32` of ±0 or a negative, `v_sqrt_f32` of a negative (`v_cvt_pk_u8_f32(NaN)` now selects +0 before `FClamp`, see "Float-to-byte pack"). | 394| Multiply-add and output modifiers | `v_mac_f32` is the VOP2 form of `v_mad_f32`, **not** of `v_fma_f32`: the product is rounded before the add (`OpFMul` + `OpFAdd`, both `NoContraction`). It used to emit `Fma`, one ULP off on some inputs. Source: LLVM `SIInstrInfo.cpp` `getNewFMAInst` (`V_MAC_F32` -> `V_MAD_F32_e64`, `V_FMAC_F32` -> `V_FMA_F32_e64`). VOP3 `clamp` and `mul:2`/`mul:4`/`div:2` now apply to `v_cvt_f32_i32`/`u32`/`ubyte0..3`, `v_cvt_f32_f16` and `v_rcp_iflag_f32` (they were dropped). Source: LLVM `VOPProfileI2F` (`Ins64 = $src0, $clamp, $omod`) and the float-source profiles. Found by `tools/f32_fuzz.py` (FUZZ-3: an exact-arithmetic model against the translated SPIR-V; 0 mismatches over 10,000 seeded programs after the fix) and pinned by `runtime/test/shaders/ps_f32_mods.asm` (`tests/semantic/test_f32_valu.py`); **GPU-checked** (TEST-298): `ps_f32_mods` gives the expected four words (`0xc0256a01 0x3f800000 0x41e00000 0x3fc00000`, so the `v_mac_f32` product is not fused and the `clamp`, `mul:4` and `div:2` on `v_cvt_f32_ubyte1`/`u32`/`f16` and `v_rcp_iflag_f32` apply) on an NVIDIA GeForce RTX 2060 SUPER (Linux, driver 615.78.08); `mul:2` on the conversions is not in that fixture. **not yet GPU-verified**. Still open: on some inputs the ISA defines a result but the emitted SPIR-V is undefined: `v_rcp_f32(±0)` (`OpFDiv` by zero), `v_rsq_f32`/`v_log_f32` of ±0 or a negative, `v_sqrt_f32` of a negative. `v_cvt_pk_u8_f32(NaN)` now selects +0 before `FClamp` (see "Float-to-byte pack"). `v_rcp_f32(±0)` (`OpFDiv` by zero), `v_rsq_f32`/`v_log_f32` of ±0 or a negative, `v_sqrt_f32` of a negative (`v_cvt_pk_u8_f32(NaN)` now selects +0 before `FClamp`, see "Float-to-byte pack"). |
394| Output modifiers on hardware (gfx1150, RDNA2) | Measured on a Radeon 880M (gfx1150, RDNA3.5; **not** RDNA2) with `tools/f32_fuzz.py --oracle hw`, 46,967 programs: `mul:2`/`mul:4`/`div:2` turn a -0 result (a flushed denormal result included) into +0, and are ignored with MODE.IEEE = 1; with f32 denormals kept they are also ignored for the ALU ops (the transcendental and cube ops still apply them). LLVM notes that omod mishandles signed zeros (`SIFoldOperands.cpp`) and D30209 describes -0 being forced to +0 before the modifier. The translator keeps -0 (`OpFMul`), so on that evidence it likely differs from hardware (see #1006). **RDNA2 does the same, rule for rule** (SHADER-353): on an RX 6700 XT (gfx1031, a discrete RDNA2 part, not the console's gfx1013; AMD Windows driver 26.11.2), seeds 1 to 6, 39,101 programs, 0 mismatch and 66 omod -0 → +0 deviations. Per MODE, counting only the programs where the omod changes the result: with IEEE off and f32 denormals flushed (the game's mode) it is applied every time (2,680, and the 66 -0 results become +0); with denormals kept it is ignored by the ALU ops (1,811) and applied by `v_rcp/rcp_iflag/rsq/sqrt/exp/log_f32` and the four cube ops (869, -0 → +0 only there); with IEEE on it is ignored (2,650) and a -0 result stays -0. Earlier, gfx1036 (the integrated GPUs of a Ryzen 9 7950X3D and a Ryzen 7 9800X3D) gave seeds 1 to 6, 38,858 programs, 0 mismatch and 56 such deviations, with identical counts through the Linux libdrm launcher and the Windows HIP launcher; `v_rcp_iflag_f32` with `clamp`/`omod` on the same GPU, 6,552 programs, 0 mismatch and 35 such deviations, otherwise behaves like `v_rcp_f32`. Also measured there: with `denorm_mode_32 = 0` f32 denormal operands read as zero and denormal results flush (add/mul/fma/min/max/rounding ops, DX9 mul), exact with 3. `v_fma_mix*` f32 operands read as zero when denormal too (SHADER-298: gfx1036, `0x00000001`, `0x807fffff`, and the integer inline constants 1 and 64; f16 operands widen to normal values); its result is not flushed, since that was not measured. Invalid operations give `0xffc00000`; a signalling NaN passes unchanged with IEEE off and is quieted with IEEE on. Details in docs/shader_validation.md ("32-bit float VALU on the GPU"). | 395| Output modifiers on hardware (gfx1150, RDNA2) | Measured on a Radeon 880M (gfx1150, RDNA3.5; **not** RDNA2) with `tools/f32_fuzz.py --oracle hw`, 46,967 programs: `mul:2`/`mul:4`/`div:2` turn a -0 result (a flushed denormal result included) into +0, and are ignored with MODE.IEEE = 1; with f32 denormals kept they are also ignored for the ALU ops (the transcendental and cube ops still apply them). LLVM notes that omod mishandles signed zeros (`SIFoldOperands.cpp`) and D30209 describes -0 being forced to +0 before the modifier. The translator keeps -0 (`OpFMul`), so on that evidence it likely differs from hardware (see #1006). **RDNA2 does the same, rule for rule** (SHADER-353): on an RX 6700 XT (gfx1031, a discrete RDNA2 part, not the console's gfx1013; AMD Windows driver 26.11.2), seeds 1 to 6, 39,101 programs, 0 mismatch and 66 omod -0 → +0 deviations. Per MODE, counting only the programs where the omod changes the result: with IEEE off and f32 denormals flushed (the game's mode) it is applied every time (2,680, and the 66 -0 results become +0); with denormals kept it is ignored by the ALU ops (1,811) and applied by `v_rcp/rcp_iflag/rsq/sqrt/exp/log_f32` and the four cube ops (869, -0 → +0 only there); with IEEE on it is ignored (2,650) and a -0 result stays -0. Earlier, gfx1036 (the integrated GPUs of a Ryzen 9 7950X3D and a Ryzen 7 9800X3D) gave seeds 1 to 6, 38,858 programs, 0 mismatch and 56 such deviations, with identical counts through the Linux libdrm launcher and the Windows HIP launcher; `v_rcp_iflag_f32` with `clamp`/`omod` on the same GPU, 6,552 programs, 0 mismatch and 35 such deviations, otherwise behaves like `v_rcp_f32`. Also measured there: with `denorm_mode_32 = 0` f32 denormal operands read as zero and denormal results flush (add/mul/fma/min/max/rounding ops, DX9 mul), exact with 3. `v_fma_mix*` f32 operands read as zero when denormal too (SHADER-298: gfx1036, `0x00000001`, `0x807fffff`, and the integer inline constants 1 and 64; f16 operands widen to normal values); its result is not flushed, since that was not measured. Invalid operations give `0xffc00000`; a signalling NaN passes unchanged with IEEE off and is quieted with IEEE on. Details in docs/shader_validation.md ("32-bit float VALU on the GPU"). |
395| Float min/max/med3 with NaN, `v_fract` | Measured on an AMD Radeon RX 6800 (gfx1030, not the console's gfx1013) with the hw-oracle tool from the AnyPS5 project, 537 input rows in all four IEEE/DX10_CLAMP combinations and in wave32 and wave64, the same for every combination with quiet NaNs. `v_min_f32`/`v_max_f32`, `v_min_f16`/`v_max_f16` and each half of `v_pk_min_f16`/`v_pk_max_f16`: one NaN operand gives the other operand, bits unchanged; both NaN give src0; -0 < +0. `v_min3`/`v_max3` = f(f(s0, s1), s2) with that min/max. `v_med3_f32`/`_f16`: with any NaN operand the result is min3(s0, s1, s2), otherwise the median (-0 < +0). `v_fract_f32` rounds x − floor(x) once and returns 0x3f7fffff (the largest float below 1) where that gives 1.0, e.g. fract(-1e-10); f16 gives 0x3bff; fract(-0) = +0, fract(±inf) = NaN, a NaN passes through. Measured natively on gfx1036 (RDNA2) in the MODE inferred for the game (IEEE 0, f32 denormals flushed): `v_floor_f32`, `v_ceil_f32` and `v_fract_f32` read a denormal operand as a zero of its sign (floor(-1e-45) = -0, ceil(+1e-45) = +0, fract of either 0), fract(±inf) is exactly `0xffc00000`, and a NaN operand comes back unchanged, a signalling one too. The translator flushes the operand and selects those words itself (`Gen.round_f32_flushed`) instead of leaving them to the driver's f32 denormal handling, which Vulkan does not fix; until 2026-11-22 a driver that keeps denormals gave -1.0, +1.0 and 0x3f7fffff there. `v_cvt_flr_i32_f32` likewise returns 0 for a negative denormal (the translator gave -1). Checked against 119 measured words by `tests/semantic/test_alu_floor_ceil_fract_hw.py`. For `v_fract_f16`, either infinity gives the gfx1036 word `0xfe00`, or +0 with the DX10 clamp. The translator selects these results explicitly. The hand-written `ps_fract_f16_infinity.asm` fixture checks both signs, the preserved destination bits and a color channel computed from the result sign in the CPU interpreter (`tests/semantic/test_fract_f16_infinity.py`). A source `neg` on a signalling NaN operand still quiets it in the translator. Not changed: f16 fract(±inf) is `0xfe00` on the hardware and a quiet positive NaN in the translator, and `neg` on a signalling NaN operand quiets it in the translator. The translator emits `NMin`/`NMax` for these min/max ops (before: `FMin`/`FMax`, whose NaN result GLSL.std.450 leaves to the implementation). med3 is `NMin(NMax(z, NMin(x, y)), NMax(x, y))` (until 2026-11-22 this used `FClamp(z, lo, hi)`, which was GLSL.std.450 undefined whenever `z` was NaN or both `x` and `y` were NaN), and when an operand can be a NaN, `OpIsNan` of each such operand (none for an inline or literal constant that is not a NaN) selects `NMin(NMin(x, y), z)` instead; all 1-, 2-, and 3-NaN operand positions for both `v_med3_f32` and `v_med3_f16` were hardware-verified on RDNA2 (`gfx1035`, wave32 & wave64). `FMin`/`FMax`, whose NaN result GLSL.std.450 leaves to the implementation). med3 is `FClamp(z, NMin(x, y), NMax(x, y))`, and when an operand can be a NaN, `OpIsNan` of each such operand (none for an inline or literal constant that is not a NaN) selects `NMin(NMin(x, y), z)` instead. `v_fract_f32` is `Fract` followed by `OpFOrdEqual` with 1.0 and an `OpSelect` of 0x3f7fffff, so the NaN of fract(±inf) is kept; `v_fract_f16` does the same before packing and then replaces a packed 0x3c00 with 0x3bff (not after an output multiplier, where 1.0 can be a true result). Other `FMin`/`FMax`/`FClamp` uses (the `clamp` bit, LOD and conversion clamps, `v_cvt_pk_u8_f32`, the BVH slab test) are unchanged. Not modelled: signalling NaNs under IEEE mode; NaN under the `clamp` bit (hardware gives +0 with DX10_CLAMP=1 and the NaN with DX10_CLAMP=0; the translator still emits `FClamp`). All-NaN float min/max/med3 ops (`v_min/max/min3/max3/med3_f32` via `Gen.nminmax_f32`, `v_min/max/min3/max3/med3_f16` via `Gen.f16_in_bits`/`Gen.all_f16_nan_cond`, and per-half `v_pk_min/max_f16` when `clamp` is unset) explicitly preserve `src0`'s NaN bits (including sign, payload, and signalling bit under `IEEE = 0`, matching the RX 6800 and `gfx1036` hardware rules). The CPU tests `tests/semantic/test_minmax_f32_payload.py` and `tests/semantic/test_alu_min3_max3_med3_16_hw.py` check operand-order payload and signalling NaN preservation. Also, without the `SignedZeroInfNanPreserve` execution mode Vulkan does not strictly guarantee NaN or signed-zero behaviour, so these rules hold where the driver keeps them. NaN under the `clamp` bit (hardware gives +0 with DX10_CLAMP=1 and the NaN with DX10_CLAMP=0; the translator still emits `FClamp`); the NaN payload when both operands are NaN (`NMin` only promises a NaN); and without the `SignedZeroInfNanPreserve` execution mode Vulkan does not strictly guarantee NaN or signed-zero behaviour, so these rules hold where the driver keeps them. With an output modifier (`mul:2`, `mul:4`, `div:2`) on `v_fract_f16` the translator applies the modifier to the f32 fract before narrowing to f16; the hardware order of rounding and modifier for that case was not measured, so a result can differ by one f16 step for tiny negative inputs (e.g. x = -1e-4 with `div:2`). GPU-checked with `runtime/test/shaders/ps_fnan_med3.asm` and `ps_fnan_fract.asm` (inputs read from memory at run time) on an AMD Radeon RX 6800, Windows 11, driver 26.11.2: 4096/4096 pixels exact; on that driver the two med3 words differed before the change (0x40e00000 and 0x40600000 instead of 0x40a00000 and 0xc0200000), and so did the f16 fract word (0x3c00 instead of 0x3bff) once f16 results were narrowed with integer round-to-nearest; the f32 fract and the min/max words were already the hardware words there. `tests/semantic/test_float_nan_fract.py` runs the measured rows through the translator and the interpreter. | 396| Float min/max/med3 with NaN, `v_fract` | Measured on an AMD Radeon RX 6800 (gfx1030, not the console's gfx1013) with the hw-oracle tool from the AnyPS5 project, 537 input rows in all four IEEE/DX10_CLAMP combinations and in wave32 and wave64, the same for every combination with quiet NaNs. `v_min_f32`/`v_max_f32`, `v_min_f16`/`v_max_f16` and each half of `v_pk_min_f16`/`v_pk_max_f16`: one NaN operand gives the other operand, bits unchanged; both NaN give src0; -0 < +0. `v_min3`/`v_max3` = f(f(s0, s1), s2) with that min/max. `v_med3_f32`/`_f16`: with any NaN operand the result is min3(s0, s1, s2), otherwise the median (-0 < +0). `v_fract_f32` rounds x − floor(x) once and returns 0x3f7fffff (the largest float below 1) where that gives 1.0, e.g. fract(-1e-10); f16 gives 0x3bff; fract(-0) = +0, fract(±inf) = NaN, a NaN passes through. Measured natively on gfx1036 (RDNA2) in the MODE inferred for the game (IEEE 0, f32 denormals flushed): `v_floor_f32`, `v_ceil_f32` and `v_fract_f32` read a denormal operand as a zero of its sign (floor(-1e-45) = -0, ceil(+1e-45) = +0, fract of either 0), fract(±inf) is exactly `0xffc00000`, and a NaN operand comes back unchanged, a signalling one too. The translator flushes the operand and selects those words itself (`Gen.round_f32_flushed`) instead of leaving them to the driver's f32 denormal handling, which Vulkan does not fix; until 2026-11-22 a driver that keeps denormals gave -1.0, +1.0 and 0x3f7fffff there. `v_cvt_flr_i32_f32` likewise returns 0 for a negative denormal (the translator gave -1). Checked against 119 measured words by `tests/semantic/test_alu_floor_ceil_fract_hw.py`. For `v_fract_f16`, either infinity gives the gfx1036 word `0xfe00`, or +0 with the DX10 clamp. The translator selects these results explicitly. The hand-written `ps_fract_f16_infinity.asm` fixture checks both signs, the preserved destination bits and a color channel computed from the result sign in the CPU interpreter (`tests/semantic/test_fract_f16_infinity.py`). A source `neg` on a signalling NaN operand still quiets it in the translator. Not changed: f16 fract(±inf) is `0xfe00` on the hardware and a quiet positive NaN in the translator, and `neg` on a signalling NaN operand quiets it in the translator. The translator emits `NMin`/`NMax` for these min/max ops (before: `FMin`/`FMax`, whose NaN result GLSL.std.450 leaves to the implementation). med3 is `NMin(NMax(z, NMin(x, y)), NMax(x, y))` (until 2026-11-22 this used `FClamp(z, lo, hi)`, which was GLSL.std.450 undefined whenever `z` was NaN or both `x` and `y` were NaN), and when an operand can be a NaN, `OpIsNan` of each such operand (none for an inline or literal constant that is not a NaN) selects `NMin(NMin(x, y), z)` instead; all 1-, 2-, and 3-NaN operand positions for both `v_med3_f32` and `v_med3_f16` were hardware-verified on RDNA2 (`gfx1035`, wave32 & wave64). `FMin`/`FMax`, whose NaN result GLSL.std.450 leaves to the implementation). med3 is `FClamp(z, NMin(x, y), NMax(x, y))`, and when an operand can be a NaN, `OpIsNan` of each such operand (none for an inline or literal constant that is not a NaN) selects `NMin(NMin(x, y), z)` instead. `v_fract_f32` is `Fract` followed by `OpFOrdEqual` with 1.0 and an `OpSelect` of 0x3f7fffff, so the NaN of fract(±inf) is kept; `v_fract_f16` does the same before packing and then replaces a packed 0x3c00 with 0x3bff (not after an output multiplier, where 1.0 can be a true result). Other `FMin`/`FMax`/`FClamp` uses (LOD and conversion clamps, `v_cvt_pk_u8_f32`, the BVH slab test) are unchanged; for the `clamp` bit see below. Not modelled: signalling NaNs under IEEE mode. NaN under the `clamp` bit: the hardware gives +0 with DX10_CLAMP=1 (the game's MODE) and the NaN with DX10_CLAMP=0, measured on gfx1036 for `v_rcp_iflag_f32` (169 programs, `docs/shader_validation.md`, "32-bit float VALU on the GPU") and for `v_fmac_f16`, `v_fma_mixlo_f16` and `v_fma_mix_f32` (SHADER-186, "f16 output modifiers, clamp and `v_fma_mix*` operands on RDNA2"). The f32 and f16 ops that apply `clamp` through `Gen.clamp_mods`/`Gen.clamp_f16` now select +0 for a NaN before `FClamp`, which GLSL.std.450 leaves undefined for a NaN operand, so they give the DX10_CLAMP=1 word, as `v_div_fixup_f32`, `v_cvt_pk_u8_f32` and the f16 frexp/ldexp clamps already did (**until 2026-11-24 `clamp_mods` emitted a bare `FClamp`**). CPU-checked by `tests/semantic/test_vop3_clamp_nan.py`; not GPU-checked. Still a bare `FClamp`: the f64 clamp (`clamp_mods_f64`) and the packed `v_pk_*` clamp. `v_dot2_f32_f16` routes its `clamp` through `clamp_mods` too, but its clamp is measured as a hardware no-op (open PR #410). All-NaN float min/max/med3 ops (`v_min/max/min3/max3/med3_f32` via `Gen.nminmax_f32`, `v_min/max/min3/max3/med3_f16` via `Gen.f16_in_bits`/`Gen.all_f16_nan_cond`, and per-half `v_pk_min/max_f16` when `clamp` is unset) explicitly preserve `src0`'s NaN bits (including sign, payload, and signalling bit under `IEEE = 0`, matching the RX 6800 and `gfx1036` hardware rules). The CPU tests `tests/semantic/test_minmax_f32_payload.py` and `tests/semantic/test_alu_min3_max3_med3_16_hw.py` check operand-order payload and signalling NaN preservation. Also, without the `SignedZeroInfNanPreserve` execution mode Vulkan does not strictly guarantee NaN or signed-zero behaviour, so these rules hold where the driver keeps them. With an output modifier (`mul:2`, `mul:4`, `div:2`) on `v_fract_f16` the translator applies the modifier to the f32 fract before narrowing to f16; the hardware order of rounding and modifier for that case was not measured, so a result can differ by one f16 step for tiny negative inputs (e.g. x = -1e-4 with `div:2`). GPU-checked with `runtime/test/shaders/ps_fnan_med3.asm` and `ps_fnan_fract.asm` (inputs read from memory at run time) on an AMD Radeon RX 6800, Windows 11, driver 26.11.2: 4096/4096 pixels exact; on that driver the two med3 words differed before the change (0x40e00000 and 0x40600000 instead of 0x40a00000 and 0xc0200000), and so did the f16 fract word (0x3c00 instead of 0x3bff) once f16 results were narrowed with integer round-to-nearest; the f32 fract and the min/max words were already the hardware words there. `tests/semantic/test_float_nan_fract.py` runs the measured rows through the translator and the interpreter. |
396| `ds_swizzle_b32` | An active destination reads the selected source lane's VGPR. If EXEC disables that source, the read returns zero; a disabled destination keeps its prior value. The [hardware measurements](shader_validation.md#hardware-oracle-for-the-lds-programs---oracle-hw) confirm the disabled-source result on gfx1036 and gfx1150. In the seven-invocation CPU fixture, lane 6 selects lane 7, which is absent. The translator returns zero in that case; the corresponding result on hardware is unverified. The fixture exercises `QUAD_PERM` and `SWAP` in `test_ds_permute.py`. A numeric `offset:N` below 0xC000 is decoded like its symbolic `swizzle(...)` form since #4177; 0xC000–0xFFFF is refused (`Unsupported`), which RDNA2 treats as a separate mode (measured on gfx1036 for all 16,384 offsets). **No game shader is affected either way** (SHADER-811): over the 1.0.2.1 package's 26,503 DXBC listings and the FidelityFX DLL's 29 FSPX programs, llvm-mc prints all 105,529 `ds_swizzle_b32` (in 6,296 DXBC programs; the FSPX programs have none) in a symbolic form, with 17 distinct offsets: 101,913 in 0x8000–0xBFFF (`QUAD_PERM`), 3,616 below 0x8000 (the bitmask mode: `BROADCAST`, `SWAP`, `BITMASK_PERM`) and none at or above 0xC000. Counted from each instruction's printed encoding (offset = bits 15:0 of the first dword) in every listing, the 1,473 with embedded data words included (only decoded instructions count), and matched by a count of the printed offset classes on a second copy (#4566). | 397| `ds_swizzle_b32` | An active destination reads the selected source lane's VGPR. If EXEC disables that source, the read returns zero; a disabled destination keeps its prior value. The [hardware measurements](shader_validation.md#hardware-oracle-for-the-lds-programs---oracle-hw) confirm the disabled-source result on gfx1036 and gfx1150. In the seven-invocation CPU fixture, lane 6 selects lane 7, which is absent. The translator returns zero in that case; the corresponding result on hardware is unverified. The fixture exercises `QUAD_PERM` and `SWAP` in `test_ds_permute.py`. A numeric `offset:N` below 0xC000 is decoded like its symbolic `swizzle(...)` form since #4177; 0xC000–0xFFFF is refused (`Unsupported`), which RDNA2 treats as a separate mode (measured on gfx1036 for all 16,384 offsets). **No game shader is affected either way** (SHADER-811): over the 1.0.2.1 package's 26,503 DXBC listings and the FidelityFX DLL's 29 FSPX programs, llvm-mc prints all 105,529 `ds_swizzle_b32` (in 6,296 DXBC programs; the FSPX programs have none) in a symbolic form, with 17 distinct offsets: 101,913 in 0x8000–0xBFFF (`QUAD_PERM`), 3,616 below 0x8000 (the bitmask mode: `BROADCAST`, `SWAP`, `BITMASK_PERM`) and none at or above 0xC000. Counted from each instruction's printed encoding (offset = bits 15:0 of the first dword) in every listing, the 1,473 with embedded data words included (only decoded instructions count), and matched by a count of the printed offset classes on a second copy (#4566). |
397| Output modifiers on hardware (gfx1150) | Measured on a Radeon 880M (gfx1150, RDNA3.5; **not** RDNA2) with `tools/f32_fuzz.py --oracle hw`, 46,967 programs: `mul:2`/`mul:4`/`div:2` turn a -0 result (a flushed denormal result included) into +0, and are ignored with MODE.IEEE = 1; with f32 denormals kept they are also ignored for the ALU ops (the transcendental and cube ops still apply them). LLVM notes that omod mishandles signed zeros (`SIFoldOperands.cpp`) and D30209 describes -0 being forced to +0 before the modifier. The translator keeps -0 (`OpFMul`), so on that evidence it likely differs from hardware (see #1006). RDNA2 itself is unmeasured (see #1006). Also measured there: with `denorm_mode_32 = 0` f32 denormal operands read as zero and denormal results flush (add/mul/fma/min/max/rounding ops, DX9 mul), exact with 3. `v_fma_mix*` f32 operands read as zero when denormal too (SHADER-298: gfx1036, `0x00000001`, `0x807fffff`, and the integer inline constants 1 and 64; f16 operands widen to normal values); its result is not flushed, since that was not measured. Invalid operations give `0xffc00000`; a signalling NaN passes unchanged with IEEE off and is quieted with IEEE on. RDNA2 does the same: gfx1036 (the integrated GPUs of a Ryzen 9 7950X3D and a Ryzen 7 9800X3D; RDNA2, but not the console's gfx1013), seeds 1 to 6, 38,858 programs, 0 mismatch and 56 omod -0 → +0 deviations, with identical counts through the Linux libdrm launcher and the Windows HIP launcher; `v_rcp_iflag_f32` with `clamp`/`omod` on the same GPU, 6,552 programs, 0 mismatch and 35 such deviations, otherwise behaves like `v_rcp_f32`. Also measured there: with `denorm_mode_32 = 0` f32 denormal operands read as zero and denormal results flush (add/mul/fma/min/max/rounding ops, DX9 mul), exact with 3; invalid operations give `0xffc00000`; a signalling NaN passes unchanged with IEEE off and is quieted with IEEE on. Details in docs/shader_validation.md ("32-bit float VALU on the GPU"). | 398| Output modifiers on hardware (gfx1150) | Measured on a Radeon 880M (gfx1150, RDNA3.5; **not** RDNA2) with `tools/f32_fuzz.py --oracle hw`, 46,967 programs: `mul:2`/`mul:4`/`div:2` turn a -0 result (a flushed denormal result included) into +0, and are ignored with MODE.IEEE = 1; with f32 denormals kept they are also ignored for the ALU ops (the transcendental and cube ops still apply them). LLVM notes that omod mishandles signed zeros (`SIFoldOperands.cpp`) and D30209 describes -0 being forced to +0 before the modifier. The translator keeps -0 (`OpFMul`), so on that evidence it likely differs from hardware (see #1006). RDNA2 itself is unmeasured (see #1006). Also measured there: with `denorm_mode_32 = 0` f32 denormal operands read as zero and denormal results flush (add/mul/fma/min/max/rounding ops, DX9 mul), exact with 3. `v_fma_mix*` f32 operands read as zero when denormal too (SHADER-298: gfx1036, `0x00000001`, `0x807fffff`, and the integer inline constants 1 and 64; f16 operands widen to normal values); its result is not flushed, since that was not measured. Invalid operations give `0xffc00000`; a signalling NaN passes unchanged with IEEE off and is quieted with IEEE on. RDNA2 does the same: gfx1036 (the integrated GPUs of a Ryzen 9 7950X3D and a Ryzen 7 9800X3D; RDNA2, but not the console's gfx1013), seeds 1 to 6, 38,858 programs, 0 mismatch and 56 omod -0 → +0 deviations, with identical counts through the Linux libdrm launcher and the Windows HIP launcher; `v_rcp_iflag_f32` with `clamp`/`omod` on the same GPU, 6,552 programs, 0 mismatch and 35 such deviations, otherwise behaves like `v_rcp_f32`. Also measured there: with `denorm_mode_32 = 0` f32 denormal operands read as zero and denormal results flush (add/mul/fma/min/max/rounding ops, DX9 mul), exact with 3; invalid operations give `0xffc00000`; a signalling NaN passes unchanged with IEEE off and is quieted with IEEE on. Details in docs/shader_validation.md ("32-bit float VALU on the GPU"). |
398| Wave64 handling | Wave size is detected per shader from the code (64-bit EXEC writes, `exec_hi`, `v_mbcnt_hi`, `*_saveexec_b64`/`*_wrexec_b64`, and 64-bit lane-mask SOP ops `s_bcnt[01]_i32_b64` / `s_ff[01]_i32_b64` / `s_wqm_b64` / `s_bfm_b64` even when the mask is an ordinary SGPR pair; mesh shaders are always wave64). In wave32 code (a header or FSPX dispatch state that says so) `s_bfm_b64` is 64-bit data instead: the translator writes `((1 << (S0 & 63)) - 1) << (S1 & 63)` to the pair, `tools/lane_masks.py` leaves it data, and it doesn't count against an FSPX program's wave32 state. The pipeline library's wave32 compute programs build an S# in place with it (`s_bfm_b64 s[88:89], 2, 54`, then `s_mov_b64` of words 2-3; 958 programs, [shader_library.md](shader_library.md)). Only constant operands are translated there; none other is seen. `tests/semantic/test_wave32_bfm64_data.py`. Wave size comes from the sidecar `fssm/<name>.fssm` header flags word `u32[0xD4]` bit 5 (`0x20` = wave32, `0` = wave64; `fssm_header.wave_size()`), cross-checked against wave64/wave32 code markers (`WAVE64_RE` / `WAVE32_RE`: a contradicting header and code listing raises `Unsupported`), and falls back to the code-marker heuristic (64-bit EXEC/VCC writes, `exec_hi`, `v_mbcnt_hi`, `*_saveexec_b64`/`*_wrexec_b64`, and 64-bit lane-mask SOP ops `s_bcnt[01]_i32_b64` / `s_ff[01]_i32_b64` / `s_wqm_b64` / `s_bfm_b64`, plus wave64 for mesh shaders) when no `FSSM`-magic sidecar is present (synthetic listings). **An FSPX program** (the FidelityFX DLL's, no FSSM blob) takes its wave size from its dispatch state instead: kind 0 word 4 bit 20, set = wave32 (`fspx/<name>.json` `wave32`). Only a strict marker (`WAVE64_RE` against wave32, `WAVE32_RE` against wave64) contradicts it and raises `Unsupported`; a `_b64` op on `vcc` or `exec` does not, since these programs move `vcc` as an ordinary SGPR pair. Without that field the heuristic stays. Confirmed on the 29 programs of 1.0.2.1: strict markers never contradict the bit, the `RSRC1` VGPR granule fits it in all 21 programs that decode cleanly, and `PSV0` lane counts agree with it in all 5 that state one ([fspx.md](fspx.md), "Kind 0: dispatch state"). Translated with the bit, the 4 programs the heuristic got wrong change size, and the other 22 translated modules are byte-identical. CPU-checked by `tests/semantic/test_fspx_wave_size.py`, including a `v_readlane_b32` whose result differs between the two sizes; `vk_pipeline_check` builds all 26 modules. Not GPU-checked on these programs' own data. Confirmed across all 26,503 corpus blobs with 0 contradictions against GFX10 SOP1/SOP2/SOPC/VOP3 encodings: 23,841 wave64 (1,154 CS, 195 GS, 9,282 MS, 10,974 PS, 2,236 VS) and 2,662 wave32 (1,535 CS, 1,127 PS); the code-marker heuristic alone misclassified 2,287 markerless wave64 shaders as wave32 (287 CS: 162 straight-line and 125 branchy, including 11 with `v_readlane_b32`, 35 `v_readfirstlane_b32`, 29 `ds_swizzle_b32`, 14 `s_barrier`; 943 PS: 906 straight-line and 37 branchy; 1,057 VS: 1,020 straight-line and 37 branchy); CPU-checked by `tests/test_fssm_header.py` and `tests/test_fssm_wave_size.py`. Until 2026-11-21 a mask-only wave64 program with no EXEC markers was translated as wave32, so `s_bcnt1_i32_b64` counted one half (#210). GPU-checked with `runtime/test/shaders/cs_w64_mask_detect.asm` (48 set bits of `(lane & 5) != 0`) on NVIDIA GeForce RTX 5060 under `LEONIDA_W64_EMULATE=1`. The hardware lane is exact in compute and mesh shaders (LocalInvocationIndex mod 64 or 32) and is used by `v_mbcnt` and EXEC writes. In other stages it's the subgroup lane. Constant EXEC writes (`s_mov_b32 exec_lo/exec_hi, K`) set each lane from its own bit of K, as `(K >> lane) & 1` (shift and mask: Intel's Windows driver evaluated `OpBitFieldUExtract` of a constant that fits in 16 bits with the lane taken mod 16, so `exec_lo = 0xffff` ran all 32 lanes; GPU-checked with `runtime/test/shaders/cs_exec_const.asm` on Intel UHD Graphics 770, driver 32.0.101.6129, and NVIDIA GeForce RTX 4080 SUPER); before, any non-zero constant turned every lane on. A register written to `exec_hi` sets lanes 32–63 only. VCC's halves follow the same rule while VCC holds a lane mask: a 32-bit write to `vcc_lo` sets lanes 0–31 of the mask and one to `vcc_hi` lanes 32–63 (until 2026-11-22 a `vcc_lo` write set all 64 lanes and a `vcc_hi` write never reached the mask that `s_cbranch_vccz`/`v_cndmask` read; CPU-checked by `tests/semantic/test_wave64_vcc_half_write.py`, not GPU-checked). Mask and `0`/`-1` half-writes to `vcc_lo`/`vcc_hi` keep VCC tracked as a lane mask across subsequent ops (`s_bcnt1_i32_b64`, further half-writes), whereas plain-data writes (`s_buffer_load_dword vcc_lo`, `s_load_dword`, scalar ALU, non-mask constants) end VCC's mask state and store the scalar word across all 64 lanes instead of updating only one mask half (confirmed on 1 wave64 PS in the 1.0.2.1 corpus and `tests/semantic/test_wave64_vcc_half_write.py`). GPU-checked with `runtime/test/shaders/cs_exec64.asm`: lanes 16–47 enabled from two constants, exact on a 32-wide-subgroup GPU. Still approximate on 32-wide subgroups: cross-lane ops between the two halves of a wave64 (readlane/permlane/DPP/shuffles across lane 31/32, wave-wide reductions). The metadata index marks every wave64 shader so a runtime can request `requiredSubgroupSize = 64` where supported (AMD), which makes those exact too. | 399| Wave64 handling | Wave size is detected per shader from the code (64-bit EXEC writes, `exec_hi`, `v_mbcnt_hi`, `*_saveexec_b64`/`*_wrexec_b64`, and 64-bit lane-mask SOP ops `s_bcnt[01]_i32_b64` / `s_ff[01]_i32_b64` / `s_wqm_b64` / `s_bfm_b64` even when the mask is an ordinary SGPR pair; mesh shaders are always wave64). In wave32 code (a header or FSPX dispatch state that says so) `s_bfm_b64` is 64-bit data instead: the translator writes `((1 << (S0 & 63)) - 1) << (S1 & 63)` to the pair, `tools/lane_masks.py` leaves it data, and it doesn't count against an FSPX program's wave32 state. The pipeline library's wave32 compute programs build an S# in place with it (`s_bfm_b64 s[88:89], 2, 54`, then `s_mov_b64` of words 2-3; 958 programs, [shader_library.md](shader_library.md)). Only constant operands are translated there; none other is seen. `tests/semantic/test_wave32_bfm64_data.py`. Wave size comes from the sidecar `fssm/<name>.fssm` header flags word `u32[0xD4]` bit 5 (`0x20` = wave32, `0` = wave64; `fssm_header.wave_size()`), cross-checked against wave64/wave32 code markers (`WAVE64_RE` / `WAVE32_RE`: a contradicting header and code listing raises `Unsupported`), and falls back to the code-marker heuristic (64-bit EXEC/VCC writes, `exec_hi`, `v_mbcnt_hi`, `*_saveexec_b64`/`*_wrexec_b64`, and 64-bit lane-mask SOP ops `s_bcnt[01]_i32_b64` / `s_ff[01]_i32_b64` / `s_wqm_b64` / `s_bfm_b64`, plus wave64 for mesh shaders) when no `FSSM`-magic sidecar is present (synthetic listings). **An FSPX program** (the FidelityFX DLL's, no FSSM blob) takes its wave size from its dispatch state instead: kind 0 word 4 bit 20, set = wave32 (`fspx/<name>.json` `wave32`). Only a strict marker (`WAVE64_RE` against wave32, `WAVE32_RE` against wave64) contradicts it and raises `Unsupported`; a `_b64` op on `vcc` or `exec` does not, since these programs move `vcc` as an ordinary SGPR pair. Without that field the heuristic stays. Confirmed on the 29 programs of 1.0.2.1: strict markers never contradict the bit, the `RSRC1` VGPR granule fits it in all 21 programs that decode cleanly, and `PSV0` lane counts agree with it in all 5 that state one ([fspx.md](fspx.md), "Kind 0: dispatch state"). Translated with the bit, the 4 programs the heuristic got wrong change size, and the other 22 translated modules are byte-identical. CPU-checked by `tests/semantic/test_fspx_wave_size.py`, including a `v_readlane_b32` whose result differs between the two sizes; `vk_pipeline_check` builds all 26 modules. Not GPU-checked on these programs' own data. Confirmed across all 26,503 corpus blobs with 0 contradictions against GFX10 SOP1/SOP2/SOPC/VOP3 encodings: 23,841 wave64 (1,154 CS, 195 GS, 9,282 MS, 10,974 PS, 2,236 VS) and 2,662 wave32 (1,535 CS, 1,127 PS); the code-marker heuristic alone misclassified 2,287 markerless wave64 shaders as wave32 (287 CS: 162 straight-line and 125 branchy, including 11 with `v_readlane_b32`, 35 `v_readfirstlane_b32`, 29 `ds_swizzle_b32`, 14 `s_barrier`; 943 PS: 906 straight-line and 37 branchy; 1,057 VS: 1,020 straight-line and 37 branchy); CPU-checked by `tests/test_fssm_header.py` and `tests/test_fssm_wave_size.py`. Until 2026-11-21 a mask-only wave64 program with no EXEC markers was translated as wave32, so `s_bcnt1_i32_b64` counted one half (#210). GPU-checked with `runtime/test/shaders/cs_w64_mask_detect.asm` (48 set bits of `(lane & 5) != 0`) on NVIDIA GeForce RTX 5060 under `LEONIDA_W64_EMULATE=1`. The hardware lane is exact in compute and mesh shaders (LocalInvocationIndex mod 64 or 32) and is used by `v_mbcnt` and EXEC writes. In other stages it's the subgroup lane. Constant EXEC writes (`s_mov_b32 exec_lo/exec_hi, K`) set each lane from its own bit of K, as `(K >> lane) & 1` (shift and mask: Intel's Windows driver evaluated `OpBitFieldUExtract` of a constant that fits in 16 bits with the lane taken mod 16, so `exec_lo = 0xffff` ran all 32 lanes; GPU-checked with `runtime/test/shaders/cs_exec_const.asm` on Intel UHD Graphics 770, driver 32.0.101.6129, and NVIDIA GeForce RTX 4080 SUPER); before, any non-zero constant turned every lane on. A register written to `exec_hi` sets lanes 32–63 only. VCC's halves follow the same rule while VCC holds a lane mask: a 32-bit write to `vcc_lo` sets lanes 0–31 of the mask and one to `vcc_hi` lanes 32–63 (until 2026-11-22 a `vcc_lo` write set all 64 lanes and a `vcc_hi` write never reached the mask that `s_cbranch_vccz`/`v_cndmask` read; CPU-checked by `tests/semantic/test_wave64_vcc_half_write.py`, not GPU-checked). Mask and `0`/`-1` half-writes to `vcc_lo`/`vcc_hi` keep VCC tracked as a lane mask across subsequent ops (`s_bcnt1_i32_b64`, further half-writes), whereas plain-data writes (`s_buffer_load_dword vcc_lo`, `s_load_dword`, scalar ALU, non-mask constants) end VCC's mask state and store the scalar word across all 64 lanes instead of updating only one mask half (confirmed on 1 wave64 PS in the 1.0.2.1 corpus and `tests/semantic/test_wave64_vcc_half_write.py`). GPU-checked with `runtime/test/shaders/cs_exec64.asm`: lanes 16–47 enabled from two constants, exact on a 32-wide-subgroup GPU. Still approximate on 32-wide subgroups: cross-lane ops between the two halves of a wave64 (readlane/permlane/DPP/shuffles across lane 31/32, wave-wide reductions). The metadata index marks every wave64 shader so a runtime can request `requiredSubgroupSize = 64` where supported (AMD), which makes those exact too. |
@@ -425,7 +426,7 @@ How the generated SPIR-V expects the runtime to work:
425| `ds_bpermute_b32` subgroup convergence | Native wave32 and wave64 apply bitwise masks to the shuffle result and the destination write so both the ballot and shuffle execute before lane predication. If the ballot has no source lane, the shuffle reads the calling lane before the result is masked to zero. MoltenVK 1.4.2 lowered the scalar selects to nested Metal ternaries, placing the subgroup operations in divergent control flow. The `cs_bpermute32` inactive-source case returned 64 on an Apple M1 Max, and all eight fixture words match with bitwise masking. | 426| `ds_bpermute_b32` subgroup convergence | Native wave32 and wave64 apply bitwise masks to the shuffle result and the destination write so both the ballot and shuffle execute before lane predication. If the ballot has no source lane, the shuffle reads the calling lane before the result is masked to zero. MoltenVK 1.4.2 lowered the scalar selects to nested Metal ternaries, placing the subgroup operations in divergent control flow. The `cs_bpermute32` inactive-source case returned 64 on an Apple M1 Max, and all eight fixture words match with bitwise masking. |
426| LDS 2-address b64 (`ds_read2_b64`, `ds_write2_b64`, `ds_read2st64_b64`, `ds_write2st64_b64`) | Two elements at vaddr + offset0·unit and vaddr + offset1·unit, unit = 8 bytes (×64 for st64); each element is two consecutive dwords, low first. `read2_b64` fills v[d:d+3] after all four loads (a vdst overlapping vaddr is safe); `write2_b64` takes two VGPR pairs. The b32 forms share the code with unit 4. Source: RDNA2 ISA DS 2-address forms. CPU-checked by `tests/semantic/test_lds_read2_write2_b64.py` (compute listings, LDS as a Workgroup variable); GPU-checked by `runtime/test/shaders/cs_lds_b64_cmpst.asm` (unit 8 and the 512-byte st64 forms, plus vdst/vaddr overlap, on an RTX 3070, driver 621.01, Windows 11; the same eight words also on an AMD RX 7600 (`gfx1102`) and a Ryzen 5 9600X iGPU (`gfx1036`, RDNA2, RADV Mesa 27.0.0-devel)). | 427| LDS 2-address b64 (`ds_read2_b64`, `ds_write2_b64`, `ds_read2st64_b64`, `ds_write2st64_b64`) | Two elements at vaddr + offset0·unit and vaddr + offset1·unit, unit = 8 bytes (×64 for st64); each element is two consecutive dwords, low first. `read2_b64` fills v[d:d+3] after all four loads (a vdst overlapping vaddr is safe); `write2_b64` takes two VGPR pairs. The b32 forms share the code with unit 4. Source: RDNA2 ISA DS 2-address forms. CPU-checked by `tests/semantic/test_lds_read2_write2_b64.py` (compute listings, LDS as a Workgroup variable); GPU-checked by `runtime/test/shaders/cs_lds_b64_cmpst.asm` (unit 8 and the 512-byte st64 forms, plus vdst/vaddr overlap, on an RTX 3070, driver 621.01, Windows 11; the same eight words also on an AMD RX 7600 (`gfx1102`) and a Ryzen 5 9600X iGPU (`gfx1036`, RDNA2, RADV Mesa 27.0.0-devel)). |
427| Compute workgroup IDs Y/Z | With four user SGPRs and only TGID_Y and TGID_Z enabled (RSRC2 `0x308`), s4 receives Y and s5 receives Z. The synthetic `cs_workgroup_yz.asm` fixture checks a 2 × 3 × 4 dispatch and each of its 24 origins against a CPU reference. | 428| Compute workgroup IDs Y/Z | With four user SGPRs and only TGID_Y and TGID_Z enabled (RSRC2 `0x308`), s4 receives Y and s5 receives Z. The synthetic `cs_workgroup_yz.asm` fixture checks a 2 × 3 × 4 dispatch and each of its 24 origins against a CPU reference. |
428| Typed image stores | `image_store` (2D, 2D array, 3D, cube) writes the dmask components (missing ones = 0). The image's numeric type lives in the T# (word 1 FORMAT [28:20], 512 GFX10 formats), so it is decided at run time. A 512-bit table built from `tools/gfx10_formats.json` (30 UINT and 15 SINT formats) picks a **sint**, **uint** or **float** view (bindings 8 + 3·dim + class; dim 0 = 2D, 1 = 2D array, 2 = 3D; class 0 float, 1 uint, 2 sint). Views have Unknown format (`shaderStorageImageWriteWithoutFormat`). **The runtime binds every storage image into all three arrays of its dimension, or at least the one matching its format.** The earlier path wrote only component 0 as `r32ui`, which was wrong for every other format. GPU-checked with `runtime/test/shaders/cs_imgstore.asm` through `runtime/test/vk_store_test.cpp`: rgba8 unorm, r32 uint and r32 sint images, every texel correct. A cube storage image is bound as a six-layer 2D array (bindings 11/12/13 for float/uint/sint, `OpTypeImage ... 2D 0 1 0 2 Unknown`, `%v3int` coordinates (x, y, face)); `tfe` and `lwe` are refused. CPU-checked by `tests/semantic/test_image_cube_store_glc.py`; **not GPU-verified**: no GPU fixture covers a cube store yet. | 429| Typed image stores | `image_store` (2D, 2D array, 3D, cube) writes the dmask components (missing ones = 0). The image's numeric type lives in the T# (word 1 FORMAT [28:20], 512 GFX10 formats), so it is decided at run time. A 512-bit table built from `tools/gfx10_formats.json` (30 UINT and 15 SINT formats) picks a **sint**, **uint** or **float** view (bindings 8 + 3·dim + class; dim 0 = 2D, 1 = 2D array, 2 = 3D; class 0 float, 1 uint, 2 sint). Views have Unknown format (`shaderStorageImageWriteWithoutFormat`). **The runtime binds every storage image into all three arrays of its dimension, or at least the one matching its format.** The earlier path wrote only component 0 as `r32ui`, which was wrong for every other format. GPU-checked with `runtime/test/shaders/cs_imgstore.asm` through `runtime/test/vk_store_test.cpp`: rgba8 unorm, r32 uint and r32 sint images, every texel correct. A cube storage image is bound as a six-layer 2D array (bindings 11/12/13 for float/uint/sint, `OpTypeImage ... 2D 0 1 0 2 Unknown`, `%v3int` coordinates (x, y, face)); `tfe` and `lwe` are refused. CPU-checked by `tests/semantic/test_image_cube_store_glc.py`. GPU-checked with `runtime/test/shaders/cs_imgstore_cube.asm` through `vk_store_test cube` (GPU-CUBE-STORE): rgba8 unorm, r32 uint and r32 sint cube images, each a cube-compatible 8x8 image of six layers bound through a six-layer 2D-array view at index 1-3 of bindings 11/12/13, and every texel of every face exact (the face selects the layer) on an RTX 4070 Ti (NVIDIA 620.70.06, Linux) and a Radeon 610M (`gfx1036`, RDNA2, RADV Mesa 26.2.6), natively and under `LEONIDA_W64_EMULATE=1`; the same fixture with the face held at 0 fails on both. |
429| Typed image loads | A noncoherent cube `image_load` reads the 2D-array sampled binding (3) with integer coordinates and layer. Its T# format selects the float, uint or sint alias, including for D16. The [RDNA2 ISA §8.2.1](https://docs.amd.com/v/u/en-US/rdna2-shader-instruction-set-architecture) assigns D16 conversion to the image format. The synthetic `cube_load_d16.asm` checks the generated views and format choices on the CPU. `image_load` on 1D/2D/2D-array/3D images uses the same T# FORMAT tables as stores, and fetches every format with `OpImageFetch` from the sampled array of its dimension (bindings 0, 3, 6, 5): UINT/SINT formats through **uint/sint aliases of that array** (same set and binding, an `OpTypeImage` of `%uint`/`%int`; Vulkan allows several variables on one binding when the descriptor type fits), everything else through the float array. A lookup miss (index 0) takes the float path, since the fallback there is RGBA8_UNORM. Results are the raw bits of the dmask components. **The runtime binds each image's view in its own format at its index of the sampled array** (what `bind_image` in `runtime/shims/d3d12_vulkan_device.cpp` already does for SRVs and UAVs), so the view's numeric type matches the alias that reads it. No storage image is read, so shaders that only load need neither `shaderStorageImageReadWithoutFormat` (missing on Intel Xe-LP, #619) nor `shaderStorageImageWriteWithoutFormat` (SHADER-151). Until 2026-11-22 integer formats were read with `OpImageRead` from the uint/sint storage arrays (bindings 8–19), which hold only unordered-access views and 256 entries: a read-only integer texture found the fallback there, or an index past the array's end. Like the float path, the fetch goes through the texture path, so it sees writes made before the dispatch, not ones made earlier in the same dispatch. **d16 loads take the same branch** (#1136) and pack the dmask components two per VGPR, low half first: f16 (round to nearest even, integer ops, no `PackHalf2x16`) from the float array, the low 16 bits of each value from the uint/sint aliases (truncated). **d16 loads take the same branch** (#1136) and pack the dmask components two per VGPR, low half first: f16 (round to nearest even, integer ops, no `PackHalf2x16`) from the float array, each value from the uint/sint aliases saturated to the 16-bit range of its signedness (`saturate_int16`). For odd component counts (1 or 3 in `dmask`), the trailing destination VGPR preserves its existing high 16 bits (`write_lo16`), matching native `gfx1036` hardware where a seeded `0x5a5a` high half survived 1-component UINT/SINT `image_load` and `image_load_mip`; until 2026-11-22 the unused high half was zeroed. Before #1136, a d16 load always read the float view, so a `Texture2D<min16uint>` `Load` returned garbage. CPU-checked by `tests/test_image_load_typed.py` (capabilities, bindings and component types for every dimension; the branch for all 512 FORMAT values, found and missed). GPU-checked with `runtime/test/shaders/cs_imgload.asm` through `vk_store_test load`, on a device made without `shaderStorageImageReadWithoutFormat`: r32 uint and r32 sint images filled before the dispatch, both read with `image_load` and their sum stored, every texel exact on an RTX 2080 Ti (NVIDIA 621.14, Windows 11), clean under the validation layer with GPU-assisted validation; the test fails a module that declares `StorageImageReadWithoutFormat`. d16: CPU-checked by `tests/test_image_load_d16_typed.py` (the uint/sint fetches go through the aliases, no storage image is read, the SPIR-V validates); GPU-checked with `runtime/test/shaders/cs_imgload_d16.asm` through `vk_store_test load`: both pre-filled texels read with d16 loads (the sint one sign-extended from bit 15 in the shader) and their sum stored, every texel exact on the RTX 2080 Ti with GPU-assisted validation (#1136 checked its first form, a store and d16 read-back in one dispatch, on an RTX 5070, and `cs_imgload_d16` passes unchanged on an AMD RX 7600 (gfx1102, RADV Mesa 27.0.0-devel) in `run_gpu_tests.py`). GPU-checked with `runtime/test/shaders/cs_imgload_d16.asm` through `vk_store_test load`: both pre-filled texels read with d16 loads (the sint one sign-extended from bit 15 in the shader) and their sum stored, every texel exact on the RTX 2080 Ti with GPU-assisted validation (#1136 checked its first form, a store and d16 read-back in one dispatch, on an RTX 5070). 2D `image_load_mip` uses the same numeric-type selection and passes the address register's mip to each fetch. Its D16 form packs the selected components in ascending order, two per VGPR. An RGBA8 two-level texture was checked on RTX 5080 and Radeon Graphics: all four exported halves matched the CPU reference for UINT, SINT and UNORM, and forcing level 0 changed every pixel. Checked on RTX 5080 and Radeon Graphics with R8G8B8A8 UINT, SINT and UNORM textures: level 1 matched the CPU reference at every pixel with GPU-assisted validation, and forcing level 0 changed all 4096 pixels for each format. Native gfx1036 saturated 32-bit UINT/SINT texels to the unsigned/signed 16-bit range in both D16 load forms; the translated 2D load matched both limits on RTX 5080 and Radeon Graphics. Native gfx1036 does the same on every dimension (SHADER-387, `tools/image_d16_probe.py`): 32_UINT and 32_32_UINT texels saturate to [0, 0xffff] and 32_SINT and 32_32_SINT texels to [-32768, 32767], never truncate, in 1D, 2D, 2D-array and 3D images, through `image_load` and `image_load_mip` alike; two-channel results pack x low and y high, and a one-channel result keeps the seeded high half. The translated d16 loads on 1D, 2D-array and 3D images still lack GPU checks. | 430| Typed image loads | A noncoherent cube `image_load` reads the 2D-array sampled binding (3) with integer coordinates and layer. Its T# format selects the float, uint or sint alias, including for D16. The [RDNA2 ISA §8.2.1](https://docs.amd.com/v/u/en-US/rdna2-shader-instruction-set-architecture) assigns D16 conversion to the image format. The synthetic `cube_load_d16.asm` checks the generated views and format choices on the CPU. `image_load` on 1D/2D/2D-array/3D images uses the same T# FORMAT tables as stores, and fetches every format with `OpImageFetch` from the sampled array of its dimension (bindings 0, 3, 6, 5): UINT/SINT formats through **uint/sint aliases of that array** (same set and binding, an `OpTypeImage` of `%uint`/`%int`; Vulkan allows several variables on one binding when the descriptor type fits), everything else through the float array. A lookup miss (index 0) takes the float path, since the fallback there is RGBA8_UNORM. Results are the raw bits of the dmask components. **The runtime binds each image's view in its own format at its index of the sampled array** (what `bind_image` in `runtime/shims/d3d12_vulkan_device.cpp` already does for SRVs and UAVs), so the view's numeric type matches the alias that reads it. No storage image is read, so shaders that only load need neither `shaderStorageImageReadWithoutFormat` (missing on Intel Xe-LP, #619) nor `shaderStorageImageWriteWithoutFormat` (SHADER-151). Until 2026-11-22 integer formats were read with `OpImageRead` from the uint/sint storage arrays (bindings 8–19), which hold only unordered-access views and 256 entries: a read-only integer texture found the fallback there, or an index past the array's end. Like the float path, the fetch goes through the texture path, so it sees writes made before the dispatch, not ones made earlier in the same dispatch. **d16 loads take the same branch** (#1136) and pack the dmask components two per VGPR, low half first: f16 (round to nearest even, integer ops, no `PackHalf2x16`) from the float array, the low 16 bits of each value from the uint/sint aliases (truncated). **d16 loads take the same branch** (#1136) and pack the dmask components two per VGPR, low half first: f16 (round to nearest even, integer ops, no `PackHalf2x16`) from the float array, each value from the uint/sint aliases saturated to the 16-bit range of its signedness (`saturate_int16`). For odd component counts (1 or 3 in `dmask`), the trailing destination VGPR preserves its existing high 16 bits (`write_lo16`), matching native `gfx1036` hardware where a seeded `0x5a5a` high half survived 1-component UINT/SINT `image_load` and `image_load_mip`; until 2026-11-22 the unused high half was zeroed. Before #1136, a d16 load always read the float view, so a `Texture2D<min16uint>` `Load` returned garbage. CPU-checked by `tests/test_image_load_typed.py` (capabilities, bindings and component types for every dimension; the branch for all 512 FORMAT values, found and missed). GPU-checked with `runtime/test/shaders/cs_imgload.asm` through `vk_store_test load`, on a device made without `shaderStorageImageReadWithoutFormat`: r32 uint and r32 sint images filled before the dispatch, both read with `image_load` and their sum stored, every texel exact on an RTX 2080 Ti (NVIDIA 621.14, Windows 11), clean under the validation layer with GPU-assisted validation; the test fails a module that declares `StorageImageReadWithoutFormat`. d16: CPU-checked by `tests/test_image_load_d16_typed.py` (the uint/sint fetches go through the aliases, no storage image is read, the SPIR-V validates); GPU-checked with `runtime/test/shaders/cs_imgload_d16.asm` through `vk_store_test load`: both pre-filled texels read with d16 loads (the sint one sign-extended from bit 15 in the shader) and their sum stored, every texel exact on the RTX 2080 Ti with GPU-assisted validation (#1136 checked its first form, a store and d16 read-back in one dispatch, on an RTX 5070, and `cs_imgload_d16` passes unchanged on an AMD RX 7600 (gfx1102, RADV Mesa 27.0.0-devel) in `run_gpu_tests.py`). GPU-checked with `runtime/test/shaders/cs_imgload_d16.asm` through `vk_store_test load`: both pre-filled texels read with d16 loads (the sint one sign-extended from bit 15 in the shader) and their sum stored, every texel exact on the RTX 2080 Ti with GPU-assisted validation (#1136 checked its first form, a store and d16 read-back in one dispatch, on an RTX 5070). 2D `image_load_mip` uses the same numeric-type selection and passes the address register's mip to each fetch. Its D16 form packs the selected components in ascending order, two per VGPR. An RGBA8 two-level texture was checked on RTX 5080 and Radeon Graphics: all four exported halves matched the CPU reference for UINT, SINT and UNORM, and forcing level 0 changed every pixel. Checked on RTX 5080 and Radeon Graphics with R8G8B8A8 UINT, SINT and UNORM textures: level 1 matched the CPU reference at every pixel with GPU-assisted validation, and forcing level 0 changed all 4096 pixels for each format. Native gfx1036 saturated 32-bit UINT/SINT texels to the unsigned/signed 16-bit range in both D16 load forms; the translated 2D load matched both limits on RTX 5080 and Radeon Graphics. Native gfx1036 does the same on every dimension (SHADER-387, `tools/image_d16_probe.py`): 32_UINT and 32_32_UINT texels saturate to [0, 0xffff] and 32_SINT and 32_32_SINT texels to [-32768, 32767], never truncate, in 1D, 2D, 2D-array and 3D images, through `image_load` and `image_load_mip` alike; two-channel results pack x low and y high, and a one-channel result keeps the seeded high half. The translated d16 loads on 1D, 2D-array and 3D images still lack GPU checks. |
430| Packed 2D mip-load addresses | For `image_load_mip` with `a16`, the first VGPR holds unsigned X (low half) and Y (high half). The low half of the second VGPR selects the mip and its high half is unused. Both ordinary and D16 results use the same address. LLVM gfx1030 assembles both forms in `tests/semantic/fixtures/packed_mip_load_2d.asm`. `tests/test_image_load_typed.py` checks the texel and mip operands of the float, UINT and SINT fetches, including noncontiguous address registers. [AMD RDNA 2 ISA, MIMG A16 field](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) | 431| Packed 2D mip-load addresses | For `image_load_mip` with `a16`, the first VGPR holds unsigned X (low half) and Y (high half). The low half of the second VGPR selects the mip and its high half is unused. Both ordinary and D16 results use the same address. LLVM gfx1030 assembles both forms in `tests/semantic/fixtures/packed_mip_load_2d.asm`. `tests/test_image_load_typed.py` checks the texel and mip operands of the float, UINT and SINT fetches, including noncontiguous address registers. [AMD RDNA 2 ISA, MIMG A16 field](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) |
431| 3D explicit-mip loads | `image_load_mip` reads x, y, z and mip from four address VGPRs. T# FORMAT selects the float, UINT or SINT 3D sampled view at binding 6. D16 narrows the selected components before packing them low half first. The unit test `test_volume_mip_fetch_uses_xyz_level_and_descriptor_type` in `tests/test_image_load_typed.py` checks the four address registers and the RGBA32 format selection on the translated module. Native gfx1036 measured UINT and SINT saturation for 3D `image_load_mip` at mip zero. [Volume load measurements](https://github.com/ItsNotRexed/Leonida/pull/2217) | 432| 3D explicit-mip loads | `image_load_mip` reads x, y, z and mip from four address VGPRs. T# FORMAT selects the float, UINT or SINT 3D sampled view at binding 6. D16 narrows the selected components before packing them low half first. The unit test `test_volume_mip_fetch_uses_xyz_level_and_descriptor_type` in `tests/test_image_load_typed.py` checks the four address registers and the RGBA32 format selection on the translated module. Native gfx1036 measured UINT and SINT saturation for 3D `image_load_mip` at mip zero. [Volume load measurements](https://github.com/ItsNotRexed/Leonida/pull/2217) |
@@ -435,10 +436,10 @@ How the generated SPIR-V expects the runtime to work:
435| Half-precision coordinates for LOD queries | For `image_get_lod a16` on 2D and 2D-array images, the low and high halves of the first address VGPR supply U and V. The array layer is excluded from `OpImageQueryLod`; the selected clamped and raw LOD outputs are f32. `tests/semantic/fixtures/get_lod_a16.asm` assembles for gfx1030 and checks the query operands and output components through `tests/test_image_load_typed.py`. [AMD RDNA2 ISA, MIMG](https://gpuopen.com/download/rdna2-shader-instruction-set-architecture.pdf) | 436| Half-precision coordinates for LOD queries | For `image_get_lod a16` on 2D and 2D-array images, the low and high halves of the first address VGPR supply U and V. The array layer is excluded from `OpImageQueryLod`; the selected clamped and raw LOD outputs are f32. `tests/semantic/fixtures/get_lod_a16.asm` assembles for gfx1030 and checks the query operands and output components through `tests/test_image_load_typed.py`. [AMD RDNA2 ISA, MIMG](https://gpuopen.com/download/rdna2-shader-instruction-set-architecture.pdf) |
436| Dynamic storage image descriptor indices | The runtime T# hash result indexes the r32ui arrays (bindings 4 and 7) used by `OpImageTexelPointer` for image atomics and the typed storage arrays (bindings 8 through 19) used by `OpImageWrite` for stores and `OpImageRead` for coherent loads. Literal T# words still go through the hash table. Emit `StorageImageArrayDynamicIndexing` and record `shaderStorageImageArrayDynamicIndexing` in the shader index when a storage array is accessed this way. Plain typed loads use sampled aliases and follow the sampled indexing rule. The same Vulkan dynamic-uniformity contract applies to storage indices. Confirmed by [Vulkan VUID 10130](https://docs.vulkan.org/spec/latest/appendices/spirvenv.html#VUID-StandaloneSpirv-StorageImageArrayDynamicIndexing-10130), the synthetic `storage_dynamic_index.asm` regression (`test_literal_storage_descriptor_and_mixed_sampled_load`, `test_storage_aliases_in_every_dimension` and `test_atomic_texel_pointers_use_storage_indices` in `tests/semantic/test_sampled_dynamic_index.py`) and `spirv-val`. | 437| Dynamic storage image descriptor indices | The runtime T# hash result indexes the r32ui arrays (bindings 4 and 7) used by `OpImageTexelPointer` for image atomics and the typed storage arrays (bindings 8 through 19) used by `OpImageWrite` for stores and `OpImageRead` for coherent loads. Literal T# words still go through the hash table. Emit `StorageImageArrayDynamicIndexing` and record `shaderStorageImageArrayDynamicIndexing` in the shader index when a storage array is accessed this way. Plain typed loads use sampled aliases and follow the sampled indexing rule. The same Vulkan dynamic-uniformity contract applies to storage indices. Confirmed by [Vulkan VUID 10130](https://docs.vulkan.org/spec/latest/appendices/spirvenv.html#VUID-StandaloneSpirv-StorageImageArrayDynamicIndexing-10130), the synthetic `storage_dynamic_index.asm` regression (`test_literal_storage_descriptor_and_mixed_sampled_load`, `test_storage_aliases_in_every_dimension` and `test_atomic_texel_pointers_use_storage_indices` in `tests/semantic/test_sampled_dynamic_index.py`) and `spirv-val`. |
437| Image atomics, size and LOD queries | `image_atomic_add/sub/and/or/xor/smin/smax/umin/umax` are `OpAtomicIAdd/ISub/And/Or/Xor/SMin/SMax/UMin/UMax` on the texel (`OpImageTexelPointer`) of an r32ui storage image, binding 4 for 2D and 7 for 3D, at the T#'s index (the view `StorageViews::r32ui` of `runtime/src/vulkan_bindless.h`). The data VGPR is the operand; with `glc` it receives the texel's previous value, without it it is not written (RDNA2 ISA, MIMG: the previous value is returned if glc is 1). `image_atomic_cmpswap` takes two data VGPRs, the new value and then the comparand (`OpAtomicCompareExchange`). A lane that EXEC turns off skips the access entirely (`OpAccessChain`, `OpImageTexelPointer`, `OpAtomic*`, and any `glc` write-back sit inside `if (active)`), leaving memory and `vdata` untouched. Two-VGPR `dmask:0x3` forms of the nine standard ops currently still operate on the low 32-bit dword as before; true 64-bit image atomics remain separate follow-up work. `image_get_resinfo` (2D, no sampler) gives, for the mip level in its address VGPR, width, height, depth (0 for 2D; a 2D array's layers minified from BASE_LEVEL, T# word 3 [15:12]) and the level count in VGPRs 0..3, with width, height and depth 0 past the last level (the size isn't queried there) (ISA: {num_mip_levels, depth, height, width} in VGPRs 3..0; `OpImageQuerySizeLod`, `OpImageQueryLevels`). `image_get_lod` (pixel shaders; 2D and 2D array, the slice ignored) gives the clamped LOD and the calculated LOD in VGPRs 0..1 (ISA: {rawLOD, clampedLOD} in VGPRs 1..0; `OpImageQueryLod`). In both, dmask keeps components and packs them into consecutive VGPRs. GPU-checked (TEST-184) on an RX 7900 XTX and a Ryzen 9 7950X3D integrated GPU (RADV, Mesa 26.3.1) and on Mesa llvmpipe, with the expected words derived by hand in each `.asm` header: `cs_imgatomic.asm` (every op on a 2D image: 0xfffffff0 tells the signed min/max from the unsigned ones, each with a case that goes the other way; cmpswap hit and miss; an op without `glc`; 63 lanes off; 64 threads adding to one texel) and `cs_imgatomic3d.asm` (six cases on a 4x4x4 volume, the three coordinates all different), through `vk_store_test words`; `cs_resinfo.asm` (a 16x4 image with five levels: levels 0, 1 and 3 in full, then dmask 0x3, 0xa and 0x8); `ps_get_lod.asm` and `ps_get_lod_array.asm` through `vk_texture_test` (calculated LOD 1 and 3 on the two-mip texture, the clamped LOD held at the last level, and at 0 by a sampler MAX_LOD of 0.25; 2 and -3 on the one-level array). Measured natively on RDNA2 (gfx1036, SHADER-388: `tools/image_query_probe.py`, 614 results in wave32 and wave64, all as follows). resinfo's depth word is 0 for a 2D image whatever T# WORD4 DEPTH holds; for a 2D array it is the layer count minified like a 3D depth, max(1, layers >> (BASE_LEVEL + level)). Past the last level, width, height and depth are 0. The level count is LAST_LEVEL - BASE_LEVEL + 1 and sizes count from BASE_LEVEL. The translator follows all three (`Gen.resinfo_words`; `cs_resinfo.asm` checks the 2D depth word and level 5 of five on RTX 5080 and Radeon Graphics, `tests/test_translate.py` the array rule). `image_get_lod`'s raw LOD includes the S#'s LOD_BIAS. Its clamped LOD is min(max(min(raw, MAX_LOD), MIN_LOD), levels - 1) under a linear mip filter (MIN_LOD wins when it is above MAX_LOD), that value rounded half up (the level read) under a point mip filter, and 0 with MIP_FILTER none: `OpImageQueryLod`'s definition. u is scaled by the width and v by the height (a 64x4 image). Unverified: the clamped LOD under a linear mip filter (the test's sampler is point-filtered, where 0.25 selects level 0), and the order of u and v in the LOD query (the test textures are square, where it makes no difference). `image_get_resinfo` on other dimensions is `Unsupported`. A host quirk the LOD test steps around: Mesa llvmpipe 26.3.1 does not apply a sampler's LOD range to `OpImageQueryLod` when its minimum and maximum are equal (0..0 gave level 1), so the second draw uses 0..0.25. | 438| Image atomics, size and LOD queries | `image_atomic_add/sub/and/or/xor/smin/smax/umin/umax` are `OpAtomicIAdd/ISub/And/Or/Xor/SMin/SMax/UMin/UMax` on the texel (`OpImageTexelPointer`) of an r32ui storage image, binding 4 for 2D and 7 for 3D, at the T#'s index (the view `StorageViews::r32ui` of `runtime/src/vulkan_bindless.h`). The data VGPR is the operand; with `glc` it receives the texel's previous value, without it it is not written (RDNA2 ISA, MIMG: the previous value is returned if glc is 1). `image_atomic_cmpswap` takes two data VGPRs, the new value and then the comparand (`OpAtomicCompareExchange`). A lane that EXEC turns off skips the access entirely (`OpAccessChain`, `OpImageTexelPointer`, `OpAtomic*`, and any `glc` write-back sit inside `if (active)`), leaving memory and `vdata` untouched. Two-VGPR `dmask:0x3` forms of the nine standard ops currently still operate on the low 32-bit dword as before; true 64-bit image atomics remain separate follow-up work. `image_get_resinfo` (2D, no sampler) gives, for the mip level in its address VGPR, width, height, depth (0 for 2D; a 2D array's layers minified from BASE_LEVEL, T# word 3 [15:12]) and the level count in VGPRs 0..3, with width, height and depth 0 past the last level (the size isn't queried there) (ISA: {num_mip_levels, depth, height, width} in VGPRs 3..0; `OpImageQuerySizeLod`, `OpImageQueryLevels`). `image_get_lod` (pixel shaders; 2D and 2D array, the slice ignored) gives the clamped LOD and the calculated LOD in VGPRs 0..1 (ISA: {rawLOD, clampedLOD} in VGPRs 1..0; `OpImageQueryLod`). In both, dmask keeps components and packs them into consecutive VGPRs. GPU-checked (TEST-184) on an RX 7900 XTX and a Ryzen 9 7950X3D integrated GPU (RADV, Mesa 26.3.1) and on Mesa llvmpipe, with the expected words derived by hand in each `.asm` header: `cs_imgatomic.asm` (every op on a 2D image: 0xfffffff0 tells the signed min/max from the unsigned ones, each with a case that goes the other way; cmpswap hit and miss; an op without `glc`; 63 lanes off; 64 threads adding to one texel) and `cs_imgatomic3d.asm` (six cases on a 4x4x4 volume, the three coordinates all different), through `vk_store_test words`; `cs_resinfo.asm` (a 16x4 image with five levels: levels 0, 1 and 3 in full, then dmask 0x3, 0xa and 0x8); `ps_get_lod.asm` and `ps_get_lod_array.asm` through `vk_texture_test` (calculated LOD 1 and 3 on the two-mip texture, the clamped LOD held at the last level, and at 0 by a sampler MAX_LOD of 0.25; 2 and -3 on the one-level array). Measured natively on RDNA2 (gfx1036, SHADER-388: `tools/image_query_probe.py`, 614 results in wave32 and wave64, all as follows). resinfo's depth word is 0 for a 2D image whatever T# WORD4 DEPTH holds; for a 2D array it is the layer count minified like a 3D depth, max(1, layers >> (BASE_LEVEL + level)). Past the last level, width, height and depth are 0. The level count is LAST_LEVEL - BASE_LEVEL + 1 and sizes count from BASE_LEVEL. The translator follows all three (`Gen.resinfo_words`; `cs_resinfo.asm` checks the 2D depth word and level 5 of five on RTX 5080 and Radeon Graphics, `tests/test_translate.py` the array rule). `image_get_lod`'s raw LOD includes the S#'s LOD_BIAS. Its clamped LOD is min(max(min(raw, MAX_LOD), MIN_LOD), levels - 1) under a linear mip filter (MIN_LOD wins when it is above MAX_LOD), that value rounded half up (the level read) under a point mip filter, and 0 with MIP_FILTER none: `OpImageQueryLod`'s definition. u is scaled by the width and v by the height (a 64x4 image). Unverified: the clamped LOD under a linear mip filter (the test's sampler is point-filtered, where 0.25 selects level 0), and the order of u and v in the LOD query (the test textures are square, where it makes no difference). `image_get_resinfo` on other dimensions is `Unsupported`. A host quirk the LOD test steps around: Mesa llvmpipe 26.3.1 does not apply a sampler's LOD range to `OpImageQueryLod` when its minimum and maximum are equal (0..0 gave level 1), so the second draw uses 0..0.25. |
438| `image_atomic_{swap,inc,dec,fmin,fmax,fcmpswap}` | The six remaining 32-bit MIMG image atomics on 2D (binding 4) and 3D (binding 7) `r32ui` storage images (including `a16` packed coordinates and optional `glc` return), guarded by `active_b` so inactive lanes skip memory access and preserve `vdata`. `image_atomic_swap` emits `OpAtomicExchange`; `inc`/`dec`/`fmin`/`fmax`/`fcmpswap` emit `OpAtomicLoad` (valid on `OpImageTexelPointer` `Image` pointers) followed by a Device-scope `OpAtomicCompareExchange` CAS loop (`inc`: `(M >= D) ? 0 : M + 1`; `dec`: `(M == 0 \|\| M > D) ? D : M - 1`; `fmin`/`fmax`: GLSL.std.450 `NMin`/`NMax`, no float-atomic extension required; `fcmpswap`: integer IEEE-754 binary32 ordered equality on raw 32-bit words — equal iff neither is NaN and `(cur == cmp) \|\| (both ±0.0)`, preserving subnormals even on Vulkan drivers reporting `shaderDenormPreserveFloat32 = false`, exiting without writing on mismatch or NaN; native RDNA2 subnormal behavior under denormal flush is unmeasured). Source: AMD RDNA2 ISA MIMG `IMAGE_ATOMIC_*`. CPU-checked structurally (including `spirv_mini_interp.check_structure` CFG validation) by `tests/semantic/test_image_atomics_32.py` (all 6 ops on 2D and 3D images, `a16`, `glc` and non-`glc`, no `AtomicFloat` capability, rejected widths/coords/dims). **Not GPU-verified on RDNA2.** | 439| `image_atomic_{swap,inc,dec,fmin,fmax,fcmpswap}` | The six remaining 32-bit MIMG image atomics on 2D (binding 4) and 3D (binding 7) `r32ui` storage images (including `a16` packed coordinates and optional `glc` return), guarded by `active_b` so inactive lanes skip memory access and preserve `vdata`. `image_atomic_swap` emits `OpAtomicExchange`; `inc`/`dec`/`fmin`/`fmax`/`fcmpswap` emit `OpAtomicLoad` (valid on `OpImageTexelPointer` `Image` pointers) followed by a Device-scope `OpAtomicCompareExchange` CAS loop (`inc`: `(M >= D) ? 0 : M + 1`; `dec`: `(M == 0 \|\| M > D) ? D : M - 1`; `fmin`/`fmax`: GLSL.std.450 `NMin`/`NMax`, no float-atomic extension required; `fcmpswap`: integer IEEE-754 binary32 ordered equality on raw 32-bit words — equal iff neither is NaN and `(cur == cmp) \|\| (both ±0.0)`, preserving subnormals even on Vulkan drivers reporting `shaderDenormPreserveFloat32 = false`, exiting without writing on mismatch or NaN; native RDNA2 subnormal behavior under denormal flush is unmeasured). Source: AMD RDNA2 ISA MIMG `IMAGE_ATOMIC_*`. CPU-checked structurally (including `spirv_mini_interp.check_structure` CFG validation) by `tests/semantic/test_image_atomics_32.py` (all 6 ops on 2D and 3D images, `a16`, `glc` and non-`glc`, no `AtomicFloat` capability, rejected widths/coords/dims). GPU-checked by `runtime/test/shaders/cs_imgatomic_ext.asm` through `vk_store_test words` (GPU-IMG-ATOMIC-EXT): all six ops on the 2D image and the volume, inc/dec on both sides of their wrap and with a D that is negative as a signed number, fmin/fmax with a NaN in the data register, fcmpswap with an equal and an unequal comparand, +0 against -0 and a NaN, `glc` and non-`glc` returns, inactive lanes held on a trap texel, and inc/dec/fmin/fmax from all 64 threads on one texel (the CAS loops under contention); every word exact on a Radeon 610M (`gfx1036`, RDNA2, RADV Mesa 26.2.6) and an RTX 4070 Ti (NVIDIA 620.70.06), natively and under `LEONIDA_W64_EMULATE=1`. Each of five planted translator faults (a signed inc/dec compare, fmin and fmax exchanged, fcmpswap without the +0/-0 rule, no inactive-lane guard, no `glc` return from swap) fails it on both. Not covered: NaN or denormal texels for fmin/fmax and fcmpswap, and +0 against -0 for fmin/fmax, where `NMin`/`NMax` and native RDNA2 may differ (native behaviour unmeasured). |
439| Hand-written short assembler forms | `llvm-mc` accepts `v_add_co_ci_u32 vD, src0, src1` (also `v_sub_co_ci_u32`, `v_subrev_co_ci_u32`) with the carry out and in left to VCC, and a modifier list shorter than the operands (`op_sel_hi:[0,0]`, `neg_lo:[1,0]` on a three-source op), whose missing entries are 0; it prints them as `v_add_co_ci_u32_e32 vD, vcc_lo, src0, src1, vcc_lo` and `[0,0,0]`. The GPU runner assembles through `llvm-mc -show-encoding`, so it sees the printed form; `tests/semantic/regen_fixtures.py` copies the `.asm` text as written, so the translator takes the source spelling too (it used to raise `IndexError` for these: the carry forms, `v_pk_fma_f16`, `v_fma_mix_*`). A probe of 42,000 operand and modifier variations of 302 ALU mnemonics, in the source spelling and as `llvm-mc` prints them, found no other `IndexError`, `KeyError` or `TypeError`. CPU-checked by `tests/semantic/test_short_asm_forms.py`. | 440| Hand-written short assembler forms | `llvm-mc` accepts `v_add_co_ci_u32 vD, src0, src1` (also `v_sub_co_ci_u32`, `v_subrev_co_ci_u32`) with the carry out and in left to VCC, and a modifier list shorter than the operands (`op_sel_hi:[0,0]`, `neg_lo:[1,0]` on a three-source op), whose missing entries are 0; it prints them as `v_add_co_ci_u32_e32 vD, vcc_lo, src0, src1, vcc_lo` and `[0,0,0]`. The GPU runner assembles through `llvm-mc -show-encoding`, so it sees the printed form; `tests/semantic/regen_fixtures.py` copies the `.asm` text as written, so the translator takes the source spelling too (it used to raise `IndexError` for these: the carry forms, `v_pk_fma_f16`, `v_fma_mix_*`). A probe of 42,000 operand and modifier variations of 302 ALU mnemonics, in the source spelling and as `llvm-mc` prints them, found no other `IndexError`, `KeyError` or `TypeError`. CPU-checked by `tests/semantic/test_short_asm_forms.py`. |
440| SDWA | `_sdwa` forms: each source is narrowed to `src0_sel`/`src1_sel` (BYTE_n/WORD_n, zero-extended, or sign-extended under `sext()`) **before** neg/abs and the op. A VGPR result goes to `dst_sel`, with `dst_unused` setting the other bits: PAD = 0, SEXT = sign copies above the field, PRESERVE = old bits kept. A byte or word destination with PRESERVE reads its incoming VGPR on first use. The synthetic `sdwa_bary_input.asm` checks this with two raw fragment weights, following the [LLVM SDWA destination rules](https://llvm.org/docs/AMDGPUModifierSyntax.html#dst-unused). VOPC has no `dst_sel`, and GFX10 `v_cmpx` has no written destination. **Until 2026-11-20 the selects were silently ignored.** That affected 3,826 of the 13,926 translated shaders: they passed `spirv-val` but computed wrong values. GPU-checked with `runtime/test/shaders/ps_sdwa.asm` and `ps_ops.asm` (also `v_pk_fma_f16`, `v_min3_u32`, `v_max3_i32`, `v_bfe_i32`): byte/word source selects, `sext()`, `UNUSED_PRESERVE` into WORD_1 and `UNUSED_SEXT` at BYTE_2 all match on every pixel. **Measured natively on RDNA2** (gfx1036 iGPU, `tools/hw_oracle`, the game's MODE): all 172 distinct SDWA forms of the 26,503 listings (79,307 instructions: opcode, operand kinds, sels, `sext`, neg/abs, `dst_unused`, omod), 12 operand words per source, 21,204 cases. 18,885 give the translator's word. The rest are: a 16-bit result with `dst_sel:DWORD`, where the hardware zeroes the high half and the translator keeps it (1,888, #2187); a NaN result, where the hardware keeps the input's sign and payload (826, of which 556 also fall in the first group, so the groups add up to 21,204; as in the f16 transcendentals row); `div:2` on -0, which gives +0 (1, as in the output-modifier rows); and 160 cases whose translation is undefined in SPIR-V (`FClamp`/`FDiv`/`Sqrt` on NaN, zero or negative operands). `tests/semantic/test_alu_sdwa_hw.py` replays 624 of the matching words, up to four per form. | 441| SDWA | `_sdwa` forms: each source is narrowed to `src0_sel`/`src1_sel` (BYTE_n/WORD_n, zero-extended, or sign-extended under `sext()`) **before** neg/abs and the op. A VGPR result goes to `dst_sel`, with `dst_unused` setting the other bits: PAD = 0, SEXT = sign copies above the field, PRESERVE = old bits kept. A byte or word destination with PRESERVE reads its incoming VGPR on first use. The synthetic `sdwa_bary_input.asm` checks this with two raw fragment weights, following the [LLVM SDWA destination rules](https://llvm.org/docs/AMDGPUModifierSyntax.html#dst-unused). VOPC has no `dst_sel`, and GFX10 `v_cmpx` has no written destination. **Until 2026-11-20 the selects were silently ignored.** That affected 3,826 of the 13,926 translated shaders: they passed `spirv-val` but computed wrong values. GPU-checked with `runtime/test/shaders/ps_sdwa.asm` and `ps_ops.asm` (also `v_pk_fma_f16`, `v_min3_u32`, `v_max3_i32`, `v_bfe_i32`): byte/word source selects, `sext()`, `UNUSED_PRESERVE` into WORD_1 and `UNUSED_SEXT` at BYTE_2 all match on every pixel. **Measured natively on RDNA2** (gfx1036 iGPU, `tools/hw_oracle`, the game's MODE): all 172 distinct SDWA forms of the 26,503 listings (79,307 instructions: opcode, operand kinds, sels, `sext`, neg/abs, `dst_unused`, omod), 12 operand words per source, 21,204 cases. 18,885 give the translator's word. The rest are: a 16-bit result with `dst_sel:DWORD`, where the hardware zeroes the high half and the translator keeps it (1,888, #2187); a NaN result, where the hardware keeps the input's sign and payload (826, of which 556 also fall in the first group, so the groups add up to 21,204; as in the f16 transcendentals row); `div:2` on -0, which gives +0 (1, as in the output-modifier rows); and 160 cases whose translation is undefined in SPIR-V (`FClamp`/`FDiv`/`Sqrt` on NaN, zero or negative operands). `tests/semantic/test_alu_sdwa_hw.py` replays 624 of the matching words, up to four per form. |
441| VOP3 output and source modifiers in the game's forms, on RDNA2 | Every distinct float VALU form in the 26,503 listings that carries `clamp`, an omod (`mul:2`/`mul:4`/`div:2`), `op_sel`/`op_sel_hi` or neg/abs: 572 forms, 1,270,932 instructions (`v_mul_legacy_f32 … clamp` alone is 147,499; `v_fma_mix_f32` has 222 forms), up to 120 random operand triples each, run natively on gfx1036 (`tools/hw_oracle`, the game's MODE) and through the translator: 542 forms, 64,802 cases (the GFX10.1-only `v_mad_f32`/`v_mad_legacy_f32`/`v_mac_f32` and `v_permlanex16` are left out). 51,761 give the translator's word. The rest are differences already on record: NaN sign and payload (5,074); f32 denormal operands or results, and a denormal intermediate that the hardware flushes before the omod or clamp (1,178; SHADER-377); an omod turning a -0 result into +0 (121; the Output modifiers rows, #1281); 1 ulp or the known sin/cos precision in `v_rcp/v_rcp_iflag/v_log/v_sin/v_cos` with an omod (56); and 6,430 whose translation is undefined in SPIR-V, mostly `FClamp` of a NaN, where the hardware gives +0 under DX10_CLAMP (#2437). 182 cases were my harness's (three distinct SGPRs, over GFX10's two-read limit). No other modifier difference. `tests/semantic/test_alu_vop3_mods_hw.py` replays 1,616 matching words, up to three per form; it fails without `clamp` (326 rows) or without the omod (237). | 442| VOP3 output and source modifiers in the game's forms, on RDNA2 | Every distinct float VALU form in the 26,503 listings that carries `clamp`, an omod (`mul:2`/`mul:4`/`div:2`), `op_sel`/`op_sel_hi` or neg/abs: 572 forms, 1,270,932 instructions (`v_mul_legacy_f32 … clamp` alone is 147,499; `v_fma_mix_f32` has 222 forms), up to 120 random operand triples each, run natively on gfx1036 (`tools/hw_oracle`, the game's MODE) and through the translator: 542 forms, 64,802 cases (the GFX10.1-only `v_mad_f32`/`v_mad_legacy_f32`/`v_mac_f32` and `v_permlanex16` are left out). 51,761 give the translator's word. The rest are differences already on record: NaN sign and payload (5,074); f32 denormal operands or results, and a denormal intermediate that the hardware flushes before the omod or clamp (1,178; SHADER-377); an omod turning a -0 result into +0 (121; the Output modifiers rows, #1281); 1 ulp or the known sin/cos precision in `v_rcp/v_rcp_iflag/v_log/v_sin/v_cos` with an omod (56); and 6,430 whose translation is undefined in SPIR-V, mostly `FClamp` of a NaN, where the hardware gives +0 under DX10_CLAMP (#2437; the f32/f16 clamp of a NaN gives +0 since 2026-11-24, see "Float min/max/med3 with NaN"). 182 cases were my harness's (three distinct SGPRs, over GFX10's two-read limit). No other modifier difference. `tests/semantic/test_alu_vop3_mods_hw.py` replays 1,616 matching words, up to three per form; it fails without `clamp` (326 rows) or without the omod (237). |
442| Byte permute | `v_perm_b32`: result byte i = BYTE_PERMUTE({src0, src1}, selector byte i), src1 = bytes 0–3 (AMD "RDNA 2" ISA reference, VOP3 opcode 836 V_PERM_B32, `byte_permute` pseudocode, page 189 of the PDF). Selector 0–7 picks that byte; **8, 9, 10, 11 give 0xff if bit 7 of byte 1, 3, 5, 7 is set, else 0x00**; 12 gives 0x00; 13 and above give 0xff. **Until 2026-11-21 selectors 8–11 gave 0x00 regardless of the sign bit**. In the 26,503-shader disassembled corpus (measured via `tools/feature_scan.py`), 0 of 10,500 shaders (11,930 `v_perm_b32` instructions) use selectors 8–11 or >= 13: all 11,258 immediate and 672 constant-register selectors (0 unresolved) use only bytes 0–7 (36,234) and 12 (11,486). GPU-checked with `runtime/test/shaders/ps_ops7.asm` (also `v_alignbit_b32` with a shift of 36, `v_med3_i32` vs `v_med3_u32`) and `ps_ops8.asm` (`v_mul_hi_u32/i32`, `v_bcnt_u32_b32`, `v_ffbl_b32`, `v_ffbh_u32` of 0, `v_xad_u32`, `v_add3_u32`), 4096/4096 pixels on an AMD Radeon iGPU (Ryzen 7 9800X3D, RDNA2, AMD driver 25.10.36) and an NVIDIA GeForce RTX 5070 (driver 621.24); before the fix `ps_ops7` gave 0x00000000 for the sign-selector word on both. Also executed by `tests/semantic/test_value_semantics.py`. When S2 is a literal or a currently known SGPR constant, the translator emits fixed byte extracts/inserts (including sign replication), folds the zero and 0xff bytes, and uses the selected source directly for a whole-word identity. `tests/semantic/test_perm_known_selector.py` checks the resulting words and that selector dispatch only remains for a clobbered SGPR. | 443| Byte permute | `v_perm_b32`: result byte i = BYTE_PERMUTE({src0, src1}, selector byte i), src1 = bytes 0–3 (AMD "RDNA 2" ISA reference, VOP3 opcode 836 V_PERM_B32, `byte_permute` pseudocode, page 189 of the PDF). Selector 0–7 picks that byte; **8, 9, 10, 11 give 0xff if bit 7 of byte 1, 3, 5, 7 is set, else 0x00**; 12 gives 0x00; 13 and above give 0xff. **Until 2026-11-21 selectors 8–11 gave 0x00 regardless of the sign bit**. In the 26,503-shader disassembled corpus (measured via `tools/feature_scan.py`), 0 of 10,500 shaders (11,930 `v_perm_b32` instructions) use selectors 8–11 or >= 13: all 11,258 immediate and 672 constant-register selectors (0 unresolved) use only bytes 0–7 (36,234) and 12 (11,486). GPU-checked with `runtime/test/shaders/ps_ops7.asm` (also `v_alignbit_b32` with a shift of 36, `v_med3_i32` vs `v_med3_u32`) and `ps_ops8.asm` (`v_mul_hi_u32/i32`, `v_bcnt_u32_b32`, `v_ffbl_b32`, `v_ffbh_u32` of 0, `v_xad_u32`, `v_add3_u32`), 4096/4096 pixels on an AMD Radeon iGPU (Ryzen 7 9800X3D, RDNA2, AMD driver 25.10.36) and an NVIDIA GeForce RTX 5070 (driver 621.24); before the fix `ps_ops7` gave 0x00000000 for the sign-selector word on both. Also executed by `tests/semantic/test_value_semantics.py`. When S2 is a literal or a currently known SGPR constant, the translator emits fixed byte extracts/inserts (including sign replication), folds the zero and 0xff bytes, and uses the selected source directly for a whole-word identity. `tests/semantic/test_perm_known_selector.py` checks the resulting words and that selector dispatch only remains for a clobbered SGPR. |
443| Sum of absolute differences (`v_sad_u8`, `v_sad_hi_u8`, `v_sad_u16`, `v_sad_u32`, `v_msad_u8`) | Unsigned, wrapping at 32 bits, with ABSDIFF(x, y) = `UMax − UMin`: `v_sad_u8` = S2 + the sum over the four bytes; `v_sad_hi_u8` = (that byte sum << 16) + S2; `v_sad_u16` = S2 + the sum over the two halves; `v_sad_u32` = \ \| S0 − S1\ \| + S2; `v_msad_u8` skips a byte where S1's byte is 0. `clamp` raises `Unsupported`: the ISA pseudocode doesn't say what it does to these ops. Source: RDNA2 ISA VOP3 opcodes 346–349 and 369 (pseudocode re-read for this row). CPU-checked by `tests/semantic/test_alu_sad.py` (#544): a 9×9 grid of edge words per op, 40 seeded cases, masked bytes, an SGPR source, `clamp` rejected; the PR also reports a 300-case differential run per op with 0 mismatches. None of them is in the translated corpus, and none is GPU-checked. **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137). Measured on native gfx1036 (AMD Radeon Graphics, RDNA2) through tools/hw_oracle across edge byte/half patterns, zero masks, and wrap cases: all match the ISA reference with 0 mismatches. | 444| Sum of absolute differences (`v_sad_u8`, `v_sad_hi_u8`, `v_sad_u16`, `v_sad_u32`, `v_msad_u8`) | Unsigned, wrapping at 32 bits, with ABSDIFF(x, y) = `UMax − UMin`: `v_sad_u8` = S2 + the sum over the four bytes; `v_sad_hi_u8` = (that byte sum << 16) + S2; `v_sad_u16` = S2 + the sum over the two halves; `v_sad_u32` = \ \| S0 − S1\ \| + S2; `v_msad_u8` skips a byte where S1's byte is 0. `clamp` raises `Unsupported`: the ISA pseudocode doesn't say what it does to these ops. Source: RDNA2 ISA VOP3 opcodes 346–349 and 369 (pseudocode re-read for this row). CPU-checked by `tests/semantic/test_alu_sad.py` (#544): a 9×9 grid of edge words per op, 40 seeded cases, masked bytes, an SGPR source, `clamp` rejected; the PR also reports a 300-case differential run per op with 0 mismatches. None of them is in the translated corpus, and none is GPU-checked. **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137). Measured on native gfx1036 (AMD Radeon Graphics, RDNA2) through tools/hw_oracle across edge byte/half patterns, zero masks, and wrap cases: all match the ISA reference with 0 mismatches. |
444| Quad-byte SAD 64-bit source operands | The GFX10.3 `null` operand supplies zero for the 64-bit input window in all three quad-byte SAD operations and for the 64-bit addend of the two packed forms. Confirmed with LLVM gfx1030 assembly and scalar byte-difference references in `tests/semantic/test_alu_qsad.py` (`test_null_pixel_source_and_null_accumulator`) and `tests/semantic/test_alu_mqsad_u32.py` (`test_null_pixel_source`). | 445| Quad-byte SAD 64-bit source operands | The GFX10.3 `null` operand supplies zero for the 64-bit input window in all three quad-byte SAD operations and for the 64-bit addend of the two packed forms. Confirmed with LLVM gfx1030 assembly and scalar byte-difference references in `tests/semantic/test_alu_qsad.py` (`test_null_pixel_source_and_null_accumulator`) and `tests/semantic/test_alu_mqsad_u32.py` (`test_null_pixel_source`). |
@@ -474,14 +475,14 @@ How the generated SPIR-V expects the runtime to work:
474| `v_ldexp_f64` | Binary64 load-exponent (`D.f64 = S0.f64 × 2^(S1.i32)`), lowered bit-exactly on the `(lo, hi)` dword pair using only 32-bit integer ops (no `OpCapability Float64` or `OpCapability Int64`, even with `clamp`). `±0`, `±inf`, and both quiet and signalling NaNs (under `IEEE = 0`) pass through bit-for-bit unchanged after `S0` `abs`/`neg`. Subnormal inputs (`denorm_mode_16_64 = 3`) are normalized via `FindUMsb` before adding `clamp(S1, -4096, 4096)` to the exponent field; overflow (`e2 >= 2047`) gives `±inf`, and subnormal outputs (`e2 <= 0`) shift the 53-bit significand right by `sh = 1 - e2` (`1..53`) and round to nearest even (carry into bit 52 yields `±min_norm`; `sh >= 54` flushes to `±0`). VOP3 `clamp` applies bit-exactly in integer ops (`DX10_CLAMP = 1`: `NaN`, `-0.0`, `<0` → `+0.0`; `>1.0` including `+inf` → `1.0`). VOP3 `omod` (`mul:2`/`mul:4`/`div:2`) is rejected as `Unsupported` because hardware ignores it under `denorm_mode_16_64 = 3` and applies it under `denorm_mode_16_64 = 0`. For immediate `S0` operands, inline integers `-16..64` sign-extend across 64 bits while 32-bit literals occupy `[63:32]` with `[31:0] = 0`. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) (`V_LDEXP_F64`). **Measured natively** on an RDNA2 iGPU (`gfx1036`, Windows driver `32.0.21042.62`, wave32 and wave64 via `tools/hw_oracle` under game MODE `IEEE=0`, `DX10_CLAMP=1`, `denorm32=0`, `denorm16_64=3`): 870 / 870 cases bit-exact across all 52 subnormal input bit positions, all 54 subnormal right-shift boundaries and exact half-ULP ties, carry into `min_norm`, `±0`/`±inf`/qNaN/sNaN, `abs`/`neg`/`clamp`, immediate/literal `S0`, and seeded random inputs (not modelled: `IEEE=1` quiets signalling NaNs). Checked on the CPU and assembled by `tests/semantic/test_alu_ldexp_f64.py`; not run on the shader corpus. | 475| `v_ldexp_f64` | Binary64 load-exponent (`D.f64 = S0.f64 × 2^(S1.i32)`), lowered bit-exactly on the `(lo, hi)` dword pair using only 32-bit integer ops (no `OpCapability Float64` or `OpCapability Int64`, even with `clamp`). `±0`, `±inf`, and both quiet and signalling NaNs (under `IEEE = 0`) pass through bit-for-bit unchanged after `S0` `abs`/`neg`. Subnormal inputs (`denorm_mode_16_64 = 3`) are normalized via `FindUMsb` before adding `clamp(S1, -4096, 4096)` to the exponent field; overflow (`e2 >= 2047`) gives `±inf`, and subnormal outputs (`e2 <= 0`) shift the 53-bit significand right by `sh = 1 - e2` (`1..53`) and round to nearest even (carry into bit 52 yields `±min_norm`; `sh >= 54` flushes to `±0`). VOP3 `clamp` applies bit-exactly in integer ops (`DX10_CLAMP = 1`: `NaN`, `-0.0`, `<0` → `+0.0`; `>1.0` including `+inf` → `1.0`). VOP3 `omod` (`mul:2`/`mul:4`/`div:2`) is rejected as `Unsupported` because hardware ignores it under `denorm_mode_16_64 = 3` and applies it under `denorm_mode_16_64 = 0`. For immediate `S0` operands, inline integers `-16..64` sign-extend across 64 bits while 32-bit literals occupy `[63:32]` with `[31:0] = 0`. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) (`V_LDEXP_F64`). **Measured natively** on an RDNA2 iGPU (`gfx1036`, Windows driver `32.0.21042.62`, wave32 and wave64 via `tools/hw_oracle` under game MODE `IEEE=0`, `DX10_CLAMP=1`, `denorm32=0`, `denorm16_64=3`): 870 / 870 cases bit-exact across all 52 subnormal input bit positions, all 54 subnormal right-shift boundaries and exact half-ULP ties, carry into `min_norm`, `±0`/`±inf`/qNaN/sNaN, `abs`/`neg`/`clamp`, immediate/literal `S0`, and seeded random inputs (not modelled: `IEEE=1` quiets signalling NaNs). Checked on the CPU and assembled by `tests/semantic/test_alu_ldexp_f64.py`; not run on the shader corpus. |
475| `v_min3_f16`, `v_max3_f16`, `v_min3_i16`, `v_min3_u16`, `v_max3_i16`, `v_max3_u16`, `v_med3_i16`, `v_med3_u16` | Three-operand 16-bit min/max/median (VOP3 only). `op_sel` bits 0..2 read the high half of S0..S2, bit 3 writes the high half of D, and the unwritten half of D is kept (see *16-bit results*). `v_min3_f16` and `v_max3_f16` read each selected f16 half through `Gen.f16_in` (`neg`/`abs` apply to the selected half), fold with `NMin`/`NMax` (so a NaN operand yields the other operand and −0 orders below +0, matching `v_min3_f32`/`v_max3_f32` and `v_med3_f16`), then apply VOP3 `omod`/`clamp` and `Gen.f16_out`. The 16-bit integer ops zero-extend (`u16`) or sign-extend (`i16`) the selected 16-bit halves, evaluate `UMin`/`UMax`/`UClamp` or `SMin`/`SMax`/`SClamp`, and write the low 16 bits into the selected half of D; `clamp` is supported on integer min3/max3/med3 as an identity no-op on the 16-bit container (hardware-verified on gfx1036 across wave32 and wave64); non-VGPR `op_sel` destinations raise `Unsupported`. `clamp` and non-VGPR `op_sel` destinations raise `Unsupported`. Until 2026-11-22 all eight raised `Unsupported`. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) VOP3 opcodes `0x351`–`0x356`, `0x359`–`0x35A`, and Mesa ACO's `can_use_opsel`. **Hardware-verified on RDNA2** (gfx1036 iGPU, AMD Windows driver 32.0.21045.16010, `tools/hw_oracle`, IEEE 0 with f16 denormals kept): 6,092 cases (every triple of ±0, a denormal, 1.0, -1.0, 2.0, ±inf, a quiet and a signalling NaN for each f16 op; every triple of 8 edge values for the i16/u16 ops; `op_sel` on each source and the destination; a 0xabcd high half on every source) match the translator's word, including keeping the destination half and returning `src0`'s NaN bits unchanged (`0x7c01` stays signalling under IEEE 0) when all three operands are NaN (`ALL_NAN_SRC0_SIGNALLING` in `tests/semantic/test_alu_min3_max3_med3_16_hw.py`, alongside 540 sampled measured words). `tests/semantic/test_alu_min3_max3_med3_16_hw.py` holds 540 of the measured words. **Not GPU-verified.** CPU-checked by `tests/semantic/test_alu_min3_max3_med3_16.py`, `tests/test_f16_op_sel.py`, and `tests/test_f16_op_sel_values.py`. CPU-checked by `tests/semantic/test_alu_min3_max3_med3_16.py`, `tests/test_f16_op_sel.py`, and `tests/test_f16_op_sel_values.py`; also **hardware-verified on RDNA2** (`gfx1035`, Windows 11, driver `26.5.1`, wave32 & wave64 via `tools/int_hw_probe.py --oracle both --group valu_min3_max3_med3_16`): all eight ops (`op_sel`, untouched destination half, NaN, −0/+0 ordering, and `v_max3_f16` `clamp`) match bit-for-bit. | 476| `v_min3_f16`, `v_max3_f16`, `v_min3_i16`, `v_min3_u16`, `v_max3_i16`, `v_max3_u16`, `v_med3_i16`, `v_med3_u16` | Three-operand 16-bit min/max/median (VOP3 only). `op_sel` bits 0..2 read the high half of S0..S2, bit 3 writes the high half of D, and the unwritten half of D is kept (see *16-bit results*). `v_min3_f16` and `v_max3_f16` read each selected f16 half through `Gen.f16_in` (`neg`/`abs` apply to the selected half), fold with `NMin`/`NMax` (so a NaN operand yields the other operand and −0 orders below +0, matching `v_min3_f32`/`v_max3_f32` and `v_med3_f16`), then apply VOP3 `omod`/`clamp` and `Gen.f16_out`. The 16-bit integer ops zero-extend (`u16`) or sign-extend (`i16`) the selected 16-bit halves, evaluate `UMin`/`UMax`/`UClamp` or `SMin`/`SMax`/`SClamp`, and write the low 16 bits into the selected half of D; `clamp` is supported on integer min3/max3/med3 as an identity no-op on the 16-bit container (hardware-verified on gfx1036 across wave32 and wave64); non-VGPR `op_sel` destinations raise `Unsupported`. `clamp` and non-VGPR `op_sel` destinations raise `Unsupported`. Until 2026-11-22 all eight raised `Unsupported`. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) VOP3 opcodes `0x351`–`0x356`, `0x359`–`0x35A`, and Mesa ACO's `can_use_opsel`. **Hardware-verified on RDNA2** (gfx1036 iGPU, AMD Windows driver 32.0.21045.16010, `tools/hw_oracle`, IEEE 0 with f16 denormals kept): 6,092 cases (every triple of ±0, a denormal, 1.0, -1.0, 2.0, ±inf, a quiet and a signalling NaN for each f16 op; every triple of 8 edge values for the i16/u16 ops; `op_sel` on each source and the destination; a 0xabcd high half on every source) match the translator's word, including keeping the destination half and returning `src0`'s NaN bits unchanged (`0x7c01` stays signalling under IEEE 0) when all three operands are NaN (`ALL_NAN_SRC0_SIGNALLING` in `tests/semantic/test_alu_min3_max3_med3_16_hw.py`, alongside 540 sampled measured words). `tests/semantic/test_alu_min3_max3_med3_16_hw.py` holds 540 of the measured words. **Not GPU-verified.** CPU-checked by `tests/semantic/test_alu_min3_max3_med3_16.py`, `tests/test_f16_op_sel.py`, and `tests/test_f16_op_sel_values.py`. CPU-checked by `tests/semantic/test_alu_min3_max3_med3_16.py`, `tests/test_f16_op_sel.py`, and `tests/test_f16_op_sel_values.py`; also **hardware-verified on RDNA2** (`gfx1035`, Windows 11, driver `26.5.1`, wave32 & wave64 via `tools/int_hw_probe.py --oracle both --group valu_min3_max3_med3_16`): all eight ops (`op_sel`, untouched destination half, NaN, −0/+0 ordering, and `v_max3_f16` `clamp`) match bit-for-bit. |
476| `v_cvt_flr_i32_f32`, `v_cvt_rpi_i32_f32` | RDNA ISA pseudocode: `f32_to_i32(floor(S0))` and `f32_to_i32(floor(S0 + 0.5))`, the `+ 0.5` rounded in binary32 like any f32 add (so 0.49999997 gives 1, where an exact round-half-up would give 0). `f32_to_i32` saturates as in the row above: INT_MAX / INT_MIN at or past ±2³¹ and for ±inf, 0 for NaN. `sat_i32(floor(S0))` and exact `sat_i32(floor(S0 + 0.5))` (computed via `f = Floor(x); (x - f >= 0.5) ? f + 1 : f`, with no binary32 rounding of `S0 + 0.5`: `0x3effffff` → `0`, `0x4b000001` → `0x00800001`, `0x4b7fffff` → `0x00ffffff`). Out-of-range values (±2³¹ and beyond, ±inf) and NaNs all saturate by the sign bit of the operand (`+NaN` → `0x7FFFFFFF`, `-NaN` → `0x80000000`, unlike `v_cvt_i32_f32` which returns `0` for NaN); the sign is read from `x` before `Floor` so driver NaN canonicalization cannot flip it. Source neg/abs apply first. Checked on the CPU by `tests/semantic/test_alu_cvt_flr_rpi.py`, **not yet GPU-verified**. **Until 2026-11-22 the translator rounded `S0 + 0.5` in binary32 and returned `0` for NaN.** Hardware-verified natively on RDNA2 (AMD Radeon 680M `gfx1035`: 82/82 wave32 and 82/82 wave64 via `tools/hw_oracle`, plus `gfx1036` confirmation in #1746) and CPU-checked by `tests/semantic/test_alu_cvt_flr_rpi.py`. | 477| `v_cvt_flr_i32_f32`, `v_cvt_rpi_i32_f32` | RDNA ISA pseudocode: `f32_to_i32(floor(S0))` and `f32_to_i32(floor(S0 + 0.5))`, the `+ 0.5` rounded in binary32 like any f32 add (so 0.49999997 gives 1, where an exact round-half-up would give 0). `f32_to_i32` saturates as in the row above: INT_MAX / INT_MIN at or past ±2³¹ and for ±inf, 0 for NaN. `sat_i32(floor(S0))` and exact `sat_i32(floor(S0 + 0.5))` (computed via `f = Floor(x); (x - f >= 0.5) ? f + 1 : f`, with no binary32 rounding of `S0 + 0.5`: `0x3effffff` → `0`, `0x4b000001` → `0x00800001`, `0x4b7fffff` → `0x00ffffff`). Out-of-range values (±2³¹ and beyond, ±inf) and NaNs all saturate by the sign bit of the operand (`+NaN` → `0x7FFFFFFF`, `-NaN` → `0x80000000`, unlike `v_cvt_i32_f32` which returns `0` for NaN); the sign is read from `x` before `Floor` so driver NaN canonicalization cannot flip it. Source neg/abs apply first. Checked on the CPU by `tests/semantic/test_alu_cvt_flr_rpi.py`, **not yet GPU-verified**. **Until 2026-11-22 the translator rounded `S0 + 0.5` in binary32 and returned `0` for NaN.** Hardware-verified natively on RDNA2 (AMD Radeon 680M `gfx1035`: 82/82 wave32 and 82/82 wave64 via `tools/hw_oracle`, plus `gfx1036` confirmation in #1746) and CPU-checked by `tests/semantic/test_alu_cvt_flr_rpi.py`. |
477| `v_cvt_pknorm_i16_f32`, `v_cvt_pknorm_u16_f32` | D[15:0] from S0 and D[31:16] from S1: the f32 is clamped to [-1, 1] (i16) or [0, 1] (u16), multiplied by 32767 or 65535 and rounded to nearest even **once, from the exact product** (SHADER-363). Mesa ACO emits these opcodes for NIR `pack_snorm_2x16`/`pack_unorm_2x16`, which `nir_opcodes.py` defines as `fround_even(fclamp(x) * 32767.0 / 65535.0)`. Emitted as `FClamp`, `OpFMul`, `RoundEven` and a convert, not `PackSnorm2x16`, whose rounding GLSL leaves to the driver. The f32 `OpFMul` can land exactly on k + 0.5 when the exact product is just below or above it, and `RoundEven` would then pick the even neighbour; the product's error `Fma(c, s, -p)` is exact, so on such a tie the translator takes floor(p) + 1 when it is positive, floor(p) when negative, and `RoundEven` when it is 0 (an exact tie). Away from a tie the two roundings agree, since k + 0.5 is an f32 there. NaN gives 0, as `v_cvt_i32_f32` does: **measured** on an RDNA2 iGPU (gfx1036, SHADER-339), 74 of 74 NaN halves (quiet and signalling, both signs, payloads, in S0 and S1) gave 0 in wave32 and wave64 under the game's MODE and with IEEE 1, DX10_CLAMP 0 or f32 denormals kept (`tools/pknorm_probe.py --oracle hw`). **The rounding differs:** the hardware rounds the exact product x · 32767 (or 65535) once, while the translator rounds the f32 `OpFMul` product and then `RoundEven`, so it is one off where the f32 product lands exactly on k + 0.5 (28 of 28 such near-tie inputs, both directions; `docs/shader_validation.md`, "`v_cvt_pknorm_*` NaN and rounding on RDNA2"). On gfx1035 (SHADER-137, `tools/int_hw_probe.py --oracle both`, wave32 and wave64) ±qNaN → 0, ±inf saturation and the round-to-nearest-even ties at ±0.5 match bit for bit. Not fixed here. NaN gives 0, as `v_cvt_i32_f32` does; that is **not measured on hardware**. Source modifiers apply. VOP3 `clamp` is a hardware no-op on RDNA2 and is accepted without changing the result; other modifiers (`mul:*`/`div:*`, `op_sel:*`) raise `Unsupported`. `clamp` raises `Unsupported`. Until 2026-11-22 both ops were rejected. CPU-checked by `tests/semantic/test_alu_cvt_pknorm_f32.py` (ties at the scale steps, ±inf, ±NaN, subnormals, out-of-range values, 40 seeded pairs, abs/neg). **Measured on RDNA2:** on an iGPU (gfx1036, SHADER-339/363, `tools/pknorm_probe.py --oracle hw`) 74 of 74 NaN halves (quiet and signalling, both signs, payloads, in S0 and S1) gave 0 and 28 of 28 near-tie inputs (both directions) gave the single-rounded word, in wave32 and wave64 under the game's MODE and with IEEE 1, DX10_CLAMP 0 or f32 denormals kept; the translator matches all 134 probe words in all ten runs (it was one off on the 28 near ties before SHADER-363; additionally, `tools/cvt_norm_mods_probe.py --hw-arch gfx1036` verified `plain` vs VOP3 `clamp` across 40 edge/near-tie/NaN/±inf/subnormal pairs + 3 source-modifier cases across 6 `HW_REG_MODE` configurations and wave32/wave64 on `gfx1036` driver `32.0.21045.29003`: 2,064/2,064 words exact with 0 clamp diffs and 0 wave diffs). CPU-checked by `tests/semantic/test_alu_cvt_pknorm_f32.py` (the twelve measured near-tie words, ties at the scale steps, ±inf, ±NaN, subnormals, out-of-range values, 40 seeded pairs, abs/neg, `clamp`), `tests/semantic/test_cvt_norm_mods.py`, and `tests/test_pknorm_probe.py`. **GPU-verified through Vulkan** (wave32 synthetic compute shader via `vk_compute_test` with `VK_LAYER_KHRONOS_validation` `1.4.363`, 8 `v_cvt_pknorm_*` plain & `clamp` output words): bit-exact on `AMD Radeon RX 9070 XT` (driver `26.11.2 (LLPC)`, `driverVersion 2.0.416`, Vulkan `1.4.359`) and `AMD Radeon(TM) Graphics` (`gfx1036`, driver `26.11.2`, `driverVersion 2.0.353`, Vulkan `1.4.315`), 0 validation errors. **Not checked through Vulkan on a GPU.** **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137): ±qNaN → 0, ±inf saturation, and round-to-nearest-even ties at ±0.5 match bit-for-bit (the near-tie rounding above is a separate case). **Not GPU-verified.** | 478| `v_cvt_pknorm_i16_f32`, `v_cvt_pknorm_u16_f32` | D[15:0] from S0 and D[31:16] from S1: the f32 is clamped to [-1, 1] (i16) or [0, 1] (u16), multiplied by 32767 or 65535 and rounded to nearest even **once, from the exact product** (SHADER-363). Mesa ACO emits these opcodes for NIR `pack_snorm_2x16`/`pack_unorm_2x16`, which `nir_opcodes.py` defines as `fround_even(fclamp(x) * 32767.0 / 65535.0)`. Emitted as `FClamp`, `OpFMul`, `RoundEven` and a convert, not `PackSnorm2x16`, whose rounding GLSL leaves to the driver. The f32 `OpFMul` can land exactly on k + 0.5 when the exact product is just below or above it, and `RoundEven` would then pick the even neighbour; the product's error `Fma(c, s, -p)` is exact, so on such a tie the translator takes floor(p) + 1 when it is positive, floor(p) when negative, and `RoundEven` when it is 0 (an exact tie). Away from a tie the two roundings agree, since k + 0.5 is an f32 there. NaN gives 0, as `v_cvt_i32_f32` does. On gfx1035 (SHADER-137, `tools/int_hw_probe.py --oracle both`, wave32 and wave64) ±qNaN → 0, ±inf saturation and the round-to-nearest-even ties at ±0.5 match bit for bit. Source modifiers apply. VOP3 `clamp` is a hardware no-op on RDNA2 and is accepted without changing the result; other modifiers (`mul:*`/`div:*`, `op_sel:*`) raise `Unsupported`. Until 2026-11-22 both ops were rejected. **Measured on RDNA2:** on an iGPU (gfx1036, SHADER-339/363, `tools/pknorm_probe.py --oracle hw`) 74 of 74 NaN halves (quiet and signalling, both signs, payloads, in S0 and S1) gave 0 and 28 of 28 near-tie inputs (both directions) gave the single-rounded word, in wave32 and wave64 under the game's MODE and with IEEE 1, DX10_CLAMP 0 or f32 denormals kept; the translator matches all 134 probe words in all ten runs (it was one off on the 28 near ties before SHADER-363; additionally, `tools/cvt_norm_mods_probe.py --hw-arch gfx1036` verified `plain` vs VOP3 `clamp` across 40 edge/near-tie/NaN/±inf/subnormal pairs + 3 source-modifier cases across 6 `HW_REG_MODE` configurations and wave32/wave64 on `gfx1036` driver `32.0.21045.29003`: 2,064/2,064 words exact with 0 clamp diffs and 0 wave diffs). CPU-checked by `tests/semantic/test_alu_cvt_pknorm_f32.py` (the twelve measured near-tie words, ties at the scale steps, ±inf, ±NaN, subnormals, out-of-range values, 40 seeded pairs, abs/neg, `clamp`), `tests/semantic/test_cvt_norm_mods.py`, and `tests/test_pknorm_probe.py`. **GPU-verified through Vulkan** (wave32 synthetic compute shader via `vk_compute_test` with `VK_LAYER_KHRONOS_validation` `1.4.363`, 8 `v_cvt_pknorm_*` plain & `clamp` output words): bit-exact on `AMD Radeon RX 9070 XT` (driver `26.11.2 (LLPC)`, `driverVersion 2.0.416`, Vulkan `1.4.359`) and `AMD Radeon(TM) Graphics` (`gfx1036`, driver `26.11.2`, `driverVersion 2.0.353`, Vulkan `1.4.315`), 0 validation errors. |
478| f16 rounding (SHADER-55, SHADER-56) | **Narrowing to f16 uses integer ops, not `PackHalf2x16`.** Every f16 ALU result (`v_*_f16` VOP1/VOP2/VOP3, `v_pk_*_f16`, `v_cvt_f16_f32`, `v_interp_p2_f16`, `v_fma_mix*`) and `v_cvt_pkrtz_f16_f32` go through `Gen.f16_bits` (round to nearest even, or round toward zero for pkrtz; f16 denormals kept, f32 denormal inputs give ±0, NaN stays a quiet NaN). After a MODE.FP_ROUND toward-zero write the ALU results take the toward-zero form instead (`Gen.f16_res`; see Known approximations). GLSL.std.450 leaves `PackHalf2x16`'s rounding to the implementation, and drivers fold a `PackHalf2x16` → `UnpackHalf2x16` round trip to a no-op, so the next f16 op saw the unrounded f32: #513 (RTX 6000 Ada, `--wave64-emulate`, `v_pk_add_f16` → `v_pk_mul_f16` 1 ulp off), and pkrtz giving round-to-nearest on llvmpipe. **f16 FMAs round once** (`v_fma_f16`, `v_fmac_f16`, `v_pk_fma_f16`): x·y is exact in f32, TwoSum gives the exact error of the f32 sum, and round-to-odd at f32 then rounds correctly to f16. An RX 6700 matched a correctly rounded f16 FMA in 12,612 of 12,612 cases (#374); `Fma` then narrowing double-rounded. Checked by `tests/semantic/test_f16_int_convert.py` (edges + seeded sweep against Python's binary16), `tests/semantic/test_f16_fma_rounding.py` (exact rational reference; built near-tie cases fail on the old translation) and `tools/valu_fuzz.py --family f16` on an RTX 6000 Ada. Image/buffer d16 packing (#489) and the 16-bit interpolant quantize (#512) are separate. **Widening an f16 ALU operand doesn't trust `UnpackHalf2x16` with denormals** (`Gen.f16_in`): on an RTX 5060 Ti (610.88) it gives 0 for a denormal that an SDWA `BYTE_1` select produced, from an inline constant or a VGPR alike, while the same denormal as a literal or already in a VGPR widens right (a local probe of all four, before and after). It depends on the driver: `ps_sdwa_f16_const` failed this way on `main` with NVIDIA 610.88 (RTX 5060 Ti, RTX 3060 Ti, Windows), 595.99 (RTX 5090, Linux) and 580.173 (RTX 3060 Ti, Linux), and passed with 621.01 (RTX 5080) and 621.24 (RTX 5070, RTX 3080 Laptop) (#3220). So a half whose exponent field is 0 is widened as sign × mantissa × 2^-24 with integer ops. Confirmed by the GPU test `ps_sdwa_f16_const` (word y, the denormal `0x0040` × 1024.0 = `0x1c00`), which gave `0x0000` on an RTX 5060 Ti (610.88) natively and under `--wave64-emulate` before and 4096/4096 exact after, and by `tests/semantic/test_value_semantics.py` running it with a flushing `UnpackHalf2x16`. The other `UnpackHalf2x16` uses (packed-f16 reads, interpolants, d16 image results) are not changed. `v_fma_mix*` with f32 sources rounds once straight to f16 via round-to-odd in both nearest and toward-zero modes (measured on an RDNA2 iGPU, gfx1036: `tools/fma_mix_probe.py --oracle hw` gave the single-rounded word for all 7 of 7 tie inputs where the two rules differ, SHADER-135; see Known approximations). `v_fma_mix*` rounds once straight to f16 via round-to-odd in both nearest-even and toward-zero modes, matching hardware (7 of 7 tie inputs of `tools/fma_mix_probe.py --oracle hw` on gfx1036, SHADER-135; see Known approximations). `v_fma_mix*` rounds once straight to f16 via round-to-odd in both nearest and toward-zero modes (see Known approximations); the hardware rounds once: 7 of 7 tie inputs of `tools/fma_mix_probe.py --oracle hw` on gfx1036 (SHADER-135). `v_fma_mix*` with f32 sources uses `Fma` then narrows (two roundings, unmeasured) in nearest-even mode; toward zero it rounds once (see Known approximations). 7 of 7 tie inputs of `tools/fma_mix_probe.py --oracle hw` on gfx1036 (SHADER-135; not fixed yet); toward zero it rounds once (see Known approximations). | 479| f16 rounding (SHADER-55, SHADER-56) | **Narrowing to f16 uses integer ops, not `PackHalf2x16`.** Every f16 ALU result (`v_*_f16` VOP1/VOP2/VOP3, `v_pk_*_f16`, `v_cvt_f16_f32`, `v_interp_p2_f16`, `v_fma_mix*`) and `v_cvt_pkrtz_f16_f32` go through `Gen.f16_bits` (round to nearest even, or round toward zero for pkrtz; f16 denormals kept, f32 denormal inputs give ±0, NaN stays a quiet NaN). After a MODE.FP_ROUND toward-zero write the ALU results take the toward-zero form instead (`Gen.f16_res`; see Known approximations). GLSL.std.450 leaves `PackHalf2x16`'s rounding to the implementation, and drivers fold a `PackHalf2x16` → `UnpackHalf2x16` round trip to a no-op, so the next f16 op saw the unrounded f32: #513 (RTX 6000 Ada, `--wave64-emulate`, `v_pk_add_f16` → `v_pk_mul_f16` 1 ulp off), and pkrtz giving round-to-nearest on llvmpipe. **f16 FMAs round once** (`v_fma_f16`, `v_fmac_f16`, `v_pk_fma_f16`): x·y is exact in f32, TwoSum gives the exact error of the f32 sum, and round-to-odd at f32 then rounds correctly to f16. An RX 6700 matched a correctly rounded f16 FMA in 12,612 of 12,612 cases (#374); `Fma` then narrowing double-rounded. Checked by `tests/semantic/test_f16_int_convert.py` (edges + seeded sweep against Python's binary16), `tests/semantic/test_f16_fma_rounding.py` (exact rational reference; built near-tie cases fail on the old translation) and `tools/valu_fuzz.py --family f16` on an RTX 6000 Ada. Image/buffer d16 packing (#489) and the 16-bit interpolant quantize (#512) are separate. **Widening an f16 ALU operand doesn't trust `UnpackHalf2x16` with denormals** (`Gen.f16_in`): on an RTX 5060 Ti (610.88) it gives 0 for a denormal that an SDWA `BYTE_1` select produced, from an inline constant or a VGPR alike, while the same denormal as a literal or already in a VGPR widens right (a local probe of all four, before and after). It depends on the driver: `ps_sdwa_f16_const` failed this way on `main` with NVIDIA 610.88 (RTX 5060 Ti, RTX 3060 Ti, Windows), 595.99 (RTX 5090, Linux) and 580.173 (RTX 3060 Ti, Linux), and passed with 621.01 (RTX 5080) and 621.24 (RTX 5070, RTX 3080 Laptop) (#3220). So a half whose exponent field is 0 is widened as sign × mantissa × 2^-24 with integer ops. Confirmed by the GPU test `ps_sdwa_f16_const` (word y, the denormal `0x0040` × 1024.0 = `0x1c00`), which gave `0x0000` on an RTX 5060 Ti (610.88) natively and under `--wave64-emulate` before and 4096/4096 exact after, and by `tests/semantic/test_value_semantics.py` running it with a flushing `UnpackHalf2x16`. The other `UnpackHalf2x16` uses (packed-f16 reads, interpolants, d16 image results) are not changed. `v_fma_mix*` with f32 sources rounds once straight to f16 via round-to-odd in both nearest and toward-zero modes (measured on an RDNA2 iGPU, gfx1036: `tools/fma_mix_probe.py --oracle hw` gave the single-rounded word for all 7 of 7 tie inputs where the two rules differ, SHADER-135; see Known approximations). `v_fma_mix*` rounds once straight to f16 via round-to-odd in both nearest-even and toward-zero modes, matching hardware (7 of 7 tie inputs of `tools/fma_mix_probe.py --oracle hw` on gfx1036, SHADER-135; see Known approximations). `v_fma_mix*` rounds once straight to f16 via round-to-odd in both nearest and toward-zero modes (see Known approximations); the hardware rounds once: 7 of 7 tie inputs of `tools/fma_mix_probe.py --oracle hw` on gfx1036 (SHADER-135). `v_fma_mix*` with f32 sources uses `Fma` then narrows (two roundings, unmeasured) in nearest-even mode; toward zero it rounds once (see Known approximations). 7 of 7 tie inputs of `tools/fma_mix_probe.py --oracle hw` on gfx1036 (SHADER-135; not fixed yet); toward zero it rounds once (see Known approximations). |
479| `v_cvt_pknorm_i16_f16`, `v_cvt_pknorm_u16_f16` | VOP3 packed normalized conversion from two f16 sources (`D[15:0]` from `S0.f16`, `D[31:16]` from `S1.f16`): each selected f16 half (`op_sel[0..1]`, with `neg`/`abs` source modifiers and inline f16 constants via `Gen.f16_in`) is clamped to `[-1, 1]` (`i16`) or `[0, 1]` (`u16`), scaled by `32767` or `65535`, and rounded once to nearest even (`+inf → 32767`/`65535`, `-inf → -32767`/`0`, `NaN → 0`, `±0` and f16 denormals `→ 0`). Uses `cl * (scale + 1) - RoundEven(cl)` for `\|cl\| >= 0.25` to avoid binary32 double-rounding at near-tie f16 inputs (e.g. `0x3801` = `0.5 + 2^-11`). **Measured natively on RDNA2** (`AMD Radeon(TM) Graphics`, `gfx1036`, wave32 & wave64 via `tools/cvt_pknorm_f16_probe.py`): across all 65,536 binary16 inputs in `plain`, `clamp`, `op_sel:[0,0,1]`, and `op_sel:[0,0,1] clamp` (1,048,576 half evaluations) plus 33 targeted edge cases (264 words), VOP3 `clamp` is a **hardware no-op**, destination `op_sel[2] = 1` (`op_sel:[s0,s1,1]`) shifts the 32-bit packed result left by 16 bits (`D[31:16] = norm16(S0.f16)`, `D[15:0] = 0x0000`, overwriting prior `vdst` and dropping `S1`), and raw reserved VOP3 `omod` bits `[60:59]` (`1..3`) are ignored by silicon (rejected by `llvm-mc` on `gfx1036`). The translator accepts `clamp` (no-op) and `op_sel[2] = 1` (`OpShiftLeftLogical` by 16), while `mul:*`/`div:*`, VOP3P modifiers (`op_sel_hi:*`, `neg_lo:*`, `neg_hi:*`), `_dpp`/`_sdwa`, duplicate `op_sel:`, and malformed `op_sel` lists raise `Unsupported`. Output modifiers (`clamp`, `mul:*`, `div:*`), `op_sel` destination bit, and VOP3P modifiers raise `Unsupported`. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) (VOP3 `v_cvt_pknorm_i16_f16` / `v_cvt_pknorm_u16_f16`) and LLVM AMDGPU `VOP3Instructions.td`. Checked bit-for-bit against an exact rational `fractions.Fraction` reference on the CPU (`spirv_mini_interp`) and with `spirv-val` by `tests/semantic/test_alu_cvt_pknorm_f16.py` and `tests/semantic/test_cvt_pknorm_f16_mods.py`, by unit tests `tests/test_cvt_pknorm_f16_probe.py`, and through Vulkan (`vk_compute_test` with `VK_LAYER_KHRONOS_validation`, 116/116 exact words, 0 clamp diffs, 0 validation errors) on `AMD Radeon RX 9070 XT` (driver `26.11.2 (LLPC)`) and `AMD Radeon(TM) Graphics` (`gfx1036`, driver `26.11.2`); not run on the shader corpus. Checked bit-for-bit against an exact rational `fractions.Fraction` reference on the CPU (`spirv_mini_interp`) and with `spirv-val` by `tests/semantic/test_alu_cvt_pknorm_f16.py`; **Hardware-verified on RDNA2** (AMD Radeon gfx1036, wave32 and wave64, `tools/int_hw_probe.py --oracle both --group valu_cvt_norm_f16`): 33 programs of four conversions each over +-0, +-1, 1 +- 1ulp, +-0.5 and the f16 neighbours of the 0.5 and 0.25 ties, an f16 denormal, +-65504, +-inf and quiet and signalling NaNs, with `op_sel:[1,0]`/`[0,1]` and `neg`/`abs`, all bit-identical to the translator. Not run on the shader corpus. **not GPU-verified** and not run on the shader corpus. . **Hardware-measured natively on `gfx1100`** (RX 7900 XTX, driver 26.10.1) with `tools/hw_oracle`, 38 cases against the same exact-rational model, all matching: the halves pack in the documented order (`0.3333 \| 0.5+2^-11` and `1.5 \| -0.5` are asymmetric), each result is one round-to-nearest-even of the exact `cl * 32767` or `cl * 65535` (`0x3801` gives `32799` for `u16`), out-of-range values and infinities saturate the same way (`+inf` gives `32767`/`65535`, `-inf` gives `-32767`/`0`, so an infinity clamps to `±1`), and `NaN` (quiet or signalling), `-0` and a denormal f16 input all give `0`. Not measured: the `op_sel` destination bit and the `neg`/`abs` source modifiers, and not run on the shader corpus. | 480| `v_cvt_pknorm_i16_f16`, `v_cvt_pknorm_u16_f16` | VOP3 packed normalized conversion from two f16 sources (`D[15:0]` from `S0.f16`, `D[31:16]` from `S1.f16`): each selected f16 half (`op_sel[0..1]`, with `neg`/`abs` source modifiers and inline f16 constants via `Gen.f16_in`) is clamped to `[-1, 1]` (`i16`) or `[0, 1]` (`u16`), scaled by `32767` or `65535`, and rounded once to nearest even (`+inf → 32767`/`65535`, `-inf → -32767`/`0`, `NaN → 0`, `±0` and f16 denormals `→ 0`). Uses `cl * (scale + 1) - RoundEven(cl)` for `\|cl\| >= 0.25` to avoid binary32 double-rounding at near-tie f16 inputs (e.g. `0x3801` = `0.5 + 2^-11`). **Measured natively on RDNA2** (`AMD Radeon(TM) Graphics`, `gfx1036`, wave32 & wave64 via `tools/cvt_pknorm_f16_probe.py`): across all 65,536 binary16 inputs in `plain`, `clamp`, `op_sel:[0,0,1]`, and `op_sel:[0,0,1] clamp` (1,048,576 half evaluations) plus 33 targeted edge cases (264 words), VOP3 `clamp` is a **hardware no-op**, destination `op_sel[2] = 1` (`op_sel:[s0,s1,1]`) shifts the 32-bit packed result left by 16 bits (`D[31:16] = norm16(S0.f16)`, `D[15:0] = 0x0000`, overwriting prior `vdst` and dropping `S1`), and raw reserved VOP3 `omod` bits `[60:59]` (`1..3`) are ignored by silicon (rejected by `llvm-mc` on `gfx1036`). The translator accepts `clamp` (no-op) and `op_sel[2] = 1` (`OpShiftLeftLogical` by 16), while `mul:*`/`div:*`, VOP3P modifiers (`op_sel_hi:*`, `neg_lo:*`, `neg_hi:*`), `_dpp`/`_sdwa`, duplicate `op_sel:`, and malformed `op_sel` lists raise `Unsupported`. Output modifiers (`clamp`, `mul:*`, `div:*`), `op_sel` destination bit, and VOP3P modifiers raise `Unsupported`. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) (VOP3 `v_cvt_pknorm_i16_f16` / `v_cvt_pknorm_u16_f16`) and LLVM AMDGPU `VOP3Instructions.td`. Checked bit-for-bit against an exact rational `fractions.Fraction` reference on the CPU (`spirv_mini_interp`) and with `spirv-val` by `tests/semantic/test_alu_cvt_pknorm_f16.py` and `tests/semantic/test_cvt_pknorm_f16_mods.py`, by unit tests `tests/test_cvt_pknorm_f16_probe.py`, and through Vulkan (`vk_compute_test` with `VK_LAYER_KHRONOS_validation`, 116/116 exact words, 0 clamp diffs, 0 validation errors) on `AMD Radeon RX 9070 XT` (driver `26.11.2 (LLPC)`) and `AMD Radeon(TM) Graphics` (`gfx1036`, driver `26.11.2`); not run on the shader corpus. Checked bit-for-bit against an exact rational `fractions.Fraction` reference on the CPU (`spirv_mini_interp`) and with `spirv-val` by `tests/semantic/test_alu_cvt_pknorm_f16.py`; **Hardware-verified on RDNA2** (AMD Radeon gfx1036, wave32 and wave64, `tools/int_hw_probe.py --oracle both --group valu_cvt_norm_f16`): 33 programs of four conversions each over +-0, +-1, 1 +- 1ulp, +-0.5 and the f16 neighbours of the 0.5 and 0.25 ties, an f16 denormal, +-65504, +-inf and quiet and signalling NaNs, with `op_sel:[1,0]`/`[0,1]` and `neg`/`abs`, all bit-identical to the translator. Not run on the shader corpus. **not GPU-verified** and not run on the shader corpus. . **Hardware-measured natively on `gfx1100`** (RX 7900 XTX, driver 26.10.1) with `tools/hw_oracle`, 38 cases against the same exact-rational model, all matching: the halves pack in the documented order (`0.3333 \| 0.5+2^-11` and `1.5 \| -0.5` are asymmetric), each result is one round-to-nearest-even of the exact `cl * 32767` or `cl * 65535` (`0x3801` gives `32799` for `u16`), out-of-range values and infinities saturate the same way (`+inf` gives `32767`/`65535`, `-inf` gives `-32767`/`0`, so an infinity clamps to `±1`), and `NaN` (quiet or signalling), `-0` and a denormal f16 input all give `0`. Not measured: the `op_sel` destination bit and the `neg`/`abs` source modifiers, and not run on the shader corpus. |
480| `s_round_mode` | SIMM16[3:0] sets FP_ROUND. The translator accepts FP32 nearest-even with FP16/64 nearest-even or toward-zero and writes the same per-invocation state as `s_setreg_imm32_b32`. Other rounding modes raise Unsupported. AMD RDNA2 ISA tables 15 and 24; synthetic positive and negative halfway-neighbour conversions check both modes in one shader (`test_round_mode_switches_half_precision_color_rounding` in `tests/semantic/test_scalar_noop_waitcnt.py`). | 481| `s_round_mode` | SIMM16[3:0] sets FP_ROUND. The translator accepts FP32 nearest-even with FP16/64 nearest-even or toward-zero and writes the same per-invocation state as `s_setreg_imm32_b32`. Other rounding modes raise Unsupported. AMD RDNA2 ISA tables 15 and 24; synthetic positive and negative halfway-neighbour conversions check both modes in one shader (`test_round_mode_switches_half_precision_color_rounding` in `tests/semantic/test_scalar_noop_waitcnt.py`). |
481| f16 narrowing size | `Gen.f16_bits` leaves out or shares steps where that can't change the result. In nearest-even mode there is no separate infinity select: infinity is already at or above the overflow threshold (65520), which gives 0x7C00. For `v_add_f16`, `v_sub_f16`, `v_subrev_f16` and `v_pk_add_f16` without omod (`exact_tiny`), the range below 2^-14 is neither rounded nor tested for underflow: a sum of two f16 values is a multiple of 2^-24, so there it is already an f16 value, and clamp keeps that true. With an omod the rounding stays, since `div:2` can create a tie. No range has an underflow test: below 2^-25 the shift is 25, which moves the mantissa (plus the rounding bias) out to 0. The subnormal range rounds like the normal one, by adding half - 1 + the kept low bit before the shift. When the program writes MODE, `Gen.f16_res` makes one pass: toward zero selects a bias of 0, the 65536 overflow threshold and 0x7BFF, and keeps the infinity select. Confirmed by running the emitted integer sequences before and after on all 2^32 f32 inputs (both roundings) and on all 2^32 f16 operand pairs (both roundings, with and without clamp): no difference. Regression test: `tests/semantic/test_f16_sum_narrowing.py`. | 482| f16 narrowing size | `Gen.f16_bits` leaves out or shares steps where that can't change the result. In nearest-even mode there is no separate infinity select: infinity is already at or above the overflow threshold (65520), which gives 0x7C00. For `v_add_f16`, `v_sub_f16`, `v_subrev_f16` and `v_pk_add_f16` without omod (`exact_tiny`), the range below 2^-14 is neither rounded nor tested for underflow: a sum of two f16 values is a multiple of 2^-24, so there it is already an f16 value, and clamp keeps that true. With an omod the rounding stays, since `div:2` can create a tie. No range has an underflow test: below 2^-25 the shift is 25, which moves the mantissa (plus the rounding bias) out to 0. The subnormal range rounds like the normal one, by adding half - 1 + the kept low bit before the shift. When the program writes MODE, `Gen.f16_res` makes one pass: toward zero selects a bias of 0, the 65536 overflow threshold and 0x7BFF, and keeps the infinity select. Confirmed by running the emitted integer sequences before and after on all 2^32 f32 inputs (both roundings) and on all 2^32 f16 operand pairs (both roundings, with and without clamp): no difference. Regression test: `tests/semantic/test_f16_sum_narrowing.py`. |
482| `v_interp_p2_f16` clamp | The VOP3 `clamp` bit on `v_interp_p2_f16` clamps its f16 result to [0, 1], applied before the narrowing like the other f16 results (Mesa ACO `aco_opcodes.py` declares the op `dst(F16)`, which takes output modifiers; llvm-mc encodes `clamp` on it but no omod). Until 2026-11-22 the translator dropped it. Checked by `tests/semantic/test_interp_f16.py`: attributes 1.5 and -0.25 read with clamp give 1.0 and +0.0, and without it 1.5 and -0.25. No GPU test: `vs_ids` gives attributes in [0, 1) only. | 483| `v_interp_p2_f16` clamp | The VOP3 `clamp` bit on `v_interp_p2_f16` clamps its f16 result to [0, 1], applied before the narrowing like the other f16 results (Mesa ACO `aco_opcodes.py` declares the op `dst(F16)`, which takes output modifiers; llvm-mc encodes `clamp` on it but no omod). Until 2026-11-22 the translator dropped it. Checked by `tests/semantic/test_interp_f16.py`: attributes 1.5 and -0.25 read with clamp give 1.0 and +0.0, and without it 1.5 and -0.25. No GPU test: `vs_ids` gives attributes in [0, 1) only. |
483| 16-bit interpolation (`v_interp_p1ll_f16` / `v_interp_p2_f16`, `high`) | A 16-bit varying shares its 32-bit param channel with another: the producer packs them as low half, high half (Mesa `ac_nir_prerast_utils.c`: `nir_pack_32_2x16_split` by `io_sem.high_16bits`), the PS sets `FP16_INTERP_MODE` (plus `ATTR1_VALID` when the high half is used, RADV `radv_ps_input_type_bits`), and the `high` bit picks the half on both ops of the pair (ACO `emit_interp_instr`, `aco_isel_helpers.cpp`; llvm-mc gfx1013 sets the same bit, byte 5 bit 0, on both: p1ll `v2, v0, attr0.x high` 0x00 → 0x01, p2 `v2, v1, attr0.x, v3 high` 0x02 → 0x03). The translated VS exports the channel's raw bits, so interpolating them as one f32 gives neither half. A location any `*_f16` interp reads is therefore declared `PerVertexKHR` (`vec4[3]`, no `Flat`; it still matches a producer's vec4 output at that location); this needs `VK_KHR_fragment_shader_barycentric` (`fragmentShaderBarycentric`) for every such PS, not just the raw-barycentric ones; the index records it like any capability (`features: ["fragmentShaderBarycentric"]`), so `vk_pipeline_check` and `vk_harness` skip such a PS on a device without it. Nothing picks `--bary-fallback` from the device: it is a translation-time flag. Each f16 read decodes its half of each vertex's word (`UnpackHalf2x16` component 0 or 1) and weights them as AMD does, P0 + i(P1 − P0) + j(P2 − P0) with i, j = `BaryCoordKHR`.y/.z, then p2 clamps and narrows as before. f32 reads of such a location (`p1/p2_f32`) interpolate the raw word the same way, and `v_interp_mov_f32` takes vertex 0's. Until 2026-11-22 `high` was ignored and both halves read the smooth-f32 interpolation of the whole word; abilliontokens counted `high` in 4,776 of 12,101 PS (39.5%, 51,684 instructions, always p1ll/p2 pairs, no `p1lv`), and Pipodi found 4,731 of those 4,776 read both halves of the same channel, with p1ll and p2 always agreeing on attribute, channel and `high`. Like the f32 path, the pair's I/J operands are not read: the weights come from `BaryCoordKHR` (213 PS that compute their own barycentrics into v0/v1 first are a separate gap). Confirmed by `tests/semantic/test_interp_f16_high.py` (per-vertex halves 0.5/1.5/2.5 and −4/8/16 at weights (0.25, 0.25, 0.5) give 1.75 and 9.0; fails on the old translation) and the GPU fixture `ps_interp_f16_high` drawn with `vs_f16_pack` (u and v packed in one channel both ways, f32 control) and, through `scripts/run_gpu_tests.py`, with the mesh producer `ms_f16_pack` (mesh `exp paramN` stores the same raw words, `Gen.ms_export`): both pass on an RTX 5070 and fail on the old translation (off by 0.984). spirv-val and `vk_pipeline_check` (real pipelines against the vec4 VS stubs, RTX 5070) also accept PS mixing high, low, f32 and flat reads of one location and of several. **Measured natively on RDNA2** (AMD Radeon 680M, `gfx1035`, wave32 and wave64 via `tools/vinterp_hw_probe.py --oracle both`, SHADER-430): the VINTRP unit reads `P0`, `P10` and `P20` from LDS at `M0 + 48·attr + {8·c, 8·c + 4, 32 + 4·c}`; `v_interp_p1ll_f16` (and `v_interp_p1lv_f16`, taking `P0.half` from `vsrc2`) widens the selected f16 half (`[15:0]` or `[31:16]` with `high`) to binary32 and writes the fused binary32 `fma(i, f32(P10.half), f32(P0.half))`, while `v_interp_p2_f16` rounds the exact `partial_f32 + j · f32(P20.half)` once to f16 following `MODE.FP_ROUND.16_64` (like `v_fma_mixlo_f16`, whereas the translator narrows the f32 sum) and writes `vdst[15:0]` while hardware keeps `vdst[31:16]`; f16 subnormal halves are preserved with `denorm_mode_16_64 = 3` (`0x0001 + 0.5·0x0200 + 0.5·0x0200 → 0x0201`, flushed to `±0` when `0`), and f16 NaN halves quiet with payload preserved (`0x7e05 → 0x7e05`, `0x7c01 → 0x7e01`). **ALU half measured on AMD hardware** (SHADER-430, `tools/interp_hw_probe.py`, gfx1036, every case matched; `docs/shader_validation.md`): `p1ll_f16` widens the chosen f16 halves exactly and computes fma(h10, I, h0) with one rounding to f32. `p2_f16` computes fma(h20, J, p1ll) and rounds it once, straight to f16: 30 hand-built ties gave that result and never f32-then-f16. It keeps vdst's high 16 bits. The translator used to zero them and now keeps them (`write_lo16`; `test_p2_f16_keeps_the_high_half_of_vdst`). **Still unverified:** what the SPI writes into LDS for a packed channel in a real draw (P10/P20 as f32 differences of the raw words, or per-half f16 differences under `FP16_INTERP_MODE`), which needs a pixel-shader harness; also f16 inf/NaN halves and `p1lv_f16`. **Unverified:** AMD hardware (whether it computes P10/P20 in f16 or rounds the p1ll intermediate differently), f16 denormal and NaN halves. **`--bary-fallback`** has no per-vertex inputs, so it keeps the old smooth-f32 read and cannot honour `high`; `check.py` skips the fixture there. MoltenVK can't compile `PerVertexKHR`: see the next row. | 484| 16-bit interpolation (`v_interp_p1ll_f16` / `v_interp_p2_f16`, `high`) | A 16-bit varying shares its 32-bit param channel with another: the producer packs them as low half, high half (Mesa `ac_nir_prerast_utils.c`: `nir_pack_32_2x16_split` by `io_sem.high_16bits`), the PS sets `FP16_INTERP_MODE` (plus `ATTR1_VALID` when the high half is used, RADV `radv_ps_input_type_bits`), and the `high` bit picks the half on both ops of the pair (ACO `emit_interp_instr`, `aco_isel_helpers.cpp`; llvm-mc gfx1013 sets the same bit, byte 5 bit 0, on both: p1ll `v2, v0, attr0.x high` 0x00 → 0x01, p2 `v2, v1, attr0.x, v3 high` 0x02 → 0x03). The translated VS exports the channel's raw bits, so interpolating them as one f32 gives neither half. A location any `*_f16` interp reads is therefore declared `PerVertexKHR` (`vec4[3]`, no `Flat`; it still matches a producer's vec4 output at that location); this needs `VK_KHR_fragment_shader_barycentric` (`fragmentShaderBarycentric`) for every such PS, not just the raw-barycentric ones; the index records it like any capability (`features: ["fragmentShaderBarycentric"]`), so `vk_pipeline_check` and `vk_harness` skip such a PS on a device without it. Nothing picks `--bary-fallback` from the device: it is a translation-time flag. Each f16 read decodes its half of each vertex's word (`UnpackHalf2x16` component 0 or 1) and weights them as AMD does, P0 + i(P1 − P0) + j(P2 − P0) with i, j = `BaryCoordKHR`.y/.z, then p2 clamps and narrows as before. f32 reads of such a location (`p1/p2_f32`) interpolate the raw word the same way, and `v_interp_mov_f32` takes vertex 0's. Until 2026-11-22 `high` was ignored and both halves read the smooth-f32 interpolation of the whole word; abilliontokens counted `high` in 4,776 of 12,101 PS (39.5%, 51,684 instructions, always p1ll/p2 pairs, no `p1lv`), and Pipodi found 4,731 of those 4,776 read both halves of the same channel, with p1ll and p2 always agreeing on attribute, channel and `high`. Like the f32 path, the pair's I/J operands are not read: the weights come from `BaryCoordKHR` (213 PS that compute their own barycentrics into v0/v1 first are a separate gap). Confirmed by `tests/semantic/test_interp_f16_high.py` (per-vertex halves 0.5/1.5/2.5 and −4/8/16 at weights (0.25, 0.25, 0.5) give 1.75 and 9.0; fails on the old translation) and the GPU fixture `ps_interp_f16_high` drawn with `vs_f16_pack` (u and v packed in one channel both ways, f32 control) and, through `scripts/run_gpu_tests.py`, with the mesh producer `ms_f16_pack` (mesh `exp paramN` stores the same raw words, `Gen.ms_export`): both pass on an RTX 5070 and fail on the old translation (off by 0.984). spirv-val and `vk_pipeline_check` (real pipelines against the vec4 VS stubs, RTX 5070) also accept PS mixing high, low, f32 and flat reads of one location and of several. **Measured natively on RDNA2** (AMD Radeon 680M, `gfx1035`, wave32 and wave64 via `tools/vinterp_hw_probe.py --oracle both`, SHADER-430): the VINTRP unit reads `P0`, `P10` and `P20` from LDS at `M0 + 48·attr + {8·c, 8·c + 4, 32 + 4·c}`; `v_interp_p1ll_f16` (and `v_interp_p1lv_f16`, taking `P0.half` from `vsrc2`) widens the selected f16 half (`[15:0]` or `[31:16]` with `high`) to binary32 and writes the fused binary32 `fma(i, f32(P10.half), f32(P0.half))`, while `v_interp_p2_f16` rounds the exact `partial_f32 + j · f32(P20.half)` once to f16 following `MODE.FP_ROUND.16_64` (like `v_fma_mixlo_f16`, whereas the translator narrows the f32 sum) and writes `vdst[15:0]` while hardware keeps `vdst[31:16]`; f16 subnormal halves are preserved with `denorm_mode_16_64 = 3` (`0x0001 + 0.5·0x0200 + 0.5·0x0200 → 0x0201`, flushed to `±0` when `0`), and f16 NaN halves quiet with payload preserved (`0x7e05 → 0x7e05`, `0x7c01 → 0x7e01`). **ALU half measured on AMD hardware** (SHADER-430, `tools/interp_hw_probe.py`, gfx1036, every case matched; `docs/shader_validation.md`): `p1ll_f16` widens the chosen f16 halves exactly and computes fma(h10, I, h0) with one rounding to f32. `p2_f16` computes fma(h20, J, p1ll) and rounds it once, straight to f16: 30 hand-built ties gave that result and never f32-then-f16. It keeps vdst's high 16 bits. The translator used to zero them and now keeps them (`write_lo16`; `test_p2_f16_keeps_the_high_half_of_vdst`). **Still unverified:** what the SPI writes into LDS for a packed channel in a real draw (P10/P20 as f32 differences of the raw words, or per-half f16 differences under `FP16_INTERP_MODE`), which needs a pixel-shader harness; also f16 inf/NaN halves and `p1lv_f16`. **Unverified:** AMD hardware (whether it computes P10/P20 in f16 or rounds the p1ll intermediate differently), f16 denormal and NaN halves. **`--bary-fallback`** has no per-vertex inputs, so it keeps the old smooth-f32 read and cannot honour `high`; `check.py` skips the fixture there. MoltenVK can't compile `PerVertexKHR`: see the next row. |
484| 16-bit interpolation without `PerVertexKHR` (`--f16-interp-fallback`) | MoltenVK reports `fragmentShaderBarycentric` but can't create a pipeline with the row above's inputs: its SPIR-V to MSL conversion stops with "PerVertexKHR decoration is not supported in MSL" (MoltenVK 1.4.2 on an Apple A18 Pro and, reported by @DomasUrbonas in #166, an M4 Pro), so `ps_interp_f16_high` failed on every Mac. With the flag no `PerVertexKHR` (and, for these reads, no `BaryCoordKHR`) is used: every VS `exp paramN`, mesh param and `--mesh-compute` vertex (`tools/mesh_compute_vs.py`) also exports the channel's two f16 halves decoded to f32 (`UnpackHalf2x16`), low halves at location 28 − 2N and high halves at 29 − 2N, so nothing goes above location 29: MoltenVK's `maxVertexOutputComponents` is 124 because Metal counts `gl_Position` in its 128 vertex-output scalars, and the Khronos validation layer counts it too, so a VS output at location 30 failed VUID-RuntimeSpirv-Location-06272 on `vs_ids` (SHADER-291); a PS `*_f16` read of attrN.c takes component c of that ordinary smooth input, then p2 clamps and narrows as before. Interpolation is linear, so the device interpolating the decoded halves gives the same P0 + i(P1 − P0) + j(P2 − P0) as the per-vertex path, with the interpolator's rounding instead of explicit f32 arithmetic. f32 and `v_interp_mov_f32` reads of such a location are the raw word as on any location (flat = the provoking vertex's word, exact). A producer leaves out the halves of a param whose locations would land on one of its own params (params 0..P−1 leave room for the halves of params 0..(28 − P) / 2), and when a PS's canonical decoded-half locations collide with an attribute it reads, its halves are packed into free locations instead (dynamic packing, below). The index records `f16_halves` ({param: [low, high location]}) on both sides; a pipeline links when the PS's entries are among its producer's. Chosen like the wave64 mode: `tools/vk_subgroup_info.py` reports `per_vertex_inputs` (false without `fragmentShaderBarycentric` or on driver ID MoltenVK), and `make_game.py` and `run_gpu_tests.py` turn the flag on where it is false (`LEONIDA_F16_INTERP_FALLBACK=1`/`0` overrides the runner; `build.py` takes only the variable, since it may run in WSL). Without the flag the translation is unchanged: all 139 GPU-test modules are byte-identical to main's, with and without `--bary-fallback` and with `--mesh-compute --wave64-emulate`, so NVIDIA and AMD keep the exact per-vertex path. Confirmed on an Apple A18 Pro (macOS 26.6.2, MoltenVK 1.4.2): `ps_interp_f16_high` drawn with `vs_f16_pack` passes natively and with wave64 emulation, every one of its 4,096 pixels bit-exact to f16 of the exact u and v in both halves (it failed before at pipeline creation), and `ms_f16_pack` through `--mesh-compute` (`LEONIDA_MESH_COMPUTE=1`) passes too; `tests/semantic/test_f16_interp_fallback.py` checks the PS reads (1.75 and 9.0 from the decoded halves), the VS exports (one-lane interpreter), the overlap rules and the default being unchanged. **Unverified:** a PS whose producer exports more params than leave room for the halves it reads (it reads that producer's param, not halves: the `f16_halves` entries then don't match); devices with fewer than 31 output locations. CPU check (TEST-398, `FallbackStagePair`): with ordinary VS exports at 28 and 29, the PS reads those values (5 and 7 in the test) in place of attr0's decoded halves (2 and 3). Only the PS lists attr0 in `f16_halves`. With param28 as the last export, location 28 carries its ordinary value and location 29 has no VS output. When the last ordinary export is at 27, both stages list the pair and the PS reads 2 and 3. The move from 30 to 29 (SHADER-291) was checked on an Apple M5 (macOS 27.2.1, MoltenVK 1.4.2, Khronos validation layer 1.4.363): over the 170 GPU-test modules `vk_pipeline_check` reported VUID-RuntimeSpirv-Location-06272 on 6 vertex shaders at location 30 and on none at 29; the same 15 modules list `f16_halves` for the same params, `run_gpu_tests.py` gives the same result per test, and `ps_interp_f16_high` reads back byte-identical pixels. **Dynamic packing and per-pipeline PSO linking (SHADER-378):** when a PS's canonical `28 − 2N`/`29 − 2N` slots collide with its raw attributes (266 corpus PS where f16-read attrs reach `n >= 7` and raw attrs reach 12–14, all with `2·\|F\| <= 29 − max`) or fall below 0, `assign_f16_half_locations` in `tools/rdna2spirv.py` packs all `f16_halves` pairs downward from location 29 into locations disjoint from its raw attributes (keeping the canonical slots byte-identical whenever collision-free, and refusing only genuine `> 30` location budget overflows); `tools/mesh_compute_vs.py` adds `pair_f16_halves` and an optional `f16_halves` override to `vs_spvasm`; and at graphics PSO creation `runtime/src/shader_library.h` loads `f16_halves` while `runtime/src/spirv_f16_halves.h` (called from `runtime/shims/d3d12_vulkan_device.cpp`) fast-paths exact matches, relocates PS/VS `Location` decorations when needed, demotes unneeded VS static half outputs to `Private`, and synthesizes `UnpackHalf2x16` half exports before `OpReturn` for params a high-param producer (`param0..15`) could not emit statically. Checked by `tests/semantic/test_f16_interp_fallback.py`, `tests/semantic/test_interp_p1lv_f16.py`, `tests/test_mesh_compute_vs.py`, `runtime/test/shader_library_test.cpp`, `runtime/test/spirv_f16_halves_test.cpp`, and `runtime/test/d3d12_f16_halves_test.cpp` (real Vulkan 1.3 draw on NVIDIA GeForce RTX 4060 Ti, driver 32.0.16.1088, Windows 11: 16-param VS + colliding PS both synthesized and relocated render exact RGBA `(64, 191, 127, 255)`). **Unverified:** native MoltenVK validation run on macOS and full-corpus recount under `--f16-interp-fallback` (needs game copy); native `MeshEXT` runtime PSO specialization (mesh PSOs are not on `main` yet); devices with fewer than 124 vertex output components. Combined with `--bary-fallback`'s geometry shader (`tools/rdna2spirv.py` allocates `%bary` outside all occupied read and reserved f16-half slots; covered by `tests/semantic/test_bary_fallback.py`, and all `3/3` whole-corpus shaders combining both draw `11/11` targets bit-exact on an RX 6650 XT). | 485| 16-bit interpolation without `PerVertexKHR` (`--f16-interp-fallback`) | MoltenVK reports `fragmentShaderBarycentric` but can't create a pipeline with the row above's inputs: its SPIR-V to MSL conversion stops with "PerVertexKHR decoration is not supported in MSL" (MoltenVK 1.4.2 on an Apple A18 Pro and, reported by @DomasUrbonas in #166, an M4 Pro), so `ps_interp_f16_high` failed on every Mac. With the flag no `PerVertexKHR` (and, for these reads, no `BaryCoordKHR`) is used: every VS `exp paramN`, mesh param and `--mesh-compute` vertex (`tools/mesh_compute_vs.py`) also exports the channel's two f16 halves decoded to f32 (`UnpackHalf2x16`), low halves at location 28 − 2N and high halves at 29 − 2N, so nothing goes above location 29: MoltenVK's `maxVertexOutputComponents` is 124 because Metal counts `gl_Position` in its 128 vertex-output scalars, and the Khronos validation layer counts it too, so a VS output at location 30 failed VUID-RuntimeSpirv-Location-06272 on `vs_ids` (SHADER-291); a PS `*_f16` read of attrN.c takes component c of that ordinary smooth input, then p2 clamps and narrows as before. Interpolation is linear, so the device interpolating the decoded halves gives the same P0 + i(P1 − P0) + j(P2 − P0) as the per-vertex path, with the interpolator's rounding instead of explicit f32 arithmetic. f32 and `v_interp_mov_f32` reads of such a location are the raw word as on any location (flat = the provoking vertex's word, exact). A producer leaves out the halves of a param whose locations would land on one of its own params (params 0..P−1 leave room for the halves of params 0..(28 − P) / 2), and when a PS's canonical decoded-half locations collide with an attribute it reads, its halves are packed into free locations instead (dynamic packing, below). The index records `f16_halves` ({param: [low, high location]}) on both sides; a pipeline links when the PS's entries are among its producer's. Chosen like the wave64 mode: `tools/vk_subgroup_info.py` reports `per_vertex_inputs` (false without `fragmentShaderBarycentric` or on driver ID MoltenVK), and `make_game.py` and `run_gpu_tests.py` turn the flag on where it is false (`LEONIDA_F16_INTERP_FALLBACK=1`/`0` overrides the runner; `build.py` takes only the variable, since it may run in WSL). Without the flag the translation is unchanged: all 139 GPU-test modules are byte-identical to main's, with and without `--bary-fallback` and with `--mesh-compute --wave64-emulate`, so NVIDIA and AMD keep the exact per-vertex path. Confirmed on an Apple A18 Pro (macOS 26.6.2, MoltenVK 1.4.2): `ps_interp_f16_high` drawn with `vs_f16_pack` passes natively and with wave64 emulation, every one of its 4,096 pixels bit-exact to f16 of the exact u and v in both halves (it failed before at pipeline creation), and `ms_f16_pack` through `--mesh-compute` (`LEONIDA_MESH_COMPUTE=1`) passes too; `tests/semantic/test_f16_interp_fallback.py` checks the PS reads (1.75 and 9.0 from the decoded halves), the VS exports (one-lane interpreter), the overlap rules and the default being unchanged. CPU check (TEST-398, `FallbackStagePair`): with ordinary VS exports at 28 and 29, the PS reads those values (5 and 7 in the test) in place of attr0's decoded halves (2 and 3). Only the PS lists attr0 in `f16_halves`. With param28 as the last export, location 28 carries its ordinary value and location 29 has no VS output. When the last ordinary export is at 27, both stages list the pair and the PS reads 2 and 3. The move from 30 to 29 (SHADER-291) was checked on an Apple M5 (macOS 27.2.1, MoltenVK 1.4.2, Khronos validation layer 1.4.363): over the 170 GPU-test modules `vk_pipeline_check` reported VUID-RuntimeSpirv-Location-06272 on 6 vertex shaders at location 30 and on none at 29; the same 15 modules list `f16_halves` for the same params, `run_gpu_tests.py` gives the same result per test, and `ps_interp_f16_high` reads back byte-identical pixels. **Dynamic packing and per-pipeline PSO linking (SHADER-378):** when a PS's canonical `28 − 2N`/`29 − 2N` slots collide with its raw attributes (266 corpus PS where f16-read attrs reach `n >= 7` and raw attrs reach 12–14, all with `2·\|F\| <= 29 − max`) or fall below 0, `assign_f16_half_locations` in `tools/rdna2spirv.py` packs all `f16_halves` pairs downward from location 29 into locations disjoint from its raw attributes (keeping the canonical slots byte-identical whenever collision-free, and refusing only genuine `> 30` location budget overflows); `tools/mesh_compute_vs.py` adds `pair_f16_halves` and an optional `f16_halves` override to `vs_spvasm`; and at graphics PSO creation `runtime/src/shader_library.h` loads `f16_halves` while `runtime/src/spirv_f16_halves.h` (called from `runtime/shims/d3d12_vulkan_device.cpp`) fast-paths exact matches, relocates PS/VS `Location` decorations when needed, demotes unneeded VS static half outputs to `Private`, and synthesizes `UnpackHalf2x16` half exports before `OpReturn` for params a high-param producer (`param0..15`) could not emit statically. Checked by `tests/semantic/test_f16_interp_fallback.py`, `tests/semantic/test_interp_p1lv_f16.py`, `tests/test_mesh_compute_vs.py`, `runtime/test/shader_library_test.cpp`, `runtime/test/spirv_f16_halves_test.cpp`, and `runtime/test/d3d12_f16_halves_test.cpp` (real Vulkan 1.3 draw on NVIDIA GeForce RTX 4060 Ti, driver 32.0.16.1088, Windows 11: 16-param VS + colliding PS both synthesized and relocated render exact RGBA `(64, 191, 127, 255)`). **Unverified:** a PS whose producer exports more params than leave room for the halves it reads (it reads that producer's param, not halves: the `f16_halves` entries then don't match); devices with fewer than 31 output locations; native MoltenVK validation run on macOS and full-corpus recount under `--f16-interp-fallback` (needs game copy); native `MeshEXT` runtime PSO specialization (mesh PSOs are not on `main` yet); devices with fewer than 124 vertex output components. Combined with `--bary-fallback`'s geometry shader (`tools/rdna2spirv.py` allocates `%bary` outside all occupied read and reserved f16-half slots; covered by `tests/semantic/test_bary_fallback.py`, and all `3/3` whole-corpus shaders combining both draw `11/11` targets bit-exact on an RX 6650 XT). |
485| `v_fmac_f16`, `v_interp_p2/mov_f32` output modifiers | VOP3 `mul:2`/`mul:4`/`div:2` (applied first) and `clamp` to [0, 1] apply to `v_fmac_f16_e64` (before narrowing to f16, matching `v_fma_f16`, high half preserved) and to `v_interp_p2_f32_e64` / `v_interp_mov_f32_e64` (no-op when no modifier is present). Until 2026-11-22 all three dropped output modifiers. Source: LLVM `llvm/test/MC/AMDGPU/gfx10_asm_vop2.s` (`v_fmac_f16_e64`) and `gfx10_asm_vop3.s` (`v_interp_p2_f32_e64`, `v_interp_mov_f32_e64`). Checked on the CPU by `tests/semantic/test_f16_fma_rounding.py` (`test_fmac_output_modifiers`) and `tests/semantic/test_interp_f32_mods.py`, and on a GPU by `ps_fmac_f16_mods.asm`, `ps_interp_f32_mods.asm` and `ps_interp_mov_mods.asm` (the last two drawn with `vs_interp_consts.asm`, whose params are constant over the triangle; each modifier and the omod-before-clamp order change a word; Tesla V100 (NVIDIA 580.95.05, Linux)). **The hardware ignores the f16 omod in the MODE the translator assumes:** on an RDNA2 iGPU (gfx1036) `mul:2`/`mul:4`/`div:2` change an f16 result (`v_fmac_f16`, `v_add/mul/fma_f16`, `v_cvt_f16_f32`, `v_exp/rcp_f16`) only with IEEE 0 and `denorm_mode_16_64 = 0`, and do nothing with f16 denormals kept; omod comes before clamp, and clamp gives +0 for -0 and, with DX10_CLAMP 1, for a NaN (SHADER-135, docs/shader_validation.md). The translator is not changed yet: which of omod and the kept f16 denormals is wrong for the game is a corpus question. | 486| `v_fmac_f16`, `v_interp_p2/mov_f32` output modifiers | VOP3 `mul:2`/`mul:4`/`div:2` (applied first) and `clamp` to [0, 1] apply to `v_fmac_f16_e64` (before narrowing to f16, matching `v_fma_f16`, high half preserved) and to `v_interp_p2_f32_e64` / `v_interp_mov_f32_e64` (no-op when no modifier is present). Until 2026-11-22 all three dropped output modifiers. Source: LLVM `llvm/test/MC/AMDGPU/gfx10_asm_vop2.s` (`v_fmac_f16_e64`) and `gfx10_asm_vop3.s` (`v_interp_p2_f32_e64`, `v_interp_mov_f32_e64`). Checked on the CPU by `tests/semantic/test_f16_fma_rounding.py` (`test_fmac_output_modifiers`) and `tests/semantic/test_interp_f32_mods.py`, and on a GPU by `ps_fmac_f16_mods.asm`, `ps_interp_f32_mods.asm` and `ps_interp_mov_mods.asm` (the last two drawn with `vs_interp_consts.asm`, whose params are constant over the triangle; each modifier and the omod-before-clamp order change a word; Tesla V100 (NVIDIA 580.95.05, Linux)). **The hardware ignores the f16 omod in the MODE the translator assumes:** on an RDNA2 iGPU (gfx1036) `mul:2`/`mul:4`/`div:2` change an f16 result (`v_fmac_f16`, `v_add/mul/fma_f16`, `v_cvt_f16_f32`, `v_exp/rcp_f16`) only with IEEE 0 and `denorm_mode_16_64 = 0`, and do nothing with f16 denormals kept; omod comes before clamp, and clamp gives +0 for -0 and, with DX10_CLAMP 1, for a NaN (SHADER-135, docs/shader_validation.md). The translator is not changed yet: which of omod and the kept f16 denormals is wrong for the game is a corpus question. |
486| `v_fmac_f16`, `v_interp_p2/mov_f32`, and f16 output modifiers | VOP3 `omod` (`[60:59]`) scales the floating-point result by `2`, `4`, or `0.5` before `clamp` (`[0.0, 1.0]`), gated by RDNA2 silicon on **both** `MODE.ieee == 0` and output denorms for the **destination precision** being flushed (`fp32_denorm` for `f32` destinations; `fp16_fp64_denorm` for `f16`/`f64` destinations). Under Leonida's default shader `MODE` (`IEEE=0`, FP32 denorms flushed, FP16/FP64 denorms kept `denorm16_64=3`), `Gen.clamp_mods(..., allow_omod=True)` applies `omod` then `clamp` on `f32` destinations (including `v_interp_p2_f32_e64`, `v_interp_mov_f32_e64`, and `v_cvt_f32_f16`), whereas `Gen.clamp_f16` (`allow_omod=False`) drops `omod` and keeps `clamp` on all `f16`-destination instructions (`v_add/sub/subrev/mul/min/max_f16`, `v_fma/fmac/min3/max3/med3_f16`, unary/transcendental/exponent `*_f16`, `v_cvt_f16_*`, `v_interp_p2_f16`, `v_fma_mixlo/hi_f16`). Hardware-verified on native RDNA2 (`gfx1036`, Windows 11, driver `32.0.21045.29003`, AMD clang `23.0.0git`, wave32 & wave64 parity, ELF binary disassembly confirming non-zero VOP3 `[60:59]` bits emitted, in-wave `v_add_f32_e64 mul:2` witness proving `IEEE=0` active -> `6.0` vs `IEEE=1` -> `3.0`): across all 4 `f16`-destination classes (binary ALU, 3-op ALU, unary/transcendental, and `v_cvt_f16_{f32,u16,i16}`), `mul:2`/`mul:4`/`div:2` are completely ignored under `IEEE=0, denorm16_64=3` while `clamp` still saturates `[0.0, 1.0]`, whereas the `f32`-destination control `v_cvt_f32_f16` scales (`2.0 -> 4.0 / 8.0 / 1.0`); flipping `MODE` to `IEEE=0, denorm16_64=0` (flushed FP16 denorms) re-enables `f16` `omod` scaling (`v_fma_f16 mul:2 -> 6.0`, `v_rcp_f16 mul:2 -> 1.0`, `v_cvt_f16_f32 mul:2 -> 4.0`), confirming the exact hardware gating condition. CPU-checked by `tests/semantic/test_f16_omod_rdna2.py`. **The gate is RDNA2 behaviour, not a general RDNA rule.** `tools/f64_omod_probe.py` (added by this PR) measures the same gate by destination precision on a gfx1036 iGPU (driver `31.0.24002.92`, raw ISA, 175 cases, `mismatches=0`, `wave_diffs=0`): `v_cvt_f64_i32`, `v_cvt_f64_u32`, `v_frexp_mant_f64`, `v_div_fixup_f64` and `v_div_fixup_f16` are f16/binary64 destinations and ignore `mul:2`/`mul:4`/`div:2` under `denorm16_64=3`, while `v_cvt_f32_f64` has binary64 sources and an f32 destination and scales under `denorm16_64=3` whenever `denorm32=0`. And @bunbeans2-arch reported in #4371 that RDNA4 `gfx1201` (RX 9070 XT, Windows driver 26.10.1, where IEEE is fixed on) applies the scaling for all 8 binary64 ops with `denorm16_64=3` kept, `v_add_f64 1.5+1.5 mul:2 = 0x4018000000000000`; that run is quoted from the thread and is not reproduced here. The two readings together are why the translator follows the console's RDNA2 MODEs rather than a hardware-agnostic rule, and why no row here should be read as describing RDNA3 or RDNA4. | 487| `v_fmac_f16`, `v_interp_p2/mov_f32`, and f16 output modifiers | VOP3 `omod` (`[60:59]`) scales the floating-point result by `2`, `4`, or `0.5` before `clamp` (`[0.0, 1.0]`), gated by RDNA2 silicon on **both** `MODE.ieee == 0` and output denorms for the **destination precision** being flushed (`fp32_denorm` for `f32` destinations; `fp16_fp64_denorm` for `f16`/`f64` destinations). Under Leonida's default shader `MODE` (`IEEE=0`, FP32 denorms flushed, FP16/FP64 denorms kept `denorm16_64=3`), `Gen.clamp_mods(..., allow_omod=True)` applies `omod` then `clamp` on `f32` destinations (including `v_interp_p2_f32_e64`, `v_interp_mov_f32_e64`, and `v_cvt_f32_f16`), whereas `Gen.clamp_f16` (`allow_omod=False`) drops `omod` and keeps `clamp` on all `f16`-destination instructions (`v_add/sub/subrev/mul/min/max_f16`, `v_fma/fmac/min3/max3/med3_f16`, unary/transcendental/exponent `*_f16`, `v_cvt_f16_*`, `v_interp_p2_f16`, `v_fma_mixlo/hi_f16`). Hardware-verified on native RDNA2 (`gfx1036`, Windows 11, driver `32.0.21045.29003`, AMD clang `23.0.0git`, wave32 & wave64 parity, ELF binary disassembly confirming non-zero VOP3 `[60:59]` bits emitted, in-wave `v_add_f32_e64 mul:2` witness proving `IEEE=0` active -> `6.0` vs `IEEE=1` -> `3.0`): across all 4 `f16`-destination classes (binary ALU, 3-op ALU, unary/transcendental, and `v_cvt_f16_{f32,u16,i16}`), `mul:2`/`mul:4`/`div:2` are completely ignored under `IEEE=0, denorm16_64=3` while `clamp` still saturates `[0.0, 1.0]`, whereas the `f32`-destination control `v_cvt_f32_f16` scales (`2.0 -> 4.0 / 8.0 / 1.0`); flipping `MODE` to `IEEE=0, denorm16_64=0` (flushed FP16 denorms) re-enables `f16` `omod` scaling (`v_fma_f16 mul:2 -> 6.0`, `v_rcp_f16 mul:2 -> 1.0`, `v_cvt_f16_f32 mul:2 -> 4.0`), confirming the exact hardware gating condition. CPU-checked by `tests/semantic/test_f16_omod_rdna2.py`. **The gate is RDNA2 behaviour, not a general RDNA rule.** `tools/f64_omod_probe.py` (added by this PR) measures the same gate by destination precision on a gfx1036 iGPU (driver `31.0.24002.92`, raw ISA, 175 cases, `mismatches=0`, `wave_diffs=0`): `v_cvt_f64_i32`, `v_cvt_f64_u32`, `v_frexp_mant_f64`, `v_div_fixup_f64` and `v_div_fixup_f16` are f16/binary64 destinations and ignore `mul:2`/`mul:4`/`div:2` under `denorm16_64=3`, while `v_cvt_f32_f64` has binary64 sources and an f32 destination and scales under `denorm16_64=3` whenever `denorm32=0`. And @bunbeans2-arch reported in #4371 that RDNA4 `gfx1201` (RX 9070 XT, Windows driver 26.10.1, where IEEE is fixed on) applies the scaling for all 8 binary64 ops with `denorm16_64=3` kept, `v_add_f64 1.5+1.5 mul:2 = 0x4018000000000000`; that run is quoted from the thread and is not reproduced here. The two readings together are why the translator follows the console's RDNA2 MODEs rather than a hardware-agnostic rule, and why no row here should be read as describing RDNA3 or RDNA4. |
487| `v_cvt_f16_f32` output modifiers | VOP3 `clamp` and `mul:2`/`mul:4`/`div:2` apply to the f16 result (Mesa ACO declares the op `dst(F16)`), in the order an RX 6800 (`gfx1030`) and Radeon Graphics (`gfx1036`) apply them: the value is rounded to f16 first, then scaled, then clamped, so in RNE `65520 div:2` is inf, not 32768. The scaling works on the f16 bits (`Gen.f16_omod`): a zero or denormal f16, before or after it, gives +0, inf and NaN pass through, and a finite overflow gives inf (±65504 under MODE toward zero, unmeasured). The scaling works on the f16 bits (`Gen.f16_omod`): a pre-omod zero or denormal f16 (`e == 0`) gives `+0`, `div:2` underflowing an exponent-1 normal (`e == 1`) gives signed zero (`h & 0x8000`, so negative inputs give `-0.0`, which a trailing `clamp` still turns into `+0`), `inf` and `NaN` pass through, and finite `mul:2`/`mul:4` overflow gives `±inf` in RNE or `±65504` under `MODE` toward zero (`FP_ROUND = 3`), where `±65520` / `±FLT_MAX` with `div:2` also round to `±65504` before halving to `±32752`. Until 2026-11-22 both modifiers were dropped; `Gen.f16_omod` also flushed `e == 1 div:2` to `+0` until the `gfx1036` measurement. Sources: [@shelbykb2's RX 6800 words](https://github.com/ItsNotRexed/Leonida/pull/718#issuecomment-7074230544) (gfx1030, not the console's gfx1013): [@shelbykb2's RX 6800 words](https://github.com/ItsNotRexed/Leonida/pull/718#issuecomment-7074230544) (gfx1030, not the console's gfx1013) and `tools/cvt_f16_omod_probe.py` on `gfx1036` (Radeon(TM) Graphics, Windows 11 driver `32.0.21045.29003`, wave32 & wave64, 2,880 evaluations, 0 diffs across static/dynamic `MODE`): `clamp` applies in every float mode, the omod only with IEEE off and f16 denormals flushed (with `denorm16_64=3` or `ieee=1` omod is ignored while `clamp` still applies), which is the mode a compiler emits an omod for, as the f32 rows above argue; 2^-15 `mul:2` and -0 `mul:2` gave 0x0000 there. That flush is modelled only on results that carry an omod. The f16 ALU results (`v_fma_f16`, `v_fmac_f16`, …) still scale before narrowing, which differs from this only on overflow, denormals and the sign of zero. Checked by `ps_outmods_f16.asm` (`tests/semantic/test_value_semantics.py`, and on a GPU in both runners): each of its six results changes a word when its modifier is dropped, and two words change when the omod is applied before the rounding. Checked by `ps_outmods_f16.asm` (`tests/semantic/test_value_semantics.py`, and on a GPU in both runners), `tests/test_cvt_f16_omod_probe.py`, and `tests/semantic/test_cvt_f16_omod.py`. | 488| `v_cvt_f16_f32` output modifiers | VOP3 `clamp` and `mul:2`/`mul:4`/`div:2` apply to the f16 result (Mesa ACO declares the op `dst(F16)`), in the order an RX 6800 (`gfx1030`) and Radeon Graphics (`gfx1036`) apply them: the value is rounded to f16 first, then scaled, then clamped, so in RNE `65520 div:2` is inf, not 32768. The scaling works on the f16 bits (`Gen.f16_omod`): a zero or denormal f16, before or after it, gives +0, inf and NaN pass through, and a finite overflow gives inf (±65504 under MODE toward zero, unmeasured). The scaling works on the f16 bits (`Gen.f16_omod`): a pre-omod zero or denormal f16 (`e == 0`) gives `+0`, `div:2` underflowing an exponent-1 normal (`e == 1`) gives signed zero (`h & 0x8000`, so negative inputs give `-0.0`, which a trailing `clamp` still turns into `+0`), `inf` and `NaN` pass through, and finite `mul:2`/`mul:4` overflow gives `±inf` in RNE or `±65504` under `MODE` toward zero (`FP_ROUND = 3`), where `±65520` / `±FLT_MAX` with `div:2` also round to `±65504` before halving to `±32752`. Until 2026-11-22 both modifiers were dropped; `Gen.f16_omod` also flushed `e == 1 div:2` to `+0` until the `gfx1036` measurement. Sources: [@shelbykb2's RX 6800 words](https://github.com/ItsNotRexed/Leonida/pull/718#issuecomment-7074230544) (gfx1030, not the console's gfx1013): [@shelbykb2's RX 6800 words](https://github.com/ItsNotRexed/Leonida/pull/718#issuecomment-7074230544) (gfx1030, not the console's gfx1013) and `tools/cvt_f16_omod_probe.py` on `gfx1036` (Radeon(TM) Graphics, Windows 11 driver `32.0.21045.29003`, wave32 & wave64, 2,880 evaluations, 0 diffs across static/dynamic `MODE`): `clamp` applies in every float mode, the omod only with IEEE off and f16 denormals flushed (with `denorm16_64=3` or `ieee=1` omod is ignored while `clamp` still applies), which is the mode a compiler emits an omod for, as the f32 rows above argue; 2^-15 `mul:2` and -0 `mul:2` gave 0x0000 there. That flush is modelled only on results that carry an omod. The f16 ALU results (`v_fma_f16`, `v_fmac_f16`, …) still scale before narrowing, which differs from this only on overflow, denormals and the sign of zero. Checked by `ps_outmods_f16.asm` (`tests/semantic/test_value_semantics.py`, and on a GPU in both runners): each of its six results changes a word when its modifier is dropped, and two words change when the omod is applied before the rounding. Checked by `ps_outmods_f16.asm` (`tests/semantic/test_value_semantics.py`, and on a GPU in both runners), `tests/test_cvt_f16_omod_probe.py`, and `tests/semantic/test_cvt_f16_omod.py`. |
@@ -502,7 +503,7 @@ How the generated SPIR-V expects the runtime to work:
502| Swizzled buffer addressing (V# SWIZZLE_ENABLE, ADD_TID_ENABLE) | MUBUF/MTBUF `buffer_load*`, `buffer_store*`, `buffer_atomic*`, `buffer_load_format_*`/`buffer_store_format_*` and `tbuffer_load/store_format_*` follow the rules measured natively on RDNA2 (`AMD Radeon(TM) Graphics`, gfx1036, Windows driver `32.0.21042.62`, wave32 and wave64; `tools/buffer_swizzle_probe.py`, SHADER-343). MUBUF/MTBUF `buffer_load*`, `buffer_store*`, `buffer_atomic*`, `buffer_load_format_*`/`buffer_store_format_*` and `tbuffer_load_format_*` follow the RDNA2 ISA ("RDNA 2" Instruction Set Architecture, 8.1.5 Buffer Addressing, "Swizzled Buffer Addressing" and tables 33, 35 and 37). Fields, Mesa 24.0.6 `src/amd/registers/gfx10-rsrc.json` (`SQ_BUF_RSRC_WORD1`, `SQ_BUF_RSRC_WORD3` and its `_gfx103` twin, the same bits): `SWIZZLE_ENABLE` word1 bit 31, `STRIDE` word1 `[29:16]`, `INDEX_STRIDE` word3 `[22:21]` (`IS = 8 << n`, i.e., 8, 16, 32 or 64), `ADD_TID_ENABLE` word3 bit 23; element size is fixed at 4 bytes (`word3[20:19]` and `word1[30]` do not alter addressing or stepping). **Effective index:** `index = idxen ? vindex : 0)`, where `lane` is the wave lane (`thread_id[5:0]` within the wave, wrapping at 32 in wave32 and 64 in wave64; `Gen.wave_lane`); **`idxen = 1` completely ignores `ADD_TID_ENABLE`** (linear or swizzled, address and bounds, loads/stores/typed/atomics). **Activation:** `SWIZZLE_ENABLE` activates (`swz_active`) only when `idxen = 1` or `ADD_TID_ENABLE = 1`; with neither, addressing is linear (`base + soffset + off`) and `OOB_SELECT 3` stays RAW even when `stride ≠ 0`. **Address formula (when `swz_active`):** `off = uint32((offen ? vaddr : 0) + inst_offset)` (32-bit wrap), `buffer_offset = (index / IS · stride + (off & ~3)) · IS + (index % IS) · 4 + (off & 3)`, `address = base + soffset + buffer_offset` (confirmed byte-exact for IS 8/16/32/64, non-4-multiple strides, stride 0, and unaligned offsets). **Two swizzle sub-modes:** (1) **Scratch swizzle** (`SWIZZLE_ENABLE = 1`, `idxen = 0`, `ADD_TID_ENABLE = 1`): raw multi-dword `buffer_load/store_dwordx2..x4` step by **`+4 · IS`** bytes per dword (and unaligned 4-byte raw accesses crossing a dword boundary split across `+4 · IS` on hardware), while **typed formats > 4 bytes** (8/12/16-byte MUBUF and MTBUF loads/stores, regardless of component count) and **8-byte `buffer_atomic_*_x2`** are **suppressed** (loads return 0, stores/atomics are no-ops, even in `OOB_SELECT 2`); typed formats ≤ 4 bytes work normally. (2) **Indexed swizzle** (`SWIZZLE_ENABLE = 1`, `idxen = 1`, regardless of `ADD_TID_ENABLE`): raw `x2..x4`, typed formats (8/12/16 bytes), and `buffer_atomic_*_x2` step **linearly by `+4` bytes** from the swizzled base address, even across `IS` boundaries, and typed formats > 4 bytes execute normally. **Bounds (`OOB_SELECT`):** modes 0, 1 and 2 follow the Buffer bounds checking row with `idx = index`; **`OOB_SELECT 3` with `swz_active` and `stride ≠ 0`** checks **`uint64(index) + uint64(soffset) >= num_records` or `off + payload > stride`** (per-dword for raw `x1..x4`, whole element for typed), while inactive swizzle or `stride = 0` keeps the RAW check `uint64(off) + uint64(soffset) + payload > num_records` (no 32-bit wrap on `off + soffset`, whereas `vaddr + inst_offset` wraps at 32 bits before bounds checking). A literal word1 / word3 (`s_mov_b32` earlier in the block) folds each bit; a run-time V# selects dynamically with `L = swz_u · (3 + INDEX_STRIDE)` (IS = 1 gives the linear address). Until 2026-11-22 the translator added `vindex + lane` when `idxen = 1` and `ADD_TID_ENABLE = 1`, swizzled even when both were 0, stepped all swizzled multi-dword/typed accesses by `4 · IS`, allowed > 4-byte typed/atomic_x2 accesses in scratch-swizzle mode, omitted `soffset` from swizzled mode 3's index check, and wrapped `off + soffset` at 32 bits in RAW mode 3. **How confirmed:** native RDNA2 measurement on `AMD Radeon(TM) Graphics` (gfx1036, Windows driver `32.0.21042.62`, wave32 & wave64) via `tools/buffer_swizzle_probe.py --oracle both` (22/22 cases across 8 groups match bit-exactly, 0 unexpected mismatches, 0 unexpected wave32/64 diffs, 64-thread `ADD_TID_ENABLE` wave-lane wrap verified at both wave sizes); CPU semantic tests `tests/semantic/test_buffer_swizzle.py` (literal and run-time V#, both sub-modes, mode 3 `soffset`, 32-bit wrap, typed/`atomic_x2` suppression, and `cs_buf_swizzle.asm`); `tests/test_buffer_swizzle_probe.py`. **Remaining approximations / unmeasured:** unaligned raw accesses splitting across `+4 · IS` in scratch-swizzle mode (the translator uses `Aligned 4` PSB loads/stores), general typed-format / `buffer_atomic_*_x2` natural alignment suppression (`16_UINT` at odd offsets, `32_*` at non-4B offsets, `atomic_*_x2` at non-8B addresses, observed on gfx1036 in both linear and swizzled modes), and GFX11's two-bit `SWIZZLE_ENABLE` (`word1[31:30]`). SWIZZLE_ENABLE word1 bit 31, STRIDE word1 [29:16], INDEX_STRIDE word3 [22:21] (IS = 8, 16, 32 or 64 indices), ADD_TID_ENABLE word3 bit 23; there is no ELEMENT_SIZE field, the element is fixed at 4 bytes (ISA 8.1.5; LLVM `SIInstrInfo::getScratchRsrcWords23` sets it only up to GFX8). `index` = (idxen ? vindex : 0) + (ADD_TID_ENABLE ? lane : 0), where the lane is thread_id[5:0] within the wave (`Gen.wave_lane`), swizzled or not: table 33 adds the thread id with no swizzle condition and table 36's ring column is linear with add_tid. `offset` = (offen ? vaddr : 0) + inst_offset, without soffset. Swizzled: buffer_offset = (index / IS · stride + offset / 4 · 4) · IS + index % IS · 4 + offset % 4, address = base + soffset + buffer_offset, so dword k of a multi-dword access (and of a typed element over 4 bytes) is 4 · IS bytes after dword k − 1, not 4. Bounds as in Buffer bounds checking, with `idx` = `index` (the lane included), except that OOB_SELECT 3 with SWIZZLE_ENABLE and stride ≠ 0 checks `index >= num_records` or `off + 4k + 4 > stride` (table 35), like mode 0; stride 0 keeps the raw check. A literal word1 / word3 (`s_mov_b32` earlier in the block) folds each bit. A run-time word1 makes IS = 2^(SWIZZLE_ENABLE · (3 + INDEX_STRIDE)): IS = 1 is the linear address, so one formula serves both and nothing is selected but the mode 3 check; a run-time word3 multiplies the lane by ADD_TID_ENABLE. Cost, measured on the 116 shaders of `runtime/test/shaders` that both versions translate (all `spirv-val` clean before and after): the 56 with a MUBUF access through a run-time V# grow by 15.1 % in SPIR-V lines (+10.4 % over all 116), 30 to 45 instructions per access (address, lane, 4 per extra dword, a select per dword of the bounds check); a literal linear V# gives the same SPIR-V as before. Outside compute and mesh shaders the lane is `SubgroupLocalInvocationId`, so a VS, PS or GS with a run-time V# now declares `GroupNonUniform`. The offset arithmetic is 32-bit, like the linear address. Until 2026-11-22 a literal V# with either bit was `Unsupported` and a run-time one was translated unswizzled. **How confirmed**: Mesa/LLVM and AMD's ISA reference (fields and formula), not measured on hardware; `tests/semantic/test_buffer_swizzle.py` (hand-worked addresses for IS 8/16/64, index msb/lsb, soffset after the swizzle, the mode 3 rule with and without a stride, per-dword x2/x3/x4 loads and stores, a 16-byte typed element, ADD_TID on lane 5 linear and swizzled, each with a literal and a run-time V#); GPU test `runtime/test/shaders/cs_buf_swizzle.asm` (check.py, `scripts/run_gpu_tests.py`), which checks the translation, not RDNA2. **Unmeasured**: the swizzled layout on RDNA2 hardware, offsets that are not dword aligned (the ISA requires alignment for swizzled accesses; the translation adds offset % 4), wrap of the 32-bit offset, and GFX11's two-bit SWIZZLE_ENABLE (word1 [31:30]). **Unmeasured** (the layout itself is measured: `docs/shader_validation.md`, SHADER-343, gfx1036, 22 of 22 cases bit-exact): offsets that are not dword aligned (the ISA requires alignment for swizzled accesses; the translation adds offset % 4), wrap of the 32-bit offset, and GFX11's two-bit SWIZZLE_ENABLE (word1 [31:30]). In the corpus `SCRATCH_EN` is 0 in every CS, so a swizzled V# can only come from a descriptor the game writes itself. | 503| Swizzled buffer addressing (V# SWIZZLE_ENABLE, ADD_TID_ENABLE) | MUBUF/MTBUF `buffer_load*`, `buffer_store*`, `buffer_atomic*`, `buffer_load_format_*`/`buffer_store_format_*` and `tbuffer_load/store_format_*` follow the rules measured natively on RDNA2 (`AMD Radeon(TM) Graphics`, gfx1036, Windows driver `32.0.21042.62`, wave32 and wave64; `tools/buffer_swizzle_probe.py`, SHADER-343). MUBUF/MTBUF `buffer_load*`, `buffer_store*`, `buffer_atomic*`, `buffer_load_format_*`/`buffer_store_format_*` and `tbuffer_load_format_*` follow the RDNA2 ISA ("RDNA 2" Instruction Set Architecture, 8.1.5 Buffer Addressing, "Swizzled Buffer Addressing" and tables 33, 35 and 37). Fields, Mesa 24.0.6 `src/amd/registers/gfx10-rsrc.json` (`SQ_BUF_RSRC_WORD1`, `SQ_BUF_RSRC_WORD3` and its `_gfx103` twin, the same bits): `SWIZZLE_ENABLE` word1 bit 31, `STRIDE` word1 `[29:16]`, `INDEX_STRIDE` word3 `[22:21]` (`IS = 8 << n`, i.e., 8, 16, 32 or 64), `ADD_TID_ENABLE` word3 bit 23; element size is fixed at 4 bytes (`word3[20:19]` and `word1[30]` do not alter addressing or stepping). **Effective index:** `index = idxen ? vindex : 0)`, where `lane` is the wave lane (`thread_id[5:0]` within the wave, wrapping at 32 in wave32 and 64 in wave64; `Gen.wave_lane`); **`idxen = 1` completely ignores `ADD_TID_ENABLE`** (linear or swizzled, address and bounds, loads/stores/typed/atomics). **Activation:** `SWIZZLE_ENABLE` activates (`swz_active`) only when `idxen = 1` or `ADD_TID_ENABLE = 1`; with neither, addressing is linear (`base + soffset + off`) and `OOB_SELECT 3` stays RAW even when `stride ≠ 0`. **Address formula (when `swz_active`):** `off = uint32((offen ? vaddr : 0) + inst_offset)` (32-bit wrap), `buffer_offset = (index / IS · stride + (off & ~3)) · IS + (index % IS) · 4 + (off & 3)`, `address = base + soffset + buffer_offset` (confirmed byte-exact for IS 8/16/32/64, non-4-multiple strides, stride 0, and unaligned offsets). **Two swizzle sub-modes:** (1) **Scratch swizzle** (`SWIZZLE_ENABLE = 1`, `idxen = 0`, `ADD_TID_ENABLE = 1`): raw multi-dword `buffer_load/store_dwordx2..x4` step by **`+4 · IS`** bytes per dword (and unaligned 4-byte raw accesses crossing a dword boundary split across `+4 · IS` on hardware), while **typed formats > 4 bytes** (8/12/16-byte MUBUF and MTBUF loads/stores, regardless of component count) and **8-byte `buffer_atomic_*_x2`** are **suppressed** (loads return 0, stores/atomics are no-ops, even in `OOB_SELECT 2`); typed formats ≤ 4 bytes work normally. (2) **Indexed swizzle** (`SWIZZLE_ENABLE = 1`, `idxen = 1`, regardless of `ADD_TID_ENABLE`): raw `x2..x4`, typed formats (8/12/16 bytes), and `buffer_atomic_*_x2` step **linearly by `+4` bytes** from the swizzled base address, even across `IS` boundaries, and typed formats > 4 bytes execute normally. **Bounds (`OOB_SELECT`):** modes 0, 1 and 2 follow the Buffer bounds checking row with `idx = index`; **`OOB_SELECT 3` with `swz_active` and `stride ≠ 0`** checks **`uint64(index) + uint64(soffset) >= num_records` or `off + payload > stride`** (per-dword for raw `x1..x4`, whole element for typed), while inactive swizzle or `stride = 0` keeps the RAW check `uint64(off) + uint64(soffset) + payload > num_records` (no 32-bit wrap on `off + soffset`, whereas `vaddr + inst_offset` wraps at 32 bits before bounds checking). A literal word1 / word3 (`s_mov_b32` earlier in the block) folds each bit; a run-time V# selects dynamically with `L = swz_u · (3 + INDEX_STRIDE)` (IS = 1 gives the linear address). Until 2026-11-22 the translator added `vindex + lane` when `idxen = 1` and `ADD_TID_ENABLE = 1`, swizzled even when both were 0, stepped all swizzled multi-dword/typed accesses by `4 · IS`, allowed > 4-byte typed/atomic_x2 accesses in scratch-swizzle mode, omitted `soffset` from swizzled mode 3's index check, and wrapped `off + soffset` at 32 bits in RAW mode 3. **How confirmed:** native RDNA2 measurement on `AMD Radeon(TM) Graphics` (gfx1036, Windows driver `32.0.21042.62`, wave32 & wave64) via `tools/buffer_swizzle_probe.py --oracle both` (22/22 cases across 8 groups match bit-exactly, 0 unexpected mismatches, 0 unexpected wave32/64 diffs, 64-thread `ADD_TID_ENABLE` wave-lane wrap verified at both wave sizes); CPU semantic tests `tests/semantic/test_buffer_swizzle.py` (literal and run-time V#, both sub-modes, mode 3 `soffset`, 32-bit wrap, typed/`atomic_x2` suppression, and `cs_buf_swizzle.asm`); `tests/test_buffer_swizzle_probe.py`. **Remaining approximations / unmeasured:** unaligned raw accesses splitting across `+4 · IS` in scratch-swizzle mode (the translator uses `Aligned 4` PSB loads/stores), general typed-format / `buffer_atomic_*_x2` natural alignment suppression (`16_UINT` at odd offsets, `32_*` at non-4B offsets, `atomic_*_x2` at non-8B addresses, observed on gfx1036 in both linear and swizzled modes), and GFX11's two-bit `SWIZZLE_ENABLE` (`word1[31:30]`). SWIZZLE_ENABLE word1 bit 31, STRIDE word1 [29:16], INDEX_STRIDE word3 [22:21] (IS = 8, 16, 32 or 64 indices), ADD_TID_ENABLE word3 bit 23; there is no ELEMENT_SIZE field, the element is fixed at 4 bytes (ISA 8.1.5; LLVM `SIInstrInfo::getScratchRsrcWords23` sets it only up to GFX8). `index` = (idxen ? vindex : 0) + (ADD_TID_ENABLE ? lane : 0), where the lane is thread_id[5:0] within the wave (`Gen.wave_lane`), swizzled or not: table 33 adds the thread id with no swizzle condition and table 36's ring column is linear with add_tid. `offset` = (offen ? vaddr : 0) + inst_offset, without soffset. Swizzled: buffer_offset = (index / IS · stride + offset / 4 · 4) · IS + index % IS · 4 + offset % 4, address = base + soffset + buffer_offset, so dword k of a multi-dword access (and of a typed element over 4 bytes) is 4 · IS bytes after dword k − 1, not 4. Bounds as in Buffer bounds checking, with `idx` = `index` (the lane included), except that OOB_SELECT 3 with SWIZZLE_ENABLE and stride ≠ 0 checks `index >= num_records` or `off + 4k + 4 > stride` (table 35), like mode 0; stride 0 keeps the raw check. A literal word1 / word3 (`s_mov_b32` earlier in the block) folds each bit. A run-time word1 makes IS = 2^(SWIZZLE_ENABLE · (3 + INDEX_STRIDE)): IS = 1 is the linear address, so one formula serves both and nothing is selected but the mode 3 check; a run-time word3 multiplies the lane by ADD_TID_ENABLE. Cost, measured on the 116 shaders of `runtime/test/shaders` that both versions translate (all `spirv-val` clean before and after): the 56 with a MUBUF access through a run-time V# grow by 15.1 % in SPIR-V lines (+10.4 % over all 116), 30 to 45 instructions per access (address, lane, 4 per extra dword, a select per dword of the bounds check); a literal linear V# gives the same SPIR-V as before. Outside compute and mesh shaders the lane is `SubgroupLocalInvocationId`, so a VS, PS or GS with a run-time V# now declares `GroupNonUniform`. The offset arithmetic is 32-bit, like the linear address. Until 2026-11-22 a literal V# with either bit was `Unsupported` and a run-time one was translated unswizzled. **How confirmed**: Mesa/LLVM and AMD's ISA reference (fields and formula), not measured on hardware; `tests/semantic/test_buffer_swizzle.py` (hand-worked addresses for IS 8/16/64, index msb/lsb, soffset after the swizzle, the mode 3 rule with and without a stride, per-dword x2/x3/x4 loads and stores, a 16-byte typed element, ADD_TID on lane 5 linear and swizzled, each with a literal and a run-time V#); GPU test `runtime/test/shaders/cs_buf_swizzle.asm` (check.py, `scripts/run_gpu_tests.py`), which checks the translation, not RDNA2. **Unmeasured**: the swizzled layout on RDNA2 hardware, offsets that are not dword aligned (the ISA requires alignment for swizzled accesses; the translation adds offset % 4), wrap of the 32-bit offset, and GFX11's two-bit SWIZZLE_ENABLE (word1 [31:30]). **Unmeasured** (the layout itself is measured: `docs/shader_validation.md`, SHADER-343, gfx1036, 22 of 22 cases bit-exact): offsets that are not dword aligned (the ISA requires alignment for swizzled accesses; the translation adds offset % 4), wrap of the 32-bit offset, and GFX11's two-bit SWIZZLE_ENABLE (word1 [31:30]). In the corpus `SCRATCH_EN` is 0 in every CS, so a swizzled V# can only come from a descriptor the game writes itself. |
503| `v_permlane16_b32` / `v_permlanex16_b32` with the source lane off in EXEC (SHADER-74) | The VOP3 modifier `op_sel:[FI, BOUND_CTRL]` decides what a lane gets when the lane it reads is off in EXEC. **FI=1** (`op_sel` bit 0, encoding 0x0800): the source lane's value, as before. **FI=0** (the default): the destination lane is not written and keeps its old value when BOUND_CTRL=0, and gets 0 when BOUND_CTRL=1 (`op_sel` bit 1, 0x1000). A source lane that is on gives its value whatever FI / BOUND_CTRL are, and a lane that is itself off is never written (normal EXEC rule). The translator shuffles the active bit with the same selector as the value (also in `--wave64-emulate`, where it is a second exchange). On a native subgroup the two shuffles are combined with bitwise masks, not a scalar select: absent source lanes are redirected to the calling lane first (as `ds_lane_read`), the value and the activity bit are fetched through the redirected index, and `ok` masks the shuffled value over the old one (over zero with BOUND_CTRL=1) and the destination write is masked too, so the ballot and both shuffles run before lane predication — MoltenVK 1.4.2 and MoltenVK main at SPIRV-Cross aa217aeb lowered the scalar select to a short-circuiting Metal ternary and the FI=0 lanes read the source lane's value instead, which `cs_w32_permlane_fi` caught on an Apple M1 Max (#5895); `v_permlanex16_b32` pairs the rows 0↔1 and 2↔3 of a wave64 as before. Until SHADER-74 every case returned the source value (right only for FI=1). Source of the bit mapping: LLVM `llvm.amdgcn.permlane16/permlanex16 <old> <src0> <src1> <src2> <fi> <bound_control>` (IntrinsicsAMDGPU.td) is selected in `VOP3Instructions.td` (`PermlanePat`) with `fi` as the `src0` op_sel bit and `bound_control` as the `src1` one, and the CodeGen tests `llvm.amdgcn.permlane.ll` print `op_sel:[1,0]` for FI and `op_sel:[0,1]` for BOUND_CTRL; `llvm-mc -mcpu=gfx1013` encodes `op_sel:[1,0]` as 0x0800 and `op_sel:[0,1]` as 0x1000 in the second byte pair of the first word (0xD777 / 0xD778). Behaviour: hardware measurement on RDNA2 (Ryzen 7950X3D iGPU, raw kernel, wave64 and wave32 consistent; the same on RDNA3.5) by aslan2142 in [#374](https://github.com/ItsNotRexed/Leonida/issues/374#issuecomment-7071597516). Pinned by `runtime/test/shaders/cs_w32_permlane_fi.asm` (EXEC 0x55555555, every active lane's source is off; out[0..7] = 1000 0 4 1 1000 0 52 49) in `check.py` and `scripts/run_gpu_tests.py`, and on the CPU by `tests/semantic/test_permlane_fi.py`. | 504| `v_permlane16_b32` / `v_permlanex16_b32` with the source lane off in EXEC (SHADER-74) | The VOP3 modifier `op_sel:[FI, BOUND_CTRL]` decides what a lane gets when the lane it reads is off in EXEC. **FI=1** (`op_sel` bit 0, encoding 0x0800): the source lane's value, as before. **FI=0** (the default): the destination lane is not written and keeps its old value when BOUND_CTRL=0, and gets 0 when BOUND_CTRL=1 (`op_sel` bit 1, 0x1000). A source lane that is on gives its value whatever FI / BOUND_CTRL are, and a lane that is itself off is never written (normal EXEC rule). The translator shuffles the active bit with the same selector as the value (also in `--wave64-emulate`, where it is a second exchange). On a native subgroup the two shuffles are combined with bitwise masks, not a scalar select: absent source lanes are redirected to the calling lane first (as `ds_lane_read`), the value and the activity bit are fetched through the redirected index, and `ok` masks the shuffled value over the old one (over zero with BOUND_CTRL=1) and the destination write is masked too, so the ballot and both shuffles run before lane predication — MoltenVK 1.4.2 and MoltenVK main at SPIRV-Cross aa217aeb lowered the scalar select to a short-circuiting Metal ternary and the FI=0 lanes read the source lane's value instead, which `cs_w32_permlane_fi` caught on an Apple M1 Max (#5895); `v_permlanex16_b32` pairs the rows 0↔1 and 2↔3 of a wave64 as before. Until SHADER-74 every case returned the source value (right only for FI=1). Source of the bit mapping: LLVM `llvm.amdgcn.permlane16/permlanex16 <old> <src0> <src1> <src2> <fi> <bound_control>` (IntrinsicsAMDGPU.td) is selected in `VOP3Instructions.td` (`PermlanePat`) with `fi` as the `src0` op_sel bit and `bound_control` as the `src1` one, and the CodeGen tests `llvm.amdgcn.permlane.ll` print `op_sel:[1,0]` for FI and `op_sel:[0,1]` for BOUND_CTRL; `llvm-mc -mcpu=gfx1013` encodes `op_sel:[1,0]` as 0x0800 and `op_sel:[0,1]` as 0x1000 in the second byte pair of the first word (0xD777 / 0xD778). Behaviour: hardware measurement on RDNA2 (Ryzen 7950X3D iGPU, raw kernel, wave64 and wave32 consistent; the same on RDNA3.5) by aslan2142 in [#374](https://github.com/ItsNotRexed/Leonida/issues/374#issuecomment-7071597516). Pinned by `runtime/test/shaders/cs_w32_permlane_fi.asm` (EXEC 0x55555555, every active lane's source is off; out[0..7] = 1000 0 4 1 1000 0 52 49) in `check.py` and `scripts/run_gpu_tests.py`, and on the CPU by `tests/semantic/test_permlane_fi.py`. |
504| Null mask source | The scalar register `null` supplies zero when read as a lane mask. The wave64 fixture in `tests/semantic/fixtures/null_mask_source.asm` checks a high-bit test, a zero-bit count, a first-set-bit search and a masked vector write after `s_and_saveexec_b64`. LLVM 21.1.8 assembles each instruction for gfx1030. [LLVM GFX10 null operand](https://releases.llvm.org/15.0.0/docs/AMDGPUOperandSyntax.html#null) | 505| Null mask source | The scalar register `null` supplies zero when read as a lane mask. The wave64 fixture in `tests/semantic/fixtures/null_mask_source.asm` checks a high-bit test, a zero-bit count, a first-set-bit search and a masked vector write after `s_and_saveexec_b64`. LLVM 21.1.8 assembles each instruction for gfx1030. [LLVM GFX10 null operand](https://releases.llvm.org/15.0.0/docs/AMDGPUOperandSyntax.html#null) |
505| Wave64 mask ballot | `tools/lane_masks.py` tracks per-lane masks (including 32-bit `MASK_LO`/`MASK_HI` halves, `vcc_lo`/`vcc_hi`, `s_bfm_b64` bitfields, `_b64` copies of immediates into `vcc`, and `_b64` bitwise/select ops combining a lane mask or `vcc` destination with immediates; 32-bit mask + non-0/-1 immediate into an SGPR stays plain data, #1792). Split wave64 SGPR pairs whose two dwords hold separately written half-masks or a half-mask paired with a 0/-1 `EITHER` constant (`include_either=True`) are recognized by `holds_lane_mask` and read `s[r]` for lanes 0–31 and `s[r+1]` for lanes 32–63 in `mask_src`, and `--wave64-emulate`'s `x_mcache` keys `wave_mask` on every dword of an SGPR operand so rewriting `s[r+1]` invalidates a cached 64-bit exchange. `s_bcnt1_i32_b64`/`b32`, `s_bcnt0_i32_b64`/`b32`, `s_ff1_i32_b64`/`b32`, `s_ff0_i32_b64`/`b32`, `s_bitcmp0/1_b32/b64`, and `v_mbcnt_lo/hi_u32_b32` reconstruct the 64-bit wave mask via `OpGroupNonUniformBitwiseOr` (`GroupNonUniformArithmetic`), restricting 32-bit half ops (including `v_mbcnt_lo/hi_u32_b32` on `vcc_hi`/`vcc_lo`/`exec_lo` via `mask_half`) and `s_cmp_eq/lg_u32` (`wave_equal`) to the known 32-bit half in wave64. `tools/lane_masks.py` tracks per-lane masks (including 32-bit `MASK_LO`/`MASK_HI` halves, `vcc_lo`/`vcc_hi`, and `s_bfm_b64` bitfields). `s_bcnt1_i32_b64`/`b32`, `s_bcnt0_i32_b64`/`b32`, `s_ff1_i32_b64`/`b32`, `s_ff0_i32_b64`/`b32`, and `s_bitcmp0/1_b32/b64` reconstruct the 64-bit wave mask via `OpGroupNonUniformBitwiseOr` (`GroupNonUniformArithmetic`), restricting 32-bit half ops and `s_cmp_eq/lg_u32` (`wave_equal`) to the known 32-bit half in wave64. Opposite-half `s_cmp_*_u32/i32` comparisons (lo vs hi), ordering comparisons on mask halves, and `s_cmp_*_u32/i32/u64` comparing a lane mask against an arbitrary scalar or immediate reconstruct the exact 32/64-bit mask words via `wave_mask`. A compare with 0 keeps the vote, but a compare with -1 (all ones) does not: lanes that were never launched (a group smaller than the wave) don't vote, while their bits are 0 in the real mask, so until 2026-11-22 `s_cmp_eq_u32 vcc_hi, -1` read 1 in a 40-thread wave64 for `vcc_hi` = 0xff. GPU-checked with `cs_w64x_partial_scmp.asm` (40-thread wave64, native and `--wave64-emulate`) and `cs_w32_partial_scmp.asm` (20-thread wave32) on an AMD Radeon RX 7800 XT (RADV, Mesa 26.2.6): all 8 words as the headers derive, and 4 of 8 wrong in each with the old translator. GPU-checked with `runtime/test/shaders/cs_wave64_ballot.asm` and `cs_wm_*.asm` on AMD Radeon RX 9070 XT (64-wide subgroup); semantic test coverage in `tests/semantic/test_scalar_bitcmp.py`, `tests/semantic/test_scalar_alu_shifts.py`, `tests/semantic/test_loop_ballot_barrier.py`, and `tests/test_lane_masks.py` (split SGPR pairs, dual-dword `x_mcache`, `_b64` mask+imm, and `v_mbcnt` half selection CPU-checked, not yet GPU-verified). GPU-checked with `runtime/test/shaders/cs_wave64_ballot.asm` and `cs_wm_*.asm` on AMD Radeon RX 9070 XT (64-wide subgroup); semantic test coverage in `tests/semantic/test_scalar_bitcmp.py` and `tests/semantic/test_scalar_alu_shifts.py`. | 506| Wave64 mask ballot | `tools/lane_masks.py` tracks per-lane masks (including 32-bit `MASK_LO`/`MASK_HI` halves, `vcc_lo`/`vcc_hi`, `s_bfm_b64` bitfields, `_b64` copies of immediates into `vcc`, and `_b64` bitwise/select ops combining a lane mask or `vcc` destination with immediates; 32-bit mask + non-0/-1 immediate into an SGPR stays plain data, #1792). Split wave64 SGPR pairs whose two dwords hold separately written half-masks or a half-mask paired with a 0/-1 `EITHER` constant (`include_either=True`) are recognized by `holds_lane_mask` and read `s[r]` for lanes 0–31 and `s[r+1]` for lanes 32–63 in `mask_src`, and `--wave64-emulate`'s `x_mcache` keys `wave_mask` on every dword of an SGPR operand so rewriting `s[r+1]` invalidates a cached 64-bit exchange. `s_bcnt1_i32_b64`/`b32`, `s_bcnt0_i32_b64`/`b32`, `s_ff1_i32_b64`/`b32`, `s_ff0_i32_b64`/`b32`, `s_bitcmp0/1_b32/b64`, and `v_mbcnt_lo/hi_u32_b32` reconstruct the 64-bit wave mask via `OpGroupNonUniformBitwiseOr` (`GroupNonUniformArithmetic`), restricting 32-bit half ops (including `v_mbcnt_lo/hi_u32_b32` on `vcc_hi`/`vcc_lo`/`exec_lo` via `mask_half`) and `s_cmp_eq/lg_u32` (`wave_equal`) to the known 32-bit half in wave64. Opposite-half `s_cmp_*_u32/i32` comparisons (lo vs hi), ordering comparisons on mask halves, and `s_cmp_*_u32/i32/u64` comparing a lane mask against an arbitrary scalar or immediate reconstruct the exact 32/64-bit mask words via `wave_mask`. A compare with 0 keeps the vote, but a compare with -1 (all ones) does not: lanes that were never launched (a group smaller than the wave) don't vote, while their bits are 0 in the real mask, so until 2026-11-22 `s_cmp_eq_u32 vcc_hi, -1` read 1 in a 40-thread wave64 for `vcc_hi` = 0xff. GPU-checked with `cs_w64x_partial_scmp.asm` (40-thread wave64, native and `--wave64-emulate`) and `cs_w32_partial_scmp.asm` (20-thread wave32) on an AMD Radeon RX 7800 XT (RADV, Mesa 26.2.6): all 8 words as the headers derive, and 4 of 8 wrong in each with the old translator. GPU-checked with `runtime/test/shaders/cs_wave64_ballot.asm` and `cs_wm_*.asm` on AMD Radeon RX 9070 XT (64-wide subgroup); semantic test coverage in `tests/semantic/test_scalar_bitcmp.py`, `tests/semantic/test_scalar_alu_shifts.py`, `tests/semantic/test_loop_ballot_barrier.py`, and `tests/test_lane_masks.py` (split SGPR pairs, dual-dword `x_mcache`, `_b64` mask+imm, and `v_mbcnt` half selection CPU-checked, not yet GPU-verified). |
506| 64-bit mask equality (SHADER-551) | `s_cmp_eq_u64` / `s_cmp_lg_u64` compare both exact 32-bit words and set a uniform SCC. Canonical full-wave masks (`exec`, mask-valued `vcc`, or a wave64 `MASK_LO`/`MASK_HI` SGPR pair) compared with another full mask or zero may use a whole-wave equality vote. Other SGPR pairs materialize each mask half separately and retain scalar data and constant words, including split, swapped, duplicated, mixed mask/data and wave32 pairs. Comparing with all ones also materializes words, so unlaunched lanes remain zero bits in partial waves. CPU-checked by `tests/semantic/test_scmp_u64_mask_pairs.py` with full and partial wave64, wave32, and wave64-emulation cases; independent synthetic Vulkan readback is reported in [PR #3007](https://github.com/ItsNotRexed/Leonida/pull/3007). No native RDNA2 instruction oracle was run for this rule. | 507| 64-bit mask equality (SHADER-551) | `s_cmp_eq_u64` / `s_cmp_lg_u64` compare both exact 32-bit words and set a uniform SCC. Canonical full-wave masks (`exec`, mask-valued `vcc`, or a wave64 `MASK_LO`/`MASK_HI` SGPR pair) compared with another full mask or zero may use a whole-wave equality vote. Other SGPR pairs materialize each mask half separately and retain scalar data and constant words, including split, swapped, duplicated, mixed mask/data and wave32 pairs. Comparing with all ones also materializes words, so unlaunched lanes remain zero bits in partial waves. CPU-checked by `tests/semantic/test_scmp_u64_mask_pairs.py` with full and partial wave64, wave32, and wave64-emulation cases; independent synthetic Vulkan readback is reported in [PR #3007](https://github.com/ItsNotRexed/Leonida/pull/3007). No native RDNA2 instruction oracle was run for this rule. |
507| VOP3 FP modifiers on constants | `tools/shader_ir.py` keeps VOP3 FP source modifiers (`neg(...)`, `\|...\|`, `-\|...\|`, `abs(...)`, and nested combinations) as `abs`/`neg` flags on `imm` and `fimm` operands so `abs` clears the sign bit first and `neg` flips it second (matching LLVM `AMDGPUInstPrinter.cpp::printOperandAndFPInputMods` and `llvm/test/MC/AMDGPU/vop3-modifiers.s`). Plain signed literals (`-1`, `-1.0`) are unchanged. Until 2026-11-22, `-\|1.0\|` folded `-` into the float before `FAbs` (yielding `+1.0`), `neg(0x3f800000)` / `neg(1)` applied two's-complement integer negation (`-4.0f` / `0xffffffff` NaN instead of `-1.0f` / `0x80000001`), and `\|0x...\|` / `-\|0x...\|` dropped `abs`. `tools/shader_meta.py` applies the same bit operations in `_imm_u32`. Checked on the CPU by `tests/test_shader_ir.py`, `tests/test_shader_meta.py` and `tests/semantic/test_vop3_const_mods.py` (f32, f16, `v_fma_mix_f32`, `v_cmp_class_f32`, f64 SPIR-V structure); GPU-checked for `-\|-2.0\|`, `neg(0x3f800000)`, `\|0xbf800000\|` and f16 `-\|0x3c00\|` by `ps_vop3_const_mods.asm` (Tesla V100 (NVIDIA 580.95.05, Linux)). | 508| VOP3 FP modifiers on constants | `tools/shader_ir.py` keeps VOP3 FP source modifiers (`neg(...)`, `\|...\|`, `-\|...\|`, `abs(...)`, and nested combinations) as `abs`/`neg` flags on `imm` and `fimm` operands so `abs` clears the sign bit first and `neg` flips it second (matching LLVM `AMDGPUInstPrinter.cpp::printOperandAndFPInputMods` and `llvm/test/MC/AMDGPU/vop3-modifiers.s`). Plain signed literals (`-1`, `-1.0`) are unchanged. Until 2026-11-22, `-\|1.0\|` folded `-` into the float before `FAbs` (yielding `+1.0`), `neg(0x3f800000)` / `neg(1)` applied two's-complement integer negation (`-4.0f` / `0xffffffff` NaN instead of `-1.0f` / `0x80000001`), and `\|0x...\|` / `-\|0x...\|` dropped `abs`. `tools/shader_meta.py` applies the same bit operations in `_imm_u32`. Checked on the CPU by `tests/test_shader_ir.py`, `tests/test_shader_meta.py` and `tests/semantic/test_vop3_const_mods.py` (f32, f16, `v_fma_mix_f32`, `v_cmp_class_f32`, f64 SPIR-V structure); GPU-checked for `-\|-2.0\|`, `neg(0x3f800000)`, `\|0xbf800000\|` and f16 `-\|0x3c00\|` by `ps_vop3_const_mods.asm` (Tesla V100 (NVIDIA 580.95.05, Linux)). |
508| `v_cmp_class_f64`, `v_cmpx_class_f64` | IEEE-754 binary64 numeric class test against the 10-bit mask (`0` sNaN, `1` qNaN, `2` `-inf`, `3` `-normal`, `4` `-subnormal`, `5` `-0`, `6` `+0`, `7` `+subnormal`, `8` `+normal`, `9` `+inf`), lowered in `Gen.cmp_class_f64` using pure 32-bit `%uint` bit extraction on `(lo, hi)` with no `Float64` capability required. Supports VGPR/SGPR pairs, float inline constants (`fimm`), sign-extended inline integers (`-16..64`), 32-bit literals placed in bits `[63:32]` (as on RDNA2), and VOP3 `abs`/`neg` sign-bit modifiers on `src0` (`abs` clears bit 63, `neg` flips bit 63 without quieting sNaN). Inactive lanes produce 0 for `v_cmp_class_f64` and stay inactive for `v_cmpx_class_f64`. Source: AMD RDNA2 ISA VOPC/VOP3 `V_CMP_CLASS_F64` / `V_CMPX_CLASS_F64`. CPU-checked by `tests/semantic/test_cmp_class_f64.py` (all 10 classes with low- and high-word payload bits, mask combinations and high-bit ignores, SGPR pairs, `fimm`/inline/literal constants, `abs`/`neg`/`-\|x\|`, `v_cmpx_class_f64` EXEC narrowing, inactive lanes, no `Float64` capability, bad-operand rejections). **Not GPU-verified.** Hardware-measured natively on `gfx1100`** (RX 7900 XTX, driver 26.10.1) through `tools/hw_oracle`: the ten classes as `f64` pairs (`0x7ff0000000000001` sNaN, `0x7ff8000000000000` qNaN, `0xfff0000000000000` -inf, `0xbff0000000000000` -normal, `0x8000000000000001` -denormal, `-0`, `+0`, `0x0000000000000001` +denormal, `0x3ff0000000000000` +normal, `0x7ff0000000000000` +inf) against their own bit, all ten bits, no bits and the nine other bits (40), and `v_cmpx_class_f64` on the launched lane true and false (2), all matching the same CPU model. Not measured: `abs`/`neg`, inactive lanes and wave64. **Not GPU-verified.** | 509| `v_cmp_class_f64`, `v_cmpx_class_f64` | IEEE-754 binary64 numeric class test against the 10-bit mask (`0` sNaN, `1` qNaN, `2` `-inf`, `3` `-normal`, `4` `-subnormal`, `5` `-0`, `6` `+0`, `7` `+subnormal`, `8` `+normal`, `9` `+inf`), lowered in `Gen.cmp_class_f64` using pure 32-bit `%uint` bit extraction on `(lo, hi)` with no `Float64` capability required. Supports VGPR/SGPR pairs, float inline constants (`fimm`), sign-extended inline integers (`-16..64`), 32-bit literals placed in bits `[63:32]` (as on RDNA2), and VOP3 `abs`/`neg` sign-bit modifiers on `src0` (`abs` clears bit 63, `neg` flips bit 63 without quieting sNaN). Inactive lanes produce 0 for `v_cmp_class_f64` and stay inactive for `v_cmpx_class_f64`. Source: AMD RDNA2 ISA VOPC/VOP3 `V_CMP_CLASS_F64` / `V_CMPX_CLASS_F64`. CPU-checked by `tests/semantic/test_cmp_class_f64.py` (all 10 classes with low- and high-word payload bits, mask combinations and high-bit ignores, SGPR pairs, `fimm`/inline/literal constants, `abs`/`neg`/`-\|x\|`, `v_cmpx_class_f64` EXEC narrowing, inactive lanes, no `Float64` capability, bad-operand rejections). **Not GPU-verified.** Hardware-measured natively on `gfx1100`** (RX 7900 XTX, driver 26.10.1) through `tools/hw_oracle`: the ten classes as `f64` pairs (`0x7ff0000000000001` sNaN, `0x7ff8000000000000` qNaN, `0xfff0000000000000` -inf, `0xbff0000000000000` -normal, `0x8000000000000001` -denormal, `-0`, `+0`, `0x0000000000000001` +denormal, `0x3ff0000000000000` +normal, `0x7ff0000000000000` +inf) against their own bit, all ten bits, no bits and the nine other bits (40), and `v_cmpx_class_f64` on the launched lane true and false (2), all matching the same CPU model. Not measured: `abs`/`neg`, inactive lanes and wave64. **Not GPU-verified.** |
@@ -584,8 +585,14 @@ LLVM_MC=/usr/lib/llvm-21/bin/llvm-mc python3 -I <repo>/tools/shader_disasm.py <w
584``` 585```
585 586
586Code starts at the u32 at FSSM offset 0xC0 (the code-section offset) plus 0x28 bytes into that section, and ends at the 587Code starts at the u32 at FSSM offset 0xC0 (the code-section offset) plus 0x28 bytes into that section, and ends at the
587last `s_endpgm`. Use `--mcpu gfx1013`. On 300 random shaders it decoded 284 cleanly (134 invalid words in total), 588last `s_endpgm`. Use `--mcpu gfx1013`. Over the whole 26,503-blob 1.0.2.1 corpus (`shader_disasm.py` at `d90444f2`,
588against 201 clean and 6,560 invalid for gfx1030 and 283 clean for gfx1010–1012. 589llvm-mc 23.1.5, data blocks excluded as below) gfx1013 decodes all 26,503 blobs with no invalid word; gfx1010, gfx1011
590and gfx1012 decode 26,439 (64 blobs with invalid words: 2,481, 2,438 and 2,438 words) and gfx1030 17,875 (8,628 blobs,
591440,225 words). An earlier sample of 300 random shaders gave 284 clean for gfx1013, 201 for gfx1030 and 283 for
592gfx1010–1012. Translating those 26,503 listings at the same commit (`rdna2spirv.py <disasm> --out <out> --shard i/16`,
593then `--merge`, default options) gives 26,503 translated and 26,503 passing `spirv-val`: 2,236 VS, 12,101 PS, 195 GS,
5942,689 CS and 9,282 mesh. The index equals the `4beffda8` run's in every field but `src_sha256`, which differs for the
5951,473 listings the data-block cut below shortened.
589 596
590Some blobs end with a constant-data block after the real code: `s_endpgm`, a dword count N, N dwords of data, a 597Some blobs end with a constant-data block after the real code: `s_endpgm`, a dword count N, N dwords of data, a
591closing `s_endpgm`, then `s_code_end` padding. The data is not code, so the tool ends the range at the count 598closing `s_endpgm`, then `s_code_end` padding. The data is not code, so the tool ends the range at the count
diff --git a/docs/gpu_test_results.md b/docs/gpu_test_results.md
index a89243e41..25a73c7f5 100644
--- a/docs/gpu_test_results.md
+++ b/docs/gpu_test_results.md
@@ -6,6 +6,7 @@ post counts and pass/fail lines there, never game shaders, logs or private paths
6 6
7| GPU | Driver, OS | Commit | build.py | check.py | run_gpu_tests.py | Failed | Entry | 7| GPU | Driver, OS | Commit | build.py | check.py | run_gpu_tests.py | Failed | Entry |
8|---|---|---|---|---|---|---|---| 8|---|---|---|---|---|---|---|---|
9| NVIDIA GeForce RTX 3080 Ti (Ampere), subgroup 32..32 | NVIDIA 616.92, Windows 11 26300.9974 | `d478a92` | not run; pre-disassembled subset | run via run_gpu_tests.py | **Subset:** 81/97 passed, 16 skipped (native); 97/97 passed (`LEONIDA_W64_EMULATE=1`); Python assembler, no spirv-val | none in the subset | [local note](../gpu-test-results/RTX3080Ti-61692.txt) |
9| AMD Radeon RX 9070 GRE (RDNA4, GFX1201), subgroup 32..64 | RADV, Mesa 26.3.1-arch3.5, Vulkan 1.4.363, CachyOS | `05961f0` | 264/264 translated and valid | 203/206 pass, 3 skipped | 218/235 passed, 16 skipped (native and emulated) | `ms_wave_info_s3`, flaky (see below) | [local note](../gpu-test-results/RX9070GRE.txt) | 10| AMD Radeon RX 9070 GRE (RDNA4, GFX1201), subgroup 32..64 | RADV, Mesa 26.3.1-arch3.5, Vulkan 1.4.363, CachyOS | `05961f0` | 264/264 translated and valid | 203/206 pass, 3 skipped | 218/235 passed, 16 skipped (native and emulated) | `ms_wave_info_s3`, flaky (see below) | [local note](../gpu-test-results/RX9070GRE.txt) |
10| AMD Radeon RX 9070 XT (RDNA4, GFX1201), subgroup 32..64 | AMD 26.11.2 (LLPC), Vulkan 1.4.359, Windows 11 26300.9550 | `5d74c27` | not run | not run | 224/241 passed, 16 skipped, 1 failed (native); 225/241 passed, 0 failed (`LEONIDA_W64_EMULATE=1`) | `ms_wave_info_s3`, every native run, flaky emulated (see below) | [local note](../gpu-test-results/RX9070XT.txt) | 11| AMD Radeon RX 9070 XT (RDNA4, GFX1201), subgroup 32..64 | AMD 26.11.2 (LLPC), Vulkan 1.4.359, Windows 11 26300.9550 | `5d74c27` | not run | not run | 224/241 passed, 16 skipped, 1 failed (native); 225/241 passed, 0 failed (`LEONIDA_W64_EMULATE=1`) | `ms_wave_info_s3`, every native run, flaky emulated (see below) | [local note](../gpu-test-results/RX9070XT.txt) |
11| AMD Radeon RX 7900 GRE (RDNA3, gfx1100), subgroup 32..64 | AMD proprietary 26.11.2 (LLPC), Vulkan 1.4.359, Windows 11 x64 | `5d74c27` | 247/247 translated and valid | run via run_gpu_tests.py | 225/241 passed, 16 skipped | none | [#166](https://github.com/ItsNotRexed/Leonida/issues/166#issuecomment-7115041436) | 12| AMD Radeon RX 7900 GRE (RDNA3, gfx1100), subgroup 32..64 | AMD proprietary 26.11.2 (LLPC), Vulkan 1.4.359, Windows 11 x64 | `5d74c27` | 247/247 translated and valid | run via run_gpu_tests.py | 225/241 passed, 16 skipped | none | [#166](https://github.com/ItsNotRexed/Leonida/issues/166#issuecomment-7115041436) |
diff --git a/docs/multi_gpu_validation.md b/docs/multi_gpu_validation.md
index dbea4da09..ca36fb423 100644
--- a/docs/multi_gpu_validation.md
+++ b/docs/multi_gpu_validation.md
@@ -45,7 +45,8 @@ stop and report the blocker; do not substitute llvmpipe. The ICD file on this bo
45- Run one process per card, keep logs per card, and aggregate counts afterwards. 45- Run one process per card, keep logs per card, and aggregate counts afterwards.
46- Each PR verification used a clean worktree at the PR head and, where a base was named, a second worktree at that 46- Each PR verification used a clean worktree at the PR head and, where a base was named, a second worktree at that
47 base with its own freshly built programs. Mixing a script from one commit with binaries from another produces 47 base with its own freshly built programs. Mixing a script from one commit with binaries from another produces
48 false failures (see "Known problems" in [testing.md](testing.md)). 48 false failures (see "Rebuild the test programs after pulling" under [Run them](testing.md#run-them) in
49 testing.md).
49- When a shard fails, rerun the *same* shard on two or three other cards. Failing everywhere points to a driver or 50- When a shard fails, rerun the *same* shard on two or three other cards. Failing everywhere points to a driver or
50 corpus issue; failing on one card points to that card. Re-run single failing tests in isolation before calling a 51 corpus issue; failing on one card points to that card. Re-run single failing tests in isolation before calling a
51 result reproducible. 52 result reproducible.
@@ -66,7 +67,10 @@ page. No game-derived data was used for any of them.
66 67
67Two failures recur on these cards at the tested commits and were confirmed on clean base worktrees, so they are 68Two failures recur on these cards at the tested commits and were confirmed on clean base worktrees, so they are
68driver-version limitations rather than regressions from the PRs tested here: `cs_w32_salu64` (wrong high word of 69driver-version limitations rather than regressions from the PRs tested here: `cs_w32_salu64` (wrong high word of
69an `s_bfe_i64` field) and `cs_signed_zero_nan`. The latter is the signed-zero class tracked in #1203. A real 70an `s_bfe_i64` field) and `cs_signed_zero_nan`. Both are Mesa bugs recorded under "Known problems" in
71[testing.md](testing.md#known-problems): ACO's `combine_add_sub_b2i` for the first and NIR's range analysis
72(`fmul_is_a_number`) folding the `x != x` check for the second; RADV from Mesa 26.3.1 passes both on a gfx1151
73(not measured on these cards). A real
70regression was found on PR #2715: two wave64 pixel fixtures returned the clear value on all three cards tested while 74regression was found on PR #2715: two wave64 pixel fixtures returned the clear value on all three cards tested while
71the PR's base passed them. 75the PR's base passed them.
72 76
diff --git a/docs/progress_dashboard.md b/docs/progress_dashboard.md
index b36e938c8..88647e1f0 100644
--- a/docs/progress_dashboard.md
+++ b/docs/progress_dashboard.md
@@ -22,7 +22,7 @@ are read directly; there is no need to re-save them as UTF-8.
22| Panel | Source | Unit | 22| Panel | Source | Unit |
23|---|---|---| 23|---|---|---|
24| Unit tests | `--run-tests` runs `tests/test_*.py` with the selection `ci.yml` uses (standard-library files with a `__main__` block), one process each; the outcome and the commit it ran on are kept in `<out>/unit_results.json`. That is CI's standard-library loop only: `tests/semantic` (the translator suite) and files that need pytest or numpy are not run, so the panel is not the whole test suite; feed those through `--junit` (`python -m pytest tests/semantic --junitxml <file>`) to see them in the runtime-tests panel | test file | 24| Unit tests | `--run-tests` runs `tests/test_*.py` with the selection `ci.yml` uses (standard-library files with a `__main__` block), one process each; the outcome and the commit it ran on are kept in `<out>/unit_results.json`. That is CI's standard-library loop only: `tests/semantic` (the translator suite) and files that need pytest or numpy are not run, so the panel is not the whole test suite; feed those through `--junit` (`python -m pytest tests/semantic --junitxml <file>`) to see them in the runtime-tests panel | test file |
25| Runtime tests | `runtime/build/Testing/Temporary/LastTest.log` and any `--junit` file (CTest `--output-junit` or pytest `--junitxml`). CTest logs and XML reports are age-checked by file modification time | test | 25| Runtime tests | `runtime/build/Testing/Temporary/LastTest.log` and any `--junit` file (CTest `--output-junit` or pytest `--junitxml`). The CTest log and CTest XML reports are age-checked by file modification time; a pytest report is not | test |
26| GPU tests | `--gpu-log <file>[=<GPU, driver, OS>]`: the saved output of `runtime/test/shaders/check.py`, one group per GPU; a log older than the last commit touching `runtime/test/shaders` or `tools/rdna2spirv.py` counts as needing a re-run | test program | 26| GPU tests | `--gpu-log <file>[=<GPU, driver, OS>]`: the saved output of `runtime/test/shaders/check.py`, one group per GPU; a log older than the last commit touching `runtime/test/shaders` or `tools/rdna2spirv.py` counts as needing a re-run | test program |
27| Translator contract | the contract table in [design.md](design.md#translator-status-and-runtime-contract), each row classified by how it says it was confirmed | contract row | 27| Translator contract | the contract table in [design.md](design.md#translator-status-and-runtime-contract), each row classified by how it says it was confirmed | contract row |
28| Runtime imports | the measured tables in [runtime_imports.md](runtime_imports.md) | import | 28| Runtime imports | the measured tables in [runtime_imports.md](runtime_imports.md) | import |
@@ -34,11 +34,15 @@ are read directly; there is no need to re-save them as UTF-8.
34Every run with `--github` reads the pull requests again, so a merge into `main` shows up on the next run as 34Every run with `--github` reads the pull requests again, so a merge into `main` shows up on the next run as
35IMPLEMENTED, even before a tracking table (such as the D3D12 tracking issue's PR column) is edited. A pull request closed without merging is 35IMPLEMENTED, even before a tracking table (such as the D3D12 tracking issue's PR column) is edited. A pull request closed without merging is
36left out. The page also lists the 30 latest merges, and the trend chart follows the share of pull requests merged and 36left out. The page also lists the 30 latest merges, and the trend chart follows the share of pull requests merged and
37of item IDs with a merged pull request. `gh pr list` reads at most 5000 per state; the Sources table says when that 37of item IDs with a merged pull request. The chart draws at most eight metrics, the first eight metric IDs of the
38limit is reached. 38history in alphabetical order, so with every source present `runtime.current`, `tests.current` and `tests.passed`
39are left out of it (they are still in the metrics table). `gh pr list` reads at most 5000 per state; the Sources
40table says when that limit is reached.
39 41
40With `--github --login <account>` the page also lists that account's claims in the coordination issue (and the issue 42Every run with `--github` also reads the open coordination issue and shows the size of three of its sections ("Up for
41it continues) and its pull requests. Nothing is posted: every `gh` call is a read. 43grabs", "Ready for review or a GPU test", "Needs a rebase on `main`") in the page header. With `--github --login
44<account>` the page also lists that account's claims in the coordination issue (and the issue it continues) and its 50
45latest pull requests. Nothing is posted: every `gh` call is a read.
42 46
43## How a status is decided 47## How a status is decided
44 48
@@ -49,7 +53,7 @@ it continues) and its pull requests. Nothing is posted: every `gh` call is a rea
49| PARTIAL | passed before a change to the test, `make_game.py`, or a Python file under `tools/`, `scripts/` or `runtime/test/shaders/` (CTest: before the last commit touching `runtime/`) | waits for a GPU measurement, or names a GPU check with an item still open | — | open | pull request open | 53| PARTIAL | passed before a change to the test, `make_game.py`, or a Python file under `tools/`, `scripts/` or `runtime/test/shaders/` (CTest: before the last commit touching `runtime/`) | waits for a GPU measurement, or names a GPU check with an item still open | — | open | pull request open |
50| FAILED | failed on its last run | — | — | — | — | 54| FAILED | failed on its last run | — | — | — | — |
51| MISSING | — | — | unimplemented | — | unclaimed | 55| MISSING | — | — | unimplemented | — | unclaimed |
52| UNKNOWN | skipped, or git can't tell what changed | states no confirmation method | — | — | claimed, no code yet | 56| UNKNOWN | skipped (a unit-test file whose every case skipped) | states no confirmation method | — | — | claimed, no code yet |
53 57
54The contract classification reads the row's own words; the matched words are shown in each cell's details, so a 58The contract classification reads the row's own words; the matched words are shown in each cell's details, so a
55wrong class is visible and the rule list in the tool (`CONFIRMATION`) can be corrected. 59wrong class is visible and the rule list in the tool (`CONFIRMATION`) can be corrected.
diff --git a/docs/related_projects.md b/docs/related_projects.md
index df0c28c18..18bc6afe5 100644
--- a/docs/related_projects.md
+++ b/docs/related_projects.md
@@ -40,6 +40,12 @@ specification. Do not paste even a small function "to save time".
40 40
41<https://github.com/realdody/americas-recomp> 41<https://github.com/realdody/americas-recomp>
42 42
43> **Availability (checked 24 November 2026):** the repository, its `xbox-series` branch and its issue #179 return
44> 404, so they are not publicly reachable at this address. The cause is not confirmed (deleted, made private, renamed
45> or moved). Links to it in [d3d12_vulkan.md](d3d12_vulkan.md), [d3d12_command_objects.md](d3d12_command_objects.md) and
46> [shader_validation.md](shader_validation.md) may not open, and the licence and `REUSE.toml` details below are as this page
47> recorded them, not re-checked. The rule below is unchanged.
48
43A **GPL-2.0-only** fork of [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5), on its `xbox-series` branch. It 49A **GPL-2.0-only** fork of [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5), on its `xbox-series` branch. It
44recompiles the same Xbox Series shaders and has run the package's DLLs against a PC D3D12 device behind an Xbox-ABI 50recompiles the same Xbox Series shaders and has run the package's DLLs against a PC D3D12 device behind an Xbox-ABI
45proxy. Since 2026-11-22 its pull requests are limited to collaborators and its README points contributors here. 51proxy. Since 2026-11-22 its pull requests are limited to collaborators and its README points contributors here.
diff --git a/docs/retail_boot_chain.md b/docs/retail_boot_chain.md
index cbe29cf83..7fd5eef65 100644
--- a/docs/retail_boot_chain.md
+++ b/docs/retail_boot_chain.md
@@ -18,6 +18,7 @@ stand-ins named below (not pull requests yet). Own 1.0.2.1 copy, Windows 11, RTX
18| 2 | The 2 MiB reserve+commit calls carry attribute words the shim refuses, and `PAGE_GRAPHICS_*` bits (0x800..0x40000) on top of `PAGE_READWRITE` | Local: accept the attribute word, drop the graphics bits and keep the CPU protection. All seven startup allocations then succeed. #6843 measures the attribute words; no PR changes the check yet | 18| 2 | The 2 MiB reserve+commit calls carry attribute words the shim refuses, and `PAGE_GRAPHICS_*` bits (0x800..0x40000) on top of `PAGE_READWRITE` | Local: accept the attribute word, drop the graphics bits and keep the CPU protection. All seven startup allocations then succeed. #6843 measures the attribute words; no PR changes the check yet |
19| 3 | `xgameruntime.lib`'s thunk treats a missing `XErrorReport` as fatal | #6582 | 19| 3 | `xgameruntime.lib`'s thunk treats a missing `XErrorReport` as fatal | #6582 |
20| 4 | Access violation in the title's allocator: its `/GA` code reads its TLS from module index 0 | #4313 | 20| 4 | Access violation in the title's allocator: its `/GA` code reads its TLS from module index 0 | #4313 |
21| 4a | Wine only, not reached on Windows: `GameInput.dll` ordinal 1, the executable's `GameInputCreate` import (by ordinal, not by name), which the loader looks up as `gameinput.dll!#1`. When `gta6rt` doesn't serve that name, the import binds to the host's `GameInput.dll`. On Windows the installed one answers; under Wine it is Wine's builtin stub, and the title reads through a null pointer right after the call. Measured by hcristosm after stop 4 with stop 5's fix (old upstream PR 4348) merged, so its order against stop 5 is not measured. #127 reproduced it on Wine 11.21 staging: the title's own `int3` 0.65 s after start, before any D3D12 call | #127 (the `#1` alias in the shim table, `runtime/shims/gameinput.cpp`), but only in a `gta6rt` built with the GameInput shim, that is with SDL3: an installed SDL3 3.2 or newer that CMake finds, `-DLEONIDA_SDL3_FETCH=ON` (`scripts/build_runtime.ps1 -FetchSdl3`) or `-DFETCHCONTENT_SOURCE_DIR_SDL3`. A build without SDL3, one with `-DLEONIDA_SDL3=OFF`, and `build_runtime.ps1`'s `cl.exe` fallback have no `GameInputCreate` at all ([gameinput.md](gameinput.md#building)), so they still stop here under Wine. With the shim and the alias, the Wine run went on to stop 6 in hcristosm's measurement |
21| 5 | Fatal assert when `DStorageGetFactory` returns null | #4348 | 22| 5 | Fatal assert when `DStorageGetFactory` returns null | #4348 |
22| 6 | `XMemAllocatePhysicalPages` unimplemented; the title asserts on FALSE | Local stand-in, §2 | 23| 6 | `XMemAllocatePhysicalPages` unimplemented; the title asserts on FALSE | Local stand-in, §2 |
23| 7 | `D3D12XboxCreateDevice` succeeds; device slot 26 is called with its arguments swapped | Local, §3.1 | 24| 7 | `D3D12XboxCreateDevice` succeeds; device slot 26 is called with its arguments swapped | Local, §3.1 |
@@ -28,6 +29,9 @@ stand-ins named below (not pull requests yet). Own 1.0.2.1 copy, Windows 11, RTX
28| 12 | Device slot 133 is called; the proxy table had 128 slots, so the call went through a null pointer | Local: a 192-slot table, and a slot 133 stand-in, §3.4 | 29| 12 | Device slot 133 is called; the proxy table had 128 slots, so the call went through a null pointer | Local: a 192-slot table, and a slot 133 stand-in, §3.4 |
29| 13 | **Current stop**: right after the first `CreateDescriptorHeap`, the title calls the heap's slot 9 (`GetCPUDescriptorHandleForHeapStart` on the PC), takes the handle from `rax` and asserts that it equals a value it already holds. Hypothesis: a console descriptor heap starts at an address the title chose or can predict, which the PC handle doesn't match | Open: a question for the descriptor model ([boot.md](boot.md) Q4) | 30| 13 | **Current stop**: right after the first `CreateDescriptorHeap`, the title calls the heap's slot 9 (`GetCPUDescriptorHandleForHeapStart` on the PC), takes the handle from `rax` and asserts that it equals a value it already holds. Hypothesis: a console descriptor heap starts at an address the title chose or can predict, which the PC handle doesn't match | Open: a question for the descriptor model ([boot.md](boot.md) Q4) |
30 31
32Row 4a is the one row measured under Wine (by hcristosm on Wine 9.0, also reproduced on Proton Experimental; by
33#127 on Wine 11.21 staging), not on the setup above. It is numbered 4a so that the Windows stops keep their numbers.
34
31At stop 13 the D3D12 trace holds 1,185 calls: the device, 5 command queues, 5 fences, 7 command allocators, 35At stop 13 the D3D12 trace holds 1,185 calls: the device, 5 command queues, 5 fences, 7 command allocators,
32581 command lists created and closed, a shader cache session, `XboxIDXGIDevice::GetAdapter`, one failed 36581 command lists created and closed, a shader cache session, `XboxIDXGIDevice::GetAdapter`, one failed
33`ID3D12Device10::CreateReservedResource2`, the first `CreateSampler2`, one committed resource (the slot 133 37`ID3D12Device10::CreateReservedResource2`, the first `CreateSampler2`, one committed resource (the slot 133
@@ -79,7 +83,7 @@ queues come from this slot, the first of them a compute queue. The first queue c
79 83
80Xbox device slot 73 is `(desc, allocator, pso, riid, out)`. `desc` is 16 bytes and its first word reads as the 84Xbox device slot 73 is `(desc, allocator, pso, riid, out)`. `desc` is 16 bytes and its first word reads as the
81`D3D12_COMMAND_LIST_TYPE`. `riid` is a console command-list IID that is not in the PC SDK (#3520 records that the 85`D3D12_COMMAND_LIST_TYPE`. `riid` is a console command-list IID that is not in the PC SDK (#3520 records that the
82package doesn't export it). The shim's unknown-IID log names it on the player's machine. Creating an 86package doesn't export it). A retail run logged it as `{c3827890-4024-474c-98cf-645b51dc4874}` (#445). Creating an
83`ID3D12GraphicsCommandList` of that type and handing out #2490's console list 87`ID3D12GraphicsCommandList` of that type and handing out #2490's console list
84proxy gets all 581 lists created and closed. 88proxy gets all 581 lists created and closed.
85 89
diff --git a/docs/runtime_imports.md b/docs/runtime_imports.md
index 7b9f62d5a..0d8207781 100644
--- a/docs/runtime_imports.md
+++ b/docs/runtime_imports.md
@@ -188,9 +188,10 @@ What this does not show: `--run` has not been run, so the entry point has not be
188reached on the way to the first frame. A bound import is not a working one (the binding only says a function with 188reached on the way to the first frame. A bound import is not a working one (the binding only says a function with
189that name exists), and an unimplemented import stops the run only if the title calls it 189that name exists), and an unimplemented import stops the run only if the title calls it
190([When an unimplemented import is called](#when-an-unimplemented-import-is-called)). The executable imports 25 190([When an unimplemented import is called](#when-an-unimplemented-import-is-called)). The executable imports 25
191functions from `ws2_32.dll` (23 by ordinal, plus `getaddrinfo` and `freeaddrinfo`) and the loader binds them to the 191functions from `ws2_32.dll` (23 by ordinal, plus `getaddrinfo` and `freeaddrinfo`). The `ws2_offline` shim now serves the
192host's, so a `--run` can open real sockets: run it with the network off. `winhttp.dll` is served by the offline shim, 192outbound and name-resolution calls among them, loopback only (see the Winsock2 section below), and the remaining
193which opens none. 193imports bind to the host's. `winhttp.dll` is served by the offline shim, which opens none. Known gap: `dnsapi.dll`
194(`DnsQuery*`) is not shimmed, so a title that calls it reaches the host's resolver.
194 195
195## Console paths and the write overlay 196## Console paths and the write overlay
196 197
@@ -449,14 +450,23 @@ on the executable, the rest is not:
449 card and text entry, which fail before starting. 450 card and text entry, which fail before starting.
450 451
451- **Accessibility and speech** (`IXAccessibilityImpl2`, slots 3-21): `XHighContrastGetMode` (5) answers Off and 452- **Accessibility and speech** (`IXAccessibilityImpl2`, slots 3-21): `XHighContrastGetMode` (5) answers Off and
452 `XClosedCaptionSetEnabled` (4) is accepted. No voice is installed: `XSpeechSynthesizerEnumerateInstalledVoices` 453 `XClosedCaptionSetEnabled` (4) is accepted. One silent voice is installed:
453 (8) calls back zero times and returns `S_OK`, `XSpeechSynthesizerCreate` (9) fails (`E_FAIL`) with a null handle, 454 `XSpeechSynthesizerEnumerateInstalledVoices(context, callback)` (8) calls back once, with voice id `leonida-silent`
454 and the handle calls (10-16, 21: close, default and custom voice, streams from text and SSML, stream size and 455 and language `en-US` (the GDK reference's `XSpeechSynthesizerVoiceInformation` layout), and returns `S_OK`
455 data) refuse the handle they were never given (`E_INVALIDARG`, outputs zeroed). The closed-caption properties (3) 456 (`E_INVALIDARG` without a callback). `XSpeechSynthesizerCreate` (9) hands
456 and the speech-to-text display calls (6, 7, 17-20) fail with `E_FAIL`, writing nothing: their parameter lists 457 out a synthesizer handle that speaks with it (`E_POINTER` for a null out pointer). Close (10), set default voice (11)
457 are not in the docs' layout. 458 and set custom voice (12, only for that voice id) accept that handle and refuse any other with `E_INVALIDARG`.
458- **`XLauncherImpl`** (`IXLauncherImpl`, slots 3-5): `XLaunchUri`, `XDisplayAcquireTimeoutDeferral` (null handle) 459 Streams from text (13) and SSML (21) are created from it and return a
459 and `XDisplayCloseTimeoutDeferralHandle` fail with `E_FAIL`; nothing is launched. 460 stream handle; its close (14) accepts it. Stream size (15) reports 44 bytes and stream data (16) copies them: a valid
461 RIFF/WAVE header for 16 kHz, 16-bit mono PCM with zero data bytes, so a title that plays narration reads a silent
462 stream (a buffer under 44 bytes gets `ERROR_INSUFFICIENT_BUFFER`). A foreign handle on 15 or 16 gets `E_INVALIDARG`,
463 outputs zeroed. The closed-caption properties (3) and the speech-to-text display calls (6, 7, 17-20) fail with
464 `E_FAIL`, writing nothing: their parameter lists are not in the docs' layout.
465- **`XLauncherImpl`** (`IXLauncherImpl`, slots 3-5): `XLaunchUri` fails with `E_FAIL`; nothing is launched.
466 `XDisplayAcquireTimeoutDeferral` (4) creates a Win32 `PowerRequestDisplayRequired` request and returns its handle (a
467 failing `PowerCreateRequest` or `PowerSetRequest` returns the Win32 error as an HRESULT).
468 `XDisplayCloseTimeoutDeferralHandle` (5) clears that request and closes the handle, so the display may sleep again.
469 Side effect on the host: while the title holds a deferral, Windows keeps the PC's display on.
460- **ASSUMPTION:** the parameter lists of the speech calls and `XHighContrastGetMode` (Off is 0), from the GDK 470- **ASSUMPTION:** the parameter lists of the speech calls and `XHighContrastGetMode` (Off is 0), from the GDK
461 reference; only the argument counts were measured, from `tools/gdk_runtime_calls.py` on the executable. 471 reference; only the argument counts were measured, from `tools/gdk_runtime_calls.py` on the executable.
462- **HDR:** `XDisplayTryEnableHdrMode` answers Disabled, because the host output is SDR. With `LEONIDA_HDR=1` it 472- **HDR:** `XDisplayTryEnableHdrMode` answers Disabled, because the host output is SDR. With `LEONIDA_HDR=1` it
@@ -628,6 +638,50 @@ Each refused server is logged once (`[rt] winhttp: offline, refused <host>:<port
628tried to reach. `runtime/test/winhttp_offline_test.cpp` (ctest `winhttp_offline`) covers the synchronous and 638tried to reach. `runtime/test/winhttp_offline_test.cpp` (ctest `winhttp_offline`) covers the synchronous and
629asynchronous paths with `.invalid` names; it opens no connection. 639asynchronous paths with `.invalid` names; it opens no connection.
630 640
641## Winsock2 (`ws2_32.dll`) offline
642
643`runtime/shims/ws2_offline.cpp` intercepts outbound Winsock2 entry points — both by name and by standard Windows
644`ws2_32.dll` ordinal (`bind`/`#2`, `connect`/`#4`, `sendto`/`#20`, `setsockopt`/`#21`, `gethostbyaddr`/`#51`,
645`gethostbyname`/`#52`,
646`WSAAsyncGetHostByAddr`/`#102`, `WSAAsyncGetHostByName`/`#103`, `getaddrinfo`, `GetAddrInfoW`, `GetAddrInfoExA/W`,
647`getnameinfo`, `GetNameInfoW`, `WSAConnect`, `WSAConnectByNameA/W`, `WSAConnectByList`, `WSASendTo`, `WSASendMsg`,
648`WSALookupServiceBeginA/W`, `WSAJoinLeaf`, and `WSAIoctl` for `WSAID_CONNECTEX` and `WSAID_WSASENDMSG`). `wsock32.dll` maps its
649`bind`, `connect`, `sendto`, `gethostbyaddr`, `gethostbyname` and `WSAAsyncGetHostBy*` exports (and their ordinals) to
650the same wrappers, since its exports forward to `ws2_32.dll` natively; its `setsockopt` (`#21`) is its own export,
651which takes the Winsock 1.1 option numbers, so it has its own wrapper. Like `ws2_32.dll` it stays host-owned
652(`owns_dll`), so `LoadLibrary` returns the real module. The shim keeps `ws2_32.dll` partially overridden
653so local socket bookkeeping (`WSAStartup`, `socket`, `closesocket`, `select`, `recv`, `send`, byte-order helpers) still
654works for loopback traffic:
655
656- `connect`, `WSAConnect`, `ConnectEx`, `sendto`, `WSASendTo`, `WSASendMsg`, `WSAConnectByNameA/W` and
657 `WSAConnectByList` allow only IPv4 loopback (`127.0.0.0/8`), IPv6 loopback (`::1`) and IPv4-mapped loopback
658 (`::ffff:127.0.0.0/104`); everything else fails with `WSAENETUNREACH`.
659- `WSAConnectByNameA/W` pass `localhost` to the host as the literal `127.0.0.1`, so the host never reads its hosts
660 file. Numeric loopback literals pass through unchanged.
661- `ConnectEx` and `WSASendMsg` from `WSAIoctl` are the host's own pointers, fetched for the socket they are called on
662 (each Winsock provider has its own), after the same loopback check.
663- `bind` narrows wildcard binds (`0.0.0.0`, `::`) to loopback (`127.0.0.1`, `::1`) and refuses other non-loopback
664 addresses with `WSAEADDRNOTAVAIL`.
665- A send to a loopback address on an unbound socket (`sendto`, `WSASendTo`, `WSASendMsg`, `WSAJoinLeaf`) would bind it
666 to the wildcard address, as Microsoft's `sendto` remarks describe, and its port would then take datagrams from other
667 hosts. The shim first binds such a socket to `127.0.0.1`, `::1` or `::ffff:127.0.0.1` (matching the destination); if
668 it stays unbound the send fails with `WSAEADDRNOTAVAIL`.
669- Multicast group joins through `setsockopt` (`IP_ADD_MEMBERSHIP`, `IP_ADD_SOURCE_MEMBERSHIP`, `IPV6_ADD_MEMBERSHIP`,
670 `MCAST_JOIN_GROUP`, `MCAST_JOIN_SOURCE_GROUP`, and `wsock32.dll`'s Winsock 1.1 `IP_ADD_MEMBERSHIP` = 5) fail with
671 `WSAEADDRNOTAVAIL`; other options pass through. `WSAJoinLeaf` gets the same loopback check as `connect`, so a group
672 address is refused with `WSAENETUNREACH`.
673- Forward lookups refuse external names with `WSAHOST_NOT_FOUND` without sending DNS traffic. A dotted octet with a
674 leading zero (`0127.0.0.1`) is refused too: Windows reads it as octal, so it is not the loopback address it looks
675 like. `getnameinfo` / `GetNameInfoW` force `NI_NUMERICHOST` (or return `WSAHOST_NOT_FOUND` under `NI_NAMEREQD`) for
676 non-loopback addresses.
677- `WSALookupServiceBeginA/W` (name-service queries) always fail with `WSASERVICE_NOT_FOUND`.
678
679`runtime/test/ws2_offline_test.cpp` (ctest `ws2_offline`) verifies name and ordinal bindings, the `wsock32.dll`
680aliases, external refusals using RFC 5737 / RFC 3849 / `.invalid` targets, the `0127.0.0.1` refusal, the
681`WSASERVICE_NOT_FOUND` refusal, wildcard-bind narrowing, a `ConnectEx` pointer from `WSAIoctl` connecting to a loopback
682listener, a local loopback UDP round-trip, loopback binds for sends on unbound UDP sockets (with a control showing
683the host's own `sendto` binds to `0.0.0.0`), and the multicast and `WSAJoinLeaf` refusals.
684
631## What this proves and what it does not 685## What this proves and what it does not
632 686
633- It proves the loader parses real Xbox Series PE files, maps their sections, applies no unnecessary relocation, 687- It proves the loader parses real Xbox Series PE files, maps their sections, applies no unnecessary relocation,
diff --git a/docs/shader_library.md b/docs/shader_library.md
index d96aaaccd..bb7e3a027 100644
--- a/docs/shader_library.md
+++ b/docs/shader_library.md
@@ -109,6 +109,40 @@ as scalar data. The translator keeps its existing behavior when the source is ab
109or the library code has another strict wave64 marker. Synthetic cases are in 109or the library code has another strict wave64 marker. Synthetic cases are in
110`tests/semantic/test_fspx_wave_size.py`. 110`tests/semantic/test_fspx_wave_size.py`.
111 111
112### Containers and programs
113
114The carved corpus is counted two ways, and the two numbers are both right (BL-5 in
115[boot_leads.md](boot_leads.md)):
116
117| Count | What it counts | 1.0.2.1 |
118|---|---|---|
119| Containers | carved `DXBC` files, one row of the carve index each | 26,503 |
120| Programs | tag-`0x0D` payloads (`XBCH` → `FSSM`) inside them | 26,698 |
121
122The difference is 195 containers that hold two payloads. All 195 are vertex shaders; every other container holds
123one:
124
125| Stage | Containers | Payloads | Containers with two |
126|---|---|---|---|
127| `vs` | 2,236 | 2,431 | 195 |
128| `ms` | 9,282 | 9,282 | 0 |
129| `ps` | 12,101 | 12,101 | 0 |
130| `gs` | 195 | 195 | 0 |
131| `cs` | 2,689 | 2,689 | 0 |
132
133So 195 is the geometry-shader count because of what the second payload is, not because geometry shaders are
134counted twice or missed: it is the same vertex shader built for the export-shader stage of a legacy
135geometry-shader pipeline ([design.md](design.md), "VS as ES (two-payload VS containers)"). The carve skips
136nothing here.
137
138`tools/fssm_unpack.py` prints these counts after it unpacks (`programs: … payloads in … containers`, then one
139line per stage when it is given the carve index, whose `stage` field it reads). It still writes one program per
140container, the last payload by default, so the 195 export-stage variants are not translated; which payload a
141geometry-shader pipeline selects is open ([fssm_crosscheck.md](fssm_crosscheck.md) §6).
142
143Measured on an own 1.0.2.1 copy from the build's `index.json` and `fssm_index.json`. The synthetic case is
144`test_program_counts_separate_containers_from_payloads` in `tests/test_fssm_unpack.py`.
145
112## 4. Tool 146## 4. Tool
113 147
114```sh 148```sh
diff --git a/docs/shader_validation.md b/docs/shader_validation.md
index 381b11642..ac33debfa 100644
--- a/docs/shader_validation.md
+++ b/docs/shader_validation.md
@@ -1997,7 +1997,7 @@ the two wave sizes agree on every word. `tools/fma_mix_probe.py --oracle hw` (th
1997`tests/semantic/spirv_mini_interp.py`, then compared with the hardware under the MODE the translator assumes for the 1997`tests/semantic/spirv_mini_interp.py`, then compared with the hardware under the MODE the translator assumes for the
1998game (IEEE 0, DX10_CLAMP 1, f32 denormals flushed, f16 denormals kept). It gives the same word for the float 1998game (IEEE 0, DX10_CLAMP 1, f32 denormals flushed, f16 denormals kept). It gives the same word for the float
1999constants in every `op_sel`/`op_sel_hi` combination, for the integer constants as f16 halves, for clamp on values that 1999constants in every `op_sel`/`op_sel_hi` combination, for the integer constants as f16 halves, for clamp on values that
2000are not NaN, and for the f16 denormals. It differs in five ways, none fixed here: 2000are not NaN, and for the f16 denormals. It differs in five ways; item 2 is fixed since 2026-11-24:
2001 2001
20021. **f16 omod.** The translator applies `mul:2`/`mul:4`/`div:2` to every f16 result. The hardware ignores them in this 20021. **f16 omod.** The translator applies `mul:2`/`mul:4`/`div:2` to every f16 result. The hardware ignores them in this
2003 MODE (24 words: `v_add/mul/fma/fmac/exp/rcp_f16`). `v_cvt_f16_f32` drops its omod and clamp today, so its omod 2003 MODE (24 words: `v_add/mul/fma/fmac/exp/rcp_f16`). `v_cvt_f16_f32` drops its omod and clamp today, so its omod
@@ -2007,6 +2007,7 @@ are not NaN, and for the f16 denormals. It differs in five ways, none fixed here
2007 when "output denormals" are off, the `SIFoldOperands.cpp` comment quoted above). That count needs the game files. 2007 when "output denormals" are off, the `SIFoldOperands.cpp` comment quoted above). That count needs the game files.
20082. **clamp of a NaN.** The interpreter refuses `FClamp` with a NaN operand, which GLSL.std.450 leaves undefined. The 20082. **clamp of a NaN.** The interpreter refuses `FClamp` with a NaN operand, which GLSL.std.450 leaves undefined. The
2009 hardware gives +0 with DX10_CLAMP 1, for `v_fmac_f16`, `v_fma_mixlo_f16` and `v_fma_mix_f32` alike (SHADER-186). 2009 hardware gives +0 with DX10_CLAMP 1, for `v_fmac_f16`, `v_fma_mixlo_f16` and `v_fma_mix_f32` alike (SHADER-186).
2010 **Fixed since 2026-11-24:** `Gen.clamp_mods` selects +0 for a NaN before `FClamp` (`tests/semantic/test_vop3_clamp_nan.py`).
20103. **Mix-op rounding.** The hardware rounds once (the section above). 20113. **Mix-op rounding.** The hardware rounds once (the section above).
20114. **f32 denormal operands of the mix ops.** They are not flushed with `denorm_mode_32 = 0`: `0x00000001`, `0x807fffff` 20124. **f32 denormal operands of the mix ops.** They are not flushed with `denorm_mode_32 = 0`: `0x00000001`, `0x807fffff`
2012 and the integer constants `1` and `64` used as f32 give the denormal, where the hardware gives a zero of its sign 2013 and the integer constants `1` and `64` used as f32 give the denormal, where the hardware gives a zero of its sign
diff --git a/docs/testing.md b/docs/testing.md
index 743d7b640..f8246f888 100644
--- a/docs/testing.md
+++ b/docs/testing.md
@@ -2,13 +2,14 @@
2 2
3The GPU tests are small hand-written RDNA2 programs in `runtime/test/shaders`. They are translated to SPIR-V and run 3The GPU tests are small hand-written RDNA2 programs in `runtime/test/shaders`. They are translated to SPIR-V and run
4on your GPU, and the results are compared with what the RDNA2 hardware gives. They need no game files, and every 4on your GPU, and the results are compared with what the RDNA2 hardware gives. They need no game files, and every
5result helps: post it in [#166](https://github.com/ItsNotRexed/Leonida/issues/166), one comment per GPU and driver. 5result helps: submit a pull request adding a record under [`gpu-test-results/`](../gpu-test-results), following
6the existing files there and [CONTRIBUTING.md](../CONTRIBUTING.md).
6If your GPU is already covered there, testing an open pull request from the review queue in the [coordination 7If your GPU is already covered there, testing an open pull request from the review queue in the [coordination
7issue][claims] helps more. 8issue][claims] helps more.
8 9
9This page collects the setup steps and the problems testers have run into so far. 10This page collects the setup steps and the problems testers have run into so far.
10 11
11[claims]: https://github.com/ItsNotRexed/Leonida/issues?q=is%3Aissue%20is%3Aopen%20in%3Atitle%20%22Coordinating%20who%20works%20on%20what%22 12[claims]: https://github.com/ubiquitarianism/leonida/issues/14
12 13
13## What you need 14## What you need
14 15
@@ -143,7 +144,7 @@ Write-Output "Test exit code: $LASTEXITCODE"
143``` 144```
144 145
145Report the executable name, the workflow run and its commit, your GPU and driver, 146Report the executable name, the workflow run and its commit, your GPU and driver,
146the exit code, and the test summary in [#166](https://github.com/ItsNotRexed/Leonida/issues/166). 147the exit code, and the test summary in your `gpu-test-results/` record.
147Label it as a single-test run so the result is easy to distinguish from a full suite run. 148Label it as a single-test run so the result is easy to distinguish from a full suite run.
148 149
149## Run them 150## Run them
@@ -170,16 +171,6 @@ python -I runtime/test/shaders/build.py <out dir>
170python -I runtime/test/shaders/check.py <out dir> <folder with the test programs> 171python -I runtime/test/shaders/check.py <out dir> <folder with the test programs>
171``` 172```
172 173
173For the standalone `v_mullit_f32` readback, build the full-screen triangle and the
174hand-written semantic fixture, then run 120 draws with runtime SGPR inputs.
175The driver checks every pixel against an integer product rounded to 24 bits.
176It reports the input words, pixel and channel on the first mismatch.
177
178```sh
179python -I runtime/test/shaders/build.py <out-dir> vs_ids ps_mullit
180python -I runtime/test/shaders/mullit_readback.py <out-dir> <harness-directory>
181```
182
183For D3D12/runtime tests, `LEONIDA_VK_VALIDATION=1` enables `VK_LAYER_KHRONOS_validation`. When running with validation, set `DISABLE_RTSS_LAYER=1` and `DISABLE_VULKAN_OBS_CAPTURE=1` if MSI Afterburner (RivaTuner) or OBS is installed: their overlay layers can add unsupported swapchain usage, and in an elevated (administrator) terminal the loader ignores `VK_LOADER_LAYERS_DISABLE=~implicit~` (see "Known problems"). 174For D3D12/runtime tests, `LEONIDA_VK_VALIDATION=1` enables `VK_LAYER_KHRONOS_validation`. When running with validation, set `DISABLE_RTSS_LAYER=1` and `DISABLE_VULKAN_OBS_CAPTURE=1` if MSI Afterburner (RivaTuner) or OBS is installed: their overlay layers can add unsupported swapchain usage, and in an elevated (administrator) terminal the loader ignores `VK_LOADER_LAYERS_DISABLE=~implicit~` (see "Known problems").
184 175
185`vk_compute_test`, `vk_bindless_test` and `vk_image_fuzz` read `LEONIDA_VK_VALIDATION` too (`vk_compute_test` 176`vk_compute_test`, `vk_bindless_test` and `vk_image_fuzz` read `LEONIDA_VK_VALIDATION` too (`vk_compute_test`
@@ -345,6 +336,17 @@ on an Apple M3 Max (MoltenVK 1.4.2 and 1.4.3): 17 workgroup shapes from 1 to 102
345subgroups, with and without full subgroups and register pressure, all 32 lanes in order. A device whose default 336subgroups, with and without full subgroups and register pressure, all 32 lanes in order. A device whose default
346isn't the requested size still prints `not available`, and those tests skip. 337isn't the requested size still prints `not available`, and those tests skip.
347 338
339`cs_w32_shift64` checks `v_lshlrev_b64`, `v_lshrrev_b64` and `v_ashrrev_i64` with 64 memory-fed cases:
340eight boundary values crossed with counts 0, 1, 31, 32, 33, 63, 64 and 65. The expected values come from Python
341integers using the low six count bits, as specified by the [RDNA2 ISA, VOP3 opcodes 767–769](https://docs.amd.com/api/khub/documents/Et~wpu9g~Ffl7d9q0QZ~Og/content).
342It also overlaps the destination with the count, one source word or the entire source pair. Both GPU runners
343compare all 640 heap words (384 results and 256 unchanged input words); the operands are loaded at runtime so
344the driver cannot replace the tested operations with constant-folded answers. Run it alone with
345`python -I scripts/run_gpu_tests.py --build runtime/build --filter cs_w32_shift64 --require-pass`.
346It needs shader Int64 support; a device that lacks it reports a skip. This is a wave32 test of 64-bit values,
347independent of wave64 emulation. On RTX 3080 Ti (616.92, Windows 11), all 640 words matched; replacing the count
348mask with 31 or the arithmetic shift with a logical shift made the test fail at words 66 and 251 respectively.
349
348## Wave64 pixel, vertex and geometry shaders (`w64_graphics.py`) 350## Wave64 pixel, vertex and geometry shaders (`w64_graphics.py`)
349 351
350Graphics stages have no emulation: on a 32-wide subgroup a wave64 VS, PS or GS runs as two 32-lane halves, and the 352Graphics stages have no emulation: on a 32-wide subgroup a wave64 VS, PS or GS runs as two 32-lane halves, and the
@@ -708,9 +710,14 @@ CS, 10,974 PS).
708 710
709## Posting your result 711## Posting your result
710 712
711Use the template at the top of [#166](https://github.com/ItsNotRexed/Leonida/issues/166): GPU, driver, subgroup 713Submit a pull request adding a file under [`gpu-test-results/`](../gpu-test-results), using the existing files
712range, OS, the commit you built, the tool versions and the counts each script printed. Post counts and pass/fail 714there as format examples. Follow [CONTRIBUTING.md](../CONTRIBUTING.md) and claim the work in the
713lines only, never shaders or logs from the game. A failure that isn't in the table above gets its own issue, linked 715[coordination issue][claims] before opening the pull request.
714from your entry. 716
717Include your GPU, driver, subgroup range, OS, the commit you built, the tool versions, and the pass, skip and fail
718counts each script printed. Label a single-test run clearly instead of presenting it as a full suite run.
719Post counts and pass/fail lines only, never shaders or logs from the game. A failure that is not in the table
720above gets its own issue, linked from your record.
715 721
716Use your system's detected CPU, GPU, VRAM and RAM model names in the #166 entry, not benchmark scores. For a rough browser-based check against reference profiles, you can use [Can I Run Leonida](https://assttro.github.io/can-i-run-leonida/). 722Use your system's detected CPU, GPU, VRAM and RAM model names in your result record, not benchmark scores.
723For a rough browser-based check against reference profiles, you can use [Can I Run Leonida](https://assttro.github.io/can-i-run-leonida/).
diff --git a/docs/textures.md b/docs/textures.md
index 7644272ff..14c3615cc 100644
--- a/docs/textures.md
+++ b/docs/textures.md
@@ -453,6 +453,44 @@ exceptions. The chunk table's offsets are 256-byte aligned (physical) and 4 KiB
453(virtual), and the virtual ranges cover every allocation the parser could lay out. The 453(virtual), and the virtual ranges cover every allocation the parser could lay out. The
45412-bit padding on BCPack chunks is zero-filled (see the header section). 45412-bit padding on BCPack chunks is zero-filled (see the header section).
455 455
456### No name streams in the pools
457
458A pool holds no name table and no string data (BUILD-1368). An earlier claim described a
459`nameTable` stream of 64-byte records (65,536 slots) and a `nameData` stream of ASCII strings;
460neither exists in this install. Every byte of a pool falls into one of the regions below
461(`tools/ttpf_mips.py` `Pool`; all 57 pools, counts only):
462
463| Region | Where | What it holds |
464|---|---|---|
465| RDS5 header and chunk table | 0x00 to `0x18 + (count − 1) * 8`, zero-padded to the ETPF index | the fields in the table above |
466| ETPF header | `etpf`, 16 bytes | magic, version, `textures`, `area` |
467| descriptors | `etpf + 0x10`, 16 bytes × `textures` | one texture record each |
468| asset keys | after the descriptors, 8 bytes × `textures` | one u64 per record; unique within each pool (57 / 57), 357,115 keys |
469| trailing metadata | after the keys, to `etpf + 0x10 + area + 32 × textures` | `area + 8 × textures` bytes: 13,973,528 in all |
470| zero padding | to chunk 0's physical offset | 0 non-zero bytes in 57 / 57 pools |
471| texture data | the chunk ranges | one virtual allocation per texture |
472
473- **The virtual space has no room for another stream.** Chunk 0's virtual offset is the
474 4 KiB-aligned metadata size and equals the lowest texture base in 57 / 57 pools. Texture bases
475 rise strictly in record order (0 duplicates, 0 unmapped), each allocation runs to the next base
476 and the last one to the virtual size (`Pool.span`).
477- **The trailing metadata reads as uniform random bytes.** In each of the 52 pools with at least
478 1 KiB of it, it has 7.87–8.00 bits/byte. It holds 54,497 zero bytes against 54,584 for uniform
479 bytes, and 0 repeated aligned 16-byte blocks. Its 3,166 printable ASCII runs of 8 bytes or more
480 (longest 17) match the 3,161 that uniform bytes give. Neither zlib nor raw deflate inflates it
481 from its start, from the end of the descriptors or from the end of `area`.
482 *Hypothesis:* per-texture digests or encrypted data. Under the ground rules it stays unread.
483- **The names occur nowhere else either.** The literal strings `nameTable`, `nameData` and
484 `streamName` occur 0 times in the 57 pool files (raw bytes, 57.94 GiB) and in the inflated
485 streams of `common.rpf` (954 streams), `script.rpf` (1,057) and `data.rpf` (28,509). Only 5 of
486 those streams contain `ttdb` at all: 2 XML content documents in `common.rpf` and 3 `RBF0` UI
487 documents in `data.rpf`. The UI documents use it in a member that holds a texture ID; no stream
488 holds a name table.
489
490What links a texture to the rest of the game is its u64 asset key. Models and materials
491reference textures by that key, and exported textures are named `texture_<index>_<key>`. The
492original texture names are not in the pools, and none of the streams searched above holds them.
493
456### Codec ids are the BCPack mode 494### Codec ids are the BCPack mode
457 495
458The on-disk codec ids are `0x04, 0x0C, 0x10, 0x14, 0x18, 0x1C, 0x20`; shifting right by 26 496The on-disk codec ids are `0x04, 0x0C, 0x10, 0x14, 0x18, 0x1C, 0x20`; shifting right by 26
diff --git a/docs/world_census.md b/docs/world_census.md
index 7b002bf5e..23e0d813f 100644
--- a/docs/world_census.md
+++ b/docs/world_census.md
@@ -67,9 +67,13 @@ map-definition metadata.
67The unread bytes are mostly small alignment and metadata gaps between streams. The gap audit found 67The unread bytes are mostly small alignment and metadata gaps between streams. The gap audit found
68**23** `0DRP` signatures in unread ranges, but none resolved to a map or metadata resource 68**23** `0DRP` signatures in unread ranges, but none resolved to a map or metadata resource
69(`raw_maps = 0`, `raw_meta = 0`), so the census is not missing a map class. No unaligned zlib stream 69(`raw_maps = 0`, `raw_meta = 0`), so the census is not missing a map class. No unaligned zlib stream
70that inflates to a `0DRP` header was found in a gap (`missed_zlib_meta = 0`). The 906 rejected 70that inflates to a `0DRP` header was found in a gap (`missed_zlib_meta = 0`). The 840 rejected
71candidates are zlib streams that do not form a complete `0x7a` resource; they are ordinary archive 71candidates are 16-byte-aligned zlib headers that do not inflate to a stream ending inside the archive
72payload, not counted maps. 72(`scan_shard`: `assemble` raises an inflate error (zlib, struct or index) or returns `None`); they are
73ordinary archive payload, not counted maps. A stream that inflates without the `0DRPz` prefix of a `0x7a`
74resource is ordinary payload and accepted. One with that prefix that does not come out whole (truncated,
75not parsing, or still short of a page) is `incomplete`; `invalid` is a second parse check behind it. Both
76are 0 here.
73 77
74## Other archives 78## Other archives
75 79
@@ -161,7 +165,8 @@ do not depend on that fix.
161`summary.json` sets `census_exact` only when all of these hold: 165`summary.json` sets `census_exact` only when all of these hold:
162 166
163- `complete` is true and every expected shard was written; 167- `complete` is true and every expected shard was written;
164- `maps_exact == maps` and `entities_exact == entities`; 168- `maps_exact == maps`, which also makes `entities_exact == entities`, since `entities_exact` sums the
169 exact rows;
165- `entity_gfx == 0` and `entity_unresolved == 0`; 170- `entity_gfx == 0` and `entity_unresolved == 0`;
166- `incomplete == 0` and `invalid == 0`; 171- `incomplete == 0` and `invalid == 0`;
167- `raw_maps == 0` and `missed_zlib_meta == 0`. 172- `raw_maps == 0` and `missed_zlib_meta == 0`.
@@ -196,7 +201,7 @@ python -I tools\world_census.py <levels.rpf> --out work\world\census --merge-onl
196python -I tests\test_world_census.py 201python -I tests\test_world_census.py
197``` 202```
198 203
199The default shard size is 2 GiB, the default job count is half the logical CPUs, and the scan is 204The default shard size is 2 GiB, the default job count is half the logical CPUs (at most 12), and the scan is
200bounded by `--start` / `--limit` when a partial pass is wanted. `--jobs 1` runs the shards in-process 205bounded by `--start` / `--limit` when a partial pass is wanted. `--jobs 1` runs the shards in-process
201instead of a process pool, which is useful for small synthetic archives and tests. 206instead of a process pool, which is useful for small synthetic archives and tests.
202 207
diff --git a/gpu-test-results/GraniteRidge-9950X3D.txt b/gpu-test-results/GraniteRidge-9950X3D.txt
new file mode 100644
index 000000000..c822475d1
--- /dev/null
+++ b/gpu-test-results/GraniteRidge-9950X3D.txt
@@ -0,0 +1,31 @@
1GPU: AMD Radeon Graphics, Ryzen 9 9950X3D integrated (RDNA2 iGPU, Granite Ridge, PCI 1002:13c0),
2 subgroup 32..64
3Driver: AMD proprietary 32.0.21042.62 (Vulkan driver 2.0.353, "2026.04.17 (AMD proprietary shader
4 compiler)"), Vulkan 1.4.315
5Subgroup: 32..64 (minSubgroupSize 32, maxSubgroupSize 64)
6OS: Windows 11 Home, build 26300
7Commit: 3aa975421d470b76da1aa986a91282c59e20d642 (main, 2026-11-24)
8Tools: llvm-mc 21.1.8 (native, built by scripts\build_llvm_mc.ps1), SPIRV-Tools v2026.4 (Vulkan SDK
9 1.4.363.0), CMake 3.31.6 + Ninja 1.12.1, MSVC 14.44.35207 (VS 2022 Build Tools 17.14,
10 Windows SDK 10.0.26100.0), Python 3.12.10
11run_gpu_tests.py: 261 shaders: 261 translated, 261 pass spirv-val
12 native: 235/252 passed, 17 skipped, 0 failed
13 LEONIDA_W64_EMULATE=1: 235/252 passed, 17 skipped, 0 failed
14Failed: none, in either run. cs_imgload_tfe and cs_imgload_d16_tfe pass on this commit (the fixtures
15 changed in #892).
16Skipped: the same 17 in both runs: the 16 "run by d3d12_*_test / w64_graphics.py" cases, and 1
17 "this device cannot require a 64-wide fragment subgroup: subgroup 32..64".
18Notes:
19- The device gives 64-wide compute subgroups, so the native run executes the wave64 compute fixtures
20 that a 32-wide device skips (cs_dpp_w64 among them); none is skipped for subgroup size.
21- Built with scripts\build_runtime.ps1 (CMake + Ninja, RelWithDebInfo, 780 targets), with the Vulkan
22 SDK's Bin folder and llvm-mc on PATH.
23- Device picked with LEONIDA_VK_DEVICE=Radeon (the machine also has an NVIDIA GeForce RTX 4080,
24 PCI 10de:2704); the run prints "device: AMD Radeon(TM) Graphics (subgroup 32..64)".
25- The same build and commit on the RTX 4080 of this machine (driver 621.24): native 203/252 passed,
26 49 skipped, 0 failed; emulated 235/252 passed, 17 skipped, 0 failed. gpu-test-results/RTX4080.txt
27 records the earlier commit d42773d0, with the two tfe failures that #892 has since fixed.
28- ctest, the D3D12 tests and w64_graphics.py were not run in this pass; this file covers
29 run_gpu_tests.py only, one run of each mode.
30- AI-assisted (Claude Code): built main and ran run_gpu_tests.py native and emulated. No game files,
31 nothing online.
diff --git a/gpu-test-results/RTX2060SUPER.txt b/gpu-test-results/RTX2060SUPER.txt
new file mode 100644
index 000000000..16d31b31e
--- /dev/null
+++ b/gpu-test-results/RTX2060SUPER.txt
@@ -0,0 +1,56 @@
1GPU: NVIDIA GeForce RTX 2060 SUPER (Turing, 8 GB, PCI 10de:1f06)
2Driver: NVIDIA 621.14 (proprietary), Vulkan 1.4.357
3Subgroup: 32..32 (default 32)
4OS: Windows 11 Pro, build 28000
5Commit: d42773d0734d5fd7b3a32a1bfd536f61186322a5
6Tools: llvm-mc 21.1.8 (AMDGPU), SPIRV-Tools v2026.4 RC2,
7 Vulkan SDK 1.4.363.0, CMake 3.31.6-msvc6,
8 MSVC 19.44.35230.0, Python 3.12.10
9CPU: AMD Ryzen 5 3600X
10RAM: 15.93 GiB reported
11
12run_gpu_tests.py:
13 257/257 shaders translated and passed spirv-val in both modes.
14 Native: 197/248 passed, 49 skipped, 2 failed.
15 LEONIDA_W64_EMULATE=1: 229/248 passed, 17 skipped, 2 failed.
16
17Failed: cs_imgload_tfe, cs_imgload_d16_tfe (both modes, #31):
18 r32 sint (sint view): 64 bad, texel(5,3) = 2071.
19 Fixture expectations are disputed; see the review on #98.
20
21Skipped: Native: 32 wave64 subgroup-related skips,
22 16 cases covered by other test programs,
23 1 fragment subgroup limitation.
24 Emulated: 16 cases covered by other test programs,
25 1 fragment subgroup limitation.
26
27Runtime: RelWithDebInfo, Windows native build.
28 304 registered, 286 passed, 11 skipped,
29 6 failed, 1 disabled.
30
31Runtime failures:
32- gameinput_host: GameInputCreate returned 0x800401F0;
33 three internal checks failed.
34- d3d12_private_data: 25 mismatches across five object types.
35- d3d12_execute_indirect_validation: 49 parity cases,
36 positive GPU dispatch OK, 0 validation errors, 5 failures.
37 All five: layer=0 warp=1 hw=1 expected=0 (#337, #306).
38- d3d12_clear: R8G8B8A8_SNORM case 2 byte 24:
39 Vulkan c0, WARP c1.
40- d3d12_draw: SEGFAULT, root cause not yet established.
41- d3d12_clear_formats: 241 matched WARP, 10 differed.
42 Differences affect R8G8_SNORM, R8G8B8A8_SNORM,
43 R16G16_SNORM and R16G16B16A16_SNORM.
44
45Notes:
46- ms_wave_info_s3: 4096/4096 pixels exact in both modes.
47- cs_signed_zero_nan: PASS in both modes.
48- Runtime reports upload heaps in system memory (no Resizable BAR).
49- GPU suite counts match the RTX 5070 report in #560,
50 tested on the same commit and NVIDIA driver.
51- Five additional runtime failures compared with #560.
52 The two systems have different Windows builds and hardware,
53 so the cause cannot yet be attributed to the GPU architecture.
54- Single baseline run performed on 2026-11-24.
55- AI-assisted test automation and report preparation.
56- Synthetic tests only; no game files used.
diff --git a/gpu-test-results/RTX3060Ti-Windows.txt b/gpu-test-results/RTX3060Ti-Windows.txt
new file mode 100644
index 000000000..69e0cb6f7
--- /dev/null
+++ b/gpu-test-results/RTX3060Ti-Windows.txt
@@ -0,0 +1,55 @@
1GPU: NVIDIA GeForce RTX 3060 Ti (Ampere / GA104, 8 GB, PCI 10de:2486)
2Driver: NVIDIA 621.14 (proprietary), Vulkan 1.4.357
3Subgroup: 32..32 (default 32)
4OS: Windows 11 Pro, build 26200.9974
5Commit: 3aa975421d470b76da1aa986a91282c59e20d642 (main, 2026-11-24)
6Tools: llvm-mc 23.1.6 (conda-forge llvm-tools, Windows, AMDGPU target),
7 SPIRV-Tools v2026.4 and glslang (conda-forge),
8 Khronos Vulkan-Headers fetched by CMake (no Vulkan SDK installed),
9 CMake 4.4.5 + Ninja 1.13.2, MSVC 19.44.35211 (toolset 14.44.35207),
10 Windows SDK 10.0.26100.0, Python 3.13.14
11CPU: AMD Ryzen 5 5600X
12RAM: 31.92 GiB reported
13
14run_gpu_tests.py:
15 261/261 shaders translated and passed spirv-val in both modes.
16 Native: 203/252 passed, 49 skipped, 0 failed.
17 LEONIDA_W64_EMULATE=1: 235/252 passed, 17 skipped, 0 failed.
18
19Failed: none in either mode.
20
21Skipped: Native: 32 "no 64-wide (compute) subgroup on this device",
22 16 cases run by other test programs (d3d12_*_test,
23 w64_graphics.py), 1 "cannot require a 64-wide fragment subgroup".
24 Emulated: the same 16, plus the 64-wide fragment one.
25
26Runtime: RelWithDebInfo, Windows native build (ctest -j 6).
27 307 registered and 1 disabled (gameinput: no SDL3 installed);
28 293 passed, 13 skipped, 1 failed.
29
30Runtime failures:
31- d3d12_execute_indirect_validation: 49 parity cases,
32 positive GPU dispatch OK, 0 validation errors, 5 failures.
33 All five: layer=0 warp=1 hw=1 expected=0 (issue 504). D3D12Core and
34 d3d10warp.dll are 10.0.26100.9818 here.
35
36Runtime skips (13; LEONIDA_GAME_DIR is unset and VK_LAYER_KHRONOS_validation
37is not installed on this machine):
38 shader_library_corpus, bink_decode, bink_abi, bink_play_headless,
39 bink_audio, fsr_dispatch, bvh_builder, vk_sync_validation,
40 d3d12_boot_movie, d3d12_first_light, d3d12_rgb9e5_rtv,
41 d3d12_sparse_queue_family_contract, d3d12_bindless_churn_validated.
42
43Notes:
44- wave64 VS/PS/GS on this 32-wide-subgroup device: tier A: 1, tier C: 1
45 (tier C is not exact there; see wave64_graphics_reasons in the index).
46- Built with cmake -S runtime -B <build> -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo
47 -DLEONIDA_VULKAN_HEADERS_FETCH=ON from a vcvars64 prompt, with llvm-mc,
48 spirv-as, spirv-val and glslangValidator on PATH.
49- xma_decoder not built (no cargo), GameInput shim not built (no SDL3).
50- Upload heaps in system memory (no Resizable BAR).
51- No game files involved: run_gpu_tests.py assembles its own RDNA2 fixtures
52 with llvm-mc and runs the translated SPIR-V on the Vulkan device.
53- AI-assisted (Claude Code): built main and ran ctest and run_gpu_tests.py,
54 native and under LEONIDA_W64_EMULATE=1, on the owner's machine. The numbers
55 are the runners' own output. No game data, nothing online.
diff --git a/gpu-test-results/RTX3080Ti-61692.txt b/gpu-test-results/RTX3080Ti-61692.txt
new file mode 100644
index 000000000..857029f35
--- /dev/null
+++ b/gpu-test-results/RTX3080Ti-61692.txt
@@ -0,0 +1,46 @@
1GPU: NVIDIA GeForce RTX 3080 Ti (Ampere), 12 GiB VRAM
2Driver: NVIDIA 616.92 (nvidia-smi)
3Subgroup: 32..32 (reported by the locally built vk_compute_test)
4OS: Windows 11, 26H2, build 10.0.26300.9974
5Date: 2026-11-24
6Commit: d478a92d4d7eae1d7b512cb4553ddc4fbc300e85 (harnesses and scripts)
7Tools: Python 3.14.3, LLVM-MinGW 20261117 UCRT x86_64 / Clang 23.1.6,
8 CMake 4.4.5, Ninja 1.13.2,
9 Khronos Vulkan-Headers d277a0a3cda9c682708c93279f0c72cd6b0ae3f3
10Scope: ONLY tests/semantic/fixtures/disasm, the pre-disassembled synthetic subset.
11 100 listings translated and assembled in each run with tools/spirv_asm.py.
12 No llvm-mc or spirv-val was available; this is NOT a full-suite or
13 SPIR-V-validation result. No game files were used.
14build.py: not run (--disasm-dir skips the assembler-dependent fixture build)
15check.py: not run separately
16run_gpu_tests.py:
17 native: 81/97 passed, 16 skipped, 0 failed; exit 0
18 LEONIDA_W64_EMULATE=1: 97/97 passed, 0 skipped, 0 failed; exit 0
19Runtime: full Windows runtime and ctest not built or run; standalone Vulkan tools only
20
21The native skips all report "no 64-wide compute subgroup on this device":
22 cs_w64_exec_computed, cs_w64_mask_imm, cs_w64x_andn2_exec, cs_w64x_ballot,
23 cs_w64x_bpermute, cs_w64x_load_ballot_load, cs_w64x_partial, cs_w64x_permute,
24 cs_w64x_readfirstlane, cs_w64x_readlane, cs_w64x_saveexec_b64, cs_w64x_writelane,
25 cs_wave64_ballot, cs_wavemask, cs_wm_bfm64, cs_wm_half_cmp.
26All sixteen pass with LEONIDA_W64_EMULATE=1.
27
28In particular, cs_w32_exec_computed passes in both modes and cs_w64_exec_computed
29passes in emulation (native skips). This is a separate driver/commit/subset measurement
30from PR #280's 621.24 full-suite record at da60a361; the different totals cannot be used
31to infer a driver regression or a full-suite improvement. The tfe fixtures reported
32there are outside this subset.
33
34Reproduction (PowerShell, with LLVM-MinGW, CMake and Ninja on PATH):
35
36 cmake -S runtime -B runtime/build/vulkan -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_COMPILER=clang++ -DLEONIDA_BUILD_WINDOWS_RUNTIME=OFF -DVulkan_INCLUDE_DIR=<Vulkan-Headers>/include
37 cmake --build runtime/build/vulkan --parallel 6 --target vk_harness vk_texture_test vk_sampler_test vk_compute_test vk_store_test vk_bindless_test
38 $env:LEONIDA_VK_DEVICE = 'RTX 3080 Ti'
39 # Native run: LEONIDA_W64_EMULATE unset.
40 python -I scripts/run_gpu_tests.py --build runtime/build/vulkan --work <native-work> --disasm-dir tests/semantic/fixtures/disasm --assembler python --require-pass
41 $env:LEONIDA_W64_EMULATE = '1'
42 python -I scripts/run_gpu_tests.py --build runtime/build/vulkan --work <emulated-work> --disasm-dir tests/semantic/fixtures/disasm --assembler python --require-pass
43
44AI-assisted: Codex prepared the local portable toolchain, built the matching programs,
45ran both modes on the contributor's GPU, and wrote this bounded result. No game data,
46shader dumps, private paths, or generated binaries are included in the contribution.
diff --git a/gpu-test-results/RTX4060-Nobara-three-tests.txt b/gpu-test-results/RTX4060-Nobara-three-tests.txt
new file mode 100644
index 000000000..06bc8d7a7
--- /dev/null
+++ b/gpu-test-results/RTX4060-Nobara-three-tests.txt
@@ -0,0 +1,49 @@
1GPU: NVIDIA GeForce RTX 4060
2VRAM: 8188 MiB reported by nvidia-smi
3Driver: NVIDIA 595.112.07
4Subgroup: Not recorded; no subgroup-range claim is made.
5OS: Nobara Linux 44 (KDE Plasma Desktop Edition)
6Commit: 1c93c8697078c3ccbd6f374caf5bb3ab0b6bc8e4
7Date: 2026-11-24
8Tools: cmake-4.3.0-1.fc44.x86_64
9 gcc-c++-16.2.1-2.fc44.x86_64
10 python3-3.14.7-1.fc44.x86_64
11 spirv-tools-2026.1-1.fc44.x86_64
12 vulkan-headers-1.4.341.0-1.fc44.noarch
13 ninja-build-1.13.2-2.fc44.x86_64
14
15Scope: Three selected synthetic compute fixtures only, using the repository's
16pre-disassembled fixtures and spirv-as. This is not a full-suite result.
17
18run_gpu_tests.py --filter cs_bounds:
19 1 shader: 1 translated, 1 pass spirv-val
20 PASS cs_bounds: 0x12345678 0x12345678 0x0 0xeeeeeeee
21 GPU summary: 1/1 passed
22
23run_gpu_tests.py --filter cs_buf:
24 2 shaders: 2 translated, 2 pass spirv-val
25 PASS cs_buf_swizzle: 0x5eed0024 0x5eed0044 0x5eed004c 0x5eed0008 0x5eed000c 0x0 0xbeef0000 0xbeef0001
26 PASS cs_buf_tail: 0x0 0x5eed000c 0x5eed0008 0x5eed000c 0x0 0x0 0x5eed0010 0x0
27 GPU summary: 2/2 passed
28
29Combined selected coverage: 3 distinct tests passed, 0 reported skipped,
300 reported failed. All 3 translated shaders passed spirv-val.
31Other fixtures, wave64-emulation runs, CTest and the translator test suite
32were not run. No game files were used. No game-compatibility claim is made.
33
34Build, from the repository root:
35 cmake -S runtime -B runtime/build/linux -G Ninja -DCMAKE_BUILD_TYPE=Release -DLEONIDA_BUILD_WINDOWS_RUNTIME=OFF -DLEONIDA_VULKAN_HEADERS_FETCH=OFF -DLEONIDA_SDL3_FETCH=OFF -DFETCHCONTENT_FULLY_DISCONNECTED=ON -DLEONIDA_REQUIRE_VULKAN=ON
36 cmake --build runtime/build/linux --target vk_compute_test vk_store_test vk_harness --parallel 2
37
38Test commands, with paths written relative to the repository root:
39 LEONIDA_VK_DEVICE=4060 LEONIDA_GPU_TEST_TIMEOUT=20 timeout --kill-after=5s 60s python3 -I scripts/run_gpu_tests.py --build runtime/build/linux --disasm-dir tests/semantic/fixtures/disasm --assembler spirv-as --filter cs_bounds --require-pass --work gpu-work-cs-bounds
40 LEONIDA_VK_DEVICE=4060 LEONIDA_GPU_TEST_TIMEOUT=20 timeout --kill-after=5s 90s python3 -I scripts/run_gpu_tests.py --build runtime/build/linux --disasm-dir tests/semantic/fixtures/disasm --assembler spirv-as --filter cs_buf --require-pass --work gpu-work-cs-buf
41
42Notes:
43- Scripts and native test programs came from the same pinned commit above.
44- LEONIDA_VK_DEVICE=4060 constrained device selection; nvidia-smi separately
45 reported the full card name, driver and VRAM listed above.
46- llvm-mc was not used; the selected pre-disassembled fixtures bypass that step.
47- The installed system Vulkan headers were used. No dependency fetch was enabled.
48- AI-assisted: setup guidance and report preparation. The hardware owner ran the
49 commands locally and supplied the test output and system metadata.
diff --git a/gpu-test-results/RTX4070.txt b/gpu-test-results/RTX4070.txt
new file mode 100644
index 000000000..26023a7fe
--- /dev/null
+++ b/gpu-test-results/RTX4070.txt
@@ -0,0 +1,24 @@
1GPU: NVIDIA GeForce RTX 4070 (Ada / AD104, PCI 10de:2786), subgroup 32..32
2Driver: NVIDIA 617.42 (proprietary, Windows), Vulkan SDK 1.4.363.0 (loader and validation tools)
3Subgroup: 32..32 (the run_gpu_tests.py device line shows subgroup 32..32)
4OS: Windows 11 Pro for Workstations 10.0.26300 (zh-CN)
5Commit: c023a365a93e5e3a75290ab70f68c8da4a227700 (main, 2026-11-24)
6Tools: llvm-mc 23.1.6 (conda llvm-tools with the AMDGPU target), SPIRV-Tools v2026.4,
7 CMake 3.31.6 + Ninja (Visual Studio 2022 Community, MSVC), Python 3.13.6
8run_gpu_tests.py: 257 shaders: 257 translated, 257 pass spirv-val
9 native: 197/248 passed, 49 skipped, 2 failed
10 LEONIDA_W64_EMULATE=1: 229/248 passed, 17 skipped, 2 failed
11Failed: cs_imgload_tfe, cs_imgload_d16_tfe (exit 1, native and emulated alike). These are the same
12 two that fail on the Radeon 780M (#31) and in the RTX 4070 Ti record, where the cause is the tfe
13 status VGPR being read but never written; the cause was not examined on this machine, and the
14 two were not rerun with #98 (SHADER-1266).
15Skipped: native: 31 "no 64-wide compute subgroup on this device" and 1 "no 64-wide subgroup on this
16 device" (the wave64 compute fixtures, which the emulated run runs), 1 "this device cannot
17 require a 64-wide fragment subgroup: subgroup 32..32" (ps_w64x_readlane, skipped in the
18 emulated run too), plus 16 "run by d3d12_*_test / w64_graphics.py" cases. Emulated: those 16
19 plus the 64-wide fragment one, 17 in all.
20Notes:
21- Built with scripts\build_runtime.ps1 (Ninja, RelWithDebInfo, MSVC) at the commit above; the tests ran
22 from runtime\build with --build runtime\build.
23- AI-assisted (Claude Code ran the build and tests; Codex, gpt-6.1-terra, checked this file against the
24 run output). No game files, nothing online.
diff --git a/gpu-test-results/RTX4080.txt b/gpu-test-results/RTX4080.txt
new file mode 100644
index 000000000..03bd1a49d
--- /dev/null
+++ b/gpu-test-results/RTX4080.txt
@@ -0,0 +1,29 @@
1GPU: NVIDIA GeForce RTX 4080 (Ada / AD103, PCI 10de:2704), subgroup 32..32
2Driver: NVIDIA 621.24 (proprietary), Vulkan 1.4.357
3Subgroup: 32..32 (minSubgroupSize 32, maxSubgroupSize 32)
4OS: Windows 11 Home, build 26300
5Commit: 71f99e2244b045c613cd669fac25104353034bc1 (main, 2026-11-24)
6Tools: llvm-mc 21.1.8 (native, built by scripts\build_llvm_mc.ps1), SPIRV-Tools v2026.4 (Vulkan SDK
7 1.4.363.0), CMake 3.31.6 + Ninja 1.12.1, MSVC 14.44.35207 (VS 2022 Build Tools 17.14,
8 Windows SDK 10.0.26100.0), Python 3.12.10
9run_gpu_tests.py: 261 shaders: 261 translated, 261 pass spirv-val
10 native: 203/252 passed, 49 skipped, 0 failed
11 LEONIDA_W64_EMULATE=1: 235/252 passed, 17 skipped, 0 failed
12Failed: none, in either run.
13Skipped: native: 31 "no 64-wide compute subgroup on this device", 1 "no 64-wide subgroup on this
14 device" and 1 "cannot require a 64-wide fragment subgroup" (the wave64 fixtures, which the
15 emulated run covers), plus the 16 "run by d3d12_*_test / w64_graphics.py" cases.
16 Emulated: the same 16, plus the 64-wide fragment one.
17History: the first record of this card, on d42773d0 (#541), had 2 failures in both runs,
18 cs_imgload_tfe and cs_imgload_d16_tfe ("r32 sint (sint view): 64 bad, texel(5,3) = 2071"):
19 197/248 native and 229/248 emulated. Both pass here, after #892. The same counts as
20 above were also measured on 3aa97542.
21Notes:
22- Built with scripts\build_runtime.ps1 (CMake + Ninja, RelWithDebInfo), with the Vulkan SDK's Bin
23 folder and llvm-mc on PATH so the llvm-mc / spirv-as / glslangValidator tests register.
24- Device picked with LEONIDA_VK_DEVICE=4080 (the machine also has an AMD Radeon integrated GPU,
25 PCI 1002:13c0); the run prints "device: NVIDIA GeForce RTX 4080 (subgroup 32..32)".
26- ctest, the D3D12 tests and w64_graphics.py were not run in this pass; this file covers
27 run_gpu_tests.py only, one run of each mode.
28- AI-assisted (Claude Code): built main and ran run_gpu_tests.py native and emulated. No game files,
29 nothing online.
diff --git a/gpu-test-results/RTX5090.txt b/gpu-test-results/RTX5090.txt
new file mode 100644
index 000000000..64720546f
--- /dev/null
+++ b/gpu-test-results/RTX5090.txt
@@ -0,0 +1,31 @@
1GPU: NVIDIA GeForce RTX 5090 (Blackwell / GB202), subgroup 32..32
2Driver: NVIDIA 621.24 (proprietary), Vulkan 1.4 (loader 1.4.363.1, Vulkan SDK)
3Subgroup: 32..32 (minSubgroupSize 32, maxSubgroupSize 32)
4OS: Windows 11 10.0.26300, 32,607 MiB of device memory
5Commit: 8f481cf16 (main, 2026-11-24)
6Tools: llvm-mc 23.1.6 (conda-forge llvm-tools, native AMDGPU target), SPIRV-Tools v2026.4,
7 CMake 3.31.6, Ninja, MSVC 14.44.35207 (VS 2022 Build Tools), Python 3.13.14
8run_gpu_tests.py: 257 shaders: 257 translated, 257 pass spirv-val
9 native: 197/248 passed, 49 skipped, 2 failed
10 LEONIDA_W64_EMULATE=1: 229/248 passed, 17 skipped, 2 failed
11Failed: cs_imgload_tfe, cs_imgload_d16_tfe (native and emulated alike): the tfe status VGPR is
12 read but never written, #31 - the same pair the RTX 4070 Ti record reports.
13Skipped: native: 31 "no 64-wide compute subgroup on this device", 1 "no 64-wide subgroup on this
14 device" and 1 "cannot require a 64-wide fragment subgroup" (the wave64 fixtures, which the
15 emulated run covers), plus the 16 documented "run by d3d12_*_test / w64_graphics.py" cases.
16 Emulated: the same 16, plus the 64-wide fragment one.
17Notes:
18- Built on Windows 11 with cmake -S runtime -B runtime/build -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo
19 -DLEONIDA_BUILD_WINDOWS_RUNTIME=OFF and cmake --build runtime/build. Only the vk_* programs were run
20 here; gta6rt and the shims need the retail package and are not part of this result.
21- llvm-mc is conda-forge's llvm-tools 23.1.6, the Windows build docs/testing.md names: the official
22 LLVM Windows release has no AMDGPU target.
23- The two "run by d3d12_*_test" failures at first were vk_bindless_test not built yet, not device
24 problems: after building that target, ps_imgatomic and ps_tex pass (12/12 in --filter ps_tex and
25 --filter ps_imgatomic).
26- No placed resources go through create_host_buffer in this suite, so the write-combined-page note
27 there is untouched by this run.
28- Nothing here quotes the executable or any other game file; the shaders are the synthetic RDNA2
29 programs in runtime/test/shaders.
30- AI-assisted (opencode): built the tree, ran run_gpu_tests.py native and with LEONIDA_W64_EMULATE=1,
31 and reran the bindless cases after building vk_bindless_test.
diff --git a/gpu-test-results/RX5700XT.txt b/gpu-test-results/RX5700XT.txt
new file mode 100644
index 000000000..987e08ff9
--- /dev/null
+++ b/gpu-test-results/RX5700XT.txt
@@ -0,0 +1,38 @@
1GPU: AMD Radeon RX 5700 XT (RDNA1 / GFX1010, Navi 10, PCI 1002:731f), subgroup 32..64
2Driver: AMD proprietary 26.11.2 (Windows 32.0.21045.29003, driverVersion 2.0.353),
3 Vulkan 1.4.315 (loader 1.4.309)
4Subgroup: 32..64 (minSubgroupSize 32, maxSubgroupSize 64; default 64, subgroupSizeControl,
5 one required size, compute-only)
6OS: Windows 11 Pro, 10.0.26200
7Commit: a0e187649e6f50a9a8ea61b3dc03974070359cb1 (main of the original repository, 2026-11-23)
8Tools: llvm-mingw 23.1.6 (clang 23.1.6), llvm-mc 23.1.6, SPIRV-Tools v2026.4,
9 CMake 4.4.5 with Ninja, Python 3.12
10run_gpu_tests.py: 247 fixtures: 246 translated, 246 pass spirv-val
11 native: 213/241 passed, 28 skipped, 0 failed
12 LEONIDA_W64_EMULATE=1: 213/241 passed, 28 skipped, 0 failed
13Skipped: 28 skips, all documented reasons:
14 6 no VK_EXT_mesh_shader on this device (RDNA1 does not expose it),
15 5 no VK_KHR_fragment_shader_barycentric (4 fixtures read BaryCoordKHR,
16 1 needs PerVertexKHR inputs),
17 1 needs a required 64-wide fragment subgroup; this device can require one size,
18 15 run by d3d12_*_test (m2_textured 4, m3_frame 4, buffer_uav 2, m4_compute 2,
19 translated_draw 2, m2_formats 1),
20 1 run by w64_graphics.py.
21Notes:
22- Built with cmake -S runtime -B runtime/build/vulkan -G Ninja -DCMAKE_BUILD_TYPE=Release
23 -DLEONIDA_BUILD_WINDOWS_RUNTIME=OFF and -DCMAKE_EXE_LINKER_FLAGS=-static with llvm-mingw.
24 Without -static every test binary exits 0xC0000135 (DLL not found) and the suite reports
25 0 passed, so a MinGW/LLVM build needs it.
26- Also run on this card: w64_graphics.py 29 fixtures: tier A 9 ok, tier B 8 ok, tier C 12
27 skipped (tier C needs a device that can require both 64 and 32, or W64G_REF), 0 failed;
28 vk_pipeline_check.py: 246 modules ok, 236 pipelines ok, 0 failed, 10 skipped (6 mesh,
29 4 barycentric), cs 113/113 (80 wave32, 33 wave64), vs 11/11, gs 1/1, ps 111/115.
30- The runtime ctest suite on this commit has one failure outside run_gpu_tests.py:
31 vk_queue_query_sync at `line 468: progress_loss_ok` (5/5 direct runs, 4/5 through ctest).
32 It is `completed_retire_ticket()` swallowing VK_ERROR_DEVICE_LOST; see the finding on the
33 coordination issue. Fixed by the old PR #6149's hunk (then 5/5 pass, full ctest 62/64,
34 0 failed, 2 skipped).
35- build.py and check.py (the two D3D12-side columns in the table) were not run on this
36 machine; the counts here come from run_gpu_tests.py, which builds and translates the same
37 fixtures.
38- AI-assisted (OpenCode). Synthetic tests only; no game files.
diff --git a/make_game.py b/make_game.py
index 6d3fbc43e..0f5c499cb 100644
--- a/make_game.py
+++ b/make_game.py
@@ -1341,14 +1341,42 @@ def shaders(game: str, work: str, jobs: int, emulate: bool = False, keep_emulate
1341 f.write(sources + "\n") 1341 f.write(sources + "\n")
1342 translate(disasm, spirv, jobs, emulate=emulate, fallbacks=fallbacks) 1342 translate(disasm, spirv, jobs, emulate=emulate, fallbacks=fallbacks)
1343 verify_translation_completeness(dxbc, spirv) 1343 verify_translation_completeness(dxbc, spirv)
1344 native_pso_hashes(dxbc, spirv)
1344 fspx_shaders(game, work, signature, emulate=emulate, fallbacks=fallbacks) 1345 fspx_shaders(game, work, signature, emulate=emulate, fallbacks=fallbacks)
1345 bvh_shaders(game, work, signature, jobs, emulate=emulate, fallbacks=fallbacks) 1346 bvh_shaders(game, work, signature, jobs, emulate=emulate, fallbacks=fallbacks)
1346 library_shaders(game, work, signature, jobs, emulate=emulate, fallbacks=fallbacks) 1347 library_shaders(game, work, signature, jobs, emulate=emulate, fallbacks=fallbacks)
1347 log("shaders: done") 1348 log("shaders: done")
1348 1349
1349 1350
1351def native_pso_hashes(dxbc: str, spirv: str) -> None:
1352 """Index the carved containers named by native graphics PSOs, including on a resumed translation."""
1353 import native_pso_hashes as tool
1354
1355 index = os.path.join(spirv, "index.json")
1356 if not os.path.isfile(index) or not os.path.isdir(dxbc):
1357 return
1358 output = os.path.join(spirv, tool.OUT_NAME)
1359 if os.path.isfile(output):
1360 stamp = os.stat(output).st_mtime_ns
1361 inputs = (index, dxbc, os.path.join(dxbc, "index.json"), tool.__file__,
1362 os.path.join(os.path.dirname(tool.__file__), "shader_carve.py"))
1363 if all(not os.path.exists(p) or os.stat(p).st_mtime_ns <= stamp for p in inputs):
1364 with os.scandir(dxbc) as files:
1365 if all(not f.name.endswith(".dxbc") or f.stat().st_mtime_ns <= stamp for f in files):
1366 return
1367 try:
1368 table = tool.build(dxbc, spirv)
1369 tool.write(spirv, table)
1370 except (OSError, ValueError) as error:
1371 fail(f"shaders: could not index native graphics pipelines: {error}")
1372 log(f"shaders: indexed {len(table)} native shader digests")
1373
1374
1350FSPX_DLL = "amd_fidelityfx_upscaler_xbox.dll" 1375FSPX_DLL = "amd_fidelityfx_upscaler_xbox.dll"
1351FSPX_TOOLS = ("fspx_unpack.py", "shader_disasm.py") # with TRANSLATION_SOURCES, what the FSPX outputs come from 1376# What the FSPX outputs come from, with TRANSLATION_SOURCES. fspx_unpack.py --disasm imports shader_disasm.py
1377# (tools/fspx_unpack.py:205), which decodes through rdna2_decode.py, its tables and mc_command.py: the listings these
1378# three produce are what rdna2spirv.py translates, so an edited decoder must rebuild the cache, not be reused from it.
1379FSPX_TOOLS = ("fspx_unpack.py", "shader_disasm.py", "rdna2_decode.py", "rdna2_isa_tables.py", "mc_command.py")
1352 1380
1353 1381
1354def file_sha256(path: str) -> str: 1382def file_sha256(path: str) -> str:
@@ -1424,7 +1452,11 @@ def fspx_shaders(game: str, work: str, mc_signature: str, emulate: bool = False,
1424 1452
1425 1453
1426LIBRARY_ARCHIVE = "shaders.rpf" 1454LIBRARY_ARCHIVE = "shaders.rpf"
1427LIBRARY_TOOLS = ("shader_library.py", "fspx_unpack.py", "shader_disasm.py") # with TRANSLATION_SOURCES 1455# With TRANSLATION_SOURCES, what the library's compute programs come from: shader_library.py carves with
1456# shader_carve.py (tools/shader_library.py:201) and unpacks/disassembles with fspx_unpack.py, so the decoder
1457# shader_disasm.py imports belongs here too (the same list as FSPX_TOOLS).
1458LIBRARY_TOOLS = ("shader_library.py", "shader_carve.py", "shader_carve_accel.py",
1459 "fspx_unpack.py", "shader_disasm.py", "rdna2_decode.py", "rdna2_isa_tables.py", "mc_command.py")
1428 1460
1429 1461
1430def library_settings(archive: str, mc_signature: str, emulate: bool, fallbacks: tuple[str, ...]) -> str: 1462def library_settings(archive: str, mc_signature: str, emulate: bool, fallbacks: tuple[str, ...]) -> str:
@@ -1527,7 +1559,8 @@ def fspx_key_clash(spirv: str):
1527 1559
1528 1560
1529BVH_DLL = "XboxBvhBuilder.dll" 1561BVH_DLL = "XboxBvhBuilder.dll"
1530BVH_TOOLS = ("pe_shader_containers.py", "fssm_unpack.py", "shader_disasm.py") # as FSPX_TOOLS, for the builder 1562BVH_TOOLS = ("pe_shader_containers.py", "fssm_unpack.py", "shader_disasm.py", # as FSPX_TOOLS, for the builder:
1563 "rdna2_decode.py", "rdna2_isa_tables.py", "mc_command.py") # what shader_disasm.py decodes with
1531# rdna2spirv.py's --max-shared-memory for the builder's programs: 32768, the maxComputeSharedMemorySize of the AMD 1564# rdna2spirv.py's --max-shared-memory for the builder's programs: 32768, the maxComputeSharedMemorySize of the AMD
1532# Windows and Intel drivers (docs/design.md, "Workgroup memory limit"). The constructor creates a pipeline for every 1565# Windows and Intel drivers (docs/design.md, "Workgroup memory limit"). The constructor creates a pipeline for every
1533# program and gives up at the first one that fails, so one module over the device's limit costs the whole builder. 1566# program and gives up at the first one that fails, so one module over the device's limit costs the whole builder.
@@ -1805,11 +1838,12 @@ def runtime_gpu_max_push_constants():
1805 return int(v) if isinstance(v, int) and not isinstance(v, bool) and v > 0 else None 1838 return int(v) if isinstance(v, int) and not isinstance(v, bool) and v > 0 else None
1806 1839
1807 1840
1808# Source and data files that produce the translated modules, metadata and partner stubs. 1841# Source and data files that produce the translated modules, metadata, partner stubs and native PSO catalog.
1809TRANSLATION_SOURCES = ("rdna2spirv.py", "shader_ir.py", "cfg_structure.py", "file_mode.py", "fssm_header.py", "lane_masks.py", "wave64_halves.py", 1842TRANSLATION_SOURCES = ("rdna2spirv.py", "shader_ir.py", "cfg_structure.py", "file_mode.py", "fssm_header.py", "lane_masks.py", "wave64_halves.py",
1810 "wave64_emulate_opt.py", "shader_meta.py", "spirv_stubs.py", "spirv_asm.py", "spirv_asm_tables.py", 1843 "wave64_emulate_opt.py", "shader_meta.py", "spirv_stubs.py", "spirv_asm.py", "spirv_asm_tables.py",
1811 "spirv_opt.py", "report_paths.py", "replace_retry.py", "fssm_unpack.py", "shader_stage_manifest.py", 1844 "spirv_opt.py", "report_paths.py", "replace_retry.py", "fssm_unpack.py", "shader_stage_manifest.py",
1812 "rdna2_decode.py", "rdna2_isa_tables.py", "gfx10_formats.json") 1845 "rdna2_decode.py", "rdna2_isa_tables.py", "gfx10_formats.json",
1846 "native_pso_hashes.py", "shader_carve.py", "shader_carve_accel.py")
1813 1847
1814 1848
1815def sources_digest(folder: str, names, lead: str = "") -> str: 1849def sources_digest(folder: str, names, lead: str = "") -> str:
diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt
index 64e346f40..e1dc13772 100644
--- a/runtime/CMakeLists.txt
+++ b/runtime/CMakeLists.txt
@@ -106,6 +106,46 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME)
106 MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>" 106 MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>"
107 ) 107 )
108 108
109 # Rust XMA2 decoder (runtime/xma_decoder), built at configure time when cargo is on PATH.
110 # Without it (or if that build fails) the runtime still builds and XMA voices output silence.
111 option(LEONIDA_REQUIRE_XMA2_DECODER "Fail configure if the Rust XMA2 decoder is unavailable" OFF)
112 find_program(LEONIDA_CARGO cargo)
113 if(LEONIDA_CARGO)
114 # Cargo's host (or configured default target) can differ from the runtime's MSVC ABI.
115 set(_xma_target x86_64-pc-windows-msvc)
116 set(_xma_target_dir ${CMAKE_BINARY_DIR}/xma_decoder)
117 set(_xma_lib ${_xma_target_dir}/${_xma_target}/release/leonida_xma2_decoder.lib)
118 set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS
119 ${CMAKE_CURRENT_SOURCE_DIR}/xma_decoder/Cargo.toml
120 ${CMAKE_CURRENT_SOURCE_DIR}/xma_decoder/Cargo.lock
121 ${CMAKE_CURRENT_SOURCE_DIR}/xma_decoder/src/lib.rs)
122 execute_process(
123 COMMAND ${LEONIDA_CARGO} build --release --locked --target ${_xma_target}
124 --manifest-path ${CMAKE_CURRENT_SOURCE_DIR}/xma_decoder/Cargo.toml
125 --target-dir ${_xma_target_dir}
126 TIMEOUT 120
127 RESULT_VARIABLE _xma_result)
128 if(_xma_result STREQUAL "0" AND EXISTS ${_xma_lib})
129 add_library(leonida_xma2_decoder STATIC IMPORTED)
130 # Link Rust's Windows SDK dependencies. CMake's C++ target selects its own CRT
131 # (/MD or /MDd); the C ABI keeps allocation and deallocation on the same side.
132 # synchronization: Rust's std imports WaitOnAddress and WakeByAddress*, which MSVC's
133 # default libraries cover but clang-cl with an xwin SDK does not (lld-link: undefined symbol).
134 set_target_properties(leonida_xma2_decoder PROPERTIES
135 IMPORTED_LOCATION ${_xma_lib}
136 INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_CURRENT_SOURCE_DIR}/xma_decoder
137 INTERFACE_COMPILE_DEFINITIONS LEONIDA_HAVE_XMA2_DECODER=1
138 INTERFACE_LINK_LIBRARIES "kernel32;ntdll;userenv;ws2_32;dbghelp;synchronization")
139 else()
140 message(WARNING "cargo build of runtime/xma_decoder failed: XMA voices will be silent")
141 endif()
142 else()
143 message(STATUS "cargo not found: runtime/xma_decoder not built, XMA voices will be silent")
144 endif()
145 if(LEONIDA_REQUIRE_XMA2_DECODER AND NOT TARGET leonida_xma2_decoder)
146 message(FATAL_ERROR "LEONIDA_REQUIRE_XMA2_DECODER is enabled, but the Rust XMA2 decoder is unavailable")
147 endif()
148
109 add_executable(gta6rt 149 add_executable(gta6rt
110 src/main.cpp 150 src/main.cpp
111 src/host_cpu.cpp 151 src/host_cpu.cpp
@@ -113,6 +153,7 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME)
113 shims/registry.cpp 153 shims/registry.cpp
114 shims/file_system.cpp 154 shims/file_system.cpp
115 shims/winhttp_offline.cpp 155 shims/winhttp_offline.cpp
156 shims/ws2_offline.cpp
116 shims/xmem.cpp 157 shims/xmem.cpp
117 shims/xg_xs.cpp 158 shims/xg_xs.cpp
118 shims/acphal.cpp 159 shims/acphal.cpp
@@ -250,6 +291,11 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME)
250 target_compile_options(acphal_test PRIVATE /W4 /permissive- /utf-8) 291 target_compile_options(acphal_test PRIVATE /W4 /permissive- /utf-8)
251 target_link_options(acphal_test PRIVATE /OPT:NOREF) 292 target_link_options(acphal_test PRIVATE /OPT:NOREF)
252 293
294 if(TARGET leonida_xma2_decoder)
295 target_link_libraries(gta6rt PRIVATE leonida_xma2_decoder)
296 target_link_libraries(acphal_test PRIVATE leonida_xma2_decoder)
297 endif()
298
253 # The Zen 2 instructions a desktop CPU may lack (src/cpu_emulation.h): decoded, emulated on a CONTEXT, and run for 299 # The Zen 2 instructions a desktop CPU may lack (src/cpu_emulation.h): decoded, emulated on a CONTEXT, and run for
254 # real with the #UD handler installed, so an Intel host takes the emulated path and an AMD one the native path. 300 # real with the #UD handler installed, so an Intel host takes the emulated path and an AMD one the native path.
255 add_executable(cpu_emulation_test test/cpu_emulation_test.cpp) 301 add_executable(cpu_emulation_test test/cpu_emulation_test.cpp)
@@ -326,6 +372,18 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME)
326 target_compile_options(winhttp_offline_test PRIVATE /W4 /permissive- /utf-8) 372 target_compile_options(winhttp_offline_test PRIVATE /W4 /permissive- /utf-8)
327 target_link_options(winhttp_offline_test PRIVATE /OPT:NOREF) 373 target_link_options(winhttp_offline_test PRIVATE /OPT:NOREF)
328 374
375 # Offline Winsock2 for mapped images (ws2_32.dll restricted to loopback); no external network is touched.
376 add_executable(ws2_offline_test
377 test/ws2_offline_test.cpp
378 shims/ws2_offline.cpp
379 shims/registry.cpp
380 )
381 target_include_directories(ws2_offline_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims)
382 target_compile_definitions(ws2_offline_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
383 target_compile_options(ws2_offline_test PRIVATE /W4 /permissive- /utf-8)
384 target_link_options(ws2_offline_test PRIVATE /OPT:NOREF)
385 target_link_libraries(ws2_offline_test PRIVATE ws2_32)
386
329 # COM lifecycle and helper shims for api-ms-win-core-com-l1-1-*.dll. 387 # COM lifecycle and helper shims for api-ms-win-core-com-l1-1-*.dll.
330 add_executable(com_shim_test 388 add_executable(com_shim_test
331 test/com_shim_test.cpp 389 test/com_shim_test.cpp
@@ -577,6 +635,10 @@ if(BUILD_TESTING)
577 target_link_options(loader_test PRIVATE /OPT:NOREF ${GTA6RT_HOST_BASE}) 635 target_link_options(loader_test PRIVATE /OPT:NOREF ${GTA6RT_HOST_BASE})
578 add_dependencies(loader_test gta6rt_tls_host) 636 add_dependencies(loader_test gta6rt_tls_host)
579 add_test(NAME loader COMMAND loader_test) 637 add_test(NAME loader COMMAND loader_test)
638 # It takes about 10 s under Wine and under a minute on a desktop with a virus scanner. Before #239 it waited on
639 # a "Bad Image" box on the Windows runner until the job's own timeout cancelled the whole job (every Windows
640 # run from 24 Nov 00:37 to 03:32 UTC); a hang like that now fails this test instead.
641 set_tests_properties(loader PROPERTIES TIMEOUT 180)
580 # PE loader tests use two locally built fixtures: a DLL with exports, imports and relocations, and an EXE that 642 # PE loader tests use two locally built fixtures: a DLL with exports, imports and relocations, and an EXE that
581 # imports it so Loader::load exercises recursive module loading. They contain no game data. 643 # imports it so Loader::load exercises recursive module loading. They contain no game data.
582 set(TINY_FIXTURE_DIR "${CMAKE_CURRENT_BINARY_DIR}/fixtures/$<CONFIG>") 644 set(TINY_FIXTURE_DIR "${CMAKE_CURRENT_BINARY_DIR}/fixtures/$<CONFIG>")
@@ -610,6 +672,8 @@ if(BUILD_TESTING)
610 add_executable(tiny_ga_tls test/fixtures/tiny_ga_tls.cpp) 672 add_executable(tiny_ga_tls test/fixtures/tiny_ga_tls.cpp)
611 target_compile_definitions(tiny_ga_tls PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) 673 target_compile_definitions(tiny_ga_tls PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
612 target_compile_options(tiny_ga_tls PRIVATE /W4 /permissive- /utf-8 /GS- /GA) 674 target_compile_options(tiny_ga_tls PRIVATE /W4 /permissive- /utf-8 /GS- /GA)
675 # /GA can remove the _tls_index reference that pulls in the CRT TLS directory.
676 target_link_options(tiny_ga_tls PRIVATE /INCLUDE:_tls_used)
613 set_target_properties(tiny_ga_tls PROPERTIES 677 set_target_properties(tiny_ga_tls PROPERTIES
614 OUTPUT_NAME tiny_ga_tls 678 OUTPUT_NAME tiny_ga_tls
615 RUNTIME_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" 679 RUNTIME_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}"
@@ -1162,6 +1226,7 @@ if(BUILD_TESTING)
1162 endif() 1226 endif()
1163 if(WIN32 AND TARGET acphal_test) 1227 if(WIN32 AND TARGET acphal_test)
1164 add_test(NAME acphal COMMAND acphal_test) 1228 add_test(NAME acphal COMMAND acphal_test)
1229 add_test(NAME acphal_noncached_only COMMAND acphal_test --noncached-only)
1165 endif() 1230 endif()
1166 if(WIN32 AND TARGET cpu_emulation_test) 1231 if(WIN32 AND TARGET cpu_emulation_test)
1167 add_test(NAME cpu_emulation COMMAND cpu_emulation_test) 1232 add_test(NAME cpu_emulation COMMAND cpu_emulation_test)
@@ -1181,6 +1246,9 @@ if(BUILD_TESTING)
1181 if(WIN32 AND TARGET winhttp_offline_test) 1246 if(WIN32 AND TARGET winhttp_offline_test)
1182 add_test(NAME winhttp_offline COMMAND winhttp_offline_test) 1247 add_test(NAME winhttp_offline COMMAND winhttp_offline_test)
1183 endif() 1248 endif()
1249 if(WIN32 AND TARGET ws2_offline_test)
1250 add_test(NAME ws2_offline COMMAND ws2_offline_test)
1251 endif()
1184 if(WIN32 AND TARGET com_shim_test) 1252 if(WIN32 AND TARGET com_shim_test)
1185 add_test(NAME com_shim COMMAND com_shim_test) 1253 add_test(NAME com_shim COMMAND com_shim_test)
1186 endif() 1254 endif()
@@ -1411,6 +1479,11 @@ if(TARGET Vulkan::Headers)
1411 add_executable(vk_shader_fma_test test/vk_shader_fma_test.cpp) 1479 add_executable(vk_shader_fma_test test/vk_shader_fma_test.cpp)
1412 target_link_libraries(vk_shader_fma_test PRIVATE Vulkan::Headers) 1480 target_link_libraries(vk_shader_fma_test PRIVATE Vulkan::Headers)
1413 add_test(NAME vk_shader_fma COMMAND vk_shader_fma_test) 1481 add_test(NAME vk_shader_fma COMMAND vk_shader_fma_test)
1482 add_executable(xdxr_builder_validation_test test/xdxr_builder_validation_test.cpp)
1483 target_link_libraries(xdxr_builder_validation_test PRIVATE Vulkan::Headers)
1484 if(BUILD_TESTING)
1485 add_test(NAME xdxr_builder_validation COMMAND xdxr_builder_validation_test)
1486 endif()
1414 # LEONIDA_VK_DEVICE names the GPU in every harness (docs/testing.md, "Choosing the GPU"): a filter that matches no 1487 # LEONIDA_VK_DEVICE names the GPU in every harness (docs/testing.md, "Choosing the GPU"): a filter that matches no
1415 # device fails the run in vk_descriptor_bench and vk_sandbox too, instead of testing another GPU (TEST-1141). 1488 # device fails the run in vk_descriptor_bench and vk_sandbox too, instead of testing another GPU (TEST-1141).
1416 find_package(Python3 COMPONENTS Interpreter QUIET) 1489 find_package(Python3 COMPONENTS Interpreter QUIET)
@@ -1611,6 +1684,18 @@ if(TARGET Vulkan::Headers)
1611 if(BUILD_TESTING) 1684 if(BUILD_TESTING)
1612 add_test(NAME vk_buffer_registration_oom COMMAND vk_buffer_registration_oom_test) 1685 add_test(NAME vk_buffer_registration_oom COMMAND vk_buffer_registration_oom_test)
1613 endif() 1686 endif()
1687 # VulkanContext::replay_.host_at resolves aliasing placed upload buffers across the full requested byte range.
1688 add_executable(vk_host_at_aliasing_test test/vk_host_at_aliasing_test.cpp)
1689 target_link_libraries(vk_host_at_aliasing_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS})
1690 if(WIN32)
1691 target_compile_definitions(vk_host_at_aliasing_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
1692 if(MSVC)
1693 target_compile_options(vk_host_at_aliasing_test PRIVATE /W4 /permissive- /EHsc /utf-8)
1694 endif()
1695 endif()
1696 if(BUILD_TESTING)
1697 add_test(NAME vk_host_at_aliasing COMMAND vk_host_at_aliasing_test)
1698 endif()
1614 # CPU-only: ScratchBuffers chunk alignment, retire/collect/forget, and spare cap (runtime/src/vulkan_scratch.h). 1699 # CPU-only: ScratchBuffers chunk alignment, retire/collect/forget, and spare cap (runtime/src/vulkan_scratch.h).
1615 add_executable(vulkan_scratch_test test/vulkan_scratch_test.cpp) 1700 add_executable(vulkan_scratch_test test/vulkan_scratch_test.cpp)
1616 target_link_libraries(vulkan_scratch_test PRIVATE Vulkan::Headers) 1701 target_link_libraries(vulkan_scratch_test PRIVATE Vulkan::Headers)
@@ -2181,7 +2266,8 @@ if(TARGET Vulkan::Headers)
2181 add_test(NAME d3d12_rgb9e5_rtv COMMAND d3d12_clear_test --rgb9e5) 2266 add_test(NAME d3d12_rgb9e5_rtv COMMAND d3d12_clear_test --rgb9e5)
2182 set_tests_properties(d3d12_rgb9e5_rtv PROPERTIES SKIP_RETURN_CODE 77) 2267 set_tests_properties(d3d12_rgb9e5_rtv PROPERTIES SKIP_RETURN_CODE 77)
2183 add_test(NAME d3d12_clear COMMAND d3d12_clear_test) 2268 add_test(NAME d3d12_clear COMMAND d3d12_clear_test)
2184 set_tests_properties(d3d12_clear PROPERTIES SKIP_RETURN_CODE 77) 2269 add_test(NAME d3d12_clear_restricted_depth COMMAND d3d12_clear_test --restricted-depth)
2270 set_tests_properties(d3d12_clear d3d12_clear_restricted_depth PROPERTIES SKIP_RETURN_CODE 77)
2185 2271
2186 # Synthetic typed-view readbacks against Windows WARP; run explicitly on a Vulkan GPU. 2272 # Synthetic typed-view readbacks against Windows WARP; run explicitly on a Vulkan GPU.
2187 add_executable(d3d12_typeless_rtv_test test/d3d12_typeless_rtv_test.cpp) 2273 add_executable(d3d12_typeless_rtv_test test/d3d12_typeless_rtv_test.cpp)
diff --git a/runtime/cmake/translator_deps.cmake b/runtime/cmake/translator_deps.cmake
index 3565fe1e2..42be0f0e2 100644
--- a/runtime/cmake/translator_deps.cmake
+++ b/runtime/cmake/translator_deps.cmake
@@ -1,6 +1,6 @@
1# What the SPIR-V that test/shaders/build.py writes comes from, besides the .asm files: build.py and the modules it 1# The shader fixtures use test/shaders/build.py, its local imports and the scripts it runs (tools/rdna2spirv.py
2# imports, the scripts it runs (tools/rdna2spirv.py, and tools/vk_subgroup_info.py, whose answer picks 2# and tools/vk_subgroup_info.py, whose answer picks --bary-fallback). Track the shader-stage dependencies in
3# --bary-fallback), and every module rdna2spirv.py imports or file it reads (make_game.py's TRANSLATION_SOURCES). 3# make_game.py's TRANSLATION_SOURCES here too, including the native PSO catalog writer.
4# Every add_custom_command that runs build.py DEPENDS on this list, so an edit to a helper such as tools/spirv_asm.py 4# Every add_custom_command that runs build.py DEPENDS on this list, so an edit to a helper such as tools/spirv_asm.py
5# rebuilds the test shaders instead of leaving the last build's SPIR-V in place (BUILD-1064). 5# rebuilds the test shaders instead of leaving the last build's SPIR-V in place (BUILD-1064).
6# tests/test_cmake_translator_deps.py fails when an import is missing here or a build.py rule doesn't use the list. 6# tests/test_cmake_translator_deps.py fails when an import is missing here or a build.py rule doesn't use the list.
@@ -16,11 +16,14 @@ set(LEONIDA_TRANSLATOR_DEPS
16 ${_leonida_repo}/tools/gfx10_formats.json 16 ${_leonida_repo}/tools/gfx10_formats.json
17 ${_leonida_repo}/tools/lane_masks.py 17 ${_leonida_repo}/tools/lane_masks.py
18 ${_leonida_repo}/tools/mc_command.py 18 ${_leonida_repo}/tools/mc_command.py
19 ${_leonida_repo}/tools/native_pso_hashes.py
19 ${_leonida_repo}/tools/rdna2_decode.py 20 ${_leonida_repo}/tools/rdna2_decode.py
20 ${_leonida_repo}/tools/rdna2_isa_tables.py 21 ${_leonida_repo}/tools/rdna2_isa_tables.py
21 ${_leonida_repo}/tools/rdna2spirv.py 22 ${_leonida_repo}/tools/rdna2spirv.py
22 ${_leonida_repo}/tools/replace_retry.py 23 ${_leonida_repo}/tools/replace_retry.py
23 ${_leonida_repo}/tools/report_paths.py 24 ${_leonida_repo}/tools/report_paths.py
25 ${_leonida_repo}/tools/shader_carve.py
26 ${_leonida_repo}/tools/shader_carve_accel.py
24 ${_leonida_repo}/tools/shader_ir.py 27 ${_leonida_repo}/tools/shader_ir.py
25 ${_leonida_repo}/tools/shader_meta.py 28 ${_leonida_repo}/tools/shader_meta.py
26 ${_leonida_repo}/tools/shader_stage_manifest.py 29 ${_leonida_repo}/tools/shader_stage_manifest.py
diff --git a/runtime/shims/acphal.cpp b/runtime/shims/acphal.cpp
index 5ead016d6..f1c33ddd9 100644
--- a/runtime/shims/acphal.cpp
+++ b/runtime/shims/acphal.cpp
@@ -1,10 +1,12 @@
1// acphal.dll: Audio Control Processor HAL. Scalable Hardware Audio Processing Engine 1// acphal.dll: Audio Control Processor HAL. Scalable Hardware Audio Processing Engine
2// (SHAPE) and APU (Audio Processing Unit) physical memory management for Xbox Series. 2// (SHAPE) and APU (Audio Processing Unit) physical memory management for Xbox Series.
3// 3//
4// On a PC there is no SHAPE/ACP hardware and APU physical memory does not exist. 4// Provides:
5// This shim creates the APU heap from process memory and manages allocations within it. 5// - A VirtualAlloc-backed APU heap (cached + non-cached) with 32-bit device addresses;
6// The SHAPE context arrays are allocated on the process heap; the ACP interface 6// - SHAPE context arrays sized to the documented GDK strides;
7// accepts and acknowledges commands to allow audio bring-up to proceed cleanly. 7// - The IAcpHal command and message queue (registration, completion, disconnect,
8// flowgraph acknowledgement, and APU notification word writes);
9// - A background XMA2 decoder pumping enabled SHAPE_XMA_CONTEXT output rings.
8// 10//
9// Signatures from the public GDK reference (devdocs.xbox.com): 11// Signatures from the public GDK reference (devdocs.xbox.com):
10// AcpHal, APU reference, SHAPE_CONTEXTS, APU_ADDRESS. 12// AcpHal, APU reference, SHAPE_CONTEXTS, APU_ADDRESS.
@@ -14,21 +16,37 @@
14 16
15#include <windows.h> 17#include <windows.h>
16 18
17#include <atomic> 19#include <algorithm>
18#include <array> 20#include <array>
21#include <atomic>
22#include <chrono>
23#include <climits>
24#include <condition_variable>
19#include <cstddef> 25#include <cstddef>
20#include <cstdint> 26#include <cstdint>
21#include <cstdio> 27#include <cstdio>
22#include <cstdlib> 28#include <cstdlib>
23#include <cstring> 29#include <cstring>
30#include <deque>
24#include <map> 31#include <map>
32#include <memory>
25#include <mutex> 33#include <mutex>
34#include <new>
35#include <optional>
26#include <set> 36#include <set>
37#include <shared_mutex>
38#include <stop_token>
27#include <string> 39#include <string>
40#include <string_view>
41#include <system_error>
42#include <thread>
28#include <vector> 43#include <vector>
29 44
30#include "shims.h" 45#include "shims.h"
31#include "startup_trace.h" 46#include "startup_trace.h"
47#if defined(LEONIDA_HAVE_XMA2_DECODER)
48#include "leonida_xma2_decoder.h"
49#endif
32 50
33namespace { 51namespace {
34 52
@@ -124,24 +142,7 @@ struct SHAPE_DMA_CONTEXT {
124static_assert(sizeof(SHAPE_DMA_CONTEXT) == 16, "SHAPE_DMA_CONTEXT is 16 bytes per GDK"); 142static_assert(sizeof(SHAPE_DMA_CONTEXT) == 16, "SHAPE_DMA_CONTEXT is 16 bytes per GDK");
125 143
126struct SHAPE_XMA_CONTEXT { 144struct SHAPE_XMA_CONTEXT {
127 uint32_t sizeRead0 : 12; 145 uint32_t words[16]; // See the shared word layout above the XMA engine.
128 uint32_t numLoops : 8;
129 uint32_t validBuffer : 2;
130 uint32_t sizeWrite : 5;
131 uint32_t offsetWrite : 5;
132 uint32_t sizeRead1 : 12;
133 uint32_t sequenceNumber : 12;
134 uint32_t stopSampleAddress : 8;
135 uint32_t subframeOffset : 4;
136 uint32_t reserved0 : 1;
137 uint32_t isLooping : 1;
138 uint32_t subframeSkip : 2;
139 uint32_t packetMetadata : 16;
140 uint32_t currentByteOffset : 26;
141 uint32_t reserved1 : 6;
142 uint32_t loopStartOffset : 26;
143 uint32_t loopEndOffset : 6;
144 uint32_t reserved[11]; // the GDK's 64-byte context: the published field list leaves one trailing word
145}; 146};
146static_assert(sizeof(SHAPE_XMA_CONTEXT) == 64, "SHAPE_XMA_CONTEXT is 64 bytes per GDK"); 147static_assert(sizeof(SHAPE_XMA_CONTEXT) == 64, "SHAPE_XMA_CONTEXT is 64 bytes per GDK");
147 148
@@ -194,21 +195,28 @@ static_assert(offsetof(SHAPE_CONTEXTS, xmaContextArray) == 0x38,
194 195
195// ---- Startup trace helper ---- 196// ---- Startup trace helper ----
196 197
197void trace_call(const char* api, const std::string& detail) { 198void trace_call(const char* api, std::string_view detail = {}) noexcept try {
198 if (!rt::startup_trace::enabled()) return; 199 if (!rt::startup_trace::enabled()) return;
199 static std::mutex mutex; 200 static std::mutex mutex;
200 static std::set<std::string> seen; 201 static std::set<std::string> seen;
201 { 202 {
202 const std::lock_guard lock(mutex); 203 const std::lock_guard lock(mutex);
203 if (!seen.insert(std::string(api) + detail).second) return; 204 if (!seen.insert(std::string(api).append(detail)).second) return;
204 } 205 }
205 rt::startup_trace::event("acphal", 206 rt::startup_trace::event("acphal",
206 std::string("\"api\":\"") + api + "\"" + detail); 207 (std::string("\"api\":\"") + api + "\"").append(detail));
208} catch (...) {
209 // Tracing cannot change the result of a guest-facing call.
207} 210}
208 211
209// ---- Genuine APU Heap Implementation ---- 212// ---- Genuine APU Heap Implementation ----
210 213
211constexpr uint32_t kApuBaseAddress = 0x40000000u; 214constexpr uint32_t kApuBaseAddress = 0x40000000u;
215constexpr uint64_t kApuRegionAlignment = 0x10000u;
216
217uint64_t align_apu_region(uint64_t size) {
218 return (size + kApuRegionAlignment - 1) & ~(kApuRegionAlignment - 1);
219}
212 220
213struct ApuRegion { 221struct ApuRegion {
214 void* base = nullptr; 222 void* base = nullptr;
@@ -241,6 +249,13 @@ struct ApuRegion {
241 return static_cast<uint8_t*>(base) + offset; 249 return static_cast<uint8_t*>(base) + offset;
242 } 250 }
243 251
252 uint8_t* span_from_offset(uint32_t offset, std::size_t len) const {
253 if (!base || len == 0 || offset >= size) return nullptr;
254 const uint64_t remaining = size - offset;
255 if (len > remaining) return nullptr;
256 return static_cast<uint8_t*>(base) + offset;
257 }
258
244 void* allocate(uint32_t alloc_size, uint32_t alignment, uint32_t* out_offset) { 259 void* allocate(uint32_t alloc_size, uint32_t alignment, uint32_t* out_offset) {
245 if (alloc_size == 0 || alignment == 0) return nullptr; 260 if (alloc_size == 0 || alignment == 0) return nullptr;
246 uint64_t at = 0; 261 uint64_t at = 0;
@@ -281,48 +296,667 @@ ApuRegion g_cached_heap;
281ApuRegion g_noncached_heap; 296ApuRegion g_noncached_heap;
282 297
283// Tracked SHAPE context arrays 298// Tracked SHAPE context arrays
284std::vector<void*> g_active_shape_arrays; 299struct ShapeArrayFree {
300 void operator()(void* array) const noexcept { std::free(array); }
301};
302
303using ShapeAllocation = std::array<std::unique_ptr<void, ShapeArrayFree>, 6>;
304
305std::mutex g_shape_mutex;
306std::vector<ShapeAllocation> g_shape_allocations;
307
308// Resolves a contiguous [apu, apu + len) byte range inside the APU heap.
309uint8_t* apu_span(uint32_t apu, std::size_t len) {
310 if (apu < kApuBaseAddress || len == 0) return nullptr;
311 std::lock_guard lock(g_apu_mutex);
312 const uint32_t offset = apu - kApuBaseAddress;
313 if (g_cached_heap.base && offset < g_cached_heap.size) {
314 return g_cached_heap.span_from_offset(offset, len);
315 }
316 if (g_noncached_heap.base) {
317 const uint64_t cached_span = align_apu_region(g_cached_heap.size);
318 if (offset >= cached_span && offset - cached_span < g_noncached_heap.size) {
319 return g_noncached_heap.span_from_offset(
320 static_cast<uint32_t>(offset - cached_span), len);
321 }
322 }
323 return nullptr;
324}
325
326// ---- ACP Command / Message Protocol Constants ----
327
328constexpr uint32_t kCmdLoadFlowgraph = 1;
329constexpr uint32_t kCmdRegisterMessages = 2;
330constexpr uint32_t kCmdUnregisterMessages = 3;
331constexpr uint32_t kCmdEnableXma = 5;
332constexpr uint32_t kCmdEnableXmas = 6;
333constexpr uint32_t kCmdDisableXma = 7;
334constexpr uint32_t kCmdDisableXmas = 8;
335constexpr uint32_t kCmdAdvanceXmaRead = 18;
336
337constexpr uint32_t kMsgFlowgraphCompleted = 0x02u;
338constexpr uint32_t kMsgCommandCompleted = 0x10u;
339constexpr uint32_t kMsgDisconnected = 0x80u;
340
341// 128 samples per audio frame at 48 kHz = 375 audio frames/second.
342constexpr uint64_t kAudioFramesPerSecond = 375;
343
344// ---- XMA2 Hardware Context Decoder Engine ----
345//
346// Each 64-byte SHAPE_XMA_CONTEXT holds 16 32-bit words shared with the title:
347// Word 0: input 0 packets (0..11), loop count (12..19, 255 = forever),
348// valid input bits (20..21), output ring blocks (22..26), write block (27..31).
349// Word 1: input 1 packets (0..11), loop end subframe (12..13), loop start skip subframes
350// (17..19), initial skip subframes (24..26), rate index (27..28: 24/32/44.1/48 kHz),
351// stereo (29), output writable (31).
352// Word 2: read bit offset (0..25), error status (26..30), error flag (31).
353// Word 3: loop start bit offset (0..25).
354// Word 4: loop end bit offset (0..25), current input buffer index (31).
355// Word 5: input 0 APU address.
356// Word 6: input 1 APU address.
357// Word 7: output ring APU address.
358// Word 8: overlap buffer APU address.
359// Word 9: output read block index (0..4).
360//
361// Packets are decoded by the Rust decoder in runtime/xma_decoder when CMake found cargo (LEONIDA_HAVE_XMA2_DECODER);
362// otherwise each packet becomes silence for its frame count. The read offset (word 2) and the loop points (words 3
363// and 4) are used per 2048-byte packet, so the loop-end subframe (word 1 bits 12..13) is not applied.
364
365constexpr std::size_t kXmaBlockBytes = 256;
366constexpr std::size_t kXmaSamplesPerBlock = kXmaBlockBytes / 2;
367constexpr std::size_t kXmaPacketBytes = 2048;
368constexpr std::size_t kXmaPacketBits = kXmaPacketBytes * 8;
369constexpr std::size_t kXmaSubframeSamples = 128;
370constexpr std::size_t kXmaFrameSamples = 512;
371constexpr uint32_t kXmaErrorInputInvalid = 4;
372
373#if defined(LEONIDA_HAVE_XMA2_DECODER)
374constexpr uint32_t kXmaRates[4] = {24000, 32000, 44100, 48000};
375struct Xma2DecoderFree {
376 void operator()(LeonidaXma2Decoder* d) const noexcept { leonida_xma2_decoder_destroy(d); }
377};
378struct Xma2PcmFree {
379 void operator()(LeonidaXma2PcmBlock* b) const noexcept { leonida_xma2_pcm_destroy(b); }
380};
381#endif
382
383struct XmaContextView {
384 uint32_t* words = nullptr;
385
386 uint32_t get(std::size_t index) const { return std::atomic_ref(words[index]).load(); }
387
388 uint32_t field(std::size_t index, uint32_t shift, uint32_t bits) const {
389 const uint32_t mask = (bits >= 32) ? 0xFFFFFFFFu : ((1u << bits) - 1u);
390 return (get(index) >> shift) & mask;
391 }
392
393 uint32_t set_field(std::size_t index, uint32_t shift, uint32_t bits, uint32_t value) const {
394 const uint32_t raw_mask = (bits >= 32) ? 0xFFFFFFFFu : ((1u << bits) - 1u);
395 const uint32_t mask = raw_mask << shift;
396 const uint32_t field_value = (value << shift) & mask;
397 std::atomic_ref word(words[index]);
398 uint32_t previous = word.load();
399 while (!word.compare_exchange_weak(previous, (previous & ~mask) | field_value)) {}
400 return previous;
401 }
402
403};
404
405struct XmaVoice {
406 explicit XmaVoice(uint32_t format_bits) : pcm(0), format(format_bits) {}
407 std::size_t channels() const { return 1u + (format >> 2); }
408 std::size_t queued_samples() const { return pcm.size() - pcm_read; }
409
410#if defined(LEONIDA_HAVE_XMA2_DECODER)
411 std::unique_ptr<LeonidaXma2Decoder, Xma2DecoderFree> decoder;
412#endif
413 std::vector<int16_t> pcm;
414 std::size_t pcm_read = 0;
415 std::size_t loop_skip = 0; // samples per channel to drop after a rewind
416 uint32_t format; // SHAPE word 1 bits 27..29, rate and channel layout
417 bool ended = false;
418};
419
420struct XmaVoiceSlot {
421 std::mutex mutex;
422 std::optional<XmaVoice> voice;
423};
424
425class XmaEngine {
426public:
427 ~XmaEngine() { unbind(); }
428
429 void bind(SHAPE_XMA_CONTEXT* array, uint32_t count) {
430 // Construct with a size so MSVC's Debug iterator allocations can also fail
431 // through this call instead of the noexcept default constructor.
432 std::vector<std::unique_ptr<XmaVoiceSlot>> slots(count);
433 for (auto& slot : slots) slot = std::make_unique<XmaVoiceSlot>();
434 unbind();
435 std::unique_lock lock(table_mutex_);
436 array_ = array;
437 voices_.swap(slots);
438 }
439
440 void unbind() {
441 {
442 std::unique_lock lock(table_mutex_);
443 array_ = nullptr;
444 voices_.clear();
445 active_count_.store(0, std::memory_order_relaxed);
446 }
447 // Once detached, commands cannot start a worker for this table.
448 stop_worker();
449 }
450
451 bool handle_command(uint32_t command, const void* config) {
452 auto read_word = [config](std::size_t index) -> uint32_t {
453 if (!config) return 0u;
454 uint32_t value = 0;
455 std::memcpy(&value, static_cast<const uint8_t*>(config) + index * sizeof(uint32_t),
456 sizeof(uint32_t));
457 return value;
458 };
459
460 switch (command) {
461 case kCmdEnableXma:
462 if (config) enable(read_word(0));
463 return true;
464 case kCmdDisableXma:
465 if (config) disable(read_word(0));
466 return true;
467 case kCmdEnableXmas:
468 case kCmdDisableXmas: {
469 std::shared_lock lock(table_mutex_);
470 const std::size_t count = voices_.size();
471 lock.unlock();
472 if (!config) return true;
473 for (std::size_t i = 0; i < count; ++i) {
474 const uint32_t bits = read_word(i / 32);
475 if ((bits & (1u << (i % 32))) != 0) {
476 if (command == kCmdEnableXmas) {
477 enable(static_cast<uint32_t>(i));
478 } else {
479 disable(static_cast<uint32_t>(i));
480 }
481 }
482 }
483 return true;
484 }
485 case kCmdAdvanceXmaRead:
486 if (config) advance_read(read_word(0), read_word(1));
487 return true;
488 default:
489 return false;
490 }
491 }
492
493 void enable(uint32_t index) {
494 std::shared_lock table_lock(table_mutex_);
495 XmaContextView ctx = context_locked(index);
496 if (!ctx.words) return;
497
498 {
499 std::lock_guard slot_lock(voices_[index]->mutex);
500 auto& voice = voices_[index]->voice;
501 const uint32_t format = ctx.field(1, 27, 3);
502 // The worker cannot access the voice until the slot is unlocked.
503 ensure_worker_and_wake();
504 if (!voice) {
505 voice.emplace(format);
506 active_count_.fetch_add(1, std::memory_order_relaxed);
507 } else if (voice->format != format) {
508 voice->pcm.clear();
509 voice->pcm_read = 0;
510 voice->loop_skip = 0;
511 voice->format = format;
512#if defined(LEONIDA_HAVE_XMA2_DECODER)
513 voice->decoder.reset();
514#endif
515 }
516 voice->ended = false;
517 ctx.set_field(2, 26, 6, 0);
518 }
519 }
520
521 void disable(uint32_t index) {
522 std::shared_lock table_lock(table_mutex_);
523 if (index >= voices_.size()) return;
524 std::lock_guard slot_lock(voices_[index]->mutex);
525 if (voices_[index]->voice.has_value()) {
526 voices_[index]->voice.reset();
527 active_count_.fetch_sub(1, std::memory_order_relaxed);
528 }
529 }
530
531 void advance_read(uint32_t index, uint32_t blocks) {
532 std::shared_lock table_lock(table_mutex_);
533 XmaContextView ctx = context_locked(index);
534 if (!ctx.words) return;
535
536 bool wake = false;
537 {
538 std::lock_guard slot_lock(voices_[index]->mutex);
539 const uint32_t size = ctx.field(0, 22, 5);
540 if (size == 0) return;
541 const uint32_t read = (ctx.field(9, 0, 5) + blocks % size) % size;
542 ctx.set_field(9, 0, 5, read);
543 if (blocks > 0) {
544 ctx.set_field(1, 31, 1, 1);
545 }
546 wake = voices_[index]->voice.has_value();
547 }
548 if (wake) ensure_worker_and_wake();
549 }
550
551private:
552 XmaContextView context_locked(uint32_t index) const {
553 if (!array_ || index >= voices_.size()) return {};
554 return XmaContextView{array_[index].words};
555 }
556
557 // Appends interleaved s16 for one 2048-byte packet. Without the Rust decoder, or when it
558 // fails, the packet becomes silence for its frame count (header bits 26..31) so timing holds.
559 static void decode_packet(XmaVoice& voice, const uint8_t* bytes) {
560 const std::size_t channels = voice.channels();
561#if defined(LEONIDA_HAVE_XMA2_DECODER)
562 if (!voice.decoder) {
563 LeonidaXma2Decoder* raw = nullptr;
564 if (leonida_xma2_decoder_create_hardware(kXmaRates[voice.format & 3u],
565 static_cast<uint32_t>(channels), &raw) == LEONIDA_XMA2_OK) {
566 voice.decoder.reset(raw);
567 }
568 }
569 if (voice.decoder) {
570 LeonidaXma2PcmBlock* raw = nullptr;
571 if (leonida_xma2_decode_buffer(voice.decoder.get(), bytes, kXmaPacketBytes, &raw) == LEONIDA_XMA2_OK) {
572 const std::unique_ptr<LeonidaXma2PcmBlock, Xma2PcmFree> block(raw);
573 const int16_t* samples = leonida_xma2_pcm_data(block.get());
574 const std::size_t count = leonida_xma2_pcm_sample_count(block.get());
575 if (count != 0) voice.pcm.insert(voice.pcm.end(), samples, samples + count);
576 return;
577 }
578 voice.decoder.reset(); // Resume with a clean state after replacing a packet with silence.
579 }
580#endif
581 voice.pcm.resize(voice.pcm.size() + static_cast<std::size_t>(bytes[0] >> 2) * kXmaFrameSamples * channels);
582 }
583
584 // Decodes the packet at the read offset of the current input buffer and queues its PCM.
585 // Offsets and loop points are used per packet: a loop plays its end packet in full and
586 // restarts at the start of the packet holding the loop start.
587 static bool decode_one_packet(XmaContextView ctx, XmaVoice& voice) {
588 if (voice.ended) return false;
589
590 const std::size_t channels = voice.channels();
591 uint32_t current = ctx.field(4, 31, 1);
592 const uint32_t valid = ctx.field(0, 20, 2);
593
594 if (valid == 0) {
595 voice.ended = true;
596 ctx.set_field(2, 26, 6, kXmaErrorInputInvalid | 32u);
597 return voice.queued_samples() != 0;
598 }
599 if ((valid & (1u << current)) == 0) {
600 current ^= 1u;
601 ctx.set_field(4, 31, 1, current);
602 }
603
604 const uint32_t address = (current == 0) ? ctx.get(5) : ctx.get(6);
605 const std::size_t packets = (current == 0) ? ctx.field(0, 0, 12) : ctx.field(1, 0, 12);
606 const std::size_t packet = ctx.field(2, 0, 26) / kXmaPacketBits;
607 const uint8_t* data = apu_span(address & ~0x7FFu, packets * kXmaPacketBytes);
608 if (!data || packet >= packets) {
609 finish_input(ctx, current, packet >= packets ? packet - packets : 0);
610 return true;
611 }
612
613 const uint8_t* packet_data = data + packet * kXmaPacketBytes;
614 const uint8_t packet_skip = packet_data[3];
615 // Decoding is only requested when less than a ring block remains. Keep that
616 // tail and reuse the packet storage as the voice consumes subsequent packets.
617 voice.pcm.erase(voice.pcm.begin(), voice.pcm.begin() + static_cast<std::ptrdiff_t>(voice.pcm_read));
618 voice.pcm_read = 0;
619 const std::size_t packet_start = voice.pcm.size();
620 decode_packet(voice, packet_data);
621 const std::size_t packet_samples = voice.pcm.size() - packet_start;
622 const std::size_t subframe_samples = kXmaSubframeSamples * channels;
623 const std::size_t initial_skip = ctx.field(1, 24, 3);
624 const std::size_t skipped_subframes = std::min(initial_skip, packet_samples / subframe_samples);
625 const std::size_t initial_samples = skipped_subframes * subframe_samples;
626 const std::size_t loop_samples = std::min(voice.loop_skip * channels, packet_samples - initial_samples);
627 const std::size_t skip_samples = initial_samples + loop_samples;
628 if (skip_samples != 0) {
629 const auto first = voice.pcm.begin() + static_cast<std::ptrdiff_t>(packet_start);
630 voice.pcm.erase(first, first + static_cast<std::ptrdiff_t>(skip_samples));
631 }
632 // Update the context only after the PCM append succeeds.
633 if (skipped_subframes != 0) {
634 ctx.set_field(1, 24, 3, static_cast<uint32_t>(initial_skip - skipped_subframes));
635 }
636 voice.loop_skip -= loop_samples / channels;
637
638 // XMA2 packet headers link packets from the same stream; 0xff ends the chain.
639 std::size_t next = packet_skip == 0xFFu ? packets : packet + 1 + packet_skip;
640 const uint32_t loops = ctx.field(0, 12, 8);
641 const std::size_t loop_end = ctx.field(4, 0, 26);
642 if (loops > 0 && loop_end != 0 && packet == loop_end / kXmaPacketBits) {
643 next = ctx.field(3, 0, 26) / kXmaPacketBits;
644 voice.loop_skip = static_cast<std::size_t>(ctx.field(1, 17, 3)) * kXmaSubframeSamples;
645#if defined(LEONIDA_HAVE_XMA2_DECODER)
646 // A frame spilling out of the loop-end packet does not continue in the loop-start packet:
647 // start a fresh decoder there rather than decode the spliced bits.
648 voice.decoder.reset();
649#endif
650 if (loops != 255u) ctx.set_field(0, 12, 8, loops - 1u);
651 }
652 if (next >= packets) {
653 finish_input(ctx, current, next - packets);
654 } else {
655 ctx.set_field(2, 0, 26, static_cast<uint32_t>(next * kXmaPacketBits));
656 }
657 return true;
658 }
659
660 static void finish_input(XmaContextView ctx, uint32_t current,
661 std::size_t skip_packets) {
662 // Publish the next offset before telling the title it can refill this input.
663 ctx.set_field(2, 0, 26, static_cast<uint32_t>(skip_packets * kXmaPacketBits));
664 const uint32_t other = 1u - current;
665 const uint32_t retired = ctx.set_field(0, 20 + current, 1, 0);
666 // Take the other input if it was queued at retirement. Otherwise a double
667 // refill of the empty pair starts at input 0. A lone input can still run.
668 ctx.set_field(4, 31, 1, (retired & (1u << (20 + other))) != 0 ? other : 0u);
669 }
670
671 static void pump_voice(XmaContextView ctx, XmaVoice& voice) {
672 const uint32_t size = ctx.field(0, 22, 5);
673 if (size == 0 || ctx.field(1, 31, 1) == 0) return;
674 auto* ring = apu_span(ctx.get(7), size * kXmaBlockBytes);
675 if (!ring) return;
676
677 for (uint32_t blocks = 0; blocks < size && ctx.field(1, 31, 1) == 1; ++blocks) {
678 int decode_guard = 0;
679 while (voice.queued_samples() < kXmaSamplesPerBlock && decode_guard++ < 16) {
680 if (!decode_one_packet(ctx, voice)) break;
681 }
682 if (voice.queued_samples() == 0) return;
683
684 const uint32_t write = ctx.field(0, 27, 5) % size;
685 uint8_t* out = ring + write * kXmaBlockBytes;
686
687 for (std::size_t i = 0; i < kXmaSamplesPerBlock; ++i) {
688 int16_t sample = 0;
689 if (voice.pcm_read != voice.pcm.size()) {
690 sample = voice.pcm[voice.pcm_read++];
691 }
692 const uint16_t raw = static_cast<uint16_t>(sample);
693 out[2 * i] = static_cast<uint8_t>(raw & 0xFFu);
694 out[2 * i + 1] = static_cast<uint8_t>((raw >> 8) & 0xFFu);
695 }
696
697 const uint32_t next_write = (write + 1u) % size;
698 ctx.set_field(0, 27, 5, next_write);
699 if (next_write == ctx.field(9, 0, 5) % size) {
700 ctx.set_field(1, 31, 1, 0);
701 }
702 }
703 }
704
705 void pump_all() {
706 std::shared_lock table_lock(table_mutex_);
707 if (!array_) return;
708 for (std::size_t i = 0; i < voices_.size(); ++i) {
709 std::lock_guard slot_lock(voices_[i]->mutex);
710 auto& voice = voices_[i]->voice;
711 if (!voice) continue;
712 auto ctx = context_locked(static_cast<uint32_t>(i));
713 try {
714 pump_voice(ctx, *voice);
715 } catch (const std::bad_alloc&) {
716 // Only this voice failed. Retire it and allow the title to enable it again.
717 voice.reset();
718 active_count_.fetch_sub(1, std::memory_order_relaxed);
719 ctx.set_field(2, 26, 6, kXmaErrorInputInvalid | 32u);
720 }
721 }
722 }
723
724 void ensure_worker_and_wake() {
725 std::lock_guard lock(worker_mutex_);
726 if (!worker_.joinable()) {
727 worker_ = std::jthread([this](std::stop_token stop) { worker_loop(stop); });
728 }
729 wake_requested_ = true;
730 worker_cv_.notify_one();
731 }
732
733 // Each worker owns its stop_token, so a stop only ever reaches the thread it was
734 // sent to; a worker started after this call is unaffected by it.
735 void stop_worker() {
736 std::jthread to_join;
737 {
738 std::lock_guard lock(worker_mutex_);
739 if (!worker_.joinable()) return;
740 worker_.request_stop();
741 worker_cv_.notify_all();
742 to_join = std::move(worker_);
743 }
744 if (to_join.joinable()) to_join.join();
745 }
746
747 void worker_loop(std::stop_token stop) {
748 for (;;) {
749 {
750 std::unique_lock lock(worker_mutex_);
751 if (stop.stop_requested()) return;
752 if (active_count_.load(std::memory_order_relaxed) == 0 && !wake_requested_) {
753 worker_cv_.wait(lock, stop, [this]() { return wake_requested_; });
754 if (stop.stop_requested()) return;
755 }
756 wake_requested_ = false;
757 }
758
759 pump_all();
760
761 std::unique_lock lock(worker_mutex_);
762 if (stop.stop_requested()) return;
763 if (!wake_requested_ && active_count_.load(std::memory_order_relaxed) > 0) {
764 // One 256-byte output block lasts ~2.67 ms at 48 kHz mono.
765 worker_cv_.wait_for(lock, stop, std::chrono::milliseconds(2),
766 [this]() { return wake_requested_; });
767 }
768 }
769 }
770
771 mutable std::shared_mutex table_mutex_;
772 SHAPE_XMA_CONTEXT* array_ = nullptr;
773 std::vector<std::unique_ptr<XmaVoiceSlot>> voices_;
774 std::atomic<uint32_t> active_count_{0};
775
776 std::mutex worker_mutex_;
777 std::condition_variable_any worker_cv_;
778 std::jthread worker_;
779 bool wake_requested_ = false;
780};
781
782XmaEngine g_xma_engine;
285 783
286// ---- IAcpHal Interface Implementation ---- 784// ---- IAcpHal Interface Implementation ----
287 785
288struct AcpHalImpl { 786#pragma pack(push, 1)
787struct AcpMessage {
788 uint32_t kind = 0;
789 uint32_t dropped = 0;
790 uint32_t usec = 0;
791 uint8_t data[16]{};
792};
793#pragma pack(pop)
794static_assert(sizeof(AcpMessage) == 28, "AcpMessage is 28 bytes");
795
796void write_u32_le(uint8_t* dst, uint32_t value) {
797 dst[0] = static_cast<uint8_t>(value & 0xFFu);
798 dst[1] = static_cast<uint8_t>((value >> 8) & 0xFFu);
799 dst[2] = static_cast<uint8_t>((value >> 16) & 0xFFu);
800 dst[3] = static_cast<uint8_t>((value >> 24) & 0xFFu);
801}
802
803void write_u64_le(uint8_t* dst, uint64_t value) {
804 write_u32_le(dst, static_cast<uint32_t>(value & 0xFFFFFFFFu));
805 write_u32_le(dst + 4, static_cast<uint32_t>(value >> 32));
806}
807
808struct IAcpHal {
809 virtual HRESULT __stdcall connect(uint32_t commands, uint32_t messages) = 0;
810 virtual HRESULT __stdcall disconnect() = 0;
811 virtual HRESULT __stdcall submit_command(uint32_t cmd, uint64_t id, uint32_t frame,
812 const void* config, uint32_t notification) = 0;
813 virtual uint32_t __stdcall pop_message(void* out) = 0;
814 virtual uint32_t __stdcall get_num_messages() = 0;
815 virtual HRESULT __stdcall release() = 0;
816};
817
818struct AcpHalImpl final : IAcpHal {
819 std::mutex mutex_;
820 bool connected_ = false;
821 uint32_t mask_ = 0;
822 std::deque<AcpMessage> messages_;
823 std::size_t capacity_ = 0;
824 uint32_t dropped_ = 0;
825 std::chrono::steady_clock::time_point since_ = std::chrono::steady_clock::now();
826
827 uint64_t elapsed_usec_locked() const {
828 const auto dt = std::chrono::steady_clock::now() - since_;
829 return static_cast<uint64_t>(
830 std::chrono::duration_cast<std::chrono::microseconds>(dt).count());
831 }
832
833 uint32_t audio_frame_locked() const {
834 return static_cast<uint32_t>((elapsed_usec_locked() * kAudioFramesPerSecond) / 1000000ull);
835 }
836
837 void post_locked(uint32_t kind, const uint8_t* payload, std::size_t len) {
838 if ((mask_ & kind) == 0) return;
839 if (messages_.size() >= capacity_) {
840 if (dropped_ < UINT32_MAX) ++dropped_;
841 return;
842 }
843 AcpMessage msg{};
844 msg.kind = kind;
845 msg.dropped = dropped_;
846 msg.usec = static_cast<uint32_t>(elapsed_usec_locked());
847 if (payload && len > 0) {
848 std::memcpy(msg.data, payload, std::min(len, sizeof(msg.data)));
849 }
850 try {
851 messages_.push_back(msg);
852 dropped_ = 0;
853 } catch (const std::bad_alloc&) {
854 if (dropped_ < UINT32_MAX) ++dropped_;
855 }
856 }
857
289 // Slot 0: Connect (called at boot with (0x1000, 0x1000), result checked) 858 // Slot 0: Connect (called at boot with (0x1000, 0x1000), result checked)
290 virtual HRESULT __stdcall connect(uint32_t, uint32_t) { 859 HRESULT __stdcall connect(uint32_t commands, uint32_t messages) override {
291 trace_call("AcpHal::Connect", ""); 860 trace_call("AcpHal::Connect", "");
861 if (commands == 0) return E_INVALIDARG;
862 std::lock_guard lock(mutex_);
863 connected_ = true;
864 capacity_ = messages;
292 return S_OK; 865 return S_OK;
293 } 866 }
294 867
295 // Slot 1: Disconnect (called at shutdown) 868 // Slot 1: Disconnect (called at shutdown)
296 virtual HRESULT __stdcall disconnect() { 869 HRESULT __stdcall disconnect() override {
297 trace_call("AcpHal::Disconnect", ""); 870 trace_call("AcpHal::Disconnect", "");
871 std::lock_guard lock(mutex_);
872 if (!connected_) return E_FAIL;
873 post_locked(kMsgDisconnected, nullptr, 0);
874 connected_ = false;
298 return S_OK; 875 return S_OK;
299 } 876 }
300 877
301 // Slot 2: SubmitCommand 878 // Slot 2: SubmitCommand
302 // Critical: The title calls slot 2 as (2, 0xf0f0f0f0, -1, config, 0) and 879 // Acknowledges command completion, updates registered message masks, dispatches
303 // a negative result triggers a fatal int3 kernel panic (+0x43ad94e). 880 // XMA voice commands, and writes any requested APU notification word.
304 virtual HRESULT __stdcall submit_command(uint32_t cmd, uint32_t d1, uint32_t d2, 881 HRESULT __stdcall submit_command(uint32_t cmd, uint64_t id, uint32_t frame,
305 const void* config, uint32_t d3) { 882 const void* config, uint32_t notification) override try {
306 (void)cmd; 883 (void)frame;
307 (void)d1; 884 auto read_word = [config](std::size_t index) -> uint32_t {
308 (void)d2; 885 if (!config) return 0u;
309 (void)config; 886 uint32_t value = 0;
310 (void)d3; 887 std::memcpy(&value, static_cast<const uint8_t*>(config) + index * sizeof(uint32_t),
311 static std::atomic<bool> warned{false}; 888 sizeof(uint32_t));
312 if (!warned.exchange(true, std::memory_order_relaxed)) { 889 return value;
313 std::fprintf(stderr, 890 };
314 "[rt] acphal: command accepted and dropped: no audio DSP hardware on PC\n"); 891
892 const bool handled_xma = g_xma_engine.handle_command(cmd, config);
893 {
894 std::lock_guard lock(mutex_);
895 if (!handled_xma) {
896 switch (cmd) {
897 case kCmdRegisterMessages:
898 mask_ |= read_word(0);
899 break;
900 case kCmdUnregisterMessages:
901 mask_ &= ~read_word(0);
902 break;
903 case kCmdLoadFlowgraph: {
904 uint8_t payload[4];
905 write_u32_le(payload, read_word(1));
906 post_locked(kMsgFlowgraphCompleted, payload, sizeof(payload));
907 break;
908 }
909 default:
910 break;
911 }
912 }
913 if (id != 0) {
914 uint8_t done[16];
915 write_u32_le(done, cmd);
916 write_u64_le(done + 4, id);
917 write_u32_le(done + 12, audio_frame_locked());
918 post_locked(kMsgCommandCompleted, done, sizeof(done));
919 }
920 }
921
922 if (notification != 0) {
923 if (uint8_t* word_bytes = apu_span(notification, sizeof(uint32_t))) {
924 if ((reinterpret_cast<uintptr_t>(word_bytes) & 3u) == 0) {
925 *reinterpret_cast<volatile uint32_t*>(word_bytes) = 1u;
926 } else {
927 static constexpr uint8_t kOneLe[4] = {1, 0, 0, 0};
928 volatile uint8_t* dst = word_bytes;
929 for (std::size_t i = 0; i < 4; ++i) dst[i] = kOneLe[i];
930 }
931 }
315 } 932 }
933
316 trace_call("AcpHal::SubmitCommand", ""); 934 trace_call("AcpHal::SubmitCommand", "");
317 return S_OK; 935 return S_OK;
936 } catch (const std::bad_alloc&) {
937 return E_OUTOFMEMORY;
938 } catch (const std::system_error&) {
939 return E_FAIL;
318 } 940 }
319 941
320 // Slots 3 and 4: PopMessage and GetNumMessages (message polling, not called by title) 942 // Slot 3: PopMessage — returns 0 without touching `out` when the queue is empty.
321 virtual uint32_t __stdcall pop_message() { return 0; } 943 uint32_t __stdcall pop_message(void* out) override {
322 virtual uint32_t __stdcall get_num_messages() { return 0; } 944 std::lock_guard lock(mutex_);
945 if (messages_.empty()) return 0u;
946 const AcpMessage msg = messages_.front();
947 messages_.pop_front();
948 if (out) std::memcpy(out, &msg, sizeof(msg));
949 return 1u;
950 }
951
952 // Slot 4: GetNumMessages
953 uint32_t __stdcall get_num_messages() override {
954 std::lock_guard lock(mutex_);
955 return static_cast<uint32_t>(messages_.size());
956 }
323 957
324 // Slot 5: Release 958 // Slot 5: Release
325 virtual HRESULT __stdcall release() { 959 HRESULT __stdcall release() override {
326 trace_call("AcpHal::Release", ""); 960 trace_call("AcpHal::Release", "");
327 delete this; 961 delete this;
328 return S_OK; 962 return S_OK;
@@ -333,7 +967,12 @@ struct AcpHalImpl {
333 967
334HRESULT __stdcall AcpHalCreate(void** ppAcpHal) { 968HRESULT __stdcall AcpHalCreate(void** ppAcpHal) {
335 if (!ppAcpHal) return E_POINTER; 969 if (!ppAcpHal) return E_POINTER;
336 *ppAcpHal = new AcpHalImpl(); 970 *ppAcpHal = nullptr;
971 try {
972 *ppAcpHal = new AcpHalImpl();
973 } catch (const std::bad_alloc&) {
974 return E_OUTOFMEMORY;
975 }
337 trace_call("AcpHalCreate", ""); 976 trace_call("AcpHalCreate", "");
338 return S_OK; 977 return S_OK;
339} 978}
@@ -343,63 +982,79 @@ HRESULT __stdcall AcpHalCreate(void** ppAcpHal) {
343HRESULT __stdcall AcpHalAllocateShapeContexts(SHAPE_CONTEXTS* ctx) { 982HRESULT __stdcall AcpHalAllocateShapeContexts(SHAPE_CONTEXTS* ctx) {
344 if (!ctx) return E_POINTER; 983 if (!ctx) return E_POINTER;
345 984
346 std::lock_guard lock(g_apu_mutex); 985 std::lock_guard lock(g_shape_mutex);
347 986
348 auto alloc_array = [](uint32_t count, size_t elem_size) -> void* { 987 ShapeAllocation pending{};
988 std::size_t array_index = 0;
989 auto alloc_array = [&](uint32_t count, size_t elem_size) -> void* {
349 if (count == 0) return nullptr; 990 if (count == 0) return nullptr;
350 void* ptr = std::calloc(count, elem_size); 991 void* ptr = std::calloc(count, elem_size);
351 if (ptr) g_active_shape_arrays.push_back(ptr); 992 if (!ptr) throw std::bad_alloc();
993 pending[array_index++].reset(ptr);
352 return ptr; 994 return ptr;
353 }; 995 };
354 996
355 ctx->srcContextArray = static_cast<SHAPE_SRC_CONTEXT*>( 997 SHAPE_CONTEXTS result{};
356 alloc_array(ctx->numSrcContexts, sizeof(SHAPE_SRC_CONTEXT))); 998 result.numSrcContexts = ctx->numSrcContexts;
357 ctx->eqCompContextArray = static_cast<SHAPE_EQCOMP_CONTEXT*>( 999 result.numEqCompContexts = ctx->numEqCompContexts;
358 alloc_array(ctx->numEqCompContexts, sizeof(SHAPE_EQCOMP_CONTEXT))); 1000 result.numFiltVolContexts = ctx->numFiltVolContexts;
359 ctx->filtVolContextArray = static_cast<SHAPE_FILTVOL_CONTEXT*>( 1001 result.numDmaContexts = ctx->numDmaContexts;
360 alloc_array(ctx->numFiltVolContexts, sizeof(SHAPE_FILTVOL_CONTEXT))); 1002 result.numXmaContexts = ctx->numXmaContexts;
361 ctx->dmaContextArray = static_cast<SHAPE_DMA_CONTEXT*>( 1003 result.numPcmContexts = ctx->numPcmContexts;
362 alloc_array(ctx->numDmaContexts, sizeof(SHAPE_DMA_CONTEXT))); 1004 try {
363 ctx->xmaContextArray = static_cast<SHAPE_XMA_CONTEXT*>( 1005 result.srcContextArray = static_cast<SHAPE_SRC_CONTEXT*>(
364 alloc_array(ctx->numXmaContexts, sizeof(SHAPE_XMA_CONTEXT))); 1006 alloc_array(result.numSrcContexts, sizeof(SHAPE_SRC_CONTEXT)));
365 ctx->pcmContextArray = static_cast<SHAPE_PCM_CONTEXT*>( 1007 result.eqCompContextArray = static_cast<SHAPE_EQCOMP_CONTEXT*>(
366 alloc_array(ctx->numPcmContexts, sizeof(SHAPE_PCM_CONTEXT))); 1008 alloc_array(result.numEqCompContexts, sizeof(SHAPE_EQCOMP_CONTEXT)));
367 1009 result.filtVolContextArray = static_cast<SHAPE_FILTVOL_CONTEXT*>(
368 // On PC there is no physical APU address translation for host context arrays; 1010 alloc_array(result.numFiltVolContexts, sizeof(SHAPE_FILTVOL_CONTEXT)));
369 // assign unique synthetic addresses from the APU base. 1011 result.dmaContextArray = static_cast<SHAPE_DMA_CONTEXT*>(
370 ctx->apuSrcContextArray = {ctx->srcContextArray ? kApuBaseAddress : 0}; 1012 alloc_array(result.numDmaContexts, sizeof(SHAPE_DMA_CONTEXT)));
371 ctx->apuEqCompContextArray = {ctx->eqCompContextArray ? kApuBaseAddress + 0x1000 : 0}; 1013 result.xmaContextArray = static_cast<SHAPE_XMA_CONTEXT*>(
372 ctx->apuFiltVolContextArray = {ctx->filtVolContextArray ? kApuBaseAddress + 0x2000 : 0}; 1014 alloc_array(result.numXmaContexts, sizeof(SHAPE_XMA_CONTEXT)));
373 ctx->apuDmaContextArray = {ctx->dmaContextArray ? kApuBaseAddress + 0x3000 : 0}; 1015 result.pcmContextArray = static_cast<SHAPE_PCM_CONTEXT*>(
374 ctx->apuXmaContextArray = {ctx->xmaContextArray ? kApuBaseAddress + 0x4000 : 0}; 1016 alloc_array(result.numPcmContexts, sizeof(SHAPE_PCM_CONTEXT)));
375 ctx->apuPcmContextArray = {ctx->pcmContextArray ? kApuBaseAddress + 0x5000 : 0}; 1017
376 1018 // Assign synthetic APU addresses to the host-side context arrays.
377 trace_call("AcpHalAllocateShapeContexts", 1019 result.apuSrcContextArray = {result.srcContextArray ? kApuBaseAddress : 0};
378 ",\"src\":" + std::to_string(ctx->numSrcContexts) + 1020 result.apuEqCompContextArray = {result.eqCompContextArray ? kApuBaseAddress + 0x1000 : 0};
379 ",\"xma\":" + std::to_string(ctx->numXmaContexts) + 1021 result.apuFiltVolContextArray = {result.filtVolContextArray ? kApuBaseAddress + 0x2000 : 0};
380 ",\"pcm\":" + std::to_string(ctx->numPcmContexts)); 1022 result.apuDmaContextArray = {result.dmaContextArray ? kApuBaseAddress + 0x3000 : 0};
1023 result.apuXmaContextArray = {result.xmaContextArray ? kApuBaseAddress + 0x4000 : 0};
1024 result.apuPcmContextArray = {result.pcmContextArray ? kApuBaseAddress + 0x5000 : 0};
1025
1026 g_shape_allocations.reserve(g_shape_allocations.size() + 1);
1027 if (result.xmaContextArray) g_xma_engine.bind(result.xmaContextArray, result.numXmaContexts);
1028 } catch (const std::bad_alloc&) {
1029 return E_OUTOFMEMORY;
1030 }
1031
1032 // Both the backing arrays and the engine's slots are now fully allocated.
1033 g_shape_allocations.push_back(std::move(pending));
1034 *ctx = result;
1035 if (rt::startup_trace::enabled()) {
1036 try {
1037 trace_call("AcpHalAllocateShapeContexts",
1038 ",\"src\":" + std::to_string(result.numSrcContexts) +
1039 ",\"xma\":" + std::to_string(result.numXmaContexts) +
1040 ",\"pcm\":" + std::to_string(result.numPcmContexts));
1041 } catch (const std::bad_alloc&) {
1042 // The allocation succeeded. A missing diagnostic does not invalidate it.
1043 }
1044 }
381 return S_OK; 1045 return S_OK;
382} 1046}
383 1047
384// ---- AcpHalReleaseShapeContexts ---- 1048// ---- AcpHalReleaseShapeContexts ----
385 1049
386HRESULT __stdcall AcpHalReleaseShapeContexts(SHAPE_CONTEXTS* ctx = nullptr) { 1050HRESULT __stdcall AcpHalReleaseShapeContexts(void* /*hal*/) {
387 std::lock_guard lock(g_apu_mutex); 1051 std::lock_guard lock(g_shape_mutex);
388 1052 // Stop and detach the XMA worker before freeing backing arrays.
389 // Free all recorded context allocations 1053 g_xma_engine.unbind();
390 for (void* p : g_active_shape_arrays) {
391 if (p) std::free(p);
392 }
393 g_active_shape_arrays.clear();
394 1054
395 if (ctx) { 1055 // The export releases the process-wide SHAPE arrays. The argument is an
396 ctx->srcContextArray = nullptr; 1056 // opaque HAL handle, and allocation descriptors are owned by the caller.
397 ctx->eqCompContextArray = nullptr; 1057 g_shape_allocations.clear();
398 ctx->filtVolContextArray = nullptr;
399 ctx->dmaContextArray = nullptr;
400 ctx->xmaContextArray = nullptr;
401 ctx->pcmContextArray = nullptr;
402 }
403 1058
404 trace_call("AcpHalReleaseShapeContexts", ""); 1059 trace_call("AcpHalReleaseShapeContexts", "");
405 return S_OK; 1060 return S_OK;
@@ -411,6 +1066,9 @@ HRESULT __stdcall ApuCreateHeap(uint32_t cachedSizeInBytes,
411 uint32_t nonCachedSizeInBytes) { 1066 uint32_t nonCachedSizeInBytes) {
412 std::lock_guard lock(g_apu_mutex); 1067 std::lock_guard lock(g_apu_mutex);
413 if (g_apu_heap_created) return E_FAIL; 1068 if (g_apu_heap_created) return E_FAIL;
1069 const uint64_t address_bytes = (nonCachedSizeInBytes ? align_apu_region(cachedSizeInBytes)
1070 : cachedSizeInBytes) + nonCachedSizeInBytes;
1071 if (address_bytes > static_cast<uint64_t>(UINT32_MAX) + 1 - kApuBaseAddress) return E_INVALIDARG;
414 1072
415 if (cachedSizeInBytes > 0) { 1073 if (cachedSizeInBytes > 0) {
416 g_cached_heap.base = VirtualAlloc( 1074 g_cached_heap.base = VirtualAlloc(
@@ -430,17 +1088,23 @@ HRESULT __stdcall ApuCreateHeap(uint32_t cachedSizeInBytes,
430 } 1088 }
431 1089
432 g_apu_heap_created = true; 1090 g_apu_heap_created = true;
433 trace_call("ApuCreateHeap", 1091 if (rt::startup_trace::enabled()) {
434 ",\"cachedSize\":" + std::to_string(cachedSizeInBytes) + 1092 try {
435 ",\"nonCachedSize\":" + std::to_string(nonCachedSizeInBytes)); 1093 trace_call("ApuCreateHeap",
1094 ",\"cachedSize\":" + std::to_string(cachedSizeInBytes) +
1095 ",\"nonCachedSize\":" + std::to_string(nonCachedSizeInBytes));
1096 } catch (const std::bad_alloc&) {
1097 // The heap is ready even if its diagnostic cannot be built.
1098 }
1099 }
436 return S_OK; 1100 return S_OK;
437} 1101}
438 1102
439// ---- ApuAlloc ---- 1103// ---- ApuAlloc ----
440 1104
441HRESULT __stdcall ApuAlloc(void** virtualAddress, uint32_t* physicalAddress, 1105HRESULT __stdcall ApuAlloc(void** virtualAddress, uint32_t* physicalAddress,
442 uint32_t sizeInBytes, uint32_t alignmentInBytes, 1106 uint32_t sizeInBytes, uint32_t alignmentInBytes,
443 uint32_t flags) { 1107 uint32_t flags) try {
444 if (!virtualAddress) return E_POINTER; 1108 if (!virtualAddress) return E_POINTER;
445 *virtualAddress = nullptr; 1109 *virtualAddress = nullptr;
446 if (physicalAddress) *physicalAddress = 0; 1110 if (physicalAddress) *physicalAddress = 0;
@@ -459,6 +1123,7 @@ HRESULT __stdcall ApuAlloc(void** virtualAddress, uint32_t* physicalAddress,
459 1123
460 if (!target->base) { 1124 if (!target->base) {
461 if (!prefer_noncached) { 1125 if (!prefer_noncached) {
1126 if (g_apu_heap_created) return E_OUTOFMEMORY;
462 // Lazy default cached heap if ApuCreateHeap wasn't called yet 1127 // Lazy default cached heap if ApuCreateHeap wasn't called yet
463 constexpr uint32_t kDefaultHeapSize = 64 * 1024 * 1024; 1128 constexpr uint32_t kDefaultHeapSize = 64 * 1024 * 1024;
464 target->base = VirtualAlloc(nullptr, kDefaultHeapSize, 1129 target->base = VirtualAlloc(nullptr, kDefaultHeapSize,
@@ -485,17 +1150,17 @@ HRESULT __stdcall ApuAlloc(void** virtualAddress, uint32_t* physicalAddress,
485 1150
486 *virtualAddress = ptr; 1151 *virtualAddress = ptr;
487 if (physicalAddress) { 1152 if (physicalAddress) {
488 // Disjoint APU address ranges: 1153 // Leave alignment padding between the two synthetic address ranges.
489 // cached: 0x40000000 .. 0x40000000 + cached_size - 1
490 // non-cached: 0x40000000 + cached_size .. 0x40000000 + cached_size + noncached_size - 1
491 uint32_t apu = kApuBaseAddress + offset; 1154 uint32_t apu = kApuBaseAddress + offset;
492 if (target == &g_noncached_heap) { 1155 if (target == &g_noncached_heap) {
493 apu += static_cast<uint32_t>(g_cached_heap.size); 1156 apu += static_cast<uint32_t>(align_apu_region(g_cached_heap.size));
494 } 1157 }
495 *physicalAddress = apu; 1158 *physicalAddress = apu;
496 } 1159 }
497 1160
498 return S_OK; 1161 return S_OK;
1162} catch (const std::bad_alloc&) {
1163 return E_OUTOFMEMORY;
499} 1164}
500 1165
501// ---- ApuFree ---- 1166// ---- ApuFree ----
@@ -530,7 +1195,7 @@ void* __stdcall ApuMapApuAddress(uint32_t apu) {
530 return g_cached_heap.from_offset(offset); 1195 return g_cached_heap.from_offset(offset);
531 } 1196 }
532 if (g_noncached_heap.base) { 1197 if (g_noncached_heap.base) {
533 const uint32_t cached_span = static_cast<uint32_t>(g_cached_heap.size); 1198 const uint32_t cached_span = static_cast<uint32_t>(align_apu_region(g_cached_heap.size));
534 if (offset >= cached_span && offset - cached_span < g_noncached_heap.size) { 1199 if (offset >= cached_span && offset - cached_span < g_noncached_heap.size) {
535 return g_noncached_heap.from_offset(offset - cached_span); 1200 return g_noncached_heap.from_offset(offset - cached_span);
536 } 1201 }
@@ -547,7 +1212,7 @@ uint32_t __stdcall ApuMapVirtualAddress(void* virtualAddress) {
547 return kApuBaseAddress + g_cached_heap.to_offset(virtualAddress); 1212 return kApuBaseAddress + g_cached_heap.to_offset(virtualAddress);
548 } 1213 }
549 if (g_noncached_heap.contains(virtualAddress)) { 1214 if (g_noncached_heap.contains(virtualAddress)) {
550 return kApuBaseAddress + static_cast<uint32_t>(g_cached_heap.size) + 1215 return kApuBaseAddress + static_cast<uint32_t>(align_apu_region(g_cached_heap.size)) +
551 g_noncached_heap.to_offset(virtualAddress); 1216 g_noncached_heap.to_offset(virtualAddress);
552 } 1217 }
553 return 0; 1218 return 0;
diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h
index d0f3b528a..07233494b 100644
--- a/runtime/shims/d3d12_com.h
+++ b/runtime/shims/d3d12_com.h
@@ -87,6 +87,7 @@ struct VulkanDeviceInfo {
87 std::vector<VkQueue> compute_queues; 87 std::vector<VkQueue> compute_queues;
88 std::vector<VkQueue> copy_queues; 88 std::vector<VkQueue> copy_queues;
89 bool separate_depth_stencil_layouts = true; 89 bool separate_depth_stencil_layouts = true;
90 bool depth_range_unrestricted = false; // VK_EXT_depth_range_unrestricted enabled on this device.
90 std::uint32_t max_push_constants_size = 0; 91 std::uint32_t max_push_constants_size = 0;
91 bool push_constants_need_fallback = false; 92 bool push_constants_need_fallback = false;
92 // maxBufferSize and maxMemoryAllocationSize, which cap the GPU address arena (src/arena_size.h). 0: read from 93 // maxBufferSize and maxMemoryAllocationSize, which cap the GPU address arena (src/arena_size.h). 0: read from
@@ -175,6 +176,9 @@ struct VulkanDeviceInfo {
175 // shaders have no amplification stage). Mesh-shader PSOs and DispatchMesh work, and CheckFeatureSupport reports 176 // shaders have no amplification stage). Mesh-shader PSOs and DispatchMesh work, and CheckFeatureSupport reports
176 // D3D12_MESH_SHADER_TIER_1; without it mesh PSOs are refused and the tier is NOT_SUPPORTED. 177 // D3D12_MESH_SHADER_TIER_1; without it mesh PSOs are refused and the tier is NOT_SUPPORTED.
177 bool mesh_shader = false; 178 bool mesh_shader = false;
179 // VK_EXT_mesh_shader's meshShaderQueries feature is enabled on `device`, so the clipping invocations of a mesh
180 // segment come from a mesh-primitives query (D3D-MESH-CLIPPING-COUNTER). Without it they read 0.
181 bool mesh_shader_queries = false;
178 // The core features enabled on `device`. Graphics PSOs that need independentBlend, fillModeNonSolid, 182 // The core features enabled on `device`. Graphics PSOs that need independentBlend, fillModeNonSolid,
179 // depthBiasClamp or dualSrcBlend are refused unless it is set here. 183 // depthBiasClamp or dualSrcBlend are refused unless it is set here.
180 VkPhysicalDeviceFeatures features{}; 184 VkPhysicalDeviceFeatures features{};
diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp
index 0273f9339..e9bc19195 100644
--- a/runtime/shims/d3d12_vulkan_device.cpp
+++ b/runtime/shims/d3d12_vulkan_device.cpp
@@ -3096,8 +3096,6 @@ public:
3096 virtual HRESULT STDMETHODCALLTYPE xbox_slot11(UINT64, UINT64, void** out) = 0; 3096 virtual HRESULT STDMETHODCALLTYPE xbox_slot11(UINT64, UINT64, void** out) = 0;
3097}; 3097};
3098 3098
3099// A pipeline state. Compute only for now: the shader is found by the SHA-256 of its FSSM program in the
3100// translator's index, and the FSSM blob is copied into the arena as the shader's code base.
3101// A D3D12_PIPELINE_STATE_STREAM_DESC (ID3D12Device2::CreatePipelineState) as the descriptions the PSO creators take. 3099// A D3D12_PIPELINE_STATE_STREAM_DESC (ID3D12Device2::CreatePipelineState) as the descriptions the PSO creators take.
3102// The stream is a run of subobjects, each a D3D12_PIPELINE_STATE_SUBOBJECT_TYPE followed by its description at that 3100// The stream is a run of subobjects, each a D3D12_PIPELINE_STATE_SUBOBJECT_TYPE followed by its description at that
3103// description's alignment, each subobject starting at pointer alignment (the d3dx12.h layout, `alignas(void*)`). A 3101// description's alignment, each subobject starting at pointer alignment (the d3dx12.h layout, `alignas(void*)`). A
@@ -3293,6 +3291,8 @@ HRESULT parse_pipeline_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, Pipe
3293 return S_OK; 3291 return S_OK;
3294} 3292}
3295 3293
3294// A pipeline state, compute (create_compute) or graphics (create_graphics): each shader is found by the SHA-256 of
3295// its FSSM program in the translator's index, and the FSSM blob is copied into the arena as the shader's code base.
3296class PipelineState final 3296class PipelineState final
3297 : public Child<PipelineState, XboxPipelineStateStubs, ID3D12Object, ID3D12DeviceChild, ID3D12Pageable, 3297 : public Child<PipelineState, XboxPipelineStateStubs, ID3D12Object, ID3D12DeviceChild, ID3D12Pageable,
3298 ID3D12PipelineState> { 3298 ID3D12PipelineState> {
@@ -5120,6 +5120,8 @@ public:
5120 info.conditional_rendering, info.ray_tracing, 5120 info.conditional_rendering, info.ray_tracing,
5121 info.xdxr_acceleration_structures && 5121 info.xdxr_acceleration_structures &&
5122 info.buffer_device_address); 5122 info.buffer_device_address);
5123 state_.context->mesh_queries = info.mesh_shader_queries;
5124 state_.context->set_depth_range_unrestricted(info.depth_range_unrestricted);
5123 if (info.physical && state_.format_properties) { 5125 if (info.physical && state_.format_properties) {
5124 state_.context->set_color_attachment_format( 5126 state_.context->set_color_attachment_format(
5125 [physical = info.physical, get_props = state_.format_properties](VkFormat format) { 5127 [physical = info.physical, get_props = state_.format_properties](VkFormat format) {
@@ -5187,7 +5189,8 @@ public:
5187 if (info.bindless && state_.context->loaded() && !create_bindless(get_device)) 5189 if (info.bindless && state_.context->loaded() && !create_bindless(get_device))
5188 std::fprintf(stderr, "[rt] d3d12: the bindless set 0 could not be created\n"); 5190 std::fprintf(stderr, "[rt] d3d12: the bindless set 0 could not be created\n");
5189 query_luid_and_clock(get_device); 5191 query_luid_and_clock(get_device);
5190 // Timestamps: what the one VkQueue every D3D12 queue submits to can write. 5192 // Timestamps: the device's timestampPeriod, enabled when the graphics family (info.queue_family) has
5193 // timestampValidBits.
5191 VkPhysicalDeviceProperties properties{}; 5194 VkPhysicalDeviceProperties properties{};
5192 device_properties(info.physical, &properties); 5195 device_properties(info.physical, &properties);
5193 state_.max_sampler_lod_bias = properties.limits.maxSamplerLodBias; 5196 state_.max_sampler_lod_bias = properties.limits.maxSamplerLodBias;
@@ -7589,35 +7592,42 @@ public:
7589 return d3d12_trace::result(method, S_OK); 7592 return d3d12_trace::result(method, S_OK);
7590 } 7593 }
7591 case D3D12_FEATURE_D3D12_OPTIONS: { 7594 case D3D12_FEATURE_D3D12_OPTIONS: {
7592 if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS)) return d3d12_trace::result(method, E_INVALIDARG); 7595 constexpr UINT kConsoleOptionsSize = sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS) + sizeof(UINT);
7593 auto* opts = static_cast<D3D12_FEATURE_DATA_D3D12_OPTIONS*>(data); 7596 if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS) && size != kConsoleOptionsSize)
7594 *opts = {}; 7597 return d3d12_trace::result(method, E_INVALIDARG);
7598 D3D12_FEATURE_DATA_D3D12_OPTIONS pc_opts{};
7595 // Answer what the layer will actually honour, not what the GPU offers: docs/d3d12_vulkan.md 4.1 says a 7599 // Answer what the layer will actually honour, not what the GPU offers: docs/d3d12_vulkan.md 4.1 says a
7596 // false "supported" is worse than a false "unsupported" at boot, and the PSO paths refuse these same 7600 // false "supported" is worse than a false "unsupported" at boot, and the PSO paths refuse these same
7597 // features when they are missing (logic ops, per the mapping vkd3d-proton's 7601 // features when they are missing (logic ops, per the mapping vkd3d-proton's
7598 // d3d12_device_caps_init_feature_options uses). 7602 // d3d12_device_caps_init_feature_options uses).
7599 opts->DoublePrecisionFloatShaderOps = state_.info.features.shaderFloat64; 7603 pc_opts.DoublePrecisionFloatShaderOps = state_.info.features.shaderFloat64;
7600 opts->OutputMergerLogicOp = state_.info.features.logicOp; 7604 pc_opts.OutputMergerLogicOp = state_.info.features.logicOp;
7601 opts->MinPrecisionSupport = D3D12_SHADER_MIN_PRECISION_SUPPORT_NONE; 7605 pc_opts.MinPrecisionSupport = D3D12_SHADER_MIN_PRECISION_SUPPORT_NONE;
7602 opts->TiledResourcesTier = D3D12_TILED_RESOURCES_TIER_NOT_SUPPORTED; 7606 pc_opts.TiledResourcesTier = D3D12_TILED_RESOURCES_TIER_NOT_SUPPORTED;
7603 opts->ResourceBindingTier = D3D12_RESOURCE_BINDING_TIER_3; // Bindless descriptor indexing supported 7607 pc_opts.ResourceBindingTier = D3D12_RESOURCE_BINDING_TIER_3; // Bindless descriptor indexing supported
7604 // No VK_EXT_shader_stencil_export is enabled and the translator emits no stencil-ref write, so a pixel 7608 // No VK_EXT_shader_stencil_export is enabled and the translator emits no stencil-ref write, so a pixel
7605 // shader that writes the stencil ref would be refused: answer unsupported, the direction 4.1 prefers. 7609 // shader that writes the stencil ref would be refused: answer unsupported, the direction 4.1 prefers.
7606 opts->PSSpecifiedStencilRefSupported = FALSE; 7610 pc_opts.PSSpecifiedStencilRefSupported = FALSE;
7607 opts->TypedUAVLoadAdditionalFormats = TRUE; 7611 pc_opts.TypedUAVLoadAdditionalFormats = TRUE;
7608 // POPS: the translator only declares PixelInterlockOrderedEXT, enabled exactly when the GPU offers 7612 // POPS: the translator only declares PixelInterlockOrderedEXT, enabled exactly when the GPU offers
7609 // VK_EXT_fragment_shader_interlock and its fragmentShaderPixelInterlock feature. 7613 // VK_EXT_fragment_shader_interlock and its fragmentShaderPixelInterlock feature.
7610 opts->ROVsSupported = state_.info.fragment_shader_interlock; 7614 pc_opts.ROVsSupported = state_.info.fragment_shader_interlock;
7611 opts->ConservativeRasterizationTier = state_.conservative_raster_tier; 7615 pc_opts.ConservativeRasterizationTier = state_.conservative_raster_tier;
7612 opts->MaxGPUVirtualAddressBitsPerResource = 40; 7616 pc_opts.MaxGPUVirtualAddressBitsPerResource = 40;
7613 opts->StandardSwizzle64KBSupported = FALSE; 7617 pc_opts.StandardSwizzle64KBSupported = FALSE;
7614 opts->CrossNodeSharingTier = D3D12_CROSS_NODE_SHARING_TIER_NOT_SUPPORTED; 7618 pc_opts.CrossNodeSharingTier = D3D12_CROSS_NODE_SHARING_TIER_NOT_SUPPORTED;
7615 opts->CrossAdapterRowMajorTextureSupported = FALSE; 7619 pc_opts.CrossAdapterRowMajorTextureSupported = FALSE;
7616 // A translated vertex shader writing a layer or viewport index needs both Vulkan 1.2 features enabled 7620 // A translated vertex shader writing a layer or viewport index needs both Vulkan 1.2 features enabled
7617 // (vkCreateShaderModule refuses the module without them, VUID-...-pCode-08740). 7621 // (vkCreateShaderModule refuses the module without them, VUID-...-pCode-08740).
7618 opts->VPAndRTArrayIndexFromAnyShaderFeedingRasterizerSupportedWithoutGSEmulation = 7622 pc_opts.VPAndRTArrayIndexFromAnyShaderFeedingRasterizerSupportedWithoutGSEmulation =
7619 state_.info.shader_output_layer && state_.info.shader_output_viewport_index; 7623 state_.info.shader_output_layer && state_.info.shader_output_viewport_index;
7620 opts->ResourceHeapTier = D3D12_RESOURCE_HEAP_TIER_1; 7624 pc_opts.ResourceHeapTier = D3D12_RESOURCE_HEAP_TIER_1;
7625 std::memcpy(data, &pc_opts, sizeof(pc_opts));
7626 if (size == kConsoleOptionsSize) {
7627 // Console titles query D3D12_FEATURE_D3D12_OPTIONS with a 0x40-byte (16-dword) buffer
7628 // (docs/d3d12_xs_surface.md §7.1): fill the 0x3C-byte PC prefix and zero the trailing 4 bytes.
7629 std::memset(static_cast<std::uint8_t*>(data) + sizeof(pc_opts), 0, sizeof(UINT));
7630 }
7621 return d3d12_trace::result(method, S_OK); 7631 return d3d12_trace::result(method, S_OK);
7622 } 7632 }
7623 case D3D12_FEATURE_D3D12_OPTIONS1: { 7633 case D3D12_FEATURE_D3D12_OPTIONS1: {
@@ -7951,8 +7961,7 @@ public:
7951 // Vulkan can still advertise buffer features for their backing formats. 7961 // Vulkan can still advertise buffer features for their backing formats.
7952 if (buffer != 0 && vk_fmt != VK_FORMAT_R8G8B8A8_SRGB && vk_fmt != VK_FORMAT_B8G8R8A8_SRGB) 7962 if (buffer != 0 && vk_fmt != VK_FORMAT_R8G8B8A8_SRGB && vk_fmt != VK_FORMAT_B8G8R8A8_SRGB)
7953 s1 |= D3D12_FORMAT_SUPPORT1_BUFFER; 7963 s1 |= D3D12_FORMAT_SUPPORT1_BUFFER;
7954 // Only what CreateGraphicsPipelineState's input layouts accept (vertex_format): R8/R16 SNORM and SINT 7964 // Only what CreateGraphicsPipelineState's input layouts accept (vertex_format).
7955 // have Vulkan vertex support but no input-layout mapping yet.
7956 VkFormat vertex_vk = VK_FORMAT_UNDEFINED; 7965 VkFormat vertex_vk = VK_FORMAT_UNDEFINED;
7957 UINT vertex_bytes = 0; 7966 UINT vertex_bytes = 0;
7958 if ((buffer & VK_FORMAT_FEATURE_VERTEX_BUFFER_BIT) && vertex_format(fs->Format, vertex_vk, vertex_bytes)) 7967 if ((buffer & VK_FORMAT_FEATURE_VERTEX_BUFFER_BIT) && vertex_format(fs->Format, vertex_vk, vertex_bytes))
@@ -8003,8 +8012,9 @@ public:
8003 s1 |= D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW; 8012 s1 |= D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW;
8004 // A typed UAV texture read is not a storage-image read: the translator reads it through the 8013 // A typed UAV texture read is not a storage-image read: the translator reads it through the
8005 // texture's sampled binding with the T#'s numeric type (rdna2spirv.py image_read_typed), so a 8014 // texture's sampled binding with the T#'s numeric type (rdna2spirv.py image_read_typed), so a
8006 // format that can be stored can be read. Typed buffer UAVs share the store side's limits: the layer 8015 // format that can be stored can be read. Typed buffer UAVs share the store side's limits: a buffer
8007 // creates no buffer UAV views yet, and rdna2spirv.py FORMATS decodes only some buffer formats. 8016 // UAV is a typed V# the layer writes itself (write_buffer_uav, no VkBufferView), and rdna2spirv.py
8017 // FORMATS decodes only some buffer formats.
8008 s2 |= D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE | D3D12_FORMAT_SUPPORT2_UAV_TYPED_LOAD; 8018 s2 |= D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE | D3D12_FORMAT_SUPPORT2_UAV_TYPED_LOAD;
8009 // Image atomics go through the r32ui storage view, which an R32_UINT UAV view gets 8019 // Image atomics go through the r32ui storage view, which an R32_UINT UAV view gets
8010 // (StorageViews::r32ui). Today that is 2D UAVs only: the translator's image atomics cover 2D and 3D, 8020 // (StorageViews::r32ui). Today that is 2D UAVs only: the translator's image atomics cover 2D and 3D,
@@ -9490,6 +9500,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin
9490 VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &mesh_features}; 9500 VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &mesh_features};
9491 vkGetPhysicalDeviceFeatures2(info.physical, &features); 9501 vkGetPhysicalDeviceFeatures2(info.physical, &features);
9492 info.mesh_shader = mesh_features.meshShader == VK_TRUE; 9502 info.mesh_shader = mesh_features.meshShader == VK_TRUE;
9503 info.mesh_shader_queries = mesh_features.meshShaderQueries == VK_TRUE;
9493 } 9504 }
9494 } 9505 }
9495 if (!info.mesh_shader) 9506 if (!info.mesh_shader)
@@ -9526,6 +9537,8 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin
9526 // are not used. 9537 // are not used.
9527 VkPhysicalDeviceMeshShaderFeaturesEXT enable_mesh{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT}; 9538 VkPhysicalDeviceMeshShaderFeaturesEXT enable_mesh{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT};
9528 enable_mesh.meshShader = VK_TRUE; 9539 enable_mesh.meshShader = VK_TRUE;
9540 // The mesh-primitives query, which counts the primitives a mesh shader emits (D3D-MESH-CLIPPING-COUNTER).
9541 enable_mesh.meshShaderQueries = info.mesh_shader_queries ? VK_TRUE : VK_FALSE;
9529 9542
9530 void* ext_chain = nullptr; 9543 void* ext_chain = nullptr;
9531 if (info.mesh_shader) { 9544 if (info.mesh_shader) {
@@ -9723,6 +9736,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin
9723 return std::any_of(extensions.begin(), extensions.end(), 9736 return std::any_of(extensions.begin(), extensions.end(),
9724 [&](const auto& e) { return std::strcmp(e.extensionName, name) == 0; }); 9737 [&](const auto& e) { return std::strcmp(e.extensionName, name) == 0; });
9725 }; 9738 };
9739 info.depth_range_unrestricted = has_device_extension(VK_EXT_DEPTH_RANGE_UNRESTRICTED_EXTENSION_NAME);
9726 VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR barycentric{ 9740 VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR barycentric{
9727 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_BARYCENTRIC_FEATURES_KHR}; 9741 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_BARYCENTRIC_FEATURES_KHR};
9728 if (has_device_extension(VK_KHR_FRAGMENT_SHADER_BARYCENTRIC_EXTENSION_NAME)) { 9742 if (has_device_extension(VK_KHR_FRAGMENT_SHADER_BARYCENTRIC_EXTENSION_NAME)) {
@@ -9899,6 +9913,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin
9899 device_info.pEnabledFeatures = &enable; 9913 device_info.pEnabledFeatures = &enable;
9900 std::vector<const char*> device_extensions; 9914 std::vector<const char*> device_extensions;
9901 v13.add_extensions(device_extensions); 9915 v13.add_extensions(device_extensions);
9916 if (info.depth_range_unrestricted) device_extensions.push_back(VK_EXT_DEPTH_RANGE_UNRESTRICTED_EXTENSION_NAME);
9902 if (info.conservative_rasterization) device_extensions.push_back(VK_EXT_CONSERVATIVE_RASTERIZATION_EXTENSION_NAME); 9917 if (info.conservative_rasterization) device_extensions.push_back(VK_EXT_CONSERVATIVE_RASTERIZATION_EXTENSION_NAME);
9903 if (info.image_view_min_lod) device_extensions.push_back(VK_EXT_IMAGE_VIEW_MIN_LOD_EXTENSION_NAME); 9918 if (info.image_view_min_lod) device_extensions.push_back(VK_EXT_IMAGE_VIEW_MIN_LOD_EXTENSION_NAME);
9904 if (info.vertex_attribute_divisor) device_extensions.push_back(divisor_extension); 9919 if (info.vertex_attribute_divisor) device_extensions.push_back(divisor_extension);
diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp
index 7f7040fdd..85aece0bd 100644
--- a/runtime/shims/d3d12_xs_device.cpp
+++ b/runtime/shims/d3d12_xs_device.cpp
@@ -76,8 +76,25 @@ struct DeviceProxy {
76 std::atomic<std::uint32_t> frame_latency{1}; 76 std::atomic<std::uint32_t> frame_latency{1};
77 std::atomic<bool> frame_event_scheduled{false}; 77 std::atomic<bool> frame_event_scheduled{false};
78 std::atomic<std::uint64_t> frame_next_token{1}; 78 std::atomic<std::uint64_t> frame_next_token{1};
79 // Optional presentation wiring attached via set_presentation_handler (guarded by presentation_lock).
80 SRWLOCK presentation_lock = SRWLOCK_INIT;
81 PresentationHandler presentation{};
79}; 82};
80 83
84// Runs f(handler) with the presentation lock held shared, so a detach cannot destroy the presentation mid-call. f
85// returns false, without calling the presentation, when it has no function for the slot; the result says whether
86// f handled the call.
87// ponytail: a presenter callback must not call set_presentation_handler (exclusive inside shared deadlocks), and a
88// detach waits for a WaitFrameEventX in flight up to its timeout.
89template <typename F>
90bool call_presentation(DeviceProxy* self, F&& f) {
91 if (!self) return false;
92 AcquireSRWLockShared(&self->presentation_lock);
93 const bool handled = f(static_cast<const PresentationHandler&>(self->presentation));
94 ReleaseSRWLockShared(&self->presentation_lock);
95 return handled;
96}
97
81constexpr unsigned kHeapSlots = 11; // IUnknown + ID3D12Object + DeviceChild + Pageable + GetDesc + 2 handles 98constexpr unsigned kHeapSlots = 11; // IUnknown + ID3D12Object + DeviceChild + Pageable + GetDesc + 2 handles
82 99
83struct HeapProxy { 100struct HeapProxy {
@@ -181,24 +198,27 @@ struct XboxDeviceSlotRoutes {
181 unsigned frame_interval = 78; // SetFrameIntervalX(output, interval_us, latency, flags) 198 unsigned frame_interval = 78; // SetFrameIntervalX(output, interval_us, latency, flags)
182 unsigned schedule_event = 79; // ScheduleFrameEventX(event, offset_us, reserved, flags) 199 unsigned schedule_event = 79; // ScheduleFrameEventX(event, offset_us, reserved, flags)
183 unsigned wait_event = 80; // WaitFrameEventX(event, timeout_ms, reserved, flags, &token) 200 unsigned wait_event = 80; // WaitFrameEventX(event, timeout_ms, reserved, flags, &token)
201 unsigned frame_statistics = 81; // GetFrameStatisticsX(token, type_mask, count, out)
184 unsigned queue_x = 48; // CreateCommandQueueX(desc, riid, out) 202 unsigned queue_x = 48; // CreateCommandQueueX(desc, riid, out)
185 unsigned list_x = 73; // CreateCommandListX(desc, allocator, initial_state, riid, out) 203 unsigned list_x = 73; // CreateCommandListX(desc, allocator, initial_state, riid, out)
186}; 204};
187 205
188unsigned env_device_slot(const char* name, unsigned fallback) { 206// Reads a slot number in lo..hi from `name`: an unset variable gives `fallback`; a bad value is logged (`what` names
207// the kind of slot) and ignored.
208unsigned env_slot(const char* name, unsigned fallback, unsigned lo, unsigned hi, const char* what) {
189 char value[32] = {}; 209 char value[32] = {};
190 const DWORD length = GetEnvironmentVariableA(name, value, sizeof(value)); 210 const DWORD length = GetEnvironmentVariableA(name, value, sizeof(value));
191 if (length == 0) return fallback; 211 if (length == 0) return fallback;
192 if (length >= sizeof(value)) { 212 if (length >= sizeof(value)) {
193 std::fprintf(stderr, "[rt] d3d12_xs: %s is too long for a device slot; the default is kept\n", name); 213 std::fprintf(stderr, "[rt] d3d12_xs: %s is too long for a %s; the default is kept\n", name, what);
194 return fallback; 214 return fallback;
195 } 215 }
196 errno = 0; 216 errno = 0;
197 char* end = nullptr; 217 char* end = nullptr;
198 const unsigned long slot = std::strtoul(value, &end, 0); 218 const unsigned long slot = std::strtoul(value, &end, 0);
199 if (errno != 0 || end == value || *end != '\0' || slot < 3 || slot > 127) { 219 if (errno != 0 || end == value || *end != '\0' || slot < lo || slot > hi) {
200 std::fprintf(stderr, "[rt] d3d12_xs: %s=%s is not a device slot in 3..127; the default is kept\n", name, 220 std::fprintf(stderr, "[rt] d3d12_xs: %s=%s is not a %s in %u..%u; the default is kept\n", name, value, what,
201 value); 221 lo, hi);
202 return fallback; 222 return fallback;
203 } 223 }
204 return static_cast<unsigned>(slot); 224 return static_cast<unsigned>(slot);
@@ -207,23 +227,29 @@ unsigned env_device_slot(const char* name, unsigned fallback) {
207const XboxDeviceSlotRoutes& xbox_device_slot_routes() { 227const XboxDeviceSlotRoutes& xbox_device_slot_routes() {
208 static const XboxDeviceSlotRoutes routes = [] { 228 static const XboxDeviceSlotRoutes routes = [] {
209 XboxDeviceSlotRoutes r; 229 XboxDeviceSlotRoutes r;
210 const unsigned frame_interval = env_device_slot("LEONIDA_XS_FRAME_INTERVAL_SLOT", r.frame_interval); 230 const unsigned frame_interval = env_slot("LEONIDA_XS_FRAME_INTERVAL_SLOT", r.frame_interval, 3, 127,
211 const unsigned schedule_event = env_device_slot("LEONIDA_XS_SCHEDULE_EVENT_SLOT", r.schedule_event); 231 "device slot");
212 const unsigned wait_event = env_device_slot("LEONIDA_XS_WAIT_EVENT_SLOT", r.wait_event); 232 const unsigned schedule_event = env_slot("LEONIDA_XS_SCHEDULE_EVENT_SLOT", r.schedule_event, 3, 127,
213 const unsigned queue_x = env_device_slot("LEONIDA_XS_QUEUE_X_SLOT", r.queue_x); 233 "device slot");
214 const unsigned list_x = env_device_slot("LEONIDA_XS_LIST_X_SLOT", r.list_x); 234 const unsigned wait_event = env_slot("LEONIDA_XS_WAIT_EVENT_SLOT", r.wait_event, 3, 127, "device slot");
235 const unsigned frame_statistics = env_slot("LEONIDA_XS_FRAME_STATISTICS_SLOT", r.frame_statistics, 3, 127,
236 "device slot");
237 const unsigned queue_x = env_slot("LEONIDA_XS_QUEUE_X_SLOT", r.queue_x, 3, 127, "device slot");
238 const unsigned list_x = env_slot("LEONIDA_XS_LIST_X_SLOT", r.list_x, 3, 127, "device slot");
215 const bool moved = frame_interval != r.frame_interval || schedule_event != r.schedule_event || 239 const bool moved = frame_interval != r.frame_interval || schedule_event != r.schedule_event ||
216 wait_event != r.wait_event || queue_x != r.queue_x || list_x != r.list_x; 240 wait_event != r.wait_event || frame_statistics != r.frame_statistics ||
241 queue_x != r.queue_x || list_x != r.list_x;
217 r.frame_interval = frame_interval; 242 r.frame_interval = frame_interval;
218 r.schedule_event = schedule_event; 243 r.schedule_event = schedule_event;
219 r.wait_event = wait_event; 244 r.wait_event = wait_event;
245 r.frame_statistics = frame_statistics;
220 r.queue_x = queue_x; 246 r.queue_x = queue_x;
221 r.list_x = list_x; 247 r.list_x = list_x;
222 if (moved) 248 if (moved)
223 std::fprintf(stderr, 249 std::fprintf(stderr,
224 "[rt] d3d12_xs: Xbox device slots: SetFrameIntervalX=%u ScheduleFrameEventX=%u " 250 "[rt] d3d12_xs: Xbox device slots: SetFrameIntervalX=%u ScheduleFrameEventX=%u "
225 "WaitFrameEventX=%u CreateCommandQueueX=%u CreateCommandListX=%u\n", 251 "WaitFrameEventX=%u GetFrameStatisticsX=%u CreateCommandQueueX=%u CreateCommandListX=%u\n",
226 r.frame_interval, r.schedule_event, r.wait_event, r.queue_x, r.list_x); 252 r.frame_interval, r.schedule_event, r.wait_event, r.frame_statistics, r.queue_x, r.list_x);
227 return r; 253 return r;
228 }(); 254 }();
229 return routes; 255 return routes;
@@ -983,6 +1009,10 @@ inline void note_list_slot(unsigned slot, std::uint64_t a1 = 0, std::uint64_t a2
983 static_cast<unsigned long long>(a3), static_cast<unsigned long long>(a4)); 1009 static_cast<unsigned long long>(a3), static_cast<unsigned long long>(a4));
984} 1010}
985 1011
1012// Measured Xbox ID3D12GraphicsCommandListX IID passed to device slot 73 (CreateCommandListX).
1013constexpr IID kXboxGraphicsCommandListXIid = {
1014 0xc3827890, 0x4024, 0x474c, {0x98, 0xcf, 0x64, 0x5b, 0x51, 0xdc, 0x48, 0x74}};
1015
986inline bool is_list_iid(const IID& iid) { 1016inline bool is_list_iid(const IID& iid) {
987 return IsEqualIID(iid, __uuidof(IUnknown)) || IsEqualIID(iid, __uuidof(ID3D12Object)) || 1017 return IsEqualIID(iid, __uuidof(IUnknown)) || IsEqualIID(iid, __uuidof(ID3D12Object)) ||
988 IsEqualIID(iid, __uuidof(ID3D12DeviceChild)) || IsEqualIID(iid, __uuidof(ID3D12CommandList)) || 1018 IsEqualIID(iid, __uuidof(ID3D12DeviceChild)) || IsEqualIID(iid, __uuidof(ID3D12CommandList)) ||
@@ -994,7 +1024,8 @@ inline bool is_list_iid(const IID& iid) {
994 IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList5)) || 1024 IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList5)) ||
995 IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList6)) || 1025 IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList6)) ||
996 IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList7)) || 1026 IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList7)) ||
997 IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList8)); 1027 IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList8)) ||
1028 IsEqualIID(iid, kXboxGraphicsCommandListXIid);
998} 1029}
999 1030
1000inline unsigned long list_add_ref(ListProxy* self) { return self->refs.fetch_add(1, std::memory_order_relaxed) + 1; } 1031inline unsigned long list_add_ref(ListProxy* self) { return self->refs.fetch_add(1, std::memory_order_relaxed) + 1; }
@@ -1022,7 +1053,10 @@ inline HRESULT list_query_interface(ListProxy* self, const IID* riid, void** out
1022 if (supports_iid(self->real, *riid)) log_refused_iid("list", *riid); 1053 if (supports_iid(self->real, *riid)) log_refused_iid("list", *riid);
1023 return E_NOINTERFACE; 1054 return E_NOINTERFACE;
1024 } 1055 }
1025 if (!supports_iid(self->real, *riid)) return E_NOINTERFACE; 1056 const IID real_iid = IsEqualIID(*riid, kXboxGraphicsCommandListXIid)
1057 ? __uuidof(ID3D12GraphicsCommandList)
1058 : *riid;
1059 if (!supports_iid(self->real, real_iid)) return E_NOINTERFACE;
1026 *out = self; 1060 *out = self;
1027 list_add_ref(self); 1061 list_add_ref(self);
1028 return S_OK; 1062 return S_OK;
@@ -1194,6 +1228,40 @@ LONG CALLBACK table_overrun_handler(EXCEPTION_POINTERS* info) {
1194 return EXCEPTION_CONTINUE_SEARCH; // diagnostics only: the fault goes on to the title's handlers or the crash 1228 return EXCEPTION_CONTINUE_SEARCH; // diagnostics only: the fault goes on to the title's handlers or the crash
1195} 1229}
1196 1230
1231// PresentX is at queue slot 30 in an older runtime layout and 32 in a newer one (public corroboration, XCL; see
1232// docs/d3d12_vulkan.md). 30 is the default and LEONIDA_XS_PRESENT_X_SLOT sets the other. SuspendX and ResumeX have no
1233// default: 0 means not routed, so they answer only when their variable is set.
1234struct XboxQueueSlotRoutes {
1235 unsigned present_x = 30; // PresentX(plane_count, planes, params)
1236 unsigned suspend_x = 0; // SuspendX(flags)
1237 unsigned resume_x = 0; // ResumeX()
1238};
1239
1240const XboxQueueSlotRoutes& xbox_queue_slot_routes() {
1241 static const XboxQueueSlotRoutes routes = [] {
1242 XboxQueueSlotRoutes r;
1243 r.present_x = env_slot("LEONIDA_XS_PRESENT_X_SLOT", r.present_x, kQueuePublicSlots, kQueueSlots - 1,
1244 "queue slot");
1245 r.suspend_x = env_slot("LEONIDA_XS_SUSPEND_X_SLOT", r.suspend_x, kQueuePublicSlots, kQueueSlots - 1,
1246 "queue slot");
1247 r.resume_x = env_slot("LEONIDA_XS_RESUME_X_SLOT", r.resume_x, kQueuePublicSlots, kQueueSlots - 1,
1248 "queue slot");
1249 // Two routes on one slot cannot both answer: PresentX keeps it, then SuspendX; the later route is unrouted.
1250 if (r.suspend_x && r.suspend_x == r.present_x) {
1251 std::fprintf(stderr, "[rt] d3d12_xs: SuspendX slot %u is PresentX's slot; SuspendX is not routed\n",
1252 r.suspend_x);
1253 r.suspend_x = 0;
1254 }
1255 if (r.resume_x && (r.resume_x == r.present_x || r.resume_x == r.suspend_x)) {
1256 std::fprintf(stderr, "[rt] d3d12_xs: ResumeX slot %u is already routed; ResumeX is not routed\n",
1257 r.resume_x);
1258 r.resume_x = 0;
1259 }
1260 return r;
1261 }();
1262 return routes;
1263}
1264
1197template <ChildKind K, unsigned Slot> 1265template <ChildKind K, unsigned Slot>
1198std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, 1266std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3,
1199 std::uint64_t a4, std::uint64_t a5, std::uint64_t a6, std::uint64_t a7, 1267 std::uint64_t a4, std::uint64_t a5, std::uint64_t a6, std::uint64_t a7,
@@ -1214,6 +1282,27 @@ std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_
1214 } else { 1282 } else {
1215 note_child_slot<K>(Slot); 1283 note_child_slot<K>(Slot);
1216 if (Slot >= self->slot_count) { 1284 if (Slot >= self->slot_count) {
1285 if constexpr (K == ChildKind::queue) {
1286 const XboxQueueSlotRoutes& qroutes = xbox_queue_slot_routes();
1287 HRESULT hr = S_OK;
1288 if (call_presentation(self->device, [&](const PresentationHandler& p) {
1289 if (Slot == qroutes.present_x && p.present_x) {
1290 hr = p.present_x(p.context, static_cast<UINT>(a1), reinterpret_cast<const void*>(a2),
1291 reinterpret_cast<const void*>(a3));
1292 return true;
1293 }
1294 if (Slot == qroutes.suspend_x && p.suspend_x) {
1295 hr = p.suspend_x(p.context, static_cast<UINT>(a1));
1296 return true;
1297 }
1298 if (Slot == qroutes.resume_x && p.resume_x) {
1299 hr = p.resume_x(p.context);
1300 return true;
1301 }
1302 return false;
1303 }))
1304 return hr_to_u64(hr);
1305 }
1217 bool expected = false; 1306 bool expected = false;
1218 if (ChildStats<K>::beyond_warned[Slot].compare_exchange_strong(expected, true, 1307 if (ChildStats<K>::beyond_warned[Slot].compare_exchange_strong(expected, true,
1219 std::memory_order_relaxed)) { 1308 std::memory_order_relaxed)) {
@@ -1380,8 +1469,14 @@ HRESULT proxy_create_command_queue(DeviceProxy* self, const D3D12_COMMAND_QUEUE_
1380// 60 Hz), and latency is the allowed frames in flight. S_OK even for 0: a boot must not abort here, and nothing paces. 1469// 60 Hz), and latency is the allowed frames in flight. S_OK even for 0: a boot must not abort here, and nothing paces.
1381HRESULT proxy_set_frame_interval_x(DeviceProxy* self, std::uint64_t output, std::uint64_t interval_us, 1470HRESULT proxy_set_frame_interval_x(DeviceProxy* self, std::uint64_t output, std::uint64_t interval_us,
1382 std::uint64_t latency, std::uint64_t flags) { 1471 std::uint64_t latency, std::uint64_t flags) {
1383 (void)output; 1472 HRESULT hr = S_OK;
1384 (void)flags; 1473 if (call_presentation(self, [&](const PresentationHandler& p) {
1474 if (!p.set_frame_interval) return false;
1475 hr = p.set_frame_interval(p.context, reinterpret_cast<IUnknown*>(output), static_cast<UINT>(interval_us),
1476 static_cast<UINT>(latency), static_cast<UINT>(flags));
1477 return true;
1478 }))
1479 return hr;
1385 self->frame_interval_us.store(static_cast<std::uint32_t>(interval_us), std::memory_order_relaxed); 1480 self->frame_interval_us.store(static_cast<std::uint32_t>(interval_us), std::memory_order_relaxed);
1386 self->frame_latency.store(static_cast<std::uint32_t>(latency ? latency : 1), std::memory_order_relaxed); 1481 self->frame_latency.store(static_cast<std::uint32_t>(latency ? latency : 1), std::memory_order_relaxed);
1387 return S_OK; 1482 return S_OK;
@@ -1390,22 +1485,31 @@ HRESULT proxy_set_frame_interval_x(DeviceProxy* self, std::uint64_t output, std:
1390// Xbox device slot 79 (public HLE): ScheduleFrameEventX(event, offset_us, pEvent, flags); our pacer has only the origin. 1485// Xbox device slot 79 (public HLE): ScheduleFrameEventX(event, offset_us, pEvent, flags); our pacer has only the origin.
1391HRESULT proxy_schedule_frame_event_x(DeviceProxy* self, std::uint64_t event, std::uint64_t offset_us, 1486HRESULT proxy_schedule_frame_event_x(DeviceProxy* self, std::uint64_t event, std::uint64_t offset_us,
1392 std::uint64_t flags) { 1487 std::uint64_t flags) {
1393 (void)event; 1488 HRESULT hr = S_OK;
1394 (void)offset_us; 1489 if (call_presentation(self, [&](const PresentationHandler& p) {
1395 (void)flags; 1490 if (!p.schedule_frame_event) return false;
1491 hr = p.schedule_frame_event(p.context, static_cast<UINT>(event), static_cast<UINT>(offset_us),
1492 static_cast<UINT>(flags));
1493 return true;
1494 }))
1495 return hr;
1396 self->frame_event_scheduled.store(true, std::memory_order_relaxed); 1496 self->frame_event_scheduled.store(true, std::memory_order_relaxed);
1397 return S_OK; 1497 return S_OK;
1398} 1498}
1399 1499
1400// Xbox device slot 80 (public HLE): WaitFrameEventX(event, timeout_ms, pEvent, flags, &token). It returns at once with 1500// Xbox device slot 80 (public HLE): WaitFrameEventX(event, timeout_ms, pEvent, flags, &token). When a presenter is
1401// a fresh non-zero token (the first-frame choice): there is no vblank source behind the device before a presenter, and 1501// attached, forwards directly to it; otherwise returns at once with a fresh non-zero token so boot tests cannot stall.
1402// a zero wait cannot stall the title. A null token pointer is E_POINTER, as a _Out_ parameter.
1403HRESULT proxy_wait_frame_event_x(DeviceProxy* self, std::uint64_t event, std::uint64_t timeout_ms, 1502HRESULT proxy_wait_frame_event_x(DeviceProxy* self, std::uint64_t event, std::uint64_t timeout_ms,
1404 std::uint64_t flags, std::uint64_t token_word) { 1503 std::uint64_t flags, std::uint64_t token_word) {
1405 (void)event;
1406 (void)timeout_ms;
1407 (void)flags;
1408 auto* token = reinterpret_cast<std::uint64_t*>(token_word); 1504 auto* token = reinterpret_cast<std::uint64_t*>(token_word);
1505 HRESULT hr = S_OK;
1506 if (call_presentation(self, [&](const PresentationHandler& p) {
1507 if (!p.wait_frame_event) return false;
1508 hr = p.wait_frame_event(p.context, static_cast<UINT>(event), static_cast<DWORD>(timeout_ms),
1509 static_cast<UINT>(flags), token);
1510 return true;
1511 }))
1512 return hr;
1409 if (!token) return E_POINTER; 1513 if (!token) return E_POINTER;
1410 std::uint64_t value = self->frame_next_token.fetch_add(1, std::memory_order_relaxed); 1514 std::uint64_t value = self->frame_next_token.fetch_add(1, std::memory_order_relaxed);
1411 if (value == 0) value = self->frame_next_token.fetch_add(1, std::memory_order_relaxed); // skip the null token 1515 if (value == 0) value = self->frame_next_token.fetch_add(1, std::memory_order_relaxed); // skip the null token
@@ -1442,8 +1546,11 @@ HRESULT proxy_create_command_list_x(DeviceProxy* self, std::uint64_t desc_word,
1442 if (!allocator) allocator = reinterpret_cast<ID3D12CommandAllocator*>(allocator_word); 1546 if (!allocator) allocator = reinterpret_cast<ID3D12CommandAllocator*>(allocator_word);
1443 auto* initial_state = reinterpret_cast<ID3D12PipelineState*>(initial_state_word); 1547 auto* initial_state = reinterpret_cast<ID3D12PipelineState*>(initial_state_word);
1444 void* created = nullptr; 1548 void* created = nullptr;
1549 const IID& create_iid = IsEqualIID(*riid, kXboxGraphicsCommandListXIid)
1550 ? __uuidof(ID3D12GraphicsCommandList)
1551 : *riid;
1445 const HRESULT hr = self->real->CreateCommandList(0, type, allocator, initial_state, 1552 const HRESULT hr = self->real->CreateCommandList(0, type, allocator, initial_state,
1446 *riid, &created); 1553 create_iid, &created);
1447 if (FAILED(hr)) return hr; 1554 if (FAILED(hr)) return hr;
1448 return wrap_list(static_cast<IUnknown*>(created), self, riid, out); 1555 return wrap_list(static_cast<IUnknown*>(created), self, riid, out);
1449} 1556}
@@ -2038,6 +2145,22 @@ std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64
2038 log_xbox_route_once(Slot, "WaitFrameEventX", a1, a2, a3, a4, a5); 2145 log_xbox_route_once(Slot, "WaitFrameEventX", a1, a2, a3, a4, a5);
2039 return hr_to_u64(proxy_wait_frame_event_x(self, a1, a2, a4, a5)); 2146 return hr_to_u64(proxy_wait_frame_event_x(self, a1, a2, a4, a5));
2040 } 2147 }
2148 if (Slot == routes.frame_statistics) {
2149 HRESULT hr = S_OK;
2150 if (call_presentation(self, [&](const PresentationHandler& p) {
2151 if (!p.get_frame_statistics) return false;
2152 log_xbox_route_once(Slot, "GetFrameStatisticsX", a1, a2, a3, a4, a5);
2153 hr = p.get_frame_statistics(p.context, a1, static_cast<UINT>(a2), reinterpret_cast<UINT*>(a3),
2154 reinterpret_cast<void*>(a4));
2155 return true;
2156 }))
2157 return hr_to_u64(hr);
2158 // No presenter: no statistics yet (S_FALSE with a zero count, the "not available yet" answer in
2159 // docs/d3d12_vulkan.md), and never the PC slot 81 (ID3D12Device13::OpenExistingHeapFromAddress1).
2160 log_xbox_route_once(Slot, "GetFrameStatisticsX", a1, a2, a3, a4, a5);
2161 if (auto* count = reinterpret_cast<UINT*>(a3)) *count = 0;
2162 return hr_to_u64(S_FALSE);
2163 }
2041 if (Slot == routes.queue_x) { 2164 if (Slot == routes.queue_x) {
2042 log_xbox_route_once(Slot, "CreateCommandQueueX", a1, a2, a3, a4, a5); 2165 log_xbox_route_once(Slot, "CreateCommandQueueX", a1, a2, a3, a4, a5);
2043 return hr_to_u64(proxy_create_command_queue_xbox(self, reinterpret_cast<const std::uint32_t*>(a1), 2166 return hr_to_u64(proxy_create_command_queue_xbox(self, reinterpret_cast<const std::uint32_t*>(a1),
@@ -2246,6 +2369,15 @@ void set_console_descriptor_heap_handler(ConsoleDescriptorHeapHandler handler) {
2246 g_console_descriptor_heap.store(handler, std::memory_order_release); 2369 g_console_descriptor_heap.store(handler, std::memory_order_release);
2247} 2370}
2248 2371
2372bool set_presentation_handler(void* device, const PresentationHandler* handler) {
2373 auto* proxy = static_cast<DeviceProxy*>(device_proxy_primary(device));
2374 if (!proxy) return false;
2375 AcquireSRWLockExclusive(&proxy->presentation_lock);
2376 proxy->presentation = handler ? *handler : PresentationHandler{};
2377 ReleaseSRWLockExclusive(&proxy->presentation_lock);
2378 return true;
2379}
2380
2249ID3D12Device* device_proxy_real_device(const void* device) { 2381ID3D12Device* device_proxy_real_device(const void* device) {
2250 if (!is_device_proxy(device)) return nullptr; 2382 if (!is_device_proxy(device)) return nullptr;
2251 return static_cast<const DeviceProxy*>(device)->real; 2383 return static_cast<const DeviceProxy*>(device)->real;
@@ -2258,7 +2390,7 @@ bool device_slot_overridden(unsigned slot) {
2258 return true; 2390 return true;
2259 const XboxDeviceSlotRoutes& routes = xbox_device_slot_routes(); 2391 const XboxDeviceSlotRoutes& routes = xbox_device_slot_routes();
2260 return slot == routes.frame_interval || slot == routes.schedule_event || slot == routes.wait_event || 2392 return slot == routes.frame_interval || slot == routes.schedule_event || slot == routes.wait_event ||
2261 slot == routes.queue_x || slot == routes.list_x; 2393 slot == routes.frame_statistics || slot == routes.queue_x || slot == routes.list_x;
2262} 2394}
2263 2395
2264bool is_queue_proxy(const void* queue) { return is_child_proxy<ChildKind::queue>(queue); } 2396bool is_queue_proxy(const void* queue) { return is_child_proxy<ChildKind::queue>(queue); }
diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h
index 7ee880939..b7f020beb 100644
--- a/runtime/shims/d3d12_xs_device.h
+++ b/runtime/shims/d3d12_xs_device.h
@@ -132,6 +132,24 @@ using ConsoleDescriptorHeapHandler = HRESULT (*)(ID3D12Device* real, const D3D12
132 REFIID riid, void** out); 132 REFIID riid, void** out);
133void set_console_descriptor_heap_handler(ConsoleDescriptorHeapHandler handler); 133void set_console_descriptor_heap_handler(ConsoleDescriptorHeapHandler handler);
134 134
135// Presentation wiring: connects device frame-event slots (78/79/80/81: SetFrameIntervalX, ScheduleFrameEventX,
136// WaitFrameEventX, GetFrameStatisticsX; 81 is LEONIDA_XS_FRAME_STATISTICS_SLOT) and queue presentation slots (PresentX
137// at 30, or LEONIDA_XS_PRESENT_X_SLOT; SuspendX and ResumeX are routed only when LEONIDA_XS_SUSPEND_X_SLOT /
138// LEONIDA_XS_RESUME_X_SLOT are set) to an external presenter such as rt::d3d12::XboxPresentation without coupling
139// d3d12_xs_device to Vulkan headers. Passing nullptr detaches the handler and restores the default mock/fallback
140// behavior.
141struct PresentationHandler {
142 void* context = nullptr;
143 HRESULT (*set_frame_interval)(void* context, IUnknown* output, UINT interval_us, UINT latency, UINT flags) = nullptr;
144 HRESULT (*schedule_frame_event)(void* context, UINT event, UINT offset_us, UINT flags) = nullptr;
145 HRESULT (*wait_frame_event)(void* context, UINT event, DWORD timeout_ms, UINT flags, std::uint64_t* token) = nullptr;
146 HRESULT (*get_frame_statistics)(void* context, std::uint64_t token, UINT type_mask, UINT* count, void* out) = nullptr;
147 HRESULT (*present_x)(void* context, UINT plane_count, const void* planes, const void* params) = nullptr;
148 HRESULT (*suspend_x)(void* context, UINT flags) = nullptr;
149 HRESULT (*resume_x)(void* context) = nullptr;
150};
151bool set_presentation_handler(void* device, const PresentationHandler* handler);
152
135// True for slots the proxy handles itself rather than forwarding verbatim: IUnknown (0-2), 8 and 75 (queue 153// True for slots the proxy handles itself rather than forwarding verbatim: IUnknown (0-2), 8 and 75 (queue
136// proxies), 9 (allocator proxies), 14, 26 (the console's struct-return form), 154// proxies), 9 (allocator proxies), 14, 26 (the console's struct-return form),
137// 31/34/35/45/46/50 (proxies unwrapped), 32 and 36 (fence proxies), 48/73 and 155// 31/34/35/45/46/50 (proxies unwrapped), 32 and 36 (fence proxies), 48/73 and
diff --git a/runtime/shims/library_loader.cpp b/runtime/shims/library_loader.cpp
index 82dd75493..250fe0209 100644
--- a/runtime/shims/library_loader.cpp
+++ b/runtime/shims/library_loader.cpp
@@ -266,7 +266,7 @@ FARPROC WINAPI get_proc_address(HMODULE module, LPCSTR name) {
266 SetLastError(ERROR_PROC_NOT_FOUND); 266 SetLastError(ERROR_PROC_NOT_FOUND);
267 return nullptr; 267 return nullptr;
268 } 268 }
269 if (module && !IS_INTRESOURCE(name)) { 269 if (module) {
270 const DWORD error = GetLastError(); 270 const DWORD error = GetLastError();
271 const std::string dll = host_module_name(module); 271 const std::string dll = host_module_name(module);
272 void* shim = dll.empty() ? nullptr : find(dll, what); 272 void* shim = dll.empty() ? nullptr : find(dll, what);
diff --git a/runtime/shims/registry.cpp b/runtime/shims/registry.cpp
index 6ec36e31c..f041df89f 100644
--- a/runtime/shims/registry.cpp
+++ b/runtime/shims/registry.cpp
@@ -494,7 +494,8 @@ void* find(const std::string& dll_lower, const std::string& name) {
494 494
495bool owns_dll(const std::string& dll_lower) { 495bool owns_dll(const std::string& dll_lower) {
496 static const char* const host[] = {"kernel32.dll", "kernelbase.dll", "msvcrt.dll", "ucrtbase.dll", "ucrtbased.dll", 496 static const char* const host[] = {"kernel32.dll", "kernelbase.dll", "msvcrt.dll", "ucrtbase.dll", "ucrtbased.dll",
497 "vulkan-1.dll", "ntdll.dll", "user32.dll"}; 497 "vulkan-1.dll", "ntdll.dll", "user32.dll", "ws2_32.dll",
498 "wsock32.dll"};
498 if (starts_with(dll_lower, "api-ms-") || starts_with(dll_lower, "ext-ms-")) return false; 499 if (starts_with(dll_lower, "api-ms-") || starts_with(dll_lower, "ext-ms-")) return false;
499 for (const char* h : host) 500 for (const char* h : host)
500 if (dll_lower == h) return false; 501 if (dll_lower == h) return false;
diff --git a/runtime/shims/ws2_offline.cpp b/runtime/shims/ws2_offline.cpp
new file mode 100644
index 000000000..0a278eb99
--- /dev/null
+++ b/runtime/shims/ws2_offline.cpp
@@ -0,0 +1,949 @@
1// ws2_offline: Winsock2 (ws2_32.dll and its wsock32.dll alias) for a mapped title, restricted to loopback only.
2//
3// Nothing in Leonida goes online. While winhttp_offline.cpp owns winhttp.dll, a title can also import Winsock2
4// functions directly (both by name and by standard Windows ws2_32.dll ordinal) or resolve them through
5// GetProcAddress / WSAIoctl. Bound straight to the host's ws2_32.dll, those calls could open external sockets or
6// trigger DNS queries. wsock32.dll exports forward to ws2_32 natively, so its bind/connect/sendto/gethostby* entries
7// go to the same wrappers.
8//
9// ws2_32.dll stays host-owned in rt::shims::owns_dll (partial override, like kernel32.dll), so socket bookkeeping
10// (WSAStartup, socket, closesocket, select, setsockopt, recv, send, byte-order helpers, freeaddrinfo) continues to
11// run natively on loopback sockets while every outbound, bind, name-resolution, and extension-lookup entry point is
12// vetted here:
13// - connect (#4), WSAConnect, WSAConnectByNameA/W, WSAConnectByList, ConnectEx (from WSAIoctl), sendto (#20),
14// WSASendTo, and WSASendMsg (direct and via WSAIoctl) permit only IPv4 loopback (127.0.0.0/8), IPv6 loopback
15// (::1), and IPv4-mapped IPv6 loopback (::ffff:127.0.0.0/104). Every other destination fails with WSAENETUNREACH.
16// WSAConnectByNameA/W pass "localhost" to the host as the literal 127.0.0.1, so the hosts file is never read.
17// - bind (#2) rewrites wildcard binds (0.0.0.0 or ::) to 127.0.0.1 or ::1 so no external peer can connect in,
18// allows explicit loopback binds, and refuses any other address with WSAEADDRNOTAVAIL.
19// - getaddrinfo, GetAddrInfoW, GetAddrInfoExA/W, gethostbyname (#52), gethostbyaddr (#51), and
20// WSAAsyncGetHostByName/Addr (#103/#102) permit only null/empty nodes, "localhost", and loopback IP literals;
21// everything else fails with WSAHOST_NOT_FOUND without sending DNS packets. A dotted octet with a leading zero
22// (0127.0.0.1) is refused: Windows reads it as octal, so it is not the loopback name it looks like.
23// - WSALookupServiceBeginA/W (name-service queries) always fail with WSASERVICE_NOT_FOUND.
24// - getnameinfo / GetNameInfoW force NI_NUMERICHOST for non-loopback addresses (or return WSAHOST_NOT_FOUND when
25// NI_NAMEREQD is set), avoiding reverse DNS lookups.
26// - WSAIoctl wraps WSAID_CONNECTEX and WSAID_WSASENDMSG and refuses SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER
27// with WSAEINVAL so extension functions cannot bypass the checks. The wrappers ask the host for the native
28// pointer of the socket they are called on, since each Winsock provider has its own.
29//
30// Every host ws2_32.dll call is resolved dynamically from System32 so gta6rt needs no static ws2_32.lib link
31// dependency. Each refused destination is logged once ("[rt] ws2: offline, refused <op> <target>") with no payload.
32#ifndef _WINSOCK_DEPRECATED_NO_WARNINGS
33#define _WINSOCK_DEPRECATED_NO_WARNINGS
34#endif
35#ifndef WIN32_LEAN_AND_MEAN
36#define WIN32_LEAN_AND_MEAN
37#endif
38#ifndef NOMINMAX
39#define NOMINMAX
40#endif
41
42#include <winsock2.h>
43#include <ws2tcpip.h>
44#include <mswsock.h>
45#include <windows.h>
46
47#include <cstdint>
48#include <cstdio>
49#include <cstring>
50#include <mutex>
51#include <set>
52#include <string>
53
54#include "shims.h"
55
56#ifndef SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER
57#define SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER 0xC8000024u
58#endif
59
60namespace rt::ws2 {
61namespace {
62
63HMODULE host_ws2() {
64 static HMODULE mod = LoadLibraryExW(L"ws2_32.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
65 return mod;
66}
67
68template <typename Fn>
69Fn host_proc(const char* name) {
70 HMODULE mod = host_ws2();
71 return mod ? reinterpret_cast<Fn>(GetProcAddress(mod, name)) : nullptr;
72}
73
74void set_wsa_error(int err) {
75 using SetErrFn = void(WSAAPI*)(int);
76 static SetErrFn fn = host_proc<SetErrFn>("WSASetLastError");
77 if (fn) {
78 fn(err);
79 } else {
80 SetLastError(static_cast<DWORD>(err));
81 }
82}
83
84uint16_t read_be16(uint16_t net_val) {
85 const auto* b = reinterpret_cast<const uint8_t*>(&net_val);
86 return static_cast<uint16_t>((static_cast<uint16_t>(b[0]) << 8) | b[1]);
87}
88
89bool is_ipv4_loopback_bytes(const uint8_t b[4]) { return b[0] == 127; }
90
91bool is_ipv4_unspecified_bytes(const uint8_t b[4]) { return b[0] == 0 && b[1] == 0 && b[2] == 0 && b[3] == 0; }
92
93bool is_ipv6_loopback_bytes(const uint8_t b[16]) {
94 // ::1
95 bool exact_loopback = true;
96 for (int i = 0; i < 15; ++i) {
97 if (b[i] != 0) {
98 exact_loopback = false;
99 break;
100 }
101 }
102 if (exact_loopback && b[15] == 1) return true;
103
104 // ::ffff:127.0.0.0/104 (IPv4-mapped loopback)
105 for (int i = 0; i < 10; ++i) {
106 if (b[i] != 0) return false;
107 }
108 return b[10] == 0xff && b[11] == 0xff && b[12] == 127;
109}
110
111bool is_ipv6_unspecified_bytes(const uint8_t b[16]) {
112 for (int i = 0; i < 16; ++i) {
113 if (b[i] != 0) return false;
114 }
115 return true;
116}
117
118bool is_loopback_sockaddr(const sockaddr* sa, int namelen) {
119 if (!sa || namelen < static_cast<int>(sizeof(ADDRESS_FAMILY))) return false;
120 if (sa->sa_family == AF_INET) {
121 if (namelen < static_cast<int>(sizeof(sockaddr_in))) return false;
122 sockaddr_in v4{};
123 std::memcpy(&v4, sa, sizeof(v4));
124 const auto* b = reinterpret_cast<const uint8_t*>(&v4.sin_addr);
125 return is_ipv4_loopback_bytes(b);
126 }
127 if (sa->sa_family == AF_INET6) {
128 if (namelen < static_cast<int>(sizeof(sockaddr_in6))) return false;
129 sockaddr_in6 v6{};
130 std::memcpy(&v6, sa, sizeof(v6));
131 const auto* b = reinterpret_cast<const uint8_t*>(&v6.sin6_addr);
132 return is_ipv6_loopback_bytes(b);
133 }
134 return false;
135}
136
137std::string format_sockaddr(const sockaddr* sa, int namelen) {
138 if (!sa || namelen < static_cast<int>(sizeof(ADDRESS_FAMILY))) return "<invalid>";
139 char buf[96] = {};
140 if (sa->sa_family == AF_INET && namelen >= static_cast<int>(sizeof(sockaddr_in))) {
141 sockaddr_in v4{};
142 std::memcpy(&v4, sa, sizeof(v4));
143 const auto* b = reinterpret_cast<const uint8_t*>(&v4.sin_addr);
144 std::snprintf(buf, sizeof(buf), "%u.%u.%u.%u:%u", b[0], b[1], b[2], b[3],
145 static_cast<unsigned>(read_be16(v4.sin_port)));
146 return buf;
147 }
148 if (sa->sa_family == AF_INET6 && namelen >= static_cast<int>(sizeof(sockaddr_in6))) {
149 sockaddr_in6 v6{};
150 std::memcpy(&v6, sa, sizeof(v6));
151 const auto* b = reinterpret_cast<const uint8_t*>(&v6.sin6_addr);
152 std::snprintf(buf, sizeof(buf), "[%02x%02x:%02x%02x:...:%02x%02x]:%u", b[0], b[1], b[2], b[3], b[14], b[15],
153 static_cast<unsigned>(read_be16(v6.sin6_port)));
154 return buf;
155 }
156 std::snprintf(buf, sizeof(buf), "family=%u", static_cast<unsigned>(sa->sa_family));
157 return buf;
158}
159
160void log_refused(const char* op, const std::string& target) {
161 // Intentionally immortal: mapped-DLL teardown can run after normal statics are destroyed.
162 static auto* mutex = new std::mutex;
163 static auto* seen = new std::set<std::string>;
164 const std::string key = std::string(op) + " " + target;
165 std::lock_guard lock(*mutex);
166 if (seen->insert(key).second) {
167 std::fprintf(stderr, "[rt] ws2: offline, refused %s %s\n", op, target.c_str());
168 }
169}
170
171bool ascii_iequals(const char* a, const char* b) {
172 if (!a || !b) return false;
173 while (*a && *b) {
174 unsigned char ca = static_cast<unsigned char>(*a++);
175 unsigned char cb = static_cast<unsigned char>(*b++);
176 if (ca >= 'A' && ca <= 'Z') ca = static_cast<unsigned char>(ca + 32);
177 if (cb >= 'A' && cb <= 'Z') cb = static_cast<unsigned char>(cb + 32);
178 if (ca != cb) return false;
179 }
180 return *a == '\0' && *b == '\0';
181}
182
183std::string narrow_ascii(const wchar_t* w) {
184 std::string out;
185 if (!w) return out;
186 for (; *w; ++w) out += (*w < 0x80) ? static_cast<char>(*w) : '?';
187 return out;
188}
189
190bool parse_ipv4_literal(const char* s, uint8_t out[4]) {
191 if (!s || !*s) return false;
192 const char* p = s;
193 for (int part = 0; part < 4; ++part) {
194 if (*p < '0' || *p > '9') return false;
195 const char* start = p;
196 unsigned val = 0;
197 int digits = 0;
198 while (*p >= '0' && *p <= '9') {
199 val = val * 10u + static_cast<unsigned>(*p - '0');
200 if (val > 255u) return false;
201 ++p;
202 ++digits;
203 }
204 if (digits == 0) return false;
205 if (digits > 1 && *start == '0') return false; // a leading zero is octal to Windows: 0127 is 87, not 127
206 out[part] = static_cast<uint8_t>(val);
207 if (part < 3) {
208 if (*p != '.') return false;
209 ++p;
210 }
211 }
212 return *p == '\0';
213}
214
215bool is_loopback_node_a(const char* node) {
216 if (!node || !*node) return true;
217 if (ascii_iequals(node, "localhost") || ascii_iequals(node, "localhost.")) return true;
218
219 uint8_t v4[4] = {};
220 if (parse_ipv4_literal(node, v4)) return is_ipv4_loopback_bytes(v4);
221
222 // Strip optional brackets and IPv6 zone suffix (%...) for literal check via host inet_pton.
223 std::string clean(node);
224 if (clean.size() >= 2 && clean.front() == '[' && clean.back() == ']') {
225 clean = clean.substr(1, clean.size() - 2);
226 }
227 if (const size_t pct = clean.find('%'); pct != std::string::npos) {
228 clean.resize(pct);
229 }
230
231 using InetPtonFn = INT(WSAAPI*)(INT, PCSTR, PVOID);
232 static InetPtonFn pton = host_proc<InetPtonFn>("inet_pton");
233 if (pton) {
234 uint8_t v6[16] = {};
235 if (pton(AF_INET6, clean.c_str(), v6) == 1) return is_ipv6_loopback_bytes(v6);
236 } else if (clean == "::1") {
237 return true;
238 }
239 return false;
240}
241
242bool is_loopback_node_w(const wchar_t* node) {
243 if (!node || !*node) return true;
244 for (const wchar_t* p = node; *p; ++p) {
245 if (*p >= 0x80) return false;
246 }
247 const std::string ascii = narrow_ascii(node);
248 return is_loopback_node_a(ascii.c_str());
249}
250
251bool is_localhost_name_a(const char* node) {
252 return ascii_iequals(node, "localhost") || ascii_iequals(node, "localhost.");
253}
254
255// ---- Socket connect / send / bind shims ----
256
257int WSAAPI connect_offline(SOCKET s, const sockaddr* name, int namelen) {
258 if (!is_loopback_sockaddr(name, namelen)) {
259 log_refused("connect", format_sockaddr(name, namelen));
260 set_wsa_error(WSAENETUNREACH);
261 return SOCKET_ERROR;
262 }
263 using Fn = int(WSAAPI*)(SOCKET, const sockaddr*, int);
264 static Fn real_fn = host_proc<Fn>("connect");
265 if (!real_fn) {
266 set_wsa_error(WSAENETUNREACH);
267 return SOCKET_ERROR;
268 }
269 return real_fn(s, name, namelen);
270}
271
272int WSAAPI wsa_connect_offline(SOCKET s, const sockaddr* name, int namelen, LPWSABUF caller_data,
273 LPWSABUF callee_data, LPQOS sqos, LPQOS gqos) {
274 if (!is_loopback_sockaddr(name, namelen)) {
275 log_refused("WSAConnect", format_sockaddr(name, namelen));
276 set_wsa_error(WSAENETUNREACH);
277 return SOCKET_ERROR;
278 }
279 using Fn = int(WSAAPI*)(SOCKET, const sockaddr*, int, LPWSABUF, LPWSABUF, LPQOS, LPQOS);
280 static Fn real_fn = host_proc<Fn>("WSAConnect");
281 if (!real_fn) {
282 set_wsa_error(WSAENETUNREACH);
283 return SOCKET_ERROR;
284 }
285 return real_fn(s, name, namelen, caller_data, callee_data, sqos, gqos);
286}
287
288BOOL WSAAPI wsa_connect_by_name_a_offline(SOCKET s, LPCSTR nodename, LPCSTR servicename,
289 LPDWORD local_addr_len, LPSOCKADDR local_addr,
290 LPDWORD remote_addr_len, LPSOCKADDR remote_addr,
291 const timeval* timeout, LPWSAOVERLAPPED reserved) {
292 if (!nodename || !*nodename || !is_loopback_node_a(nodename)) {
293 log_refused("WSAConnectByNameA", nodename ? nodename : "<null>");
294 set_wsa_error(WSAENETUNREACH);
295 return FALSE;
296 }
297 using Fn = BOOL(WSAAPI*)(SOCKET, LPCSTR, LPCSTR, LPDWORD, LPSOCKADDR, LPDWORD, LPSOCKADDR, const timeval*,
298 LPWSAOVERLAPPED);
299 static Fn real_fn = host_proc<Fn>("WSAConnectByNameA");
300 if (!real_fn) {
301 set_wsa_error(WSAENETUNREACH);
302 return FALSE;
303 }
304 // The host would resolve "localhost" through its hosts file; hand it the literal instead.
305 LPCSTR node = is_localhost_name_a(nodename) ? "127.0.0.1" : nodename;
306 return real_fn(s, node, servicename, local_addr_len, local_addr, remote_addr_len, remote_addr, timeout, reserved);
307}
308
309BOOL WSAAPI wsa_connect_by_name_w_offline(SOCKET s, LPWSTR nodename, LPWSTR servicename,
310 LPDWORD local_addr_len, LPSOCKADDR local_addr,
311 LPDWORD remote_addr_len, LPSOCKADDR remote_addr,
312 const timeval* timeout, LPWSAOVERLAPPED reserved) {
313 if (!nodename || !*nodename || !is_loopback_node_w(nodename)) {
314 log_refused("WSAConnectByNameW", nodename ? narrow_ascii(nodename) : "<null>");
315 set_wsa_error(WSAENETUNREACH);
316 return FALSE;
317 }
318 using Fn = BOOL(WSAAPI*)(SOCKET, LPWSTR, LPWSTR, LPDWORD, LPSOCKADDR, LPDWORD, LPSOCKADDR, const timeval*,
319 LPWSAOVERLAPPED);
320 static Fn real_fn = host_proc<Fn>("WSAConnectByNameW");
321 if (!real_fn) {
322 set_wsa_error(WSAENETUNREACH);
323 return FALSE;
324 }
325 // The host would resolve "localhost" through its hosts file; hand it the literal instead.
326 wchar_t loopback[] = L"127.0.0.1";
327 LPWSTR node = is_localhost_name_a(narrow_ascii(nodename).c_str()) ? loopback : nodename;
328 return real_fn(s, node, servicename, local_addr_len, local_addr, remote_addr_len, remote_addr, timeout, reserved);
329}
330
331BOOL WSAAPI wsa_connect_by_list_offline(SOCKET s, PSOCKET_ADDRESS_LIST addr_list, LPDWORD local_addr_len,
332 LPSOCKADDR local_addr, LPDWORD remote_addr_len, LPSOCKADDR remote_addr,
333 const timeval* timeout, LPWSAOVERLAPPED reserved) {
334 if (!addr_list || addr_list->iAddressCount <= 0) {
335 set_wsa_error(WSAEINVAL);
336 return FALSE;
337 }
338 for (INT i = 0; i < addr_list->iAddressCount; ++i) {
339 const SOCKET_ADDRESS& entry = addr_list->Address[i];
340 if (!is_loopback_sockaddr(entry.lpSockaddr, entry.iSockaddrLength)) {
341 log_refused("WSAConnectByList", format_sockaddr(entry.lpSockaddr, entry.iSockaddrLength));
342 set_wsa_error(WSAENETUNREACH);
343 return FALSE;
344 }
345 }
346 using Fn = BOOL(WSAAPI*)(SOCKET, PSOCKET_ADDRESS_LIST, LPDWORD, LPSOCKADDR, LPDWORD, LPSOCKADDR, const timeval*,
347 LPWSAOVERLAPPED);
348 static Fn real_fn = host_proc<Fn>("WSAConnectByList");
349 if (!real_fn) {
350 set_wsa_error(WSAENETUNREACH);
351 return FALSE;
352 }
353 return real_fn(s, addr_list, local_addr_len, local_addr, remote_addr_len, remote_addr, timeout, reserved);
354}
355
356// sendto, WSASendTo, WSASendMsg and WSAJoinLeaf bind an unbound socket to the wildcard address (Microsoft's remarks
357// for sendto and WSAJoinLeaf: getsockname then reports 0.0.0.0 or ::), so its port would also take datagrams from other
358// hosts. Bind such a socket to the loopback address of the (already checked) loopback destination's family first.
359// Returns false, with WSAEADDRNOTAVAIL set, only if the socket is still unbound afterwards.
360bool bind_loopback_if_unbound(SOCKET s, const sockaddr* dest) {
361 using NameFn = int(WSAAPI*)(SOCKET, sockaddr*, int*);
362 using BindFn = int(WSAAPI*)(SOCKET, const sockaddr*, int);
363 using LastErrFn = int(WSAAPI*)();
364 static NameFn real_getsockname = host_proc<NameFn>("getsockname");
365 static BindFn real_bind = host_proc<BindFn>("bind");
366 static LastErrFn real_last_error = host_proc<LastErrFn>("WSAGetLastError");
367 if (!real_getsockname || !real_bind || !real_last_error) {
368 set_wsa_error(WSAEADDRNOTAVAIL);
369 return false;
370 }
371 // Unbound is WSAEINVAL; any other getsockname error (not a socket, ...) is left for the real call to report.
372 const auto unbound = [&] {
373 sockaddr_storage local{};
374 int local_len = sizeof(local);
375 return real_getsockname(s, reinterpret_cast<sockaddr*>(&local), &local_len) == SOCKET_ERROR &&
376 real_last_error() == WSAEINVAL;
377 };
378 if (!unbound()) return true;
379
380 sockaddr_storage local{};
381 int local_len = 0;
382 if (dest->sa_family == AF_INET) {
383 auto* v4 = reinterpret_cast<sockaddr_in*>(&local);
384 v4->sin_family = AF_INET;
385 auto* b = reinterpret_cast<uint8_t*>(&v4->sin_addr);
386 b[0] = 127;
387 b[3] = 1;
388 local_len = sizeof(sockaddr_in);
389 } else {
390 sockaddr_in6 to6{};
391 std::memcpy(&to6, dest, sizeof(to6));
392 const auto* d = reinterpret_cast<const uint8_t*>(&to6.sin6_addr);
393 auto* v6 = reinterpret_cast<sockaddr_in6*>(&local);
394 v6->sin6_family = AF_INET6;
395 auto* b = reinterpret_cast<uint8_t*>(&v6->sin6_addr);
396 if (d[10] == 0xff && d[11] == 0xff) { // IPv4-mapped loopback destination: ::ffff:127.0.0.1
397 b[10] = 0xff;
398 b[11] = 0xff;
399 b[12] = 127;
400 b[15] = 1;
401 } else { // ::1
402 b[15] = 1;
403 }
404 local_len = sizeof(sockaddr_in6);
405 }
406 // A concurrent send on the same socket may have bound it between the two checks; that bind came through here too.
407 if (real_bind(s, reinterpret_cast<const sockaddr*>(&local), local_len) == 0 || !unbound()) return true;
408 log_refused("implicit wildcard bind", format_sockaddr(reinterpret_cast<const sockaddr*>(&local), local_len));
409 set_wsa_error(WSAEADDRNOTAVAIL);
410 return false;
411}
412
413int WSAAPI sendto_offline(SOCKET s, const char* buf, int len, int flags, const sockaddr* to, int tolen) {
414 if (to && tolen > 0 && !is_loopback_sockaddr(to, tolen)) {
415 log_refused("sendto", format_sockaddr(to, tolen));
416 set_wsa_error(WSAENETUNREACH);
417 return SOCKET_ERROR;
418 }
419 if (to && tolen > 0 && !bind_loopback_if_unbound(s, to)) return SOCKET_ERROR;
420 using Fn = int(WSAAPI*)(SOCKET, const char*, int, int, const sockaddr*, int);
421 static Fn real_fn = host_proc<Fn>("sendto");
422 if (!real_fn) {
423 set_wsa_error(WSAENETUNREACH);
424 return SOCKET_ERROR;
425 }
426 return real_fn(s, buf, len, flags, to, tolen);
427}
428
429int WSAAPI wsa_send_to_offline(SOCKET s, LPWSABUF buffers, DWORD buffer_count, LPDWORD bytes_sent, DWORD flags,
430 const sockaddr* to, int tolen, LPWSAOVERLAPPED overlapped,
431 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion) {
432 if (to && tolen > 0 && !is_loopback_sockaddr(to, tolen)) {
433 log_refused("WSASendTo", format_sockaddr(to, tolen));
434 set_wsa_error(WSAENETUNREACH);
435 return SOCKET_ERROR;
436 }
437 if (to && tolen > 0 && !bind_loopback_if_unbound(s, to)) return SOCKET_ERROR;
438 using Fn = int(WSAAPI*)(SOCKET, LPWSABUF, DWORD, LPDWORD, DWORD, const sockaddr*, int, LPWSAOVERLAPPED,
439 LPWSAOVERLAPPED_COMPLETION_ROUTINE);
440 static Fn real_fn = host_proc<Fn>("WSASendTo");
441 if (!real_fn) {
442 set_wsa_error(WSAENETUNREACH);
443 return SOCKET_ERROR;
444 }
445 return real_fn(s, buffers, buffer_count, bytes_sent, flags, to, tolen, overlapped, completion);
446}
447
448int WSAAPI wsa_send_msg_offline(SOCKET s, LPWSAMSG msg, DWORD flags, LPDWORD bytes_sent,
449 LPWSAOVERLAPPED overlapped, LPWSAOVERLAPPED_COMPLETION_ROUTINE completion) {
450 if (msg && msg->name && msg->namelen > 0 && !is_loopback_sockaddr(msg->name, msg->namelen)) {
451 log_refused("WSASendMsg", format_sockaddr(msg->name, msg->namelen));
452 set_wsa_error(WSAENETUNREACH);
453 return SOCKET_ERROR;
454 }
455 if (msg && msg->name && msg->namelen > 0 && !bind_loopback_if_unbound(s, msg->name)) return SOCKET_ERROR;
456 using Fn = int(WSAAPI*)(SOCKET, LPWSAMSG, DWORD, LPDWORD, LPWSAOVERLAPPED, LPWSAOVERLAPPED_COMPLETION_ROUTINE);
457 static Fn real_fn = host_proc<Fn>("WSASendMsg");
458 if (!real_fn) {
459 set_wsa_error(WSAENETUNREACH);
460 return SOCKET_ERROR;
461 }
462 return real_fn(s, msg, flags, bytes_sent, overlapped, completion);
463}
464
465int WSAAPI bind_offline(SOCKET s, const sockaddr* name, int namelen) {
466 if (!name || namelen < static_cast<int>(sizeof(ADDRESS_FAMILY))) {
467 set_wsa_error(WSAEINVAL);
468 return SOCKET_ERROR;
469 }
470 using Fn = int(WSAAPI*)(SOCKET, const sockaddr*, int);
471 static Fn real_fn = host_proc<Fn>("bind");
472 if (!real_fn) {
473 set_wsa_error(WSAEADDRNOTAVAIL);
474 return SOCKET_ERROR;
475 }
476
477 if (name->sa_family == AF_INET && namelen >= static_cast<int>(sizeof(sockaddr_in))) {
478 sockaddr_in v4{};
479 std::memcpy(&v4, name, sizeof(v4));
480 auto* b = reinterpret_cast<uint8_t*>(&v4.sin_addr);
481 if (is_ipv4_unspecified_bytes(b)) {
482 b[0] = 127;
483 b[1] = 0;
484 b[2] = 0;
485 b[3] = 1;
486 return real_fn(s, reinterpret_cast<const sockaddr*>(&v4), sizeof(v4));
487 }
488 if (is_ipv4_loopback_bytes(b)) {
489 return real_fn(s, name, namelen);
490 }
491 } else if (name->sa_family == AF_INET6 && namelen >= static_cast<int>(sizeof(sockaddr_in6))) {
492 sockaddr_in6 v6{};
493 std::memcpy(&v6, name, sizeof(v6));
494 auto* b = reinterpret_cast<uint8_t*>(&v6.sin6_addr);
495 if (is_ipv6_unspecified_bytes(b)) {
496 b[15] = 1;
497 return real_fn(s, reinterpret_cast<const sockaddr*>(&v6), sizeof(v6));
498 }
499 if (is_ipv6_loopback_bytes(b)) {
500 return real_fn(s, name, namelen);
501 }
502 }
503
504 log_refused("bind", format_sockaddr(name, namelen));
505 set_wsa_error(WSAEADDRNOTAVAIL);
506 return SOCKET_ERROR;
507}
508
509// ---- Multicast ----
510
511// A multicast group join makes the host announce membership on a real interface and receive the group's traffic
512// from other hosts, so every join is refused. Leaving a group and the other options pass through.
513bool is_multicast_join(int level, int optname) {
514 if (level == IPPROTO_IP) {
515 return optname == IP_ADD_MEMBERSHIP || optname == IP_ADD_SOURCE_MEMBERSHIP || optname == MCAST_JOIN_GROUP ||
516 optname == MCAST_JOIN_SOURCE_GROUP;
517 }
518 if (level == IPPROTO_IPV6) {
519 return optname == IPV6_ADD_MEMBERSHIP || optname == MCAST_JOIN_GROUP || optname == MCAST_JOIN_SOURCE_GROUP;
520 }
521 return false;
522}
523
524int refuse_multicast_join(const char* op, int level, int optname) {
525 log_refused(op, "multicast join (level " + std::to_string(level) + ", option " + std::to_string(optname) + ")");
526 set_wsa_error(WSAEADDRNOTAVAIL);
527 return SOCKET_ERROR;
528}
529
530int WSAAPI setsockopt_offline(SOCKET s, int level, int optname, const char* optval, int optlen) {
531 if (is_multicast_join(level, optname)) return refuse_multicast_join("setsockopt", level, optname);
532 using Fn = int(WSAAPI*)(SOCKET, int, int, const char*, int);
533 static Fn real_fn = host_proc<Fn>("setsockopt");
534 if (!real_fn) {
535 set_wsa_error(WSAENETDOWN);
536 return SOCKET_ERROR;
537 }
538 return real_fn(s, level, optname, optval, optlen);
539}
540
541// wsock32.dll's setsockopt is its own export, not a forwarder: it takes the Winsock 1.1 IPPROTO_IP numbers, maps
542// 5 (winsock.h IP_ADD_MEMBERSHIP) to the Winsock 2 value and passes numbers it does not know through unchanged (Wine's
543// dlls/wsock32/socket.c remaps the same table). Refuse both spellings of a join, then let the host wsock32 remap.
544int WSAAPI wsock32_setsockopt_offline(SOCKET s, int level, int optname, const char* optval, int optlen) {
545 constexpr int kWinsock1AddMembership = 5;
546 if (is_multicast_join(level, optname) || (level == IPPROTO_IP && optname == kWinsock1AddMembership)) {
547 return refuse_multicast_join("wsock32 setsockopt", level, optname);
548 }
549 using Fn = int(WSAAPI*)(SOCKET, int, int, const char*, int);
550 static HMODULE host_wsock32 = LoadLibraryExW(L"wsock32.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
551 static Fn real_fn = host_wsock32 ? reinterpret_cast<Fn>(GetProcAddress(host_wsock32, "setsockopt")) : nullptr;
552 if (!real_fn) {
553 set_wsa_error(WSAENETDOWN);
554 return SOCKET_ERROR;
555 }
556 return real_fn(s, level, optname, optval, optlen);
557}
558
559// WSAJoinLeaf joins a multipoint session; a group address is never loopback, so in practice every join is refused.
560SOCKET WSAAPI wsa_join_leaf_offline(SOCKET s, const sockaddr* name, int namelen, LPWSABUF caller_data,
561 LPWSABUF callee_data, LPQOS sqos, LPQOS gqos, DWORD flags) {
562 if (!is_loopback_sockaddr(name, namelen)) {
563 log_refused("WSAJoinLeaf", format_sockaddr(name, namelen));
564 set_wsa_error(WSAENETUNREACH);
565 return INVALID_SOCKET;
566 }
567 if (!bind_loopback_if_unbound(s, name)) return INVALID_SOCKET;
568 using Fn = SOCKET(WSAAPI*)(SOCKET, const sockaddr*, int, LPWSABUF, LPWSABUF, LPQOS, LPQOS, DWORD);
569 static Fn real_fn = host_proc<Fn>("WSAJoinLeaf");
570 if (!real_fn) {
571 set_wsa_error(WSAENETUNREACH);
572 return INVALID_SOCKET;
573 }
574 return real_fn(s, name, namelen, caller_data, callee_data, sqos, gqos, flags);
575}
576
577// ---- Name resolution shims ----
578
579INT WSAAPI getaddrinfo_offline(PCSTR node, PCSTR service, const ADDRINFOA* hints, PADDRINFOA* result) {
580 if (result) *result = nullptr;
581 if (!is_loopback_node_a(node)) {
582 log_refused("getaddrinfo", node ? node : "<null>");
583 set_wsa_error(WSAHOST_NOT_FOUND);
584 return WSAHOST_NOT_FOUND;
585 }
586 using Fn = INT(WSAAPI*)(PCSTR, PCSTR, const ADDRINFOA*, PADDRINFOA*);
587 static Fn real_fn = host_proc<Fn>("getaddrinfo");
588 if (!real_fn) {
589 set_wsa_error(WSAHOST_NOT_FOUND);
590 return WSAHOST_NOT_FOUND;
591 }
592 return real_fn(node, service, hints, result);
593}
594
595INT WSAAPI get_addr_info_w_offline(PCWSTR node, PCWSTR service, const ADDRINFOW* hints, PADDRINFOW* result) {
596 if (result) *result = nullptr;
597 if (!is_loopback_node_w(node)) {
598 log_refused("GetAddrInfoW", node ? narrow_ascii(node) : "<null>");
599 set_wsa_error(WSAHOST_NOT_FOUND);
600 return WSAHOST_NOT_FOUND;
601 }
602 using Fn = INT(WSAAPI*)(PCWSTR, PCWSTR, const ADDRINFOW*, PADDRINFOW*);
603 static Fn real_fn = host_proc<Fn>("GetAddrInfoW");
604 if (!real_fn) {
605 set_wsa_error(WSAHOST_NOT_FOUND);
606 return WSAHOST_NOT_FOUND;
607 }
608 return real_fn(node, service, hints, result);
609}
610
611INT WSAAPI get_addr_info_ex_a_offline(PCSTR name, PCSTR service, DWORD ns, LPGUID nsp_id, const ADDRINFOEXA* hints,
612 PADDRINFOEXA* result, timeval* timeout, LPOVERLAPPED overlapped,
613 LPLOOKUPSERVICE_COMPLETION_ROUTINE completion, LPHANDLE cancel_handle) {
614 if (result) *result = nullptr;
615 if (cancel_handle) *cancel_handle = nullptr;
616 if (!is_loopback_node_a(name)) {
617 log_refused("GetAddrInfoExA", name ? name : "<null>");
618 set_wsa_error(WSAHOST_NOT_FOUND);
619 return WSAHOST_NOT_FOUND;
620 }
621 using Fn = INT(WSAAPI*)(PCSTR, PCSTR, DWORD, LPGUID, const ADDRINFOEXA*, PADDRINFOEXA*, timeval*, LPOVERLAPPED,
622 LPLOOKUPSERVICE_COMPLETION_ROUTINE, LPHANDLE);
623 static Fn real_fn = host_proc<Fn>("GetAddrInfoExA");
624 if (!real_fn) {
625 set_wsa_error(WSAHOST_NOT_FOUND);
626 return WSAHOST_NOT_FOUND;
627 }
628 return real_fn(name, service, ns, nsp_id, hints, result, timeout, overlapped, completion, cancel_handle);
629}
630
631INT WSAAPI get_addr_info_ex_w_offline(PCWSTR name, PCWSTR service, DWORD ns, LPGUID nsp_id, const ADDRINFOEXW* hints,
632 PADDRINFOEXW* result, timeval* timeout, LPOVERLAPPED overlapped,
633 LPLOOKUPSERVICE_COMPLETION_ROUTINE completion, LPHANDLE cancel_handle) {
634 if (result) *result = nullptr;
635 if (cancel_handle) *cancel_handle = nullptr;
636 if (!is_loopback_node_w(name)) {
637 log_refused("GetAddrInfoExW", name ? narrow_ascii(name) : "<null>");
638 set_wsa_error(WSAHOST_NOT_FOUND);
639 return WSAHOST_NOT_FOUND;
640 }
641 using Fn = INT(WSAAPI*)(PCWSTR, PCWSTR, DWORD, LPGUID, const ADDRINFOEXW*, PADDRINFOEXW*, timeval*, LPOVERLAPPED,
642 LPLOOKUPSERVICE_COMPLETION_ROUTINE, LPHANDLE);
643 static Fn real_fn = host_proc<Fn>("GetAddrInfoExW");
644 if (!real_fn) {
645 set_wsa_error(WSAHOST_NOT_FOUND);
646 return WSAHOST_NOT_FOUND;
647 }
648 return real_fn(name, service, ns, nsp_id, hints, result, timeout, overlapped, completion, cancel_handle);
649}
650
651hostent* WSAAPI gethostbyname_offline(const char* name) {
652 if (!is_loopback_node_a(name)) {
653 log_refused("gethostbyname", name ? name : "<null>");
654 set_wsa_error(WSAHOST_NOT_FOUND);
655 return nullptr;
656 }
657 using Fn = hostent*(WSAAPI*)(const char*);
658 static Fn real_fn = host_proc<Fn>("gethostbyname");
659 if (!real_fn) {
660 set_wsa_error(WSAHOST_NOT_FOUND);
661 return nullptr;
662 }
663 return real_fn(name);
664}
665
666bool is_loopback_raw_addr(const char* addr, int len, int type) {
667 if (!addr) return false;
668 if (type == AF_INET && len == 4) {
669 return is_ipv4_loopback_bytes(reinterpret_cast<const uint8_t*>(addr));
670 }
671 if (type == AF_INET6 && len == 16) {
672 return is_ipv6_loopback_bytes(reinterpret_cast<const uint8_t*>(addr));
673 }
674 return false;
675}
676
677hostent* WSAAPI gethostbyaddr_offline(const char* addr, int len, int type) {
678 if (!is_loopback_raw_addr(addr, len, type)) {
679 log_refused("gethostbyaddr", "non-loopback");
680 set_wsa_error(WSAHOST_NOT_FOUND);
681 return nullptr;
682 }
683 using Fn = hostent*(WSAAPI*)(const char*, int, int);
684 static Fn real_fn = host_proc<Fn>("gethostbyaddr");
685 if (!real_fn) {
686 set_wsa_error(WSAHOST_NOT_FOUND);
687 return nullptr;
688 }
689 return real_fn(addr, len, type);
690}
691
692HANDLE WSAAPI wsa_async_get_host_by_name_offline(HWND hWnd, u_int wMsg, const char* name, char* buf, int buflen) {
693 if (!is_loopback_node_a(name)) {
694 log_refused("WSAAsyncGetHostByName", name ? name : "<null>");
695 set_wsa_error(WSAHOST_NOT_FOUND);
696 return nullptr;
697 }
698 using Fn = HANDLE(WSAAPI*)(HWND, u_int, const char*, char*, int);
699 static Fn real_fn = host_proc<Fn>("WSAAsyncGetHostByName");
700 if (!real_fn) {
701 set_wsa_error(WSAHOST_NOT_FOUND);
702 return nullptr;
703 }
704 return real_fn(hWnd, wMsg, name, buf, buflen);
705}
706
707HANDLE WSAAPI wsa_async_get_host_by_addr_offline(HWND hWnd, u_int wMsg, const char* addr, int len, int type,
708 char* buf, int buflen) {
709 if (!is_loopback_raw_addr(addr, len, type)) {
710 log_refused("WSAAsyncGetHostByAddr", "non-loopback");
711 set_wsa_error(WSAHOST_NOT_FOUND);
712 return nullptr;
713 }
714 using Fn = HANDLE(WSAAPI*)(HWND, u_int, const char*, int, int, char*, int);
715 static Fn real_fn = host_proc<Fn>("WSAAsyncGetHostByAddr");
716 if (!real_fn) {
717 set_wsa_error(WSAHOST_NOT_FOUND);
718 return nullptr;
719 }
720 return real_fn(hWnd, wMsg, addr, len, type, buf, buflen);
721}
722
723INT WSAAPI getnameinfo_offline(const sockaddr* sa, socklen_t salen, PCHAR host, DWORD host_size, PCHAR serv,
724 DWORD serv_size, INT flags) {
725 if (!is_loopback_sockaddr(sa, static_cast<int>(salen))) {
726 if ((flags & NI_NAMEREQD) != 0) {
727 log_refused("getnameinfo", format_sockaddr(sa, static_cast<int>(salen)));
728 set_wsa_error(WSAHOST_NOT_FOUND);
729 return WSAHOST_NOT_FOUND;
730 }
731 flags |= NI_NUMERICHOST;
732 }
733 using Fn = INT(WSAAPI*)(const sockaddr*, socklen_t, PCHAR, DWORD, PCHAR, DWORD, INT);
734 static Fn real_fn = host_proc<Fn>("getnameinfo");
735 if (!real_fn) {
736 set_wsa_error(WSAHOST_NOT_FOUND);
737 return WSAHOST_NOT_FOUND;
738 }
739 return real_fn(sa, salen, host, host_size, serv, serv_size, flags);
740}
741
742INT WSAAPI get_name_info_w_offline(const sockaddr* sa, socklen_t salen, PWCHAR host, DWORD host_size, PWCHAR serv,
743 DWORD serv_size, INT flags) {
744 if (!is_loopback_sockaddr(sa, static_cast<int>(salen))) {
745 if ((flags & NI_NAMEREQD) != 0) {
746 log_refused("GetNameInfoW", format_sockaddr(sa, static_cast<int>(salen)));
747 set_wsa_error(WSAHOST_NOT_FOUND);
748 return WSAHOST_NOT_FOUND;
749 }
750 flags |= NI_NUMERICHOST;
751 }
752 using Fn = INT(WSAAPI*)(const sockaddr*, socklen_t, PWCHAR, DWORD, PWCHAR, DWORD, INT);
753 static Fn real_fn = host_proc<Fn>("GetNameInfoW");
754 if (!real_fn) {
755 set_wsa_error(WSAHOST_NOT_FOUND);
756 return WSAHOST_NOT_FOUND;
757 }
758 return real_fn(sa, salen, host, host_size, serv, serv_size, flags);
759}
760
761// ---- Name-service queries (WSALookupServiceBegin) ----
762
763// Name-service (SAP/RNR) queries would reach the host's providers, so every begin call is refused.
764int WSAAPI wsa_lookup_service_begin_a_offline(LPWSAQUERYSETA restrictions, DWORD, LPHANDLE lookup) {
765 if (lookup) *lookup = nullptr;
766 const bool named = restrictions && restrictions->lpszServiceInstanceName;
767 log_refused("WSALookupServiceBeginA", named ? restrictions->lpszServiceInstanceName : "<null>");
768 set_wsa_error(WSASERVICE_NOT_FOUND);
769 return SOCKET_ERROR;
770}
771
772int WSAAPI wsa_lookup_service_begin_w_offline(LPWSAQUERYSETW restrictions, DWORD, LPHANDLE lookup) {
773 if (lookup) *lookup = nullptr;
774 const bool named = restrictions && restrictions->lpszServiceInstanceName;
775 log_refused("WSALookupServiceBeginW", named ? narrow_ascii(restrictions->lpszServiceInstanceName) : "<null>");
776 set_wsa_error(WSASERVICE_NOT_FOUND);
777 return SOCKET_ERROR;
778}
779
780// ---- WSAIoctl extension-function interception (ConnectEx / WSASendMsg) ----
781
782// The provider's own extension function for `s`. Asked per socket: each Winsock provider has its own pointers.
783template <typename Fn>
784Fn host_extension(SOCKET s, const GUID& guid) {
785 using IoctlFn = int(WSAAPI*)(SOCKET, DWORD, LPVOID, DWORD, LPVOID, DWORD, LPDWORD, LPWSAOVERLAPPED,
786 LPWSAOVERLAPPED_COMPLETION_ROUTINE);
787 static IoctlFn ioctl = host_proc<IoctlFn>("WSAIoctl");
788 if (!ioctl) return nullptr;
789 GUID requested = guid;
790 Fn fn = nullptr;
791 DWORD returned = 0;
792 if (ioctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, &requested, sizeof(requested), &fn, sizeof(fn), &returned, nullptr,
793 nullptr) != 0)
794 return nullptr;
795 return fn;
796}
797
798BOOL PASCAL connect_ex_offline(SOCKET s, const sockaddr* name, int namelen, PVOID send_buf, DWORD send_len,
799 LPDWORD bytes_sent, LPOVERLAPPED overlapped) {
800 if (!is_loopback_sockaddr(name, namelen)) {
801 log_refused("ConnectEx", format_sockaddr(name, namelen));
802 set_wsa_error(WSAENETUNREACH);
803 return FALSE;
804 }
805 static constexpr GUID kConnectExGuid = WSAID_CONNECTEX;
806 LPFN_CONNECTEX real_fn = host_extension<LPFN_CONNECTEX>(s, kConnectExGuid);
807 if (!real_fn) {
808 set_wsa_error(WSAENETUNREACH);
809 return FALSE;
810 }
811 return real_fn(s, name, namelen, send_buf, send_len, bytes_sent, overlapped);
812}
813
814int PASCAL wsa_send_msg_ext_offline(SOCKET s, LPWSAMSG msg, DWORD flags, LPDWORD bytes_sent,
815 LPWSAOVERLAPPED overlapped, LPWSAOVERLAPPED_COMPLETION_ROUTINE completion) {
816 if (msg && msg->name && msg->namelen > 0 && !is_loopback_sockaddr(msg->name, msg->namelen)) {
817 log_refused("WSASendMsg(ext)", format_sockaddr(msg->name, msg->namelen));
818 set_wsa_error(WSAENETUNREACH);
819 return SOCKET_ERROR;
820 }
821 if (msg && msg->name && msg->namelen > 0 && !bind_loopback_if_unbound(s, msg->name)) return SOCKET_ERROR;
822 static constexpr GUID kSendMsgGuid = WSAID_WSASENDMSG;
823 LPFN_WSASENDMSG real_fn = host_extension<LPFN_WSASENDMSG>(s, kSendMsgGuid);
824 if (!real_fn) {
825 set_wsa_error(WSAENETUNREACH);
826 return SOCKET_ERROR;
827 }
828 return real_fn(s, msg, flags, bytes_sent, overlapped, completion);
829}
830
831int WSAAPI wsa_ioctl_offline(SOCKET s, DWORD io_control_code, LPVOID in_buf, DWORD in_len, LPVOID out_buf,
832 DWORD out_len, LPDWORD bytes_returned, LPWSAOVERLAPPED overlapped,
833 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion) {
834 using Fn = int(WSAAPI*)(SOCKET, DWORD, LPVOID, DWORD, LPVOID, DWORD, LPDWORD, LPWSAOVERLAPPED,
835 LPWSAOVERLAPPED_COMPLETION_ROUTINE);
836 static Fn real_fn = host_proc<Fn>("WSAIoctl");
837 if (!real_fn) {
838 set_wsa_error(WSAEINVAL);
839 return SOCKET_ERROR;
840 }
841
842 if (io_control_code == SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER) {
843 set_wsa_error(WSAEINVAL);
844 return SOCKET_ERROR;
845 }
846
847 if (io_control_code == SIO_GET_EXTENSION_FUNCTION_POINTER && in_buf && in_len >= sizeof(GUID)) {
848 static constexpr GUID kConnectExGuid = WSAID_CONNECTEX;
849 static constexpr GUID kSendMsgGuid = WSAID_WSASENDMSG;
850 GUID requested{};
851 std::memcpy(&requested, in_buf, sizeof(requested));
852
853 if (std::memcmp(&requested, &kConnectExGuid, sizeof(GUID)) == 0) {
854 if (!out_buf || out_len < sizeof(void*) || !bytes_returned) {
855 set_wsa_error(WSAEFAULT);
856 return SOCKET_ERROR;
857 }
858 LPFN_CONNECTEX real_ext = nullptr;
859 DWORD returned = 0;
860 const int rc = real_fn(s, io_control_code, in_buf, in_len, &real_ext, sizeof(real_ext), &returned,
861 overlapped, completion);
862 if (rc != 0) return rc;
863 LPFN_CONNECTEX wrapped = &connect_ex_offline;
864 std::memcpy(out_buf, &wrapped, sizeof(wrapped));
865 *bytes_returned = sizeof(wrapped);
866 return 0;
867 }
868 if (std::memcmp(&requested, &kSendMsgGuid, sizeof(GUID)) == 0) {
869 if (!out_buf || out_len < sizeof(void*) || !bytes_returned) {
870 set_wsa_error(WSAEFAULT);
871 return SOCKET_ERROR;
872 }
873 LPFN_WSASENDMSG real_ext = nullptr;
874 DWORD returned = 0;
875 const int rc = real_fn(s, io_control_code, in_buf, in_len, &real_ext, sizeof(real_ext), &returned,
876 overlapped, completion);
877 if (rc != 0) return rc;
878 LPFN_WSASENDMSG wrapped = &wsa_send_msg_ext_offline;
879 std::memcpy(out_buf, &wrapped, sizeof(wrapped));
880 *bytes_returned = sizeof(wrapped);
881 return 0;
882 }
883 }
884
885 return real_fn(s, io_control_code, in_buf, in_len, out_buf, out_len, bytes_returned, overlapped, completion);
886}
887
888} // namespace
889} // namespace rt::ws2
890
891namespace {
892using namespace rt::ws2;
893} // namespace
894
895// Both named exports and the fixed Windows ordinals (#2 bind, #4 connect, #20 sendto, #21 setsockopt,
896// #51 gethostbyaddr, #52 gethostbyname, #102 WSAAsyncGetHostByAddr, #103 WSAAsyncGetHostByName) are registered so
897// static imports by ordinal and dynamic GetProcAddress lookups resolve to the same offline wrappers. wsock32.dll gets
898// the same wrappers for the entries it shares with ws2_32, since those exports forward to ws2_32 natively; its
899// setsockopt is its own export (Winsock 1.1 option numbers), so it gets its own wrapper.
900SHIM_TABLE(ws2_offline,
901 {"ws2_32.dll", "bind", reinterpret_cast<void*>(&bind_offline)},
902 {"ws2_32.dll", "#2", reinterpret_cast<void*>(&bind_offline)},
903 {"ws2_32.dll", "connect", reinterpret_cast<void*>(&connect_offline)},
904 {"ws2_32.dll", "#4", reinterpret_cast<void*>(&connect_offline)},
905 {"ws2_32.dll", "sendto", reinterpret_cast<void*>(&sendto_offline)},
906 {"ws2_32.dll", "#20", reinterpret_cast<void*>(&sendto_offline)},
907 {"ws2_32.dll", "setsockopt", reinterpret_cast<void*>(&setsockopt_offline)},
908 {"ws2_32.dll", "#21", reinterpret_cast<void*>(&setsockopt_offline)},
909 {"ws2_32.dll", "WSAJoinLeaf", reinterpret_cast<void*>(&wsa_join_leaf_offline)},
910 {"ws2_32.dll", "gethostbyaddr", reinterpret_cast<void*>(&gethostbyaddr_offline)},
911 {"ws2_32.dll", "#51", reinterpret_cast<void*>(&gethostbyaddr_offline)},
912 {"ws2_32.dll", "gethostbyname", reinterpret_cast<void*>(&gethostbyname_offline)},
913 {"ws2_32.dll", "#52", reinterpret_cast<void*>(&gethostbyname_offline)},
914 {"ws2_32.dll", "WSAAsyncGetHostByAddr", reinterpret_cast<void*>(&wsa_async_get_host_by_addr_offline)},
915 {"ws2_32.dll", "#102", reinterpret_cast<void*>(&wsa_async_get_host_by_addr_offline)},
916 {"ws2_32.dll", "WSAAsyncGetHostByName", reinterpret_cast<void*>(&wsa_async_get_host_by_name_offline)},
917 {"ws2_32.dll", "#103", reinterpret_cast<void*>(&wsa_async_get_host_by_name_offline)},
918 {"ws2_32.dll", "getaddrinfo", reinterpret_cast<void*>(&getaddrinfo_offline)},
919 {"ws2_32.dll", "GetAddrInfoW", reinterpret_cast<void*>(&get_addr_info_w_offline)},
920 {"ws2_32.dll", "GetAddrInfoExA", reinterpret_cast<void*>(&get_addr_info_ex_a_offline)},
921 {"ws2_32.dll", "GetAddrInfoExW", reinterpret_cast<void*>(&get_addr_info_ex_w_offline)},
922 {"ws2_32.dll", "getnameinfo", reinterpret_cast<void*>(&getnameinfo_offline)},
923 {"ws2_32.dll", "GetNameInfoW", reinterpret_cast<void*>(&get_name_info_w_offline)},
924 {"ws2_32.dll", "WSAConnect", reinterpret_cast<void*>(&wsa_connect_offline)},
925 {"ws2_32.dll", "WSAConnectByNameA", reinterpret_cast<void*>(&wsa_connect_by_name_a_offline)},
926 {"ws2_32.dll", "WSAConnectByNameW", reinterpret_cast<void*>(&wsa_connect_by_name_w_offline)},
927 {"ws2_32.dll", "WSAConnectByList", reinterpret_cast<void*>(&wsa_connect_by_list_offline)},
928 {"ws2_32.dll", "WSASendTo", reinterpret_cast<void*>(&wsa_send_to_offline)},
929 {"ws2_32.dll", "WSASendMsg", reinterpret_cast<void*>(&wsa_send_msg_offline)},
930 {"ws2_32.dll", "WSAIoctl", reinterpret_cast<void*>(&wsa_ioctl_offline)},
931 {"ws2_32.dll", "WSALookupServiceBeginA", reinterpret_cast<void*>(&wsa_lookup_service_begin_a_offline)},
932 {"ws2_32.dll", "WSALookupServiceBeginW", reinterpret_cast<void*>(&wsa_lookup_service_begin_w_offline)},
933 {"wsock32.dll", "bind", reinterpret_cast<void*>(&bind_offline)},
934 {"wsock32.dll", "#2", reinterpret_cast<void*>(&bind_offline)},
935 {"wsock32.dll", "connect", reinterpret_cast<void*>(&connect_offline)},
936 {"wsock32.dll", "#4", reinterpret_cast<void*>(&connect_offline)},
937 {"wsock32.dll", "sendto", reinterpret_cast<void*>(&sendto_offline)},
938 {"wsock32.dll", "#20", reinterpret_cast<void*>(&sendto_offline)},
939 {"wsock32.dll", "setsockopt", reinterpret_cast<void*>(&wsock32_setsockopt_offline)},
940 {"wsock32.dll", "#21", reinterpret_cast<void*>(&wsock32_setsockopt_offline)},
941 {"wsock32.dll", "gethostbyaddr", reinterpret_cast<void*>(&gethostbyaddr_offline)},
942 {"wsock32.dll", "#51", reinterpret_cast<void*>(&gethostbyaddr_offline)},
943 {"wsock32.dll", "gethostbyname", reinterpret_cast<void*>(&gethostbyname_offline)},
944 {"wsock32.dll", "#52", reinterpret_cast<void*>(&gethostbyname_offline)},
945 {"wsock32.dll", "WSAAsyncGetHostByAddr", reinterpret_cast<void*>(&wsa_async_get_host_by_addr_offline)},
946 {"wsock32.dll", "#102", reinterpret_cast<void*>(&wsa_async_get_host_by_addr_offline)},
947 {"wsock32.dll", "WSAAsyncGetHostByName", reinterpret_cast<void*>(&wsa_async_get_host_by_name_offline)},
948 {"wsock32.dll", "#103", reinterpret_cast<void*>(&wsa_async_get_host_by_name_offline)},
949);
diff --git a/runtime/shims/xbox_present.cpp b/runtime/shims/xbox_present.cpp
index dd5f810cf..f8791e1bf 100644
--- a/runtime/shims/xbox_present.cpp
+++ b/runtime/shims/xbox_present.cpp
@@ -1,6 +1,7 @@
1#include "xbox_present.h" 1#include "xbox_present.h"
2 2
3#include "d3d12_trace.h" 3#include "d3d12_trace.h"
4#include "d3d12_xs_device.h"
4 5
5#include "../src/vulkan_present.h" 6#include "../src/vulkan_present.h"
6 7
@@ -66,6 +67,7 @@ XboxPresentation::XboxPresentation(std::unique_ptr<WindowPresenter> presenter, l
66} 67}
67 68
68XboxPresentation::~XboxPresentation() { 69XboxPresentation::~XboxPresentation() {
70 if (presents_.load() > 0) log_pacing_summary();
69 { 71 {
70 std::lock_guard lock(worker_mutex_); 72 std::lock_guard lock(worker_mutex_);
71 worker_stop_ = true; 73 worker_stop_ = true;
@@ -75,6 +77,26 @@ XboxPresentation::~XboxPresentation() {
75 presenter_->set_abort(nullptr); 77 presenter_->set_abort(nullptr);
76} 78}
77 79
80void XboxPresentation::log_pacing_summary() const {
81 const leonida::FramePacingSummary s = pacer_.pacing_summary();
82 std::fprintf(stderr,
83 "[rt] present: pacing summary frames=%llu samples=%llu target_us=%u mean_us=%.1f drift_us=%+.1f "
84 "p50_us=%llu p95_us=%llu p99_us=%llu latency_samples=%llu latency_p50_us=%llu "
85 "latency_p95_us=%llu latency_p99_us=%llu\n",
86 static_cast<unsigned long long>(s.frames),
87 static_cast<unsigned long long>(s.samples),
88 s.target_interval_us,
89 s.mean_us,
90 s.drift_us,
91 static_cast<unsigned long long>(s.p50_us),
92 static_cast<unsigned long long>(s.p95_us),
93 static_cast<unsigned long long>(s.p99_us),
94 static_cast<unsigned long long>(s.latency_samples),
95 static_cast<unsigned long long>(s.latency_p50_us),
96 static_cast<unsigned long long>(s.latency_p95_us),
97 static_cast<unsigned long long>(s.latency_p99_us));
98}
99
78// Windows' SDR white level costs a QueryDisplayConfig and two DisplayConfigGetDeviceInfo calls (measured in 100// Windows' SDR white level costs a QueryDisplayConfig and two DisplayConfigGetDeviceInfo calls (measured in
79// xbox_present_test, docs section 4.5): too much for the present path, which would hitch once a second and feed the pacer. 101// xbox_present_test, docs section 4.5): too much for the present path, which would hitch once a second and feed the pacer.
80// So it is read here, about once a second while an HDR10 swapchain is in use, and PresentX reads the cached value. 102// So it is read here, about once a second while an HDR10 swapchain is in use, and PresentX reads the cached value.
@@ -314,4 +336,39 @@ HRESULT XboxPresentation::ResumeX() {
314 return S_OK; 336 return S_OK;
315} 337}
316 338
339bool attach_xbox_presentation(void* device_proxy, XboxPresentation* presentation) {
340 if (!presentation) return rt::d3d12_xs::set_presentation_handler(device_proxy, nullptr);
341 rt::d3d12_xs::PresentationHandler handler{};
342 handler.context = presentation;
343 handler.set_frame_interval = [](void* ctx, IUnknown* output, UINT interval_us, UINT latency, UINT flags) {
344 return static_cast<XboxPresentation*>(ctx)->SetFrameIntervalX(output, interval_us, latency, flags);
345 };
346 handler.schedule_frame_event = [](void* ctx, UINT event, UINT offset_us, UINT flags) {
347 return static_cast<XboxPresentation*>(ctx)->ScheduleFrameEventX(event, offset_us, flags);
348 };
349 handler.wait_frame_event = [](void* ctx, UINT event, DWORD timeout_ms, UINT flags, std::uint64_t* token) {
350 return static_cast<XboxPresentation*>(ctx)->WaitFrameEventX(event, timeout_ms, flags, token);
351 };
352 handler.get_frame_statistics = [](void* ctx, std::uint64_t token, UINT type_mask, UINT* count, void* out) {
353 return static_cast<XboxPresentation*>(ctx)->GetFrameStatisticsX(
354 token, type_mask, count, static_cast<leonida::FrameStatistic*>(out));
355 };
356 handler.present_x = [](void* ctx, UINT plane_count, const void* planes, const void* params) {
357 return static_cast<XboxPresentation*>(ctx)->PresentX(
358 plane_count, static_cast<const XboxPresentPlaneParameters*>(planes),
359 static_cast<const XboxPresentParameters*>(params));
360 };
361 handler.suspend_x = [](void* ctx, UINT flags) {
362 return static_cast<XboxPresentation*>(ctx)->SuspendX(flags);
363 };
364 handler.resume_x = [](void* ctx) {
365 return static_cast<XboxPresentation*>(ctx)->ResumeX();
366 };
367 return rt::d3d12_xs::set_presentation_handler(device_proxy, &handler);
368}
369
370bool detach_xbox_presentation(void* device_proxy) {
371 return rt::d3d12_xs::set_presentation_handler(device_proxy, nullptr);
372}
373
317} // namespace rt::d3d12 374} // namespace rt::d3d12
diff --git a/runtime/shims/xbox_present.h b/runtime/shims/xbox_present.h
index 60a317bee..6230d82ea 100644
--- a/runtime/shims/xbox_present.h
+++ b/runtime/shims/xbox_present.h
@@ -171,6 +171,9 @@ public:
171 std::uint64_t presents() const { return presents_; } 171 std::uint64_t presents() const { return presents_; }
172 // Frames shown mid-scan because of ImmediateThresholdPercent. 172 // Frames shown mid-scan because of ImmediateThresholdPercent.
173 std::uint64_t immediate_presents() const { return pacer_.immediate_presents(); } 173 std::uint64_t immediate_presents() const { return pacer_.immediate_presents(); }
174 // Frame-time percentiles, mean drift against target interval, and origin-to-present latency (BL-6).
175 leonida::FramePacingSummary pacing_summary() const { return pacer_.pacing_summary(); }
176 void log_pacing_summary() const;
174 177
175private: 178private:
176 // PresentX without its `[d3d12-trace]` line. 179 // PresentX without its `[d3d12-trace]` line.
@@ -199,5 +202,15 @@ private:
199}; 202};
200 203
201inline constexpr UINT xbox_frame_event_origin = leonida::frame_event_origin; 204inline constexpr UINT xbox_frame_event_origin = leonida::frame_event_origin;
205inline constexpr UINT xbox_frame_event_vblank = leonida::frame_event_vblank;
206inline constexpr UINT xbox_frame_event_flip = leonida::frame_event_flip;
207inline constexpr UINT xbox_frame_wait_token_on_timeout = leonida::frame_wait_flag_token_on_timeout;
208
209// Seam for the presenter, not yet called by the runtime: gta6rt creates no XboxPresentation, and only
210// d3d12_boot_movie_test and xbox_present_test construct one. Wires it into a d3d12_xs device proxy's frame-event
211// slots (78–81) and queue PresentX (slot 30, or LEONIDA_XS_PRESENT_X_SLOT); SuspendX and ResumeX are routed only
212// when LEONIDA_XS_SUSPEND_X_SLOT / LEONIDA_XS_RESUME_X_SLOT are set. Passing nullptr detaches the presentation.
213bool attach_xbox_presentation(void* device_proxy, XboxPresentation* presentation);
214bool detach_xbox_presentation(void* device_proxy);
202 215
203} // namespace rt::d3d12 216} // namespace rt::d3d12
diff --git a/runtime/shims/xgameruntime_offline.cpp b/runtime/shims/xgameruntime_offline.cpp
index cc7a91d21..23a5e9d81 100644
--- a/runtime/shims/xgameruntime_offline.cpp
+++ b/runtime/shims/xgameruntime_offline.cpp
@@ -1,5 +1,5 @@
1// xgameruntime: XGameEventImpl, XGameUiImpl, XGameStreamingImpl, XDisplayImpl, XUserDeviceImpl, XAccessibilityImpl and 1// xgameruntime: XGameEventImpl, XGameUiImpl, XGameStreamingImpl, XDisplayImpl, XUserDeviceImpl, XAccessibilityImpl
2// XLauncherImpl, offline: small classes a title calls early. 2// and XLauncherImpl, offline: small classes a title calls early.
3// 3//
4// Each XGameEvent*, XGameUi* and XGameStreaming* function in xgameruntime.lib asks QueryApiImpl for its class and 4// Each XGameEvent*, XGameUi* and XGameStreaming* function in xgameruntime.lib asks QueryApiImpl for its class and
5// calls one slot with its own arguments after `this`. The class and interface ids and the method order are 5// calls one slot with its own arguments after `this`. The class and interface ids and the method order are
@@ -18,17 +18,19 @@
18// XUserDeviceImpl every device belongs to the offline user; associations and audio endpoints never change, so 18// XUserDeviceImpl every device belongs to the offline user; associations and audio endpoints never change, so
19// their change registrations are kept until unregistered and never called back; the user has 19// their change registrations are kept until unregistered and never called back; the user has
20// no audio endpoint of its own; finding a controller shows no UI (as on desktop). 20// no audio endpoint of its own; finding a controller shows no UI (as on desktop).
21// XAccessibilityImpl high contrast is Off, closed captions can't be configured, no voice is installed (enumerating 21// XAccessibilityImpl high contrast is Off, closed captions can't be configured, one silent voice is installed
22// calls back zero times), XSpeechSynthesizerCreate fails (E_FAIL) with a null handle, the other 22// (enumerating calls back once), XSpeechSynthesizerCreate hands out a synthesizer whose
23// speech calls refuse the handle they were never given (E_INVALIDARG), speech-to-text display 23// text/SSML streams return a valid 44-byte empty 16 kHz mono 16-bit PCM WAVE header so titles
24// calls fail (E_FAIL). 24// that play narration continue cleanly; speech-to-text display calls fail (E_FAIL).
25// XLauncherImpl XLaunchUri and the display timeout deferral calls fail (E_FAIL); nothing is launched. 25// XLauncherImpl XLaunchUri fails offline (E_FAIL); XDisplayAcquireTimeoutDeferral / Close acquire and clear a
26// real Win32 PowerRequestDisplayRequired handle so the host display stays awake.
26// 27//
27// Slots whose signature the public pages don't give answer with a value that is safe whichever way the caller reads 28// Slots whose signature the public pages don't give answer with a value that is safe whichever way the caller reads
28// it: see `client_not_connected` (XGameStreaming) and `offline_failure`. 29// it: see `client_not_connected` (XGameStreaming) and `offline_failure`.
29#include <windows.h> 30#include <windows.h>
30 31
31#include <atomic> 32#include <atomic>
33#include <cstddef>
32#include <cstdint> 34#include <cstdint>
33#include <cstdio> 35#include <cstdio>
34#include <cstdlib> 36#include <cstdlib>
@@ -604,38 +606,94 @@ HRESULT STDMETHODCALLTYPE accessibility_high_contrast(void*, uint32_t* mode) {
604// 4: HRESULT XClosedCaptionSetEnabled(bool enabled): there are no captions to show; accepted and dropped. 606// 4: HRESULT XClosedCaptionSetEnabled(bool enabled): there are no captions to show; accepted and dropped.
605HRESULT STDMETHODCALLTYPE accessibility_captions_set_enabled(void*, bool) { return S_OK; } 607HRESULT STDMETHODCALLTYPE accessibility_captions_set_enabled(void*, bool) { return S_OK; }
606 608
607// 8: HRESULT XSpeechSynthesizerEnumerateInstalledVoices(callback, void* context): no voice is installed, so the 609// XSpeechSynthesizerVoiceInformation and its callback, in the GDK reference's member order (the gender is
608// callback runs zero times. ASSUMPTION: the argument order (GDK reference), only the count (2) was measured. 610// XSpeechSynthesizerVoiceGender, a uint32_t enum: Female 0, Male 1).
609HRESULT STDMETHODCALLTYPE speech_enumerate_voices(void*, void* callback, void*) { 611struct SpeechVoiceInformation {
610 return callback ? S_OK : E_INVALIDARG; 612 const char* description;
613 const char* display_name;
614 uint32_t gender;
615 const char* voice_id;
616 const char* language;
617};
618static_assert(offsetof(SpeechVoiceInformation, voice_id) == 24 && sizeof(SpeechVoiceInformation) == 40, "x64 layout");
619using InstalledVoicesCallback = bool(CALLBACK*)(const SpeechVoiceInformation* information, void* context);
620constexpr SpeechVoiceInformation kSilentVoice = {"Leonida silent voice - English (United States)",
621 "Leonida silent voice", 0, "leonida-silent", "en-US"};
622
623// 8: HRESULT XSpeechSynthesizerEnumerateInstalledVoices(void* context, callback): one voice, the silent one every
624// synthesizer below speaks with. ASSUMPTION: the argument order (GDK reference), only the count (2) was measured.
625HRESULT STDMETHODCALLTYPE speech_enumerate_voices(void*, void* context, InstalledVoicesCallback callback) {
626 if (!callback) return E_INVALIDARG;
627 callback(&kSilentVoice, context);
628 return S_OK;
629}
630
631// Valid 44-byte RIFF/WAVE header for 16 kHz, 16-bit mono PCM with 0 data bytes (silent speech stream).
632constexpr uint8_t kSilentWave[44] = {
633 'R', 'I', 'F', 'F', 0x24, 0x00, 0x00, 0x00, 'W', 'A', 'V', 'E', 'f', 'm', 't', ' ',
634 0x10, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x80, 0x3e, 0x00, 0x00, 0x00, 0x7d, 0x00, 0x00,
635 0x02, 0x00, 0x10, 0x00, 'd', 'a', 't', 'a', 0x00, 0x00, 0x00, 0x00,
636};
637
638uint8_t g_speech_synth_handle = 0;
639uint8_t g_speech_stream_handle = 0;
640
641// 9: HRESULT XSpeechSynthesizerCreate(XSpeechSynthesizerHandle* handle): silent synthesizer handle.
642HRESULT STDMETHODCALLTYPE speech_create(void*, void** handle) {
643 if (!handle) return E_POINTER;
644 *handle = &g_speech_synth_handle;
645 return S_OK;
646}
647
648// 10: HRESULT XSpeechSynthesizerCloseHandle(XSpeechSynthesizerHandle handle)
649HRESULT STDMETHODCALLTYPE speech_close_synth(void*, void* handle) {
650 return handle == &g_speech_synth_handle ? S_OK : E_INVALIDARG;
611} 651}
612 652
613// 9: HRESULT XSpeechSynthesizerCreate(XSpeechSynthesizerHandle* handle): no synthesizer offline. 653// 11: HRESULT XSpeechSynthesizerSetDefaultVoice(XSpeechSynthesizerHandle handle)
614HRESULT STDMETHODCALLTYPE speech_create(void* self, void** handle) { 654HRESULT STDMETHODCALLTYPE speech_set_default_voice(void*, void* handle) {
615 if (handle) *handle = nullptr; 655 return handle == &g_speech_synth_handle ? S_OK : E_INVALIDARG;
616 return offline_failure<kAccessibilityName, 9>(self);
617} 656}
618 657
619// 10-12, 14: a synthesizer or stream handle is the first argument, and none was ever handed out: E_INVALIDARG. 658// 12: HRESULT XSpeechSynthesizerSetCustomVoice(XSpeechSynthesizerHandle handle, const char* voiceId): only the
620HRESULT STDMETHODCALLTYPE speech_bad_handle(void*) { return E_INVALIDARG; } 659// enumerated voice is installed.
660HRESULT STDMETHODCALLTYPE speech_set_custom_voice(void*, void* handle, const char* voice_id) {
661 if (handle != &g_speech_synth_handle || !voice_id) return E_INVALIDARG;
662 return std::strcmp(voice_id, kSilentVoice.voice_id) == 0 ? S_OK : E_INVALIDARG;
663}
621 664
622// 13, 21: HRESULT XSpeechSynthesizerCreateStreamFromText/Ssml(synthesizer, const char* text, 665// 13, 21: HRESULT XSpeechSynthesizerCreateStreamFromText/Ssml(synthesizer, const char* text,
623// XSpeechSynthesizerStreamHandle* stream) 666// XSpeechSynthesizerStreamHandle* stream)
624HRESULT STDMETHODCALLTYPE speech_create_stream(void*, void*, const char*, void** stream) { 667HRESULT STDMETHODCALLTYPE speech_create_stream(void*, void* synth, const char*, void** stream) {
625 if (stream) *stream = nullptr; 668 if (stream) *stream = nullptr;
626 return E_INVALIDARG; 669 if (synth != &g_speech_synth_handle) return E_INVALIDARG;
670 if (!stream) return E_POINTER;
671 *stream = &g_speech_stream_handle;
672 return S_OK;
673}
674
675// 14: HRESULT XSpeechSynthesizerCloseStreamHandle(XSpeechSynthesizerStreamHandle stream)
676HRESULT STDMETHODCALLTYPE speech_close_stream(void*, void* stream) {
677 return stream == &g_speech_stream_handle ? S_OK : E_INVALIDARG;
627} 678}
628 679
629// 15: HRESULT XSpeechSynthesizerGetStreamDataSize(stream, size_t* size) 680// 15: HRESULT XSpeechSynthesizerGetStreamDataSize(stream, size_t* size)
630HRESULT STDMETHODCALLTYPE speech_stream_size(void*, void*, size_t* size) { 681HRESULT STDMETHODCALLTYPE speech_stream_size(void*, void* stream, size_t* size) {
631 if (size) *size = 0; 682 if (size) *size = 0;
632 return E_INVALIDARG; 683 if (stream != &g_speech_stream_handle) return E_INVALIDARG;
684 if (!size) return E_POINTER;
685 *size = sizeof(kSilentWave);
686 return S_OK;
633} 687}
634 688
635// 16: HRESULT XSpeechSynthesizerGetStreamData(stream, size_t size, void* buffer, size_t* used) 689// 16: HRESULT XSpeechSynthesizerGetStreamData(stream, size_t size, void* buffer, size_t* used)
636HRESULT STDMETHODCALLTYPE speech_stream_data(void*, void*, size_t, void*, size_t* used) { 690HRESULT STDMETHODCALLTYPE speech_stream_data(void*, void* stream, size_t size, void* buffer, size_t* used) {
637 if (used) *used = 0; 691 if (used) *used = 0;
638 return E_INVALIDARG; 692 if (stream != &g_speech_stream_handle) return E_INVALIDARG;
693 if (!buffer || size < sizeof(kSilentWave)) return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
694 std::memcpy(buffer, kSilentWave, sizeof(kSilentWave));
695 if (used) *used = sizeof(kSilentWave);
696 return S_OK;
639} 697}
640 698
641// The slots with no offline counterpart whose arguments the layout doesn't give: the caption properties (3) and 699// The slots with no offline counterpart whose arguments the layout doesn't give: the caption properties (3) and
@@ -654,11 +712,11 @@ const void* const kAccessibilityVtable[] = {
654 FN(accessibility_offline<7>), // 7 XSpeechToTextSendString 712 FN(accessibility_offline<7>), // 7 XSpeechToTextSendString
655 FN(speech_enumerate_voices), // 8 XSpeechSynthesizerEnumerateInstalledVoices 713 FN(speech_enumerate_voices), // 8 XSpeechSynthesizerEnumerateInstalledVoices
656 FN(speech_create), // 9 XSpeechSynthesizerCreate 714 FN(speech_create), // 9 XSpeechSynthesizerCreate
657 FN(speech_bad_handle), // 10 XSpeechSynthesizerCloseHandle 715 FN(speech_close_synth), // 10 XSpeechSynthesizerCloseHandle
658 FN(speech_bad_handle), // 11 XSpeechSynthesizerSetDefaultVoice 716 FN(speech_set_default_voice), // 11 XSpeechSynthesizerSetDefaultVoice
659 FN(speech_bad_handle), // 12 XSpeechSynthesizerSetCustomVoice 717 FN(speech_set_custom_voice), // 12 XSpeechSynthesizerSetCustomVoice
660 FN(speech_create_stream), // 13 XSpeechSynthesizerCreateStreamFromText 718 FN(speech_create_stream), // 13 XSpeechSynthesizerCreateStreamFromText
661 FN(speech_bad_handle), // 14 XSpeechSynthesizerCloseStreamHandle 719 FN(speech_close_stream), // 14 XSpeechSynthesizerCloseStreamHandle
662 FN(speech_stream_size), // 15 XSpeechSynthesizerGetStreamDataSize 720 FN(speech_stream_size), // 15 XSpeechSynthesizerGetStreamDataSize
663 FN(speech_stream_data), // 16 XSpeechSynthesizerGetStreamData 721 FN(speech_stream_data), // 16 XSpeechSynthesizerGetStreamData
664 FN(accessibility_offline<17>), // 17 XSpeechToTextBeginHypothesisString 722 FN(accessibility_offline<17>), // 17 XSpeechToTextBeginHypothesisString
@@ -680,11 +738,31 @@ constexpr char kLauncherName[] = "XLauncherImpl";
680constexpr GUID kLauncherClass = {0x1b339674, 0x328d, 0x4283, {0xa2, 0x00, 0x31, 0x71, 0xf1, 0x8d, 0x36, 0x39}}; 738constexpr GUID kLauncherClass = {0x1b339674, 0x328d, 0x4283, {0xa2, 0x00, 0x31, 0x71, 0xf1, 0x8d, 0x36, 0x39}};
681 739
682// 3: HRESULT XLaunchUri(XUserHandle user, const char* uri): nothing is launched; E_FAIL. 740// 3: HRESULT XLaunchUri(XUserHandle user, const char* uri): nothing is launched; E_FAIL.
683// 4: HRESULT XDisplayAcquireTimeoutDeferral(XDisplayTimeoutDeferralHandle* handle): none is handed out. 741// 4: HRESULT XDisplayAcquireTimeoutDeferral(XDisplayTimeoutDeferralHandle* handle): Win32 display power request.
684// 5: XDisplayCloseTimeoutDeferralHandle(handle): no handle exists; E_FAIL, which a void caller ignores. 742// 5: void XDisplayCloseTimeoutDeferralHandle(XDisplayTimeoutDeferralHandle handle): clears and closes the request.
685HRESULT STDMETHODCALLTYPE launcher_acquire_deferral(void* self, void** handle) { 743HRESULT STDMETHODCALLTYPE launcher_acquire_deferral(void*, void** handle) {
686 if (handle) *handle = nullptr; 744 if (!handle) return E_POINTER;
687 return offline_failure<kLauncherName, 4>(self); 745 *handle = nullptr;
746 wchar_t reason[] = L"Title display timeout deferral";
747 REASON_CONTEXT ctx{};
748 ctx.Version = POWER_REQUEST_CONTEXT_VERSION;
749 ctx.Flags = POWER_REQUEST_CONTEXT_SIMPLE_STRING;
750 ctx.Reason.SimpleReasonString = reason;
751 const HANDLE req = PowerCreateRequest(&ctx);
752 if (req == INVALID_HANDLE_VALUE) return HRESULT_FROM_WIN32(GetLastError());
753 if (!PowerSetRequest(req, PowerRequestDisplayRequired)) {
754 const DWORD err = GetLastError();
755 CloseHandle(req);
756 return HRESULT_FROM_WIN32(err);
757 }
758 *handle = req;
759 return S_OK;
760}
761
762void STDMETHODCALLTYPE launcher_close_deferral(void*, void* handle) {
763 if (!handle) return;
764 PowerClearRequest(handle, PowerRequestDisplayRequired);
765 CloseHandle(handle);
688} 766}
689 767
690HRESULT STDMETHODCALLTYPE launcher_query_interface(void*, REFIID iid, void** out); 768HRESULT STDMETHODCALLTYPE launcher_query_interface(void*, REFIID iid, void** out);
@@ -692,7 +770,7 @@ const void* const kLauncherVtable[] = {
692 FN(launcher_query_interface), FN(object_add_ref), FN(object_release), // 0-2 IUnknown 770 FN(launcher_query_interface), FN(object_add_ref), FN(object_release), // 0-2 IUnknown
693 FN((offline_failure<kLauncherName, 3>)), // 3 XLaunchUri 771 FN((offline_failure<kLauncherName, 3>)), // 3 XLaunchUri
694 FN(launcher_acquire_deferral), // 4 XDisplayAcquireTimeoutDeferral 772 FN(launcher_acquire_deferral), // 4 XDisplayAcquireTimeoutDeferral
695 FN((offline_failure<kLauncherName, 5>)), // 5 XDisplayCloseTimeoutDeferralHandle 773 FN(launcher_close_deferral), // 5 XDisplayCloseTimeoutDeferralHandle
696}; 774};
697static_assert(std::size(kLauncherVtable) == 6, "IUnknown + IXLauncherImpl's 3 methods"); 775static_assert(std::size(kLauncherVtable) == 6, "IUnknown + IXLauncherImpl's 3 methods");
698ClassObject g_launcher_object{kLauncherVtable}; 776ClassObject g_launcher_object{kLauncherVtable};
diff --git a/runtime/src/cpu_emulation.h b/runtime/src/cpu_emulation.h
index fac13eeee..8df3b55d0 100644
--- a/runtime/src/cpu_emulation.h
+++ b/runtime/src/cpu_emulation.h
@@ -272,6 +272,84 @@ inline bool apply(const Decoded& d, CONTEXT* c, EXCEPTION_RECORD* fault = nullpt
272 return true; 272 return true;
273} 273}
274 274
275inline uint64_t gpr_read(const CONTEXT* c, int r) {
276 switch (r) {
277 case 0: return c->Rax; case 1: return c->Rcx; case 2: return c->Rdx; case 3: return c->Rbx;
278 case 4: return c->Rsp; case 5: return c->Rbp; case 6: return c->Rsi; case 7: return c->Rdi;
279 case 8: return c->R8; case 9: return c->R9; case 10: return c->R10; case 11: return c->R11;
280 case 12: return c->R12; case 13: return c->R13; case 14: return c->R14; case 15: return c->R15;
281 default: return 0;
282 }
283}
284
285enum class ClzeroLoopResult { no_match, ok, faulted };
286
287inline void apply_cmp_flags(CONTEXT* c, uint64_t lhs, uint64_t rhs) {
288 const uint64_t diff = lhs - rhs;
289 uint32_t flags = c->EFlags & ~DWORD(0x8D5u); // clear CF(0), PF(2), AF(4), ZF(6), SF(7), OF(11)
290 if (lhs < rhs) flags |= 0x1u; // CF
291 uint8_t lo8 = static_cast<uint8_t>(diff);
292 lo8 ^= lo8 >> 4;
293 lo8 ^= lo8 >> 2;
294 lo8 ^= lo8 >> 1;
295 if ((lo8 & 1u) == 0) flags |= 0x4u; // PF
296 if ((lhs ^ rhs ^ diff) & 0x10u) flags |= 0x10u; // AF
297 if (diff == 0) flags |= 0x40u; // ZF
298 if (diff >> 63) flags |= 0x80u; // SF
299 if (((lhs ^ rhs) & (lhs ^ diff)) >> 63) flags |= 0x800u; // OF
300 c->EFlags = flags;
301}
302
303// Fast-path for the Zen 2 zeroing loop: `clzero; add rax, 0x40; cmp rax, reg64; jb -12` (12 bytes).
304// Zeroes the entire writable span in one memset instead of raising #UD + VirtualQuery per 64-byte line.
305inline ClzeroLoopResult try_clzero_loop(const uint8_t* code, std::size_t avail, CONTEXT* c, EXCEPTION_RECORD* fault) {
306 if (avail < 12) return ClzeroLoopResult::no_match;
307 if (code[0] != 0x0F || code[1] != 0x01 || code[2] != 0xFC) return ClzeroLoopResult::no_match;
308 if (code[3] != 0x48 || code[4] != 0x83 || code[5] != 0xC0 || code[6] != 0x40) return ClzeroLoopResult::no_match;
309 if ((code[7] != 0x48 && code[7] != 0x4C) || code[8] != 0x39 || (code[9] & 0xC7) != 0xC0)
310 return ClzeroLoopResult::no_match;
311 if (code[10] != 0x72 || code[11] != 0xF4) return ClzeroLoopResult::no_match;
312
313 const int limit_reg = ((code[9] >> 3) & 7) | ((code[7] & 4) << 1);
314 if (limit_reg == 0 || limit_reg == 4) return ClzeroLoopResult::no_match;
315
316 const uint64_t start = c->Rax;
317 const uint64_t limit = gpr_read(c, limit_reg);
318 if ((start & 63) != 0 || limit <= start + 64) return ClzeroLoopResult::no_match;
319
320 uint64_t total = (limit - start + 63) & ~uint64_t(63);
321 constexpr uint64_t kMaxBatch = uint64_t(64) << 20;
322 if (total > kMaxBatch) total = kMaxBatch;
323 const uint64_t end = start + total;
324
325 for (uint64_t cur = start; cur < end;) {
326 const DWORD err = writable(cur);
327 if (err) {
328 if (cur > start) {
329 std::memset(reinterpret_cast<void*>(start), 0, std::size_t(cur - start));
330 c->Rax = cur;
331 apply_cmp_flags(c, cur, limit);
332 }
333 if (fault) {
334 std::memset(fault, 0, sizeof *fault);
335 fault->ExceptionCode = err;
336 fault->NumberParameters = 2;
337 fault->ExceptionInformation[0] = 1;
338 fault->ExceptionInformation[1] = ULONG_PTR(cur);
339 }
340 return ClzeroLoopResult::faulted;
341 }
342 const uint64_t next_page = (cur & ~uint64_t(0xFFF)) + 0x1000;
343 cur = next_page < end ? next_page : end;
344 }
345
346 std::memset(reinterpret_cast<void*>(start), 0, std::size_t(total));
347 c->Rax = end;
348 apply_cmp_flags(c, end, limit);
349 if (end >= limit) c->Rip += 12;
350 return ClzeroLoopResult::ok;
351}
352
275inline LONG CALLBACK handler(EXCEPTION_POINTERS* info) { 353inline LONG CALLBACK handler(EXCEPTION_POINTERS* info) {
276 if (info->ExceptionRecord->ExceptionCode != STATUS_ILLEGAL_INSTRUCTION) return EXCEPTION_CONTINUE_SEARCH; 354 if (info->ExceptionRecord->ExceptionCode != STATUS_ILLEGAL_INSTRUCTION) return EXCEPTION_CONTINUE_SEARCH;
277 CONTEXT* c = info->ContextRecord; 355 CONTEXT* c = info->ContextRecord;
@@ -281,6 +359,25 @@ inline LONG CALLBACK handler(EXCEPTION_POINTERS* info) {
281 const Decoded d = decode(code, avail); 359 const Decoded d = decode(code, avail);
282 if (d.op == Op::none) return EXCEPTION_CONTINUE_SEARCH; 360 if (d.op == Op::none) return EXCEPTION_CONTINUE_SEARCH;
283 EXCEPTION_RECORD fault; 361 EXCEPTION_RECORD fault;
362 if (d.op == Op::clzero && !d.addr32 && d.length == 3) {
363 const uint64_t fault_rip = c->Rip;
364 const ClzeroLoopResult lr = try_clzero_loop(code, avail, c, &fault);
365 if (lr == ClzeroLoopResult::ok) {
366 if (count(d.op).fetch_add(1, std::memory_order_relaxed) == 0)
367 std::fprintf(stderr, "[rt] cpu: this CPU has no %s; emulating it (first at %p)\n", name(d.op),
368 reinterpret_cast<void*>(fault_rip));
369 return EXCEPTION_CONTINUE_EXECUTION;
370 }
371 if (lr == ClzeroLoopResult::faulted) {
372 EXCEPTION_RECORD* r = info->ExceptionRecord;
373 r->ExceptionCode = fault.ExceptionCode;
374 r->ExceptionFlags = 0;
375 r->NumberParameters = fault.NumberParameters;
376 r->ExceptionInformation[0] = fault.ExceptionInformation[0];
377 r->ExceptionInformation[1] = fault.ExceptionInformation[1];
378 return EXCEPTION_CONTINUE_SEARCH;
379 }
380 }
284 if (!apply(d, c, &fault)) { 381 if (!apply(d, c, &fault)) {
285 // CLZERO on a line it cannot write: the CPU would raise that fault at this instruction, so the next handlers 382 // CLZERO on a line it cannot write: the CPU would raise that fault at this instruction, so the next handlers
286 // see it instead of the #UD (RIP still points at the instruction). 383 // see it instead of the #UD (RIP still points at the instruction).
diff --git a/runtime/src/frame_pacer.h b/runtime/src/frame_pacer.h
index fa9c20df1..afeaf191e 100644
--- a/runtime/src/frame_pacer.h
+++ b/runtime/src/frame_pacer.h
@@ -30,14 +30,17 @@
30// suspended) is unchanged. 30// suspended) is unchanged.
31 31
32#include <algorithm> 32#include <algorithm>
33#include <array>
33#include <atomic> 34#include <atomic>
34#include <chrono> 35#include <chrono>
35#include <condition_variable> 36#include <condition_variable>
37#include <cstddef>
36#include <cstdint> 38#include <cstdint>
37#include <deque> 39#include <deque>
38#include <functional> 40#include <functional>
39#include <limits> 41#include <limits>
40#include <mutex> 42#include <mutex>
43#include <vector>
41 44
42namespace leonida { 45namespace leonida {
43 46
@@ -102,8 +105,14 @@ private:
102 std::function<void()> wake_; 105 std::function<void()> wake_;
103}; 106};
104 107
105// Provisional definitions of ours: the real constants and layouts of the console API are unmeasured. 108// Provisional definitions of ours: the real constants and layouts of the console API are unmeasured. Frame event
109// kinds (0: origin, 1: vblank, 2: flip) and wait flags.
106inline constexpr std::uint32_t frame_event_origin = 0; 110inline constexpr std::uint32_t frame_event_origin = 0;
111inline constexpr std::uint32_t frame_event_vblank = 1;
112inline constexpr std::uint32_t frame_event_flip = 2;
113inline constexpr std::uint32_t frame_event_count = 3;
114// Issue a consecutive frame token even when WaitFrameEventX(origin, ...) times out (returns S_FALSE).
115inline constexpr std::uint32_t frame_wait_flag_token_on_timeout = 2;
107// Statistics types (bit mask). Interval and render entries are never produced here. 116// Statistics types (bit mask). Interval and render entries are never produced here.
108inline constexpr std::uint32_t stat_frame_interval = 0x01; 117inline constexpr std::uint32_t stat_frame_interval = 0x01;
109inline constexpr std::uint32_t stat_frame_event = 0x02; 118inline constexpr std::uint32_t stat_frame_event = 0x02;
@@ -143,6 +152,25 @@ struct FrameStatistic {
143 float percent_scanned = 0.0f; // display entries: where the scan was when the frame came up (0 at a vblank) 152 float percent_scanned = 0.0f; // display entries: where the scan was when the frame came up (0 at a vblank)
144}; 153};
145 154
155// Fixed-capacity ring buffer size for recent frame-time and origin-to-present latency samples (BL-6).
156inline constexpr std::size_t frame_pacing_window = 1024;
157
158// Summary over the most recent `frame_pacing_window` presented frames (p50/p95/p99 and mean drift against target).
159struct FramePacingSummary {
160 std::uint64_t frames = 0; // total presented frames recorded
161 std::uint64_t samples = 0; // present-to-present intervals in the ring buffer (<= frame_pacing_window)
162 std::uint32_t target_interval_us = 0; // active target interval in us (0 when unpaced or uncapped)
163 double mean_us = 0.0; // mean present-to-present interval over `samples`
164 double drift_us = 0.0; // mean_us - target_interval_us (0 when unpaced/uncapped or samples == 0)
165 std::uint64_t p50_us = 0; // nearest-rank 50th percentile frame interval in us
166 std::uint64_t p95_us = 0; // nearest-rank 95th percentile frame interval in us
167 std::uint64_t p99_us = 0; // nearest-rank 99th percentile frame interval in us
168 std::uint64_t latency_samples = 0; // origin-to-present latency samples in the ring buffer
169 std::uint64_t latency_p50_us = 0; // nearest-rank 50th percentile origin-to-present latency in us
170 std::uint64_t latency_p95_us = 0; // nearest-rank 95th percentile origin-to-present latency in us
171 std::uint64_t latency_p99_us = 0; // nearest-rank 99th percentile origin-to-present latency in us
172};
173
146class FramePacer { 174class FramePacer {
147public: 175public:
148 explicit FramePacer(FrameClock& clock) : clock_(clock) { 176 explicit FramePacer(FrameClock& clock) : clock_(clock) {
@@ -177,38 +205,42 @@ public:
177 latency_ = std::max(latency, 1u); 205 latency_ = std::max(latency, 1u);
178 epoch_us_ = clock_.now_us(); 206 epoch_us_ = clock_.now_us();
179 interval_set_ = true; 207 interval_set_ = true;
180 offset_us_ = std::min(offset_us_, period_us - 1); 208 for (std::uint32_t k = 0; k < frame_event_count; ++k) {
181 last_origin_ = 0; // origin 0 is the epoch itself, which has passed 209 event_offset_us_[k] = std::min(event_offset_us_[k], period_us - 1);
210 last_event_tick_[k] = 0; // tick 0 is the epoch itself, which has passed
211 }
182 cv_.notify_all(); 212 cv_.notify_all();
183 return pacer_hr::ok; 213 return pacer_hr::ok;
184 } 214 }
185 215
186 // ScheduleFrameEventX(event, offset, ..., flags). Only the origin event exists here. 216 // ScheduleFrameEventX(event, offset, ..., flags). Supports origin (0), vblank (1), and flip (2).
187 std::int32_t schedule_frame_event(std::uint32_t event, std::uint32_t offset_us, std::uint32_t flags) { 217 std::int32_t schedule_frame_event(std::uint32_t event, std::uint32_t offset_us, std::uint32_t flags) {
188 (void)flags; 218 (void)flags;
189 if (event != frame_event_origin) return pacer_hr::invalid_arg; 219 if (event >= frame_event_count) return pacer_hr::invalid_arg;
190 std::lock_guard guard(mutex_); 220 std::lock_guard guard(mutex_);
191 if (suspended_ || !interval_set_) return pacer_hr::invalid_state; 221 if (suspended_ || !interval_set_) return pacer_hr::invalid_state;
192 if (offset_us >= period_us_) return pacer_hr::invalid_arg; 222 if (offset_us >= period_us_) return pacer_hr::invalid_arg;
193 offset_us_ = offset_us; 223 event_offset_us_[event] = offset_us;
194 armed_ = true; 224 event_armed_[event] = true;
195 // The first origin is the next one that has not come yet: origin n is due at epoch + n * period + offset. 225 // The first event is the next one that has not come yet: tick n is due at epoch + n * period + offset.
196 const std::uint64_t now = clock_.now_us(); 226 const std::uint64_t now = clock_.now_us();
197 last_origin_ = now >= epoch_us_ + offset_us_ ? std::int64_t((now - epoch_us_ - offset_us_) / period_us_) : 0; 227 last_event_tick_[event] =
228 now >= epoch_us_ + offset_us ? std::int64_t((now - epoch_us_ - offset_us) / period_us_) : 0;
198 cv_.notify_all(); 229 cv_.notify_all();
199 return pacer_hr::ok; 230 return pacer_hr::ok;
200 } 231 }
201 232
202 // WaitFrameEventX(event, timeout, ..., flags, &token). Blocks until the next origin, and while `latency` frames 233 // WaitFrameEventX(event, timeout, ..., flags, &token). Origin waits block until the next origin tick and while
203 // are in flight. pacer_hr::timeout when `timeout_ms` passes first (infinite_timeout_ms: never); the token is left 234 // `latency` frames are in flight, issuing a consecutive token on success (or on timeout with
204 // alone then. invalid_state when nothing is registered, the pacer is suspended, or one of those happens while waiting. 235 // frame_wait_flag_token_on_timeout, returning S_FALSE). Vblank/flip waits pace independently per event kind and
236 // leave `*token` untouched.
205 std::int32_t wait_frame_event(std::uint32_t event, std::uint32_t timeout_ms, std::uint32_t flags, 237 std::int32_t wait_frame_event(std::uint32_t event, std::uint32_t timeout_ms, std::uint32_t flags,
206 std::uint64_t* token) { 238 std::uint64_t* token) {
207 (void)flags; 239 if (event >= frame_event_count) return pacer_hr::invalid_arg;
208 if (event != frame_event_origin || !token) return pacer_hr::invalid_arg; 240 if (event == frame_event_origin && !token) return pacer_hr::invalid_arg;
209 std::unique_lock lock(mutex_); 241 std::unique_lock lock(mutex_);
210 ++waiters_; 242 ++waiters_;
211 const std::int32_t result = wait_locked(lock, timeout_ms, token); 243 const std::int32_t result = wait_locked(lock, event, timeout_ms, flags, token);
212 if (--waiters_ == 0) cv_.notify_all(); 244 if (--waiters_ == 0) cv_.notify_all();
213 return result; 245 return result;
214 } 246 }
@@ -301,8 +333,9 @@ public:
301 std::lock_guard guard(mutex_); 333 std::lock_guard guard(mutex_);
302 const std::uint64_t now = clock_.now_us(); 334 const std::uint64_t now = clock_.now_us();
303 retire_locked(now); 335 retire_locked(now);
336 record_present_timing_locked(now, token);
304 last_presented_ = std::max(last_presented_, token); 337 last_presented_ = std::max(last_presented_, token);
305 if (!interval_set_ || !armed_ || uncapped_) { // not paced or uncapped: shows at once 338 if (!interval_set_ || !any_armed_locked() || uncapped_) { // not paced or uncapped: shows at once
306 for (Record& r : records_) 339 for (Record& r : records_)
307 if (r.token == token) { r.presented = r.displayed = true; r.present_us = r.display_us = now; } 340 if (r.token == token) { r.presented = r.displayed = true; r.present_us = r.display_us = now; }
308 return; 341 return;
@@ -330,8 +363,9 @@ public:
330 // the origin event not armed or the cap off it is not paced: it shows at once and is not counted. 363 // the origin event not armed or the cap off it is not paced: it shows at once and is not counted.
331 void note_untokened_present() { 364 void note_untokened_present() {
332 std::lock_guard guard(mutex_); 365 std::lock_guard guard(mutex_);
333 if (!interval_set_ || !armed_ || uncapped_) return;
334 const std::uint64_t now = clock_.now_us(); 366 const std::uint64_t now = clock_.now_us();
367 record_present_timing_locked(now, 0);
368 if (!interval_set_ || !any_armed_locked() || uncapped_) return;
335 retire_locked(now); 369 retire_locked(now);
336 const std::uint64_t since = now > epoch_us_ ? now - epoch_us_ : 0; 370 const std::uint64_t since = now > epoch_us_ ? now - epoch_us_ : 0;
337 std::uint64_t flip = epoch_us_ + (since / period_us_ + 1) * period_us_; 371 std::uint64_t flip = epoch_us_ + (since / period_us_ + 1) * period_us_;
@@ -344,7 +378,9 @@ public:
344 void suspend() { 378 void suspend() {
345 std::lock_guard guard(mutex_); 379 std::lock_guard guard(mutex_);
346 suspended_ = true; 380 suspended_ = true;
347 interval_set_ = armed_ = false; 381 interval_set_ = false;
382 has_last_present_ = false; // do not count the suspended pause as a frame interval after resume
383 for (bool& a : event_armed_) a = false;
348 pending_.clear(); 384 pending_.clear();
349 cv_.notify_all(); 385 cv_.notify_all();
350 } 386 }
@@ -352,7 +388,8 @@ public:
352 void resume() { 388 void resume() {
353 std::lock_guard guard(mutex_); 389 std::lock_guard guard(mutex_);
354 suspended_ = false; 390 suspended_ = false;
355 interval_set_ = armed_ = false; 391 interval_set_ = false;
392 for (bool& a : event_armed_) a = false;
356 cv_.notify_all(); 393 cv_.notify_all();
357 } 394 }
358 395
@@ -366,13 +403,54 @@ public:
366 // Frames that were flipped mid-scan because of ImmediateThresholdPercent. 403 // Frames that were flipped mid-scan because of ImmediateThresholdPercent.
367 std::uint64_t immediate_presents() const { std::lock_guard guard(mutex_); return immediate_presents_; } 404 std::uint64_t immediate_presents() const { std::lock_guard guard(mutex_); return immediate_presents_; }
368 std::uint32_t period_us() const { std::lock_guard guard(mutex_); return period_us_; } 405 std::uint32_t period_us() const { std::lock_guard guard(mutex_); return period_us_; }
369 bool registered() const { std::lock_guard guard(mutex_); return interval_set_ && armed_; } 406 bool registered() const { std::lock_guard guard(mutex_); return interval_set_ && any_armed_locked(); }
370 407
371 // The fps cap off (LEONIDA_PRESENT_UNCAP; see the top comment): waits never block and presents count as shown 408 // The fps cap off (LEONIDA_PRESENT_UNCAP; see the top comment): waits never block and presents count as shown
372 // at once. Registration and suspension keep meaning what they did; the flag survives suspend/resume. 409 // at once. Registration and suspension keep meaning what they did; the flag survives suspend/resume.
373 void set_uncapped(bool on) { std::lock_guard guard(mutex_); uncapped_ = on; } 410 void set_uncapped(bool on) { std::lock_guard guard(mutex_); uncapped_ = on; }
374 bool uncapped() const { std::lock_guard guard(mutex_); return uncapped_; } 411 bool uncapped() const { std::lock_guard guard(mutex_); return uncapped_; }
375 412
413 // Frame-time percentiles, mean drift against the active target interval, and origin-to-present latency over
414 // the last `frame_pacing_window` presented frames (BL-6).
415 FramePacingSummary pacing_summary() const {
416 FramePacingSummary out;
417 std::vector<std::uint64_t> intervals;
418 std::vector<std::uint64_t> latencies;
419 {
420 std::lock_guard guard(mutex_);
421 out.frames = presents_recorded_;
422 out.target_interval_us = (interval_set_ && !uncapped_) ? period_us_ : 0u;
423 intervals.reserve(interval_count_);
424 for (std::size_t i = 0; i < interval_count_; ++i) intervals.push_back(interval_ring_[i]);
425 latencies.reserve(latency_count_);
426 for (std::size_t i = 0; i < latency_count_; ++i) latencies.push_back(latency_ring_[i]);
427 }
428 auto percentile = [](const std::vector<std::uint64_t>& sorted, std::size_t pct) -> std::uint64_t {
429 if (sorted.empty()) return 0;
430 const std::size_t idx = (pct * sorted.size() + 99) / 100 - 1;
431 return sorted[std::min(idx, sorted.size() - 1)];
432 };
433 if (!intervals.empty()) {
434 out.samples = intervals.size();
435 double sum = 0.0;
436 for (std::uint64_t v : intervals) sum += double(v);
437 out.mean_us = sum / double(intervals.size());
438 if (out.target_interval_us != 0) out.drift_us = out.mean_us - double(out.target_interval_us);
439 std::sort(intervals.begin(), intervals.end());
440 out.p50_us = percentile(intervals, 50);
441 out.p95_us = percentile(intervals, 95);
442 out.p99_us = percentile(intervals, 99);
443 }
444 if (!latencies.empty()) {
445 out.latency_samples = latencies.size();
446 std::sort(latencies.begin(), latencies.end());
447 out.latency_p50_us = percentile(latencies, 50);
448 out.latency_p95_us = percentile(latencies, 95);
449 out.latency_p99_us = percentile(latencies, 99);
450 }
451 return out;
452 }
453
376private: 454private:
377 struct Pending { 455 struct Pending {
378 std::uint64_t token; 456 std::uint64_t token;
@@ -386,6 +464,29 @@ private:
386 bool presented = false, displayed = false; 464 bool presented = false, displayed = false;
387 }; 465 };
388 466
467 void record_present_timing_locked(std::uint64_t now, std::uint64_t token) {
468 ++presents_recorded_;
469 if (has_last_present_ && now >= last_present_us_) {
470 interval_ring_[interval_head_] = now - last_present_us_;
471 interval_head_ = (interval_head_ + 1) % frame_pacing_window;
472 if (interval_count_ < frame_pacing_window) ++interval_count_;
473 }
474 has_last_present_ = true;
475 last_present_us_ = now;
476 if (token != 0) {
477 for (const Record& r : records_) {
478 if (r.token == token) {
479 if (now >= r.origin_us) {
480 latency_ring_[latency_head_] = now - r.origin_us;
481 latency_head_ = (latency_head_ + 1) % frame_pacing_window;
482 if (latency_count_ < frame_pacing_window) ++latency_count_;
483 }
484 break;
485 }
486 }
487 }
488 }
489
389 // Frames whose vblank has come are shown. 490 // Frames whose vblank has come are shown.
390 void retire_locked(std::uint64_t now) { 491 void retire_locked(std::uint64_t now) {
391 while (!pending_.empty() && pending_.front().flip_us <= now) { 492 while (!pending_.empty() && pending_.front().flip_us <= now) {
@@ -399,45 +500,67 @@ private:
399 } 500 }
400 } 501 }
401 502
402 std::int32_t wait_locked(std::unique_lock<std::mutex>& lock, std::uint32_t timeout_ms, std::uint64_t* token) { 503 bool any_armed_locked() const {
504 return event_armed_[0] || event_armed_[1] || event_armed_[2];
505 }
506
507 std::uint64_t issue_token_locked(std::uint64_t origin_us, std::uint64_t due_us) {
508 const std::uint64_t tok = ++issued_;
509 Record record;
510 record.token = tok;
511 record.origin_us = origin_us;
512 record.due_us = due_us;
513 records_.push_back(record);
514 if (records_.size() > 64) records_.pop_front();
515 return tok;
516 }
517
518 std::int32_t wait_locked(std::unique_lock<std::mutex>& lock, std::uint32_t event, std::uint32_t timeout_ms,
519 std::uint32_t flags, std::uint64_t* token) {
520 const bool is_origin = (event == frame_event_origin);
521 const bool token_on_timeout = (flags & frame_wait_flag_token_on_timeout) != 0;
403 const std::uint64_t start = clock_.now_us(); 522 const std::uint64_t start = clock_.now_us();
404 const std::uint64_t give_up = timeout_ms == infinite_timeout_ms ? no_deadline 523 const std::uint64_t give_up = timeout_ms == infinite_timeout_ms ? no_deadline
405 : start + std::uint64_t(timeout_ms) * 1000; 524 : start + std::uint64_t(timeout_ms) * 1000;
406 for (;;) { 525 for (;;) {
407 if (shutdown_ || suspended_ || !interval_set_ || !armed_) return pacer_hr::invalid_state; 526 if (shutdown_ || suspended_ || !interval_set_) return pacer_hr::invalid_state;
527 if (is_origin ? !event_armed_[frame_event_origin]
528 : (!event_armed_[event] && !event_armed_[frame_event_origin])) {
529 return pacer_hr::invalid_state;
530 }
408 const std::uint64_t now = clock_.now_us(); 531 const std::uint64_t now = clock_.now_us();
409 retire_locked(now); 532 retire_locked(now);
410 if (uncapped_) { // no vblank grid and no latency throttle: a token at once, due now 533 if (uncapped_) { // no vblank grid and no latency throttle
411 *token = ++issued_; 534 if (is_origin) *token = issue_token_locked(now, now);
412 Record record;
413 record.token = *token;
414 record.origin_us = now;
415 record.due_us = now;
416 records_.push_back(record);
417 if (records_.size() > 64) records_.pop_front();
418 return pacer_hr::ok; 535 return pacer_hr::ok;
419 } 536 }
420 const std::uint64_t first = epoch_us_ + offset_us_; // origin 0 537 const std::uint32_t offset = event_offset_us_[event];
421 const std::int64_t next = last_origin_ + 1; 538 const std::uint64_t first = epoch_us_ + offset; // tick 0
539 const std::int64_t next = last_event_tick_[event] + 1;
422 const std::uint64_t next_us = first + std::uint64_t(next) * period_us_; 540 const std::uint64_t next_us = first + std::uint64_t(next) * period_us_;
423 std::uint64_t wake = next_us; 541 std::uint64_t wake = next_us;
424 if (now >= next_us) { 542 if (now >= next_us) {
425 if (pending_.size() < latency_) { 543 if (!is_origin || pending_.size() < latency_) {
426 const std::int64_t newest = std::int64_t((now - first) / period_us_); 544 const std::int64_t newest = std::int64_t((now - first) / period_us_);
427 const std::int64_t origin = std::max(next, newest); 545 const std::int64_t tick = std::max(next, newest);
428 last_origin_ = origin; 546 last_event_tick_[event] = tick;
429 *token = ++issued_; 547 if (is_origin) {
430 Record record; 548 const std::uint64_t origin_us = first + std::uint64_t(tick) * period_us_;
431 record.token = *token; 549 const std::uint64_t due_us = origin_us - offset + period_us_;
432 record.origin_us = first + std::uint64_t(origin) * period_us_; 550 *token = issue_token_locked(origin_us, due_us);
433 record.due_us = record.origin_us - offset_us_ + period_us_; 551 }
434 records_.push_back(record);
435 if (records_.size() > 64) records_.pop_front();
436 return pacer_hr::ok; 552 return pacer_hr::ok;
437 } 553 }
438 wake = pending_.front().flip_us; // blocked by the latency: until the oldest frame is shown 554 wake = pending_.front().flip_us; // blocked by the latency: until the oldest frame is shown
439 } 555 }
440 if (give_up != no_deadline && now >= give_up) return pacer_hr::timeout; 556 if (give_up != no_deadline && now >= give_up) {
557 if (is_origin && token_on_timeout) {
558 // Frame started early on timeout: issue a consecutive token without consuming the tick.
559 *token = issue_token_locked(now, next_us - offset + period_us_);
560 return pacer_hr::false_;
561 }
562 return token_on_timeout ? pacer_hr::false_ : pacer_hr::timeout;
563 }
441 clock_.wait(lock, cv_, give_up == no_deadline ? wake : std::min(wake, give_up)); 564 clock_.wait(lock, cv_, give_up == no_deadline ? wake : std::min(wake, give_up));
442 } 565 }
443 } 566 }
@@ -450,16 +573,25 @@ private:
450 573
451 bool suspended_ = false; 574 bool suspended_ = false;
452 bool interval_set_ = false; 575 bool interval_set_ = false;
453 bool armed_ = false; 576 bool event_armed_[frame_event_count] = {false, false, false};
454 bool uncapped_ = false; 577 bool uncapped_ = false;
455 std::uint32_t period_us_ = 0; 578 std::uint32_t period_us_ = 0;
456 std::uint32_t latency_ = 1; 579 std::uint32_t latency_ = 1;
457 std::uint32_t offset_us_ = 0; 580 std::uint32_t event_offset_us_[frame_event_count] = {0, 0, 0};
458 std::uint64_t epoch_us_ = 0; 581 std::uint64_t epoch_us_ = 0;
459 std::int64_t last_origin_ = 0; // origin 0 is the epoch itself, which has passed 582 std::int64_t last_event_tick_[frame_event_count] = {0, 0, 0}; // tick 0 is the epoch itself, which has passed
460 std::uint64_t issued_ = 0; 583 std::uint64_t issued_ = 0;
461 std::uint64_t last_presented_ = 0; 584 std::uint64_t last_presented_ = 0;
462 std::uint64_t immediate_presents_ = 0; 585 std::uint64_t immediate_presents_ = 0;
586 std::uint64_t presents_recorded_ = 0;
587 bool has_last_present_ = false;
588 std::uint64_t last_present_us_ = 0;
589 std::array<std::uint64_t, frame_pacing_window> interval_ring_{};
590 std::size_t interval_head_ = 0;
591 std::size_t interval_count_ = 0;
592 std::array<std::uint64_t, frame_pacing_window> latency_ring_{};
593 std::size_t latency_head_ = 0;
594 std::size_t latency_count_ = 0;
463 std::deque<Pending> pending_; 595 std::deque<Pending> pending_;
464 std::deque<Record> records_; 596 std::deque<Record> records_;
465}; 597};
diff --git a/runtime/src/gfx10_descriptors.h b/runtime/src/gfx10_descriptors.h
index b225cddef..a4a9b4448 100644
--- a/runtime/src/gfx10_descriptors.h
+++ b/runtime/src/gfx10_descriptors.h
@@ -631,8 +631,9 @@ inline VkSamplerCreateInfo vulkan_sampler(const Sampler& sampler, float max_lod_
631 if (sampler.unnormalized) { 631 if (sampler.unnormalized) {
632 info.unnormalizedCoordinates = VK_TRUE; 632 info.unnormalizedCoordinates = VK_TRUE;
633 // VUID-VkSamplerCreateInfo-unnormalizedCoordinates-01075: U and V clamp to the edge or the border (a 633 // VUID-VkSamplerCreateInfo-unnormalizedCoordinates-01075: U and V clamp to the edge or the border (a
634 // repeating mode would wrap at a texel count the sampler cannot know); -01072: one filter for min and mag. 634 // repeating mode would wrap at a texel count the sampler cannot know); -01072: one filter for min and mag;
635 // The S# allows any address mode with FORCE_UNNORMALIZED, and WRAP is its default (word 0 = 0). 635 // -01074: mipLodBias must be zero. The S# allows any address mode or LOD bias with FORCE_UNNORMALIZED, and
636 // WRAP is its default (word 0 = 0).
636 const auto clamp_or_border = [](VkSamplerAddressMode m) { 637 const auto clamp_or_border = [](VkSamplerAddressMode m) {
637 return m == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ? m : VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; 638 return m == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ? m : VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
638 }; 639 };
@@ -640,6 +641,7 @@ inline VkSamplerCreateInfo vulkan_sampler(const Sampler& sampler, float max_lod_
640 info.addressModeV = clamp_or_border(info.addressModeV); 641 info.addressModeV = clamp_or_border(info.addressModeV);
641 info.minFilter = info.magFilter; 642 info.minFilter = info.magFilter;
642 info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; 643 info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST;
644 info.mipLodBias = 0.0f;
643 info.minLod = info.maxLod = 0.0f; 645 info.minLod = info.maxLod = 0.0f;
644 info.anisotropyEnable = VK_FALSE; 646 info.anisotropyEnable = VK_FALSE;
645 info.maxAnisotropy = 1.0f; 647 info.maxAnisotropy = 1.0f;
diff --git a/runtime/src/mods.h b/runtime/src/mods.h
index 10155bf19..bd635e9a0 100644
--- a/runtime/src/mods.h
+++ b/runtime/src/mods.h
@@ -78,8 +78,8 @@ struct LoadResult {
78// "0x..." -> that value; anything else -> joaat(name). Returns false for an empty name or a malformed hex value. 78// "0x..." -> that value; anything else -> joaat(name). Returns false for an empty name or a malformed hex value.
79inline bool parse_model_id(const std::string& text, uint32_t& out) { 79inline bool parse_model_id(const std::string& text, uint32_t& out) {
80 if (text.empty()) return false; 80 if (text.empty()) return false;
81 if (text.size() > 2 && text[0] == '0' && (text[1] == 'x' || text[1] == 'X')) { 81 if (text.size() >= 2 && text[0] == '0' && (text[1] == 'x' || text[1] == 'X')) {
82 if (text.size() > 10) return false; 82 if (text.size() == 2 || text.size() > 10) return false;
83 uint32_t v = 0; 83 uint32_t v = 0;
84 for (std::size_t i = 2; i < text.size(); ++i) { 84 for (std::size_t i = 2; i < text.size(); ++i) {
85 const char c = text[i]; 85 const char c = text[i];
diff --git a/runtime/src/retire_tickets.h b/runtime/src/retire_tickets.h
index a48302859..675460cac 100644
--- a/runtime/src/retire_tickets.h
+++ b/runtime/src/retire_tickets.h
@@ -24,7 +24,7 @@ public:
24 while (!pending_.empty()) { 24 while (!pending_.empty()) {
25 const Entry& front = pending_.front(); 25 const Entry& front = pending_.front();
26 if (!front.idle && !query(front.semaphore, front.value)) break; 26 if (!front.idle && !query(front.semaphore, front.value)) break;
27 completed_ = front.ticket; 27 if (front.ticket > completed_) completed_ = front.ticket;
28 pending_.pop_front(); 28 pending_.pop_front();
29 } 29 }
30 return completed_; 30 return completed_;
@@ -34,8 +34,18 @@ public:
34 // that must have them done (and may not hold the lock that guards this object while it waits) waits for. 34 // that must have them done (and may not hold the lock that guards this object while it waits) waits for.
35 std::vector<std::pair<Semaphore, std::uint64_t>> pending_through(std::uint64_t ticket) const { 35 std::vector<std::pair<Semaphore, std::uint64_t>> pending_through(std::uint64_t ticket) const {
36 std::vector<std::pair<Semaphore, std::uint64_t>> out; 36 std::vector<std::pair<Semaphore, std::uint64_t>> out;
37 for (const Entry& entry : pending_) 37 for (const Entry& entry : pending_) {
38 if (entry.ticket <= ticket && !entry.idle) out.emplace_back(entry.semaphore, entry.value); 38 if (entry.ticket > ticket || entry.idle) continue;
39 bool merged = false;
40 for (auto& [sem, val] : out) {
41 if (sem == entry.semaphore) {
42 if (entry.value > val) val = entry.value;
43 merged = true;
44 break;
45 }
46 }
47 if (!merged) out.emplace_back(entry.semaphore, entry.value);
48 }
39 return out; 49 return out;
40 } 50 }
41 51
diff --git a/runtime/src/shader_library.h b/runtime/src/shader_library.h
index 9f752317e..596ad0ae9 100644
--- a/runtime/src/shader_library.h
+++ b/runtime/src/shader_library.h
@@ -246,7 +246,7 @@ inline ZlibError inflate_codes(BitReader& in, std::vector<std::uint8_t>& out, co
246 if (d < 0 || d >= 30) return ZlibError::data; 246 if (d < 0 || d >= 30) return ZlibError::data;
247 const std::size_t distance = std::size_t(distance_base[d]) + in.bits(distance_extra[d]); 247 const std::size_t distance = std::size_t(distance_base[d]) + in.bits(distance_extra[d]);
248 if (in.failed() || distance > out.size()) return ZlibError::data; 248 if (in.failed() || distance > out.size()) return ZlibError::data;
249 if (out.size() + length > limit) return ZlibError::limit; 249 if (out.size() > limit || length > limit - out.size()) return ZlibError::limit;
250 const std::size_t from = out.size() - distance; 250 const std::size_t from = out.size() - distance;
251 for (std::size_t i = 0; i < length; ++i) out.push_back(out[from + i]); 251 for (std::size_t i = 0; i < length; ++i) out.push_back(out[from + i]);
252 } 252 }
@@ -284,7 +284,7 @@ inline bool zlib_inflate(std::span<const std::uint8_t> in, std::vector<std::uint
284 if (!reader.byte(x)) return fail(ZlibError::data); 284 if (!reader.byte(x)) return fail(ZlibError::data);
285 const unsigned length = b[0] | (b[1] << 8), complement = b[2] | (b[3] << 8); 285 const unsigned length = b[0] | (b[1] << 8), complement = b[2] | (b[3] << 8);
286 if (length != (~complement & 0xffff)) return fail(ZlibError::data); 286 if (length != (~complement & 0xffff)) return fail(ZlibError::data);
287 if (out.size() + length > limit) return fail(ZlibError::limit); 287 if (out.size() > limit || length > limit - out.size()) return fail(ZlibError::limit);
288 for (unsigned i = 0; i < length; ++i) { 288 for (unsigned i = 0; i < length; ++i) {
289 std::uint8_t x; 289 std::uint8_t x;
290 if (!reader.byte(x)) return fail(ZlibError::data); 290 if (!reader.byte(x)) return fail(ZlibError::data);
@@ -349,7 +349,7 @@ inline bool zlib_inflate(std::span<const std::uint8_t> in, std::vector<std::uint
349 } 349 }
350 // Adler-32, big-endian, after the deflate data's last whole byte. 350 // Adler-32, big-endian, after the deflate data's last whole byte.
351 const std::size_t at = 2 + reader.position(); 351 const std::size_t at = 2 + reader.position();
352 if (at + 4 > in.size()) return fail(ZlibError::data); 352 if (at > in.size() || in.size() - at < 4) return fail(ZlibError::data);
353 std::uint32_t a = 1, b = 0; 353 std::uint32_t a = 1, b = 0;
354 for (const std::uint8_t x : out) { 354 for (const std::uint8_t x : out) {
355 a = (a + x) % 65521; 355 a = (a + x) % 65521;
@@ -1045,9 +1045,20 @@ private:
1045 if (const Json* fh = meta.find("f16_halves"); fh && fh->kind == Json::Kind::object) { 1045 if (const Json* fh = meta.find("f16_halves"); fh && fh->kind == Json::Kind::object) {
1046 for (const auto& [key, val] : fh->object) { 1046 for (const auto& [key, val] : fh->object) {
1047 if (key.empty() || val.kind != Json::Kind::array || val.array.size() != 2) continue; 1047 if (key.empty() || val.kind != Json::Kind::array || val.array.size() != 2) continue;
1048 char* end = nullptr; 1048 std::uint64_t param = 0;
1049 const unsigned long param = std::strtoul(key.c_str(), &end, 10); 1049 bool ok = true;
1050 if (!end || *end != '\0') continue; 1050 for (const char c : key) {
1051 if (c < '0' || c > '9') {
1052 ok = false;
1053 break;
1054 }
1055 param = param * 10u + std::uint64_t(c - '0');
1056 if (param > UINT32_MAX) {
1057 ok = false;
1058 break;
1059 }
1060 }
1061 if (!ok) continue;
1051 e.f16_halves[std::uint32_t(param)] = {u32(&val.array[0]), u32(&val.array[1])}; 1062 e.f16_halves[std::uint32_t(param)] = {u32(&val.array[0]), u32(&val.array[1])};
1052 } 1063 }
1053 } 1064 }
diff --git a/runtime/src/statistics_sum.comp b/runtime/src/statistics_sum.comp
index c4960347c..c4a02a459 100644
--- a/runtime/src/statistics_sum.comp
+++ b/runtime/src/statistics_sum.comp
@@ -2,9 +2,11 @@
2 2
3// Adds the D3D12_QUERY_DATA_PIPELINE_STATISTICS segments of one split pipeline-statistics query (D3D-162): one 3// Adds the D3D12_QUERY_DATA_PIPELINE_STATISTICS segments of one split pipeline-statistics query (D3D-162): one
4// invocation per counter, in the order of VkQueryPipelineStatisticFlagBits, which is the D3D12 field order. 4// invocation per counter, in the order of VkQueryPipelineStatisticFlagBits, which is the D3D12 field order.
5// `mesh` segments come from the pool a mesh draw can run in (D3D-291), which counts only clipping, fragment and 5// `mesh` segments come from the pool a mesh draw can run in (D3D-291), which counts only the fragment and compute
6// compute: they are copied to counters 5..8 of their record, so CSInvocations sits at 8 and the input-assembly, 6// invocations: they are copied to counters 7 and 8 of their record, so PSInvocations takes the fragment one and
7// vertex, geometry and tessellation counters (0..4, 8 and 9 of the D3D12 order) add nothing. 7// CSInvocations the compute one, and every other counter adds nothing.
8// The clipping invocations of a mesh segment come from the mesh-primitives count of that segment, copied to
9// counter 5 (D3D-MESH-CLIPPING-COUNTER); without that count the field stays 0.
8layout(local_size_x = 11) in; 10layout(local_size_x = 11) in;
9layout(set = 0, binding = 0, std430) buffer QueryResults { 11layout(set = 0, binding = 0, std430) buffer QueryResults {
10 uvec2 total[11]; 12 uvec2 total[11];
@@ -15,7 +17,7 @@ layout(push_constant) uniform ResolveRange { uint count; uint mesh; };
15void main() { 17void main() {
16 const uint counter = gl_LocalInvocationID.x; 18 const uint counter = gl_LocalInvocationID.x;
17 uvec2 sum = total[counter]; 19 uvec2 sum = total[counter];
18 const bool counted = mesh == 0u || (counter >= 5u && counter <= 7u) || counter == 10u; 20 const bool counted = mesh == 0u || counter == 5u || counter == 7u || counter == 10u;
19 const uint source = mesh != 0u && counter == 10u ? 8u : counter; 21 const uint source = mesh != 0u && counter == 10u ? 8u : counter;
20 for (uint i = 0; counted && i < count; ++i) { 22 for (uint i = 0; counted && i < count; ++i) {
21 uvec2 segment = segments[i * 11 + source]; 23 uvec2 segment = segments[i * 11 + source];
diff --git a/runtime/src/statistics_sum_spirv.h b/runtime/src/statistics_sum_spirv.h
index 9c67f0429..a147cd4df 100644
--- a/runtime/src/statistics_sum_spirv.h
+++ b/runtime/src/statistics_sum_spirv.h
@@ -7,7 +7,7 @@ namespace leonida {
7// From statistics_sum.comp. Compile with glslangValidator -V --target-env vulkan1.0 -Os -g0, 7// From statistics_sum.comp. Compile with glslangValidator -V --target-env vulkan1.0 -Os -g0,
8// then encode the little-endian SPIR-V as uint32_t words. No shader compiler is needed at runtime build time. 8// then encode the little-endian SPIR-V as uint32_t words. No shader compiler is needed at runtime build time.
9inline constexpr std::uint32_t statistics_sum_spirv[] = { 9inline constexpr std::uint32_t statistics_sum_spirv[] = {
10 0x07230203, 0x00010000, 0x0008000b, 0x00000080, 0x00000000, 0x00020011, 0x00000001, 0x0006000b, 10 0x07230203, 0x00010000, 0x0008000b, 0x00000084, 0x00000000, 0x00020011, 0x00000001, 0x0006000b,
11 0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, 0x00000000, 0x00000001, 11 0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, 0x00000000, 0x00000001,
12 0x0006000f, 0x00000005, 0x00000004, 0x6e69616d, 0x00000000, 0x0000000b, 0x00060010, 0x00000004, 12 0x0006000f, 0x00000005, 0x00000004, 0x6e69616d, 0x00000000, 0x0000000b, 0x00060010, 0x00000004,
13 0x00000011, 0x0000000b, 0x00000001, 0x00000001, 0x00040047, 0x0000000b, 0x0000000b, 0x0000001b, 13 0x00000011, 0x0000000b, 0x00000001, 0x00000001, 0x00040047, 0x0000000b, 0x0000000b, 0x0000001b,
@@ -16,7 +16,7 @@ inline constexpr std::uint32_t statistics_sum_spirv[] = {
16 0x00050048, 0x00000016, 0x00000001, 0x00000023, 0x00000058, 0x00040047, 0x00000018, 0x00000021, 16 0x00050048, 0x00000016, 0x00000001, 0x00000023, 0x00000058, 0x00040047, 0x00000018, 0x00000021,
17 0x00000000, 0x00040047, 0x00000018, 0x00000022, 0x00000000, 0x00030047, 0x00000022, 0x00000002, 17 0x00000000, 0x00040047, 0x00000018, 0x00000022, 0x00000000, 0x00030047, 0x00000022, 0x00000002,
18 0x00050048, 0x00000022, 0x00000000, 0x00000023, 0x00000000, 0x00050048, 0x00000022, 0x00000001, 18 0x00050048, 0x00000022, 0x00000000, 0x00000023, 0x00000000, 0x00050048, 0x00000022, 0x00000001,
19 0x00000023, 0x00000004, 0x00040047, 0x00000072, 0x0000000b, 0x00000019, 0x00020013, 0x00000002, 19 0x00000023, 0x00000004, 0x00040047, 0x0000006f, 0x0000000b, 0x00000019, 0x00020013, 0x00000002,
20 0x00030021, 0x00000003, 0x00000002, 0x00040015, 0x00000006, 0x00000020, 0x00000000, 0x00040017, 20 0x00030021, 0x00000003, 0x00000002, 0x00040015, 0x00000006, 0x00000020, 0x00000000, 0x00040017,
21 0x00000009, 0x00000006, 0x00000003, 0x00040020, 0x0000000a, 0x00000001, 0x00000009, 0x0004003b, 21 0x00000009, 0x00000006, 0x00000003, 0x00040020, 0x0000000a, 0x00000001, 0x00000009, 0x0004003b,
22 0x0000000a, 0x0000000b, 0x00000001, 0x0004002b, 0x00000006, 0x0000000c, 0x00000000, 0x00040020, 22 0x0000000a, 0x0000000b, 0x00000001, 0x0004002b, 0x00000006, 0x0000000c, 0x00000000, 0x00040020,
@@ -28,42 +28,39 @@ inline constexpr std::uint32_t statistics_sum_spirv[] = {
28 0x00000002, 0x00000010, 0x00020014, 0x0000001f, 0x0004001e, 0x00000022, 0x00000006, 0x00000006, 28 0x00000002, 0x00000010, 0x00020014, 0x0000001f, 0x0004001e, 0x00000022, 0x00000006, 0x00000006,
29 0x00040020, 0x00000023, 0x00000009, 0x00000022, 0x0004003b, 0x00000023, 0x00000024, 0x00000009, 29 0x00040020, 0x00000023, 0x00000009, 0x00000022, 0x0004003b, 0x00000023, 0x00000024, 0x00000009,
30 0x0004002b, 0x00000019, 0x00000025, 0x00000001, 0x00040020, 0x00000026, 0x00000009, 0x00000006, 30 0x0004002b, 0x00000019, 0x00000025, 0x00000001, 0x00040020, 0x00000026, 0x00000009, 0x00000006,
31 0x0004002b, 0x00000006, 0x0000002e, 0x00000005, 0x0004002b, 0x00000006, 0x00000031, 0x00000007, 31 0x0004002b, 0x00000006, 0x0000002b, 0x00000005, 0x0004002b, 0x00000006, 0x0000002f, 0x00000007,
32 0x0004002b, 0x00000006, 0x00000036, 0x0000000a, 0x0004002b, 0x00000006, 0x00000040, 0x00000008, 32 0x0004002b, 0x00000006, 0x00000033, 0x0000000a, 0x0004002b, 0x00000006, 0x0000003d, 0x00000008,
33 0x0004002b, 0x00000006, 0x0000005e, 0x00000001, 0x0006002c, 0x00000009, 0x00000072, 0x00000013, 33 0x0004002b, 0x00000006, 0x0000005b, 0x00000001, 0x0006002c, 0x00000009, 0x0000006f, 0x00000013,
34 0x0000005e, 0x0000005e, 0x00050036, 0x00000002, 0x00000004, 0x00000000, 0x00000003, 0x000200f8, 34 0x0000005b, 0x0000005b, 0x00050036, 0x00000002, 0x00000004, 0x00000000, 0x00000003, 0x000200f8,
35 0x00000005, 0x00050041, 0x0000000d, 0x0000000e, 0x0000000b, 0x0000000c, 0x0004003d, 0x00000006, 35 0x00000005, 0x00050041, 0x0000000d, 0x0000000e, 0x0000000b, 0x0000000c, 0x0004003d, 0x00000006,
36 0x0000000f, 0x0000000e, 0x00060041, 0x0000001c, 0x0000001d, 0x00000018, 0x0000001a, 0x0000000f, 36 0x0000000f, 0x0000000e, 0x00060041, 0x0000001c, 0x0000001d, 0x00000018, 0x0000001a, 0x0000000f,
37 0x0004003d, 0x00000010, 0x0000001e, 0x0000001d, 0x00050041, 0x00000026, 0x00000027, 0x00000024, 37 0x0004003d, 0x00000010, 0x0000001e, 0x0000001d, 0x00050041, 0x00000026, 0x00000027, 0x00000024,
38 0x00000025, 0x0004003d, 0x00000006, 0x00000028, 0x00000027, 0x000500aa, 0x0000001f, 0x00000029, 38 0x00000025, 0x0004003d, 0x00000006, 0x00000028, 0x00000027, 0x000500aa, 0x0000001f, 0x00000029,
39 0x00000028, 0x0000000c, 0x000400a8, 0x0000001f, 0x0000002a, 0x00000029, 0x000300f7, 0x0000002c, 39 0x00000028, 0x0000000c, 0x000500aa, 0x0000001f, 0x0000002c, 0x0000000f, 0x0000002b, 0x000500a6,
40 0x00000000, 0x000400fa, 0x0000002a, 0x0000002b, 0x0000002c, 0x000200f8, 0x0000002b, 0x000500ae, 40 0x0000001f, 0x0000002d, 0x00000029, 0x0000002c, 0x000500aa, 0x0000001f, 0x00000030, 0x0000000f,
41 0x0000001f, 0x0000002f, 0x0000000f, 0x0000002e, 0x000500b2, 0x0000001f, 0x00000032, 0x0000000f, 41 0x0000002f, 0x000500a6, 0x0000001f, 0x00000031, 0x0000002d, 0x00000030, 0x000500aa, 0x0000001f,
42 0x00000031, 0x000500a7, 0x0000001f, 0x00000033, 0x0000002f, 0x00000032, 0x000200f9, 0x0000002c, 42 0x00000034, 0x0000000f, 0x00000033, 0x000500a6, 0x0000001f, 0x00000035, 0x00000031, 0x00000034,
43 0x000200f8, 0x0000002c, 0x000700f5, 0x0000001f, 0x00000034, 0x00000029, 0x00000005, 0x00000033, 43 0x000500ab, 0x0000001f, 0x00000039, 0x00000028, 0x0000000c, 0x000500a7, 0x0000001f, 0x0000003c,
44 0x0000002b, 0x000500aa, 0x0000001f, 0x00000037, 0x0000000f, 0x00000036, 0x000500a6, 0x0000001f, 44 0x00000039, 0x00000034, 0x000600a9, 0x00000006, 0x0000003f, 0x0000003c, 0x0000003d, 0x0000000f,
45 0x00000038, 0x00000034, 0x00000037, 0x000500ab, 0x0000001f, 0x0000003c, 0x00000028, 0x0000000c, 45 0x000200f9, 0x00000041, 0x000200f8, 0x00000041, 0x000700f5, 0x00000010, 0x00000082, 0x0000001e,
46 0x000500a7, 0x0000001f, 0x0000003f, 0x0000003c, 0x00000037, 0x000600a9, 0x00000006, 0x00000042, 46 0x00000005, 0x00000083, 0x00000042, 0x000700f5, 0x00000006, 0x00000071, 0x0000000c, 0x00000005,
47 0x0000003f, 0x00000040, 0x0000000f, 0x000200f9, 0x00000044, 0x000200f8, 0x00000044, 0x000700f5, 47 0x0000006b, 0x00000042, 0x000400f6, 0x00000043, 0x00000042, 0x00000000, 0x000200f9, 0x00000045,
48 0x00000010, 0x0000007f, 0x0000001e, 0x0000002c, 0x0000007c, 0x00000045, 0x000700f5, 0x00000006, 48 0x000200f8, 0x00000045, 0x000300f7, 0x00000048, 0x00000000, 0x000400fa, 0x00000035, 0x00000047,
49 0x0000007d, 0x0000000c, 0x0000002c, 0x0000006e, 0x00000045, 0x000400f6, 0x00000046, 0x00000045, 49 0x00000048, 0x000200f8, 0x00000047, 0x00050041, 0x00000026, 0x0000004a, 0x00000024, 0x0000001a,
50 0x00000000, 0x000200f9, 0x00000048, 0x000200f8, 0x00000048, 0x000300f7, 0x0000004b, 0x00000000, 50 0x0004003d, 0x00000006, 0x0000004b, 0x0000004a, 0x000500b0, 0x0000001f, 0x0000004c, 0x00000071,
51 0x000400fa, 0x00000038, 0x0000004a, 0x0000004b, 0x000200f8, 0x0000004a, 0x00050041, 0x00000026, 51 0x0000004b, 0x000200f9, 0x00000048, 0x000200f8, 0x00000048, 0x000700f5, 0x0000001f, 0x0000004d,
52 0x0000004d, 0x00000024, 0x0000001a, 0x0004003d, 0x00000006, 0x0000004e, 0x0000004d, 0x000500b0, 52 0x00000035, 0x00000045, 0x0000004c, 0x00000047, 0x000400fa, 0x0000004d, 0x00000042, 0x00000043,
53 0x0000001f, 0x0000004f, 0x0000007d, 0x0000004e, 0x000200f9, 0x0000004b, 0x000200f8, 0x0000004b, 53 0x000200f8, 0x00000042, 0x00050084, 0x00000006, 0x00000050, 0x00000071, 0x00000013, 0x00050080,
54 0x000700f5, 0x0000001f, 0x00000050, 0x00000038, 0x00000048, 0x0000004f, 0x0000004a, 0x000400fa, 54 0x00000006, 0x00000052, 0x00000050, 0x0000003f, 0x00060041, 0x0000001c, 0x00000053, 0x00000018,
55 0x00000050, 0x00000045, 0x00000046, 0x000200f8, 0x00000045, 0x00050084, 0x00000006, 0x00000053, 55 0x00000025, 0x00000052, 0x0004003d, 0x00000010, 0x00000054, 0x00000053, 0x00050051, 0x00000006,
56 0x0000007d, 0x00000013, 0x00050080, 0x00000006, 0x00000055, 0x00000053, 0x00000042, 0x00060041, 56 0x00000057, 0x00000082, 0x00000000, 0x00050051, 0x00000006, 0x00000059, 0x00000054, 0x00000000,
57 0x0000001c, 0x00000056, 0x00000018, 0x00000025, 0x00000055, 0x0004003d, 0x00000010, 0x00000057, 57 0x00050080, 0x00000006, 0x0000005a, 0x00000057, 0x00000059, 0x00050051, 0x00000006, 0x0000005d,
58 0x00000056, 0x00050051, 0x00000006, 0x0000005a, 0x0000007f, 0x00000000, 0x00050051, 0x00000006, 58 0x00000054, 0x00000001, 0x000500b0, 0x0000001f, 0x00000061, 0x0000005a, 0x00000057, 0x000600a9,
59 0x0000005c, 0x00000057, 0x00000000, 0x00050080, 0x00000006, 0x0000005d, 0x0000005a, 0x0000005c, 59 0x00000006, 0x00000062, 0x00000061, 0x0000005b, 0x0000000c, 0x00050080, 0x00000006, 0x00000063,
60 0x00050051, 0x00000006, 0x00000060, 0x00000057, 0x00000001, 0x000500b0, 0x0000001f, 0x00000064, 60 0x0000005d, 0x00000062, 0x00050051, 0x00000006, 0x00000065, 0x00000082, 0x00000001, 0x00050080,
61 0x0000005d, 0x0000005a, 0x000600a9, 0x00000006, 0x00000065, 0x00000064, 0x0000005e, 0x0000000c, 61 0x00000006, 0x00000066, 0x00000065, 0x00000063, 0x00050050, 0x00000010, 0x00000083, 0x0000005a,
62 0x00050080, 0x00000006, 0x00000066, 0x00000060, 0x00000065, 0x00050051, 0x00000006, 0x00000068, 62 0x00000066, 0x00050080, 0x00000006, 0x0000006b, 0x00000071, 0x00000025, 0x000200f9, 0x00000041,
63 0x0000007f, 0x00000001, 0x00050080, 0x00000006, 0x00000069, 0x00000068, 0x00000066, 0x00050050, 63 0x000200f8, 0x00000043, 0x0003003e, 0x0000001d, 0x00000082, 0x000100fd, 0x00010038,
64 0x00000010, 0x0000007c, 0x0000005d, 0x00000069, 0x00050080, 0x00000006, 0x0000006e, 0x0000007d,
65 0x00000025, 0x000200f9, 0x00000044, 0x000200f8, 0x00000046, 0x0003003e, 0x0000001d, 0x0000007f,
66 0x000100fd, 0x00010038,
67}; 64};
68 65
69} // namespace leonida 66} // namespace leonida
diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h
index e3e4defe8..f4373787b 100644
--- a/runtime/src/vulkan_backend.h
+++ b/runtime/src/vulkan_backend.h
@@ -244,12 +244,16 @@ public:
244 244
245 // Adds `count` pipeline-statistics results into one D3D12_QUERY_DATA_PIPELINE_STATISTICS at dst + offset: the 245 // Adds `count` pipeline-statistics results into one D3D12_QUERY_DATA_PIPELINE_STATISTICS at dst + offset: the
246 // segments of a statistics query that was split around helper dispatches (D3D-162) or mesh draws (D3D-291). 246 // segments of a statistics query that was split around helper dispatches (D3D-162) or mesh draws (D3D-291).
247 // Segment i is in `mesh_queries` when mesh[i] is set (four counters: clipping, fragment and compute; see 247 // Segment i is in `mesh_queries` when mesh[i] is set (two counters: fragment and compute; see
248 // statistics_sum.comp), otherwise in `queries` (all eleven). 248 // statistics_sum.comp), otherwise in `queries` (all eleven). A mesh segment's clipping invocations come from
249 void sum_statistics(VkCommandBuffer cb, VkQueryPool queries, VkQueryPool mesh_queries, const std::uint8_t* mesh, 249 // `primitives_queries`, the mesh-primitives count of that segment (D3D-MESH-CLIPPING-COUNTER); it is null when
250 std::uint32_t first, std::uint32_t count, VkBuffer dst, VkDeviceSize offset) const { 250 // the device has no meshShaderQueries, and the field then reads 0.
251 void sum_statistics(VkCommandBuffer cb, VkQueryPool queries, VkQueryPool mesh_queries,
252 VkQueryPool primitives_queries, const std::uint8_t* mesh, std::uint32_t first,
253 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) const {
251 constexpr VkDeviceSize result = statistics_counters * word_size; 254 constexpr VkDeviceSize result = statistics_counters * word_size;
252 constexpr VkDeviceSize mesh_slot = 5 * word_size; // CInvocations, where the mesh pool's first counter goes 255 constexpr VkDeviceSize mesh_slot = 7 * word_size; // PSInvocations, where the mesh pool's first counter goes
256 constexpr VkDeviceSize clipping_slot = 5 * word_size; // CInvocations, where the mesh-primitives count goes
253 begin_scratch_write(cb); 257 begin_scratch_write(cb);
254 vk_.vkCmdFillBuffer(cb, scratch_, 0, result, 0); 258 vk_.vkCmdFillBuffer(cb, scratch_, 0, result, 0);
255 bind(cb, statistics_pipeline_); 259 bind(cb, statistics_pipeline_);
@@ -258,9 +262,18 @@ public:
258 std::uint32_t chunk = 1; 262 std::uint32_t chunk = 1;
259 while (chunk < std::min(count, statistics_capacity) && bool(mesh && mesh[first + chunk]) == in_mesh) 263 while (chunk < std::min(count, statistics_capacity) && bool(mesh && mesh[first + chunk]) == in_mesh)
260 ++chunk; 264 ++chunk;
265 if (in_mesh) {
266 // The mesh pool holds only the fragment and compute counters, so the clipping field of a mesh
267 // segment reads 0 unless the mesh-primitives count fills it (D3D-MESH-CLIPPING-COUNTER).
268 vk_.vkCmdFillBuffer(cb, scratch_, result, chunk * result, 0);
269 barrier(cb, transfer, transfer, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT);
270 }
261 vk_.vkCmdCopyQueryPoolResults(cb, in_mesh ? mesh_queries : queries, first, chunk, scratch_, 271 vk_.vkCmdCopyQueryPoolResults(cb, in_mesh ? mesh_queries : queries, first, chunk, scratch_,
262 result + (in_mesh ? mesh_slot : 0), result, 272 result + (in_mesh ? mesh_slot : 0), result,
263 VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); 273 VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT);
274 if (in_mesh && primitives_queries)
275 vk_.vkCmdCopyQueryPoolResults(cb, primitives_queries, first, chunk, scratch_, result + clipping_slot,
276 result, VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT);
264 barrier(cb, transfer | compute, compute, VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_SHADER_WRITE_BIT, 277 barrier(cb, transfer | compute, compute, VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_SHADER_WRITE_BIT,
265 shader_access); 278 shader_access);
266 dispatch(cb, chunk, 1, in_mesh); 279 dispatch(cb, chunk, 1, in_mesh);
@@ -923,6 +936,10 @@ struct TileRange {
923#endif 936#endif
924class VulkanContext { 937class VulkanContext {
925public: 938public:
939 // mesh_queries: VK_EXT_mesh_shader's meshShaderQueries feature is enabled on `device`, so a mesh segment's
940 // clipping invocations can come from a mesh-primitives query (D3D-MESH-CLIPPING-COUNTER). Set by the device
941 // that created the context.
942 bool mesh_queries = false;
926 // conditional_rendering: VK_EXT_conditional_rendering is enabled on `device` (SetPredication). 943 // conditional_rendering: VK_EXT_conditional_rendering is enabled on `device` (SetPredication).
927 // ray_tracing: VK_KHR_acceleration_structure + VK_KHR_ray_query are enabled on `device`. 944 // ray_tracing: VK_KHR_acceleration_structure + VK_KHR_ray_query are enabled on `device`.
928 // xdxr: acceleration-structure builds write XDXR BVH4 records (xdxr_build.h) instead; needs bufferDeviceAddress. 945 // xdxr: acceleration-structure builds write XDXR BVH4 records (xdxr_build.h) instead; needs bufferDeviceAddress.
@@ -1000,7 +1017,7 @@ public:
1000 // binding's host pointer is null on DEFAULT and READBACK heaps, whose mapped bytes the GPU can write. 1017 // binding's host pointer is null on DEFAULT and READBACK heaps, whose mapped bytes the GPU can write.
1001 replay_.host_at = [this](std::uint64_t va, std::uint64_t bytes, const std::uint8_t*& host) { 1018 replay_.host_at = [this](std::uint64_t va, std::uint64_t bytes, const std::uint8_t*& host) {
1002 BufferVaIndex<ResourceId>::Hit hit{}; 1019 BufferVaIndex<ResourceId>::Hit hit{};
1003 if (!buffer_vas_.find(va, hit)) return HostReadStatus::absent; 1020 if (!buffer_vas_.find(va, hit, bytes)) return HostReadStatus::absent;
1004 const ResourceBinding* b = resolve(hit.id); 1021 const ResourceBinding* b = resolve(hit.id);
1005 if (!b) return HostReadStatus::absent; 1022 if (!b) return HostReadStatus::absent;
1006 if (!b->host) return HostReadStatus::not_cpu_written; 1023 if (!b->host) return HostReadStatus::not_cpu_written;
@@ -1268,6 +1285,11 @@ public:
1268 replay_.zero_size = size; 1285 replay_.zero_size = size;
1269 } 1286 }
1270 1287
1288 void set_depth_range_unrestricted(bool enabled) {
1289 std::unique_lock lock(resource_mutex_);
1290 replay_.depth_range_unrestricted = enabled;
1291 }
1292
1271 // Physical-device COLOR_ATTACHMENT format check for reinterpreted UAV clears. 1293 // Physical-device COLOR_ATTACHMENT format check for reinterpreted UAV clears.
1272 void set_color_attachment_format(std::function<bool(VkFormat)> check) { 1294 void set_color_attachment_format(std::function<bool(VkFormat)> check) {
1273 std::unique_lock lock(resource_mutex_); 1295 std::unique_lock lock(resource_mutex_);
@@ -1483,12 +1505,23 @@ public:
1483 void note_bindless_upload() { bindless_upload_pending_ = true; } 1505 void note_bindless_upload() { bindless_upload_pending_ = true; }
1484 1506
1485 std::uint64_t completed_retire_ticket() { 1507 std::uint64_t completed_retire_ticket() {
1486 std::lock_guard lock(submit_mutex_); 1508 bool lost = false;
1487 if (is_device_lost()) return 0; 1509 std::uint64_t ticket = 0;
1488 return retire_tickets_.completed([this](VkSemaphore semaphore, std::uint64_t value) { 1510 {
1489 std::uint64_t done = 0; 1511 std::lock_guard lock(submit_mutex_);
1490 return vk.vkGetSemaphoreCounterValue(device_, semaphore, &done) == VK_SUCCESS && done >= value; 1512 if (is_device_lost()) return 0;
1491 }); 1513 ticket = retire_tickets_.completed([this, &lost](VkSemaphore semaphore, std::uint64_t value) {
1514 std::uint64_t done = 0;
1515 const VkResult result = vk.vkGetSemaphoreCounterValue(device_, semaphore, &done);
1516 if (result == VK_ERROR_DEVICE_LOST) lost = true;
1517 return result == VK_SUCCESS && done >= value;
1518 });
1519 }
1520 // Outside submit_mutex_, as in submit(): notifying the fence dispatcher can run callbacks that submit.
1521 // A DEVICE_LOST seen here is the first Vulkan operation to discover it; it must not be mistaken for
1522 // "this ticket has not completed".
1523 if (lost) mark_device_lost();
1524 return lost ? 0 : ticket;
1492 } 1525 }
1493 1526
1494 void drain_deleted_resources(std::uint64_t current_ticket) { 1527 void drain_deleted_resources(std::uint64_t current_ticket) {
@@ -2394,9 +2427,11 @@ private:
2394 occlusion_resolve_->normalize(cb, pool, first, count, dst, offset); 2427 occlusion_resolve_->normalize(cb, pool, first, count, dst, offset);
2395 }; 2428 };
2396 replay.sum_statistics = [this](VkCommandBuffer cb, VkQueryPool pool, VkQueryPool mesh_pool, 2429 replay.sum_statistics = [this](VkCommandBuffer cb, VkQueryPool pool, VkQueryPool mesh_pool,
2397 const std::uint8_t* mesh, std::uint32_t first, std::uint32_t count, 2430 VkQueryPool primitives_pool, const std::uint8_t* mesh,
2398 VkBuffer dst, VkDeviceSize offset) { 2431 std::uint32_t first, std::uint32_t count, VkBuffer dst,
2399 occlusion_resolve_->sum_statistics(cb, pool, mesh_pool, mesh, first, count, dst, offset); 2432 VkDeviceSize offset) {
2433 occlusion_resolve_->sum_statistics(cb, pool, mesh_pool, primitives_pool, mesh, first, count, dst,
2434 offset);
2400 }; 2435 };
2401 replay.sum_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, 2436 replay.sum_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first,
2402 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { 2437 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) {
@@ -2443,18 +2478,26 @@ private:
2443 if (std::find(statistics->mesh.begin(), statistics->mesh.end(), 1) == statistics->mesh.end()) { 2478 if (std::find(statistics->mesh.begin(), statistics->mesh.end(), 1) == statistics->mesh.end()) {
2444 statistics->mesh.clear(); 2479 statistics->mesh.clear();
2445 } else { 2480 } else {
2446 // The counters a mesh draw allows (VUID-vkCmdDrawMeshTasksEXT-pipelineStatistics-07076): clipping 2481 // The counters a mesh draw allows (VUID-vkCmdDrawMeshTasksEXT-pipelineStatistics-07076): the
2447 // invocations and primitives, fragment and compute invocations (D3D-291). 2482 // fragment and compute invocations, and no other (D3D-291).
2448 VkQueryPoolCreateInfo info{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO}; 2483 VkQueryPoolCreateInfo info{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO};
2449 info.queryType = VK_QUERY_TYPE_PIPELINE_STATISTICS; 2484 info.queryType = VK_QUERY_TYPE_PIPELINE_STATISTICS;
2450 info.queryCount = statistics_segments; 2485 info.queryCount = statistics_segments;
2451 info.pipelineStatistics = VK_QUERY_PIPELINE_STATISTIC_CLIPPING_INVOCATIONS_BIT | 2486 info.pipelineStatistics = kMeshStatisticsFlags;
2452 VK_QUERY_PIPELINE_STATISTIC_CLIPPING_PRIMITIVES_BIT |
2453 VK_QUERY_PIPELINE_STATISTIC_FRAGMENT_SHADER_INVOCATIONS_BIT |
2454 VK_QUERY_PIPELINE_STATISTIC_COMPUTE_SHADER_INVOCATIONS_BIT;
2455 if (context_.vk.vkCreateQueryPool(statistics->device, &info, nullptr, &statistics->mesh_pool) != 2487 if (context_.vk.vkCreateQueryPool(statistics->device, &info, nullptr, &statistics->mesh_pool) !=
2456 VK_SUCCESS) 2488 VK_SUCCESS)
2457 return ReplayResult::unsupported; 2489 return ReplayResult::unsupported;
2490 // The mesh-primitives count of a mesh segment (D3D-MESH-CLIPPING-COUNTER): a query of its own type,
2491 // which the pipeline-statistics pool cannot hold. The device needs the meshShaderQueries feature,
2492 // or the clipping field of a mesh segment stays 0.
2493 if (context_.mesh_queries) {
2494 VkQueryPoolCreateInfo primitives{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO};
2495 primitives.queryType = VK_QUERY_TYPE_MESH_PRIMITIVES_GENERATED_EXT;
2496 primitives.queryCount = statistics_segments;
2497 if (context_.vk.vkCreateQueryPool(statistics->device, &primitives, nullptr,
2498 &statistics->primitives_pool) != VK_SUCCESS)
2499 return ReplayResult::unsupported;
2500 }
2458 } 2501 }
2459 } 2502 }
2460 // QueryReplay::plan() reads QueryPool::ended / occlusion and QueryReplay::commit() writes them after 2503 // QueryReplay::plan() reads QueryPool::ended / occlusion and QueryReplay::commit() writes them after
@@ -2515,6 +2558,18 @@ private:
2515 discard(); 2558 discard();
2516 return ReplayResult::unsupported; 2559 return ReplayResult::unsupported;
2517 } 2560 }
2561 // D3D12 ends every ExecuteCommandLists with all its work done and its writes visible to the next one on the
2562 // queue (implicit state decay relies on it), and a list may then touch the same memory without a barrier:
2563 // two submissions copying into one buffer, say. Vulkan orders submissions on a queue only by what their
2564 // barriers say, so this one starts with a full memory barrier against everything submitted before it
2565 // (synchronization validation: WRITE_AFTER_WRITE between vk_queue_test's back-to-back copies).
2566 if (context_.vk.vkCmdPipelineBarrier) { // a mocked context may leave it out
2567 VkMemoryBarrier full{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
2568 full.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT;
2569 full.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
2570 context_.vk.vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
2571 VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 1, &full, 0, nullptr, 0, nullptr);
2572 }
2518 if (!tracker_lock.owns_lock()) tracker_lock.lock(); 2573 if (!tracker_lock.owns_lock()) tracker_lock.lock();
2519 if (!transfer_only && context_.bindless_prepare_ && !context_.bindless_prepare_(command_buffer)) { 2574 if (!transfer_only && context_.bindless_prepare_ && !context_.bindless_prepare_(command_buffer)) {
2520 const bool ended = context_.vk.vkEndCommandBuffer(command_buffer) == VK_SUCCESS; 2575 const bool ended = context_.vk.vkEndCommandBuffer(command_buffer) == VK_SUCCESS;
diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h
index 889bb71f7..bcaea02f8 100644
--- a/runtime/src/vulkan_replay.h
+++ b/runtime/src/vulkan_replay.h
@@ -216,7 +216,10 @@ inline VkPipelineStageFlags2 vulkan_sync(std::uint32_t sync) {
216 VK_PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT}, 216 VK_PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT},
217 {y::render_target, VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT}, 217 {y::render_target, VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT},
218 {y::compute_shading, VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT}, 218 {y::compute_shading, VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT},
219 {y::copy, VK_PIPELINE_STAGE_2_COPY_BIT}, 219 // CLEAR as well: two D3D12 copy-scope commands are recorded as Vulkan clear commands, WriteBufferImmediate
220 // as vkCmdUpdateBuffer and ResolveQueryData's never-written queries as vkCmdFillBuffer, and synchronization2
221 // puts both in the CLEAR stage, not COPY.
222 {y::copy, VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_CLEAR_BIT},
220 {y::resolve, VK_PIPELINE_STAGE_2_RESOLVE_BIT}, 223 {y::resolve, VK_PIPELINE_STAGE_2_RESOLVE_BIT},
221 {y::execute_indirect, VK_PIPELINE_STAGE_2_DRAW_INDIRECT_BIT}, 224 {y::execute_indirect, VK_PIPELINE_STAGE_2_DRAW_INDIRECT_BIT},
222 {y::all_shading, pre_raster | VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT}, 225 {y::all_shading, pre_raster | VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT},
@@ -716,6 +719,9 @@ struct OcclusionSegmentPool {
716 // segment index whether it runs there. Empty when no segment of the submission holds a mesh draw. 719 // segment index whether it runs there. Empty when no segment of the submission holds a mesh draw.
717 VkQueryPool mesh_pool = VK_NULL_HANDLE; 720 VkQueryPool mesh_pool = VK_NULL_HANDLE;
718 std::vector<std::uint8_t> mesh; 721 std::vector<std::uint8_t> mesh;
722 // The mesh-primitives pool of the mesh segments (D3D-MESH-CLIPPING-COUNTER): one query per segment, begun and
723 // ended with the mesh segment. Null when the device has no meshShaderQueries.
724 VkQueryPool primitives_pool = VK_NULL_HANDLE;
719 725
720 OcclusionSegmentPool() = default; 726 OcclusionSegmentPool() = default;
721 OcclusionSegmentPool(const OcclusionSegmentPool&) = delete; 727 OcclusionSegmentPool(const OcclusionSegmentPool&) = delete;
@@ -723,6 +729,7 @@ struct OcclusionSegmentPool {
723 ~OcclusionSegmentPool() { 729 ~OcclusionSegmentPool() {
724 if (pool) destroy(device, pool, nullptr); 730 if (pool) destroy(device, pool, nullptr);
725 if (mesh_pool) destroy(device, mesh_pool, nullptr); 731 if (mesh_pool) destroy(device, mesh_pool, nullptr);
732 if (primitives_pool) destroy(device, primitives_pool, nullptr);
726 } 733 }
727}; 734};
728 735
@@ -810,6 +817,7 @@ struct ReplayFunctions {
810 PFN_vkCmdPipelineBarrier pipeline_barrier = nullptr; 817 PFN_vkCmdPipelineBarrier pipeline_barrier = nullptr;
811 PFN_vkCmdClearColorImage clear_color_image = nullptr; 818 PFN_vkCmdClearColorImage clear_color_image = nullptr;
812 PFN_vkCmdClearDepthStencilImage clear_depth_stencil_image = nullptr; 819 PFN_vkCmdClearDepthStencilImage clear_depth_stencil_image = nullptr;
820 bool depth_range_unrestricted = false; // Allows out-of-range float depth clear values.
813 // Optional; a list that needs a missing one is rejected with ReplayResult::unsupported. 821 // Optional; a list that needs a missing one is rejected with ReplayResult::unsupported.
814 PFN_vkCmdPipelineBarrier2 pipeline_barrier2 = nullptr; // enhanced barriers 822 PFN_vkCmdPipelineBarrier2 pipeline_barrier2 = nullptr; // enhanced barriers
815 VkPipelineStageFlags2 queue_stages = 0; 823 VkPipelineStageFlags2 queue_stages = 0;
@@ -875,9 +883,12 @@ struct ReplayFunctions {
875 VkBuffer dst, VkDeviceSize offset)> resolve_binary_occlusion; 883 VkBuffer dst, VkDeviceSize offset)> resolve_binary_occlusion;
876 // Adds `count` pipeline-statistics results into one D3D12_QUERY_DATA_PIPELINE_STATISTICS, outside conditional 884 // Adds `count` pipeline-statistics results into one D3D12_QUERY_DATA_PIPELINE_STATISTICS, outside conditional
877 // rendering: the segments of a statistics query split around resolves (D3D-162) and mesh draws (D3D-291). 885 // rendering: the segments of a statistics query split around resolves (D3D-162) and mesh draws (D3D-291).
878 // Segment i is in the second pool when mesh[i] is set (mesh may be null: none is). 886 // Segment i is in the second pool when mesh[i] is set (mesh may be null: none is). The third pool holds the
879 std::function<void(VkCommandBuffer, VkQueryPool, VkQueryPool mesh_pool, const std::uint8_t* mesh, 887 // mesh-primitives count of a mesh segment (D3D-MESH-CLIPPING-COUNTER); it is null when the device has no
880 std::uint32_t first, std::uint32_t count, VkBuffer dst, VkDeviceSize offset)> 888 // meshShaderQueries.
889 std::function<void(VkCommandBuffer, VkQueryPool, VkQueryPool mesh_pool, VkQueryPool primitives_pool,
890 const std::uint8_t* mesh, std::uint32_t first, std::uint32_t count, VkBuffer dst,
891 VkDeviceSize offset)>
881 sum_statistics; 892 sum_statistics;
882 // Sums `count` binary-occlusion segments and normalizes the total to a 64-bit 0 or 1, outside conditional 893 // Sums `count` binary-occlusion segments and normalizes the total to a 64-bit 0 or 1, outside conditional
883 // rendering: a binary query split over physical segments because it overlaps other occlusion queries (D3D-252). 894 // rendering: a binary query split over physical segments because it overlaps other occlusion queries (D3D-252).
@@ -958,6 +969,8 @@ struct QueryResolveRun {
958 bool sum = false; 969 bool sum = false;
959 // Statistics segments: the mesh-compatible pool and the kind of each segment (OcclusionSegmentPool::mesh). 970 // Statistics segments: the mesh-compatible pool and the kind of each segment (OcclusionSegmentPool::mesh).
960 VkQueryPool mesh_pool = VK_NULL_HANDLE; 971 VkQueryPool mesh_pool = VK_NULL_HANDLE;
972 // The mesh-primitives pool of the mesh segments (D3D-MESH-CLIPPING-COUNTER); null without meshShaderQueries.
973 VkQueryPool primitives_pool = VK_NULL_HANDLE;
961 const std::uint8_t* mesh = nullptr; 974 const std::uint8_t* mesh = nullptr;
962}; 975};
963 976
@@ -1598,6 +1611,7 @@ inline ReplayResult prepare_buffer_uav_clear(const ClearUnorderedAccess& clear,
1598 if (offset > UINT64_MAX - p.binding.buffer_offset || 1611 if (offset > UINT64_MAX - p.binding.buffer_offset ||
1599 bytes > UINT64_MAX - (p.binding.buffer_offset + offset)) return ReplayResult::invalid_clear; 1612 bytes > UINT64_MAX - (p.binding.buffer_offset + offset)) return ReplayResult::invalid_clear;
1600 offset += p.binding.buffer_offset; // the view is relative to the resource, which starts at buffer_offset 1613 offset += p.binding.buffer_offset; // the view is relative to the resource, which starts at buffer_offset
1614 if (offset % std::min(e, 4u)) return ReplayResult::unsupported;
1601 if (e > 4 && bytes % 4) { 1615 if (e > 4 && bytes % 4) {
1602 return ReplayResult::unsupported; 1616 return ReplayResult::unsupported;
1603 } 1617 }
@@ -1869,27 +1883,48 @@ inline ReplayResult prepare_texture_copy(const CopyTexture& copy, Prepared& p) {
1869 return ReplayResult::success; 1883 return ReplayResult::success;
1870} 1884}
1871 1885
1872// RGBA8 CopyTiles accepts arbitrary byte offsets into its linear buffer, while VkBufferImageCopy requires texel 1886// CopyTiles accepts arbitrary byte offsets into its linear buffer, while VkBufferImageCopy requires texel/block
1873// alignment. Stage only the occupied texels through aligned transfer scratch; leave partial-tile padding alone. 1887// alignment (VUID-vkCmdCopyBufferToImage-dstImage-07975). Stage only the occupied texels/blocks through aligned
1874inline bool stage_unaligned_tile(const ReplayFunctions& vk, Prepared& p, bool upload) { 1888// transfer scratch; leave partial-tile padding alone.
1889inline bool stage_unaligned_tile(const ReplayFunctions& vk, Prepared& p, const ResourceBinding& image,
1890 const BlockFormat& fmt, bool upload) {
1875 auto& region = p.buffer_image_copies.front(); 1891 auto& region = p.buffer_image_copies.front();
1876 const VkDeviceSize row_bytes = VkDeviceSize(region.imageExtent.width) * 4; 1892 if (!fmt.bytes || !fmt.block || image.rgb96 ||
1877 const VkDeviceSize pitch = VkDeviceSize(region.bufferRowLength) * 4; 1893 (image.depth24_as_float && region.imageSubresource.aspectMask == VK_IMAGE_ASPECT_DEPTH_BIT))
1878 const auto rows = region.imageExtent.height; 1894 return false;
1895 const VkDeviceSize blocks_w = (VkDeviceSize(region.imageExtent.width) + fmt.block - 1) / fmt.block;
1896 const VkDeviceSize rows = (VkDeviceSize(region.imageExtent.height) + fmt.block - 1) / fmt.block;
1897 const VkDeviceSize depth = region.imageExtent.depth;
1898 const VkDeviceSize row_bytes = blocks_w * fmt.bytes;
1899 const VkDeviceSize pitch =
1900 region.bufferRowLength ? VkDeviceSize(region.bufferRowLength / fmt.block) * fmt.bytes : row_bytes;
1901 const VkDeviceSize slice_rows =
1902 region.bufferImageHeight ? VkDeviceSize(region.bufferImageHeight / fmt.block) : rows;
1903 const VkDeviceSize slice_pitch = slice_rows * pitch;
1904 const VkDeviceSize slice_bytes = row_bytes * rows;
1905 const VkDeviceSize total_bytes = slice_bytes * depth;
1879 VkDeviceSize scratch_offset = 0; 1906 VkDeviceSize scratch_offset = 0;
1880 if (!vk.copy_scratch || !vk.copy_scratch(row_bytes * rows, p.tile_scratch, scratch_offset)) return false; 1907 if (!total_bytes || !vk.copy_scratch || !vk.copy_scratch(total_bytes, p.tile_scratch, scratch_offset)) return false;
1881 const auto app_offset = region.bufferOffset; 1908 const auto app_offset = region.bufferOffset;
1882 const auto add_copy = [&](VkDeviceSize linear, VkDeviceSize scratch, VkDeviceSize bytes) { 1909 const auto add_copy = [&](VkDeviceSize linear, VkDeviceSize scratch, VkDeviceSize bytes) {
1883 p.tile_rows.push_back(upload ? VkBufferCopy{linear, scratch, bytes} : VkBufferCopy{scratch, linear, bytes}); 1910 p.tile_rows.push_back(upload ? VkBufferCopy{linear, scratch, bytes} : VkBufferCopy{scratch, linear, bytes});
1884 }; 1911 };
1885 if (row_bytes == pitch) { 1912 if (row_bytes == pitch && (depth == 1 || slice_rows == rows)) {
1886 add_copy(app_offset, scratch_offset, row_bytes * rows); 1913 add_copy(app_offset, scratch_offset, total_bytes);
1914 } else if (row_bytes == pitch) {
1915 for (VkDeviceSize z = 0; z < depth; ++z)
1916 add_copy(app_offset + z * slice_pitch, scratch_offset + z * slice_bytes, slice_bytes);
1887 } else { 1917 } else {
1888 for (std::uint32_t row = 0; row < rows; ++row) 1918 for (VkDeviceSize z = 0; z < depth; ++z) {
1889 add_copy(app_offset + row * pitch, scratch_offset + row * row_bytes, row_bytes); 1919 const VkDeviceSize linear_slice = app_offset + z * slice_pitch;
1920 const VkDeviceSize scratch_slice = scratch_offset + z * slice_bytes;
1921 for (VkDeviceSize row = 0; row < rows; ++row)
1922 add_copy(linear_slice + row * pitch, scratch_slice + row * row_bytes, row_bytes);
1923 }
1890 } 1924 }
1891 region.bufferOffset = scratch_offset; 1925 region.bufferOffset = scratch_offset;
1892 region.bufferRowLength = 0; 1926 region.bufferRowLength = 0;
1927 region.bufferImageHeight = 0;
1893 return true; 1928 return true;
1894} 1929}
1895 1930
@@ -2300,6 +2335,8 @@ public:
2300 // For each of those segments, whether it holds mesh draws and so runs in statistics_mesh_pool (D3D-291). 2335 // For each of those segments, whether it holds mesh draws and so runs in statistics_mesh_pool (D3D-291).
2301 std::vector<std::uint8_t> statistics_mesh; 2336 std::vector<std::uint8_t> statistics_mesh;
2302 VkQueryPool statistics_mesh_pool = VK_NULL_HANDLE; 2337 VkQueryPool statistics_mesh_pool = VK_NULL_HANDLE;
2338 // The mesh-primitives pool of the list's mesh segments (D3D-MESH-CLIPPING-COUNTER).
2339 VkQueryPool statistics_primitives_pool = VK_NULL_HANDLE;
2303 // Copies, resolves and UAV clears that run as transfers, recorded while a predicate was set. D3D12 skips them 2340 // Copies, resolves and UAV clears that run as transfers, recorded while a predicate was set. D3D12 skips them
2304 // when the predicate says so, but Vulkan's conditional rendering does not cover transfer commands, so they run 2341 // when the predicate says so, but Vulkan's conditional rendering does not cover transfer commands, so they run
2305 // unconditionally (docs/d3d12_vulkan.md section 4.7). Counted so the caller can report it. 2342 // unconditionally (docs/d3d12_vulkan.md section 4.7). Counted so the caller can report it.
@@ -2344,10 +2381,26 @@ inline ReplayResult plan_occlusion_segments(PreparedList& out) {
2344// Helper dispatches must not contribute to the application's CSInvocations (D3D-162). Query resolves and 2381// Helper dispatches must not contribute to the application's CSInvocations (D3D-162). Query resolves and
2345// ordinary helper commands share one sequence of physical statistics segments. Resolve dispatch requirements 2382// ordinary helper commands share one sequence of physical statistics segments. Resolve dispatch requirements
2346// depend on heap state at planning time, so every non-timestamp resolve splits conservatively. 2383// depend on heap state at planning time, so every non-timestamp resolve splits conservatively.
2347// A mesh draw cannot run while a query with the input-assembly, vertex, geometry or tessellation counters is active 2384// The counters a mesh draw may count: VUID-vkCmdDrawMeshTasksEXT-pipelineStatistics-07076 leaves the input
2348// (VUID-vkCmdDrawMeshTasksEXT-pipelineStatistics-07076), though D3D12 allows it and reads those fields as 0. A query 2385// assembly, vertex, geometry, tessellation and clipping bits out of the pipelineStatistics flags of every pool that
2349// that holds a mesh draw is split as well (D3D-291): a segment's first draw decides whether it runs in the full pool 2386// is active during a mesh draw, so a mesh segment runs in a pool with the fragment and compute counters only
2350// or in the mesh one (statistics_mesh), and a later draw of the other kind ends it and begins one of its own kind. 2387// (D3D-291). D3D12 counts the clipping invocations and primitives of a mesh pipeline, but Vulkan has no counter for
2388// them during a mesh draw, so those two fields read 0.
2389inline constexpr VkQueryPipelineStatisticFlags kMeshStatisticsFlags =
2390 VK_QUERY_PIPELINE_STATISTIC_FRAGMENT_SHADER_INVOCATIONS_BIT | VK_QUERY_PIPELINE_STATISTIC_COMPUTE_SHADER_INVOCATIONS_BIT;
2391// The bits the same VUID forbids in a pool that is active during a mesh draw.
2392inline constexpr VkQueryPipelineStatisticFlags kForbiddenMeshStatisticsFlags =
2393 VK_QUERY_PIPELINE_STATISTIC_INPUT_ASSEMBLY_VERTICES_BIT | VK_QUERY_PIPELINE_STATISTIC_INPUT_ASSEMBLY_PRIMITIVES_BIT |
2394 VK_QUERY_PIPELINE_STATISTIC_VERTEX_SHADER_INVOCATIONS_BIT | VK_QUERY_PIPELINE_STATISTIC_GEOMETRY_SHADER_INVOCATIONS_BIT |
2395 VK_QUERY_PIPELINE_STATISTIC_GEOMETRY_SHADER_PRIMITIVES_BIT | VK_QUERY_PIPELINE_STATISTIC_CLIPPING_INVOCATIONS_BIT |
2396 VK_QUERY_PIPELINE_STATISTIC_CLIPPING_PRIMITIVES_BIT |
2397 VK_QUERY_PIPELINE_STATISTIC_TESSELLATION_CONTROL_SHADER_PATCHES_BIT |
2398 VK_QUERY_PIPELINE_STATISTIC_TESSELLATION_EVALUATION_SHADER_INVOCATIONS_BIT;
2399// A mesh draw cannot run while a query with the input-assembly, vertex, geometry, tessellation or clipping counters
2400// is active (VUID-vkCmdDrawMeshTasksEXT-pipelineStatistics-07076), though D3D12 allows it and reads those fields as
2401// 0. A query that holds a mesh draw is split as well (D3D-291): a segment's first draw decides whether it runs in
2402// the full pool or in the mesh one (statistics_mesh), and a later draw of the other kind ends it and begins one of
2403// its own kind.
2351// Dispatches and segments without draws use the full pool; ExecuteIndirect draws count as vertex draws. Each draw 2404// Dispatches and segments without draws use the full pool; ExecuteIndirect draws count as vertex draws. Each draw
2352// has its own rendering scope, so a split before one stays outside rendering, as a helper's does. 2405// has its own rendering scope, so a split before one stays outside rendering, as a helper's does.
2353inline void plan_statistics_segments(PreparedList& out) { 2406inline void plan_statistics_segments(PreparedList& out) {
@@ -2785,9 +2838,15 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2785 // A depth plane footprint of a D24 texture stored as D32: words of 24-bit UNORM, floats in the image. 2838 // A depth plane footprint of a D24 texture stored as D32: words of 24-bit UNORM, floats in the image.
2786 const bool upload = texture_copy->src.footprint; 2839 const bool upload = texture_copy->src.footprint;
2787 const ResourceBinding& image = upload ? p.binding : p.source; 2840 const ResourceBinding& image = upload ? p.binding : p.source;
2788 if (result == ReplayResult::success && texture_copy->tile_footprint && !p.buffer_image_copies.empty() && 2841 if (result == ReplayResult::success && texture_copy->tile_footprint && !p.buffer_image_copies.empty()) {
2789 p.buffer_image_copies.front().bufferOffset % 4 && !detail::stage_unaligned_tile(vk, p, upload)) 2842 const auto& region = p.buffer_image_copies.front();
2790 return ReplayResult::unsupported; 2843 const BlockFormat fmt = copy_block_format(image, region.imageSubresource.aspectMask);
2844 const std::uint32_t alignment =
2845 (region.imageSubresource.aspectMask & depth_stencil_aspects) || image.rgb96 ? 4 : fmt.bytes;
2846 if (alignment > 1 && region.bufferOffset % alignment &&
2847 !detail::stage_unaligned_tile(vk, p, image, fmt, upload))
2848 return ReplayResult::unsupported;
2849 }
2791 const bool depth24_footprint = result == ReplayResult::success && image.depth24_as_float && 2850 const bool depth24_footprint = result == ReplayResult::success && image.depth24_as_float &&
2792 !p.buffer_image_copies.empty() && 2851 !p.buffer_image_copies.empty() &&
2793 p.buffer_image_copies[0].imageSubresource.aspectMask == VK_IMAGE_ASPECT_DEPTH_BIT; 2852 p.buffer_image_copies[0].imageSubresource.aspectMask == VK_IMAGE_ASPECT_DEPTH_BIT;
@@ -3191,6 +3250,7 @@ public:
3191 retain(statistics_pool); 3250 retain(statistics_pool);
3192 list.statistics_pool = statistics_pool->pool; 3251 list.statistics_pool = statistics_pool->pool;
3193 list.statistics_mesh_pool = statistics_pool->mesh_pool; 3252 list.statistics_mesh_pool = statistics_pool->mesh_pool;
3253 list.statistics_primitives_pool = statistics_pool->primitives_pool;
3194 list.statistics_base = statistics_base; 3254 list.statistics_base = statistics_base;
3195 } else if (mesh) { 3255 } else if (mesh) {
3196 // Unsplit, the query would be active around a mesh draw with counters Vulkan forbids there. 3256 // Unsplit, the query would be active around a mesh draw with counters Vulkan forbids there.
@@ -3247,7 +3307,8 @@ public:
3247 const bool any_mesh = kinds && std::find(kinds + saved.first, kinds + saved.first + saved.count, 3307 const bool any_mesh = kinds && std::find(kinds + saved.first, kinds + saved.first + saved.count,
3248 std::uint8_t(1)) != kinds + saved.first + saved.count; 3308 std::uint8_t(1)) != kinds + saved.first + saved.count;
3249 run = {saved.segments->pool, saved.first, saved.count, run.offset, 3309 run = {saved.segments->pool, saved.first, saved.count, run.offset,
3250 saved.count > 1 || any_mesh, saved.segments->mesh_pool, kinds}; 3310 saved.count > 1 || any_mesh, saved.segments->mesh_pool,
3311 saved.segments->primitives_pool, kinds};
3251 if (any_mesh && !statistics) return ReplayResult::invalid_query; 3312 if (any_mesh && !statistics) return ReplayResult::invalid_query;
3252 if (!can_sum || (run.sum && !uncounted)) return ReplayResult::unsupported; 3313 if (!can_sum || (run.sum && !uncounted)) return ReplayResult::unsupported;
3253 if (statistics) needs_statistics_sum |= run.sum; 3314 if (statistics) needs_statistics_sum |= run.sum;
@@ -3314,6 +3375,9 @@ inline void end_statistics_segment(const PreparedList& list, std::uint32_t segme
3314 const ReplayFunctions& vk) { 3375 const ReplayFunctions& vk) {
3315 if (segment == PreparedQuery::no_segment) return; 3376 if (segment == PreparedQuery::no_segment) return;
3316 vk.end_query(cb, statistics_segment_pool(list, segment), list.statistics_base + segment); 3377 vk.end_query(cb, statistics_segment_pool(list, segment), list.statistics_base + segment);
3378 // The mesh-primitives count of a mesh segment (D3D-MESH-CLIPPING-COUNTER).
3379 if (list.statistics_primitives_pool && list.statistics_mesh[segment])
3380 vk.end_query(cb, list.statistics_primitives_pool, list.statistics_base + segment);
3317} 3381}
3318 3382
3319inline void begin_statistics_segment(const PreparedList& list, std::uint32_t segment, VkCommandBuffer cb, 3383inline void begin_statistics_segment(const PreparedList& list, std::uint32_t segment, VkCommandBuffer cb,
@@ -3322,6 +3386,12 @@ inline void begin_statistics_segment(const PreparedList& list, std::uint32_t seg
3322 const auto pool = statistics_segment_pool(list, segment); 3386 const auto pool = statistics_segment_pool(list, segment);
3323 vk.reset_query_pool(cb, pool, list.statistics_base + segment, 1); 3387 vk.reset_query_pool(cb, pool, list.statistics_base + segment, 1);
3324 vk.begin_query(cb, pool, list.statistics_base + segment, 0); 3388 vk.begin_query(cb, pool, list.statistics_base + segment, 0);
3389 // The mesh-primitives count of a mesh segment (D3D-MESH-CLIPPING-COUNTER): a query of its own type, which the
3390 // mesh statistics pool cannot hold.
3391 if (list.statistics_primitives_pool && list.statistics_mesh[segment]) {
3392 vk.reset_query_pool(cb, list.statistics_primitives_pool, list.statistics_base + segment, 1);
3393 vk.begin_query(cb, list.statistics_primitives_pool, list.statistics_base + segment, 0);
3394 }
3325} 3395}
3326 3396
3327} // namespace detail 3397} // namespace detail
@@ -3382,7 +3452,8 @@ inline void emit_query(const PreparedList& list, const detail::PreparedQuery& qu
3382 if (!run.pool) { 3452 if (!run.pool) {
3383 vk.fill_buffer(cb, dst, run.offset, VkDeviceSize(run.count) * size, 0); 3453 vk.fill_buffer(cb, dst, run.offset, VkDeviceSize(run.count) * size, 0);
3384 } else if (run.sum && resolve.type == d3d12_query::pipeline_statistics) { 3454 } else if (run.sum && resolve.type == d3d12_query::pipeline_statistics) {
3385 vk.sum_statistics(cb, run.pool, run.mesh_pool, run.mesh, run.first, run.count, dst, run.offset); 3455 vk.sum_statistics(cb, run.pool, run.mesh_pool, run.primitives_pool, run.mesh, run.first, run.count,
3456 dst, run.offset);
3386 } else if (run.sum && binary) { 3457 } else if (run.sum && binary) {
3387 vk.sum_binary_occlusion(cb, run.pool, run.first, run.count, dst, run.offset); 3458 vk.sum_binary_occlusion(cb, run.pool, run.first, run.count, dst, run.offset);
3388 } else if (run.sum || binary) { 3459 } else if (run.sum || binary) {
@@ -3615,10 +3686,13 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3615 const VulkanAccess state = vulkan_access(d3d12_state::depth_write, false); 3686 const VulkanAccess state = vulkan_access(d3d12_state::depth_write, false);
3616 auto pieces = detail::current(tracker, id, range, image_layout(p.binding, state.layout)); 3687 auto pieces = detail::current(tracker, id, range, image_layout(p.binding, state.layout));
3617 detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, state.layout), tracker); 3688 detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, state.layout), tracker);
3618 const float depth = p.binding.depth24 ? depth24_clear_value(depth_clear->depth) // see depth24.h 3689 float depth = p.binding.depth24 ? depth24_clear_value(depth_clear->depth) // see depth24.h
3619 : p.binding.format == VK_FORMAT_D16_UNORM 3690 : p.binding.format == VK_FORMAT_D16_UNORM
3620 ? detail::quantize_unorm(depth_clear->depth, 65535.0) // see quantize_unorm 3691 ? detail::quantize_unorm(depth_clear->depth, 65535.0) // see quantize_unorm
3621 : depth_clear->depth; 3692 : depth_clear->depth;
3693 // Without the extension both clear commands require a depth in [0, 1], including for float images.
3694 if (!vk.depth_range_unrestricted)
3695 depth = std::isnan(depth) ? 0.0f : std::clamp(depth, 0.0f, 1.0f);
3622 const VkClearDepthStencilValue value{depth, depth_clear->stencil}; 3696 const VkClearDepthStencilValue value{depth, depth_clear->stencil};
3623 if (p.rects.empty()) { 3697 if (p.rects.empty()) {
3624 detail::round_trip(vk, command_buffer, p.binding, pieces, image_layout(p.binding, transfer_dst.layout), 3698 detail::round_trip(vk, command_buffer, p.binding, pieces, image_layout(p.binding, transfer_dst.layout),
diff --git a/runtime/src/vulkan_scratch.h b/runtime/src/vulkan_scratch.h
index 4a8a59ddd..33d84bf72 100644
--- a/runtime/src/vulkan_scratch.h
+++ b/runtime/src/vulkan_scratch.h
@@ -46,12 +46,16 @@ public:
46 constexpr VkDeviceSize alignment = 256, minimum = 4u << 20; 46 constexpr VkDeviceSize alignment = 256, minimum = 4u << 20;
47 if (!loaded_ || !bytes) return false; 47 if (!loaded_ || !bytes) return false;
48 for (auto& chunk : current_.chunks) { 48 for (auto& chunk : current_.chunks) {
49 const VkDeviceSize start = (chunk.used + alignment - 1) / alignment * alignment; 49 const VkDeviceSize rem = chunk.used % alignment;
50 if (start <= chunk.size && bytes <= chunk.size - start) { 50 const VkDeviceSize pad = rem ? alignment - rem : 0;
51 chunk.used = start + bytes; 51 if (pad <= chunk.size - chunk.used) {
52 buffer = chunk.buffer; 52 const VkDeviceSize start = chunk.used + pad;
53 offset = start; 53 if (bytes <= chunk.size - start) {
54 return true; 54 chunk.used = start + bytes;
55 buffer = chunk.buffer;
56 offset = start;
57 return true;
58 }
55 } 59 }
56 } 60 }
57 Chunk chunk; 61 Chunk chunk;
diff --git a/runtime/src/xdxr_build.h b/runtime/src/xdxr_build.h
index e0851098f..e1c1a233e 100644
--- a/runtime/src/xdxr_build.h
+++ b/runtime/src/xdxr_build.h
@@ -133,7 +133,13 @@ public:
133 // update ignores `pair`. 133 // update ignores `pair`.
134 bool record_blas(VkCommandBuffer cb, const XdxrLayout& layout, const std::vector<XdxrTriangles>& geometries, 134 bool record_blas(VkCommandBuffer cb, const XdxrLayout& layout, const std::vector<XdxrTriangles>& geometries,
135 std::uint64_t dst, std::uint64_t scratch, std::uint64_t update_from = 0, bool pair = false) { 135 std::uint64_t dst, std::uint64_t scratch, std::uint64_t update_from = 0, bool pair = false) {
136 if (!loaded_ || layout.tlas) return false; 136 if (!loaded_ || layout.tlas || !layout.size || !dst || !scratch) return false;
137 std::uint64_t total = 0;
138 for (const auto& geo : geometries) {
139 total += geo.triangle_count;
140 if (total > layout.elements) return false;
141 }
142 if (total != layout.elements) return false;
137 Push p = base(layout, dst, scratch); 143 Push p = base(layout, dst, scratch);
138 if (pair && !update_from) p.flags |= flag_pair; 144 if (pair && !update_from) p.flags |= flag_pair;
139 if (update_from) refit_begin(cb, layout, p, update_from); else begin(cb, layout, p); 145 if (update_from) refit_begin(cb, layout, p, update_from); else begin(cb, layout, p);
@@ -155,7 +161,6 @@ public:
155 dispatch(cb, t, t.count); 161 dispatch(cb, t, t.count);
156 first += geo.triangle_count; 162 first += geo.triangle_count;
157 } 163 }
158 if (first != layout.elements) return false;
159 if (update_from) refit_finish(cb, layout, p); else finish(cb, layout, p); 164 if (update_from) refit_finish(cb, layout, p); else finish(cb, layout, p);
160 return true; 165 return true;
161 } 166 }
@@ -164,7 +169,8 @@ public:
164 // `update_from`: as for record_blas; the instances may move, and name other BLASes. 169 // `update_from`: as for record_blas; the instances may move, and name other BLASes.
165 bool record_tlas(VkCommandBuffer cb, const XdxrLayout& layout, std::uint64_t instances, std::uint64_t dst, 170 bool record_tlas(VkCommandBuffer cb, const XdxrLayout& layout, std::uint64_t instances, std::uint64_t dst,
166 std::uint64_t scratch, std::uint64_t bias = 0, std::uint64_t update_from = 0) { 171 std::uint64_t scratch, std::uint64_t bias = 0, std::uint64_t update_from = 0) {
167 if (!loaded_ || !layout.tlas) return false; 172 if (!loaded_ || !layout.tlas || !layout.size || !dst || !scratch || (layout.elements && !instances))
173 return false;
168 Push p = base(layout, dst, scratch); 174 Push p = base(layout, dst, scratch);
169 p.bias = split(bias); 175 p.bias = split(bias);
170 if (update_from) refit_begin(cb, layout, p, update_from); else begin(cb, layout, p); 176 if (update_from) refit_begin(cb, layout, p, update_from); else begin(cb, layout, p);
@@ -341,7 +347,7 @@ private:
341 // dependency on its results to the caller's barrier (the application's UAV or AS barrier). 347 // dependency on its results to the caller's barrier (the application's UAV or AS barrier).
342 void dispatch(VkCommandBuffer cb, const Push& p, std::uint32_t threads, bool barrier = true) { 348 void dispatch(VkCommandBuffer cb, const Push& p, std::uint32_t threads, bool barrier = true) {
343 vk_.vkCmdPushConstants(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(Push), &p); 349 vk_.vkCmdPushConstants(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(Push), &p);
344 vk_.vkCmdDispatch(cb, (threads + 63) / 64, 1, 1); 350 vk_.vkCmdDispatch(cb, std::uint32_t((std::uint64_t(threads) + 63u) / 64u), 1, 1);
345 if (!barrier) return; 351 if (!barrier) return;
346 VkMemoryBarrier b{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; 352 VkMemoryBarrier b{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
347 b.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; 353 b.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
diff --git a/runtime/src/xdxr_descs.h b/runtime/src/xdxr_descs.h
index b44ce0372..3798b0fe7 100644
--- a/runtime/src/xdxr_descs.h
+++ b/runtime/src/xdxr_descs.h
@@ -99,12 +99,11 @@ constexpr uint32_t kPostbuildInfoOfflineStatistics = 0x10;
99// The record a setting is read from, the way the DLL finds it: the first record of `type` from the start, stepping 99// The record a setting is read from, the way the DLL finds it: the first record of `type` from the start, stepping
100// over types 0, 1 and 2, and stopping at any other type. Null when there is none. 100// over types 0, 1 and 2, and stopping at any other type. Null when there is none.
101inline const StreamRecord* find_stream_record(const StreamDesc& desc, uint32_t type) { 101inline const StreamRecord* find_stream_record(const StreamDesc& desc, uint32_t type) {
102 if (desc.size_in_bytes == 0 || desc.stream == nullptr) 102 if (desc.size_in_bytes < sizeof(StreamRecord) || desc.stream == nullptr)
103 return nullptr; 103 return nullptr;
104 const auto* record = static_cast<const StreamRecord*>(desc.stream); 104 const auto* record = static_cast<const StreamRecord*>(desc.stream);
105 const auto* end = reinterpret_cast<const StreamRecord*>(static_cast<const uint8_t*>(desc.stream) + 105 const uint64_t count = desc.size_in_bytes / sizeof(StreamRecord);
106 desc.size_in_bytes); 106 for (uint64_t i = 0; i < count; ++i, ++record) {
107 for (; record < end; ++record) {
108 if (record->type == type) 107 if (record->type == type)
109 return record; 108 return record;
110 if (record->type > 2) 109 if (record->type > 2)
diff --git a/runtime/test/acphal_test.cpp b/runtime/test/acphal_test.cpp
index bd93f7040..be2c6f1e1 100644
--- a/runtime/test/acphal_test.cpp
+++ b/runtime/test/acphal_test.cpp
@@ -6,13 +6,44 @@
6 6
7#include <windows.h> 7#include <windows.h>
8 8
9#include <algorithm>
10#include <atomic>
9#include <cstddef> 11#include <cstddef>
10#include <cstdint> 12#include <cstdint>
11#include <cstdio> 13#include <cstdio>
14#include <cstdlib>
12#include <cstring> 15#include <cstring>
16#include <new>
17#include <thread>
18#include <vector>
13 19
14#include "shims.h" 20#include "shims.h"
15 21
22// Fail only the calling test thread's designated allocation.
23static thread_local int allocations_before_failure = -1;
24static std::atomic<bool> fail_worker_allocation{false};
25static std::atomic<bool> count_worker_allocations{false};
26static std::atomic<unsigned> worker_allocations{0};
27static DWORD test_thread_id;
28void* operator new(std::size_t size) {
29 if (allocations_before_failure == 0) {
30 allocations_before_failure = -1;
31 throw std::bad_alloc();
32 }
33 if (fail_worker_allocation.load() && GetCurrentThreadId() != test_thread_id &&
34 fail_worker_allocation.exchange(false)) {
35 throw std::bad_alloc();
36 }
37 if (count_worker_allocations.load() && GetCurrentThreadId() != test_thread_id) {
38 worker_allocations.fetch_add(1, std::memory_order_relaxed);
39 }
40 if (allocations_before_failure > 0) --allocations_before_failure;
41 if (void* memory = std::malloc(size ? size : 1)) return memory;
42 throw std::bad_alloc();
43}
44void operator delete(void* memory) noexcept { std::free(memory); }
45void operator delete(void* memory, std::size_t) noexcept { std::free(memory); }
46
16namespace { 47namespace {
17 48
18using AcpHalCreateFn = HRESULT(__stdcall*)(void**); 49using AcpHalCreateFn = HRESULT(__stdcall*)(void**);
@@ -66,9 +97,62 @@ static_assert(sizeof(TestShapeContexts) == 120, "TestShapeContexts is 120 bytes"
66static_assert(offsetof(TestShapeContexts, xmaContextArray) == 0x38, 97static_assert(offsetof(TestShapeContexts, xmaContextArray) == 0x38,
67 "xmaContextArray is at offset +0x38"); 98 "xmaContextArray is at offset +0x38");
68 99
100struct XmaWords {
101 uint32_t* data;
102
103 std::atomic_ref<uint32_t> operator[](std::size_t index) const {
104 return std::atomic_ref(data[index]);
105 }
106};
107
108// Synthetic XMA2 with one nonzero spectral coefficient per channel and frame.
109void write_xma_packet(uint8_t* packet, uint32_t frames, uint8_t packet_skip,
110 uint32_t rate_index = 3, bool stereo = false) {
111 constexpr uint32_t scale_bands[] = {23, 24, 23, 23};
112 const uint32_t bands = scale_bands[rate_index];
113 const uint32_t channels = stereo ? 2u : 1u;
114 const uint32_t frame_bits = stereo ? 90 + 2 * bands : 59 + bands;
115 std::memset(packet, 0xFF, 2048);
116 std::size_t at = 0;
117 auto put = [&](uint32_t value, std::size_t width) {
118 for (std::size_t i = 0; i < width; ++i, ++at) {
119 const auto mask = static_cast<uint8_t>(0x80u >> (at % 8));
120 packet[at / 8] &= static_cast<uint8_t>(~mask);
121 if ((value >> (width - 1 - i)) & 1u) packet[at / 8] |= mask;
122 }
123 };
124 put((frames << 26) | (1u << 8) | packet_skip, 32);
125 for (uint32_t frame = 0; frame < frames; ++frame) {
126 put(frame_bits, 15);
127 put(0b10u, 2); // Fixed layout, one 512-sample subframe.
128 if (stereo) put(0, 1); // No optional decorrelation matrix.
129 put(0, 11); // Gain, trim, fill and subframe error flag.
130 if (stereo) put(0b010u, 3); // Two channels without decorrelation.
131 put((1u << channels) - 1, channels); // Coefficients are present in each channel.
132 put(1, 1); // Explicit vector coefficient count.
133 put(0, 8 * channels); // Use only run/level coding.
134 put(0, 6); // Quantizer adjustment.
135 if (stereo) put(0, 5); // No per-channel quantizer modifiers.
136 for (uint32_t channel = 0; channel < channels; ++channel) {
137 put(0, 2); // Scale factor step.
138 put((1u << bands) - 1, bands); // One zero delta per scale band.
139 }
140 for (uint32_t channel = 0; channel < channels; ++channel) {
141 put(0, 1); // Run/level table 0.
142 put(0b00u, 2); // Run 0, level 1.
143 put(channel == 0 ? 1u : 0u, 1);
144 put(0b0101011u, 7); // End of coefficients.
145 }
146 put(0, 1); // Frame padding bit.
147 put(frame + 1 < frames ? 1 : 0, 1);
148 }
149}
150
69} // namespace 151} // namespace
70 152
71int main() { 153int main(int argc, char** argv) {
154 std::setvbuf(stdout, nullptr, _IONBF, 0);
155 test_thread_id = GetCurrentThreadId();
72 std::printf("acphal_test: registered acphal.dll shim verification\n"); 156 std::printf("acphal_test: registered acphal.dll shim verification\n");
73 157
74 const auto create = reinterpret_cast<AcpHalCreateFn>( 158 const auto create = reinterpret_cast<AcpHalCreateFn>(
@@ -107,18 +191,44 @@ int main() {
107 return 1; 191 return 1;
108 } 192 }
109 193
194 // Heap configuration is process-wide, so CTest exercises this mode separately.
195 if (argc == 2 && std::strcmp(argv[1], "--noncached-only") == 0) {
196 check(create_heap(0, 0x6000u) == S_OK, "Create only the non-cached APU heap");
197 void* noncached = nullptr;
198 uint32_t noncached_address = 0;
199 check(alloc(&noncached, &noncached_address, 0x1000, 0x800, 2) == S_OK && noncached != nullptr,
200 "Allocate from the non-cached heap");
201 void* cached = noncached;
202 uint32_t cached_address = noncached_address;
203 check(alloc(&cached, &cached_address, 0x1000, 0x800, 1) == E_OUTOFMEMORY &&
204 cached == nullptr && cached_address == 0,
205 "A missing cached heap stays unavailable after explicit configuration");
206 check(map_apu(noncached_address) == noncached && map_virtual(noncached) == noncached_address,
207 "A failed cached allocation leaves the non-cached mapping unchanged");
208 free_mem(noncached);
209 std::printf("acphal_test complete: %d checks, %d failures\n", g_checks, g_failures);
210 return g_failures != 0;
211 }
212
110 // 1. AcpHalCreate 213 // 1. AcpHalCreate
111 void* acp = nullptr; 214 void* acp = nullptr;
112 check(create(&acp) == S_OK && acp != nullptr, 215 check(create(&acp) == S_OK && acp != nullptr,
113 "AcpHalCreate returns S_OK with a non-null object"); 216 "AcpHalCreate returns S_OK with a non-null object");
114 check(create(nullptr) == E_POINTER, 217 check(create(nullptr) == E_POINTER,
115 "AcpHalCreate(nullptr) returns E_POINTER"); 218 "AcpHalCreate(nullptr) returns E_POINTER");
219 void* failed_hal = acp;
220 allocations_before_failure = 0;
221 const HRESULT create_failure = create(&failed_hal);
222 allocations_before_failure = -1;
223 check(create_failure == E_OUTOFMEMORY && failed_hal == nullptr,
224 "AcpHalCreate returns E_OUTOFMEMORY and clears the output");
116 225
117 if (acp) { 226 if (acp) {
118 using Slot0Fn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t); 227 using Slot0Fn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t);
119 using Slot1Fn = HRESULT(__stdcall*)(void*); 228 using Slot1Fn = HRESULT(__stdcall*)(void*);
120 using Slot2Fn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t, uint32_t, const void*, uint32_t); 229 using Slot2Fn = HRESULT(__stdcall*)(void*, uint32_t, uint64_t, uint32_t, const void*, uint32_t);
121 using Slot3Fn = uint32_t(__stdcall*)(void*); 230 using Slot3Fn = uint32_t(__stdcall*)(void*, void*);
231 using Slot4Fn = uint32_t(__stdcall*)(void*);
122 using Slot5Fn = HRESULT(__stdcall*)(void*); 232 using Slot5Fn = HRESULT(__stdcall*)(void*);
123 233
124 auto vtable = *static_cast<void* const* const*>(acp); 234 auto vtable = *static_cast<void* const* const*>(acp);
@@ -139,8 +249,8 @@ int main() {
139 "IAcpHal slot 2 (submit_command) returns S_OK (vital boot unblocker)"); 249 "IAcpHal slot 2 (submit_command) returns S_OK (vital boot unblocker)");
140 250
141 // Slots 3 and 4: Message polling returns 0 251 // Slots 3 and 4: Message polling returns 0
142 check(reinterpret_cast<Slot3Fn>(vtable[3])(acp) == 0, "IAcpHal slot 3 returns 0"); 252 check(reinterpret_cast<Slot3Fn>(vtable[3])(acp, nullptr) == 0, "IAcpHal slot 3 returns 0");
143 check(reinterpret_cast<Slot3Fn>(vtable[4])(acp) == 0, "IAcpHal slot 4 returns 0"); 253 check(reinterpret_cast<Slot4Fn>(vtable[4])(acp) == 0, "IAcpHal slot 4 returns 0");
144 254
145 // Slot 1: Disconnect returns S_OK 255 // Slot 1: Disconnect returns S_OK
146 check(reinterpret_cast<Slot1Fn>(vtable[1])(acp) == S_OK, "IAcpHal slot 1 returns S_OK"); 256 check(reinterpret_cast<Slot1Fn>(vtable[1])(acp) == S_OK, "IAcpHal slot 1 returns S_OK");
@@ -150,8 +260,8 @@ int main() {
150 } 260 }
151 261
152 // 2. ApuCreateHeap: title passes (cachedSize, nonCachedSize=0x226e00) 262 // 2. ApuCreateHeap: title passes (cachedSize, nonCachedSize=0x226e00)
153 check(create_heap(4 * 1024 * 1024, 0x226e00) == S_OK, 263 check(create_heap(4 * 1024 * 1024 + 0x400, 0x226e00) == S_OK,
154 "ApuCreateHeap(4 MiB, 0x226e00) succeeds"); 264 "ApuCreateHeap succeeds with an unaligned cached heap size");
155 check(create_heap(4 * 1024 * 1024, 0x226e00) != S_OK, 265 check(create_heap(4 * 1024 * 1024, 0x226e00) != S_OK,
156 "ApuCreateHeap second call fails (heap already created)"); 266 "ApuCreateHeap second call fails (heap already created)");
157 267
@@ -252,11 +362,513 @@ int main() {
252 check(ctx_all.xmaContextArray != nullptr, "xmaContextArray is allocated"); 362 check(ctx_all.xmaContextArray != nullptr, "xmaContextArray is allocated");
253 check(ctx_all.pcmContextArray != nullptr, "pcmContextArray is allocated"); 363 check(ctx_all.pcmContextArray != nullptr, "pcmContextArray is allocated");
254 364
365 TestShapeContexts retry_ctx{};
366 retry_ctx.numXmaContexts = 2;
367 allocations_before_failure = 1; // The tracked allocation can grow, then voice slot allocation fails.
368 HRESULT allocation_result = E_UNEXPECTED;
369 try {
370 allocation_result = alloc_ctx(&retry_ctx);
371 } catch (const std::bad_alloc&) {
372 // An exception across the AcpHal boundary is a regression.
373 }
374 allocations_before_failure = -1;
375 check(allocation_result == E_OUTOFMEMORY && retry_ctx.xmaContextArray == nullptr,
376 "A failed XMA slot allocation returns E_OUTOFMEMORY without publishing a context");
377 check(alloc_ctx(&retry_ctx) == S_OK && retry_ctx.xmaContextArray != nullptr,
378 "SHAPE allocation can be retried after memory pressure");
379
255 // Release shape contexts 380 // Release shape contexts
381 std::memset(&ctx_all, 0x55, sizeof(ctx_all));
256 check(release_ctx(&ctx_all) == S_OK, "AcpHalReleaseShapeContexts succeeds"); 382 check(release_ctx(&ctx_all) == S_OK, "AcpHalReleaseShapeContexts succeeds");
257 check(ctx_all.xmaContextArray == nullptr, "xmaContextArray is reset to null"); 383 const auto* released_argument = reinterpret_cast<const uint8_t*>(&ctx_all);
384 check(std::all_of(released_argument, released_argument + sizeof(ctx_all),
385 [](uint8_t b) { return b == 0x55; }),
386 "SHAPE release does not write through an opaque or recycled argument");
258 check(release_ctx(nullptr) == S_OK, "AcpHalReleaseShapeContexts(nullptr) succeeds"); 387 check(release_ctx(nullptr) == S_OK, "AcpHalReleaseShapeContexts(nullptr) succeeds");
259 388
389 // 7. ACP command/message queue protocol (register, complete, overflow drops, disconnect, notify word)
390 {
391 #pragma pack(push, 1)
392 struct TestAcpMessage {
393 uint32_t kind;
394 uint32_t dropped;
395 uint32_t usec;
396 uint8_t data[16];
397 };
398 #pragma pack(pop)
399 static_assert(sizeof(TestAcpMessage) == 28, "ACP message is 28 bytes");
400
401 using ConnectFn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t);
402 using DisconnectFn = HRESULT(__stdcall*)(void*);
403 using SubmitFn = HRESULT(__stdcall*)(void*, uint32_t, uint64_t, uint32_t, const void*, uint32_t);
404 using PopFn = uint32_t(__stdcall*)(void*, TestAcpMessage*);
405 using CountFn = uint32_t(__stdcall*)(void*);
406 using ReleaseFn = HRESULT(__stdcall*)(void*);
407
408 void* q_acp = nullptr;
409 check(create(&q_acp) == S_OK && q_acp != nullptr, "AcpHalCreate for queue test");
410 auto vt = *static_cast<void* const* const*>(q_acp);
411 const auto fn_connect = reinterpret_cast<ConnectFn>(vt[0]);
412 const auto fn_disconnect = reinterpret_cast<DisconnectFn>(vt[1]);
413 const auto fn_submit = reinterpret_cast<SubmitFn>(vt[2]);
414 const auto fn_pop = reinterpret_cast<PopFn>(vt[3]);
415 const auto fn_count = reinterpret_cast<CountFn>(vt[4]);
416 const auto fn_release = reinterpret_cast<ReleaseFn>(vt[5]);
417
418 check(fn_connect(q_acp, 0, 16) == E_INVALIDARG, "Connect(commands=0) returns E_INVALIDARG");
419 check(fn_disconnect(q_acp) == E_FAIL, "Disconnect before Connect returns E_FAIL");
420 check(fn_connect(q_acp, 16, 2) == S_OK, "Connect(16, 2) succeeds");
421
422 // Allocate a 4-byte notification word in APU memory.
423 void* notify_va = nullptr;
424 uint32_t notify_apu = 0;
425 check(alloc(&notify_va, &notify_apu, 16, 16, 1) == S_OK && notify_va != nullptr,
426 "ApuAlloc notification word succeeds");
427 *static_cast<uint32_t*>(notify_va) = 0;
428
429 const uint32_t reg_mask = 0x92u; // FLOWGRAPH_COMPLETED(0x02) | COMMAND_COMPLETED(0x10) | DISCONNECTED(0x80)
430 check(fn_submit(q_acp, 2, 0x1122334455667788ull, 0xffffffffu, &reg_mask, notify_apu) == S_OK,
431 "REGISTER_MESSAGES with id and notify word succeeds");
432 check(*static_cast<volatile uint32_t*>(notify_va) == 1u,
433 "SubmitCommand writes 1 to APU notification word");
434 check(fn_count(q_acp) == 1u, "COMMAND_COMPLETED queued after REGISTER_MESSAGES");
435
436 TestAcpMessage msg{};
437 check(fn_pop(q_acp, &msg) == 1u, "PopMessage retrieves COMMAND_COMPLETED");
438 uint32_t ack_cmd = 0;
439 uint64_t ack_id = 0;
440 std::memcpy(&ack_cmd, msg.data, 4);
441 std::memcpy(&ack_id, msg.data + 4, 8);
442 check(msg.kind == 0x10u && msg.dropped == 0u && ack_cmd == 2u && ack_id == 0x1122334455667788ull,
443 "COMMAND_COMPLETED payload carries command id and 64-bit token");
444
445 // Overflow queue of capacity 2 with 4 commands -> 2 dropped, reported on the 5th.
446 for (uint64_t tok = 1; tok <= 4; ++tok) {
447 check(fn_submit(q_acp, 12, tok, 0xffffffffu, nullptr, 0) == S_OK,
448 "SubmitCommand during overflow succeeds");
449 }
450 check(fn_count(q_acp) == 2u, "Message queue caps at capacity 2");
451 check(fn_pop(q_acp, &msg) == 1u && fn_pop(q_acp, &msg) == 1u,
452 "Drained the 2 queued messages");
453 check(fn_submit(q_acp, 12, 5, 0xffffffffu, nullptr, 0) == S_OK,
454 "SubmitCommand 5 after drain succeeds");
455 check(fn_pop(q_acp, &msg) == 1u && msg.dropped == 2u,
456 "Next queued message reports dropped == 2");
457
458 // LOAD_FLOWGRAPH posts FLOWGRAPH_COMPLETED carrying word(1).
459 const uint32_t fg_cfg[2] = {0, 0x42u};
460 check(fn_submit(q_acp, 1, 0, 0xffffffffu, fg_cfg, 0) == S_OK, "LOAD_FLOWGRAPH succeeds");
461 check(fn_pop(q_acp, &msg) == 1u && msg.kind == 0x02u, "FLOWGRAPH_COMPLETED queued");
462 uint32_t fg_id = 0;
463 std::memcpy(&fg_id, msg.data, 4);
464 check(fg_id == 0x42u, "FLOWGRAPH_COMPLETED carries flowgraph word");
465
466 const uint32_t command_completed_mask = 0x10u;
467 check(fn_submit(q_acp, 3, 0x100u, 0xffffffffu, &command_completed_mask, 0) == S_OK &&
468 fn_count(q_acp) == 0u,
469 "UNREGISTER_MESSAGES suppresses command-completed messages");
470
471 // Disconnect posts DISCONNECTED.
472 check(fn_disconnect(q_acp) == S_OK, "Disconnect succeeds when connected");
473 check(fn_count(q_acp) == 1u, "Disconnect queued DISCONNECTED message");
474 check(fn_pop(q_acp, &msg) == 1u && msg.kind == 0x80u, "Popped DISCONNECTED message");
475
476 free_mem(notify_va);
477 check(fn_release(q_acp) == S_OK, "Release queue AcpHal succeeds");
478 }
479
480 // 8. End-to-end XMA2 context ring decoding via background decoder thread
481 {
482 // Two synthetic XMA2 packets with three mono frames each. Each frame
483 // transmits one positive spectral coefficient so decoded PCM differs from fallback silence.
484 TestShapeContexts xma_ctx{};
485 xma_ctx.numXmaContexts = 4;
486 check(alloc_ctx(&xma_ctx) == S_OK && xma_ctx.xmaContextArray != nullptr,
487 "Allocate 4 XMA SHAPE contexts");
488
489 void* in_va = nullptr;
490 uint32_t in_apu = 0;
491 check(alloc(&in_va, &in_apu, 0x1000, 0x800, 1) == S_OK && in_va != nullptr,
492 "ApuAlloc 2-packet XMA2 input buffer");
493 auto* packets = static_cast<uint8_t*>(in_va);
494 write_xma_packet(packets, 3, 0);
495 write_xma_packet(packets + 2048, 3, 0);
496
497 void* out_va = nullptr;
498 uint32_t out_apu = 0;
499 check(alloc(&out_va, &out_apu, 0x400, 0x100, 2) == S_OK && out_va != nullptr,
500 "ApuAlloc 4-block XMA2 output ring");
501 std::memset(out_va, 0x55, 0x400);
502
503 // Configure voice index 1: 2 packets in input 0, input 0 valid, 4 output blocks,
504 // writable = 1, 48 kHz mono, read_bit = 32.
505 const XmaWords words{static_cast<uint32_t*>(xma_ctx.xmaContextArray) + 16};
506 words[0] = 2u | (1u << 20) | (4u << 22);
507 words[1] = (1u << 31) | (3u << 27);
508 words[2] = 32u;
509 words[5] = in_apu;
510 words[7] = out_apu;
511
512 using ConnectFn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t);
513 using SubmitFn = HRESULT(__stdcall*)(void*, uint32_t, uint64_t, uint32_t, const void*, uint32_t);
514 using ReleaseFn = HRESULT(__stdcall*)(void*);
515
516 void* x_acp = nullptr;
517 check(create(&x_acp) == S_OK && x_acp != nullptr, "AcpHalCreate for XMA decode test");
518 auto vt = *static_cast<void* const* const*>(x_acp);
519 const auto fn_connect = reinterpret_cast<ConnectFn>(vt[0]);
520 const auto fn_submit = reinterpret_cast<SubmitFn>(vt[2]);
521 const auto fn_release = reinterpret_cast<ReleaseFn>(vt[5]);
522
523 check(fn_connect(x_acp, 0x1000, 0x1000) == S_OK, "Connect for XMA decode test");
524
525 // ENABLE_XMA (cmd 5) on voice 1.
526 const uint32_t enable_arg = 1u;
527 worker_allocations.store(0);
528 count_worker_allocations.store(true);
529 check(fn_submit(x_acp, 5, 0xf1, 0xffffffffu, &enable_arg, 0) == S_OK,
530 "ENABLE_XMA voice 1 succeeds");
531
532 // Wait up to 500 ms for the background decoder thread to fill the 4-block ring.
533 for (int wait = 0; wait < 500 && ((words[1] >> 31) & 1u) == 1u; ++wait) {
534 Sleep(1);
535 }
536 const bool ring_full = (words[1] >> 31) == 0u;
537 check(ring_full, "Background XMA2 decoder fills ring and clears writable flag");
538 check(((words[0] >> 27) & 0x1Fu) == 0u,
539 "Write block wrapped back to 0 after filling 4 blocks");
540
541 const auto* ring_bytes = static_cast<const uint8_t*>(out_va);
542#if defined(LEONIDA_HAVE_XMA2_DECODER)
543 check(ring_full && std::any_of(ring_bytes, ring_bytes + 0x400,
544 [](uint8_t b) { return b != 0 && b != 0x55; }),
545 "The Rust decoder writes non-silent PCM");
546#else
547 check(ring_full && std::all_of(ring_bytes, ring_bytes + 0x400, [](uint8_t b) { return b == 0; }),
548 "The fallback writes silence");
549#endif
550
551 // Advance read pointer 4 blocks at a time until input exhausts and INPUT_INVALID fires.
552 const uint32_t advance_args[2] = {1u, 4u};
553 int written_blocks = ring_full ? 4 : 0;
554 bool advanced = true;
555 for (int step = 0; step < 6; ++step) {
556 advanced &= fn_submit(x_acp, 18, 0xf2 + static_cast<uint64_t>(step),
557 0xffffffffu, advance_args, 0) == S_OK;
558 // Wait until either ring fills again (writable == 0) or stream hits error bit.
559 for (int wait = 0; wait < 200; ++wait) {
560 const uint32_t w1 = words[1];
561 const uint32_t w2 = words[2];
562 if (((w1 >> 31) & 1u) == 0u || ((w2 >> 31) & 1u) == 1u) break;
563 Sleep(1);
564 }
565 if (((words[2] >> 31) & 1u) == 1u && ((words[1] >> 31) & 1u) == 1u) {
566 break;
567 }
568 if ((words[1] >> 31) != 0u) break;
569 written_blocks += 4;
570 }
571 check(advanced, "ADVANCE_XMA_READ succeeds");
572 check(written_blocks == 24, "Six frames write exactly 24 blocks before input exhaustion");
573 count_worker_allocations.store(false);
574 const unsigned allocation_count = worker_allocations.load();
575 std::printf("C++ worker allocations for six PCM frames: %u\n", allocation_count);
576 check(allocation_count > 0 && allocation_count < 16,
577 "PCM storage is reused across packets instead of allocating per sample block");
578 check(((words[0] >> 20) & 3u) == 0u, "XMA input buffer valid bits cleared on exhaustion");
579 check(((words[2] >> 31) & 1u) == 1u, "XMA error flag set on exhaustion");
580 check(((words[2] >> 26) & 0x1Fu) == 4u, "XMA error status is INPUT_INVALID (4)");
581
582 // DISABLE_XMA (cmd 7) on voice 1.
583 const uint32_t disable_arg = 1u;
584 check(fn_submit(x_acp, 7, 0xf9, 0xffffffffu, &disable_arg, 0) == S_OK,
585 "DISABLE_XMA voice 1 succeeds");
586 check(fn_release(x_acp) == S_OK, "Release XMA AcpHal succeeds");
587 free_mem(in_va);
588 free_mem(out_va);
589 check(release_ctx(&xma_ctx) == S_OK, "Release XMA SHAPE contexts joins decoder cleanly");
590 }
591
592 // 8b. Loops are rounded to whole packets: the loop end packet plays in full and the read
593 // restarts at the packet holding the loop start. One 1-frame packet = 512 samples = 4 blocks.
594 {
595 TestShapeContexts xma_ctx{};
596 xma_ctx.numXmaContexts = 4;
597 check(alloc_ctx(&xma_ctx) == S_OK && xma_ctx.xmaContextArray != nullptr,
598 "Allocate 4 XMA SHAPE contexts for the packet loop test");
599
600 void* in_va = nullptr;
601 uint32_t in_apu = 0;
602 check(alloc(&in_va, &in_apu, 0x2000, 0x800, 2) == S_OK && in_va != nullptr &&
603 (in_apu & 0x7FFu) == 0 && map_apu(in_apu) == in_va,
604 "Non-cached XMA input keeps its requested alignment and round trips");
605 auto* packets = static_cast<uint8_t*>(in_va);
606 write_xma_packet(packets, 1, 1); // Packet 1 belongs to another stream.
607 write_xma_packet(packets + 0x800, 2, 0);
608 write_xma_packet(packets + 0x1000, 1, 0);
609
610 void* out_va = nullptr;
611 uint32_t out_apu = 0;
612 check(alloc(&out_va, &out_apu, 0x1000, 0x100, 2) == S_OK && out_va != nullptr,
613 "ApuAlloc 16-block loop output ring");
614
615 // Voice index 2.
616 const XmaWords words{static_cast<uint32_t*>(xma_ctx.xmaContextArray) + 32};
617
618 using ConnectFn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t);
619 using SubmitFn = HRESULT(__stdcall*)(void*, uint32_t, uint64_t, uint32_t, const void*, uint32_t);
620 using ReleaseFn = HRESULT(__stdcall*)(void*);
621
622 void* x_acp = nullptr;
623 check(create(&x_acp) == S_OK && x_acp != nullptr, "AcpHalCreate for packet loop test");
624 auto vt = *static_cast<void* const* const*>(x_acp);
625 const auto fn_connect = reinterpret_cast<ConnectFn>(vt[0]);
626 const auto fn_submit = reinterpret_cast<SubmitFn>(vt[2]);
627 const auto fn_release = reinterpret_cast<ReleaseFn>(vt[5]);
628 check(fn_connect(x_acp, 0x1000, 0x1000) == S_OK, "Connect for packet loop test");
629
630 auto configure_voice = [&](uint32_t loops, uint32_t input_0_packets, uint32_t ring_size,
631 uint32_t write, uint32_t read) {
632 std::memset(out_va, 0x55, 0x1000);
633 const uint32_t input_1_packets = 3u - input_0_packets;
634 words[0] = input_0_packets | (loops << 12) |
635 ((input_1_packets != 0 ? 3u : 1u) << 20) | (ring_size << 22) | (write << 27);
636 words[1] = (1u << 31) | (3u << 27) | input_1_packets;
637 words[2] = 32u; // read at packet 0
638 words[3] = 32u; // loop start: packet 0
639 words[4] = 100u; // loop end: packet 0
640 words[5] = in_apu;
641 words[6] = in_apu + input_0_packets * 2048u;
642 words[7] = out_apu;
643 words[9] = read;
644 };
645
646 const uint32_t voice_index = 2u;
647 // Returns the number of blocks written before input exhaustion, or -1 on timeout.
648 auto run_blocks = [&](uint32_t loops, uint32_t input_0_packets = 3,
649 uint32_t initial_skip = 0, uint32_t loop_skip = 0) -> int {
650 configure_voice(loops, input_0_packets, 16, 0, 0);
651 words[1].fetch_or((initial_skip << 24) | (loop_skip << 17));
652 check(fn_submit(x_acp, 5, 0xf3, 0xffffffffu, &voice_index, 0) == S_OK,
653 "ENABLE_XMA voice 2 succeeds");
654 int wait = 0;
655 for (; wait < 1000 && ((words[2] >> 31) & 1u) == 0u; ++wait) {
656 Sleep(1);
657 }
658 const int blocks = ((words[2] >> 31) & 1u) != 0u
659 ? static_cast<int>((words[0] >> 27) & 0x1Fu)
660 : -1;
661 check(fn_submit(x_acp, 7, 0xf4, 0xffffffffu, &voice_index, 0) == S_OK,
662 "DISABLE_XMA voice 2 succeeds");
663 return blocks;
664 };
665
666 check(run_blocks(0) == 8, "Packets 0 and 2 write 8 blocks, skipping packet 1");
667 check(run_blocks(1) == 12, "One loop of packet 0 writes 12 blocks (packets 0, 0, 2)");
668 check(((words[0] >> 12) & 0xFFu) == 0u, "Loop count is consumed by the single loop");
669 const auto* ring_bytes = static_cast<const uint8_t*>(out_va);
670#if defined(LEONIDA_HAVE_XMA2_DECODER)
671 auto has_signal = [](const uint8_t* start) {
672 return std::any_of(start, start + 0x400, [](uint8_t b) { return b != 0 && b != 0x55; });
673 };
674 check(has_signal(ring_bytes) && has_signal(ring_bytes + 0x400) && has_signal(ring_bytes + 0x800),
675 "Rust produces signal before and after rewinding the loop");
676 check(std::memcmp(ring_bytes, ring_bytes + 0x400, 0x400) == 0,
677 "Rewind decodes the first packet from fresh decoder state");
678#endif
679 check(run_blocks(1, 3, 2, 1) == 9 && ((words[1] >> 24) & 7u) == 0,
680 "Initial and loop subframe skips consume 3 blocks and clear the initial skip");
681 check(run_blocks(0, 2) == 8,
682 "A skip to the end of input 0 continues at input 1");
683 check(run_blocks(0, 1) == 8,
684 "An overshooting skip starts at packet 1 of input 1");
685#if defined(LEONIDA_HAVE_XMA2_DECODER)
686 check(has_signal(ring_bytes) && has_signal(ring_bytes + 0x400),
687 "Rust produces signal on both sides of the buffer switch");
688#endif
689
690 configure_voice(255, 3, 4, 7, 9);
691 check(fn_submit(x_acp, 5, 0xf3, 0xffffffffu, &voice_index, 0) == S_OK,
692 "Enable infinite loop with out-of-range ring indices");
693 for (int wait = 0; wait < 1000 && (words[1] >> 31) != 0u; ++wait) Sleep(1);
694 check((words[1] >> 31) == 0u && ((words[0] >> 27) & 0x1Fu) == 1u,
695 "Ring stops at the normalized read index");
696 check(fn_submit(x_acp, 7, 0xf4, 0xffffffffu, &voice_index, 0) == S_OK,
697 "Disable infinite loop after filling bounded ring");
698 check(((words[0] >> 12) & 0xFFu) == 255u, "Infinite loop does not consume its loop count");
699 check(std::all_of(ring_bytes + 0x400, ring_bytes + 0x1000,
700 [](uint8_t b) { return b == 0x55; }),
701 "Output never writes beyond the configured four-block ring");
702
703 words[0] = 3u << 22; // three ring blocks
704 words[9] = 2u;
705 const uint32_t advance_args[2] = {2u, UINT32_MAX};
706 check(fn_submit(x_acp, 18, 0xf5, 0xffffffffu, advance_args, 0) == S_OK && words[9] == 2u,
707 "ADVANCE_XMA_READ wraps at the ring size without overflowing");
708
709 auto wait_for_ring = [&]() {
710 for (int wait = 0; wait < 1000 && (words[1] >> 31) != 0u; ++wait) Sleep(1);
711 return (words[1] >> 31) == 0u;
712 };
713 const uint32_t refill_read_args[2] = {voice_index, 4};
714
715 configure_voice(0, 3, 4, 0, 0);
716 words[0] = 1u | (1u << 20) | (4u << 22);
717 write_xma_packet(packets, 3, 0);
718 check(fn_submit(x_acp, 5, 0xf6, 0xffffffffu, &voice_index, 0) == S_OK && wait_for_ring(),
719 "First packet fills the ring and leaves queued PCM");
720 TestShapeContexts source_only{};
721 source_only.numSrcContexts = 1;
722 check(alloc_ctx(&source_only) == S_OK && source_only.srcContextArray != nullptr,
723 "A non-XMA allocation can coexist with the active XMA table");
724 words[0].fetch_or(1u << 20);
725 check(fn_submit(x_acp, 5, 0xf7, 0xffffffffu, &voice_index, 0) == S_OK,
726 "Re-enable while refilling the current input");
727 int refills = 0;
728 for (int i = 0; i < 5; ++i) {
729 if (fn_submit(x_acp, 18, 0xf8, 0xffffffffu, refill_read_args, 0) != S_OK || !wait_for_ring()) break;
730 ++refills;
731 }
732 check(refills == 5 && (words[2] >> 31) == 0u && ((words[0] >> 20) & 3u) == 0u,
733 "Refill and repeated enable preserve all six frames and consume the reused input");
734 check(fn_submit(x_acp, 7, 0xf9, 0xffffffffu, &voice_index, 0) == S_OK,
735 "Disable the single-buffer refill voice");
736
737 // The next same-stream packet is in the first input's refill, after a short second input.
738 write_xma_packet(packets, 1, 2);
739 write_xma_packet(packets + 0x1000, 2, 0);
740 write_xma_packet(packets + 0x1800, 1, 0);
741 configure_voice(0, 1, 4, 0, 0);
742 words[1] = (words[1] & ~0xFFFu) | 1u;
743 check(fn_submit(x_acp, 5, 0xfa, 0xffffffffu, &voice_index, 0) == S_OK && wait_for_ring(),
744 "Voice fills the ring before the skip crosses two buffers");
745 words[5] = in_apu + 0x1000u;
746 words[0] = (words[0] & ~0xFFFu) | 2u | (1u << 20);
747 check(fn_submit(x_acp, 18, 0xfb, 0xffffffffu, refill_read_args, 0) == S_OK && wait_for_ring(),
748 "The same-stream packet fills the ring after two buffer crossings");
749 check(((words[0] >> 20) & 3u) == 0u && (words[4] >> 31) == 0u,
750 "A skip across both buffers lands on the last packet of the reloaded input");
751 check(fn_submit(x_acp, 7, 0xfc, 0xffffffffu, &voice_index, 0) == S_OK,
752 "Disable the two-buffer refill voice");
753
754 // Both sides were empty. When both are refilled, the title's first input wins.
755 write_xma_packet(packets, 1, 0);
756 configure_voice(0, 3, 4, 0, 0);
757 words[0] = 1u | (1u << 20) | (4u << 22);
758 const uint32_t voice_bit = 1u << voice_index;
759 check(fn_submit(x_acp, 6, 0, 0xffffffffu, &voice_bit, 0) == S_OK && wait_for_ring(),
760 "ENABLE_XMAS starts the selected voice and exhausts the first input");
761 write_xma_packet(packets, 2, 0);
762 write_xma_packet(packets + 0x800, 1, 0);
763 words[6] = in_apu + 0x800u;
764 words[1].fetch_or(1u);
765 words[0].fetch_or(3u << 20);
766 check(fn_submit(x_acp, 18, 0, 0xffffffffu, refill_read_args, 0) == S_OK && wait_for_ring(),
767 "A double refill supplies the next PCM blocks");
768 check(((words[0] >> 20) & 3u) == 2u && (words[4] >> 31) == 1u,
769 "A double refill plays input 0 before input 1");
770#if defined(LEONIDA_HAVE_XMA2_DECODER)
771 check(has_signal(ring_bytes), "Rust decodes non-silent PCM after a double refill");
772#endif
773
774 check(fn_submit(x_acp, 8, 0, 0xffffffffu, &voice_bit, 0) == S_OK,
775 "Reset the voice before exhausting both inputs");
776 write_xma_packet(packets, 1, 0);
777 write_xma_packet(packets + 0x800, 1, 0);
778 configure_voice(0, 1, 8, 0, 0);
779 words[1] = (words[1] & ~0xFFFu) | 1u;
780 check(fn_submit(x_acp, 6, 0, 0xffffffffu, &voice_bit, 0) == S_OK && wait_for_ring() &&
781 ((words[0] >> 20) & 3u) == 0u,
782 "The voice exhausts input 0 and then input 1");
783 write_xma_packet(packets, 2, 0);
784 words[0].fetch_or(3u << 20);
785 const uint32_t full_ring[2] = {voice_index, 8};
786 check(fn_submit(x_acp, 18, 0, 0xffffffffu, full_ring, 0) == S_OK && wait_for_ring() &&
787 ((words[0] >> 20) & 3u) == 2u,
788 "A double refill plays input 0 first even after exhausting input 1");
789
790 // Reconfigure the still-enabled slot and verify that no queued PCM or old format survives.
791 bool reconfigured = true;
792 for (uint32_t rate = 0; rate < 4; ++rate) {
793 const bool stereo = (rate & 1u) == 0;
794 write_xma_packet(packets, 1, 0, rate, stereo);
795 words[0] = 1u | (1u << 20) | (16u << 22);
796 words[2] = 32u;
797 words[4] = 0u;
798 words[9] = 12u;
799 std::memset(out_va, 0, 0x1000);
800 // Enable applies the new format before making the output writable.
801 words[1] = ((rate | (stereo ? 4u : 0u)) << 27);
802 reconfigured &= fn_submit(x_acp, 5, 0, 0xffffffffu, &voice_index, 0) == S_OK;
803 reconfigured &= fn_submit(x_acp, 18, 0, 0xffffffffu, refill_read_args, 0) == S_OK;
804 for (int wait = 0; wait < 1000 && (words[2] >> 31) == 0u; ++wait) Sleep(1);
805 reconfigured &= (words[2] >> 31) == 1u && ((words[0] >> 27) & 0x1Fu) == (stereo ? 8u : 4u);
806#if defined(LEONIDA_HAVE_XMA2_DECODER)
807 reconfigured &= has_signal(ring_bytes);
808#endif
809 }
810 check(reconfigured, "Re-enabled voices select mono or stereo PCM at all four sample rates");
811 check(fn_submit(x_acp, 8, 0, 0xffffffffu, &voice_bit, 0) == S_OK,
812 "DISABLE_XMAS stops the selected voice");
813
814 configure_voice(0, 3, 4, 0, 0);
815 write_xma_packet(packets, 1, 1);
816 fail_worker_allocation.store(true);
817 check(fn_submit(x_acp, 5, 0, 0xffffffffu, &voice_index, 0) == S_OK,
818 "Enable a voice before an injected worker allocation failure");
819 for (int wait = 0; wait < 1000 && (words[2] >> 31) == 0u; ++wait) Sleep(1);
820 check(!fail_worker_allocation.exchange(false) && (words[2] >> 31) != 0u,
821 "Worker allocation failure surfaces an XMA error without terminating the process");
822 check(fn_submit(x_acp, 5, 0, 0xffffffffu, &voice_index, 0) == S_OK && wait_for_ring(),
823 "A voice can run again after a worker allocation failure");
824
825 check(release_ctx(x_acp) == S_OK, "Release SHAPE contexts through the opaque AcpHal handle");
826 check(fn_release(x_acp) == S_OK, "Release packet loop AcpHal succeeds");
827 free_mem(in_va);
828 free_mem(out_va);
829 check(release_ctx(&xma_ctx) == S_OK, "Release packet loop SHAPE contexts");
830 }
831
832 // 9. ENABLE_XMA racing SHAPE allocation and release, including concurrent releases.
833 {
834 using RaceConnectFn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t);
835 using RaceSubmitFn = HRESULT(__stdcall*)(void*, uint32_t, uint64_t, uint32_t, const void*, uint32_t);
836 using RaceReleaseFn = HRESULT(__stdcall*)(void*);
837
838 void* race_acp = nullptr;
839 check(create(&race_acp) == S_OK && race_acp != nullptr, "AcpHalCreate for XMA race test");
840 auto race_vt = *static_cast<void* const* const*>(race_acp);
841 const auto race_connect = reinterpret_cast<RaceConnectFn>(race_vt[0]);
842 const auto race_submit = reinterpret_cast<RaceSubmitFn>(race_vt[2]);
843 const auto race_release = reinterpret_cast<RaceReleaseFn>(race_vt[5]);
844 check(race_connect(race_acp, 0x1000, 0x1000) == S_OK, "Connect for XMA race test");
845
846 constexpr int kRaceIterations = 20000;
847 std::atomic<int> bind_failures{0};
848 std::thread enabler([&]() {
849 const uint32_t enable_arg = 1u;
850 for (int i = 0; i < kRaceIterations; ++i) {
851 race_submit(race_acp, 5, 0xe000u + static_cast<uint64_t>(i), 0xffffffffu,
852 &enable_arg, 0);
853 }
854 });
855 std::thread releaser([&]() {
856 for (int i = 0; i < kRaceIterations; ++i) {
857 if (release_ctx(nullptr) != S_OK) ++bind_failures;
858 }
859 });
860 for (int i = 0; i < kRaceIterations; ++i) {
861 TestShapeContexts race_ctx{};
862 race_ctx.numXmaContexts = 4;
863 if (alloc_ctx(&race_ctx) != S_OK) ++bind_failures;
864 if (release_ctx(&race_ctx) != S_OK) ++bind_failures;
865 }
866 enabler.join();
867 releaser.join();
868 check(bind_failures == 0, "20000 bind/release cycles race ENABLE_XMA and independent releases");
869 check(race_release(race_acp) == S_OK, "Release race AcpHal succeeds");
870 }
871
260 std::printf("acphal_test complete: %d checks, %d failures\n", g_checks, g_failures); 872 std::printf("acphal_test complete: %d checks, %d failures\n", g_checks, g_failures);
261 return g_failures ? 1 : 0; 873 return g_failures ? 1 : 0;
262} 874}
diff --git a/runtime/test/check_sparse_queue_family.py b/runtime/test/check_sparse_queue_family.py
index 27ebc1f5d..b16e4121c 100644
--- a/runtime/test/check_sparse_queue_family.py
+++ b/runtime/test/check_sparse_queue_family.py
@@ -29,6 +29,19 @@ SPARSE_FLAGS = "VkBufferCreateFlags = 7 (VK_BUFFER_CREATE_SPARSE_BINDING_BIT"
29MODE = re.compile(r"sharingMode:\s+VkSharingMode = (VK_SHARING_MODE_\w+)") 29MODE = re.compile(r"sharingMode:\s+VkSharingMode = (VK_SHARING_MODE_\w+)")
30COUNT = re.compile(r"queueFamilyIndexCount:\s+uint32_t = (\d+)") 30COUNT = re.compile(r"queueFamilyIndexCount:\s+uint32_t = (\d+)")
31INDICES = re.compile(r"pQueueFamilyIndices\[(\d+)\]:\s+const uint32_t = (\d+)") 31INDICES = re.compile(r"pQueueFamilyIndices\[(\d+)\]:\s+const uint32_t = (\d+)")
32CREATE_DEVICE = re.compile(r"^vkCreateDevice\(.*?(?=^vk\w+\(|\Z)", re.M | re.S)
33QUEUE_FAMILY_PROPS = re.compile(r"^vkGetPhysicalDeviceQueueFamilyProperties\(.*?(?=^vk\w+\(|\Z)", re.M | re.S)
34PHYS_DEVICE = re.compile(r"physicalDevice:\s+VkPhysicalDevice\s*=\s*([0-9a-fA-Fx]+)")
35QUEUE_CREATE_COUNT = re.compile(r"queueCreateInfoCount:\s+uint32_t\s*=\s*(\d+)")
36QUEUE_FAMILY_INDEX = re.compile(
37 r"pQueueCreateInfos\[0\]:(?:(?!pQueueCreateInfos\[|enabledLayerCount).)*?queueFamilyIndex:\s+uint32_t\s*=\s*(\d+)",
38 re.S,
39)
40QUEUE_FAMILY_PROP_COUNT = re.compile(r"pQueueFamilyPropertyCount:\s+uint32_t\*\s*=\s*(\d+)")
41VK_QUEUE_GRAPHICS_BIT = 0x1
42VK_QUEUE_COMPUTE_BIT = 0x2
43VK_QUEUE_TRANSFER_BIT = 0x4
44VK_QUEUE_SPARSE_BINDING_BIT = 0x8
32# Each of the two runs gets 30 s, so both together stay inside the CTest TIMEOUT of 65 s (runtime/CMakeLists.txt). 45# Each of the two runs gets 30 s, so both together stay inside the CTest TIMEOUT of 65 s (runtime/CMakeLists.txt).
33RUN_TIMEOUT = 30 46RUN_TIMEOUT = 30
34ACCESS_VIOLATION = 0xC0000005 # STATUS_ACCESS_VIOLATION, as Windows reports it in the exit code 47ACCESS_VIOLATION = 0xC0000005 # STATUS_ACCESS_VIOLATION, as Windows reports it in the exit code
@@ -38,7 +51,118 @@ CALL_HEAD = re.compile(r"^(vk\w+)\(", re.M)
38CASE = re.compile(r"^RESULT (LAYER_MAP_(?:DIRECT|COPY|COMPUTE)_COPY_COMPUTE) PASS mapped_mismatch=0/65536 unmapped_nonzero=0/65536$", re.M) 51CASE = re.compile(r"^RESULT (LAYER_MAP_(?:DIRECT|COPY|COMPUTE)_COPY_COMPUTE) PASS mapped_mismatch=0/65536 unmapped_nonzero=0/65536$", re.M)
39 52
40 53
41def check_trace(path: Path, expect_exclusive: bool) -> tuple[int, int]: 54def _pick_sparse_queue_families(families: list[tuple[int, int, int, int, int]],
55 graphics: int) -> tuple[int, int, int]:
56 """Mirror runtime/src/queue_families.h (pick_queue_families + sparse_capable_queue_families)."""
57 def fine_grained(family: tuple[int, int, int, int, int]) -> bool:
58 return family[2:] == (1, 1, 1)
59
60 compute = copy = graphics
61 have_compute = have_copy = False
62 for i, family in enumerate(families):
63 flags, count = family[0], family[1]
64 if count == 0:
65 continue
66 if not have_compute and (flags & VK_QUEUE_COMPUTE_BIT) and not (flags & VK_QUEUE_GRAPHICS_BIT):
67 compute = i
68 have_compute = True
69 if (not have_copy and (flags & VK_QUEUE_TRANSFER_BIT)
70 and not (flags & (VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT)) and fine_grained(family)):
71 copy = i
72 have_copy = True
73 if not have_copy and have_compute and fine_grained(families[compute]):
74 copy = compute
75 if not (families[compute][0] & VK_QUEUE_SPARSE_BINDING_BIT):
76 compute = graphics
77 if not (families[copy][0] & VK_QUEUE_SPARSE_BINDING_BIT):
78 copy = graphics
79 return graphics, compute, copy
80
81
82def single_sparse_queue_family(path: Path) -> bool:
83 """True when vkCreateDevice uses 1 queue family and the physical device yields only 1 sparse-capable family.
84
85 Mirrors runtime/src/queue_families.h (pick_queue_families + sparse_capable_queue_families): Leonida picks the
86 first non-graphics async compute or fine-grained (1x1x1) DMA transfer family, then falls back to graphics if the
87 chosen family lacks SPARSE_BINDING. On single-family GPUs (e.g. Intel Xe-LP iGPUs), VK_SHARING_MODE_CONCURRENT
88 is illegal (VUID-00914).
89 """
90 text = path.read_text(encoding="utf-8", errors="replace")
91 devices = CREATE_DEVICE.findall(text)
92 if len(devices) != 1:
93 return False
94 pdev_m = PHYS_DEVICE.search(devices[0])
95 qci_m = QUEUE_CREATE_COUNT.search(devices[0])
96 if not pdev_m or not qci_m or int(qci_m.group(1)) != 1:
97 return False
98 pdev = pdev_m.group(1)
99 created_graphics: int | None = None
100 if "pQueueCreateInfos[" in devices[0]:
101 qfi_m = QUEUE_FAMILY_INDEX.search(devices[0])
102 if not qfi_m:
103 return False
104 created_graphics = int(qfi_m.group(1))
105
106 families: list[tuple[int, int, int, int, int]] | None = None
107 max_expected = 0
108 for call in QUEUE_FAMILY_PROPS.findall(text):
109 after = call.split("<after returning from implementation>", 1)
110 if "<before calling into implementation>" in call and len(after) != 2:
111 pm = PHYS_DEVICE.search(call)
112 if pm and pm.group(1) == pdev:
113 return False
114 continue
115 body = after[1] if len(after) == 2 else call
116 pm = PHYS_DEVICE.search(body)
117 if not pm or pm.group(1) != pdev:
118 continue
119 cnt_m = QUEUE_FAMILY_PROP_COUNT.search(body)
120 if cnt_m:
121 max_expected = max(max_expected, int(cnt_m.group(1)))
122 if "pQueueFamilyProperties[" not in body:
123 continue
124 if not cnt_m:
125 return False
126 expected = int(cnt_m.group(1))
127 if expected <= 0:
128 return False
129 chunks = re.split(r"(?=pQueueFamilyProperties\[\d+\]:)", body)[1:]
130 if len(chunks) != expected:
131 return False
132 parsed: dict[int, tuple[int, int, int, int, int]] = {}
133 for chunk in chunks:
134 im = re.match(r"pQueueFamilyProperties\[(\d+)\]:", chunk)
135 fm = re.search(r"queueFlags:\s+VkQueueFlags\s*=\s*(\d+)", chunk)
136 cm = re.search(r"queueCount:\s+uint32_t\s*=\s*(\d+)", chunk)
137 wm = re.search(r"width:\s+uint32_t\s*=\s*(\d+)", chunk)
138 hm = re.search(r"height:\s+uint32_t\s*=\s*(\d+)", chunk)
139 dm = re.search(r"depth:\s+uint32_t\s*=\s*(\d+)", chunk)
140 if not (im and fm and cm and wm and hm and dm):
141 return False
142 idx = int(im.group(1))
143 if idx >= expected or idx in parsed:
144 return False
145 parsed[idx] = (int(fm.group(1)), int(cm.group(1)), int(wm.group(1)), int(hm.group(1)), int(dm.group(1)))
146 if len(parsed) != expected:
147 return False
148 families = [parsed[i] for i in range(expected)]
149 if not families or len(families) != max_expected:
150 return False
151
152 graphics = (created_graphics if created_graphics is not None
153 else next((i for i, (flags, count, *_) in enumerate(families)
154 if count > 0 and (flags & VK_QUEUE_GRAPHICS_BIT)), None))
155 if graphics is None or graphics >= len(families):
156 return False
157 g_flags, g_count = families[graphics][0], families[graphics][1]
158 if g_count == 0 or not (g_flags & VK_QUEUE_GRAPHICS_BIT) or not (g_flags & VK_QUEUE_SPARSE_BINDING_BIT):
159 return False
160
161 direct, compute, copy = _pick_sparse_queue_families(families, graphics)
162 return compute == direct and copy == direct
163
164
165def check_trace(path: Path, expect_exclusive: bool, *, single_family: bool = False) -> tuple[int, int]:
42 rows = path.read_text(encoding="utf-8", errors="replace").splitlines() 166 rows = path.read_text(encoding="utf-8", errors="replace").splitlines()
43 records = 0 167 records = 0
44 for i, line in enumerate(rows): 168 for i, line in enumerate(rows):
@@ -53,8 +177,11 @@ def check_trace(path: Path, expect_exclusive: bool) -> tuple[int, int]:
53 raise AssertionError(f"incomplete API dump sparse VkBuffer at line {i+1}") 177 raise AssertionError(f"incomplete API dump sparse VkBuffer at line {i+1}")
54 sharing, n = mode.group(1), int(count.group(1)) 178 sharing, n = mode.group(1), int(count.group(1))
55 indices = [(int(slot), int(family)) for slot, family in INDICES.findall(tail)] 179 indices = [(int(slot), int(family)) for slot, family in INDICES.findall(tail)]
56 if expect_exclusive: 180 if expect_exclusive or single_family:
57 if sharing != "VK_SHARING_MODE_EXCLUSIVE" or n != 0 or indices: 181 if sharing != "VK_SHARING_MODE_EXCLUSIVE" or n != 0 or indices:
182 if single_family and not expect_exclusive:
183 raise AssertionError(f"invalid sparse buffer on single-family device at line {i+1}: "
184 f"{sharing}, count={n}, indices={indices}")
58 raise AssertionError(f"baseline negative control not reproduced at line {i+1}") 185 raise AssertionError(f"baseline negative control not reproduced at line {i+1}")
59 elif (sharing != "VK_SHARING_MODE_CONCURRENT" or n < 2 or len(indices) != n 186 elif (sharing != "VK_SHARING_MODE_CONCURRENT" or n < 2 or len(indices) != n
60 or len({slot for slot, _ in indices if slot < n}) != n 187 or len({slot for slot, _ in indices if slot < n}) != n
@@ -101,13 +228,18 @@ def main() -> int:
101 if not candidates: 228 if not candidates:
102 print("SKIP 77: Vulkan SDK VK_LAYER_LUNARG_api_dump unavailable or did not write trace") 229 print("SKIP 77: Vulkan SDK VK_LAYER_LUNARG_api_dump unavailable or did not write trace")
103 return 77 230 return 77
104 calls, infos = check_trace(candidates[0], args.expect_baseline_exclusive) 231 single_family = single_sparse_queue_family(candidates[0])
232 calls, infos = check_trace(candidates[0], args.expect_baseline_exclusive, single_family=single_family)
105 validation_out, skip = run_pass(exe, validation_env, path) 233 validation_out, skip = run_pass(exe, validation_env, path)
106 if skip: 234 if skip:
107 return skip 235 return skip
108 errors = [line for line in validation_out.splitlines() if "Validation Error" in line or "VUID-" in line] 236 errors = [line for line in validation_out.splitlines() if "Validation Error" in line or "VUID-" in line]
109 if errors: 237 if errors:
110 raise AssertionError(f"Khronos validation reported {len(errors)} error line(s); first: {errors[0][:300]}") 238 raise AssertionError(f"Khronos validation reported {len(errors)} error line(s); first: {errors[0][:300]}")
239 if single_family:
240 print(f"SKIP 77: GPU exposes only 1 sparse-capable queue family; cross-family CONCURRENT sparse buffer "
241 f"contract requires 2+ families ({calls} EXCLUSIVE sparse VkBuffer creations and Khronos validation passed)")
242 return 77
111 kinds = sorted(CASE.findall(dump_out)) 243 kinds = sorted(CASE.findall(dump_out))
112 print(f"GPU PASS: {len(kinds)} COPY/COMPUTE sparse queue cases, mapped 65,536 bytes exact, unmapped 65,536 zeros") 244 print(f"GPU PASS: {len(kinds)} COPY/COMPUTE sparse queue cases, mapped 65,536 bytes exact, unmapped 65,536 zeros")
113 print(f"VK API CONTRACT PASS: {calls} sparse VkBuffer creations / {infos} create-info records = " 245 print(f"VK API CONTRACT PASS: {calls} sparse VkBuffer creations / {infos} create-info records = "
diff --git a/runtime/test/cpu_emulation_test.cpp b/runtime/test/cpu_emulation_test.cpp
index 4e1ef3cdb..f94f08044 100644
--- a/runtime/test/cpu_emulation_test.cpp
+++ b/runtime/test/cpu_emulation_test.cpp
@@ -145,6 +145,56 @@ void test_apply() {
145 check(fault.ExceptionCode == STATUS_ACCESS_VIOLATION && fault.NumberParameters == 2 && 145 check(fault.ExceptionCode == STATUS_ACCESS_VIOLATION && fault.NumberParameters == 2 &&
146 fault.ExceptionInformation[0] == 1 && fault.ExceptionInformation[1] == 0, 146 fault.ExceptionInformation[0] == 1 && fault.ExceptionInformation[1] == 0,
147 "clzero on an unwritable line reports a write access violation at the line"); 147 "clzero on an unwritable line reports a write access violation at the line");
148
149 // try_clzero_loop EFlags: first-line fault keeps incoming flags, post-prefix fault and >64 MiB batch apply CMP.
150 const uint8_t loop12[] = {0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x48, 0x39, 0xD0, 0x72, 0xF4};
151 if (auto* two_pages = static_cast<uint8_t*>(VirtualAlloc(nullptr, 8192, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE))) {
152 const uint64_t start = reinterpret_cast<uint64_t>(two_pages);
153 DWORD old = 0;
154 VirtualProtect(two_pages, 8192, PAGE_READONLY, &old);
155 c = {};
156 c.Rax = start;
157 c.Rdx = start + 8192;
158 c.Rip = rip;
159 c.EFlags = 0x202;
160 check(ce::try_clzero_loop(loop12, sizeof loop12, &c, &fault) == ce::ClzeroLoopResult::faulted &&
161 c.Rax == start && c.Rip == rip && c.EFlags == 0x202,
162 "clzero loop fault on first line preserves entry EFlags");
163
164 VirtualProtect(two_pages, 4096, PAGE_READWRITE, &old);
165 std::memset(two_pages, 0x5A, 4096);
166 c = {};
167 c.Rax = start;
168 c.Rdx = start + 8192;
169 c.Rip = rip;
170 c.EFlags = 0x246; // ZF=1, CF=0 on entry
171 check(ce::try_clzero_loop(loop12, sizeof loop12, &c, &fault) == ce::ClzeroLoopResult::faulted,
172 "clzero loop post-prefix fault reported");
173 bool prefix_zeroed = true;
174 for (int i = 0; i < 4096; ++i) prefix_zeroed &= two_pages[i] == 0;
175 check(prefix_zeroed && c.Rax == start + 4096 && c.Rip == rip &&
176 fault.ExceptionCode == STATUS_ACCESS_VIOLATION && fault.ExceptionInformation[1] == start + 4096 &&
177 (c.EFlags & 0xC1u) == 0x81u,
178 "clzero loop post-prefix fault zeroes prefix and applies CMP flags (CF=1, ZF=0, SF=1)");
179 VirtualFree(two_pages, 0, MEM_RELEASE);
180 }
181
182 constexpr size_t kLargeSpan = (size_t(64) << 20) + 4096;
183 if (auto* large = static_cast<uint8_t*>(VirtualAlloc(nullptr, kLargeSpan, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE))) {
184 const uint64_t base = reinterpret_cast<uint64_t>(large);
185 c = {};
186 c.Rax = base;
187 c.Rdx = base + kLargeSpan;
188 c.Rip = rip;
189 c.EFlags = 0x202;
190 check(ce::try_clzero_loop(loop12, sizeof loop12, &c, &fault) == ce::ClzeroLoopResult::ok &&
191 c.Rip == rip && c.Rax == base + (uint64_t(64) << 20) && (c.EFlags & 0xC1u) == 0x81u,
192 "clzero loop >64 MiB first batch applies CMP flags (CF=1, ZF=0, SF=1)");
193 check(ce::try_clzero_loop(loop12, sizeof loop12, &c, &fault) == ce::ClzeroLoopResult::ok &&
194 c.Rip == rip + 12 && c.Rax == base + kLargeSpan && (c.EFlags & 0xC1u) == 0x40u,
195 "clzero loop >64 MiB second batch completes with CF=0, ZF=1, SF=0");
196 VirtualFree(large, 0, MEM_RELEASE);
197 }
148} 198}
149 199
150// ---- Running the real encodings ---- 200// ---- Running the real encodings ----
@@ -244,6 +294,33 @@ void test_live(const ce::Host& host) {
244 "clzero with 66 emulated"); 294 "clzero with 66 emulated");
245 } 295 }
246 296
297 // clzero loop fast-path: mov rax, rcx; clzero; add rax, 0x40; cmp rax, rdx; jb -12; ret
298 {
299 alignas(64) static uint8_t buf[512];
300 std::memset(buf, 0xA5, sizeof buf);
301 Code clz_loop({0x48, 0x89, 0xC8, 0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x48, 0x39, 0xD0, 0x72, 0xF4, 0xC3});
302 check(run(clz_loop, buf + 64, buf + 320, &ex), "clzero loop ran");
303 bool loop_ok = true;
304 for (int i = 0; i < 512; ++i) loop_ok &= buf[i] == ((i >= 64 && i < 320) ? 0 : 0xA5);
305 check(loop_ok, "clzero loop zeroed exact span [64, 320)");
306
307 // REX.R limit register (r8): mov rax, rcx; mov r8, rdx; clzero; add rax, 0x40; cmp rax, r8; jb -12; ret
308 std::memset(buf, 0xA5, sizeof buf);
309 Code clz_r8({0x48, 0x89, 0xC8, 0x49, 0x89, 0xD0, 0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x4C, 0x39, 0xC0,
310 0x72, 0xF4, 0xC3});
311 check(run(clz_r8, buf + 64, buf + 320, &ex), "clzero loop (r8) ran");
312 bool r8_ok = true;
313 for (int i = 0; i < 512; ++i) r8_ok &= buf[i] == ((i >= 64 && i < 320) ? 0 : 0xA5);
314 check(r8_ok, "clzero loop (r8) zeroed exact span [64, 320)");
315
316 // Non-multiple-of-64 limit (300): rounds up to 320, matching native do-while `cmp rax, limit; jb`.
317 std::memset(buf, 0xA5, sizeof buf);
318 check(run(clz_loop, buf + 64, buf + 300, &ex), "clzero loop (unaligned limit) ran");
319 bool unaligned_ok = true;
320 for (int i = 0; i < 512; ++i) unaligned_ok &= buf[i] == ((i >= 64 && i < 320) ? 0 : 0xA5);
321 check(unaligned_ok, "clzero loop (unaligned limit 300) zeroed span [64, 320)");
322 }
323
247 // mov rax,rcx; xor ecx,ecx; xor edx,edx; monitorx; xor eax,eax; xor ecx,ecx; mwaitx; ret 324 // mov rax,rcx; xor ecx,ecx; xor edx,edx; monitorx; xor eax,eax; xor ecx,ecx; mwaitx; ret
248 // (no timer: an interrupt or a store ends a native wait; the emulated one returns at once) 325 // (no timer: an interrupt or a store ends a native wait; the emulated one returns at once)
249 Code mon({0x48, 0x89, 0xC8, 0x31, 0xC9, 0x31, 0xD2, 0x0F, 0x01, 0xFA, 0x31, 0xC0, 0x31, 0xC9, 0x0F, 0x01, 0xFB, 326 Code mon({0x48, 0x89, 0xC8, 0x31, 0xC9, 0x31, 0xD2, 0x0F, 0x01, 0xFA, 0x31, 0xC0, 0x31, 0xC9, 0x0F, 0x01, 0xFB,
diff --git a/runtime/test/d3d12_clear_test.cpp b/runtime/test/d3d12_clear_test.cpp
index 46c467ca9..abc3b0bd7 100644
--- a/runtime/test/d3d12_clear_test.cpp
+++ b/runtime/test/d3d12_clear_test.cpp
@@ -6,7 +6,9 @@
6#include "vk_test_device.h" 6#include "vk_test_device.h"
7#include "../shims/d3d12_com.h" 7#include "../shims/d3d12_com.h"
8#include <dxgi1_4.h> 8#include <dxgi1_4.h>
9#include <algorithm>
9#include <array> 10#include <array>
11#include <cmath>
10#include <vector> 12#include <vector>
11#include <cstring> 13#include <cstring>
12#include <cstdint> 14#include <cstdint>
@@ -375,10 +377,9 @@ bool check_unlisted_rtvs(ID3D12Device* device) {
375} // namespace 377} // namespace
376 378
377// ClearDepthStencilView values at the edge of what D3D12 accepts: on a D32_FLOAT target a depth outside [0, 1] and a 379// ClearDepthStencilView values at the edge of what D3D12 accepts: on a D32_FLOAT target a depth outside [0, 1] and a
378// NaN are stored exactly as given, and flags that name no plane clear nothing (the target keeps the value of the clear 380// NaN are stored exactly as given by WARP; flags that name no plane clear nothing. On Vulkan the float values
379// before it). WARP shows both in the read-back, and the layer must show the same texels; a call the layer refuses fails 381// can be preserved with unrestricted depth. Also check the legal [0, 1] clear values on a restricted device.
380// Close() inside clear_depth_and_read. 382bool check_depth_clear_edge_values(ID3D12Device* host, ID3D12Device* ours, bool unrestricted_depth) {
381bool check_depth_clear_edge_values(ID3D12Device* host, ID3D12Device* ours) {
382 constexpr UINT width = 5, height = 3; 383 constexpr UINT width = 5, height = 3;
383 const auto read = [](ID3D12Device* device, FLOAT depth_full, FLOAT depth_part, bool part_no_flags, 384 const auto read = [](ID3D12Device* device, FLOAT depth_full, FLOAT depth_part, bool part_no_flags,
384 std::vector<unsigned char>& depth) { 385 std::vector<unsigned char>& depth) {
@@ -402,34 +403,40 @@ bool check_depth_clear_edge_values(ID3D12Device* host, ID3D12Device* ours) {
402 std::memcpy(&warp_value, expected.data() + at, 4); 403 std::memcpy(&warp_value, expected.data() + at, 4);
403 std::fprintf(stderr, "%s (%u,%u): WARP cleared %g, expected %g\n", what, x, y, warp_value, want); 404 std::fprintf(stderr, "%s (%u,%u): WARP cleared %g, expected %g\n", what, x, y, warp_value, want);
404 ++wrong; 405 ++wrong;
405 } else if (std::memcmp(got.data() + at, expected.data() + at, 4)) { 406 }
406 FLOAT warp_value, layer_value; 407 FLOAT want_layer = want;
407 std::memcpy(&warp_value, expected.data() + at, 4); 408 if (!unrestricted_depth)
409 want_layer = std::isnan(want) ? 0.0f : std::clamp(want, 0.0f, 1.0f);
410 if (std::memcmp(got.data() + at, &want_layer, 4)) {
411 FLOAT layer_value;
408 std::memcpy(&layer_value, got.data() + at, 4); 412 std::memcpy(&layer_value, got.data() + at, 4);
409 std::fprintf(stderr, "%s (%u,%u): layer cleared %g, WARP %g\n", what, x, y, layer_value, 413 std::fprintf(stderr, "%s (%u,%u): layer cleared %g, expected %g\n", what, x, y, layer_value,
410 warp_value); 414 want_layer);
411 ++wrong; 415 ++wrong;
412 } 416 }
413 } 417 }
414 if (wrong) return false; 418 if (wrong) return false;
415 std::printf("%s: %ux%u depth texels match WARP\n", what, width, height); 419 std::printf("%s: %ux%u depth texels matched (%s)\n", what, width, height,
420 unrestricted_depth ? "WARP parity" : "restricted Vulkan depth");
416 return true; 421 return true;
417 }; 422 };
418 if (!compare("depth 1.5 and -0.5 are stored as given", 1.5f, -0.5f, false, 1.5f, -0.5f)) return false; 423 if (!compare("depth clear with 1.5 and -0.5", 1.5f, -0.5f, false, 1.5f, -0.5f)) return false;
419 // NaN is likewise not clamped away; WARP stores the quiet NaN it was given. 424 // NaN is likewise not clamped away; WARP stores the quiet NaN it was given.
420 const FLOAT nan = std::numeric_limits<float>::quiet_NaN(); 425 const FLOAT nan = std::numeric_limits<float>::quiet_NaN();
421 if (!compare("a NaN depth stays NaN", nan, nan, false, nan, nan)) return false; 426 if (!compare("depth clear with NaN", nan, nan, false, nan, nan)) return false;
422 return compare("flags 0 leaves the target alone", 0.25f, 0.75f, true, 0.25f, 0.25f); 427 return compare("flags 0 leaves the target alone", 0.25f, 0.75f, true, 0.25f, 0.25f);
423} 428}
424 429
425int main(int argc, char** argv) { 430int main(int argc, char** argv) {
426 const bool volume_only = argc == 2 && std::strcmp(argv[1], "--volume") == 0; 431 const bool volume_only = argc == 2 && std::strcmp(argv[1], "--volume") == 0;
427 const bool rgb9e5_only = argc == 2 && std::strcmp(argv[1], "--rgb9e5") == 0; 432 const bool rgb9e5_only = argc == 2 && std::strcmp(argv[1], "--rgb9e5") == 0;
428 if (argc != 1 && !volume_only && !rgb9e5_only) { 433 const bool restricted_depth = argc == 2 && std::strcmp(argv[1], "--restricted-depth") == 0;
429 std::fprintf(stderr, "usage: d3d12_clear_test [--volume|--rgb9e5]\n"); 434 if (argc != 1 && !volume_only && !rgb9e5_only && !restricted_depth) {
435 std::fprintf(stderr, "usage: d3d12_clear_test [--volume|--rgb9e5|--restricted-depth]\n");
430 return 2; 436 return 2;
431 } 437 }
432 vktest::Device vk; 438 vktest::Device vk;
439 vk.request_depth_range_unrestricted = !restricted_depth && !volume_only && !rgb9e5_only;
433 const auto device_status = vk.initialize(); 440 const auto device_status = vk.initialize();
434 if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips 441 if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips
435 if (device_status != vktest::DeviceStatus::ready) return 1; 442 if (device_status != vktest::DeviceStatus::ready) return 1;
@@ -444,6 +451,7 @@ int main(int argc, char** argv) {
444 info.device = vk.device; 451 info.device = vk.device;
445 info.queue = vk.queue; 452 info.queue = vk.queue;
446 info.queue_family = vk.family; 453 info.queue_family = vk.family;
454 info.depth_range_unrestricted = vk.depth_range_unrestricted;
447 if (FAILED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&ours.p)))) return 1; 455 if (FAILED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&ours.p)))) return 1;
448 if (rgb9e5_only) { 456 if (rgb9e5_only) {
449 D3D12_FEATURE_DATA_FORMAT_SUPPORT fs{DXGI_FORMAT_R9G9B9E5_SHAREDEXP}; 457 D3D12_FEATURE_DATA_FORMAT_SUPPORT fs{DXGI_FORMAT_R9G9B9E5_SHAREDEXP};
@@ -470,10 +478,12 @@ int main(int argc, char** argv) {
470 std::fprintf(stderr, "WARP reference unavailable: differential test cannot run\n"); 478 std::fprintf(stderr, "WARP reference unavailable: differential test cannot run\n");
471 return 1; 479 return 1;
472 } 480 }
481 if (restricted_depth)
482 return check_depth_clear_edge_values(host.p, ours.p, false) ? 0 : 1;
473 if (!check_volume_rtvs(host.p, ours.p)) return 1; 483 if (!check_volume_rtvs(host.p, ours.p)) return 1;
474 if (volume_only) return 0; 484 if (volume_only) return 0;
475 if (!check_unlisted_rtvs(ours.p)) return 1; 485 if (!check_unlisted_rtvs(ours.p)) return 1;
476 if (!check_depth_clear_edge_values(host.p, ours.p)) return 1; 486 if (!check_depth_clear_edge_values(host.p, ours.p, vk.depth_range_unrestricted)) return 1;
477 const float nan = std::numeric_limits<float>::quiet_NaN(), inf = std::numeric_limits<float>::infinity(); 487 const float nan = std::numeric_limits<float>::quiet_NaN(), inf = std::numeric_limits<float>::infinity();
478 // Integer-format values: negatives, fractions, NaN and overflow exercise the numeric float->int conversion. 488 // Integer-format values: negatives, fractions, NaN and overflow exercise the numeric float->int conversion.
479 const std::array<float, 4> int_values[] = { 489 const std::array<float, 4> int_values[] = {
@@ -677,7 +687,7 @@ int main(int argc, char** argv) {
677 static_cast<unsigned long long>(validation_errors)); 687 static_cast<unsigned long long>(validation_errors));
678 if (validation_errors) return 1; 688 if (validation_errors) return 1;
679 if (compare_failed) return compare_failed; 689 if (compare_failed) return compare_failed;
680 if (volume_only || rgb9e5_only) return 0; 690 if (volume_only || rgb9e5_only || restricted_depth) return 0;
681 std::printf("RTV and DSV clears: %u full/rectangle readbacks matched WARP\n", cases_checked); 691 std::printf("RTV and DSV clears: %u full/rectangle readbacks matched WARP\n", cases_checked);
682 return 0; 692 return 0;
683} 693}
diff --git a/runtime/test/d3d12_dxr_validation_test.cpp b/runtime/test/d3d12_dxr_validation_test.cpp
index 2e09a39ee..a3749acfd 100644
--- a/runtime/test/d3d12_dxr_validation_test.cpp
+++ b/runtime/test/d3d12_dxr_validation_test.cpp
@@ -93,6 +93,28 @@ int run_suite(ID3D12Device* base_dev, const char* name, bool check_strict_valida
93 std::printf("%s: raytracing not supported (tier=%d), skipping\n", name, static_cast<int>(o5.RaytracingTier)); 93 std::printf("%s: raytracing not supported (tier=%d), skipping\n", name, static_cast<int>(o5.RaytracingTier));
94 return 77; 94 return 77;
95 } 95 }
96 if (check_strict_validation && o5.RaytracingTier == D3D12_RAYTRACING_TIER_NOT_SUPPORTED) {
97 // Leonida reports RaytracingTier == NOT_SUPPORTED even when XDXR or KHR acceleration structures are
98 // available. Probe PrebuildInfo before creating RAYTRACING_ACCELERATION_STRUCTURE buffers, which
99 // CreateCommittedResource refuses when neither backend is active (e.g. LEONIDA_RT_AS=khr on a non-RT GPU).
100 D3D12_RAYTRACING_GEOMETRY_DESC probe_tri{};
101 probe_tri.Type = D3D12_RAYTRACING_GEOMETRY_TYPE_TRIANGLES;
102 probe_tri.Flags = D3D12_RAYTRACING_GEOMETRY_FLAG_OPAQUE;
103 probe_tri.Triangles.VertexFormat = DXGI_FORMAT_R32G32B32_FLOAT;
104 probe_tri.Triangles.VertexCount = 3;
105 probe_tri.Triangles.VertexBuffer.StrideInBytes = 12;
106 D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS probe_in{};
107 probe_in.Type = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL;
108 probe_in.DescsLayout = D3D12_ELEMENTS_LAYOUT_ARRAY;
109 probe_in.NumDescs = 1;
110 probe_in.pGeometryDescs = &probe_tri;
111 D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO probe_info{};
112 dev->GetRaytracingAccelerationStructurePrebuildInfo(&probe_in, &probe_info);
113 if (probe_info.ResultDataMaxSizeInBytes == 0 || probe_info.ScratchDataSizeInBytes == 0) {
114 std::printf("%s: neither XDXR nor KHR acceleration structures supported, skipping\n", name);
115 return 77;
116 }
117 }
96 118
97 Ref<ID3D12Resource> vb, inst_buf, scratch, blas_buf, tlas_buf, src_as, post_buf; 119 Ref<ID3D12Resource> vb, inst_buf, scratch, blas_buf, tlas_buf, src_as, post_buf;
98 if (!make_buffer(dev.p, 4096, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_FLAG_NONE, 120 if (!make_buffer(dev.p, 4096, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_FLAG_NONE,
@@ -164,10 +186,6 @@ int run_suite(ID3D12Device* base_dev, const char* name, bool check_strict_valida
164 in.pGeometryDescs = &tri; 186 in.pGeometryDescs = &tri;
165 dev->GetRaytracingAccelerationStructurePrebuildInfo(&in, &info); 187 dev->GetRaytracingAccelerationStructurePrebuildInfo(&in, &info);
166 if (info.ResultDataMaxSizeInBytes == 0 || info.ScratchDataSizeInBytes == 0) { 188 if (info.ResultDataMaxSizeInBytes == 0 || info.ScratchDataSizeInBytes == 0) {
167 if (check_strict_validation && o5.RaytracingTier == D3D12_RAYTRACING_TIER_NOT_SUPPORTED) {
168 std::printf("%s: neither XDXR nor KHR acceleration structures supported, skipping\n", name);
169 return 77;
170 }
171 std::fprintf(stderr, "%s: valid BLAS ARRAY prebuild returned zero\n", name); 189 std::fprintf(stderr, "%s: valid BLAS ARRAY prebuild returned zero\n", name);
172 return 1; 190 return 1;
173 } 191 }
diff --git a/runtime/test/d3d12_mesh_test.cpp b/runtime/test/d3d12_mesh_test.cpp
index df430c11a..1b99b8d0b 100644
--- a/runtime/test/d3d12_mesh_test.cpp
+++ b/runtime/test/d3d12_mesh_test.cpp
@@ -138,6 +138,7 @@ int main() {
138 info.buffer_device_address = true; 138 info.buffer_device_address = true;
139 info.shader_dir = library.string(); 139 info.shader_dir = library.string();
140 info.mesh_shader = mesh; 140 info.mesh_shader = mesh;
141 info.mesh_shader_queries = mesh && d.mesh_shader_queries;
141 info.pipeline_statistics_query = d.pipeline_statistics_query; 142 info.pipeline_statistics_query = d.pipeline_statistics_query;
142 return info; 143 return info;
143 }; 144 };
@@ -405,8 +406,15 @@ int main() {
405 // query 2 the two vertex draws alone. A mesh draw has no input assembly or vertex shader, so those fields 406 // query 2 the two vertex draws alone. A mesh draw has no input assembly or vertex shader, so those fields
406 // count only the two full-screen triangles (3 vertices, 1 primitive each). How many clipping and pixel 407 // count only the two full-screen triangles (3 vertices, 1 primitive each). How many clipping and pixel
407 // shader invocations a draw makes is the driver's (RADV's PSInvocations is not the pixel count), so query 408 // shader invocations a draw makes is the driver's (RADV's PSInvocations is not the pixel count), so query
408 // 0 is checked against query 2: more of both is the mesh segment's share. Under LEONIDA_VK_VALIDATION=1 the 409 // 0 is checked against query 2: more pixel shader invocations is the mesh segment's share. A mesh segment
409 // run must stay free of VUID-vkCmdDrawMeshTasksEXT-pipelineStatistics-07076. 410 // runs in a pool that counts the fragment and compute invocations only, because
411 // VUID-vkCmdDrawMeshTasksEXT-pipelineStatistics-07076 leaves the clipping counters out of a pool that is
412 // active during a mesh draw; D3D12 counts the clipping invocations and primitives of a mesh pipeline, so
413 // those two fields read 0 here. Under LEONIDA_VK_VALIDATION=1 the run must stay free of the VUID.
414 // Where the device has the meshShaderQueries feature, the clipping invocations of a mesh segment come
415 // from a mesh-primitives query instead (D3D-MESH-CLIPPING-COUNTER): the number of primitives the mesh
416 // shader emitted that reached the fragment shader. How many that is depends on the driver, so the counts
417 // are compared with each other and not written down.
410 if (d.pipeline_statistics_query) { 418 if (d.pipeline_statistics_query) {
411 const D3D12_QUERY_HEAP_DESC statistics_desc{D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS, 3, 0}; 419 const D3D12_QUERY_HEAP_DESC statistics_desc{D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS, 3, 0};
412 Ref<ID3D12QueryHeap> statistics; 420 Ref<ID3D12QueryHeap> statistics;
@@ -472,11 +480,26 @@ int main() {
472 EXPECT(vertex_only.IAVertices == 6 && vertex_only.IAPrimitives == 2); 480 EXPECT(vertex_only.IAVertices == 6 && vertex_only.IAPrimitives == 2);
473 EXPECT(mixed.GSInvocations == 0 && mixed.GSPrimitives == 0 && mixed.HSInvocations == 0 && 481 EXPECT(mixed.GSInvocations == 0 && mixed.GSPrimitives == 0 && mixed.HSInvocations == 0 &&
474 mixed.DSInvocations == 0 && mixed.CSInvocations == 0); 482 mixed.DSInvocations == 0 && mixed.CSInvocations == 0);
475 EXPECT(mixed.CInvocations > vertex_only.CInvocations && mixed.PSInvocations > vertex_only.PSInvocations); 483 // The clipping invocations of the mesh segments (D3D-MESH-CLIPPING-COUNTER). Without the feature they
484 // read 0; with it they are the mesh-primitives count of those segments.
485 const auto mesh_clipping = mixed.CInvocations - vertex_only.CInvocations;
486 if (d.mesh_shader_queries) {
487 // The count has to be wired up, not merely self-consistent. A layer that reported the feature but
488 // never created the third pool would leave both counts at 0, and 0 >= 0 would still hold. How many
489 // primitives the mesh shader emits is the driver's, so ask for a positive count and not for a
490 // number: the mesh draw above fills the top-left quadrant, so it emits at least one.
491 EXPECT(mesh_clipping >= mesh_only.CInvocations);
492 EXPECT(mesh_only.CInvocations > 0);
493 } else {
494 EXPECT(mesh_clipping == 0);
495 }
496 EXPECT(mixed.PSInvocations > vertex_only.PSInvocations);
476 EXPECT(mesh_only.IAVertices == 0 && mesh_only.IAPrimitives == 0 && mesh_only.VSInvocations == 0 && 497 EXPECT(mesh_only.IAVertices == 0 && mesh_only.IAPrimitives == 0 && mesh_only.VSInvocations == 0 &&
477 mesh_only.GSInvocations == 0 && mesh_only.GSPrimitives == 0 && mesh_only.HSInvocations == 0 && 498 mesh_only.GSInvocations == 0 && mesh_only.GSPrimitives == 0 && mesh_only.HSInvocations == 0 &&
478 mesh_only.DSInvocations == 0 && mesh_only.CSInvocations == 0); 499 mesh_only.DSInvocations == 0 && mesh_only.CSInvocations == 0);
479 EXPECT(mesh_only.CInvocations > 0 && mesh_only.PSInvocations > 0); 500 // Vulkan has no clipped-primitive counter, so the clipping primitives of a mesh segment stay 0.
501 EXPECT(mesh_only.CPrimitives == 0 && mesh_only.PSInvocations > 0);
502 if (!d.mesh_shader_queries) EXPECT(mesh_only.CInvocations == 0);
480 } else { 503 } else {
481 std::printf("pipelineStatisticsQuery not available: the D3D-291 statistics check is skipped\n"); 504 std::printf("pipelineStatisticsQuery not available: the D3D-291 statistics check is skipped\n");
482 } 505 }
diff --git a/runtime/test/d3d12_pipeline_library_host_test.cpp b/runtime/test/d3d12_pipeline_library_host_test.cpp
index e8b8c5795..3ed6341d8 100644
--- a/runtime/test/d3d12_pipeline_library_host_test.cpp
+++ b/runtime/test/d3d12_pipeline_library_host_test.cpp
@@ -3,9 +3,9 @@
3// corrupt blobs, the other device's serialized blob, the null-output capability check and other interfaces, and on 3// corrupt blobs, the other device's serialized blob, the null-output capability check and other interfaces, and on
4// an empty library StorePipeline / LoadComputePipeline / LoadGraphicsPipeline / LoadPipeline with null, empty and 4// an empty library StorePipeline / LoadComputePipeline / LoadGraphicsPipeline / LoadPipeline with null, empty and
5// unknown names and null PSOs, descriptions or outputs, and Serialize with null, short and long buffers. Every HRESULT 5// unknown names and null PSOs, descriptions or outputs, and Serialize with null, short and long buffers. Every HRESULT
6// is recorded, with whether the output pointer was written; the two records must be the same, step by step. The 6// and output pointer state are recorded. The public argument checks must agree step by step. Serialized sizes and
7// serialized size and bytes are each device's own format and are not compared. A step the host runtime faults on is 7// the result of changing a trailing byte are reported for each device's own format. Host faults are reported
8// reported and not compared. No shaders or game data. Skips (77) without a Vulkan GPU; without a host D3D12 device 8// separately. No shaders or game data. Skips (77) without a Vulkan GPU. Without a host D3D12 device,
9// only the layer's own record is printed. Set LEONIDA_D3D49_VERBOSE=1 to print every step. 9// only the layer's own record is printed. Set LEONIDA_D3D49_VERBOSE=1 to print every step.
10#include "vk_test_device.h" 10#include "vk_test_device.h"
11#include "../shims/d3d12_com.h" 11#include "../shims/d3d12_com.h"
@@ -105,7 +105,9 @@ const Step kSteps[] = {
105 longer.resize(longer.size() + 64, 0); 105 longer.resize(longer.size() + 64, 0);
106 return create(c, longer.data(), longer.size()); 106 return create(c, longer.data(), longer.size());
107 }}, 107 }},
108 {"create: its own blob, last byte flipped", [](Context& c) { 108 // The layer's empty LPL1 library contains only the header, so its last byte is in the reserved field.
109 // The native library has its own driver-specific layout.
110 {"create: its own blob, last byte flipped [own format]", [](Context& c) {
109 std::vector<std::uint8_t> flipped(c.own); 111 std::vector<std::uint8_t> flipped(c.own);
110 flipped.back() ^= 0xFF; 112 flipped.back() ^= 0xFF;
111 return create(c, flipped.data(), flipped.size()); 113 return create(c, flipped.data(), flipped.size());
diff --git a/runtime/test/d3d12_pipeline_library_test.cpp b/runtime/test/d3d12_pipeline_library_test.cpp
index 1ba930cc7..fb3c3ad03 100644
--- a/runtime/test/d3d12_pipeline_library_test.cpp
+++ b/runtime/test/d3d12_pipeline_library_test.cpp
@@ -206,8 +206,9 @@ int main() {
206 EXPECT(lib->LoadPipeline(L"gfx", &empty_stream, IID_PPV_ARGS(&wrong.p)) == E_INVALIDARG && !wrong.p); 206 EXPECT(lib->LoadPipeline(L"gfx", &empty_stream, IID_PPV_ARGS(&wrong.p)) == E_INVALIDARG && !wrong.p);
207 EXPECT(SUCCEEDED(lib->LoadPipeline(L"gfx", &stream_desc, IID_PPV_ARGS(&loaded_any.p))) && loaded_any.p); 207 EXPECT(SUCCEEDED(lib->LoadPipeline(L"gfx", &stream_desc, IID_PPV_ARGS(&loaded_any.p))) && loaded_any.p);
208 208
209 constexpr SIZE_T lpl1_header_size = 4 * sizeof(std::uint32_t);
209 const SIZE_T blob_size = lib->GetSerializedSize(); 210 const SIZE_T blob_size = lib->GetSerializedSize();
210 EXPECT(blob_size >= 16); 211 EXPECT(blob_size >= lpl1_header_size);
211 std::vector<std::uint8_t> blob(blob_size); 212 std::vector<std::uint8_t> blob(blob_size);
212 EXPECT(lib->Serialize(nullptr, blob_size) == E_INVALIDARG); 213 EXPECT(lib->Serialize(nullptr, blob_size) == E_INVALIDARG);
213 EXPECT(lib->Serialize(blob.data(), blob_size - 1) == E_INVALIDARG); 214 EXPECT(lib->Serialize(blob.data(), blob_size - 1) == E_INVALIDARG);
@@ -216,6 +217,12 @@ int main() {
216 Ref<ID3D12PipelineLibrary> reloaded; 217 Ref<ID3D12PipelineLibrary> reloaded;
217 EXPECT(SUCCEEDED(device->CreatePipelineLibrary(blob.data(), blob.size(), IID_PPV_ARGS(&reloaded.p))) && reloaded.p); 218 EXPECT(SUCCEEDED(device->CreatePipelineLibrary(blob.data(), blob.size(), IID_PPV_ARGS(&reloaded.p))) && reloaded.p);
218 219
220 // The final word in the LPL1 header is reserved and must be zero.
221 blob[lpl1_header_size - 1] ^= 0xFF;
222 Ref<ID3D12PipelineLibrary> rejected;
223 EXPECT(device->CreatePipelineLibrary(blob.data(), blob.size(), IID_PPV_ARGS(&rejected.p)) == E_INVALIDARG &&
224 !rejected.p);
225
219 // 4. Execute the loaded compute PSO and loaded graphics PSO on the GPU. 226 // 4. Execute the loaded compute PSO and loaded graphics PSO on the GPU.
220 Ref<ID3D12CommandQueue> queue; 227 Ref<ID3D12CommandQueue> queue;
221 const D3D12_COMMAND_QUEUE_DESC qd{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, D3D12_COMMAND_QUEUE_FLAG_NONE, 0}; 228 const D3D12_COMMAND_QUEUE_DESC qd{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, D3D12_COMMAND_QUEUE_FLAG_NONE, 0};
diff --git a/runtime/test/d3d12_state_map_test.cpp b/runtime/test/d3d12_state_map_test.cpp
index 9db6ad0c1..2fec30ba4 100644
--- a/runtime/test/d3d12_state_map_test.cpp
+++ b/runtime/test/d3d12_state_map_test.cpp
@@ -404,7 +404,10 @@ int main() {
404 CHECK(vulkan_sync(y::split) == VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT); 404 CHECK(vulkan_sync(y::split) == VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT);
405 CHECK(vulkan_sync(y::render_target) == VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT); 405 CHECK(vulkan_sync(y::render_target) == VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT);
406 CHECK(vulkan_sync(y::copy | y::pixel_shading) == 406 CHECK(vulkan_sync(y::copy | y::pixel_shading) ==
407 (VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT)); 407 (VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_CLEAR_BIT | VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT));
408 // SYNC_COPY covers WriteBufferImmediate (vkCmdUpdateBuffer) and ResolveQueryData's zero fill (vkCmdFillBuffer),
409 // which synchronization2 runs in the CLEAR stage, not COPY (D3D-838).
410 CHECK(vulkan_sync(y::copy) == (VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_CLEAR_BIT));
408 CHECK(vulkan_sync(y::raytracing) == VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT); 411 CHECK(vulkan_sync(y::raytracing) == VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT);
409 CHECK(vulkan_barrier_access(a::no_access) == VK_ACCESS_2_NONE); 412 CHECK(vulkan_barrier_access(a::no_access) == VK_ACCESS_2_NONE);
410 const auto cb_scope = vulkan_barrier_scope(y::pixel_shading, a::constant_buffer); 413 const auto cb_scope = vulkan_barrier_scope(y::pixel_shading, a::constant_buffer);
@@ -427,7 +430,8 @@ int main() {
427 widened = scope(y::clear_unordered_access_view, a::copy_source); // CLEAR only writes 430 widened = scope(y::clear_unordered_access_view, a::copy_source); // CLEAR only writes
428 CHECK(widened.stages & VK_PIPELINE_STAGE_2_ALL_TRANSFER_BIT); 431 CHECK(widened.stages & VK_PIPELINE_STAGE_2_ALL_TRANSFER_BIT);
429 widened = scope(y::copy, a::unordered_access); 432 widened = scope(y::copy, a::unordered_access);
430 CHECK(widened.stages == (VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_PRE_RASTERIZATION_SHADERS_BIT | 433 CHECK(widened.stages == (VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_CLEAR_BIT |
434 VK_PIPELINE_STAGE_2_PRE_RASTERIZATION_SHADERS_BIT |
431 VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT)); 435 VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT));
432 // Pairs Vulkan already accepts are left exactly as vulkan_sync / vulkan_barrier_access map them. 436 // Pairs Vulkan already accepts are left exactly as vulkan_sync / vulkan_barrier_access map them.
433 const std::pair<std::uint32_t, std::uint32_t> unchanged[] = { 437 const std::pair<std::uint32_t, std::uint32_t> unchanged[] = {
diff --git a/runtime/test/d3d12_vulkan_device_test.cpp b/runtime/test/d3d12_vulkan_device_test.cpp
index 056e82561..99bb6d1a4 100644
--- a/runtime/test/d3d12_vulkan_device_test.cpp
+++ b/runtime/test/d3d12_vulkan_device_test.cpp
@@ -5168,6 +5168,12 @@ int main() {
5168 EXPECT(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options)))); 5168 EXPECT(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options))));
5169 EXPECT(options.ResourceBindingTier == D3D12_RESOURCE_BINDING_TIER_3); 5169 EXPECT(options.ResourceBindingTier == D3D12_RESOURCE_BINDING_TIER_3);
5170 EXPECT(options.MaxGPUVirtualAddressBitsPerResource == 40); 5170 EXPECT(options.MaxGPUVirtualAddressBitsPerResource == 40);
5171 // Console 0x40-byte (16-dword) D3D12_OPTIONS query (docs/d3d12_xs_surface.md §7.1): 0x3C PC prefix + zero tail.
5172 UINT console_opts[16]{};
5173 console_opts[15] = 0xdeadbeefu;
5174 EXPECT(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, console_opts, sizeof(console_opts))));
5175 EXPECT(std::memcmp(console_opts, &options, sizeof(options)) == 0);
5176 EXPECT(console_opts[15] == 0);
5171 5177
5172 D3D12_FEATURE_DATA_GPU_VIRTUAL_ADDRESS_SUPPORT va_support{}; 5178 D3D12_FEATURE_DATA_GPU_VIRTUAL_ADDRESS_SUPPORT va_support{};
5173 EXPECT(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_GPU_VIRTUAL_ADDRESS_SUPPORT, &va_support, sizeof(va_support)))); 5179 EXPECT(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_GPU_VIRTUAL_ADDRESS_SUPPORT, &va_support, sizeof(va_support))));
diff --git a/runtime/test/frame_pacer_test.cpp b/runtime/test/frame_pacer_test.cpp
index 8d089acda..81b647fd2 100644
--- a/runtime/test/frame_pacer_test.cpp
+++ b/runtime/test/frame_pacer_test.cpp
@@ -586,6 +586,155 @@ int main() {
586 EXPECT(ms.count() >= 45 && ms.count() < 1000); 586 EXPECT(ms.count() >= 45 && ms.count() < 1000);
587 } 587 }
588 588
589 // TOKEN_ON_TIMEOUT (flag 2) and multi-event pacing (origin poll + blocking flip/vblank wait).
590 {
591 ManualFrameClock clock;
592 FramePacer pacer(clock);
593 EXPECT(pacer.set_frame_interval(period, 3, 0) == pacer_hr::ok);
594 EXPECT(pacer.schedule_frame_event(frame_event_origin, 0, 0) == pacer_hr::ok);
595 EXPECT(pacer.schedule_frame_event(frame_event_vblank, 0, 0) == pacer_hr::ok);
596 EXPECT(pacer.schedule_frame_event(frame_event_flip, 0, 0) == pacer_hr::ok);
597
598 // Origin poll with timeout 0 and TOKEN_ON_TIMEOUT issues a consecutive token and returns S_FALSE.
599 std::uint64_t tok1 = 0;
600 EXPECT(pacer.wait_frame_event(frame_event_origin, 0, frame_wait_flag_token_on_timeout, &tok1) ==
601 pacer_hr::false_);
602 EXPECT(tok1 == 1);
603 EXPECT(pacer.check_present_token(tok1) == pacer_hr::ok);
604
605 // A blocking flip wait paces to the next tick and preserves the caller's token unchanged.
606 auto flip_wait = std::async(std::launch::async, [&] {
607 std::uint64_t preserved = tok1;
608 const std::int32_t hr = pacer.wait_frame_event(frame_event_flip, infinite_timeout_ms, 0, &preserved);
609 return Result{hr, preserved};
610 });
611 EXPECT(blocked(flip_wait));
612 clock.advance_us(period);
613 const Result fr = flip_wait.get();
614 EXPECT(fr.hr == pacer_hr::ok && fr.token == tok1);
615
616 // Second flip wait blocks for the following tick; vblank wait on tick 1 succeeds immediately (independent).
617 EXPECT(pacer.wait_frame_event(frame_event_vblank, 0, 0, nullptr) == pacer_hr::ok);
618 auto flip_wait2 = std::async(std::launch::async, [&] {
619 return Result{pacer.wait_frame_event(frame_event_flip, infinite_timeout_ms, 0, nullptr), 0};
620 });
621 EXPECT(blocked(flip_wait2));
622 clock.advance_us(period);
623 EXPECT(flip_wait2.get().hr == pacer_hr::ok);
624
625 // Origin wait at tick 2 advances consecutively after the early-started token 1.
626 std::uint64_t tok2 = 0;
627 EXPECT(pacer.wait_frame_event(frame_event_origin, 0, 0, &tok2) == pacer_hr::ok && tok2 == 2);
628 }
629
630 // BL-6: frame pacing drift reporting (p50/p95/p99 frame times, mean drift vs target interval,
631 // origin-to-present latency, ring-buffer wrap-around, suspend/resume gap exclusion, and uncapped mode).
632 {
633 auto near = [](double a, double b) { return (a > b ? a - b : b - a) < 1e-6; };
634
635 // 1) Empty and single-frame edge cases.
636 ManualFrameClock clock;
637 FramePacer pacer(clock);
638 EXPECT(setup(pacer, 2));
639 FramePacingSummary s0 = pacer.pacing_summary();
640 EXPECT(s0.frames == 0 && s0.samples == 0 && s0.target_interval_us == period);
641 EXPECT(near(s0.mean_us, 0.0) && near(s0.drift_us, 0.0));
642 EXPECT(s0.p50_us == 0 && s0.p95_us == 0 && s0.p99_us == 0 && s0.latency_samples == 0);
643
644 clock.advance_us(period);
645 std::uint64_t tok = 0;
646 EXPECT(pacer.wait_frame_event(frame_event_origin, 0, 0, &tok) == pacer_hr::ok);
647 clock.advance_us(2000);
648 pacer.commit_present_token(tok, 1);
649 FramePacingSummary s1 = pacer.pacing_summary();
650 EXPECT(s1.frames == 1 && s1.samples == 0 && s1.latency_samples == 1 && s1.latency_p50_us == 2000);
651 EXPECT(near(s1.mean_us, 0.0) && near(s1.drift_us, 0.0));
652
653 // 2) 100 known intervals (16000 + 100*i us for i = 1..100) and known origin->present latencies:
654 // mean = 16000 + 5050 = 21050.0 us, drift = +5050.0 us,
655 // nearest-rank p50 = 16000 + 50*100 = 21000, p95 = 25500, p99 = 25900.
656 ManualFrameClock clock2;
657 FramePacer pacer2(clock2);
658 EXPECT(setup(pacer2, 4));
659 // Present an anchor frame first at t = period + 1000 (latency = 1000 us).
660 clock2.advance_us(period);
661 std::uint64_t t = 0;
662 EXPECT(pacer2.wait_frame_event(frame_event_origin, 0, 0, &t) == pacer_hr::ok);
663 clock2.advance_us(1000);
664 pacer2.commit_present_token(t, 1);
665 for (std::uint64_t i = 1; i <= 100; ++i) {
666 const std::uint64_t dt = period + i * 100;
667 clock2.advance_us(dt);
668 // Issue token after dt - (i * 50)? Simpler: issue token at origin (which passed), present immediately.
669 std::uint64_t tok_i = 0;
670 EXPECT(pacer2.wait_frame_event(frame_event_origin, 0, 0, &tok_i) == pacer_hr::ok);
671 pacer2.commit_present_token(tok_i, 1);
672 }
673 const FramePacingSummary s100 = pacer2.pacing_summary();
674 EXPECT(s100.frames == 101 && s100.samples == 100 && s100.target_interval_us == period);
675 EXPECT(near(s100.mean_us, 21050.0));
676 EXPECT(near(s100.drift_us, 5050.0));
677 EXPECT(s100.p50_us == 21000 && s100.p95_us == 25500 && s100.p99_us == 25900);
678 EXPECT(s100.latency_samples == 101);
679
680 // 3) Negative drift (untokened/early presents faster than target period) + exact origin-to-present latency.
681 ManualFrameClock clock3;
682 FramePacer pacer3(clock3);
683 EXPECT(setup(pacer3, 4));
684 clock3.advance_us(period);
685 EXPECT(pacer3.wait_frame_event(frame_event_origin, 0, 0, &t) == pacer_hr::ok);
686 clock3.advance_us(3000); // latency = 3000
687 pacer3.commit_present_token(t, 1);
688 clock3.advance_us(10000); // dt = 10000 (< 16000) -> drift = -6000
689 pacer3.note_untokened_present();
690 const FramePacingSummary sneg = pacer3.pacing_summary();
691 EXPECT(sneg.frames == 2 && sneg.samples == 1 && sneg.target_interval_us == period);
692 EXPECT(near(sneg.mean_us, 10000.0) && near(sneg.drift_us, -6000.0));
693 EXPECT(sneg.p50_us == 10000 && sneg.p95_us == 10000 && sneg.p99_us == 10000);
694 EXPECT(sneg.latency_samples == 1 && sneg.latency_p50_us == 3000 && sneg.latency_p99_us == 3000);
695
696 // 4) Suspend/resume gap is excluded from frame intervals.
697 pacer3.suspend();
698 clock3.advance_us(5'000'000); // 5 second pause while suspended
699 pacer3.resume();
700 EXPECT(setup(pacer3, 2));
701 clock3.advance_us(period);
702 EXPECT(pacer3.wait_frame_event(frame_event_origin, 0, 0, &t) == pacer_hr::ok);
703 pacer3.commit_present_token(t, 1);
704 const FramePacingSummary ssusp = pacer3.pacing_summary();
705 EXPECT(ssusp.frames == 3 && ssusp.samples == 1 && ssusp.p99_us == 10000); // 5s gap not recorded
706
707 // 5) Ring-buffer wrap-around: fill with slow 32000 us frames, then overwrite entire window with steady 16000 us.
708 ManualFrameClock clock4;
709 FramePacer pacer4(clock4);
710 EXPECT(setup(pacer4, 2));
711 clock4.advance_us(period);
712 EXPECT(pacer4.wait_frame_event(frame_event_origin, 0, 0, &t) == pacer_hr::ok);
713 pacer4.commit_present_token(t, 1);
714 for (std::size_t i = 0; i < frame_pacing_window; ++i) {
715 clock4.advance_us(period * 2);
716 EXPECT(pacer4.wait_frame_event(frame_event_origin, 0, 0, &t) == pacer_hr::ok);
717 pacer4.commit_present_token(t, 1);
718 }
719 const FramePacingSummary slow = pacer4.pacing_summary();
720 EXPECT(slow.samples == frame_pacing_window && near(slow.mean_us, double(period * 2)) &&
721 near(slow.drift_us, double(period)));
722 for (std::size_t i = 0; i < frame_pacing_window; ++i) {
723 clock4.advance_us(period);
724 EXPECT(pacer4.wait_frame_event(frame_event_origin, 0, 0, &t) == pacer_hr::ok);
725 pacer4.commit_present_token(t, 1);
726 }
727 const FramePacingSummary steady = pacer4.pacing_summary();
728 EXPECT(steady.frames == 1 + 2 * frame_pacing_window && steady.samples == frame_pacing_window);
729 EXPECT(near(steady.mean_us, double(period)) && near(steady.drift_us, 0.0));
730 EXPECT(steady.p50_us == period && steady.p95_us == period && steady.p99_us == period);
731
732 // 6) Uncapped mode: target_interval_us == 0 and drift_us == 0 while intervals are still tracked.
733 pacer4.set_uncapped(true);
734 const FramePacingSummary uncap = pacer4.pacing_summary();
735 EXPECT(uncap.target_interval_us == 0 && near(uncap.drift_us, 0.0) && uncap.p50_us == period);
736 }
737
589 std::printf("frame_pacer_test: all cases pass\n"); 738 std::printf("frame_pacer_test: all cases pass\n");
590 return 0; 739 return 0;
591} 740}
diff --git a/runtime/test/gfx10_descriptors_test.cpp b/runtime/test/gfx10_descriptors_test.cpp
index 523180ee7..85843edb8 100644
--- a/runtime/test/gfx10_descriptors_test.cpp
+++ b/runtime/test/gfx10_descriptors_test.cpp
@@ -359,18 +359,21 @@ int main() {
359 CHECK(info.addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE && info.mipLodBias == -0.75f); 359 CHECK(info.addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE && info.mipLodBias == -0.75f);
360 CHECK(info.minLod == 0.5f && info.maxLod == 4.25f); 360 CHECK(info.minLod == 0.5f && info.maxLod == 4.25f);
361 info = vulkan_sampler({.mag_filter = Filter::aniso_point, .mip_filter = MipFilter::linear, .max_anisotropy = 8, 361 info = vulkan_sampler({.mag_filter = Filter::aniso_point, .mip_filter = MipFilter::linear, .max_anisotropy = 8,
362 .compare = CompareFunction::greater, .max_lod = 9.0f, .unnormalized = true}); 362 .compare = CompareFunction::greater, .min_lod = 1.5f, .max_lod = 9.0f,
363 .lod_bias = 2.5f, .unnormalized = true});
363 CHECK(info.unnormalizedCoordinates == VK_TRUE && info.mipmapMode == VK_SAMPLER_MIPMAP_MODE_NEAREST); 364 CHECK(info.unnormalizedCoordinates == VK_TRUE && info.mipmapMode == VK_SAMPLER_MIPMAP_MODE_NEAREST);
364 CHECK(info.maxLod == 0.0f && info.anisotropyEnable == VK_FALSE && info.compareEnable == VK_FALSE); 365 CHECK(info.minLod == 0.0f && info.maxLod == 0.0f && info.mipLodBias == 0.0f);
366 CHECK(info.anisotropyEnable == VK_FALSE && info.compareEnable == VK_FALSE);
365 // Unnormalised: U and V clamp (wrap, the default S# mode, would be invalid: VUID ...-01075), border stays border, 367 // Unnormalised: U and V clamp (wrap, the default S# mode, would be invalid: VUID ...-01075), border stays border,
366 // W is free; min and mag filter agree (VUID ...-01072). 368 // W is free; min and mag filter agree (VUID ...-01072); mipLodBias is zero (VUID ...-01074).
367 CHECK(info.addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE && 369 CHECK(info.addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE &&
368 info.addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE && 370 info.addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE &&
369 info.addressModeW == VK_SAMPLER_ADDRESS_MODE_REPEAT && info.minFilter == info.magFilter); 371 info.addressModeW == VK_SAMPLER_ADDRESS_MODE_REPEAT && info.minFilter == info.magFilter);
370 info = vulkan_sampler({.address_u = AddressMode::clamp_border, .address_v = AddressMode::mirror, 372 info = vulkan_sampler({.address_u = AddressMode::clamp_border, .address_v = AddressMode::mirror,
371 .min_filter = Filter::bilinear, .unnormalized = true}); 373 .min_filter = Filter::bilinear, .lod_bias = -3.25f, .unnormalized = true});
372 CHECK(info.addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER && 374 CHECK(info.addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER &&
373 info.addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE && info.minFilter == VK_FILTER_NEAREST); 375 info.addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE && info.minFilter == VK_FILTER_NEAREST &&
376 info.mipLodBias == 0.0f);
374 CHECK(vulkan_address_mode(AddressMode::mirror) == VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT); 377 CHECK(vulkan_address_mode(AddressMode::mirror) == VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT);
375 CHECK(vulkan_address_mode(AddressMode::mirror_once_last_texel) == VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE); 378 CHECK(vulkan_address_mode(AddressMode::mirror_once_last_texel) == VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE);
376 CHECK(vulkan_address_mode(AddressMode::clamp_half_border) == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE); 379 CHECK(vulkan_address_mode(AddressMode::clamp_half_border) == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE);
diff --git a/runtime/test/loader_tls_test.cpp b/runtime/test/loader_tls_test.cpp
index 625ff6d86..133b27c81 100644
--- a/runtime/test/loader_tls_test.cpp
+++ b/runtime/test/loader_tls_test.cpp
@@ -790,7 +790,8 @@ void test_ga_tls_existing_thread(const fs::path& exe) {
790 { 790 {
791 rt::Loader loader(exe.parent_path()); 791 rt::Loader loader(exe.parent_path());
792 rt::Module& m = loader.load(exe); 792 rt::Module& m = loader.load(exe);
793 check(m.tls_index != 0, "the /GA fixture gets a module TLS index other than the process EXE's 0"); 793 check(m.tls_index != rt::kNoTlsIndex && m.tls_index != 0,
794 "the /GA fixture gets a valid module TLS index other than the process EXE's 0");
794 check(m.tls_ga_slot != rt::kNoTlsIndex, "load() rewrites the /GA fixture's index-0 TLS reads"); 795 check(m.tls_ga_slot != rt::kNoTlsIndex, "load() rewrites the /GA fixture's index-0 TLS reads");
795 get = find_export<int(__cdecl*)()>(m, "ga_tls_get"); 796 get = find_export<int(__cdecl*)()>(m, "ga_tls_get");
796 set = find_export<void(__cdecl*)(int)>(m, "ga_tls_set"); 797 set = find_export<void(__cdecl*)(int)>(m, "ga_tls_set");
diff --git a/runtime/test/mods_test.cpp b/runtime/test/mods_test.cpp
index a29979b25..e95bc4e16 100644
--- a/runtime/test/mods_test.cpp
+++ b/runtime/test/mods_test.cpp
@@ -41,6 +41,9 @@ int main() {
41 check(!parse_model_id("0x123456789", id), "a hash wider than 32 bits is refused"); 41 check(!parse_model_id("0x123456789", id), "a hash wider than 32 bits is refused");
42 check(!parse_model_id("0xZZ", id), "a malformed hash is refused"); 42 check(!parse_model_id("0xZZ", id), "a malformed hash is refused");
43 check(!parse_model_id("", id), "an empty name is refused"); 43 check(!parse_model_id("", id), "an empty name is refused");
44 id = 0xCAFEBABEu;
45 check(!parse_model_id("0x", id) && id == 0xCAFEBABEu, "a bare 0x prefix is refused");
46 check(!parse_model_id("0X", id) && id == 0xCAFEBABEu, "a bare 0X prefix is refused");
44 47
45 Mod mod; 48 Mod mod;
46 std::string error; 49 std::string error;
@@ -53,6 +56,8 @@ int main() {
53 "a condition the runtime cannot honour yet is refused, not ignored"); 56 "a condition the runtime cannot honour yet is refused, not ignored");
54 check(!parse_mod(R"({"archetype_swaps":[{"from":"cs_mandy","to":"0xD7C0CDFF"}]})", "m", mod, error), 57 check(!parse_mod(R"({"archetype_swaps":[{"from":"cs_mandy","to":"0xD7C0CDFF"}]})", "m", mod, error),
55 "a swap of a model with itself is refused"); 58 "a swap of a model with itself is refused");
59 check(!parse_mod(R"({"archetype_swaps":[{"from":"0x","to":"cs_mandy"}]})", "m", mod, error),
60 "a bare 0x prefix in an archetype swap is refused");
56 check(!parse_mod(R"({"enabled":"yes"})", "m", mod, error), "\"enabled\" must be a boolean"); 61 check(!parse_mod(R"({"enabled":"yes"})", "m", mod, error), "\"enabled\" must be a boolean");
57 check(!parse_mod("[1,2]", "m", mod, error), "a manifest that is not an object is refused"); 62 check(!parse_mod("[1,2]", "m", mod, error), "a manifest that is not an object is refused");
58 check(parse_mod("{}", "folder_name", mod, error) && mod.name == "folder_name", "the name defaults to the folder"); 63 check(parse_mod("{}", "folder_name", mod, error) && mod.name == "folder_name", "the name defaults to the folder");
diff --git a/runtime/test/replay_copy_offset_test.cpp b/runtime/test/replay_copy_offset_test.cpp
index 7392344ff..b5f93c102 100644
--- a/runtime/test/replay_copy_offset_test.cpp
+++ b/runtime/test/replay_copy_offset_test.cpp
@@ -310,6 +310,103 @@ int main() {
310 dst_buf = saved_dst; 310 dst_buf = saved_dst;
311 } 311 }
312 312
313 // 6. tile_footprint unaligned staging honors format alignment (8B, 16B, BC1) and 3D slice layout.
314 {
315 const auto saved_src = src_buf, saved_dst = dst_buf;
316 VkDeviceSize scratch_req = 0;
317 vk.copy_scratch = [&](std::uint64_t bytes, VkBuffer& buf, VkDeviceSize& off) {
318 scratch_req = bytes;
319 buf = handle<VkBuffer>(0xA000);
320 off = 256;
321 return true;
322 };
323
324 ResourceBinding rgba16f_img{};
325 rgba16f_img.image = handle<VkImage>(6);
326 rgba16f_img.format = VK_FORMAT_R16G16B16A16_SFLOAT; // 8 bytes/texel
327 rgba16f_img.aspects = VK_IMAGE_ASPECT_COLOR_BIT;
328 rgba16f_img.width = 8;
329 rgba16f_img.height = 4;
330 rgba16f_img.mip_levels = 1;
331 rgba16f_img.array_layers = 1;
332 rgba16f_img.depth = 2;
333 rgba16f_img.volume = true;
334 rgba16f_img.samples = 1;
335
336 ResourceBinding bc1_img{};
337 bc1_img.image = handle<VkImage>(7);
338 bc1_img.format = VK_FORMAT_BC1_RGBA_UNORM_BLOCK; // 8 bytes per 4x4 block
339 bc1_img.aspects = VK_IMAGE_ASPECT_COLOR_BIT;
340 bc1_img.width = 12;
341 bc1_img.height = 8;
342 bc1_img.mip_levels = 1;
343 bc1_img.array_layers = 1;
344 bc1_img.depth = 1;
345 bc1_img.samples = 1;
346
347 const auto resolve_tile = [&](ResourceId id) -> const ResourceBinding* {
348 if (id == 6) return &rgba16f_img;
349 if (id == 7) return &bc1_img;
350 return resolve(id);
351 };
352
353 // 6a. 8-byte 3D texture with bufferOffset = 4 (4-byte aligned, NOT 8-byte aligned): must stage both slices.
354 src_buf.buffer_offset = 0;
355 src_buf.size = 4096;
356 {
357 const CopyLocation tex{6, false, 0, 0, 0, 0, 0, 0};
358 // footprint: width=8, height=4, depth=2, row_pitch=256 (32 texels/row, slice_pitch=1024), offset=4
359 const CopyLocation fp{1, true, 0, 4, 8, 4, 2, 256};
360 CopyTexture copy{tex, 0, 0, 0, fp, true, {0, 0, 0, 4, 2, 2}}; // 4x2x2 texels -> 32B/row, 2 rows, 2 slices = 128B
361 copy.tile_footprint = true;
362 CommandList list;
363 expect(list.copy_texture(copy) && list.close(), "record 8B 3D tile_footprint upload");
364 buffer_copies.clear();
365 b2i_copies.clear();
366 scratch_req = 0;
367 expect(replay(list, VK_NULL_HANDLE, resolve_tile, vk) == ReplayResult::success,
368 "8B 3D tile_footprint upload with offset=4 replays");
369 expect(scratch_req == 128, "8B 3D tile_footprint allocates 4*8 * 2 * 2 = 128 bytes of scratch");
370 expect(buffer_copies.size() == 4, "8B 3D tile_footprint stages 2 rows x 2 slices");
371 expect(buffer_copies.size() == 4 &&
372 buffer_copies[0].srcOffset == 4 && buffer_copies[0].dstOffset == 256 && buffer_copies[0].size == 32 &&
373 buffer_copies[1].srcOffset == 260 && buffer_copies[1].dstOffset == 288 && buffer_copies[1].size == 32 &&
374 buffer_copies[2].srcOffset == 1028 && buffer_copies[2].dstOffset == 320 && buffer_copies[2].size == 32 &&
375 buffer_copies[3].srcOffset == 1284 && buffer_copies[3].dstOffset == 352 && buffer_copies[3].size == 32,
376 "8B 3D tile_footprint row/slice strides match 256B row_pitch and 1024B slice_pitch");
377 expect(b2i_copies.size() == 1 && b2i_copies[0].bufferOffset == 256 &&
378 b2i_copies[0].bufferRowLength == 0 && b2i_copies[0].bufferImageHeight == 0,
379 "8B 3D tile_footprint emits aligned scratch offset and clears row/image height");
380 }
381
382 // 6b. BC1 (8B per 4x4 block) with bufferOffset = 4: must stage 2x2 blocks = 32B, not texels*4.
383 {
384 const CopyLocation tex{7, false, 0, 0, 0, 0, 0, 0};
385 // footprint: width=12 (3 blocks), height=8 (2 blocks), row_pitch=256 (32*8B), offset=4
386 const CopyLocation fp{1, true, 0, 4, 12, 8, 1, 256};
387 CopyTexture copy{tex, 0, 0, 0, fp, true, {0, 0, 0, 8, 8, 1}}; // 2x2 blocks: 16B/row, 2 rows = 32B
388 copy.tile_footprint = true;
389 CommandList list;
390 expect(list.copy_texture(copy) && list.close(), "record BC1 tile_footprint upload");
391 buffer_copies.clear();
392 b2i_copies.clear();
393 scratch_req = 0;
394 expect(replay(list, VK_NULL_HANDLE, resolve_tile, vk) == ReplayResult::success,
395 "BC1 tile_footprint upload with offset=4 replays");
396 expect(scratch_req == 32, "BC1 tile_footprint allocates 2*8 * 2 = 32 bytes of scratch");
397 expect(buffer_copies.size() == 2 &&
398 buffer_copies[0].srcOffset == 4 && buffer_copies[0].dstOffset == 256 && buffer_copies[0].size == 16 &&
399 buffer_copies[1].srcOffset == 260 && buffer_copies[1].dstOffset == 272 && buffer_copies[1].size == 16,
400 "BC1 tile_footprint copies 16B block rows at 256B pitch");
401 expect(b2i_copies.size() == 1 && b2i_copies[0].bufferOffset == 256 && b2i_copies[0].bufferRowLength == 0,
402 "BC1 tile_footprint emits aligned scratch offset");
403 }
404
405 vk.copy_scratch = {};
406 src_buf = saved_src;
407 dst_buf = saved_dst;
408 }
409
313 if (failures) return 1; 410 if (failures) return 1;
314 std::printf("replay_copy_offset: CopyResource and CopyTexture apply ResourceBinding::buffer_offset\n"); 411 std::printf("replay_copy_offset: CopyResource and CopyTexture apply ResourceBinding::buffer_offset\n");
315 return 0; 412 return 0;
diff --git a/runtime/test/replay_query_edges_test.cpp b/runtime/test/replay_query_edges_test.cpp
index 820dc0dc1..1e3da7c29 100644
--- a/runtime/test/replay_query_edges_test.cpp
+++ b/runtime/test/replay_query_edges_test.cpp
@@ -1,6 +1,7 @@
1// Query heap boundaries, resolve helper chunking, arena offsets, query reuse across lists/submissions, and 1// Query heap boundaries, resolve helper chunking, arena offsets, query reuse across lists/submissions, the mesh
2// predication around copies. These edge cases are only reached by GPU tests today; this CPU mock lets CI 2// pool of a statistics query and predication around copies. These edge cases are only reached by GPU tests today;
3// without a GPU check replay planning, emitted commands, destination guards, and pool ownership on submit failure. 3// this CPU mock lets CI without a GPU check replay planning, emitted commands, destination guards, and pool ownership
4// on submit failure.
4// Shader arithmetic and Vulkan entry points are mocked; no driver is loaded. No GPU or game data. 5// Shader arithmetic and Vulkan entry points are mocked; no driver is loaded. No GPU or game data.
5#include "../src/vulkan_backend.h" 6#include "../src/vulkan_backend.h"
6 7
@@ -61,7 +62,10 @@ struct MockReplay {
61 std::vector<Call> copies; 62 std::vector<Call> copies;
62 std::vector<std::pair<VkQueryPool, unsigned>> resets; 63 std::vector<std::pair<VkQueryPool, unsigned>> resets;
63 std::set<VkQueryPool> statistics_pools; 64 std::set<VkQueryPool> statistics_pools;
65 std::set<VkQueryPool> mesh_pools; // pools with the two counters a mesh draw allows (D3D-291)
66 std::set<VkQueryPool> primitives_pools; // the mesh-primitives count of a mesh segment (D3D-MESH-CLIPPING-COUNTER)
64 std::vector<unsigned> chunks; 67 std::vector<unsigned> chunks;
68 std::vector<unsigned> meshes; // statistics_sum.comp's mesh flag, one per chunk
65 std::vector<unsigned> groups; 69 std::vector<unsigned> groups;
66 std::vector<VkBufferCopy> transfers; 70 std::vector<VkBufferCopy> transfers;
67 std::vector<std::string> events; 71 std::vector<std::string> events;
@@ -111,8 +115,12 @@ struct MockReplay {
111 copies.push_back({p, first, count, off, stride}); 115 copies.push_back({p, first, count, off, stride});
112 auto& q = values.at(p); 116 auto& q = values.at(p);
113 expect(first <= q.size() && count <= q.size() - first, "mock query access out of bounds"); 117 expect(first <= q.size() && count <= q.size() - first, "mock query access out of bounds");
118 // A mesh pool counts two counters, not the eleven of the full pool (D3D-291).
119 const unsigned counters = mesh_pools.count(p) ? 2u
120 : primitives_pools.count(p) ? 1u
121 : (stride == statistics_size ? statistics_counters : 1u);
114 for (unsigned i = 0; i < count; ++i) { 122 for (unsigned i = 0; i < count; ++i) {
115 for (unsigned j = 0; j < (stride == statistics_size ? statistics_counters : 1u); ++j) { 123 for (unsigned j = 0; j < counters; ++j) {
116 word(b, off + i * stride + word_size * j, q[first + i][j]); 124 word(b, off + i * stride + word_size * j, q[first + i][j]);
117 } 125 }
118 } 126 }
@@ -239,8 +247,8 @@ struct MockReplay {
239 VkDeviceSize off) { 247 VkDeviceSize off) {
240 helper(false, false, p, f, n, b, off); 248 helper(false, false, p, f, n, b, off);
241 }; 249 };
242 v.sum_statistics = [helper](VkCommandBuffer, VkQueryPool p, VkQueryPool, const std::uint8_t*, unsigned f, 250 v.sum_statistics = [helper](VkCommandBuffer, VkQueryPool p, VkQueryPool, VkQueryPool, const std::uint8_t*,
243 unsigned n, VkBuffer b, VkDeviceSize off) { 251 unsigned f, unsigned n, VkBuffer b, VkDeviceSize off) {
244 helper(true, false, p, f, n, b, off); 252 helper(true, false, p, f, n, b, off);
245 }; 253 };
246 v.resolve_binary_occlusion = [helper](VkCommandBuffer, VkQueryPool p, unsigned f, unsigned n, VkBuffer b, 254 v.resolve_binary_occlusion = [helper](VkCommandBuffer, VkQueryPool p, unsigned f, unsigned n, VkBuffer b,
@@ -286,26 +294,33 @@ void test_helper_chunks() {
286 const VkDescriptorSet*, unsigned, const unsigned*) {}; 294 const VkDescriptorSet*, unsigned, const unsigned*) {};
287 vk.vkCmdPushConstants = +[](VkCommandBuffer, VkPipelineLayout, VkShaderStageFlags, unsigned off, unsigned size, 295 vk.vkCmdPushConstants = +[](VkCommandBuffer, VkPipelineLayout, VkShaderStageFlags, unsigned off, unsigned size,
288 const void*p) { 296 const void*p) {
289 // The count, then statistics_sum.comp's mesh flag (D3D-291), which no segment here sets. 297 // The count, then statistics_sum.comp's mesh flag (D3D-291).
290 expect(off == 0 && size == 2 * sizeof(unsigned), "chunk push constants"); 298 expect(off == 0 && size == 2 * sizeof(unsigned), "chunk push constants");
291 expect(static_cast<const unsigned *>(p)[1] == 0, "chunk push constants: no mesh segment"); 299 MockReplay::current->chunks.push_back(static_cast<const unsigned *>(p)[0]);
292 MockReplay::current->chunks.push_back(*static_cast<const unsigned *>(p)); 300 MockReplay::current->meshes.push_back(static_cast<const unsigned *>(p)[1]);
293 }; 301 };
294 vk.vkCmdDispatch = +[](VkCommandBuffer, unsigned x, unsigned y, unsigned z) { 302 vk.vkCmdDispatch = +[](VkCommandBuffer, unsigned x, unsigned y, unsigned z) {
295 auto& c = *MockReplay::current; 303 auto& c = *MockReplay::current;
296 c.groups.push_back(x); 304 c.groups.push_back(x);
297 expect(y == 1 && z == 1, "dispatch dimensions"); 305 expect(y == 1 && z == 1, "dispatch dimensions");
298 auto n = c.chunks.back(); 306 auto n = c.chunks.back();
307 const bool mesh = c.meshes.back() != 0;
299 if (c.mode == MockReplay::binary) { 308 if (c.mode == MockReplay::binary) {
300 for (unsigned i = 0; i < n; ++i) { 309 for (unsigned i = 0; i < n; ++i) {
301 c.word(VK_NULL_HANDLE, word_size * i, c.word(VK_NULL_HANDLE, word_size * i) != 0); 310 c.word(VK_NULL_HANDLE, word_size * i, c.word(VK_NULL_HANDLE, word_size * i) != 0);
302 } 311 }
303 } else { 312 } else {
304 for (unsigned j = 0; j < (c.mode == MockReplay::statistics ? statistics_counters : 1u); ++j) { 313 const bool statistics = c.mode == MockReplay::statistics;
305 unsigned width = c.mode == MockReplay::statistics ? statistics_counters : 1; 314 for (unsigned j = 0; j < (statistics ? statistics_counters : 1u); ++j) {
315 // A mesh segment counts the mesh-primitives count, the fragment and the compute invocations,
316 // and they land in CInvocations, PSInvocations and CSInvocations (statistics_sum.comp, D3D-291 and
317 // D3D-MESH-CLIPPING-COUNTER).
318 if (mesh && statistics && j != 5 && j != 7 && j != 10) continue;
319 const unsigned source = mesh && j == 10 ? 8 : j;
320 unsigned width = statistics ? statistics_counters : 1;
306 auto total = c.word(VK_NULL_HANDLE, word_size * j); 321 auto total = c.word(VK_NULL_HANDLE, word_size * j);
307 for (unsigned i = 0; i < n; ++i) { 322 for (unsigned i = 0; i < n; ++i) {
308 total += c.word(VK_NULL_HANDLE, word_size * (width * (i + 1) + j)); 323 total += c.word(VK_NULL_HANDLE, word_size * (width * (i + 1) + source));
309 } 324 }
310 c.word(VK_NULL_HANDLE, word_size * j, total); 325 c.word(VK_NULL_HANDLE, word_size * j, total);
311 } 326 }
@@ -338,6 +353,7 @@ void test_helper_chunks() {
338 auto expected = c.buffers[dst]; 353 auto expected = c.buffers[dst];
339 c.copies.clear(); 354 c.copies.clear();
340 c.chunks.clear(); 355 c.chunks.clear();
356 c.meshes.clear();
341 c.groups.clear(); 357 c.groups.clear();
342 c.transfers.clear(); 358 c.transfers.clear();
343 if (mode == MockReplay::binary) { 359 if (mode == MockReplay::binary) {
@@ -348,7 +364,8 @@ void test_helper_chunks() {
348 } 364 }
349 } else { 365 } else {
350 if (mode == MockReplay::statistics) { 366 if (mode == MockReplay::statistics) {
351 helper.sum_statistics({}, qp, VK_NULL_HANDLE, nullptr, first, n, dst, output_offset); 367 helper.sum_statistics({}, qp, VK_NULL_HANDLE, VK_NULL_HANDLE, nullptr, first, n, dst,
368 output_offset);
352 } else { 369 } else {
353 helper.sum({}, qp, first, n, dst, output_offset); 370 helper.sum({}, qp, first, n, dst, output_offset);
354 } 371 }
@@ -363,6 +380,8 @@ void test_helper_chunks() {
363 expect(c.buffers[dst] == expected, "numeric helper result and destination guard bytes"); 380 expect(c.buffers[dst] == expected, "numeric helper result and destination guard bytes");
364 expect(c.chunks == (extra ? std::vector<unsigned>{capacity, 1} 381 expect(c.chunks == (extra ? std::vector<unsigned>{capacity, 1}
365 : std::vector<unsigned>{capacity}), "exact chunk sizes"); 382 : std::vector<unsigned>{capacity}), "exact chunk sizes");
383 expect(std::all_of(c.meshes.begin(), c.meshes.end(), [](unsigned m) { return m == 0; }),
384 "no mesh segment in these chunks");
366 expect(c.copies.size() == 1 + extra && c.copies[0].first == first && (!extra 385 expect(c.copies.size() == 1 + extra && c.copies[0].first == first && (!extra
367 || c.copies[1].first == first + capacity), "chunk query indices end exactly at heap boundary"); 386 || c.copies[1].first == first + capacity), "chunk query indices end exactly at heap boundary");
368 std::vector<unsigned> expected_groups(1 + extra, 1); 387 std::vector<unsigned> expected_groups(1 + extra, 1);
@@ -388,10 +407,53 @@ void test_helper_chunks() {
388 expect(c.word(dst, output_offset) == reset_sum, "sum accumulator reset between calls"); 407 expect(c.word(dst, output_offset) == reset_sum, "sum accumulator reset between calls");
389 c.mode = MockReplay::statistics; 408 c.mode = MockReplay::statistics;
390 c.values[qp][first_query].fill(reset_counter); 409 c.values[qp][first_query].fill(reset_counter);
391 helper.sum_statistics({}, qp, VK_NULL_HANDLE, nullptr, first_query, 1, dst, output_offset); 410 helper.sum_statistics({}, qp, VK_NULL_HANDLE, VK_NULL_HANDLE, nullptr, first_query, 1, dst, output_offset);
392 for (unsigned j = 0; j < statistics_counters; ++j) { 411 for (unsigned j = 0; j < statistics_counters; ++j) {
393 expect(c.word(dst, output_offset + word_size * j) == reset_counter, "statistics accumulator reset"); 412 expect(c.word(dst, output_offset + word_size * j) == reset_counter, "statistics accumulator reset");
394 } 413 }
414
415 // A statistics query that holds a mesh draw is split so the mesh segments run in the mesh pool (D3D-291). That
416 // pool counts the fragment and compute invocations only, so the sum copies them into the PSInvocations and
417 // CSInvocations fields of their record, and the clipping fields a mesh draw cannot count stay 0.
418 {
419 constexpr unsigned mesh_segments = 3;
420 constexpr std::uint64_t fragment = 40;
421 constexpr std::uint64_t compute = 7;
422 constexpr std::uint64_t generated = 5; // the primitives a mesh segment emits (D3D-MESH-CLIPPING-COUNTER)
423 const std::uint8_t mesh_flags[mesh_segments] = {1, 1, 1};
424 auto mesh_pool = handle<VkQueryPool>(3);
425 auto primitives_pool = handle<VkQueryPool>(4);
426 c.mesh_pools.insert(mesh_pool);
427 c.primitives_pools.insert(primitives_pool);
428 c.values[mesh_pool].resize(mesh_segments);
429 c.values[primitives_pool].resize(mesh_segments);
430 std::uint64_t fragment_total = 0, compute_total = 0, generated_total = 0;
431 for (unsigned i = 0; i < mesh_segments; ++i) {
432 c.values[mesh_pool][i][0] = fragment + i; // the fragment shader invocations
433 c.values[mesh_pool][i][1] = compute + i; // the compute shader invocations
434 c.values[primitives_pool][i][0] = generated + i; // the primitives the mesh shader emitted
435 fragment_total += c.values[mesh_pool][i][0];
436 compute_total += c.values[mesh_pool][i][1];
437 generated_total += c.values[primitives_pool][i][0];
438 }
439 c.buffers[dst].assign(buffer_bytes, guard_byte);
440 auto expected = c.buffers[dst];
441 c.copies.clear();
442 c.chunks.clear();
443 c.meshes.clear();
444 c.groups.clear();
445 c.transfers.clear();
446 helper.sum_statistics({}, qp, mesh_pool, primitives_pool, mesh_flags, 0, mesh_segments, dst, output_offset);
447 for (unsigned j = 0; j < statistics_counters; ++j) {
448 const std::uint64_t v = j == 5 ? generated_total : j == 7 ? fragment_total : j == 10 ? compute_total : 0;
449 std::memcpy(expected.data() + output_offset + word_size * j, &v, word_size);
450 }
451 expect(c.buffers[dst] == expected,
452 "a mesh segment fills CInvocations, PSInvocations and CSInvocations, and no other field");
453 expect(c.meshes.size() == 1 && c.meshes[0] == 1, "the mesh chunk says its segments are mesh ones");
454 expect(c.copies.size() == 2 && c.copies[0].pool == mesh_pool && c.copies[1].pool == primitives_pool,
455 "the mesh segment is read from the mesh pool and the mesh-primitives pool");
456 }
395} 457}
396 458
397void test_query_state() { 459void test_query_state() {
diff --git a/runtime/test/replay_query_predication_test.cpp b/runtime/test/replay_query_predication_test.cpp
index 3ef0b484a..87056a499 100644
--- a/runtime/test/replay_query_predication_test.cpp
+++ b/runtime/test/replay_query_predication_test.cpp
@@ -127,8 +127,8 @@ int main() {
127 vk.query_pool = [&](QueryHeapId id) -> QueryPool* { 127 vk.query_pool = [&](QueryHeapId id) -> QueryPool* {
128 return id == 1 ? &heap : id == 6 ? &statistics_heap : nullptr; 128 return id == 1 ? &heap : id == 6 ? &statistics_heap : nullptr;
129 }; 129 };
130 vk.sum_statistics = [](VkCommandBuffer, VkQueryPool pool, VkQueryPool, const std::uint8_t*, std::uint32_t first, 130 vk.sum_statistics = [](VkCommandBuffer, VkQueryPool pool, VkQueryPool, VkQueryPool, const std::uint8_t*,
131 std::uint32_t count, VkBuffer, VkDeviceSize) { 131 std::uint32_t first, std::uint32_t count, VkBuffer, VkDeviceSize) {
132 g_trace->events.push_back(query_event("sum_statistics", pool, first) + "+" + std::to_string(count)); 132 g_trace->events.push_back(query_event("sum_statistics", pool, first) + "+" + std::to_string(count));
133 }; 133 };
134 vk.resolve_binary_occlusion = [](VkCommandBuffer, VkQueryPool, std::uint32_t, std::uint32_t, VkBuffer, 134 vk.resolve_binary_occlusion = [](VkCommandBuffer, VkQueryPool, std::uint32_t, std::uint32_t, VkBuffer,
@@ -685,14 +685,18 @@ int main() {
685 auto segments = std::make_shared<OcclusionSegmentPool>(); 685 auto segments = std::make_shared<OcclusionSegmentPool>();
686 segments->pool = handle<VkQueryPool>(9); 686 segments->pool = handle<VkQueryPool>(9);
687 segments->mesh_pool = handle<VkQueryPool>(10); 687 segments->mesh_pool = handle<VkQueryPool>(10);
688 segments->primitives_pool = handle<VkQueryPool>(11);
688 segments->mesh = prepared.statistics_mesh; 689 segments->mesh = prepared.statistics_mesh;
689 segments->destroy = mock_destroy_pool; 690 segments->destroy = mock_destroy_pool;
690 QueryReplay queries; 691 QueryReplay queries;
691 expect(queries.plan(prepared, {}, 0, true, segments, 0) == ReplayResult::success, "plan mixed list"); 692 expect(queries.plan(prepared, {}, 0, true, segments, 0) == ReplayResult::success, "plan mixed list");
692 expect(prepared.statistics_mesh_pool == handle<VkQueryPool>(10), "mixed list: the mesh pool is the list's"); 693 expect(prepared.statistics_mesh_pool == handle<VkQueryPool>(10), "mixed list: the mesh pool is the list's");
694 expect(prepared.statistics_primitives_pool == handle<VkQueryPool>(11),
695 "mixed list: the mesh-primitives pool is the list's");
693 expect(q[6].resolves.size() == 1 && q[6].resolves[0].sum && q[6].resolves[0].first == 3 && 696 expect(q[6].resolves.size() == 1 && q[6].resolves[0].sum && q[6].resolves[0].first == 3 &&
694 q[6].resolves[0].count == 1 && q[6].resolves[0].mesh_pool == handle<VkQueryPool>(10) && 697 q[6].resolves[0].count == 1 && q[6].resolves[0].mesh_pool == handle<VkQueryPool>(10) &&
695 q[6].resolves[0].mesh && q[6].resolves[0].mesh[3] == 1, 698 q[6].resolves[0].primitives_pool == handle<VkQueryPool>(11) && q[6].resolves[0].mesh &&
699 q[6].resolves[0].mesh[3] == 1,
696 "mixed list: the mesh-only query's resolve sums its one mesh segment"); 700 "mixed list: the mesh-only query's resolve sums its one mesh segment");
697 expect(queries.needs_statistics_sum, "mixed list: the statistics sum helper is needed"); 701 expect(queries.needs_statistics_sum, "mixed list: the statistics sum helper is needed");
698 702
@@ -755,6 +759,21 @@ int main() {
755 expect(q[3].statistics_first == 1 && q[3].statistics_count == 3, "overlap-mesh: query 1 sums segments 1-3"); 759 expect(q[3].statistics_first == 1 && q[3].statistics_count == 3, "overlap-mesh: query 1 sums segments 1-3");
756 } 760 }
757 761
762 // 17. D3D-291: the pool a mesh draw runs in must not enable a counter
763 // VUID-vkCmdDrawMeshTasksEXT-pipelineStatistics-07076 forbids, or the validation layer reports the VUID on
764 // every DispatchMesh inside a statistics query. The VUID leaves the fragment and compute invocations
765 // allowed, and those are the two the mesh pool counts; the nine it names are the rest of the eleven.
766 {
767 constexpr VkQueryPipelineStatisticFlags all_counters = 0x7ff; // the counters of a D3D12 statistics heap
768 expect((kMeshStatisticsFlags & kForbiddenMeshStatisticsFlags) == 0,
769 "the mesh pool enables none of the counters the VUID forbids");
770 expect((all_counters & ~kForbiddenMeshStatisticsFlags) == kMeshStatisticsFlags,
771 "the mesh pool counts every counter the VUID leaves allowed");
772 expect(kMeshStatisticsFlags == (VK_QUERY_PIPELINE_STATISTIC_FRAGMENT_SHADER_INVOCATIONS_BIT |
773 VK_QUERY_PIPELINE_STATISTIC_COMPUTE_SHADER_INVOCATIONS_BIT),
774 "the mesh pool counts the fragment and compute invocations");
775 }
776
758 if (failures) return 1; 777 if (failures) return 1;
759 std::puts("replay_query_predication_test: query resolves suspend conditional rendering around fills, copies and dispatches"); 778 std::puts("replay_query_predication_test: query resolves suspend conditional rendering around fills, copies and dispatches");
760 return 0; 779 return 0;
diff --git a/runtime/test/replay_uav_clear_offset_test.cpp b/runtime/test/replay_uav_clear_offset_test.cpp
index 35818fe8e..b315ed30d 100644
--- a/runtime/test/replay_uav_clear_offset_test.cpp
+++ b/runtime/test/replay_uav_clear_offset_test.cpp
@@ -173,6 +173,18 @@ int main() {
173 range.buffer_offset = UINT64_MAX - 2; 173 range.buffer_offset = UINT64_MAX - 2;
174 expect(run({1, true, VK_FORMAT_R8_UINT, 1, 2, 1, 0, 0, 1}) == ReplayResult::invalid_clear && writes.empty(), 174 expect(run({1, true, VK_FORMAT_R8_UINT, 1, 2, 1, 0, 0, 1}) == ReplayResult::invalid_clear && writes.empty(),
175 "backing range overflow is rejected before scratch allocation or emission"); 175 "backing range overflow is rejected before scratch allocation or emission");
176 // Misaligned backing buffer_offset must be rejected for multi-byte elements (e.g., e > 4 violates
177 // VUID-vkCmdUpdateBuffer-dstOffset-00032; e == 2/4 would byte-swap/rotate elements in vkCmdFillBuffer).
178 range.buffer_offset = at + 2;
179 expect(run({1, true, VK_FORMAT_R32G32B32A32_UINT, 0, 32, 16, 0, 0, 1}) == ReplayResult::unsupported && writes.empty(),
180 "misaligned backing buffer_offset for 16-byte element clear is rejected before vkCmdUpdateBuffer");
181 expect(run({1, true, VK_FORMAT_R32_UINT, 0, 16, 4, 0, 0, 1}) == ReplayResult::unsupported && writes.empty(),
182 "misaligned backing buffer_offset for 4-byte element clear is rejected before vkCmdFillBuffer");
183 range.buffer_offset = at + 1;
184 expect(run({1, true, VK_FORMAT_R16_UINT, 0, 16, 2, 0, 0, 1}) == ReplayResult::unsupported && writes.empty(),
185 "odd backing buffer_offset for 2-byte element clear is rejected before vkCmdFillBuffer");
186 expect(run({1, true, VK_FORMAT_R8_UINT, 0, 16, 1, 0, 0, 1}) == ReplayResult::success,
187 "odd backing buffer_offset for 1-byte R8 element clear still replays");
176 range.buffer_offset = at; 188 range.buffer_offset = at;
177 vk.copy_scratch = {}; 189 vk.copy_scratch = {};
178 190
diff --git a/runtime/test/retire_tickets_test.cpp b/runtime/test/retire_tickets_test.cpp
index 8eb5e02d0..f1dc836de 100644
--- a/runtime/test/retire_tickets_test.cpp
+++ b/runtime/test/retire_tickets_test.cpp
@@ -30,6 +30,24 @@ int main() {
30 queue_one_destroyed = true; 30 queue_one_destroyed = true;
31 if (tickets.completed(query) != 4 || queried_destroyed) return 4; 31 if (tickets.completed(query) != 4 || queried_destroyed) return 4;
32 32
33 // pending_through() must coalesce repeated submissions on the same queue to the highest
34 // timeline value, omit idle queues, and exclude tickets past the requested cutoff.
35 tickets.record(5, 1, 10);
36 tickets.record(6, 2, 20);
37 tickets.record(7, 1, 12);
38 tickets.record(8, 1, 15);
39 tickets.record(9, 2, 25);
40 tickets.queue_idle(2);
41 const auto wait_list = tickets.pending_through(7);
42 if (wait_list.size() != 1 || wait_list[0].first != 1 || wait_list[0].second != 12) return 5;
43
44 // A non-monotonic ticket must not move the completed prefix backward.
45 done[1] = 15;
46 if (tickets.completed(query) != 9) return 6;
47 tickets.record(3, 1, 16);
48 done[1] = 16;
49 if (tickets.completed(query) != 9) return 7;
50
33 std::puts("out-of-order queue completion kept the retirement prefix safe"); 51 std::puts("out-of-order queue completion kept the retirement prefix safe");
34 return 0; 52 return 0;
35} 53}
diff --git a/runtime/test/shader_library_test.cpp b/runtime/test/shader_library_test.cpp
index bf7ad80d1..55105d987 100644
--- a/runtime/test/shader_library_test.cpp
+++ b/runtime/test/shader_library_test.cpp
@@ -8,6 +8,7 @@
8#include <filesystem> 8#include <filesystem>
9#include <fstream> 9#include <fstream>
10#include <initializer_list> 10#include <initializer_list>
11#include <limits>
11#include <sstream> 12#include <sstream>
12#include <string> 13#include <string>
13#include <vector> 14#include <vector>
@@ -570,6 +571,10 @@ int main() {
570 broken.resize(100); // truncated 571 broken.resize(100); // truncated
571 CHECK(!zlib_inflate(broken, out)); 572 CHECK(!zlib_inflate(broken, out));
572 CHECK(!zlib_inflate(dynamic, out, 599)); // larger than the limit 573 CHECK(!zlib_inflate(dynamic, out, 599)); // larger than the limit
574 const auto max_limit = (std::numeric_limits<std::size_t>::max)();
575 CHECK(zlib_inflate(stored, out, max_limit) && out.size() == 40);
576 CHECK(zlib_inflate(fixed, out, max_limit) && out == bytes("hello hello hello leonida"));
577 CHECK(zlib_inflate(dynamic, out, max_limit) && out == skewed(600));
573 CHECK(!zlib_inflate(bytes("not zlib"), out)); 578 CHECK(!zlib_inflate(bytes("not zlib"), out));
574 579
575 Json json; 580 Json json;
@@ -642,7 +647,9 @@ int main() {
642 "{\"semantic\": \"TEXCOORD\", \"semantic_index\": 3, \"register\": -1, \"system_value\": 0, " 647 "{\"semantic\": \"TEXCOORD\", \"semantic_index\": 3, \"register\": -1, \"system_value\": 0, "
643 "\"component_type\": \"float\"}]},\n" 648 "\"component_type\": \"float\"}]},\n"
644 " \"ps_out\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << hash << "\", \"inputs\": [0, 1, 28, 29], " 649 " \"ps_out\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << hash << "\", \"inputs\": [0, 1, 28, 29], "
645 "\"outputs\": [0, 2], \"f16_halves\": {\"0\": [28, 29], \"bad\": [1], \"7\": [20, 21]}},\n" 650 "\"outputs\": [0, 2], \"f16_halves\": {\"0\": [28, 29], \"bad\": [1], \"-1\": [1, 2], "
651 "\"+2\": [3, 4], \" 3\": [5, 6], \"4294967296\": [9, 10], \"99999999999999999999\": [11, 12], "
652 "\"7\": [20, 21]}},\n"
646 " \"ps_native\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << hash2 << "\", \"wave64\": true, " 653 " \"ps_native\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << hash2 << "\", \"wave64\": true, "
647 "\"subgroup_size\": 64},\n" 654 "\"subgroup_size\": 64},\n"
648 " \"cs_emulated\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << hash2 << "\", \"wave64\": true, " 655 " \"cs_emulated\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << hash2 << "\", \"wave64\": true, "
diff --git a/runtime/test/shaders/build.py b/runtime/test/shaders/build.py
index c9fd70e4a..03a7ecd22 100644
--- a/runtime/test/shaders/build.py
+++ b/runtime/test/shaders/build.py
@@ -124,8 +124,6 @@ def cs_fssm_extra(path):
124 124
125 125
126def shader_source(name): 126def shader_source(name):
127 if name == "ps_mullit":
128 return "../../../tests/semantic/fixtures/ps_mullit"
129 return "vs_clip" if name in CLIP_CASES else name 127 return "vs_clip" if name in CLIP_CASES else name
130 128
131 129
@@ -216,8 +214,7 @@ def main():
216 out = Path(sys.argv[1]) 214 out = Path(sys.argv[1])
217 available = sorted({p.stem for p in Path(HERE).glob("*.asm")} | CLIP_CASES.keys()) 215 available = sorted({p.stem for p in Path(HERE).glob("*.asm")} | CLIP_CASES.keys())
218 names = sys.argv[2:] or available 216 names = sys.argv[2:] or available
219 # mullit_readback.py uses the CPU semantic fixture as an explicit build target. 217 unknown = sorted(set(names) - set(available))
220 unknown = sorted(set(names) - set(available) - {"ps_mullit"})
221 if unknown: 218 if unknown:
222 sys.exit("Unknown test shaders: " + ", ".join(unknown)) 219 sys.exit("Unknown test shaders: " + ", ".join(unknown))
223 skipped = [n for n in names if n.startswith("ms_")] 220 skipped = [n for n in names if n.startswith("ms_")]
diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py
index 7b3777287..7b4bcdf13 100644
--- a/runtime/test/shaders/check.py
+++ b/runtime/test/shaders/check.py
@@ -358,6 +358,33 @@ def heap_init_env():
358 return {"VKC_HEAP_INIT": path, "VKC_OUT_WORDS": str(len(HEAP_INIT_FILE) // 4)} 358 return {"VKC_HEAP_INIT": path, "VKC_OUT_WORDS": str(len(HEAP_INIT_FILE) // 4)}
359 359
360 360
361def shift64_words():
362 """cs_w32_shift64: input heap and full expected readback, using Python integers as the oracle."""
363 values = (0, 1, 0xFFFFFFFF, 0x100000000, 0x7FFFFFFFFFFFFFFF,
364 0x8000000000000000, 0xFFFFFFFFFFFFFFFF, 0x8123456789ABCDEF)
365 counts = (0, 1, 31, 32, 33, 63, 64, 65)
366 inputs, results = [], []
367 for value in values:
368 for count in counts:
369 inputs.extend((value & 0xFFFFFFFF, value >> 32, count, 0xA5A5A5A5))
370 signed = value if value < (1 << 63) else value - (1 << 64)
371 shift = count & 63
372 for result in (value << shift, value >> shift, signed >> shift):
373 results.extend((result & 0xFFFFFFFF, (result >> 32) & 0xFFFFFFFF))
374 return [0xEEEEEEEE] * len(results) + inputs, results + inputs
375
376
377def shift64_test(tools, spirv, env=None):
378 """Verify all three 64-bit shifts for 64 memory-fed cases, including the untouched input records."""
379 initial, expected = shift64_words()
380 with tempfile.TemporaryDirectory(prefix="leonida-shift64-") as tmp:
381 path = Path(tmp) / "input.bin"
382 path.write_bytes(struct.pack(f"<{len(initial)}I", *initial))
383 child = dict(os.environ if env is None else env, VKC_HEAP_INIT=str(path))
384 child.setdefault("VKC_SUBGROUP_SIZE", str(subgroup_size(spirv, "cs_w32_shift64") or 32))
385 return dump_test(tools, spirv, "cs_w32_shift64", expected, len(expected), child)
386
387
361# cs_user_sgprs.asm: vk_compute_test puts these words in s4..s7 and the shader stores them back. 388# cs_user_sgprs.asm: vk_compute_test puts these words in s4..s7 and the shader stores them back.
362USER_SGPRS = [0x4F000000, 0xDEADBEEF, 7, 0xFFFFFFFF] 389USER_SGPRS = [0x4F000000, 0xDEADBEEF, 7, 0xFFFFFFFF]
363USER_SGPRS_ENV = {"VKC_SGPRS": ",".join(hex(w) for w in USER_SGPRS)} 390USER_SGPRS_ENV = {"VKC_SGPRS": ",".join(hex(w) for w in USER_SGPRS)}
@@ -597,6 +624,17 @@ STORE_WORDS = {
597 # 3D image atomics: the data register afterwards (sint image) and the six texels afterwards (volume) 624 # 3D image atomics: the data register afterwards (sint image) and the six texels afterwards (volume)
598 "cs_imgatomic3d": ({}, dict(enumerate([0x101, 0xDB, 0xF4, 0xCE, 0xE6, 0xFF])), 625 "cs_imgatomic3d": ({}, dict(enumerate([0x101, 0xDB, 0xF4, 0xCE, 0xE6, 0xFF])),
599 {57: 0x111, 19: 3, 44: 0xF4, 6: 0xD00D, 30: 0xE6, 39: 0x10}), 626 {57: 0x111, 19: 3, 44: 0xF4, 6: 0xD00D, 30: 0xE6, 39: 0x10}),
627 # GPU-IMG-ATOMIC-EXT: swap, inc, dec, fmin, fmax and fcmpswap. The 2D cases' texels afterwards (uint image, with the
628 # four that all 64 threads hit at 40..43), the data registers afterwards (sint image: 2D cases at 0..20, 3D cases
629 # at 32..37) and the 3D cases' texels afterwards (volume)
630 "cs_imgatomic_ext": ({0: 0x12345678, 1: 0xABCDEF01, 2: 0, 3: 0x68, 4: 0, 5: 0x68, 6: 0x32, 7: 9, 8: 0x6D,
631 9: 0x3FC00000, 10: 0xC0400000, 11: 0x40200000, 12: 0x3FC00000, 13: 0x3FC00000,
632 14: 0x3FC00000, 15: 0x40490FDB, 16: 0x3FC00000, 17: 0x3F800000, 18: 0x7FC00000,
633 19: 0x78, 20: 0x77, 40: 0xCC, 41: 0x4D, 42: 0x427C0000, 43: 0xC27C0000},
634 {0: 0x64, 1: 0xABCDEF01, 2: 0x66, 3: 0x67, 4: 0x68, 5: 0x69, 6: 0x6A, 7: 0, 8: 0x1F4,
635 **dict.fromkeys(range(9, 17), 0x3FC00000), 17: 0, 18: 0x7FC00000, 19: 0x77, 20: 0x78,
636 32: 0x101, 33: 0xDB, 34: 0xF4, 35: 0x3FC00000, 36: 0x3FC00000, 37: 0x3FC00000},
637 {6: 0xC0400000, 19: 0xDC, 30: 0x40200000, 39: 0x40490FDB, 44: 0x64, 57: 0x0BADF00D}),
600 # image_get_resinfo on a 16x4 image with five levels: (width, height, depth, levels) of levels 0, 1 and 3, then 638 # image_get_resinfo on a 16x4 image with five levels: (width, height, depth, levels) of levels 0, 1 and 3, then
601 # width and height of level 2 and an untouched register, height and levels of level 1, the levels alone, and 639 # width and height of level 2 and an untouched register, height and levels of level 1, the levels alone, and
602 # level 5, past the last (2D depth 0 and the past-the-end zeros measured on RDNA2, SHADER-388) 640 # level 5, past the last (2D depth 0 and the past-the-end zeros measured on RDNA2, SHADER-388)
@@ -1842,6 +1880,7 @@ def main():
1842 expected_words=USER_SGPRS_WORDS, env=USER_SGPRS_ENV))) 1880 expected_words=USER_SGPRS_WORDS, env=USER_SGPRS_ENV)))
1843 results.append(("cs_heap_init", compute_test(tools, spirv, "cs_heap_init", "1", "dump", 1881 results.append(("cs_heap_init", compute_test(tools, spirv, "cs_heap_init", "1", "dump",
1844 expected_words=HEAP_INIT_EXPECTED, env=heap_init_env()))) 1882 expected_words=HEAP_INIT_EXPECTED, env=heap_init_env())))
1883 results.append(("cs_w32_shift64", shift64_test(tools, spirv)))
1845 results.append(("cs_cvt_f32_sat", cvt_f32_sat_test(tools, spirv))) 1884 results.append(("cs_cvt_f32_sat", cvt_f32_sat_test(tools, spirv)))
1846 results.append(("cs_fma_fused", fma_fused_test(tools, spirv))) 1885 results.append(("cs_fma_fused", fma_fused_test(tools, spirv)))
1847 results.append(("cs_cvt_pk_u8", compute_test(tools, spirv, "cs_cvt_pk_u8", "1", "dump", 1886 results.append(("cs_cvt_pk_u8", compute_test(tools, spirv, "cs_cvt_pk_u8", "1", "dump",
@@ -1857,7 +1896,8 @@ def main():
1857 results.append(("ms_wave_info_s3", mesh_w64x_test(tools, spirv, "ms_wave_info_s3"))) 1896 results.append(("ms_wave_info_s3", mesh_w64x_test(tools, spirv, "ms_wave_info_s3")))
1858 with tempfile.TemporaryDirectory(prefix="leonida-mesh-") as tmp: 1897 with tempfile.TemporaryDirectory(prefix="leonida-mesh-") as tmp:
1859 results.append(("ms_v5_workgroup", mesh_v5_test(tools, spirv, Path(tmp) / "groups.raw"))) 1898 results.append(("ms_v5_workgroup", mesh_v5_test(tools, spirv, Path(tmp) / "groups.raw")))
1860 for name, args in (("cs_imgstore", []), ("cs_imgload", ["load"]), ("cs_imgload_tfe", ["load"]), 1899 for name, args in (("cs_imgstore", []), ("cs_imgstore_cube", ["cube"]), ("cs_imgload", ["load"]),
1900 ("cs_imgload_tfe", ["load"]),
1861 ("cs_imgload_d16", ["load-d16"]), ("cs_imgload_d16_tfe", ["load-d16"]), 1901 ("cs_imgload_d16", ["load-d16"]), ("cs_imgload_d16_tfe", ["load-d16"]),
1862 ("cs_sample_lz_int_d16", ["load-d16"])): 1902 ("cs_sample_lz_int_d16", ["load-d16"])):
1863 code, out = run(os.path.join(tools, "vk_store_test" + EXE), os.path.join(spirv, name + ".spv"), *args) 1903 code, out = run(os.path.join(tools, "vk_store_test" + EXE), os.path.join(spirv, name + ".spv"), *args)
diff --git a/runtime/test/shaders/cs_div_fmas_f64.asm b/runtime/test/shaders/cs_div_fmas_f64.asm
index 41b594752..dfede7187 100644
--- a/runtime/test/shaders/cs_div_fmas_f64.asm
+++ b/runtime/test/shaders/cs_div_fmas_f64.asm
@@ -4,7 +4,8 @@
4; fma(a, a, c) = 2^-60 = 0x3c300000_00000000 fused; rounding a*a first gives 1 + 2^-29 and a result of 0 ("split"). 4; fma(a, a, c) = 2^-60 = 0x3c300000_00000000 fused; rounding a*a first gives 1 + 2^-29 and a result of 0 ("split").
5; out[0..1] = 0x00000000 0x3c300000 (split: 0x00000000 0x00000000). Under --fma khr (LEONIDA_FMA=khr) the translator 5; out[0..1] = 0x00000000 0x3c300000 (split: 0x00000000 0x00000000). Under --fma khr (LEONIDA_FMA=khr) the translator
6; emits OpFmaKHR on doubles (feature shaderFmaFloat64) and only the fused words pass; under the default GLSL Fma a 6; emits OpFmaKHR on doubles (feature shaderFmaFloat64) and only the fused words pass; under the default GLSL Fma a
7; driver may split (NVIDIA RTX 4090, 621.24, does). 7; driver may split. The operands here are literals, so a driver that folds the constant Fma while compiling can
8; round it twice: NVIDIA RTX 4090 (621.24) does, while the same values as run-time operands are fused there.
8s_mov_b64 vcc, 0 9s_mov_b64 vcc, 0
9v_mov_b32 v0, 0x00400000 10v_mov_b32 v0, 0x00400000
10v_mov_b32 v1, 0x3ff00000 11v_mov_b32 v1, 0x3ff00000
diff --git a/runtime/test/shaders/cs_div_fmas_f64_rt.asm b/runtime/test/shaders/cs_div_fmas_f64_rt.asm
new file mode 100644
index 000000000..cf95b23bb
--- /dev/null
+++ b/runtime/test/shaders/cs_div_fmas_f64_rt.asm
@@ -0,0 +1,18 @@
1; group: 1,1,1
2; rsrc2: 0x8090
3; cs_div_fmas_f64 with its operands read at run time: s4..s7 hold a = 1 + 2^-30 (0x3ff00000_00400000) and
4; c = -(1 + 2^-29) (0xbff00000_00800000), seeded by vk_compute_test's VKC_SGPRS, so the driver cannot fold the Fma
5; while compiling the pipeline. v_div_fmas_f64 with VCC = 0 is fma(a, a, c) = 2^-60 with one rounding, 0 with two.
6; Run: VKC_SGPRS=0x00400000,0x3ff00000,0x00800000,0xbff00000 vk_compute_test cs_div_fmas_f64_rt.spv 1 dump
7; out[0..1] = 0x00000000 0x3c300000 (split: 0x00000000 0x00000000). Measured fused under the default GLSL Fma on the
8; NVIDIA RTX 4090 (621.24), RTX 3070 (621.01) and RTX 5060 Laptop (621.24), all of which except the 5060 split the
9; all-constant cs_div_fmas_f64.
10s_mov_b64 vcc, 0
11v_mov_b32 v0, s4
12v_mov_b32 v1, s5
13v_mov_b32 v2, s6
14v_mov_b32 v3, s7
15v_div_fmas_f64 v[4:5], v[0:1], v[0:1], v[2:3]
16v_mov_b32 v6, 0
17buffer_store_dwordx2 v[4:5], v6, s[0:3], 0 offen
18s_endpgm
diff --git a/runtime/test/shaders/cs_imgatomic_ext.asm b/runtime/test/shaders/cs_imgatomic_ext.asm
new file mode 100644
index 000000000..e58ecbcb6
--- /dev/null
+++ b/runtime/test/shaders/cs_imgatomic_ext.asm
@@ -0,0 +1,313 @@
1; The six image atomics that cs_imgatomic.asm and cs_imgatomic3d.asm don't run: image_atomic_swap, inc, dec, fmin, fmax
2; and fcmpswap, on the 2D r32 uint image (binding 4) and the 3D r32 uint volume (binding 7) (GPU-IMG-ATOMIC-EXT).
3; RDNA2 ISA (MIMG), M = the texel before the op, D = the data register, C = the comparand (fcmpswap's second data
4; register): swap writes D; inc writes (M >= D) ? 0 : M + 1 and dec (M == 0 || M > D) ? D : M - 1, both compares
5; unsigned (cases 19 and 20 have a D that is negative as a signed number); fmin and fmax write the smaller / larger
6; of M and D as floats; fcmpswap writes D where M equals C as floats (never with a NaN, +0 equals -0). With glc the
7; data register returns M; without glc it is left alone. The cases avoid what the ISA and SPIR-V leave open: no NaN
8; in memory for fmin/fmax (the ISA's compare and GLSL NMin differ there), no fmin/fmax of +0 against -0 (NMin may
9; return either), and no denormals (RDNA2's flush behaviour is unmeasured).
10; Run: vk_store_test cs_imgatomic_ext.spv words. The tool fills the uint image (T# 0x2000...) with M = 100 + i at
11; texel i = 8y + x, the sint image (T# 0x3000...) with -2i and the volume (T# 0x5000...) with 200 + i at
12; i = 16z + 4y + x. 1.5 = 0x3fc00000, 2.5 = 0x40200000, -3.0 = 0xc0400000, 2.0 = 0x40000000, 1.0 = 0x3f800000,
13; pi = 0x40490fdb, NaN = 0x7fc00000.
14; First, all 64 threads (no glc), each on one shared texel: inc with D = 0xffffffff on texel 40 (140 + 64 = 0xcc),
15; dec with D = 0xffffffff on 41 (141 - 64 = 0x4d), fmax with D = float(t) on 42 (63.0 = 0x427c0000), fmin with
16; D = -float(t) on 43 (-63.0 = 0xc27c0000); the fills there are small positive denormals as floats, below every D
17; of fmax but 0.0 and above every D of fmin, so the result does not depend on them. Then every lane sets the trap:
18; coordinates (2, 3, 3) and data 1 in every data register. After that only thread 0 is on, so the 63 inactive lanes
19; keep the trap: an op they ran anyway would land on uint texel 26 or volume texel 62 (swap writes 1 there; the
20; fills, 126 and 262, must survive), and an inc applied by every lane would show in its case. 2D case c works on
21; uint texel c and stores its data register afterwards into sint texel c; "preset" is what a swap without glc
22; puts in the texel first.
23; c op D C glc M (preset) uint word c afterwards sint word c
24; 0 swap 0x12345678 - yes 100 0x12345678 0x00000064
25; 1 swap 0xabcdef01 - no 101 0xabcdef01 0xabcdef01
26; 2 inc 102 - yes 102 0x00000000 0x00000066
27; 3 inc 200 - yes 103 0x00000068 0x00000067
28; 4 inc 50 - yes 104 0x00000000 0x00000068
29; 5 dec 200 - yes 105 0x00000068 0x00000069
30; 6 dec 50 - yes 106 0x00000032 0x0000006a
31; 7 dec 9 - yes 0 (preset) 0x00000009 0x00000000
32; 8 inc 500 - no 108 0x0000006d 0x000001f4
33; 9 fmin 2.5 - yes 1.5 (preset) 0x3fc00000 0x3fc00000
34; 10 fmin -3.0 - yes 1.5 (preset) 0xc0400000 0x3fc00000
35; 11 fmax 2.5 - yes 1.5 (preset) 0x40200000 0x3fc00000
36; 12 fmax -3.0 - yes 1.5 (preset) 0x3fc00000 0x3fc00000
37; 13 fmin NaN - yes 1.5 (preset) 0x3fc00000 0x3fc00000
38; 14 fmax NaN - yes 1.5 (preset) 0x3fc00000 0x3fc00000
39; 15 fcmpswap pi 1.5 yes 1.5 (preset) 0x40490fdb 0x3fc00000
40; 16 fcmpswap pi 2.0 yes 1.5 (preset) 0x3fc00000 0x3fc00000
41; 17 fcmpswap 1.0 -0.0 yes 0 (preset) 0x3f800000 0x00000000
42; 18 fcmpswap 1.0 NaN yes NaN (preset) 0x7fc00000 0x7fc00000
43; 19 inc 0xfffffff0 - yes 119 0x00000078 0x00000077
44; 20 dec 0xfffffff0 - yes 120 0x00000077 0x00000078
45; 3D case j works on volume texel i = 16z + 4y + x (three different coordinates, so a swapped pair lands elsewhere),
46; always with glc, and stores its data register afterwards into sint texel 32 + j.
47; j op D C (x, y, z) i V (preset) volume word i afterwards sint word 32 + j
48; 0 swap 0x0badf00d - (1, 2, 3) 57 257 0x0badf00d 0x00000101
49; 1 inc 300 - (3, 0, 1) 19 219 0x000000dc 0x000000db
50; 2 dec 100 - (0, 3, 2) 44 244 0x00000064 0x000000f4
51; 3 fmin -3.0 - (2, 1, 0) 6 1.5 (preset) 0xc0400000 0x3fc00000
52; 4 fmax 2.5 - (2, 3, 1) 30 1.5 (preset) 0x40200000 0x3fc00000
53; 5 fcmpswap pi 1.5 (3, 1, 2) 39 1.5 (preset) 0x40490fdb 0x3fc00000
54; Every other word keeps its fill.
55s_mov_b32 s8, 0x5000
56s_mov_b32 s9, 0x1400000
57s_mov_b32 s10, 0x55
58s_mov_b32 s11, 0x55
59s_mov_b32 s12, 0x55
60s_mov_b32 s13, 0x55
61s_mov_b32 s14, 0x55
62s_mov_b32 s15, 0x55
63s_mov_b32 s16, 0x2000
64s_mov_b32 s17, 0x1400000
65s_mov_b32 s18, 0x22
66s_mov_b32 s19, 0x22
67s_mov_b32 s20, 0x22
68s_mov_b32 s21, 0x22
69s_mov_b32 s22, 0x22
70s_mov_b32 s23, 0x22
71s_mov_b32 s24, 0x3000
72s_mov_b32 s25, 0x1500000
73s_mov_b32 s26, 0x33
74s_mov_b32 s27, 0x33
75s_mov_b32 s28, 0x33
76s_mov_b32 s29, 0x33
77s_mov_b32 s30, 0x33
78s_mov_b32 s31, 0x33
79v_mov_b32_e32 v2, 5
80v_mov_b32_e32 v1, 0
81v_mov_b32_e32 v10, -1
82image_atomic_inc v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
83v_mov_b32_e32 v1, 1
84v_mov_b32_e32 v10, -1
85image_atomic_dec v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
86v_mov_b32_e32 v1, 2
87v_cvt_f32_u32_e32 v10, v0
88image_atomic_fmax v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
89v_mov_b32_e32 v1, 3
90v_cvt_f32_u32_e32 v10, v0
91v_xor_b32_e32 v10, 0x80000000, v10
92image_atomic_fmin v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
93v_mov_b32_e32 v1, 2
94v_mov_b32_e32 v2, 3
95v_mov_b32_e32 v3, 3
96v_mov_b32_e32 v6, 2
97v_mov_b32_e32 v7, 3
98v_mov_b32_e32 v10, 1
99v_mov_b32_e32 v11, 1
100v_mov_b32_e32 v12, 1
101v_cmpx_eq_u32_e32 0, v0
102v_mov_b32_e32 v1, 0
103v_mov_b32_e32 v2, 0
104v_mov_b32_e32 v10, 0x12345678
105image_atomic_swap v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc
106s_waitcnt vmcnt(0)
107image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
108v_mov_b32_e32 v1, 1
109v_mov_b32_e32 v2, 0
110v_mov_b32_e32 v10, 0xabcdef01
111image_atomic_swap v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
112image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
113v_mov_b32_e32 v1, 2
114v_mov_b32_e32 v2, 0
115v_mov_b32_e32 v10, 0x66
116image_atomic_inc v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc
117s_waitcnt vmcnt(0)
118image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
119v_mov_b32_e32 v1, 3
120v_mov_b32_e32 v2, 0
121v_mov_b32_e32 v10, 0xc8
122image_atomic_inc v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc
123s_waitcnt vmcnt(0)
124image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
125v_mov_b32_e32 v1, 4
126v_mov_b32_e32 v2, 0
127v_mov_b32_e32 v10, 50
128image_atomic_inc v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc
129s_waitcnt vmcnt(0)
130image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
131v_mov_b32_e32 v1, 5
132v_mov_b32_e32 v2, 0
133v_mov_b32_e32 v10, 0xc8
134image_atomic_dec v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc
135s_waitcnt vmcnt(0)
136image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
137v_mov_b32_e32 v1, 6
138v_mov_b32_e32 v2, 0
139v_mov_b32_e32 v10, 50
140image_atomic_dec v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc
141s_waitcnt vmcnt(0)
142image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
143v_mov_b32_e32 v1, 7
144v_mov_b32_e32 v2, 0
145v_mov_b32_e32 v12, 0
146image_atomic_swap v12, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
147v_mov_b32_e32 v10, 9
148image_atomic_dec v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc
149s_waitcnt vmcnt(0)
150image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
151v_mov_b32_e32 v1, 0
152v_mov_b32_e32 v2, 1
153v_mov_b32_e32 v10, 0x1f4
154image_atomic_inc v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
155image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
156v_mov_b32_e32 v1, 1
157v_mov_b32_e32 v2, 1
158v_mov_b32_e32 v12, 0x3fc00000
159image_atomic_swap v12, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
160v_mov_b32_e32 v10, 0x40200000
161image_atomic_fmin v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc
162s_waitcnt vmcnt(0)
163image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
164v_mov_b32_e32 v1, 2
165v_mov_b32_e32 v2, 1
166v_mov_b32_e32 v12, 0x3fc00000
167image_atomic_swap v12, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
168v_mov_b32_e32 v10, 0xc0400000
169image_atomic_fmin v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc
170s_waitcnt vmcnt(0)
171image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
172v_mov_b32_e32 v1, 3
173v_mov_b32_e32 v2, 1
174v_mov_b32_e32 v12, 0x3fc00000
175image_atomic_swap v12, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
176v_mov_b32_e32 v10, 0x40200000
177image_atomic_fmax v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc
178s_waitcnt vmcnt(0)
179image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
180v_mov_b32_e32 v1, 4
181v_mov_b32_e32 v2, 1
182v_mov_b32_e32 v12, 0x3fc00000
183image_atomic_swap v12, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
184v_mov_b32_e32 v10, 0xc0400000
185image_atomic_fmax v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc
186s_waitcnt vmcnt(0)
187image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
188v_mov_b32_e32 v1, 5
189v_mov_b32_e32 v2, 1
190v_mov_b32_e32 v12, 0x3fc00000
191image_atomic_swap v12, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
192v_mov_b32_e32 v10, 0x7fc00000
193image_atomic_fmin v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc
194s_waitcnt vmcnt(0)
195image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
196v_mov_b32_e32 v1, 6
197v_mov_b32_e32 v2, 1
198v_mov_b32_e32 v12, 0x3fc00000
199image_atomic_swap v12, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
200v_mov_b32_e32 v10, 0x7fc00000
201image_atomic_fmax v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc
202s_waitcnt vmcnt(0)
203image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
204v_mov_b32_e32 v1, 7
205v_mov_b32_e32 v2, 1
206v_mov_b32_e32 v12, 0x3fc00000
207image_atomic_swap v12, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
208v_mov_b32_e32 v10, 0x40490fdb
209v_mov_b32_e32 v11, 0x3fc00000
210image_atomic_fcmpswap v[10:11], v[1:2], s[16:23] dmask:0x3 dim:SQ_RSRC_IMG_2D unorm glc
211s_waitcnt vmcnt(0)
212image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
213v_mov_b32_e32 v1, 0
214v_mov_b32_e32 v2, 2
215v_mov_b32_e32 v12, 0x3fc00000
216image_atomic_swap v12, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
217v_mov_b32_e32 v10, 0x40490fdb
218v_mov_b32_e32 v11, 0x40000000
219image_atomic_fcmpswap v[10:11], v[1:2], s[16:23] dmask:0x3 dim:SQ_RSRC_IMG_2D unorm glc
220s_waitcnt vmcnt(0)
221image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
222v_mov_b32_e32 v1, 1
223v_mov_b32_e32 v2, 2
224v_mov_b32_e32 v12, 0
225image_atomic_swap v12, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
226v_mov_b32_e32 v10, 0x3f800000
227v_mov_b32_e32 v11, 0x80000000
228image_atomic_fcmpswap v[10:11], v[1:2], s[16:23] dmask:0x3 dim:SQ_RSRC_IMG_2D unorm glc
229s_waitcnt vmcnt(0)
230image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
231v_mov_b32_e32 v1, 2
232v_mov_b32_e32 v2, 2
233v_mov_b32_e32 v12, 0x7fc00000
234image_atomic_swap v12, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
235v_mov_b32_e32 v10, 0x3f800000
236v_mov_b32_e32 v11, 0x7fc00000
237image_atomic_fcmpswap v[10:11], v[1:2], s[16:23] dmask:0x3 dim:SQ_RSRC_IMG_2D unorm glc
238s_waitcnt vmcnt(0)
239image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
240v_mov_b32_e32 v1, 3
241v_mov_b32_e32 v2, 2
242v_mov_b32_e32 v10, 0xfffffff0
243image_atomic_inc v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc
244s_waitcnt vmcnt(0)
245image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
246v_mov_b32_e32 v1, 4
247v_mov_b32_e32 v2, 2
248v_mov_b32_e32 v10, 0xfffffff0
249image_atomic_dec v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc
250s_waitcnt vmcnt(0)
251image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
252v_mov_b32_e32 v1, 1
253v_mov_b32_e32 v2, 2
254v_mov_b32_e32 v3, 3
255v_mov_b32_e32 v10, 0xbadf00d
256image_atomic_swap v10, v[1:3], s[8:15] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm glc
257s_waitcnt vmcnt(0)
258v_mov_b32_e32 v6, 0
259v_mov_b32_e32 v7, 4
260image_store v10, v[6:7], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
261v_mov_b32_e32 v1, 3
262v_mov_b32_e32 v2, 0
263v_mov_b32_e32 v3, 1
264v_mov_b32_e32 v10, 0x12c
265image_atomic_inc v10, v[1:3], s[8:15] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm glc
266s_waitcnt vmcnt(0)
267v_mov_b32_e32 v6, 1
268v_mov_b32_e32 v7, 4
269image_store v10, v[6:7], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
270v_mov_b32_e32 v1, 0
271v_mov_b32_e32 v2, 3
272v_mov_b32_e32 v3, 2
273v_mov_b32_e32 v10, 0x64
274image_atomic_dec v10, v[1:3], s[8:15] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm glc
275s_waitcnt vmcnt(0)
276v_mov_b32_e32 v6, 2
277v_mov_b32_e32 v7, 4
278image_store v10, v[6:7], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
279v_mov_b32_e32 v1, 2
280v_mov_b32_e32 v2, 1
281v_mov_b32_e32 v3, 0
282v_mov_b32_e32 v12, 0x3fc00000
283image_atomic_swap v12, v[1:3], s[8:15] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm
284v_mov_b32_e32 v10, 0xc0400000
285image_atomic_fmin v10, v[1:3], s[8:15] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm glc
286s_waitcnt vmcnt(0)
287v_mov_b32_e32 v6, 3
288v_mov_b32_e32 v7, 4
289image_store v10, v[6:7], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
290v_mov_b32_e32 v1, 2
291v_mov_b32_e32 v2, 3
292v_mov_b32_e32 v3, 1
293v_mov_b32_e32 v12, 0x3fc00000
294image_atomic_swap v12, v[1:3], s[8:15] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm
295v_mov_b32_e32 v10, 0x40200000
296image_atomic_fmax v10, v[1:3], s[8:15] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm glc
297s_waitcnt vmcnt(0)
298v_mov_b32_e32 v6, 4
299v_mov_b32_e32 v7, 4
300image_store v10, v[6:7], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
301v_mov_b32_e32 v1, 3
302v_mov_b32_e32 v2, 1
303v_mov_b32_e32 v3, 2
304v_mov_b32_e32 v12, 0x3fc00000
305image_atomic_swap v12, v[1:3], s[8:15] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm
306v_mov_b32_e32 v10, 0x40490fdb
307v_mov_b32_e32 v11, 0x3fc00000
308image_atomic_fcmpswap v[10:11], v[1:3], s[8:15] dmask:0x3 dim:SQ_RSRC_IMG_3D unorm glc
309s_waitcnt vmcnt(0)
310v_mov_b32_e32 v6, 5
311v_mov_b32_e32 v7, 4
312image_store v10, v[6:7], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
313s_endpgm
diff --git a/runtime/test/shaders/cs_imgload_d16_tfe.asm b/runtime/test/shaders/cs_imgload_d16_tfe.asm
index 0739810d1..119653577 100644
--- a/runtime/test/shaders/cs_imgload_d16_tfe.asm
+++ b/runtime/test/shaders/cs_imgload_d16_tfe.asm
@@ -1,8 +1,10 @@
1; tfe status VGPR on a d16 image_load (SHADER-1266): cs_imgload_d16 with tfe on both loads. Under d16 one 1; tfe status VGPR on a d16 image_load (SHADER-1266): cs_imgload_d16 with tfe on both loads. Under d16 one
2; component fills one VGPR, and with tfe the fetch status follows it, so vdata is v[7:8] and v[11:12]. Every texel is 2; component fills one VGPR, and with tfe the fetch status follows it, so vdata is v[7:8] and v[11:12]. On a resident
3; resident, so the status is 0. Each status VGPR is seeded with 1000 and added into the result, so a stale status 3; texel, RDNA2 hardware leaves the status VGPR unchanged. The two status VGPRs are seeded with distinct values
4; moves every texel by 2000. The unpacking and the result are cs_imgload_d16's, checked by vk_store_test load-d16 4; (v8 = 0x3e8, v12 = 0x7d0) and independently checked via (v8 ^ 0x3e8) | (v12 ^ 0x7d0) before adding into v11, so
5; (including its saturation row). Suggested by @nnonno91, who ran the same companion on gfx1036 and an RTX 5090 in #8968. 5; zeroing or modifying either status VGPR shifts every texel. The unpacking and the result are cs_imgload_d16's,
6; checked by vk_store_test load-d16 (including its saturation row). Suggested by @nnonno91, who ran the same
7; companion on gfx1036 and an RTX 5090 in #8968.
6v_and_b32_e32 v1, 7, v0 8v_and_b32_e32 v1, 7, v0
7v_lshrrev_b32_e32 v2, 3, v0 9v_lshrrev_b32_e32 v2, 3, v0
8v_cvt_f32_u32_e32 v3, v1 10v_cvt_f32_u32_e32 v3, v1
@@ -38,14 +40,16 @@ s_mov_b32 s28, 0x33
38s_mov_b32 s29, 0x33 40s_mov_b32 s29, 0x33
39s_mov_b32 s30, 0x33 41s_mov_b32 s30, 0x33
40s_mov_b32 s31, 0x33 42s_mov_b32 s31, 0x33
41v_mov_b32_e32 v12, 0x3e8 43v_mov_b32_e32 v12, 0x7d0
42image_load v[11:12], v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm tfe d16 44image_load v[11:12], v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm tfe d16
43s_waitcnt vmcnt(0) 45s_waitcnt vmcnt(0)
44v_and_b32_e32 v7, 0xffff, v7 46v_and_b32_e32 v7, 0xffff, v7
45v_bfe_i32 v11, v11, 0, 16 47v_bfe_i32 v11, v11, 0, 16
46v_add_nc_u32_e32 v11, v7, v11 48v_add_nc_u32_e32 v11, v7, v11
49v_xor_b32_e32 v8, 0x3e8, v8
50v_xor_b32_e32 v12, 0x7d0, v12
51v_or_b32_e32 v8, v8, v12
47v_add_nc_u32_e32 v11, v8, v11 52v_add_nc_u32_e32 v11, v8, v11
48v_add_nc_u32_e32 v11, v12, v11
49v_mov_b32_e32 v12, 0 53v_mov_b32_e32 v12, 0
50v_mov_b32_e32 v13, 0 54v_mov_b32_e32 v13, 0
51v_mov_b32_e32 v14, 0 55v_mov_b32_e32 v14, 0
diff --git a/runtime/test/shaders/cs_imgload_tfe.asm b/runtime/test/shaders/cs_imgload_tfe.asm
index 63ad9dc71..6eb3e76f6 100644
--- a/runtime/test/shaders/cs_imgload_tfe.asm
+++ b/runtime/test/shaders/cs_imgload_tfe.asm
@@ -1,9 +1,10 @@
1; tfe status VGPR on image_load (SHADER-1266): cs_imgload with tfe on both loads. With tfe an MIMG read returns one 1; tfe status VGPR on image_load (SHADER-1266): cs_imgload with tfe on both loads. With tfe an MIMG read reserves one
2; more dword after its data, the fetch status, at vdata[data_count] (RDNA2 ISA, MIMG TFE/LWE). Every texel here is 2; more dword after its data, the fetch status, at vdata[data_count] (RDNA2 ISA, MIMG TFE/LWE). On a resident texel,
3; resident, so the status is 0. Each status VGPR is seeded with 1000 before its load and added into the result, so a 3; RDNA2 hardware leaves the status VGPR unchanged. The two status VGPRs are seeded with distinct values (v8 = 0x3e8,
4; status that keeps its old value moves every texel by 1000 or 2000. vk_store_test fills the r32 uint image with 4; v12 = 0x7d0) and independently checked via (v8 ^ 0x3e8) | (v12 ^ 0x7d0) before adding into v11, so zeroing or
5; 100 + 8y + x and the r32 sint image with -2 (8y + x) before the dispatch; the rgba8 image is stored as in 5; modifying either status VGPR shifts every texel. vk_store_test fills the r32 uint image with 100 + 8y + x and the
6; cs_imgstore. Run: vk_store_test cs_imgload_tfe.spv load -> sint = 100 - (8y + x), uint unchanged. 6; r32 sint image with -2 (8y + x) before the dispatch; the rgba8 image is stored as in cs_imgstore.
7; Run: vk_store_test cs_imgload_tfe.spv load -> sint = 100 - (8y + x), uint unchanged.
7v_and_b32_e32 v1, 7, v0 8v_and_b32_e32 v1, 7, v0
8v_lshrrev_b32_e32 v2, 3, v0 9v_lshrrev_b32_e32 v2, 3, v0
9v_cvt_f32_u32_e32 v3, v1 10v_cvt_f32_u32_e32 v3, v1
@@ -39,12 +40,14 @@ s_mov_b32 s28, 0x33
39s_mov_b32 s29, 0x33 40s_mov_b32 s29, 0x33
40s_mov_b32 s30, 0x33 41s_mov_b32 s30, 0x33
41s_mov_b32 s31, 0x33 42s_mov_b32 s31, 0x33
42v_mov_b32_e32 v12, 0x3e8 43v_mov_b32_e32 v12, 0x7d0
43image_load v[11:12], v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm tfe 44image_load v[11:12], v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm tfe
44s_waitcnt vmcnt(0) 45s_waitcnt vmcnt(0)
45v_add_nc_u32_e32 v11, v7, v11 46v_add_nc_u32_e32 v11, v7, v11
47v_xor_b32_e32 v8, 0x3e8, v8
48v_xor_b32_e32 v12, 0x7d0, v12
49v_or_b32_e32 v8, v8, v12
46v_add_nc_u32_e32 v11, v8, v11 50v_add_nc_u32_e32 v11, v8, v11
47v_add_nc_u32_e32 v11, v12, v11
48v_mov_b32_e32 v12, 0 51v_mov_b32_e32 v12, 0
49v_mov_b32_e32 v13, 0 52v_mov_b32_e32 v13, 0
50v_mov_b32_e32 v14, 0 53v_mov_b32_e32 v14, 0
diff --git a/runtime/test/shaders/cs_imgstore_cube.asm b/runtime/test/shaders/cs_imgstore_cube.asm
new file mode 100644
index 000000000..9763e233f
--- /dev/null
+++ b/runtime/test/shaders/cs_imgstore_cube.asm
@@ -0,0 +1,95 @@
1; Typed image_store on dim:SQ_RSRC_IMG_CUBE (GPU-CUBE-STORE): three T#s built in SGPRs (FORMAT 56 rgba8 unorm, 20 r32
2; uint, 21 r32 sint; word3 TYPE = 0xB, SQ_RSRC_IMG_CUBE), 64 threads, thread t at (x, y) = (t & 7, t >> 3) of an 8x8
3; face, each store to all six faces (v3 = face). The translator writes a cube through a six-layer 2D-array storage
4; view (bindings 11/12/13, the layer is the face), as the runtime binds a cube UAV (runtime/src/vulkan_bindless.h).
5; Run: vk_store_test cs_imgstore_cube.spv cube (checks every texel of all six layers of all three images):
6; rgba8 unorm: (x / 7, y / 7, face / 5, 1)
7; r32 uint: 100 + 1000 face + 8y + x
8; r32 sint: -(1000 face + 8y + x)
9v_and_b32_e32 v1, 7, v0
10v_lshrrev_b32_e32 v2, 3, v0
11v_cvt_f32_u32_e32 v4, v1
12v_cvt_f32_u32_e32 v5, v2
13v_mul_f32_e32 v4, 0x3e124925, v4
14v_mul_f32_e32 v5, 0x3e124925, v5
15v_mov_b32_e32 v7, 1.0
16v_add_nc_u32_e32 v16, 100, v0
17v_mov_b32_e32 v9, 0
18v_mov_b32_e32 v10, 0
19v_mov_b32_e32 v11, 0
20v_mov_b32_e32 v13, 0
21v_mov_b32_e32 v14, 0
22v_mov_b32_e32 v15, 0
23s_mov_b32 s8, 0x1000
24s_mov_b32 s9, 0x3800000
25s_mov_b32 s10, 0x11
26s_mov_b32 s11, 0xb0000011
27s_mov_b32 s12, 0x11
28s_mov_b32 s13, 0x11
29s_mov_b32 s14, 0x11
30s_mov_b32 s15, 0x11
31s_mov_b32 s16, 0x2000
32s_mov_b32 s17, 0x1400000
33s_mov_b32 s18, 0x22
34s_mov_b32 s19, 0xb0000022
35s_mov_b32 s20, 0x22
36s_mov_b32 s21, 0x22
37s_mov_b32 s22, 0x22
38s_mov_b32 s23, 0x22
39s_mov_b32 s24, 0x3000
40s_mov_b32 s25, 0x1500000
41s_mov_b32 s26, 0x33
42s_mov_b32 s27, 0xb0000033
43s_mov_b32 s28, 0x33
44s_mov_b32 s29, 0x33
45s_mov_b32 s30, 0x33
46s_mov_b32 s31, 0x33
47v_mov_b32_e32 v3, 0
48v_cvt_f32_u32_e32 v6, v3
49v_mul_f32_e32 v6, 0x3e4ccccd, v6
50image_store v[4:7], v[1:3], s[8:15] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm
51v_add_nc_u32_e32 v8, 0, v16
52image_store v[8:11], v[1:3], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm
53v_sub_nc_u32_e32 v12, 0, v0
54image_store v[12:15], v[1:3], s[24:31] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm
55v_mov_b32_e32 v3, 1
56v_cvt_f32_u32_e32 v6, v3
57v_mul_f32_e32 v6, 0x3e4ccccd, v6
58image_store v[4:7], v[1:3], s[8:15] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm
59v_add_nc_u32_e32 v8, 1000, v16
60image_store v[8:11], v[1:3], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm
61v_sub_nc_u32_e32 v12, -1000, v0
62image_store v[12:15], v[1:3], s[24:31] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm
63v_mov_b32_e32 v3, 2
64v_cvt_f32_u32_e32 v6, v3
65v_mul_f32_e32 v6, 0x3e4ccccd, v6
66image_store v[4:7], v[1:3], s[8:15] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm
67v_add_nc_u32_e32 v8, 2000, v16
68image_store v[8:11], v[1:3], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm
69v_sub_nc_u32_e32 v12, -2000, v0
70image_store v[12:15], v[1:3], s[24:31] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm
71v_mov_b32_e32 v3, 3
72v_cvt_f32_u32_e32 v6, v3
73v_mul_f32_e32 v6, 0x3e4ccccd, v6
74image_store v[4:7], v[1:3], s[8:15] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm
75v_add_nc_u32_e32 v8, 3000, v16
76image_store v[8:11], v[1:3], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm
77v_sub_nc_u32_e32 v12, -3000, v0
78image_store v[12:15], v[1:3], s[24:31] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm
79v_mov_b32_e32 v3, 4
80v_cvt_f32_u32_e32 v6, v3
81v_mul_f32_e32 v6, 0x3e4ccccd, v6
82image_store v[4:7], v[1:3], s[8:15] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm
83v_add_nc_u32_e32 v8, 4000, v16
84image_store v[8:11], v[1:3], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm
85v_sub_nc_u32_e32 v12, -4000, v0
86image_store v[12:15], v[1:3], s[24:31] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm
87v_mov_b32_e32 v3, 5
88v_cvt_f32_u32_e32 v6, v3
89v_mul_f32_e32 v6, 0x3e4ccccd, v6
90image_store v[4:7], v[1:3], s[8:15] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm
91v_add_nc_u32_e32 v8, 5000, v16
92image_store v[8:11], v[1:3], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm
93v_sub_nc_u32_e32 v12, -5000, v0
94image_store v[12:15], v[1:3], s[24:31] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm
95s_endpgm
diff --git a/runtime/test/shaders/cs_w32_lds_subdword.asm b/runtime/test/shaders/cs_w32_lds_subdword.asm
index cb2f94243..10c5bd214 100644
--- a/runtime/test/shaders/cs_w32_lds_subdword.asm
+++ b/runtime/test/shaders/cs_w32_lds_subdword.asm
@@ -12,23 +12,27 @@
12; out[2] ds_read_i8 offset:2 -> 0xFFFFFFB2 out[3] ds_read_u8 offset:2 -> 0x000000B2 12; out[2] ds_read_i8 offset:2 -> 0xFFFFFFB2 out[3] ds_read_u8 offset:2 -> 0x000000B2
13; out[4] ds_read_i8 offset:3 -> 0x00000011 out[5] ds_read_i16 offset:6 -> 0xFFFFA1B2 13; out[4] ds_read_i8 offset:3 -> 0x00000011 out[5] ds_read_i16 offset:6 -> 0xFFFFA1B2
14; out[6] ds_read_u16 offset:6 -> 0x0000A1B2 out[7] ds_read_i16 offset:4 -> 0xFFFFC3D4 14; out[6] ds_read_u16 offset:6 -> 0x0000A1B2 out[7] ds_read_i16 offset:4 -> 0xFFFFC3D4
15; Every lane writes the same bytes, so the result does not depend on lane order. 15; Only lane zero accesses LDS and writes the results, avoiding concurrent writes to the same word.
16; Workgroup barriers separate the initial stores, narrow writes, and reads of the same words.
16; group: 32,1,1 17; group: 32,1,1
17; Run: vk_compute_test cs_w32_lds_subdword.spv 1 dump 18; Run: vk_compute_test cs_w32_lds_subdword.spv 1 dump
18; -> out[0..7] = 0x11B2D444 0xA1B2C3D4 0xFFFFFFB2 0x000000B2 0x00000011 0xFFFFA1B2 0x0000A1B2 0xFFFFC3D4 19; -> out[0..7] = 0x11B2D444 0xA1B2C3D4 0xFFFFFFB2 0x000000B2 0x00000011 0xFFFFA1B2 0x0000A1B2 0xFFFFC3D4
19; mattr: +wavefrontsize32,-wavefrontsize64 20; mattr: +wavefrontsize32,-wavefrontsize64
21v_cmpx_eq_u32_e32 0, v0
20v_mov_b32_e32 v2, 0 22v_mov_b32_e32 v2, 0
21v_mov_b32_e32 v4, 0x11223344 23v_mov_b32_e32 v4, 0x11223344
22v_mov_b32_e32 v5, 0x55667788 24v_mov_b32_e32 v5, 0x55667788
23ds_write_b32 v2, v4 25ds_write_b32 v2, v4
24ds_write_b32 v2, v5 offset:4 26ds_write_b32 v2, v5 offset:4
25s_waitcnt lgkmcnt(0) 27s_waitcnt lgkmcnt(0)
28s_barrier
26v_mov_b32_e32 v3, 0xa1b2c3d4 29v_mov_b32_e32 v3, 0xa1b2c3d4
27ds_write_b8 v2, v3 offset:1 30ds_write_b8 v2, v3 offset:1
28ds_write_b8_d16_hi v2, v3 offset:2 31ds_write_b8_d16_hi v2, v3 offset:2
29ds_write_b16 v2, v3 offset:4 32ds_write_b16 v2, v3 offset:4
30ds_write_b16_d16_hi v2, v3 offset:6 33ds_write_b16_d16_hi v2, v3 offset:6
31s_waitcnt lgkmcnt(0) 34s_waitcnt lgkmcnt(0)
35s_barrier
32ds_read_b32 v10, v2 36ds_read_b32 v10, v2
33ds_read_b32 v11, v2 offset:4 37ds_read_b32 v11, v2 offset:4
34ds_read_i8 v12, v2 offset:2 38ds_read_i8 v12, v2 offset:2
@@ -38,7 +42,6 @@ ds_read_i16 v15, v2 offset:6
38ds_read_u16 v16, v2 offset:6 42ds_read_u16 v16, v2 offset:6
39ds_read_i16 v17, v2 offset:4 43ds_read_i16 v17, v2 offset:4
40s_waitcnt lgkmcnt(0) 44s_waitcnt lgkmcnt(0)
41v_cmpx_eq_u32_e32 0, v0
42v_mov_b32_e32 v21, 0 45v_mov_b32_e32 v21, 0
43buffer_store_dword v10, v21, s[0:3], 0 offen 46buffer_store_dword v10, v21, s[0:3], 0 offen
44v_mov_b32_e32 v21, 4 47v_mov_b32_e32 v21, 4
diff --git a/runtime/test/shaders/cs_w32_shift64.asm b/runtime/test/shaders/cs_w32_shift64.asm
new file mode 100644
index 000000000..97920b114
--- /dev/null
+++ b/runtime/test/shaders/cs_w32_shift64.asm
@@ -0,0 +1,29 @@
1; GPU-VALU64-SHIFTS: dynamic 64-bit shifts, including overlapping destinations.
2; group: 64,1,1
3; mattr: +wavefrontsize32,-wavefrontsize64
4; check.py seeds 64 records at byte 0x600: {value.lo, value.hi, count, padding}.
5; They are the Cartesian product of eight signed/unsigned boundary values and
6; counts 0, 1, 31, 32, 33, 63, 64, 65. Each thread reads one record from memory,
7; so neither the translator nor the driver can fold the shifts of literal inputs.
8; RDNA2 ISA VOP3 opcodes 767..769: count is S0[5:0]; logical shifts zero-fill,
9; arithmetic right shift sign-extends. Results are modulo 2^64, low word first.
10; Thread i writes six words at 24*i: left, logical right, arithmetic right.
11; Left overwrites its count register; logical right overlaps its source's high
12; word; arithmetic right overwrites both source words. All inputs must be read
13; before either destination word is written. The input records remain unchanged.
14; Run with the heap initialized by check.py's shift64_test; compare all 640 words.
15v_lshlrev_b32_e32 v1, 4, v0
16v_mul_lo_u32 v10, v0, 24
17buffer_load_dwordx4 v[2:5], v1, s[0:3], 0 offen offset:1536
18s_waitcnt vmcnt(0)
19v_lshlrev_b64 v[4:5], v4, v[2:3]
20buffer_store_dwordx2 v[4:5], v10, s[0:3], 0 offen
21buffer_load_dwordx4 v[2:5], v1, s[0:3], 0 offen offset:1536
22s_waitcnt vmcnt(0)
23v_lshrrev_b64 v[3:4], v4, v[2:3]
24buffer_store_dwordx2 v[3:4], v10, s[0:3], 0 offen offset:8
25buffer_load_dwordx4 v[2:5], v1, s[0:3], 0 offen offset:1536
26s_waitcnt vmcnt(0)
27v_ashrrev_i64 v[2:3], v4, v[2:3]
28buffer_store_dwordx2 v[2:3], v10, s[0:3], 0 offen offset:16
29s_endpgm
diff --git a/runtime/test/shaders/mullit_readback.py b/runtime/test/shaders/mullit_readback.py
deleted file mode 100644
index 007b516b1..000000000
--- a/runtime/test/shaders/mullit_readback.py
+++ /dev/null
@@ -1,122 +0,0 @@
1"""Check the ps_mullit semantic fixture with runtime SGPR inputs and RGBA32F readback.
2
3python -I runtime/test/shaders/build.py <work> vs_ids ps_mullit
4python -I runtime/test/shaders/mullit_readback.py <work> <harness directory>
5"""
6import argparse
7import itertools
8import os
9from pathlib import Path
10import random
11import struct
12import sys
13import tempfile
14
15sys.path.insert(0, str(Path(__file__).resolve().parent))
16from check import EXE, run
17
18SIGN = 0x80000000
19INF = 0x7f800000
20MIN_NORMAL = 0x00800000
21ONE = 0x3f800000
22LIGHT_OFF = 0xff7fffff
23PAYLOAD_MASK = 0x40000000
24
25
26def lighting_product(x, y, gate):
27 """Return the expected f32 word using integer significands throughout."""
28 ax, ay = x & ~SIGN, y & ~SIGN
29 if not MIN_NORMAL <= gate <= INF or y in (LIGHT_OFF, SIGN | INF) or ay > INF:
30 return LIGHT_OFF
31 if min(ax, ay) < MIN_NORMAL:
32 return 0
33 if ax > INF:
34 return x
35 sign = (x ^ y) & SIGN
36 if INF in (ax, ay):
37 return sign | INF
38
39 product = (MIN_NORMAL + ax % MIN_NORMAL) * (MIN_NORMAL + ay % MIN_NORMAL)
40 shift = product.bit_length() - 24
41 unit = 1 << shift
42 mantissa, remainder = divmod(product, unit)
43 if 2 * remainder > unit or (2 * remainder == unit and mantissa % 2):
44 mantissa += 1
45 exponent = (ax >> 23) + (ay >> 23) - 127 + shift - 23
46 if mantissa == 2 * MIN_NORMAL:
47 mantissa //= 2
48 exponent += 1
49 # Round before flushing. A product just below MIN_NORMAL can carry into it.
50 if exponent <= 0:
51 return sign
52 if exponent >= 255:
53 return sign | INF
54 return sign | (exponent << 23) | (mantissa - MIN_NORMAL)
55
56
57def operand_triples():
58 gates = (ONE, INF, MIN_NORMAL, 1, MIN_NORMAL - 1, 0, SIGN, SIGN | ONE, 0x7fc23456, 0xffa54321)
59 yield from ((0x40400000, 0xc0200000, gate) for gate in gates)
60 yield from itertools.product(
61 (0, SIGN, 1, SIGN | (MIN_NORMAL - 1), 0x7fa12345, 0xffc12345, INF),
62 (0, SIGN | 1, LIGHT_OFF, INF, SIGN | INF, 0x7fc09876, ONE), (ONE,))
63 yield from itertools.product(
64 (ONE - 4, ONE - 3, ONE - 2, ONE - 1, ONE, SIGN | ONE, 0xbf7ffffe, 0xbf7fffff),
65 (MIN_NORMAL, MIN_NORMAL + 1, MIN_NORMAL + 2), (ONE,))
66 for x, y in ((INF - 1, 0x40000000), (LIGHT_OFF, 0x40000000), (INF - 1, MIN_NORMAL),
67 (MIN_NORMAL, 0x3f000000), (SIGN | MIN_NORMAL, 0x3f000000),
68 (INF, SIGN | ONE), (ONE, LIGHT_OFF - 1)):
69 yield x, y, ONE
70 # Halfway products round up to 0x3fc00002 and down to 0x3fc00004.
71 yield 0x3fc00000, ONE + 1, ONE
72 yield 0x3fc00000, ONE + 3, ONE
73 rng = random.Random(578)
74 for _ in range(28):
75 x = rng.randrange(MIN_NORMAL, INF) | rng.choice((0, SIGN))
76 y = rng.randrange(MIN_NORMAL, INF) | rng.choice((0, SIGN))
77 yield x, y, ONE
78
79
80def mismatch(data, x, y, gate):
81 result = lighting_product(x, y, gate)
82 modified = lighting_product(x ^ SIGN, y & ~SIGN, gate)
83 expected = (result, modified, LIGHT_OFF, result ^ PAYLOAD_MASK)
84 if len(data) != 4 * 4 * 16:
85 return f"expected 256 bytes, got {len(data)}"
86 for i, pixel in enumerate(struct.iter_unpack("<4I", data)):
87 for channel, want, got in zip("RGBA", expected, pixel):
88 # A float attachment can change a NaN payload. Alpha exposes the raw
89 # R payload as a finite word in exactly those cases.
90 if want & ~SIGN > INF and got & ~SIGN > INF:
91 continue
92 if got != want:
93 return f"pixel {i} {channel}: got {got:#010x}, expected {want:#010x}"
94 return None
95
96
97def main():
98 parser = argparse.ArgumentParser(description=__doc__)
99 parser.add_argument("work", type=Path)
100 parser.add_argument("build", type=Path)
101 args = parser.parse_args()
102 spirv = args.work / "spirv"
103 cases = dict.fromkeys(operand_triples())
104 with tempfile.TemporaryDirectory() as tmp:
105 raw = Path(tmp) / "pixels.raw"
106 for inputs in cases:
107 raw.unlink(missing_ok=True)
108 words = ",".join(map(hex, inputs))
109 code, output = run(args.build / ("vk_harness" + EXE), spirv / "vs_ids.spv",
110 spirv / "ps_mullit.spv", raw, "4", "4", env=dict(os.environ, VKH_SGPRS=words))
111 if code:
112 print(f"{words}: vk_harness exited {code}\n{output}", file=sys.stderr)
113 return code
114 problem = mismatch(raw.read_bytes(), *inputs) if raw.is_file() else "missing readback"
115 if problem:
116 sys.exit(f"{words}: {problem}")
117 print(f"{len(cases)} operand triples, {16 * len(cases)} pixels matched")
118 return 0
119
120
121if __name__ == "__main__":
122 sys.exit(main())
diff --git a/runtime/test/vk_command_replay_test.cpp b/runtime/test/vk_command_replay_test.cpp
index 9769e70be..c31c23b60 100644
--- a/runtime/test/vk_command_replay_test.cpp
+++ b/runtime/test/vk_command_replay_test.cpp
@@ -1265,6 +1265,81 @@ int part_j(vktest::Device& d) {
1265 return 0; 1265 return 0;
1266} 1266}
1267 1267
1268// Part K (D3D-838): an enhanced barrier with SYNC_COPY orders a WriteBufferImmediate before it. The write is recorded
1269// as vkCmdUpdateBuffer, which synchronization2 runs in the CLEAR stage, not COPY, and a DEFAULT-mode write gets no
1270// barrier of its own (replay leaves it to the application's). So: the write puts a word in src, a SYNC_COPY ->
1271// SYNC_COPY buffer barrier (COPY_DEST -> COPY_SOURCE) follows, and CopyBufferRegion copies the word to dst. Under
1272// LEONIDA_VK_VALIDATION=1 synchronization validation reports the read-after-write hazard when the barrier's source
1273// stages leave CLEAR out; in every run the copied word is checked.
1274int part_k(vktest::Device& d) {
1275 constexpr VkDeviceSize bytes = 256;
1276 constexpr std::uint64_t va_src = 0x50000;
1277 constexpr std::uint32_t value = 0x5eed1234;
1278 constexpr VkBufferUsageFlags usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
1279 void *src_mapped = nullptr, *dst_mapped = nullptr;
1280 const VkBuffer src = d.buffer(bytes, usage, &src_mapped);
1281 const VkBuffer dst = d.buffer(bytes, usage, &dst_mapped);
1282 EXPECT(src && dst && src_mapped && dst_mapped);
1283 std::memset(src_mapped, 0, bytes);
1284 std::memset(dst_mapped, 0, bytes);
1285
1286 constexpr ResourceId src_id = 50, dst_id = 51;
1287 ResourceBinding src_binding{}, dst_binding{};
1288 src_binding.buffer = src;
1289 src_binding.size = bytes;
1290 src_binding.va = va_src;
1291 dst_binding.buffer = dst;
1292 dst_binding.size = bytes;
1293 const auto resolve = [&](ResourceId id) -> const ResourceBinding* {
1294 if (id == src_id) return &src_binding;
1295 if (id == dst_id) return &dst_binding;
1296 return nullptr;
1297 };
1298 ReplayFunctions vk{};
1299 vk.pipeline_barrier = d.fn<PFN_vkCmdPipelineBarrier>("vkCmdPipelineBarrier");
1300 vk.pipeline_barrier2 = d.fn<PFN_vkCmdPipelineBarrier2>("vkCmdPipelineBarrier2");
1301 vk.copy_buffer = d.fn<PFN_vkCmdCopyBuffer>("vkCmdCopyBuffer"); // replay wants all four copy functions
1302 vk.copy_buffer_to_image = d.fn<PFN_vkCmdCopyBufferToImage>("vkCmdCopyBufferToImage");
1303 vk.copy_image_to_buffer = d.fn<PFN_vkCmdCopyImageToBuffer>("vkCmdCopyImageToBuffer");
1304 vk.copy_image = d.fn<PFN_vkCmdCopyImage>("vkCmdCopyImage");
1305 vk.update_buffer = d.fn<PFN_vkCmdUpdateBuffer>("vkCmdUpdateBuffer");
1306 vk.buffer_at = [&](std::uint64_t va, std::uint64_t length, VkBuffer& buffer, VkDeviceSize& offset) {
1307 if (va < va_src || va - va_src >= bytes || length > bytes - (va - va_src)) return false;
1308 buffer = src;
1309 offset = va - va_src;
1310 return true;
1311 };
1312
1313 namespace ac = d3d12_access;
1314 namespace y = d3d12_sync;
1315 CommandList list;
1316 EXPECT(list.write_immediate({va_src + 8, value, write_immediate_mode::normal}));
1317 EXPECT(list.barrier(BufferBarrier{y::copy, y::copy, ac::copy_dest, ac::copy_source, src_id}));
1318 EXPECT(list.copy_buffer({dst_id, 16, src_id, 8, 4}));
1319 EXPECT(list.close());
1320
1321 const unsigned errors_before = d.validation_errors();
1322 ReplayResult result = ReplayResult::success;
1323 EXPECT(d.run([&](VkCommandBuffer cb) {
1324 result = replay(list, cb, resolve, vk);
1325 if (result != ReplayResult::success) std::fprintf(stderr, "K: replay returned %d\n", int(result));
1326 return result == ReplayResult::success;
1327 }));
1328 const unsigned errors = d.validation_errors() - errors_before;
1329 std::uint32_t copied = 0;
1330 std::memcpy(&copied, static_cast<const std::uint8_t*>(dst_mapped) + 16, 4);
1331 if (copied != value) {
1332 std::fprintf(stderr, "K: copied 0x%08x, want 0x%08x\n", copied, value);
1333 ++g_mismatches;
1334 }
1335 if (errors) {
1336 std::fprintf(stderr, "K: %u validation errors: a SYNC_COPY barrier does not cover vkCmdUpdateBuffer\n", errors);
1337 return 1;
1338 }
1339 std::printf("K: SYNC_COPY orders WriteBufferImmediate (vkCmdUpdateBuffer, CLEAR stage) before a copy\n");
1340 return 0;
1341}
1342
1268} // namespace 1343} // namespace
1269 1344
1270int main() { 1345int main() {
@@ -1276,7 +1351,7 @@ int main() {
1276 } 1351 }
1277 EXPECT(status == vktest::DeviceStatus::ready); 1352 EXPECT(status == vktest::DeviceStatus::ready);
1278 if (part_a(device) || part_b(device) || part_c(device) || part_d(device) || part_e(device) || part_f(device) || 1353 if (part_a(device) || part_b(device) || part_c(device) || part_d(device) || part_e(device) || part_f(device) ||
1279 part_g(device) || part_h(device) || part_i(device) || part_j(device)) 1354 part_g(device) || part_h(device) || part_i(device) || part_j(device) || part_k(device))
1280 return 1; 1355 return 1;
1281 if (g_mismatches) return 1; 1356 if (g_mismatches) return 1;
1282 if (device.validation_errors()) { 1357 if (device.validation_errors()) {
diff --git a/runtime/test/vk_compute_test.cpp b/runtime/test/vk_compute_test.cpp
index 5ac0bb1bb..8cc6a2a2f 100644
--- a/runtime/test/vk_compute_test.cpp
+++ b/runtime/test/vk_compute_test.cpp
@@ -152,7 +152,8 @@ static int run(int argc, char** argv) {
152 } 152 }
153 // VKC_HEAP_FILE=<path>[@<offset>]: copy a file into the heap so a shader can read a buffer (a BVH, its 153 // VKC_HEAP_FILE=<path>[@<offset>]: copy a file into the heap so a shader can read a buffer (a BVH, its
154 // descriptor blocks and the records) without the test hard-coding it. The offset is a decimal or 0x hex byte 154 // descriptor blocks and the records) without the test hard-coding it. The offset is a decimal or 0x hex byte
155 // offset (no octal, sign or spaces); addresses the shader sees are Xbox VAs, i.e. heap offsets, as for every 155 // offset (no octal, sign or spaces) below 2^32, and the whole file must fit below 2^32 too (the heap is the
156 // 32-bit GPU window); addresses the shader sees are Xbox VAs, i.e. heap offsets, as for every
156 // other heap buffer here. Two overlaps to keep in mind: "bvh" mode writes its synthetic scene after this copy, 157 // other heap buffer here. Two overlaps to keep in mind: "bvh" mode writes its synthetic scene after this copy,
157 // so a file at 0x100..0x264 is overwritten there, and the output V# starts at heap offset 0, so a file at @0 158 // so a file at 0x100..0x264 is overwritten there, and the output V# starts at heap offset 0, so a file at @0
158 // shares bytes with the dispatch's output. 159 // shares bytes with the dispatch's output.
@@ -175,15 +176,30 @@ static int run(int argc, char** argv) {
175 } 176 }
176 char* end = nullptr; 177 char* end = nullptr;
177 const unsigned long long parsed = std::strtoull(body, &end, hex ? 16 : 10); 178 const unsigned long long parsed = std::strtoull(body, &end, hex ? 16 : 10);
178 if (end == body || *end || parsed > (1ull << 32) || heap_file_path.empty()) { 179 // The heap is the 32-bit Xbox GPU window: an offset of 2^32 is one past it (RT-439).
180 if (end == body || *end || parsed >= (1ull << 32) || heap_file_path.empty()) {
179 std::fprintf(stderr, "VKC_HEAP_FILE: expected <path>[@<offset>], got \"%s\"\n", heap_file_env); 181 std::fprintf(stderr, "VKC_HEAP_FILE: expected <path>[@<offset>], got \"%s\"\n", heap_file_env);
180 return 2; 182 return 2;
181 } 183 }
182 heap_file_at = parsed; 184 heap_file_at = parsed;
183 } 185 }
184 std::ifstream hf(heap_file_path, std::ios::binary); 186 // The size is checked on the open file before anything is read, so a file that can't fit is refused
185 heap_file.assign(std::istreambuf_iterator<char>(hf), {}); 187 // without reading it into memory (@shdann on #5878).
186 if (heap_file.empty()) { 188 std::ifstream hf(heap_file_path, std::ios::binary | std::ios::ate);
189 const std::streamoff length = hf ? static_cast<std::streamoff>(hf.tellg()) : std::streamoff(-1);
190 if (length <= 0) {
191 std::fprintf(stderr, "VKC_HEAP_FILE: cannot read %s\n", heap_file_path.c_str());
192 return 2;
193 }
194 if (static_cast<unsigned long long>(length) > (1ull << 32) - heap_file_at) { // the last byte too must fit
195 std::fprintf(stderr, "VKC_HEAP_FILE: %s (%lld bytes) at 0x%llx runs past the 4 GiB heap\n",
196 heap_file_path.c_str(), static_cast<long long>(length),
197 static_cast<unsigned long long>(heap_file_at));
198 return 2;
199 }
200 heap_file.resize(static_cast<std::size_t>(length));
201 hf.seekg(0);
202 if (!hf.read(heap_file.data(), length)) {
187 std::fprintf(stderr, "VKC_HEAP_FILE: cannot read %s\n", heap_file_path.c_str()); 203 std::fprintf(stderr, "VKC_HEAP_FILE: cannot read %s\n", heap_file_path.c_str());
188 return 2; 204 return 2;
189 } 205 }
diff --git a/runtime/test/vk_host_at_aliasing_test.cpp b/runtime/test/vk_host_at_aliasing_test.cpp
new file mode 100644
index 000000000..06ce1946d
--- /dev/null
+++ b/runtime/test/vk_host_at_aliasing_test.cpp
@@ -0,0 +1,257 @@
1// VulkanContext::replay_.host_at resolution across aliasing placed buffers (via KHR TLAS array-of-pointers staging).
2// Public runtime classes with fake Vulkan procedures: no loader, GPU, or game data.
3#include "../src/vulkan_backend.h"
4
5#include <array>
6#include <cstdint>
7#include <cstdio>
8#include <cstring>
9#include <type_traits>
10#include <vector>
11
12namespace {
13
14int failures = 0;
15int live_buffers = 0;
16int live_memories = 0;
17int mapped_count = 0;
18int as_builds = 0;
19bool build_saw_array_of_pointers = false;
20VkDeviceAddress build_instances_address = 0;
21std::array<std::uint8_t, 256> stage_bytes{};
22std::vector<std::uint64_t> staged_addresses;
23
24void expect(bool ok, const char* what) {
25 if (!ok) {
26 std::fprintf(stderr, "FAIL: %s\n", what);
27 ++failures;
28 }
29}
30
31template<typename Handle>
32Handle handle(std::uintptr_t value) {
33 if constexpr (std::is_pointer_v<Handle>)
34 return reinterpret_cast<Handle>(value);
35 else
36 return static_cast<Handle>(value);
37}
38
39constexpr VkDeviceAddress kStageDeviceAddress = 0xfeed0000ull;
40
41VKAPI_ATTR VkResult VKAPI_CALL mock_create_pool(VkDevice, const VkCommandPoolCreateInfo*,
42 const VkAllocationCallbacks*, VkCommandPool* out) {
43 *out = handle<VkCommandPool>(1);
44 return VK_SUCCESS;
45}
46VKAPI_ATTR void VKAPI_CALL mock_destroy_pool(VkDevice, VkCommandPool, const VkAllocationCallbacks*) {}
47VKAPI_ATTR VkResult VKAPI_CALL mock_create_semaphore(VkDevice, const VkSemaphoreCreateInfo*,
48 const VkAllocationCallbacks*, VkSemaphore* out) {
49 *out = handle<VkSemaphore>(1);
50 return VK_SUCCESS;
51}
52VKAPI_ATTR void VKAPI_CALL mock_destroy_semaphore(VkDevice, VkSemaphore, const VkAllocationCallbacks*) {}
53VKAPI_ATTR VkResult VKAPI_CALL mock_semaphore_counter(VkDevice, VkSemaphore, std::uint64_t* out) {
54 *out = UINT64_MAX;
55 return VK_SUCCESS;
56}
57VKAPI_ATTR VkResult VKAPI_CALL mock_queue_wait_idle(VkQueue) { return VK_SUCCESS; }
58VKAPI_ATTR VkResult VKAPI_CALL mock_allocate_commands(VkDevice, const VkCommandBufferAllocateInfo*,
59 VkCommandBuffer* out) {
60 *out = handle<VkCommandBuffer>(1);
61 return VK_SUCCESS;
62}
63VKAPI_ATTR VkResult VKAPI_CALL mock_reset_command(VkCommandBuffer, VkCommandBufferResetFlags) { return VK_SUCCESS; }
64VKAPI_ATTR VkResult VKAPI_CALL mock_begin_command(VkCommandBuffer, const VkCommandBufferBeginInfo*) { return VK_SUCCESS; }
65VKAPI_ATTR VkResult VKAPI_CALL mock_end_command(VkCommandBuffer) { return VK_SUCCESS; }
66VKAPI_ATTR VkResult VKAPI_CALL mock_queue_submit(VkQueue, std::uint32_t, const VkSubmitInfo*, VkFence) {
67 return VK_SUCCESS;
68}
69VKAPI_ATTR void VKAPI_CALL mock_cmd_barrier(VkCommandBuffer, VkPipelineStageFlags, VkPipelineStageFlags,
70 VkDependencyFlags, std::uint32_t, const VkMemoryBarrier*, std::uint32_t,
71 const VkBufferMemoryBarrier*, std::uint32_t,
72 const VkImageMemoryBarrier*) {}
73VKAPI_ATTR VkResult VKAPI_CALL mock_create_buffer(VkDevice, const VkBufferCreateInfo*, const VkAllocationCallbacks*,
74 VkBuffer* out) {
75 ++live_buffers;
76 *out = handle<VkBuffer>(0x100 + live_buffers);
77 return VK_SUCCESS;
78}
79VKAPI_ATTR void VKAPI_CALL mock_destroy_buffer(VkDevice, VkBuffer, const VkAllocationCallbacks*) { --live_buffers; }
80VKAPI_ATTR void VKAPI_CALL mock_buffer_memory_reqs(VkDevice, VkBuffer, VkMemoryRequirements* reqs) {
81 reqs->size = stage_bytes.size();
82 reqs->alignment = 16;
83 reqs->memoryTypeBits = 1u;
84}
85VKAPI_ATTR VkResult VKAPI_CALL mock_allocate_memory(VkDevice, const VkMemoryAllocateInfo*, const VkAllocationCallbacks*,
86 VkDeviceMemory* out) {
87 ++live_memories;
88 *out = handle<VkDeviceMemory>(0x200 + live_memories);
89 return VK_SUCCESS;
90}
91VKAPI_ATTR void VKAPI_CALL mock_free_memory(VkDevice, VkDeviceMemory, const VkAllocationCallbacks*) { --live_memories; }
92VKAPI_ATTR VkResult VKAPI_CALL mock_bind_buffer_memory(VkDevice, VkBuffer, VkDeviceMemory, VkDeviceSize) {
93 return VK_SUCCESS;
94}
95VKAPI_ATTR VkResult VKAPI_CALL mock_map_memory(VkDevice, VkDeviceMemory, VkDeviceSize offset, VkDeviceSize,
96 VkMemoryMapFlags, void** data) {
97 ++mapped_count;
98 *data = stage_bytes.data() + offset;
99 return VK_SUCCESS;
100}
101VKAPI_ATTR void VKAPI_CALL mock_unmap_memory(VkDevice, VkDeviceMemory) { --mapped_count; }
102VKAPI_ATTR VkDeviceAddress VKAPI_CALL mock_buffer_device_address(VkDevice, const VkBufferDeviceAddressInfo*) {
103 return kStageDeviceAddress;
104}
105VKAPI_ATTR void VKAPI_CALL mock_build_as(VkCommandBuffer, std::uint32_t info_count,
106 const VkAccelerationStructureBuildGeometryInfoKHR* infos,
107 const VkAccelerationStructureBuildRangeInfoKHR* const* ranges) {
108 ++as_builds;
109 if (info_count && infos && infos[0].geometryCount && infos[0].pGeometries &&
110 infos[0].pGeometries[0].geometryType == VK_GEOMETRY_TYPE_INSTANCES_KHR) {
111 const auto& inst = infos[0].pGeometries[0].geometry.instances;
112 build_saw_array_of_pointers = inst.arrayOfPointers == VK_TRUE;
113 build_instances_address = inst.data.deviceAddress;
114 const std::uint32_t n = ranges && ranges[0] ? ranges[0][0].primitiveCount : 0;
115 staged_addresses.resize(n);
116 for (std::uint32_t i = 0; i < n; ++i)
117 std::memcpy(&staged_addresses[i], stage_bytes.data() + 8ull * i, sizeof(std::uint64_t));
118 }
119}
120
121VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL mock_proc(VkDevice, const char* name) {
122#define PROC(vk_name, impl) \
123 if (std::strcmp(name, #vk_name) == 0) return reinterpret_cast<PFN_vkVoidFunction>(impl)
124 PROC(vkCreateCommandPool, mock_create_pool);
125 PROC(vkDestroyCommandPool, mock_destroy_pool);
126 PROC(vkCreateSemaphore, mock_create_semaphore);
127 PROC(vkDestroySemaphore, mock_destroy_semaphore);
128 PROC(vkGetSemaphoreCounterValue, mock_semaphore_counter);
129 PROC(vkQueueWaitIdle, mock_queue_wait_idle);
130 PROC(vkAllocateCommandBuffers, mock_allocate_commands);
131 PROC(vkResetCommandBuffer, mock_reset_command);
132 PROC(vkBeginCommandBuffer, mock_begin_command);
133 PROC(vkEndCommandBuffer, mock_end_command);
134 PROC(vkQueueSubmit, mock_queue_submit);
135 PROC(vkCmdPipelineBarrier, mock_cmd_barrier);
136 PROC(vkCreateBuffer, mock_create_buffer);
137 PROC(vkDestroyBuffer, mock_destroy_buffer);
138 PROC(vkGetBufferMemoryRequirements, mock_buffer_memory_reqs);
139 PROC(vkAllocateMemory, mock_allocate_memory);
140 PROC(vkFreeMemory, mock_free_memory);
141 PROC(vkBindBufferMemory, mock_bind_buffer_memory);
142 PROC(vkMapMemory, mock_map_memory);
143 PROC(vkUnmapMemory, mock_unmap_memory);
144 PROC(vkGetBufferDeviceAddress, mock_buffer_device_address);
145 PROC(vkCmdBuildAccelerationStructuresKHR, mock_build_as);
146#undef PROC
147 return nullptr;
148}
149
150leonida::ResourceBinding make_buffer(std::uintptr_t id, std::uint64_t va, std::uint64_t size,
151 const std::uint8_t* host) {
152 leonida::ResourceBinding b{};
153 b.buffer = handle<VkBuffer>(id);
154 b.va = va;
155 b.size = size;
156 b.host = host;
157 return b;
158}
159
160leonida::ReplayResult run_tlas_pointers(leonida::VulkanContext& ctx, std::uint64_t dst_va, std::uint64_t pointers_va,
161 std::uint32_t instance_count) {
162 leonida::BuildAccelerationStructure b{};
163 b.is_tlas = true;
164 b.dst_va = dst_va;
165 b.scratch_va = 0x20000;
166 b.instances_va = pointers_va;
167 b.instance_count = instance_count;
168 b.instance_pointers = true;
169
170 leonida::CommandList list;
171 expect(list.build_acceleration_structure(std::move(b)) && list.close(), "invalid TLAS test command list");
172 leonida::VulkanQueue queue(ctx, handle<VkQueue>(1), 0);
173 expect(queue.ok(), "mock VulkanQueue did not initialize");
174 const leonida::CommandList* lists[] = {&list};
175 return queue.execute(lists);
176}
177
178} // namespace
179
180int main() {
181 constexpr std::uint64_t kHeapBase = 0x1000000ull;
182 constexpr std::uint64_t kDstVa = 0x10000ull;
183 constexpr std::uint64_t kInstVa = 0x4000ull;
184 constexpr std::uint64_t kPtrVa = 0x8000ull;
185 constexpr std::uint64_t kGpuVa = 0xc000ull;
186 constexpr std::uint64_t kBaseVa = 0xe000ull;
187
188 {
189 leonida::VulkanContext ctx(mock_proc, handle<VkDevice>(1), false, false, true, false);
190 VkPhysicalDeviceMemoryProperties mem{};
191 mem.memoryHeapCount = 1;
192 mem.memoryHeaps[0].size = 1024 * 1024;
193 mem.memoryTypes[0].propertyFlags =
194 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
195 mem.memoryTypes[0].heapIndex = 0;
196 mem.memoryTypeCount = 1;
197 ctx.set_occlusion_resolve_memory(mem);
198 ctx.set_heap_base(kHeapBase);
199 ctx.register_acceleration_structure(kDstVa, handle<VkAccelerationStructureKHR>(0x500));
200
201 // Backing buffer covering both 64-byte instance descriptors.
202 std::array<std::uint8_t, 128> inst_storage{};
203 ctx.add_resource(1, make_buffer(1, kInstVa, inst_storage.size(), inst_storage.data()));
204
205 // Case 1: Tied-start aliasing upload buffers: ID 10 holds 64 bytes, higher-ID 20 holds only 8 bytes.
206 // host_at(kPtrVa, 16) must pick ID 10 instead of failing on ID 20.
207 std::array<std::uint64_t, 8> big_ptrs{kInstVa, kInstVa + 64};
208 std::array<std::uint64_t, 1> small_ptrs{kInstVa + 64};
209 ctx.add_resource(10, make_buffer(10, kPtrVa, big_ptrs.size() * sizeof(std::uint64_t),
210 reinterpret_cast<const std::uint8_t*>(big_ptrs.data())));
211 ctx.add_resource(20, make_buffer(20, kPtrVa, small_ptrs.size() * sizeof(std::uint64_t),
212 reinterpret_cast<const std::uint8_t*>(small_ptrs.data())));
213
214 as_builds = 0;
215 staged_addresses.clear();
216 expect(run_tlas_pointers(ctx, kDstVa, kPtrVa, 2) == leonida::ReplayResult::success,
217 "host_at must resolve aliasing larger placed upload buffer for full byte range");
218 expect(as_builds == 1 && build_saw_array_of_pointers && build_instances_address == kStageDeviceAddress,
219 "TLAS build did not consume staged KHR pointer buffer");
220 expect(staged_addresses.size() == 2 && staged_addresses[0] == kHeapBase + kInstVa &&
221 staged_addresses[1] == kHeapBase + kInstVa + 64,
222 "staged instance device addresses came from wrong aliasing buffer");
223
224 // Case 2: Request larger than every aliasing buffer (80 > 64) still fails with invalid_copy.
225 as_builds = 0;
226 expect(run_tlas_pointers(ctx, kDstVa, kPtrVa, 10) == leonida::ReplayResult::invalid_copy && as_builds == 0,
227 "oversized range past every aliasing buffer must fail");
228
229 // Case 3: Non-CPU-written (DEFAULT/READBACK, host == nullptr) buffer returns unsupported without falling through.
230 ctx.add_resource(30, make_buffer(30, kGpuVa, 64, nullptr));
231 expect(run_tlas_pointers(ctx, kDstVa, kGpuVa, 2) == leonida::ReplayResult::unsupported,
232 "GPU-only buffer must return unsupported");
233
234 // Case 4: Offset aliasing: small placed buffer starting inside a larger CPU-mapped placed buffer.
235 std::array<std::uint64_t, 16> offset_big{};
236 offset_big[4] = kInstVa;
237 offset_big[5] = kInstVa + 64;
238 std::array<std::uint64_t, 1> offset_small{kInstVa};
239 ctx.add_resource(40, make_buffer(40, kBaseVa, offset_big.size() * sizeof(std::uint64_t),
240 reinterpret_cast<const std::uint8_t*>(offset_big.data())));
241 ctx.add_resource(41, make_buffer(41, kBaseVa + 32, offset_small.size() * sizeof(std::uint64_t),
242 reinterpret_cast<const std::uint8_t*>(offset_small.data())));
243 as_builds = 0;
244 staged_addresses.clear();
245 expect(run_tlas_pointers(ctx, kDstVa, kBaseVa + 32, 2) == leonida::ReplayResult::success && as_builds == 1,
246 "host_at at offset must fall back to aliasing container buffer holding full range");
247 expect(staged_addresses.size() == 2 && staged_addresses[0] == kHeapBase + kInstVa &&
248 staged_addresses[1] == kHeapBase + kInstVa + 64,
249 "offset aliasing staged wrong addresses");
250 }
251
252 expect(live_buffers == 0 && live_memories == 0 && mapped_count == 0,
253 "mock staging buffers/memories leaked after VulkanContext teardown");
254 if (failures) return 1;
255 std::puts("vk_host_at_aliasing: ok");
256 return 0;
257}
diff --git a/runtime/test/vk_queue_test.cpp b/runtime/test/vk_queue_test.cpp
index 744adfab8..8dad391b0 100644
--- a/runtime/test/vk_queue_test.cpp
+++ b/runtime/test/vk_queue_test.cpp
@@ -64,6 +64,33 @@ VKAPI_ATTR VkResult VKAPI_CALL stalling_wait_semaphores(VkDevice device, const V
64 return real_wait_semaphores(device, info, timeout); 64 return real_wait_semaphores(device, info, timeout);
65} 65}
66 66
67// Each submission's command buffer starts with a full memory barrier (D3D12's ExecuteCommandLists boundary): counts
68// the command buffers begun and those whose first barrier is that one.
69PFN_vkBeginCommandBuffer real_begin = nullptr;
70PFN_vkCmdPipelineBarrier real_barrier = nullptr;
71std::uint32_t begun = 0, led_by_full_barrier = 0;
72bool awaiting_first_barrier = false;
73
74VKAPI_ATTR VkResult VKAPI_CALL counting_begin(VkCommandBuffer cb, const VkCommandBufferBeginInfo* info) {
75 ++begun;
76 awaiting_first_barrier = true;
77 return real_begin(cb, info);
78}
79
80VKAPI_ATTR void VKAPI_CALL watching_barrier(VkCommandBuffer cb, VkPipelineStageFlags src, VkPipelineStageFlags dst,
81 VkDependencyFlags flags, std::uint32_t memory_count,
82 const VkMemoryBarrier* memory, std::uint32_t buffer_count,
83 const VkBufferMemoryBarrier* buffers, std::uint32_t image_count,
84 const VkImageMemoryBarrier* images) {
85 if (awaiting_first_barrier) {
86 awaiting_first_barrier = false;
87 if (src == VK_PIPELINE_STAGE_ALL_COMMANDS_BIT && dst == VK_PIPELINE_STAGE_ALL_COMMANDS_BIT &&
88 memory_count == 1 && (memory[0].srcAccessMask & VK_ACCESS_MEMORY_WRITE_BIT))
89 ++led_by_full_barrier;
90 }
91 real_barrier(cb, src, dst, flags, memory_count, memory, buffer_count, buffers, image_count, images);
92}
93
67const char* flags_text(VkQueueFlags f) { 94const char* flags_text(VkQueueFlags f) {
68 static char buf[32]; 95 static char buf[32];
69 std::snprintf(buf, sizeof buf, "%s%s%s", f & VK_QUEUE_GRAPHICS_BIT ? "G" : "", f & VK_QUEUE_COMPUTE_BIT ? "C" : "", 96 std::snprintf(buf, sizeof buf, "%s%s%s", f & VK_QUEUE_GRAPHICS_BIT ? "G" : "", f & VK_QUEUE_COMPUTE_BIT ? "C" : "",
@@ -347,6 +374,38 @@ int main() {
347 EXPECT(compute.execute(clear_lists) == ReplayResult::unsupported); 374 EXPECT(compute.execute(clear_lists) == ReplayResult::unsupported);
348 std::printf("copy and compute queues refuse a render-target clear\n"); 375 std::printf("copy and compute queues refuse a render-target clear\n");
349 376
377 // 4b. Two ExecuteCommandLists copying into the same buffer, with no barrier in either list: D3D12 orders them (each
378 // ends with its work done and visible), so each submission's command buffer must start with a full memory barrier.
379 // Before, none did, and synchronization validation reported WRITE_AFTER_WRITE between them (in 5 below).
380 {
381 void* map = nullptr;
382 VkBuffer twice_src = d.buffer(4096, usage, &map);
383 VkBuffer twice_dst = d.buffer(4096, usage, &map);
384 EXPECT(twice_src && twice_dst);
385 add_buffer(9, twice_src, 4096);
386 add_buffer(10, twice_dst, 4096);
387 CommandList twice;
388 EXPECT(twice.copy_buffer({10, 0, 9, 0, 4096}));
389 EXPECT(twice.close());
390 const CommandList* twice_lists[] = {&twice};
391 real_begin = context.vk.vkBeginCommandBuffer;
392 real_barrier = context.vk.vkCmdPipelineBarrier;
393 context.vk.vkBeginCommandBuffer = counting_begin;
394 context.vk.vkCmdPipelineBarrier = watching_barrier;
395 begun = led_by_full_barrier = 0;
396 for (Kind kind : {Kind::direct, Kind::copy}) {
397 VulkanQueue& q = kind == Kind::direct ? direct : copy;
398 EXPECT(q.execute(twice_lists) == ReplayResult::success);
399 EXPECT(q.execute(twice_lists) == ReplayResult::success);
400 EXPECT(q.idle());
401 }
402 context.vk.vkBeginCommandBuffer = real_begin;
403 context.vk.vkCmdPipelineBarrier = real_barrier;
404 std::printf("ExecuteCommandLists boundary: %u of %u submissions start with a full memory barrier\n",
405 led_by_full_barrier, begun);
406 EXPECT(begun >= 4 && led_by_full_barrier == begun);
407 }
408
350 // 5. A caller that submits faster than the GPU finishes must not grow the queue's command buffers without bound: 409 // 5. A caller that submits faster than the GPU finishes must not grow the queue's command buffers without bound:
351 // at the cap it waits for the oldest one. Big host-visible copies keep the GPU behind the submitting loop. The first 410 // at the cap it waits for the oldest one. Big host-visible copies keep the GPU behind the submitting loop. The first
352 // waits time out (injected), as on a stalled GPU: the cap must hold through a timeout too. 411 // waits time out (injected), as on a stalled GPU: the cap must hold through a timeout too.
diff --git a/runtime/test/vk_store_test.cpp b/runtime/test/vk_store_test.cpp
index 5567511d0..99a602aeb 100644
--- a/runtime/test/vk_store_test.cpp
+++ b/runtime/test/vk_store_test.cpp
@@ -16,6 +16,10 @@
16// at binding 7, where 2D and 3D image atomics address their image, and at index 4 of the sampled array a 16x4 rgba8 16// at binding 7, where 2D and 3D image atomics address their image, and at index 4 of the sampled array a 16x4 rgba8
17// image with all five mip levels (never read, only queried), behind the T# the runtime writes for such an image. 17// image with all five mip levels (never read, only queried), behind the T# the runtime writes for such an image.
18// "signed-zero" checks three direct float stores and all remaining RGBA32 guard words (SHADER-605). 18// "signed-zero" checks three direct float stores and all remaining RGBA32 guard words (SHADER-605).
19// "cube" (cs_imgstore_cube.asm, GPU-CUBE-STORE): the shader stores to three cube images (the same three formats, T#
20// word3 TYPE = SQ_RSRC_IMG_CUBE). As the runtime binds a cube UAV (runtime/src/vulkan_bindless.h), each is a
21// cube-compatible 8x8 image of six layers whose storage view is a six-layer 2D array, at index k + 1 of the 2D-array
22// storage arrays (bindings 11 / 12 / 13 for float / uint / sint). Checks every texel of every layer (the face).
19#include "vulkan_loader.h" 23#include "vulkan_loader.h"
20#include "vk_device_pick.h" 24#include "vk_device_pick.h"
21#include "vk_shader_fma.h" 25#include "vk_shader_fma.h"
@@ -60,7 +64,10 @@ static void table_insert(std::vector<uint32_t>& t, const uint32_t key[8], uint32
60} 64}
61 65
62int main(int argc, char** argv) { 66int main(int argc, char** argv) {
63 if (argc < 2) { std::fprintf(stderr, "usage: vk_store_test cs.spv [load|load-d16|words|signed-zero]\n"); return 2; } 67 if (argc < 2) {
68 std::fprintf(stderr, "usage: vk_store_test cs.spv [load|load-d16|words|signed-zero|cube]\n");
69 return 2;
70 }
64 gipa = load_vulkan(); 71 gipa = load_vulkan();
65 if (!gipa) return 1; 72 if (!gipa) return 1;
66#define LOADI(name) auto name = reinterpret_cast<PFN_##name>(gipa(inst, #name)) 73#define LOADI(name) auto name = reinterpret_cast<PFN_##name>(gipa(inst, #name))
@@ -126,6 +133,7 @@ int main(int argc, char** argv) {
126 // "words" mode: the two images filled as for "load"; the shader's results are whatever it leaves in them. 133 // "words" mode: the two images filled as for "load"; the shader's results are whatever it leaves in them.
127 const bool words_mode = argc > 2 && !std::strcmp(argv[2], "words"); 134 const bool words_mode = argc > 2 && !std::strcmp(argv[2], "words");
128 const bool signed_zero = argc > 2 && !std::strcmp(argv[2], "signed-zero"); 135 const bool signed_zero = argc > 2 && !std::strcmp(argv[2], "signed-zero");
136 const bool cube_mode = argc > 2 && !std::strcmp(argv[2], "cube");
129 if (signed_zero) { 137 if (signed_zero) {
130 LOADI(vkGetPhysicalDeviceProperties2); 138 LOADI(vkGetPhysicalDeviceProperties2);
131 VkPhysicalDeviceFloatControlsProperties controls{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FLOAT_CONTROLS_PROPERTIES}; 139 VkPhysicalDeviceFloatControlsProperties controls{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FLOAT_CONTROLS_PROPERTIES};
@@ -224,6 +232,10 @@ int main(int argc, char** argv) {
224 uint32_t t[8] = {0x1000 * (k + 1), fmts[k] << 20}; 232 uint32_t t[8] = {0x1000 * (k + 1), fmts[k] << 20};
225 for (int j = 2; j < 8; j++) t[j] = 0x11 * (k + 1); 233 for (int j = 2; j < 8; j++) t[j] = 0x11 * (k + 1);
226 table_insert(table, t, k + 1); // its index in the 2D arrays; 0 is the fallback, as in the runtime 234 table_insert(table, t, k + 1); // its index in the 2D arrays; 0 is the fallback, as in the runtime
235 if (cube_mode) { // the cube T# (cs_imgstore_cube.asm): word3 also has TYPE = 0xB, index k + 1 of the 2D arrays
236 t[3] |= 0xB0000000u;
237 table_insert(table, t, k + 1);
238 }
227 } 239 }
228 // Index 4: a 16x4 rgba8 image with its whole mip chain (16x4, 8x2, 4x1, 2x1, 1x1) for image_get_resinfo. Its key 240 // Index 4: a 16x4 rgba8 image with its whole mip chain (16x4, 8x2, 4x1, 2x1, 1x1) for image_get_resinfo. Its key
229 // is the T# of exactly that image (gfx10_descriptors.h), which cs_resinfo.asm builds word for word. 241 // is the T# of exactly that image (gfx10_descriptors.h), which cs_resinfo.asm builds word for word.
@@ -296,6 +308,26 @@ int main(int argc, char** argv) {
296 vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; 308 vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
297 CHECK(vkCreateImageView(dev, &vi, nullptr, &vol_view)); 309 CHECK(vkCreateImageView(dev, &vi, nullptr, &vol_view));
298 } 310 }
311 // Cube mode: three cube-compatible 8x8 images of six layers, each seen through a six-layer 2D-array view.
312 const uint32_t FACES = 6;
313 VkImage cube[3]{}; VkImageView cube_view[3]{};
314 for (int k = 0; cube_mode && k < 3; k++) {
315 VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO};
316 ii.flags = VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT;
317 ii.imageType = VK_IMAGE_TYPE_2D; ii.format = vkf[k]; ii.extent = {W, W, 1}; ii.mipLevels = 1;
318 ii.arrayLayers = FACES; ii.samples = VK_SAMPLE_COUNT_1_BIT; ii.tiling = VK_IMAGE_TILING_OPTIMAL;
319 ii.usage = VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
320 CHECK(vkCreateImage(dev, &ii, nullptr, &cube[k]));
321 VkMemoryRequirements mr; vkGetImageMemoryRequirements(dev, cube[k], &mr);
322 VkMemoryAllocateInfo mai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
323 mai.allocationSize = mr.size; mai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
324 VkDeviceMemory m; CHECK(vkAllocateMemory(dev, &mai, nullptr, &m));
325 CHECK(vkBindImageMemory(dev, cube[k], m, 0));
326 VkImageViewCreateInfo vi{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO};
327 vi.image = cube[k]; vi.viewType = VK_IMAGE_VIEW_TYPE_2D_ARRAY; vi.format = vkf[k];
328 vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, FACES};
329 CHECK(vkCreateImageView(dev, &vi, nullptr, &cube_view[k]));
330 }
299 VkSamplerCreateInfo sci{VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO}; 331 VkSamplerCreateInfo sci{VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO};
300 VkSampler sampler; CHECK(vkCreateSampler(dev, &sci, nullptr, &sampler)); 332 VkSampler sampler; CHECK(vkCreateSampler(dev, &sci, nullptr, &sampler));
301 // Set 0: binding 0 = sampled images, 1 = samplers, 2 = hash table, 8/9/10 = float/uint/sint 2D storage image arrays. 333 // Set 0: binding 0 = sampled images, 1 = samplers, 2 = hash table, 8/9/10 = float/uint/sint 2D storage image arrays.
@@ -303,23 +335,27 @@ int main(int argc, char** argv) {
303 // index 4. Binding 0 holds each image's view in its own format (typed image_load reads the uint and sint ones 335 // index 4. Binding 0 holds each image's view in its own format (typed image_load reads the uint and sint ones
304 // through integer aliases); every element of a storage array holds the image of its class, so all of them are 336 // through integer aliases); every element of a storage array holds the image of its class, so all of them are
305 // valid descriptors. Bindings 4 and 7 = the 2D and 3D r32ui storage images of the image atomics: the uint image 337 // valid descriptors. Bindings 4 and 7 = the 2D and 3D r32ui storage images of the image atomics: the uint image
306 // and the volume, in every element. 338 // and the volume, in every element. Cube mode adds 11/12/13 = the float/uint/sint 2D-array storage arrays, which
339 // hold the cube image of their class in every element.
307 constexpr uint32_t N = 5; 340 constexpr uint32_t N = 5;
308 VkDescriptorSetLayoutBinding b[8]{}; 341 const uint32_t bindings = cube_mode ? 11 : 8;
342 VkDescriptorSetLayoutBinding b[11]{};
309 b[0] = {0, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, N, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; 343 b[0] = {0, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, N, VK_SHADER_STAGE_COMPUTE_BIT, nullptr};
310 b[1] = {1, VK_DESCRIPTOR_TYPE_SAMPLER, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; 344 b[1] = {1, VK_DESCRIPTOR_TYPE_SAMPLER, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr};
311 b[2] = {2, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; 345 b[2] = {2, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr};
312 for (int k = 0; k < 3; k++) b[3 + k] = {uint32_t(8 + k), VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, N, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; 346 for (int k = 0; k < 3; k++) b[3 + k] = {uint32_t(8 + k), VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, N, VK_SHADER_STAGE_COMPUTE_BIT, nullptr};
313 b[6] = {4, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, N, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; 347 b[6] = {4, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, N, VK_SHADER_STAGE_COMPUTE_BIT, nullptr};
314 b[7] = {7, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, N, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; 348 b[7] = {7, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, N, VK_SHADER_STAGE_COMPUTE_BIT, nullptr};
349 for (int k = 0; k < 3; k++)
350 b[8 + k] = {uint32_t(11 + k), VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, N, VK_SHADER_STAGE_COMPUTE_BIT, nullptr};
315 VkDescriptorSetLayoutCreateInfo dli{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; 351 VkDescriptorSetLayoutCreateInfo dli{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO};
316 dli.bindingCount = 8; dli.pBindings = b; 352 dli.bindingCount = bindings; dli.pBindings = b;
317 VkDescriptorSetLayout dsl; CHECK(vkCreateDescriptorSetLayout(dev, &dli, nullptr, &dsl)); 353 VkDescriptorSetLayout dsl; CHECK(vkCreateDescriptorSetLayout(dev, &dli, nullptr, &dsl));
318 VkDescriptorPoolSize ps[4] = { 354 VkDescriptorPoolSize ps[4] = {
319 {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, N}, 355 {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, N},
320 {VK_DESCRIPTOR_TYPE_SAMPLER, 1}, 356 {VK_DESCRIPTOR_TYPE_SAMPLER, 1},
321 {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}, 357 {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1},
322 {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 5 * N}, 358 {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, (bindings - 3) * N},
323 }; 359 };
324 VkDescriptorPoolCreateInfo dpi{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; 360 VkDescriptorPoolCreateInfo dpi{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO};
325 dpi.maxSets = 1; dpi.poolSizeCount = 4; dpi.pPoolSizes = ps; 361 dpi.maxSets = 1; dpi.poolSizeCount = 4; dpi.pPoolSizes = ps;
@@ -335,8 +371,8 @@ int main(int argc, char** argv) {
335 {VK_NULL_HANDLE, wide_view, VK_IMAGE_LAYOUT_GENERAL}}; 371 {VK_NULL_HANDLE, wide_view, VK_IMAGE_LAYOUT_GENERAL}};
336 VkDescriptorImageInfo smpi{sampler, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_UNDEFINED}; 372 VkDescriptorImageInfo smpi{sampler, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_UNDEFINED};
337 VkDescriptorImageInfo dii[3][N]; 373 VkDescriptorImageInfo dii[3][N];
338 VkDescriptorImageInfo r32ui[N], r32ui_3d[N]; 374 VkDescriptorImageInfo r32ui[N], r32ui_3d[N], cube_ii[3][N];
339 VkWriteDescriptorSet wr[8]{}; 375 VkWriteDescriptorSet wr[11]{};
340 for (auto& w : wr) { w.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; w.dstSet = ds; w.descriptorCount = 1; } 376 for (auto& w : wr) { w.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; w.dstSet = ds; w.descriptorCount = 1; }
341 wr[0].dstBinding = 0; wr[0].descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; wr[0].pImageInfo = sii; 377 wr[0].dstBinding = 0; wr[0].descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; wr[0].pImageInfo = sii;
342 wr[0].descriptorCount = N; 378 wr[0].descriptorCount = N;
@@ -353,7 +389,12 @@ int main(int argc, char** argv) {
353 for (uint32_t e = 0; e < N; e++) r32ui_3d[e] = {VK_NULL_HANDLE, vol_view, VK_IMAGE_LAYOUT_GENERAL}; 389 for (uint32_t e = 0; e < N; e++) r32ui_3d[e] = {VK_NULL_HANDLE, vol_view, VK_IMAGE_LAYOUT_GENERAL};
354 wr[7].dstBinding = 7; wr[7].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; 390 wr[7].dstBinding = 7; wr[7].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
355 wr[7].pImageInfo = r32ui_3d; wr[7].descriptorCount = N; 391 wr[7].pImageInfo = r32ui_3d; wr[7].descriptorCount = N;
356 vkUpdateDescriptorSets(dev, 8, wr, 0, nullptr); 392 for (int k = 0; cube_mode && k < 3; k++) {
393 for (uint32_t e = 0; e < N; e++) cube_ii[k][e] = {VK_NULL_HANDLE, cube_view[k], VK_IMAGE_LAYOUT_GENERAL};
394 wr[8 + k].dstBinding = 11 + k; wr[8 + k].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
395 wr[8 + k].pImageInfo = cube_ii[k]; wr[8 + k].descriptorCount = N;
396 }
397 vkUpdateDescriptorSets(dev, bindings, wr, 0, nullptr);
357 398
358 VkShaderModuleCreateInfo smi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; 399 VkShaderModuleCreateInfo smi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO};
359 smi.codeSize = code.size(); smi.pCode = reinterpret_cast<const uint32_t*>(code.data()); 400 smi.codeSize = code.size(); smi.pCode = reinterpret_cast<const uint32_t*>(code.data());
@@ -383,6 +424,11 @@ int main(int argc, char** argv) {
383 const uint32_t image_words = W * W * (signed_zero ? 4 : 1); 424 const uint32_t image_words = W * W * (signed_zero ? 4 : 1);
384 VkBuffer rb[3]; void* rbp[3]; 425 VkBuffer rb[3]; void* rbp[3];
385 for (int k = 0; k < 3; k++) CHECK(make_buffer(image_words * 4, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &rb[k], &rbp[k])); 426 for (int k = 0; k < 3; k++) CHECK(make_buffer(image_words * 4, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &rb[k], &rbp[k]));
427 // Cube mode: each cube image's six layers read back one after another, texel (x, y) of face f at 64f + 8y + x.
428 const uint32_t cube_words = W * W * FACES;
429 VkBuffer cube_rb[3]{}; void* cube_rbp[3]{};
430 for (int k = 0; cube_mode && k < 3; k++)
431 CHECK(make_buffer(cube_words * 4, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &cube_rb[k], &cube_rbp[k]));
386 // Load and words modes: what the uint and sint images hold before the dispatch, texel (x, y) at i = 8y + x. 432 // Load and words modes: what the uint and sint images hold before the dispatch, texel (x, y) at i = 8y + x.
387 // The last row of the D16 fixture ("load-d16" only) exercises both sides of each 16-bit boundary. 433 // The last row of the D16 fixture ("load-d16" only) exercises both sides of each 16-bit boundary.
388 struct PackedLoad { uint32_t u; int32_t s, sum; }; 434 struct PackedLoad { uint32_t u; int32_t s, sum; };
@@ -471,6 +517,17 @@ int main(int argc, char** argv) {
471 vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, 517 vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0,
472 nullptr, 0, nullptr, 3 - first_fill, ib + first_fill); 518 nullptr, 0, nullptr, 3 - first_fill, ib + first_fill);
473 } 519 }
520 VkImageMemoryBarrier cube_ib[3]{};
521 for (int k = 0; cube_mode && k < 3; k++) {
522 cube_ib[k] = ib[0];
523 cube_ib[k].image = cube[k]; cube_ib[k].oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
524 cube_ib[k].newLayout = VK_IMAGE_LAYOUT_GENERAL; cube_ib[k].srcAccessMask = 0;
525 cube_ib[k].dstAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
526 cube_ib[k].subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, FACES};
527 }
528 if (cube_mode)
529 vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr,
530 0, nullptr, 3, cube_ib);
474 vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pipe); 531 vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pipe);
475 vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pl, 0, 1, &ds, 0, nullptr); 532 vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pl, 0, 1, &ds, 0, nullptr);
476 uint32_t pc[36] = {}; 533 uint32_t pc[36] = {};
@@ -493,6 +550,19 @@ int main(int argc, char** argv) {
493 bic.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; bic.imageExtent = {W, W, 1}; 550 bic.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; bic.imageExtent = {W, W, 1};
494 vkCmdCopyImageToBuffer(cmd, img[k], VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, rb[k], 1, &bic); 551 vkCmdCopyImageToBuffer(cmd, img[k], VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, rb[k], 1, &bic);
495 } 552 }
553 if (cube_mode) {
554 for (int k = 0; k < 3; k++) {
555 cube_ib[k].oldLayout = VK_IMAGE_LAYOUT_GENERAL; cube_ib[k].newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
556 cube_ib[k].srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; cube_ib[k].dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
557 }
558 vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0,
559 nullptr, 3, cube_ib);
560 for (int k = 0; k < 3; k++) {
561 VkBufferImageCopy bic{}; // all six layers, tightly packed one after another
562 bic.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, FACES}; bic.imageExtent = {W, W, 1};
563 vkCmdCopyImageToBuffer(cmd, cube[k], VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, cube_rb[k], 1, &bic);
564 }
565 }
496 if (words_mode) { 566 if (words_mode) {
497 vol_ib.oldLayout = VK_IMAGE_LAYOUT_GENERAL; vol_ib.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; 567 vol_ib.oldLayout = VK_IMAGE_LAYOUT_GENERAL; vol_ib.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
498 vol_ib.srcAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; 568 vol_ib.srcAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
@@ -514,6 +584,30 @@ int main(int argc, char** argv) {
514 CHECK(vkQueueSubmit(q, 1, &si, VK_NULL_HANDLE)); 584 CHECK(vkQueueSubmit(q, 1, &si, VK_NULL_HANDLE));
515 CHECK(vkQueueWaitIdle(q)); 585 CHECK(vkQueueWaitIdle(q));
516 586
587 if (cube_mode) { // every texel of every face, against what cs_imgstore_cube.asm writes there
588 uint32_t bad[3] = {};
589 for (uint32_t face = 0; face < FACES; face++)
590 for (uint32_t y = 0; y < W; y++)
591 for (uint32_t x = 0; x < W; x++) {
592 const uint32_t i = y * W + x, at = face * W * W + i;
593 const uint8_t* c = static_cast<const uint8_t*>(cube_rbp[0]) + 4 * at;
594 const int er = int(std::lround(x / 7.0 * 255)), eg = int(std::lround(y / 7.0 * 255));
595 const int eb = int(std::lround(face / 5.0 * 255));
596 if (std::abs(c[0] - er) > 1 || std::abs(c[1] - eg) > 1 || std::abs(c[2] - eb) > 1 || c[3] != 255)
597 bad[0]++;
598 if (static_cast<const uint32_t*>(cube_rbp[1])[at] != 100 + 1000 * face + i) bad[1]++;
599 if (static_cast<const int32_t*>(cube_rbp[2])[at] != -int32_t(1000 * face + i)) bad[2]++;
600 }
601 const uint32_t at = 4 * W * W + 3 * W + 5; // texel (5, 3) of face 4
602 const uint8_t* c = static_cast<const uint8_t*>(cube_rbp[0]) + 4 * at;
603 std::printf("rgba8 unorm cube (float view): %u bad, face 4 texel(5,3) = %u %u %u %u\n", bad[0], c[0], c[1],
604 c[2], c[3]);
605 std::printf("r32 uint cube (uint view): %u bad, face 4 texel(5,3) = %u\n", bad[1],
606 static_cast<const uint32_t*>(cube_rbp[1])[at]);
607 std::printf("r32 sint cube (sint view): %u bad, face 4 texel(5,3) = %d\n", bad[2],
608 static_cast<const int32_t*>(cube_rbp[2])[at]);
609 return (bad[0] || bad[1] || bad[2]) ? 1 : 0;
610 }
517 if (signed_zero) { 611 if (signed_zero) {
518 constexpr uint32_t neg = 0x80000000; 612 constexpr uint32_t neg = 0x80000000;
519 constexpr uint32_t stores[] = {neg, 0, 0, 0, neg, 0x3f800000, 0, 0, neg, neg, 0, 0}; 613 constexpr uint32_t stores[] = {neg, 0, 0, 0, neg, 0x3f800000, 0, 0, neg, neg, 0, 0};
diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h
index 5cccd1836..f1083231b 100644
--- a/runtime/test/vk_test_device.h
+++ b/runtime/test/vk_test_device.h
@@ -106,6 +106,8 @@ public:
106 bool storage_buffer_8bit = false; // storageBuffer8BitAccess enabled 106 bool storage_buffer_8bit = false; // storageBuffer8BitAccess enabled
107 bool conditional_rendering = false; // VK_EXT_conditional_rendering enabled, where available 107 bool conditional_rendering = false; // VK_EXT_conditional_rendering enabled, where available
108 bool host_image_copy = false; // VK_EXT_host_image_copy and hostImageCopy enabled 108 bool host_image_copy = false; // VK_EXT_host_image_copy and hostImageCopy enabled
109 bool request_depth_range_unrestricted = false;
110 bool depth_range_unrestricted = false; // VK_EXT_depth_range_unrestricted enabled
109 // create(true) only: VK_KHR (else EXT) swapchain_maintenance1 and its feature enabled, with the surface half on the 111 // create(true) only: VK_KHR (else EXT) swapchain_maintenance1 and its feature enabled, with the surface half on the
110 // instance, so a vsync swapchain can switch to IMMEDIATE or FIFO_RELAXED per present. 112 // instance, so a vsync swapchain can switch to IMMEDIATE or FIFO_RELAXED per present.
111 bool swapchain_maintenance1 = false; 113 bool swapchain_maintenance1 = false;
@@ -118,6 +120,7 @@ public:
118 bool conservative_rasterization = false; // VK_EXT_conservative_rasterization enabled where available 120 bool conservative_rasterization = false; // VK_EXT_conservative_rasterization enabled where available
119 bool request_mesh_shader = false; // set before create(): enable VK_EXT_mesh_shader (meshShader) where available 121 bool request_mesh_shader = false; // set before create(): enable VK_EXT_mesh_shader (meshShader) where available
120 bool mesh_shader = false; // VK_EXT_mesh_shader and meshShader are enabled 122 bool mesh_shader = false; // VK_EXT_mesh_shader and meshShader are enabled
123 bool mesh_shader_queries = false; // the meshShaderQueries feature is enabled on the device
121 bool debug_utils = false; // VK_EXT_debug_utils is enabled on the instance 124 bool debug_utils = false; // VK_EXT_debug_utils is enabled on the instance
122 // The subgroup sizes of the device, with subgroupSizeControl and computeFullSubgroups enabled where it has them. 125 // The subgroup sizes of the device, with subgroupSizeControl and computeFullSubgroups enabled where it has them.
123 leonida::SubgroupSizeCaps subgroup; 126 leonida::SubgroupSizeCaps subgroup;
@@ -523,10 +526,13 @@ public:
523 VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &mesh_features}; 526 VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &mesh_features};
524 instance_fn<PFN_vkGetPhysicalDeviceFeatures2>("vkGetPhysicalDeviceFeatures2")(physical, &query); 527 instance_fn<PFN_vkGetPhysicalDeviceFeatures2>("vkGetPhysicalDeviceFeatures2")(physical, &query);
525 mesh_shader = mesh_features.meshShader == VK_TRUE; 528 mesh_shader = mesh_features.meshShader == VK_TRUE;
529 mesh_shader_queries = mesh_features.meshShaderQueries == VK_TRUE;
526 } 530 }
527 if (mesh_shader) { 531 if (mesh_shader) {
528 mesh_features = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT, *v13_.next()}; 532 mesh_features = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT, *v13_.next()};
529 mesh_features.meshShader = VK_TRUE; 533 mesh_features.meshShader = VK_TRUE;
534 // The mesh-primitives query, which counts the primitives a mesh shader emits (D3D-MESH-CLIPPING-COUNTER).
535 mesh_features.meshShaderQueries = mesh_shader_queries ? VK_TRUE : VK_FALSE;
530 *v13_.next() = &mesh_features; 536 *v13_.next() = &mesh_features;
531 } 537 }
532 enable.occlusionQueryPrecise = features.features.occlusionQueryPrecise; // query heaps, where available 538 enable.occlusionQueryPrecise = features.features.occlusionQueryPrecise; // query heaps, where available
@@ -567,6 +573,11 @@ public:
567 enabled = enable; 573 enabled = enable;
568 std::vector<const char*> device_extensions; 574 std::vector<const char*> device_extensions;
569 v13_.add_extensions(device_extensions); 575 v13_.add_extensions(device_extensions);
576 depth_range_unrestricted = request_depth_range_unrestricted &&
577 std::any_of(extensions.begin(), extensions.end(), [](const auto& e) {
578 return std::strcmp(e.extensionName, VK_EXT_DEPTH_RANGE_UNRESTRICTED_EXTENSION_NAME) == 0;
579 });
580 if (depth_range_unrestricted) device_extensions.push_back(VK_EXT_DEPTH_RANGE_UNRESTRICTED_EXTENSION_NAME);
570 conservative_rasterization = std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { 581 conservative_rasterization = std::any_of(extensions.begin(), extensions.end(), [](const auto& e) {
571 return std::strcmp(e.extensionName, VK_EXT_CONSERVATIVE_RASTERIZATION_EXTENSION_NAME) == 0; 582 return std::strcmp(e.extensionName, VK_EXT_CONSERVATIVE_RASTERIZATION_EXTENSION_NAME) == 0;
572 }); 583 });
diff --git a/runtime/test/vulkan_scratch_test.cpp b/runtime/test/vulkan_scratch_test.cpp
index 8ca6a819a..f63610615 100644
--- a/runtime/test/vulkan_scratch_test.cpp
+++ b/runtime/test/vulkan_scratch_test.cpp
@@ -8,6 +8,7 @@
8#include <cstdint> 8#include <cstdint>
9#include <cstdio> 9#include <cstdio>
10#include <cstring> 10#include <cstring>
11#include <limits>
11#include <unordered_map> 12#include <unordered_map>
12#include <unordered_set> 13#include <unordered_set>
13 14
@@ -289,6 +290,26 @@ int main() {
289 EXPECT(vk.live_buffers.empty() && vk.live_memory.empty()); 290 EXPECT(vk.live_buffers.empty() && vk.live_memory.empty());
290 } 291 }
291 292
293 // A chunk whose used byte count is within 255 bytes of UINT64_MAX must not wrap alignment back to offset 0.
294 {
295 FakeVulkan vk;
296 g_vk = &vk;
297 {
298 ScratchBuffers scratch(fake_get_device_proc, k_device, fake_allocate);
299 VkBuffer buf1 = VK_NULL_HANDLE, buf2 = VK_NULL_HANDLE;
300 VkDeviceSize off1 = 1, off2 = 1;
301 const std::uint64_t near_max = std::numeric_limits<std::uint64_t>::max() - 100u;
302 EXPECT(scratch.get(near_max, buf1, off1));
303 EXPECT(buf1 != VK_NULL_HANDLE && off1 == 0 && vk.create_buffer_calls == 1);
304
305 EXPECT(scratch.get(16, buf2, off2));
306 EXPECT(buf2 != VK_NULL_HANDLE && buf2 != buf1 && off2 == 0);
307 EXPECT(vk.create_buffer_calls == 2 && vk.allocate_calls == 2);
308 EXPECT(vk.live_buffers.size() == 2 && vk.live_memory.size() == 2);
309 }
310 EXPECT(vk.live_buffers.empty() && vk.live_memory.empty());
311 }
312
292 std::printf("vulkan_scratch: all checks passed\n"); 313 std::printf("vulkan_scratch: all checks passed\n");
293 return 0; 314 return 0;
294} 315}
diff --git a/runtime/test/ws2_offline_test.cpp b/runtime/test/ws2_offline_test.cpp
new file mode 100644
index 000000000..32cdda48c
--- /dev/null
+++ b/runtime/test/ws2_offline_test.cpp
@@ -0,0 +1,547 @@
1// Checks the offline Winsock2 (ws2_32.dll) shim (runtime/shims/ws2_offline.cpp).
2//
3// Resolves every shimmed symbol through rt::shims::find under ws2_32.dll (by name and by standard Windows ordinal),
4// checks that wsock32.dll resolves its shared entries to the same wrappers, and verifies that external addresses
5// (RFC 5737 192.0.2.1 / RFC 3849 2001:db8::1), .invalid hostnames, octal-looking 0127.0.0.1 and name-service queries
6// are refused in-process while loopback (127.0.0.1 / ::1 / localhost) still works. Sends on unbound UDP sockets bind
7// them to loopback, and multicast joins (setsockopt on both DLLs, WSAJoinLeaf) are refused. Nothing touches the network.
8#ifndef _WINSOCK_DEPRECATED_NO_WARNINGS
9#define _WINSOCK_DEPRECATED_NO_WARNINGS
10#endif
11#ifndef WIN32_LEAN_AND_MEAN
12#define WIN32_LEAN_AND_MEAN
13#endif
14#ifndef NOMINMAX
15#define NOMINMAX
16#endif
17
18#include <winsock2.h>
19#include <ws2tcpip.h>
20#include <mswsock.h>
21#include <windows.h>
22
23#include <cstdint>
24#include <cstdio>
25#include <cstring>
26
27#include "shims.h"
28
29#ifndef SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER
30#define SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER 0xC8000024u
31#endif
32
33namespace {
34
35int g_checks = 0;
36int g_failures = 0;
37
38void check(bool condition, const char* what) {
39 ++g_checks;
40 std::printf("%s %s\n", condition ? "PASS" : "FAIL", what);
41 if (!condition) ++g_failures;
42}
43
44template <typename Fn>
45Fn resolve(const char* sym) {
46 return reinterpret_cast<Fn>(rt::shims::find("ws2_32.dll", sym));
47}
48
49sockaddr_in make_v4(uint8_t a, uint8_t b, uint8_t c, uint8_t d, uint16_t port) {
50 sockaddr_in sa{};
51 sa.sin_family = AF_INET;
52 sa.sin_port = htons(port);
53 auto* bytes = reinterpret_cast<uint8_t*>(&sa.sin_addr);
54 bytes[0] = a;
55 bytes[1] = b;
56 bytes[2] = c;
57 bytes[3] = d;
58 return sa;
59}
60
61sockaddr_in6 make_v6_doc(uint16_t port) {
62 // 2001:db8::1 (RFC 3849 documentation prefix, non-loopback)
63 sockaddr_in6 sa{};
64 sa.sin6_family = AF_INET6;
65 sa.sin6_port = htons(port);
66 auto* bytes = reinterpret_cast<uint8_t*>(&sa.sin6_addr);
67 bytes[0] = 0x20;
68 bytes[1] = 0x01;
69 bytes[2] = 0x0d;
70 bytes[3] = 0xb8;
71 bytes[15] = 0x01;
72 return sa;
73}
74
75} // namespace
76
77int main() {
78 WSADATA wsa{};
79 if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) {
80 std::fprintf(stderr, "WSAStartup failed (%d)\n", WSAGetLastError());
81 return 1;
82 }
83
84 using BindFn = int(WSAAPI*)(SOCKET, const sockaddr*, int);
85 using ConnectFn = int(WSAAPI*)(SOCKET, const sockaddr*, int);
86 using SendToFn = int(WSAAPI*)(SOCKET, const char*, int, int, const sockaddr*, int);
87 using WsaConnectFn = int(WSAAPI*)(SOCKET, const sockaddr*, int, LPWSABUF, LPWSABUF, LPQOS, LPQOS);
88 using WsaConnectByNameAFn = BOOL(WSAAPI*)(SOCKET, LPCSTR, LPCSTR, LPDWORD, LPSOCKADDR, LPDWORD, LPSOCKADDR,
89 const timeval*, LPWSAOVERLAPPED);
90 using WsaConnectByNameWFn = BOOL(WSAAPI*)(SOCKET, LPWSTR, LPWSTR, LPDWORD, LPSOCKADDR, LPDWORD, LPSOCKADDR,
91 const timeval*, LPWSAOVERLAPPED);
92 using WsaConnectByListFn = BOOL(WSAAPI*)(SOCKET, PSOCKET_ADDRESS_LIST, LPDWORD, LPSOCKADDR, LPDWORD, LPSOCKADDR,
93 const timeval*, LPWSAOVERLAPPED);
94 using WsaSendToFn = int(WSAAPI*)(SOCKET, LPWSABUF, DWORD, LPDWORD, DWORD, const sockaddr*, int, LPWSAOVERLAPPED,
95 LPWSAOVERLAPPED_COMPLETION_ROUTINE);
96 using WsaSendMsgFn = int(WSAAPI*)(SOCKET, LPWSAMSG, DWORD, LPDWORD, LPWSAOVERLAPPED,
97 LPWSAOVERLAPPED_COMPLETION_ROUTINE);
98 using WsaIoctlFn = int(WSAAPI*)(SOCKET, DWORD, LPVOID, DWORD, LPVOID, DWORD, LPDWORD, LPWSAOVERLAPPED,
99 LPWSAOVERLAPPED_COMPLETION_ROUTINE);
100 using GetAddrInfoAFn = INT(WSAAPI*)(PCSTR, PCSTR, const ADDRINFOA*, PADDRINFOA*);
101 using GetAddrInfoWFn = INT(WSAAPI*)(PCWSTR, PCWSTR, const ADDRINFOW*, PADDRINFOW*);
102 using GetNameInfoAFn = INT(WSAAPI*)(const sockaddr*, socklen_t, PCHAR, DWORD, PCHAR, DWORD, INT);
103 using GetHostByNameFn = hostent*(WSAAPI*)(const char*);
104 using GetHostByAddrFn = hostent*(WSAAPI*)(const char*, int, int);
105 using LookupBeginWFn = int(WSAAPI*)(LPWSAQUERYSETW, DWORD, LPHANDLE);
106
107 const auto sh_bind = resolve<BindFn>("bind");
108 const auto sh_bind_ord = resolve<BindFn>("#2");
109 const auto sh_connect = resolve<ConnectFn>("connect");
110 const auto sh_connect_ord = resolve<ConnectFn>("#4");
111 const auto sh_sendto = resolve<SendToFn>("sendto");
112 const auto sh_sendto_ord = resolve<SendToFn>("#20");
113 const auto sh_wsa_connect = resolve<WsaConnectFn>("WSAConnect");
114 const auto sh_connect_name_a = resolve<WsaConnectByNameAFn>("WSAConnectByNameA");
115 const auto sh_connect_name_w = resolve<WsaConnectByNameWFn>("WSAConnectByNameW");
116 const auto sh_connect_list = resolve<WsaConnectByListFn>("WSAConnectByList");
117 const auto sh_wsa_sendto = resolve<WsaSendToFn>("WSASendTo");
118 const auto sh_wsa_sendmsg = resolve<WsaSendMsgFn>("WSASendMsg");
119 const auto sh_wsa_ioctl = resolve<WsaIoctlFn>("WSAIoctl");
120 const auto sh_getaddrinfo = resolve<GetAddrInfoAFn>("getaddrinfo");
121 const auto sh_getaddrinfo_w = resolve<GetAddrInfoWFn>("GetAddrInfoW");
122 const auto sh_getnameinfo = resolve<GetNameInfoAFn>("getnameinfo");
123 const auto sh_gethostbyname = resolve<GetHostByNameFn>("gethostbyname");
124 const auto sh_gethostbyname_ord = resolve<GetHostByNameFn>("#52");
125 const auto sh_gethostbyaddr = resolve<GetHostByAddrFn>("gethostbyaddr");
126 const auto sh_gethostbyaddr_ord = resolve<GetHostByAddrFn>("#51");
127
128 check(sh_bind && sh_bind == sh_bind_ord, "bind and #2 resolve to the same shim");
129 check(sh_connect && sh_connect == sh_connect_ord, "connect and #4 resolve to the same shim");
130 check(sh_sendto && sh_sendto == sh_sendto_ord, "sendto and #20 resolve to the same shim");
131 check(sh_gethostbyname && sh_gethostbyname == sh_gethostbyname_ord, "gethostbyname and #52 resolve to the same shim");
132 check(sh_gethostbyaddr && sh_gethostbyaddr == sh_gethostbyaddr_ord, "gethostbyaddr and #51 resolve to the same shim");
133 check(sh_wsa_connect && sh_connect_name_a && sh_connect_name_w && sh_connect_list && sh_wsa_sendto &&
134 sh_wsa_sendmsg && sh_wsa_ioctl && sh_getaddrinfo && sh_getaddrinfo_w && sh_getnameinfo &&
135 rt::shims::find("ws2_32.dll", "#102") && rt::shims::find("ws2_32.dll", "#103"),
136 "all offline Winsock2 shims resolve through the registry");
137 check(!rt::shims::owns_dll("ws2_32.dll"),
138 "ws2_32.dll stays partially overridden (host socket bookkeeping remains available)");
139 check(!rt::shims::owns_dll("wsock32.dll"),
140 "wsock32.dll stays partially overridden (host socket bookkeeping remains available)");
141
142 // wsock32.dll resolves its shared entries to the same wrappers as ws2_32.dll, by name and by ordinal.
143 check(rt::shims::find("wsock32.dll", "connect") == sh_connect && rt::shims::find("wsock32.dll", "#4") == sh_connect,
144 "wsock32.dll connect and #4 resolve to the ws2_32.dll connect shim");
145 check(rt::shims::find("wsock32.dll", "bind") == sh_bind && rt::shims::find("wsock32.dll", "#2") == sh_bind,
146 "wsock32.dll bind and #2 resolve to the ws2_32.dll bind shim");
147 check(rt::shims::find("wsock32.dll", "gethostbyname") == sh_gethostbyname &&
148 rt::shims::find("wsock32.dll", "#52") == sh_gethostbyname,
149 "wsock32.dll gethostbyname and #52 resolve to the ws2_32.dll shim");
150
151 // 1. External connect / WSAConnect / WSAConnectByName / WSAConnectByList refused with WSAENETUNREACH.
152 {
153 const SOCKET tcp = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
154 check(tcp != INVALID_SOCKET, "create IPv4 TCP socket");
155 const sockaddr_in ext4 = make_v4(192, 0, 2, 1, 443);
156 const sockaddr_in6 ext6 = make_v6_doc(443);
157
158 WSASetLastError(0);
159 check(sh_connect(tcp, reinterpret_cast<const sockaddr*>(&ext4), sizeof(ext4)) == SOCKET_ERROR &&
160 WSAGetLastError() == WSAENETUNREACH,
161 "connect refuses external IPv4 with WSAENETUNREACH");
162
163 WSASetLastError(0);
164 check(sh_connect(tcp, reinterpret_cast<const sockaddr*>(&ext6), sizeof(ext6)) == SOCKET_ERROR &&
165 WSAGetLastError() == WSAENETUNREACH,
166 "connect refuses external IPv6 with WSAENETUNREACH");
167
168 WSASetLastError(0);
169 check(sh_wsa_connect(tcp, reinterpret_cast<const sockaddr*>(&ext4), sizeof(ext4), nullptr, nullptr, nullptr,
170 nullptr) == SOCKET_ERROR &&
171 WSAGetLastError() == WSAENETUNREACH,
172 "WSAConnect refuses external IPv4 with WSAENETUNREACH");
173
174 WSASetLastError(0);
175 check(sh_connect_name_a(tcp, "example.invalid", "443", nullptr, nullptr, nullptr, nullptr, nullptr, nullptr) ==
176 FALSE &&
177 WSAGetLastError() == WSAENETUNREACH,
178 "WSAConnectByNameA refuses external hostname with WSAENETUNREACH");
179
180 wchar_t bad_host[] = L"example.invalid";
181 wchar_t port_w[] = L"443";
182 WSASetLastError(0);
183 check(sh_connect_name_w(tcp, bad_host, port_w, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr) == FALSE &&
184 WSAGetLastError() == WSAENETUNREACH,
185 "WSAConnectByNameW refuses external hostname with WSAENETUNREACH");
186
187 SOCKET_ADDRESS_LIST list{};
188 sockaddr_in ext4_mut = ext4;
189 list.iAddressCount = 1;
190 list.Address[0].lpSockaddr = reinterpret_cast<LPSOCKADDR>(&ext4_mut);
191 list.Address[0].iSockaddrLength = sizeof(ext4_mut);
192 WSASetLastError(0);
193 check(sh_connect_list(tcp, &list, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr) == FALSE &&
194 WSAGetLastError() == WSAENETUNREACH,
195 "WSAConnectByList refuses non-loopback address list with WSAENETUNREACH");
196
197 // ConnectEx via WSAIoctl is wrapped and refuses external targets.
198 GUID connect_ex_guid = WSAID_CONNECTEX;
199 LPFN_CONNECTEX connect_ex = nullptr;
200 DWORD returned = 0;
201 const int ioctl_rc = sh_wsa_ioctl(tcp, SIO_GET_EXTENSION_FUNCTION_POINTER, &connect_ex_guid,
202 sizeof(connect_ex_guid), &connect_ex, sizeof(connect_ex), &returned, nullptr,
203 nullptr);
204 check(ioctl_rc == 0 && connect_ex != nullptr && returned == sizeof(connect_ex),
205 "WSAIoctl returns wrapped ConnectEx");
206 if (connect_ex) {
207 OVERLAPPED ov{};
208 WSASetLastError(0);
209 check(connect_ex(tcp, reinterpret_cast<const sockaddr*>(&ext4), sizeof(ext4), nullptr, 0, nullptr, &ov) ==
210 FALSE &&
211 WSAGetLastError() == WSAENETUNREACH,
212 "wrapped ConnectEx refuses external IPv4 with WSAENETUNREACH");
213 }
214
215 // SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER is refused.
216 DWORD dummy_ret = 0;
217 WSASetLastError(0);
218 check(sh_wsa_ioctl(tcp, SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER, nullptr, 0, nullptr, 0, &dummy_ret,
219 nullptr, nullptr) == SOCKET_ERROR &&
220 WSAGetLastError() == WSAEINVAL,
221 "WSAIoctl refuses SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER");
222
223 closesocket(tcp);
224 }
225
226 // 2. External datagram sends (sendto, WSASendTo, WSASendMsg direct & via WSAIoctl) refused with WSAENETUNREACH.
227 {
228 const SOCKET udp = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
229 check(udp != INVALID_SOCKET, "create IPv4 UDP socket");
230 const sockaddr_in ext4 = make_v4(192, 0, 2, 2, 53);
231 char payload[] = "ping";
232
233 WSASetLastError(0);
234 check(sh_sendto(udp, payload, 4, 0, reinterpret_cast<const sockaddr*>(&ext4), sizeof(ext4)) == SOCKET_ERROR &&
235 WSAGetLastError() == WSAENETUNREACH,
236 "sendto refuses external IPv4 with WSAENETUNREACH");
237
238 WSABUF wbuf{4, payload};
239 DWORD sent = 0;
240 WSASetLastError(0);
241 check(sh_wsa_sendto(udp, &wbuf, 1, &sent, 0, reinterpret_cast<const sockaddr*>(&ext4), sizeof(ext4), nullptr,
242 nullptr) == SOCKET_ERROR &&
243 WSAGetLastError() == WSAENETUNREACH,
244 "WSASendTo refuses external IPv4 with WSAENETUNREACH");
245
246 sockaddr_in ext4_mut = ext4;
247 WSAMSG msg{};
248 msg.name = reinterpret_cast<LPSOCKADDR>(&ext4_mut);
249 msg.namelen = sizeof(ext4_mut);
250 msg.lpBuffers = &wbuf;
251 msg.dwBufferCount = 1;
252 WSASetLastError(0);
253 check(sh_wsa_sendmsg(udp, &msg, 0, &sent, nullptr, nullptr) == SOCKET_ERROR &&
254 WSAGetLastError() == WSAENETUNREACH,
255 "WSASendMsg refuses external IPv4 with WSAENETUNREACH");
256
257 GUID sendmsg_guid = WSAID_WSASENDMSG;
258 LPFN_WSASENDMSG sendmsg_ext = nullptr;
259 DWORD returned = 0;
260 const int ioctl_rc = sh_wsa_ioctl(udp, SIO_GET_EXTENSION_FUNCTION_POINTER, &sendmsg_guid, sizeof(sendmsg_guid),
261 &sendmsg_ext, sizeof(sendmsg_ext), &returned, nullptr, nullptr);
262 check(ioctl_rc == 0 && sendmsg_ext != nullptr, "WSAIoctl returns wrapped WSASendMsg");
263 if (sendmsg_ext) {
264 WSASetLastError(0);
265 check(sendmsg_ext(udp, &msg, 0, &sent, nullptr, nullptr) == SOCKET_ERROR &&
266 WSAGetLastError() == WSAENETUNREACH,
267 "wrapped WSASendMsg extension refuses external IPv4 with WSAENETUNREACH");
268 }
269
270 closesocket(udp);
271 }
272
273 // 3. bind narrows wildcard 0.0.0.0 to 127.0.0.1 and refuses non-loopback addresses.
274 {
275 const SOCKET s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
276 const sockaddr_in ext4 = make_v4(192, 0, 2, 1, 0);
277 WSASetLastError(0);
278 check(sh_bind(s, reinterpret_cast<const sockaddr*>(&ext4), sizeof(ext4)) == SOCKET_ERROR &&
279 WSAGetLastError() == WSAEADDRNOTAVAIL,
280 "bind refuses non-loopback IPv4 with WSAEADDRNOTAVAIL");
281
282 const sockaddr_in any4 = make_v4(0, 0, 0, 0, 0);
283 check(sh_bind(s, reinterpret_cast<const sockaddr*>(&any4), sizeof(any4)) == 0,
284 "bind accepts wildcard 0.0.0.0 and rewrites to loopback");
285 sockaddr_in bound{};
286 int bound_len = sizeof(bound);
287 check(getsockname(s, reinterpret_cast<sockaddr*>(&bound), &bound_len) == 0 &&
288 bound.sin_addr.s_addr == htonl(INADDR_LOOPBACK),
289 "wildcard bind narrowed socket address to 127.0.0.1");
290 closesocket(s);
291 }
292
293 // 4. DNS lookups refuse external hostnames and permit localhost / 127.0.0.1.
294 {
295 ADDRINFOA* res = nullptr;
296 check(sh_getaddrinfo("example.invalid", "443", nullptr, &res) == WSAHOST_NOT_FOUND && res == nullptr,
297 "getaddrinfo refuses external hostname with WSAHOST_NOT_FOUND");
298 // Windows reads a leading-zero octet as octal, so 0127.0.0.1 is 87.0.0.1 there; it is refused, not loopback.
299 res = nullptr;
300 check(sh_getaddrinfo("0127.0.0.1", "80", nullptr, &res) == WSAHOST_NOT_FOUND && res == nullptr,
301 "getaddrinfo refuses octal-looking 0127.0.0.1 with WSAHOST_NOT_FOUND");
302 check(sh_getaddrinfo("127.0.0.1", "80", nullptr, &res) == 0 && res != nullptr,
303 "getaddrinfo permits 127.0.0.1");
304 if (res) freeaddrinfo(res);
305 res = nullptr;
306 check(sh_getaddrinfo("localhost", "80", nullptr, &res) == 0 && res != nullptr,
307 "getaddrinfo permits localhost");
308 if (res) freeaddrinfo(res);
309
310 ADDRINFOW* res_w = nullptr;
311 check(sh_getaddrinfo_w(L"example.invalid", L"443", nullptr, &res_w) == WSAHOST_NOT_FOUND && res_w == nullptr,
312 "GetAddrInfoW refuses external hostname with WSAHOST_NOT_FOUND");
313 check(sh_getaddrinfo_w(L"localhost", L"80", nullptr, &res_w) == 0 && res_w != nullptr,
314 "GetAddrInfoW permits localhost");
315 if (res_w) FreeAddrInfoW(res_w);
316
317 WSASetLastError(0);
318 check(sh_gethostbyname("example.invalid") == nullptr && WSAGetLastError() == WSAHOST_NOT_FOUND,
319 "gethostbyname refuses external hostname with WSAHOST_NOT_FOUND");
320
321 const uint8_t ext_bytes[4] = {192, 0, 2, 1};
322 WSASetLastError(0);
323 check(sh_gethostbyaddr(reinterpret_cast<const char*>(ext_bytes), 4, AF_INET) == nullptr &&
324 WSAGetLastError() == WSAHOST_NOT_FOUND,
325 "gethostbyaddr refuses external IPv4 with WSAHOST_NOT_FOUND");
326
327 const sockaddr_in ext4 = make_v4(192, 0, 2, 1, 80);
328 char host_buf[64] = {};
329 check(sh_getnameinfo(reinterpret_cast<const sockaddr*>(&ext4), sizeof(ext4), host_buf, sizeof(host_buf),
330 nullptr, 0, NI_NAMEREQD) == WSAHOST_NOT_FOUND,
331 "getnameinfo with NI_NAMEREQD refuses external IPv4");
332 check(sh_getnameinfo(reinterpret_cast<const sockaddr*>(&ext4), sizeof(ext4), host_buf, sizeof(host_buf),
333 nullptr, 0, 0) == 0 &&
334 std::strcmp(host_buf, "192.0.2.1") == 0,
335 "getnameinfo without NI_NAMEREQD returns numeric IP without reverse DNS");
336 }
337
338 // 5. Real loopback UDP round-trip through the shimmed bind and sendto succeeds.
339 {
340 const SOCKET recv_sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
341 const SOCKET send_sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
342 const sockaddr_in loop = make_v4(127, 0, 0, 1, 0);
343 check(sh_bind(recv_sock, reinterpret_cast<const sockaddr*>(&loop), sizeof(loop)) == 0,
344 "loopback UDP receiver bind succeeds");
345 sockaddr_in dst{};
346 int dst_len = sizeof(dst);
347 check(getsockname(recv_sock, reinterpret_cast<sockaddr*>(&dst), &dst_len) == 0,
348 "getsockname returns loopback UDP port");
349 const char msg[] = "ok";
350 check(sh_sendto(send_sock, msg, 2, 0, reinterpret_cast<const sockaddr*>(&dst), sizeof(dst)) == 2,
351 "loopback sendto succeeds");
352 char got[8] = {};
353 const int n = recv(recv_sock, got, sizeof(got), 0);
354 check(n == 2 && got[0] == 'o' && got[1] == 'k', "loopback UDP payload received");
355 closesocket(send_sock);
356 closesocket(recv_sock);
357 }
358
359 // 6. Name-service queries are refused with WSASERVICE_NOT_FOUND.
360 {
361 const auto sh_lookup_w = resolve<LookupBeginWFn>("WSALookupServiceBeginW");
362 wchar_t service[] = L"example.invalid";
363 WSAQUERYSETW restrictions{};
364 restrictions.dwSize = sizeof(restrictions);
365 restrictions.lpszServiceInstanceName = service;
366 HANDLE lookup = nullptr;
367 WSASetLastError(0);
368 check(sh_lookup_w && sh_lookup_w(&restrictions, 0, &lookup) == SOCKET_ERROR &&
369 WSAGetLastError() == WSASERVICE_NOT_FOUND && lookup == nullptr,
370 "WSALookupServiceBeginW refuses with WSASERVICE_NOT_FOUND");
371 }
372
373 // 7. ConnectEx from WSAIoctl connects to a loopback listener through the host's per-socket pointer.
374 {
375 const SOCKET listener = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
376 sockaddr_in any = make_v4(127, 0, 0, 1, 0);
377 sockaddr_in listen_addr{};
378 int listen_len = sizeof(listen_addr);
379 check(sh_bind(listener, reinterpret_cast<const sockaddr*>(&any), sizeof(any)) == 0 &&
380 listen(listener, 1) == 0 && getsockname(listener, reinterpret_cast<sockaddr*>(&listen_addr),
381 &listen_len) == 0,
382 "loopback TCP listener is up");
383
384 const SOCKET client = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
385 check(sh_bind(client, reinterpret_cast<const sockaddr*>(&any), sizeof(any)) == 0,
386 "ConnectEx client socket is bound to loopback (ConnectEx requires a bound socket)");
387 GUID connect_ex_guid = WSAID_CONNECTEX;
388 LPFN_CONNECTEX connect_ex = nullptr;
389 DWORD returned = 0;
390 check(sh_wsa_ioctl(client, SIO_GET_EXTENSION_FUNCTION_POINTER, &connect_ex_guid, sizeof(connect_ex_guid),
391 &connect_ex, sizeof(connect_ex), &returned, nullptr, nullptr) == 0 &&
392 connect_ex != nullptr,
393 "WSAIoctl returns a ConnectEx pointer for a bound TCP socket");
394
395 if (connect_ex) {
396 OVERLAPPED ov{};
397 ov.hEvent = WSACreateEvent();
398 check(connect_ex(client, reinterpret_cast<const sockaddr*>(&listen_addr), sizeof(listen_addr), nullptr, 0,
399 nullptr, &ov) == TRUE ||
400 (WSAGetLastError() == WSA_IO_PENDING &&
401 WSAWaitForMultipleEvents(1, &ov.hEvent, TRUE, 5000, FALSE) == WSA_WAIT_EVENT_0),
402 "wrapped ConnectEx connects to the loopback listener");
403 DWORD transferred = 0, flags = 0;
404 check(WSAGetOverlappedResult(client, &ov, &transferred, FALSE, &flags) == TRUE,
405 "ConnectEx completes with no error");
406 WSACloseEvent(ov.hEvent);
407 }
408
409 const SOCKET ext = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
410 sockaddr_in ext_any = make_v4(127, 0, 0, 1, 0);
411 check(sh_bind(ext, reinterpret_cast<const sockaddr*>(&ext_any), sizeof(ext_any)) == 0,
412 "second ConnectEx socket is bound to loopback");
413 if (connect_ex) {
414 const sockaddr_in ext4 = make_v4(192, 0, 2, 1, 443);
415 OVERLAPPED ov{};
416 WSASetLastError(0);
417 check(connect_ex(ext, reinterpret_cast<const sockaddr*>(&ext4), sizeof(ext4), nullptr, 0, nullptr, &ov) ==
418 FALSE &&
419 WSAGetLastError() == WSAENETUNREACH,
420 "wrapped ConnectEx refuses non-loopback 192.0.2.1 with WSAENETUNREACH");
421 }
422 closesocket(ext);
423 closesocket(client);
424 closesocket(listener);
425 }
426
427 // Implicit binds, multicast joins and WSAJoinLeaf. A send on an unbound datagram socket binds it to the wildcard
428 // address (Microsoft's sendto remarks); the shim binds it to loopback first. Joins are refused before the host.
429 {
430 using SetSockOptFn = int(WSAAPI*)(SOCKET, int, int, const char*, int);
431 using JoinLeafFn = SOCKET(WSAAPI*)(SOCKET, const sockaddr*, int, LPWSABUF, LPWSABUF, LPQOS, LPQOS, DWORD);
432 const auto sh_setsockopt = resolve<SetSockOptFn>("setsockopt");
433 const auto sh_join_leaf = resolve<JoinLeafFn>("WSAJoinLeaf");
434 const auto ws1_setsockopt = reinterpret_cast<SetSockOptFn>(rt::shims::find("wsock32.dll", "setsockopt"));
435 check(sh_setsockopt && sh_setsockopt == resolve<SetSockOptFn>("#21"),
436 "setsockopt and #21 resolve to the same shim");
437 check(sh_join_leaf != nullptr, "WSAJoinLeaf resolves to a shim");
438 check(ws1_setsockopt && ws1_setsockopt == reinterpret_cast<SetSockOptFn>(rt::shims::find("wsock32.dll", "#21")) &&
439 ws1_setsockopt != sh_setsockopt,
440 "wsock32.dll setsockopt and #21 resolve to their own Winsock 1.1 shim");
441
442 const SOCKET receiver = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
443 sockaddr_in to = make_v4(127, 0, 0, 1, 0);
444 int to_len = sizeof(to);
445 check(bind(receiver, reinterpret_cast<const sockaddr*>(&to), sizeof(to)) == 0 &&
446 getsockname(receiver, reinterpret_cast<sockaddr*>(&to), &to_len) == 0,
447 "bind a loopback UDP receiver");
448 const auto local_v4_first_byte = [](SOCKET s) {
449 sockaddr_in local{};
450 int len = sizeof(local);
451 if (getsockname(s, reinterpret_cast<sockaddr*>(&local), &len) != 0 || local.sin_port == 0) return -1;
452 return static_cast<int>(reinterpret_cast<const uint8_t*>(&local.sin_addr)[0]);
453 };
454 char payload[] = "ping";
455
456 const SOCKET control = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
457 check(sendto(control, payload, 4, 0, reinterpret_cast<const sockaddr*>(&to), sizeof(to)) == 4 &&
458 local_v4_first_byte(control) == 0,
459 "control: the host sendto binds an unbound UDP socket to 0.0.0.0");
460 const SOCKET unbound = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
461 check(sh_sendto(unbound, payload, 4, 0, reinterpret_cast<const sockaddr*>(&to), sizeof(to)) == 4 &&
462 local_v4_first_byte(unbound) == 127,
463 "sendto binds an unbound UDP socket to 127.0.0.1 before sending");
464 const SOCKET unbound_wsa = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
465 WSABUF wbuf{4, payload};
466 DWORD sent = 0;
467 check(sh_wsa_sendto(unbound_wsa, &wbuf, 1, &sent, 0, reinterpret_cast<const sockaddr*>(&to), sizeof(to), nullptr,
468 nullptr) == 0 &&
469 sent == 4 && local_v4_first_byte(unbound_wsa) == 127,
470 "WSASendTo binds an unbound UDP socket to 127.0.0.1 before sending");
471 check(sh_sendto(unbound, payload, 4, 0, reinterpret_cast<const sockaddr*>(&to), sizeof(to)) == 4 &&
472 local_v4_first_byte(unbound) == 127,
473 "a second sendto on the now-bound socket keeps its loopback binding");
474
475 const SOCKET receiver6 = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP);
476 if (receiver6 != INVALID_SOCKET) {
477 sockaddr_in6 to6{};
478 to6.sin6_family = AF_INET6;
479 reinterpret_cast<uint8_t*>(&to6.sin6_addr)[15] = 1; // ::1
480 int to6_len = sizeof(to6);
481 const bool bound6 = bind(receiver6, reinterpret_cast<const sockaddr*>(&to6), sizeof(to6)) == 0 &&
482 getsockname(receiver6, reinterpret_cast<sockaddr*>(&to6), &to6_len) == 0;
483 const SOCKET unbound6 = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP);
484 sockaddr_in6 local6{};
485 int local6_len = sizeof(local6);
486 check(bound6 && sh_sendto(unbound6, payload, 4, 0, reinterpret_cast<const sockaddr*>(&to6), sizeof(to6)) == 4 &&
487 getsockname(unbound6, reinterpret_cast<sockaddr*>(&local6), &local6_len) == 0 &&
488 reinterpret_cast<const uint8_t*>(&local6.sin6_addr)[15] == 1 &&
489 reinterpret_cast<const uint8_t*>(&local6.sin6_addr)[0] == 0,
490 "sendto binds an unbound IPv6 UDP socket to ::1 before sending");
491 closesocket(unbound6);
492 closesocket(receiver6);
493 }
494
495 // 239.255.0.1 (administratively scoped group); every join is refused before it reaches the host.
496 ip_mreq mreq{};
497 auto* group = reinterpret_cast<uint8_t*>(&mreq.imr_multiaddr);
498 group[0] = 239;
499 group[1] = 255;
500 group[3] = 1;
501 const auto refused = [](int rc) { return rc == SOCKET_ERROR && WSAGetLastError() == WSAEADDRNOTAVAIL; };
502 const char* mreq_bytes = reinterpret_cast<const char*>(&mreq);
503 WSASetLastError(0);
504 check(refused(sh_setsockopt(unbound, IPPROTO_IP, IP_ADD_MEMBERSHIP, mreq_bytes, sizeof(mreq))),
505 "setsockopt refuses IP_ADD_MEMBERSHIP with WSAEADDRNOTAVAIL");
506 WSASetLastError(0);
507 check(refused(sh_setsockopt(unbound, IPPROTO_IP, IP_ADD_SOURCE_MEMBERSHIP, mreq_bytes, sizeof(mreq))),
508 "setsockopt refuses IP_ADD_SOURCE_MEMBERSHIP");
509 WSASetLastError(0);
510 check(refused(sh_setsockopt(unbound, IPPROTO_IP, MCAST_JOIN_GROUP, mreq_bytes, sizeof(mreq))),
511 "setsockopt refuses MCAST_JOIN_GROUP");
512 WSASetLastError(0);
513 check(refused(sh_setsockopt(unbound, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, mreq_bytes, sizeof(mreq))),
514 "setsockopt refuses IPV6_ADD_MEMBERSHIP");
515 WSASetLastError(0);
516 check(refused(ws1_setsockopt(unbound, IPPROTO_IP, 5, mreq_bytes, sizeof(mreq))),
517 "wsock32 setsockopt refuses the Winsock 1.1 IP_ADD_MEMBERSHIP (5)");
518 WSASetLastError(0);
519 check(refused(ws1_setsockopt(unbound, IPPROTO_IP, IP_ADD_MEMBERSHIP, mreq_bytes, sizeof(mreq))),
520 "wsock32 setsockopt refuses the Winsock 2 IP_ADD_MEMBERSHIP (12) it would pass through");
521 int value = 3;
522 const char* value_bytes = reinterpret_cast<const char*>(&value);
523 check(sh_setsockopt(unbound, IPPROTO_IP, IP_MULTICAST_TTL, value_bytes, sizeof(value)) == 0,
524 "setsockopt passes other IPPROTO_IP options (IP_MULTICAST_TTL)");
525 check(ws1_setsockopt(unbound, IPPROTO_IP, 7, value_bytes, sizeof(value)) == 0,
526 "wsock32 setsockopt passes the Winsock 1.1 IP_TTL (7) to the host's remap");
527 value = 65536;
528 check(sh_setsockopt(unbound, SOL_SOCKET, SO_RCVBUF, value_bytes, sizeof(value)) == 0,
529 "setsockopt passes SOL_SOCKET options");
530
531 const sockaddr_in group_addr = make_v4(239, 255, 0, 1, 5000);
532 WSASetLastError(0);
533 check(sh_join_leaf(unbound, reinterpret_cast<const sockaddr*>(&group_addr), sizeof(group_addr), nullptr, nullptr,
534 nullptr, nullptr, JL_BOTH) == INVALID_SOCKET &&
535 WSAGetLastError() == WSAENETUNREACH,
536 "WSAJoinLeaf refuses a multicast group with WSAENETUNREACH");
537
538 closesocket(unbound_wsa);
539 closesocket(unbound);
540 closesocket(control);
541 closesocket(receiver);
542 }
543
544 WSACleanup();
545 std::printf("%d check(s), %d failure(s)\n", g_checks, g_failures);
546 return g_failures ? 1 : 0;
547}
diff --git a/runtime/test/xdxr_builder_validation_test.cpp b/runtime/test/xdxr_builder_validation_test.cpp
new file mode 100644
index 000000000..5ea6226ff
--- /dev/null
+++ b/runtime/test/xdxr_builder_validation_test.cpp
@@ -0,0 +1,183 @@
1// Unit tests for XdxrBuilder pre-validation in src/xdxr_build.h (no Vulkan instance, no GPU).
2// Mismatched geometry sums, null device addresses, uncomputed layouts, and 32-bit overflow counts must fail before
3// recording any command into the Vulkan command buffer.
4#include "../src/xdxr_build.h"
5
6#include <cstdint>
7#include <cstdio>
8#include <cstring>
9#include <type_traits>
10#include <vector>
11
12#define CHECK(condition) do { \
13 if (!(condition)) { \
14 std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); \
15 return 1; \
16 } \
17} while (0)
18
19namespace {
20
21template<typename Handle>
22Handle fake_handle(std::uintptr_t value) {
23 if constexpr (std::is_pointer_v<Handle>)
24 return reinterpret_cast<Handle>(value);
25 else
26 return static_cast<Handle>(value);
27}
28
29struct MockRecorder {
30 unsigned binds = 0;
31 unsigned pushes = 0;
32 unsigned dispatches = 0;
33 unsigned barriers = 0;
34 std::uint32_t last_group_count_x = 0;
35 std::uint32_t last_copy_count = 0;
36
37 void reset() { *this = MockRecorder{}; }
38 bool empty() const { return !binds && !pushes && !dispatches && !barriers; }
39};
40
41MockRecorder g_rec;
42
43VKAPI_ATTR VkResult VKAPI_CALL mock_create_shader_module(VkDevice, const VkShaderModuleCreateInfo*,
44 const VkAllocationCallbacks*, VkShaderModule* out) {
45 *out = fake_handle<VkShaderModule>(1);
46 return VK_SUCCESS;
47}
48
49VKAPI_ATTR void VKAPI_CALL mock_destroy_shader_module(VkDevice, VkShaderModule, const VkAllocationCallbacks*) {}
50
51VKAPI_ATTR VkResult VKAPI_CALL mock_create_pipeline_layout(VkDevice, const VkPipelineLayoutCreateInfo*,
52 const VkAllocationCallbacks*, VkPipelineLayout* out) {
53 *out = fake_handle<VkPipelineLayout>(2);
54 return VK_SUCCESS;
55}
56
57VKAPI_ATTR void VKAPI_CALL mock_destroy_pipeline_layout(VkDevice, VkPipelineLayout, const VkAllocationCallbacks*) {}
58
59VKAPI_ATTR VkResult VKAPI_CALL mock_create_compute_pipelines(VkDevice, VkPipelineCache, std::uint32_t count,
60 const VkComputePipelineCreateInfo*,
61 const VkAllocationCallbacks*, VkPipeline* out) {
62 for (std::uint32_t i = 0; i < count; ++i) out[i] = fake_handle<VkPipeline>(3 + i);
63 return VK_SUCCESS;
64}
65
66VKAPI_ATTR void VKAPI_CALL mock_destroy_pipeline(VkDevice, VkPipeline, const VkAllocationCallbacks*) {}
67
68VKAPI_ATTR void VKAPI_CALL mock_cmd_bind_pipeline(VkCommandBuffer, VkPipelineBindPoint, VkPipeline) { ++g_rec.binds; }
69
70VKAPI_ATTR void VKAPI_CALL mock_cmd_push_constants(VkCommandBuffer, VkPipelineLayout, VkShaderStageFlags,
71 std::uint32_t, std::uint32_t size, const void* values) {
72 ++g_rec.pushes;
73 if (size >= 80 && values) {
74 std::uint32_t mode = 0, count = 0;
75 std::memcpy(&mode, static_cast<const std::uint8_t*>(values) + 48, 4);
76 std::memcpy(&count, static_cast<const std::uint8_t*>(values) + 52, 4);
77 if (mode == 12) g_rec.last_copy_count = count;
78 }
79}
80
81VKAPI_ATTR void VKAPI_CALL mock_cmd_dispatch(VkCommandBuffer, std::uint32_t x, std::uint32_t, std::uint32_t) {
82 ++g_rec.dispatches;
83 g_rec.last_group_count_x = x;
84}
85
86VKAPI_ATTR void VKAPI_CALL mock_cmd_pipeline_barrier(VkCommandBuffer, VkPipelineStageFlags, VkPipelineStageFlags,
87 VkDependencyFlags, std::uint32_t, const VkMemoryBarrier*,
88 std::uint32_t, const VkBufferMemoryBarrier*, std::uint32_t,
89 const VkImageMemoryBarrier*) {
90 ++g_rec.barriers;
91}
92
93VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL mock_get_device_proc_addr(VkDevice, const char* name) {
94 if (!name) return nullptr;
95 if (std::strcmp(name, "vkCreateShaderModule") == 0) return reinterpret_cast<PFN_vkVoidFunction>(mock_create_shader_module);
96 if (std::strcmp(name, "vkDestroyShaderModule") == 0) return reinterpret_cast<PFN_vkVoidFunction>(mock_destroy_shader_module);
97 if (std::strcmp(name, "vkCreatePipelineLayout") == 0) return reinterpret_cast<PFN_vkVoidFunction>(mock_create_pipeline_layout);
98 if (std::strcmp(name, "vkDestroyPipelineLayout") == 0) return reinterpret_cast<PFN_vkVoidFunction>(mock_destroy_pipeline_layout);
99 if (std::strcmp(name, "vkCreateComputePipelines") == 0) return reinterpret_cast<PFN_vkVoidFunction>(mock_create_compute_pipelines);
100 if (std::strcmp(name, "vkDestroyPipeline") == 0) return reinterpret_cast<PFN_vkVoidFunction>(mock_destroy_pipeline);
101 if (std::strcmp(name, "vkCmdBindPipeline") == 0) return reinterpret_cast<PFN_vkVoidFunction>(mock_cmd_bind_pipeline);
102 if (std::strcmp(name, "vkCmdPushConstants") == 0) return reinterpret_cast<PFN_vkVoidFunction>(mock_cmd_push_constants);
103 if (std::strcmp(name, "vkCmdDispatch") == 0) return reinterpret_cast<PFN_vkVoidFunction>(mock_cmd_dispatch);
104 if (std::strcmp(name, "vkCmdPipelineBarrier") == 0) return reinterpret_cast<PFN_vkVoidFunction>(mock_cmd_pipeline_barrier);
105 return nullptr;
106}
107
108} // namespace
109
110int main() {
111 using namespace leonida;
112
113 const VkDevice dev = fake_handle<VkDevice>(0x1000);
114 const VkCommandBuffer cb = fake_handle<VkCommandBuffer>(0x2000);
115 XdxrBuilder builder(mock_get_device_proc_addr, dev);
116 CHECK(builder.loaded());
117
118 XdxrLayout blas1;
119 CHECK(blas1.compute(1, false));
120 XdxrLayout blas4;
121 CHECK(blas4.compute(4, false));
122 XdxrLayout tlas0;
123 CHECK(tlas0.compute(0, true));
124 XdxrLayout tlas4;
125 CHECK(tlas4.compute(4, true));
126 const XdxrLayout uncomputed{};
127
128 const std::uint64_t dst = 0x100000;
129 const std::uint64_t scratch = 0x200000;
130 const std::uint64_t instances = 0x300000;
131
132 // 1. Fewer triangles than layout.elements must fail cleanly without recording any commands.
133 g_rec.reset();
134 CHECK(!builder.record_blas(cb, blas4, {XdxrTriangles{.triangle_count = 3}}, dst, scratch));
135 CHECK(g_rec.empty());
136
137 // 2. More triangles than layout.elements must fail cleanly without recording any commands.
138 g_rec.reset();
139 CHECK(!builder.record_blas(cb, blas4,
140 {XdxrTriangles{.triangle_count = 2}, XdxrTriangles{.triangle_count = 3}},
141 dst, scratch));
142 CHECK(g_rec.empty());
143
144 // 3. Sums that would wrap uint32_t back to layout.elements must be rejected before any dispatch.
145 g_rec.reset();
146 CHECK(!builder.record_blas(cb, blas1,
147 {XdxrTriangles{.triangle_count = 0x80000001u},
148 XdxrTriangles{.triangle_count = 0x80000000u}},
149 dst, scratch));
150 CHECK(g_rec.empty());
151
152 // 4. Null addresses, uncomputed layouts, and non-empty TLAS with null instances record nothing.
153 g_rec.reset();
154 CHECK(!builder.record_blas(cb, blas1, {XdxrTriangles{.triangle_count = 1}}, 0, scratch));
155 CHECK(!builder.record_blas(cb, blas1, {XdxrTriangles{.triangle_count = 1}}, dst, 0));
156 CHECK(!builder.record_blas(cb, uncomputed, {}, dst, scratch));
157 CHECK(!builder.record_tlas(cb, tlas4, instances, 0, scratch));
158 CHECK(!builder.record_tlas(cb, tlas4, instances, dst, 0));
159 CHECK(!builder.record_tlas(cb, tlas4, 0, dst, scratch));
160 CHECK(!builder.record_tlas(cb, uncomputed, instances, dst, scratch));
161 CHECK(g_rec.empty());
162
163 // 5. Empty TLAS with null instances pointer is valid and records a build.
164 g_rec.reset();
165 CHECK(builder.record_tlas(cb, tlas0, 0, dst, scratch));
166 CHECK(g_rec.binds > 0 && g_rec.dispatches > 0);
167
168 // 6. Valid multi-geometry BLAS records dispatches.
169 g_rec.reset();
170 CHECK(builder.record_blas(cb, blas4,
171 {XdxrTriangles{.triangle_count = 1}, XdxrTriangles{.triangle_count = 3}},
172 dst, scratch));
173 CHECK(g_rec.binds > 0 && g_rec.dispatches > 0 && g_rec.pushes == g_rec.dispatches);
174
175 // 7. Large record_copy dispatches compute group counts without 32-bit overflow.
176 g_rec.reset();
177 CHECK(builder.record_copy(cb, dst, dst + 0x10000, 0xffffffffull));
178 CHECK(g_rec.dispatches == 1 && g_rec.last_copy_count == 0x3fffffffu &&
179 g_rec.last_group_count_x == (0x3fffffffu + 63u) / 64u);
180
181 std::puts("xdxr_builder_validation: all checks passed");
182 return 0;
183}
diff --git a/runtime/test/xdxr_descs_test.cpp b/runtime/test/xdxr_descs_test.cpp
index 209fd4fcc..8b857b8d7 100644
--- a/runtime/test/xdxr_descs_test.cpp
+++ b/runtime/test/xdxr_descs_test.cpp
@@ -69,6 +69,19 @@ int stream_lookup() {
69 records[1].type = 0; 69 records[1].type = 0;
70 CHECK(find_stream_record(stream_of(records, 1), 0) == nullptr); 70 CHECK(find_stream_record(stream_of(records, 1), 0) == nullptr);
71 CHECK(find_stream_record(stream_of(records, 2), 0) == &records[1]); 71 CHECK(find_stream_record(stream_of(records, 2), 0) == &records[1]);
72
73 // Trailing bytes shorter than one complete StreamRecord are never read.
74 records[0].type = 0;
75 const size_t small_sizes[] = {1, 4, sizeof(StreamRecord) - 1};
76 for (size_t bytes : small_sizes)
77 CHECK(find_stream_record(StreamDesc{bytes, records}, 0) == nullptr);
78 records[0].type = 1;
79 records[1].type = 0;
80 const size_t partial_second_sizes[] = {sizeof(StreamRecord) + 1, 2 * sizeof(StreamRecord) - 1};
81 for (size_t bytes : partial_second_sizes) {
82 CHECK(find_stream_record(StreamDesc{bytes, records}, 1) == &records[0]);
83 CHECK(find_stream_record(StreamDesc{bytes, records}, 0) == nullptr);
84 }
72 return 0; 85 return 0;
73} 86}
74 87
diff --git a/runtime/test/xgameruntime_offline_test.cpp b/runtime/test/xgameruntime_offline_test.cpp
index 7668b6164..66b110054 100644
--- a/runtime/test/xgameruntime_offline_test.cpp
+++ b/runtime/test/xgameruntime_offline_test.cpp
@@ -8,6 +8,7 @@
8#include <cstdio> 8#include <cstdio>
9#include <cstdlib> 9#include <cstdlib>
10#include <cstring> 10#include <cstring>
11#include <string>
11 12
12#include <XAsync.h> 13#include <XAsync.h>
13#include <XAsyncProvider.h> 14#include <XAsyncProvider.h>
@@ -74,7 +75,16 @@ constexpr GUID kAccessibilityClass = {0x3e241977, 0x6237, 0x41e9, {0x85, 0x59, 0
74constexpr GUID kAccessibility2 = {0xd722b373, 0x8c4d, 0x4692, {0x9e, 0x51, 0xd6, 0xad, 0x9b, 0x37, 0xaa, 0x7d}}; 75constexpr GUID kAccessibility2 = {0xd722b373, 0x8c4d, 0x4692, {0x9e, 0x51, 0xd6, 0xad, 0x9b, 0x37, 0xaa, 0x7d}};
75constexpr GUID kLauncherClass = {0x1b339674, 0x328d, 0x4283, {0xa2, 0x00, 0x31, 0x71, 0xf1, 0x8d, 0x36, 0x39}}; 76constexpr GUID kLauncherClass = {0x1b339674, 0x328d, 0x4283, {0xa2, 0x00, 0x31, 0x71, 0xf1, 0x8d, 0x36, 0x39}};
76 77
77using EnumVoices = HRESULT(STDMETHODCALLTYPE*)(void*, void*, void*); 78struct VoiceInformation { // XSpeechSynthesizerVoiceInformation, the GDK reference's member order
79 const char* description;
80 const char* display_name;
81 uint32_t gender;
82 const char* voice_id;
83 const char* language;
84};
85using VoiceCallback = bool(CALLBACK*)(const VoiceInformation*, void*);
86using EnumVoices = HRESULT(STDMETHODCALLTYPE*)(void*, void* context, VoiceCallback callback);
87using SetCustomVoice = HRESULT(STDMETHODCALLTYPE*)(void*, void*, const char*);
78using SpeechCreate = HRESULT(STDMETHODCALLTYPE*)(void*, void**); 88using SpeechCreate = HRESULT(STDMETHODCALLTYPE*)(void*, void**);
79using SpeechClose = HRESULT(STDMETHODCALLTYPE*)(void*, void*); 89using SpeechClose = HRESULT(STDMETHODCALLTYPE*)(void*, void*);
80using SpeechStream = HRESULT(STDMETHODCALLTYPE*)(void*, void*, const char*, void**); 90using SpeechStream = HRESULT(STDMETHODCALLTYPE*)(void*, void*, const char*, void**);
@@ -93,6 +103,19 @@ void* user_object(HRESULT(WINAPI* query)(const GUID*, REFIID, void**)) {
93 103
94void CALLBACK on_state(void*, uint64_t, uint32_t) {} 104void CALLBACK on_state(void*, uint64_t, uint32_t) {}
95 105
106struct VoicesSeen {
107 int count = 0;
108 std::string voice_id;
109 std::string language;
110};
111bool CALLBACK on_voice(const VoiceInformation* info, void* context) {
112 auto* seen = static_cast<VoicesSeen*>(context);
113 ++seen->count;
114 seen->voice_id = info && info->voice_id ? info->voice_id : "";
115 seen->language = info && info->language ? info->language : "";
116 return true;
117}
118
96// XUserDeviceImpl slots 4/5 (device association) and 7/8 (default audio endpoint): kept until unregistered, never 119// XUserDeviceImpl slots 4/5 (device association) and 7/8 (default audio endpoint): kept until unregistered, never
97// called back offline. 120// called back offline.
98long g_device_callbacks = 0; 121long g_device_callbacks = 0;
@@ -290,22 +313,45 @@ int main() {
290 "XHighContrastGetMode reports Off"); 313 "XHighContrastGetMode reports Off");
291 check(at<SetEnabled>(acc, 4)(acc, true) == S_OK, "XClosedCaptionSetEnabled is accepted"); 314 check(at<SetEnabled>(acc, 4)(acc, true) == S_OK, "XClosedCaptionSetEnabled is accepted");
292 check(FAILED(at<NoArgs>(acc, 3)(acc)), "the closed-caption properties are not available offline"); 315 check(FAILED(at<NoArgs>(acc, 3)(acc)), "the closed-caption properties are not available offline");
293 check(at<EnumVoices>(acc, 8)(acc, reinterpret_cast<void*>(&on_state), nullptr) == S_OK && 316 VoicesSeen seen;
294 at<EnumVoices>(acc, 8)(acc, nullptr, nullptr) == E_INVALIDARG, 317 check(at<EnumVoices>(acc, 8)(acc, &seen, &on_voice) == S_OK && seen.count == 1 &&
295 "XSpeechSynthesizerEnumerateInstalledVoices: no voices, S_OK (a callback is required)"); 318 seen.voice_id == "leonida-silent" && seen.language == "en-US",
296 void* synth = reinterpret_cast<void*>(1); 319 "XSpeechSynthesizerEnumerateInstalledVoices(context, callback): one silent voice, its context passed back");
297 check(at<SpeechCreate>(acc, 9)(acc, &synth) == E_FAIL && synth == nullptr, 320 check(at<EnumVoices>(acc, 8)(acc, nullptr, nullptr) == E_INVALIDARG,
298 "XSpeechSynthesizerCreate fails offline and nulls the handle"); 321 "XSpeechSynthesizerEnumerateInstalledVoices: a callback is required");
299 void* stream = reinterpret_cast<void*>(1); 322 void* synth = nullptr;
300 size_t size = 5, got = 5; 323 check(at<SpeechCreate>(acc, 9)(acc, &synth) == S_OK && synth != nullptr &&
324 at<SpeechCreate>(acc, 9)(acc, nullptr) == E_POINTER,
325 "XSpeechSynthesizerCreate returns a silent synthesizer handle");
326 void* stream = nullptr;
327 size_t size = 0, got = 0;
301 check(at<SpeechClose>(acc, 10)(acc, nullptr) == E_INVALIDARG && at<SpeechClose>(acc, 11)(acc, nullptr) == E_INVALIDARG && 328 check(at<SpeechClose>(acc, 10)(acc, nullptr) == E_INVALIDARG && at<SpeechClose>(acc, 11)(acc, nullptr) == E_INVALIDARG &&
302 at<SpeechClose>(acc, 12)(acc, nullptr) == E_INVALIDARG && at<SpeechClose>(acc, 14)(acc, nullptr) == E_INVALIDARG, 329 at<SpeechClose>(acc, 12)(acc, nullptr) == E_INVALIDARG && at<SpeechClose>(acc, 14)(acc, nullptr) == E_INVALIDARG,
303 "close and set-voice calls on a null handle: E_INVALIDARG"); 330 "close and set-voice calls on a null handle: E_INVALIDARG");
331 check(at<SpeechClose>(acc, 11)(acc, synth) == S_OK, "XSpeechSynthesizerSetDefaultVoice succeeds on valid handle");
332 check(at<SetCustomVoice>(acc, 12)(acc, synth, seen.voice_id.c_str()) == S_OK &&
333 at<SetCustomVoice>(acc, 12)(acc, synth, "not-installed") == E_INVALIDARG &&
334 at<SetCustomVoice>(acc, 12)(acc, synth, nullptr) == E_INVALIDARG,
335 "XSpeechSynthesizerSetCustomVoice accepts the enumerated voice only");
304 check(at<SpeechStream>(acc, 13)(acc, nullptr, "hi", &stream) == E_INVALIDARG && stream == nullptr, 336 check(at<SpeechStream>(acc, 13)(acc, nullptr, "hi", &stream) == E_INVALIDARG && stream == nullptr,
305 "CreateStreamFromText on a null synthesizer: E_INVALIDARG, no stream"); 337 "CreateStreamFromText on a null synthesizer: E_INVALIDARG, no stream");
306 stream = reinterpret_cast<void*>(1); 338 check(at<SpeechStream>(acc, 13)(acc, synth, "Hello", &stream) == S_OK && stream != nullptr,
307 check(at<SpeechStream>(acc, 21)(acc, nullptr, "<speak/>", &stream) == E_INVALIDARG && stream == nullptr, 339 "CreateStreamFromText returns a silent WAVE stream");
308 "CreateStreamFromSsml on a null synthesizer: E_INVALIDARG, no stream"); 340 check(at<StreamSize>(acc, 15)(acc, stream, &size) == S_OK && size == 44,
341 "GetStreamDataSize reports the 44-byte empty WAVE header");
342 uint8_t wav[64] = {};
343 check(at<StreamData>(acc, 16)(acc, stream, 8, wav, &got) == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER) && got == 0,
344 "GetStreamData rejects an undersized buffer with ERROR_INSUFFICIENT_BUFFER");
345 check(at<StreamData>(acc, 16)(acc, stream, sizeof(wav), wav, &got) == S_OK && got == 44 &&
346 std::memcmp(wav, "RIFF", 4) == 0 && std::memcmp(wav + 8, "WAVEfmt ", 8) == 0 &&
347 std::memcmp(wav + 36, "data", 4) == 0,
348 "GetStreamData writes a valid silent 16 kHz mono 16-bit PCM WAVE header");
349 check(at<SpeechClose>(acc, 14)(acc, stream) == S_OK, "XSpeechSynthesizerCloseStreamHandle succeeds");
350 stream = nullptr;
351 check(at<SpeechStream>(acc, 21)(acc, synth, "<speak/>", &stream) == S_OK && stream != nullptr &&
352 at<SpeechClose>(acc, 14)(acc, stream) == S_OK,
353 "CreateStreamFromSsml returns a silent WAVE stream");
354 check(at<SpeechClose>(acc, 10)(acc, synth) == S_OK, "XSpeechSynthesizerCloseHandle succeeds");
309 check(at<StreamSize>(acc, 15)(acc, nullptr, &size) == E_INVALIDARG && size == 0 && 355 check(at<StreamSize>(acc, 15)(acc, nullptr, &size) == E_INVALIDARG && size == 0 &&
310 at<StreamData>(acc, 16)(acc, nullptr, 8, nullptr, &got) == E_INVALIDARG && got == 0, 356 at<StreamData>(acc, 16)(acc, nullptr, 8, nullptr, &got) == E_INVALIDARG && got == 0,
311 "stream size and data on a null stream: E_INVALIDARG, zero written"); 357 "stream size and data on a null stream: E_INVALIDARG, zero written");
@@ -317,12 +363,17 @@ int main() {
317 void* launcher = nullptr; 363 void* launcher = nullptr;
318 check(query(&kLauncherClass, kLauncherClass, &launcher) == S_OK && launcher, "XLauncherImpl for its class id"); 364 check(query(&kLauncherClass, kLauncherClass, &launcher) == S_OK && launcher, "XLauncherImpl for its class id");
319 if (!launcher) return 1; 365 if (!launcher) return 1;
320 void* deferral = reinterpret_cast<void*>(1); 366 void* deferral = nullptr;
367 using CloseDeferral = void(STDMETHODCALLTYPE*)(void*, void*);
321 check(at<LaunchUri>(launcher, 3)(launcher, nullptr, "https://example.com") == E_FAIL, 368 check(at<LaunchUri>(launcher, 3)(launcher, nullptr, "https://example.com") == E_FAIL,
322 "XLaunchUri is not available offline"); 369 "XLaunchUri is not available offline");
323 check(at<AcquireDeferral>(launcher, 4)(launcher, &deferral) == E_FAIL && deferral == nullptr && 370 check(at<AcquireDeferral>(launcher, 4)(launcher, nullptr) == E_POINTER,
324 at<NoArgs>(launcher, 5)(launcher) == E_FAIL, 371 "XDisplayAcquireTimeoutDeferral rejects null out pointer");
325 "the display timeout deferral is not available offline"); 372 check(at<AcquireDeferral>(launcher, 4)(launcher, &deferral) == S_OK && deferral != nullptr,
373 "XDisplayAcquireTimeoutDeferral acquires a display power request handle");
374 at<CloseDeferral>(launcher, 5)(launcher, deferral);
375 at<CloseDeferral>(launcher, 5)(launcher, nullptr);
376 check(true, "XDisplayCloseTimeoutDeferralHandle closes handle and ignores null");
326 GUID other = kLauncherClass; 377 GUID other = kLauncherClass;
327 other.Data1 ^= 1; 378 other.Data1 ^= 1;
328 void* none = reinterpret_cast<void*>(1); 379 void* none = reinterpret_cast<void*>(1);
diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp
index 224030247..888bedf24 100644
--- a/runtime/test/xs_proxy_mock_test.cpp
+++ b/runtime/test/xs_proxy_mock_test.cpp
@@ -91,6 +91,8 @@ struct Mock {
91 bool allocator_tag; // allocator: answers kLeonidaCommandAllocatorTag; device: the allocators it makes do 91 bool allocator_tag; // allocator: answers kLeonidaCommandAllocatorTag; device: the allocators it makes do
92 bool create_null; // device: creation returns create_result with no object 92 bool create_null; // device: creation returns create_result with no object
93 HRESULT create_result; // device: what creation returns (S_OK makes the object) 93 HRESULT create_result; // device: what creation returns (S_OK makes the object)
94 bool list_refuse; // device: CreateCommandList refuses every riid with E_NOINTERFACE
95 IID create_riid; // device: copy of the riid its last CreateCommandList got (the caller's may be a local)
94 Mock* last_child; // device: the object its last creation or open made 96 Mock* last_child; // device: the object its last creation or open made
95 unsigned calls[kMockSlots]; 97 unsigned calls[kMockSlots];
96 std::uint64_t args[kMockSlots][5]; 98 std::uint64_t args[kMockSlots][5];
@@ -276,8 +278,10 @@ HRESULT WINAPI mock_create_command_list(Mock* self, std::uint64_t node_mask, std
276 self->args[12][2] = allocator; 278 self->args[12][2] = allocator;
277 self->args[12][3] = initial_state; 279 self->args[12][3] = initial_state;
278 self->args[12][4] = reinterpret_cast<std::uint64_t>(riid); 280 self->args[12][4] = reinterpret_cast<std::uint64_t>(riid);
281 if (riid) self->create_riid = *riid;
279 if (!out) return S_FALSE; 282 if (!out) return S_FALSE;
280 *out = nullptr; 283 *out = nullptr;
284 if (self->list_refuse) return E_NOINTERFACE;
281 if (self->create_null || FAILED(self->create_result)) return self->create_result; 285 if (self->create_null || FAILED(self->create_result)) return self->create_result;
282 Mock* child = new_mock(Kind::command_list); 286 Mock* child = new_mock(Kind::command_list);
283 child->list_level = self->list_level; 287 child->list_level = self->list_level;
@@ -981,17 +985,27 @@ int check_xbox_slots() {
981 985
982// ---- 8. Environment overrides for the Xbox device slots (one process each, read once) ---- 986// ---- 8. Environment overrides for the Xbox device slots (one process each, read once) ----
983 987
988struct EnvPresenter {
989 int stats = 0, present = 0, suspend = 0, resume = 0;
990};
991
984int run_env_slots(bool valid) { 992int run_env_slots(bool valid) {
985 const char* frame_interval = valid ? "96" : "2"; 993 const char* frame_interval = valid ? "96" : "2";
986 const char* schedule_event = valid ? "97" : "2"; 994 const char* schedule_event = valid ? "97" : "2";
987 const char* wait_event = valid ? "98" : "2"; 995 const char* wait_event = valid ? "98" : "2";
988 const char* queue_x = valid ? "99" : "2"; 996 const char* queue_x = valid ? "99" : "2";
989 const char* list_x = valid ? "100" : "2"; 997 const char* list_x = valid ? "100" : "2";
998 const char* frame_statistics = valid ? "101" : "2";
999 const char* suspend_x = valid ? "33" : "2"; // a queue slot beyond the PC table, as SuspendX would be
1000 const char* resume_x = valid ? "30" : "2"; // equal to PresentX's default: ResumeX is unrouted (logged)
990 EXPECT(SetEnvironmentVariableA("LEONIDA_XS_FRAME_INTERVAL_SLOT", frame_interval) != FALSE); 1001 EXPECT(SetEnvironmentVariableA("LEONIDA_XS_FRAME_INTERVAL_SLOT", frame_interval) != FALSE);
991 EXPECT(SetEnvironmentVariableA("LEONIDA_XS_SCHEDULE_EVENT_SLOT", schedule_event) != FALSE); 1002 EXPECT(SetEnvironmentVariableA("LEONIDA_XS_SCHEDULE_EVENT_SLOT", schedule_event) != FALSE);
992 EXPECT(SetEnvironmentVariableA("LEONIDA_XS_WAIT_EVENT_SLOT", wait_event) != FALSE); 1003 EXPECT(SetEnvironmentVariableA("LEONIDA_XS_WAIT_EVENT_SLOT", wait_event) != FALSE);
1004 EXPECT(SetEnvironmentVariableA("LEONIDA_XS_FRAME_STATISTICS_SLOT", frame_statistics) != FALSE);
993 EXPECT(SetEnvironmentVariableA("LEONIDA_XS_QUEUE_X_SLOT", queue_x) != FALSE); 1005 EXPECT(SetEnvironmentVariableA("LEONIDA_XS_QUEUE_X_SLOT", queue_x) != FALSE);
994 EXPECT(SetEnvironmentVariableA("LEONIDA_XS_LIST_X_SLOT", list_x) != FALSE); 1006 EXPECT(SetEnvironmentVariableA("LEONIDA_XS_LIST_X_SLOT", list_x) != FALSE);
1007 EXPECT(SetEnvironmentVariableA("LEONIDA_XS_SUSPEND_X_SLOT", suspend_x) != FALSE);
1008 EXPECT(SetEnvironmentVariableA("LEONIDA_XS_RESUME_X_SLOT", resume_x) != FALSE);
995 1009
996 Mock* mock = nullptr; 1010 Mock* mock = nullptr;
997 void* device = make_device(mock, 11, true); 1011 void* device = make_device(mock, 11, true);
@@ -1018,6 +1032,36 @@ int run_env_slots(bool valid) {
1018 EXPECT(hr_of(raw(device, 78, 0, 16667, 1, 0)) == S_OK && mock->calls[78] == 1); 1032 EXPECT(hr_of(raw(device, 78, 0, 16667, 1, 0)) == S_OK && mock->calls[78] == 1);
1019 EXPECT(release(list) == 0); 1033 EXPECT(release(list) == 0);
1020 EXPECT(release(allocator) == 0); 1034 EXPECT(release(allocator) == 0);
1035
1036 // The presenter answers frame statistics at 101 only (81 is not routed, so the mock refuses it); PresentX
1037 // stays at 30, SuspendX answers at 33, and ResumeX, asked for 30, is unrouted, so 32 is refused.
1038 EnvPresenter env{};
1039 xs::PresentationHandler h{};
1040 h.context = &env;
1041 h.get_frame_statistics = [](void* ctx, std::uint64_t, UINT, UINT*, void*) -> HRESULT {
1042 ++static_cast<EnvPresenter*>(ctx)->stats;
1043 return S_FALSE;
1044 };
1045 h.present_x = [](void* ctx, UINT, const void*, const void*) -> HRESULT {
1046 ++static_cast<EnvPresenter*>(ctx)->present;
1047 return S_OK;
1048 };
1049 h.suspend_x = [](void* ctx, UINT) -> HRESULT {
1050 ++static_cast<EnvPresenter*>(ctx)->suspend;
1051 return S_OK;
1052 };
1053 h.resume_x = [](void* ctx) -> HRESULT {
1054 ++static_cast<EnvPresenter*>(ctx)->resume;
1055 return S_OK;
1056 };
1057 EXPECT(xs::set_presentation_handler(device, &h));
1058 UINT count = 0;
1059 EXPECT(hr_of(raw(device, 101, 77, 0x1a, word(&count), 0)) == S_FALSE && env.stats == 1);
1060 EXPECT(hr_of(raw(device, 81, 77, 0x1a, word(&count), 0)) == E_NOTIMPL && env.stats == 1);
1061 EXPECT(hr_of(raw(queue, 30, 1, 0, 0)) == S_OK && env.present == 1);
1062 EXPECT(hr_of(raw(queue, 33)) == S_OK && env.suspend == 1);
1063 EXPECT(hr_of(raw(queue, 32)) == E_NOTIMPL && env.resume == 0);
1064 EXPECT(xs::set_presentation_handler(device, nullptr));
1021 EXPECT(release(queue) == 0); 1065 EXPECT(release(queue) == 0);
1022 } else { 1066 } else {
1023 // Values outside 3..127 are ignored: the five defaults still answer, and a PC slot that is not a default is 1067 // Values outside 3..127 are ignored: the five defaults still answer, and a PC slot that is not a default is
@@ -1025,6 +1069,7 @@ int run_env_slots(bool valid) {
1025 EXPECT(hr_of(raw(device, 78, 0, 16667, 1, 0)) == S_OK && mock->calls[78] == 0); 1069 EXPECT(hr_of(raw(device, 78, 0, 16667, 1, 0)) == S_OK && mock->calls[78] == 0);
1026 EXPECT(hr_of(raw(device, 79, 0, 0, 0, 0)) == S_OK && mock->calls[79] == 0); 1070 EXPECT(hr_of(raw(device, 79, 0, 0, 0, 0)) == S_OK && mock->calls[79] == 0);
1027 EXPECT(hr_of(raw(device, 80, 0, 0, 0, 0, word(&token))) == S_OK && token && mock->calls[80] == 0); 1071 EXPECT(hr_of(raw(device, 80, 0, 0, 0, 0, word(&token))) == S_OK && token && mock->calls[80] == 0);
1072 EXPECT(hr_of(raw(device, 81, 0, 0, 0, 0)) == S_FALSE); // the default GetFrameStatisticsX slot, unattached
1028 EXPECT(hr_of(raw(device, 71)) == S_OK && mock->calls[71] == 1); // not an Xbox slot: forwarded 1073 EXPECT(hr_of(raw(device, 71)) == S_OK && mock->calls[71] == 1); // not an Xbox slot: forwarded
1029 } 1074 }
1030 EXPECT(release(device) == 0 && mock->refs == 0); 1075 EXPECT(release(device) == 0 && mock->refs == 0);
@@ -1504,6 +1549,39 @@ int check_console_command_list() {
1504 EXPECT(real_queue->array[10][0] == word(unwrapped_list)); 1549 EXPECT(real_queue->array[10][0] == word(unwrapped_list));
1505 EXPECT(real_queue->array[10][1] == word(real_list)); 1550 EXPECT(real_queue->array[10][1] == word(real_list));
1506 1551
1552 // 5b. Public list revisions the proxy does not model and unknown private IIDs must not trigger a retry.
1553 // Spell out the Windows SDK's ID3D12GraphicsCommandList9 IID so this also builds with older headers.
1554 const IID list9_iid = {0x34ed2808, 0xffe6, 0x4c2b, {0xb1, 0x1a, 0xca, 0xbd, 0x2b, 0x0c, 0x59, 0xe1}};
1555 const IID unknown_iid = {0x12345678, 0x1234, 0x1234, {1, 2, 3, 4, 5, 6, 7, 8}};
1556 for (const IID* iid : {&list9_iid, &unknown_iid}) {
1557 const unsigned calls_before = mock_device->calls[12];
1558 void* unsupported_list = list_proxy;
1559 EXPECT(hr_of(raw(device, 73, word(&desc), word(allocator), 0, word(iid), word(&unsupported_list))) ==
1560 E_NOINTERFACE);
1561 EXPECT(!unsupported_list && mock_device->calls[12] == calls_before + 1);
1562 }
1563
1564 // The measured Xbox list IID is created as ID3D12GraphicsCommandList in one call and stays queryable on the proxy.
1565 const IID console_iid = {0xc3827890, 0x4024, 0x474c, {0x98, 0xcf, 0x64, 0x5b, 0x51, 0xdc, 0x48, 0x74}};
1566 const unsigned calls12_before = mock_device->calls[12];
1567 void* console_list = nullptr;
1568 EXPECT(hr_of(raw(device, 73, word(&desc), word(allocator), 0, word(&console_iid), word(&console_list))) == S_OK);
1569 EXPECT(xs::is_command_list_proxy(console_list) && mock_device->calls[12] == calls12_before + 1);
1570 EXPECT(IsEqualIID(mock_device->create_riid, __uuidof(ID3D12GraphicsCommandList)));
1571 void* console_list_qi = nullptr;
1572 EXPECT(hr_of(raw(console_list, 0, word(&console_iid), word(&console_list_qi))) == S_OK);
1573 EXPECT(console_list_qi == console_list && release(console_list_qi) == 1);
1574 EXPECT(release(console_list) == 0);
1575
1576 // The PC device refuses even ID3D12GraphicsCommandList for a PC IID: E_NOINTERFACE comes back as is, no retry.
1577 mock_device->list_refuse = true;
1578 const unsigned calls12_refused = mock_device->calls[12];
1579 console_list = nullptr;
1580 EXPECT(hr_of(raw(device, 73, word(&desc), word(allocator), 0, word(&list_iid), word(&console_list))) ==
1581 E_NOINTERFACE);
1582 EXPECT(!console_list && mock_device->calls[12] == calls12_refused + 1);
1583 mock_device->list_refuse = false;
1584
1507 // 6. Test with list_level = 7 (supporting ID3D12GraphicsCommandList7, 81 slots) 1585 // 6. Test with list_level = 7 (supporting ID3D12GraphicsCommandList7, 81 slots)
1508 mock_device->list_level = 7; 1586 mock_device->list_level = 7;
1509 void* list7_proxy = nullptr; 1587 void* list7_proxy = nullptr;
@@ -1534,6 +1612,99 @@ int check_console_command_list() {
1534 return 0; 1612 return 0;
1535} 1613}
1536 1614
1615// ---- 11. Presentation handler wiring (device slots 78–81 + queue PresentX/SuspendX/ResumeX) ----
1616
1617struct MockPresenter {
1618 int interval_calls = 0;
1619 UINT last_interval = 0;
1620 int schedule_calls = 0;
1621 UINT last_event = 0;
1622 int wait_calls = 0;
1623 UINT last_flags = 0;
1624 int stats_calls = 0;
1625 int present_calls = 0;
1626 UINT last_planes = 0;
1627 int suspend_calls = 0;
1628 int resume_calls = 0;
1629};
1630
1631int check_presentation_wiring() {
1632 Mock* mock = nullptr;
1633 void* device = make_device(mock, 11, true);
1634 EXPECT(device != nullptr);
1635 void* queue = make_queue(device);
1636 EXPECT(queue != nullptr);
1637
1638 MockPresenter p{};
1639 xs::PresentationHandler h{};
1640 h.context = &p;
1641 h.set_frame_interval = [](void* ctx, IUnknown*, UINT us, UINT, UINT) -> HRESULT {
1642 auto* m = static_cast<MockPresenter*>(ctx);
1643 ++m->interval_calls;
1644 m->last_interval = us;
1645 return S_OK;
1646 };
1647 h.schedule_frame_event = [](void* ctx, UINT ev, UINT, UINT) -> HRESULT {
1648 auto* m = static_cast<MockPresenter*>(ctx);
1649 ++m->schedule_calls;
1650 m->last_event = ev;
1651 return S_OK;
1652 };
1653 h.wait_frame_event = [](void* ctx, UINT, DWORD, UINT flags, std::uint64_t* tok) -> HRESULT {
1654 auto* m = static_cast<MockPresenter*>(ctx);
1655 ++m->wait_calls;
1656 m->last_flags = flags;
1657 if (tok) *tok = 77;
1658 return S_FALSE;
1659 };
1660 h.get_frame_statistics = [](void* ctx, std::uint64_t, UINT, UINT* count, void*) -> HRESULT {
1661 auto* m = static_cast<MockPresenter*>(ctx);
1662 ++m->stats_calls;
1663 if (count) *count = 0;
1664 return S_FALSE;
1665 };
1666 h.present_x = [](void* ctx, UINT plane_count, const void*, const void*) -> HRESULT {
1667 auto* m = static_cast<MockPresenter*>(ctx);
1668 ++m->present_calls;
1669 m->last_planes = plane_count;
1670 return S_OK;
1671 };
1672 h.suspend_x = [](void* ctx, UINT) -> HRESULT {
1673 ++static_cast<MockPresenter*>(ctx)->suspend_calls;
1674 return S_OK;
1675 };
1676 h.resume_x = [](void* ctx) -> HRESULT {
1677 ++static_cast<MockPresenter*>(ctx)->resume_calls;
1678 return S_OK;
1679 };
1680
1681 EXPECT(xs::set_presentation_handler(device, &h));
1682 EXPECT(hr_of(raw(device, 78, 0, 33333, 2, 0)) == S_OK && p.interval_calls == 1 && p.last_interval == 33333);
1683 EXPECT(hr_of(raw(device, 79, 2, 0, 0, 0)) == S_OK && p.schedule_calls == 1 && p.last_event == 2);
1684 std::uint64_t tok = 0;
1685 EXPECT(hr_of(raw(device, 80, 0, 0, 0, 2, word(&tok))) == S_FALSE && tok == 77 && p.wait_calls == 1 &&
1686 p.last_flags == 2);
1687 UINT count = 3;
1688 EXPECT(hr_of(raw(device, 81, 77, 0x1a, word(&count), 0)) == S_FALSE && count == 0 && p.stats_calls == 1);
1689
1690 // Queue slot 30 routes to PresentX while attached. SuspendX and ResumeX have no default route, so 31/32 are refused
1691 // and never reach the presenter (the env mode, run_env_slots, routes them).
1692 EXPECT(hr_of(raw(queue, 30, 1, 0x1000, 0x2000)) == S_OK && p.present_calls == 1 && p.last_planes == 1);
1693 EXPECT(hr_of(raw(queue, 31, 0)) == E_NOTIMPL && p.suspend_calls == 0);
1694 EXPECT(hr_of(raw(queue, 32)) == E_NOTIMPL && p.resume_calls == 0);
1695
1696 // Detaching restores default E_NOTIMPL refusal on beyond-PC queue slots.
1697 EXPECT(xs::set_presentation_handler(device, nullptr));
1698 UINT none = 7; // unattached GetFrameStatisticsX: no statistics yet, never the PC slot 81
1699 EXPECT(hr_of(raw(device, 81, 77, 0x1a, word(&none), 0)) == S_FALSE && none == 0 && p.stats_calls == 1);
1700 EXPECT(hr_of(raw(queue, 30, 1, 0, 0)) == E_NOTIMPL && p.present_calls == 1);
1701
1702 EXPECT(release(queue) == 0);
1703 EXPECT(release(device) == 0 && mock->refs == 0);
1704 std::printf("%s: presentation handler wiring (slots 78-81 and queue PresentX 30) passed\n", g_label);
1705 return 0;
1706}
1707
1537int main(int argc, char** argv) { 1708int main(int argc, char** argv) {
1538 no_dialogs(); 1709 no_dialogs();
1539 std::setvbuf(stdout, nullptr, _IONBF, 0); 1710 std::setvbuf(stdout, nullptr, _IONBF, 0);
@@ -1546,7 +1717,8 @@ int main(int argc, char** argv) {
1546 if (check_tail(true) || check_levels() || check_slot48() || check_fence1() || check_create_failures() || check_open_shared() || 1717 if (check_tail(true) || check_levels() || check_slot48() || check_fence1() || check_create_failures() || check_open_shared() ||
1547 check_alloc_failures() || check_allocators() || check_xbox_slots() || check_console_command_list() || 1718 check_alloc_failures() || check_allocators() || check_xbox_slots() || check_console_command_list() ||
1548 check_custom_heap_properties() || 1719 check_custom_heap_properties() ||
1549 check_resource_allocation_info() || check_slot70() || check_committed_resource3_x()) 1720 check_resource_allocation_info() || check_slot70() || check_committed_resource3_x() ||
1721 check_presentation_wiring())
1550 return 1; 1722 return 1;
1551 std::printf("xs_proxy_mock_test: PASS (%d allocations refused on purpose)\n", g_failed_news); 1723 std::printf("xs_proxy_mock_test: PASS (%d allocations refused on purpose)\n", g_failed_news);
1552 return 0; 1724 return 0;
diff --git a/runtime/xma_decoder/README.md b/runtime/xma_decoder/README.md
index 4a6d5fb10..9db801810 100644
--- a/runtime/xma_decoder/README.md
+++ b/runtime/xma_decoder/README.md
@@ -6,8 +6,6 @@ Each decoder handle serializes decode calls. The returned PCM block owns its sam
6 6
7The tests build packets in memory; they do not open or contain audio fixtures. The synthetic C++ smoke test verifies the exported ABI and ownership boundary. 7The tests build packets in memory; they do not open or contain audio fixtures. The synthetic C++ smoke test verifies the exported ABI and ownership boundary.
8 8
9This PR adds the decoder boundary only; the Windows XAudio2 engine/source-voice adapter is a follow-up stage.
10
11Run: 9Run:
12 10
13```powershell 11```powershell
@@ -17,3 +15,12 @@ cargo build --manifest-path runtime/xma_decoder/Cargo.toml --locked
17``` 15```
18 16
19The C++ smoke test is run by the xma2-decoder workflow with MSVC. It links ws2_32, userenv, and ntdll for Rust's Windows standard library. 17The C++ smoke test is run by the xma2-decoder workflow with MSVC. It links ws2_32, userenv, and ntdll for Rust's Windows standard library.
18
19## Use in the runtime
20
21`runtime/CMakeLists.txt` builds this crate for `x86_64-pc-windows-msvc` at configure time when `cargo` is on `PATH` and links it into `gta6rt` and `acphal_test` with `LEONIDA_HAVE_XMA2_DECODER` defined. The first build fetches the pinned `xma` git dependency. Set `CARGO_NET_OFFLINE=true` for a configure that uses only the local Cargo cache.
22
23`runtime/shims/acphal.cpp` uses `leonida_xma2_decoder_create_hardware` and decodes whole 2048-byte packets, so loop points are rounded to packets. The shim creates a fresh decoder after a loop rewind or a decoder error.
24
25Without `cargo`, when that build fails, or with the cl.exe fallback of `scripts/build_runtime.ps1`, XMA voices output silence.
26Use `-DLEONIDA_REQUIRE_XMA2_DECODER=ON` to require the decoder in a CMake build, as the Windows runtime CI does.
diff --git a/runtime/xma_decoder/leonida_xma2_decoder.h b/runtime/xma_decoder/leonida_xma2_decoder.h
index 98dd5c49c..a4c5b4534 100644
--- a/runtime/xma_decoder/leonida_xma2_decoder.h
+++ b/runtime/xma_decoder/leonida_xma2_decoder.h
@@ -25,6 +25,10 @@ enum LeonidaXma2Status {
25 25
26int32_t leonida_xma2_decoder_create(uint32_t sample_rate, uint32_t channels, 26int32_t leonida_xma2_decoder_create(uint32_t sample_rate, uint32_t channels,
27 LeonidaXma2Decoder **out_decoder); 27 LeonidaXma2Decoder **out_decoder);
28/* Like leonida_xma2_decoder_create, but decodes like the console's XMA hardware: the first
29 frame is kept and there is no 64-sample start skip; the caller applies the context's skip. */
30int32_t leonida_xma2_decoder_create_hardware(uint32_t sample_rate, uint32_t channels,
31 LeonidaXma2Decoder **out_decoder);
28int32_t leonida_xma2_decode_buffer(LeonidaXma2Decoder *decoder, 32int32_t leonida_xma2_decode_buffer(LeonidaXma2Decoder *decoder,
29 const uint8_t *input, size_t input_len, 33 const uint8_t *input, size_t input_len,
30 LeonidaXma2PcmBlock **out_block); 34 LeonidaXma2PcmBlock **out_block);
diff --git a/runtime/xma_decoder/src/lib.rs b/runtime/xma_decoder/src/lib.rs
index 1b435a0ce..69fedf49e 100644
--- a/runtime/xma_decoder/src/lib.rs
+++ b/runtime/xma_decoder/src/lib.rs
@@ -59,6 +59,28 @@ pub unsafe extern "C" fn leonida_xma2_decoder_create(
59 channels: u32, 59 channels: u32,
60 out_decoder: *mut *mut LeonidaXma2Decoder, 60 out_decoder: *mut *mut LeonidaXma2Decoder,
61) -> i32 { 61) -> i32 {
62 unsafe { create_with(sample_rate, channels, out_decoder, Xma2Stream::new) }
63}
64
65/// Like `leonida_xma2_decoder_create`, but decodes like the console's XMA hardware: the first
66/// frame is kept and there is no 64-sample start skip; the caller applies the context's skip.
67/// # Safety
68/// Same as `leonida_xma2_decoder_create`.
69#[no_mangle]
70pub unsafe extern "C" fn leonida_xma2_decoder_create_hardware(
71 sample_rate: u32,
72 channels: u32,
73 out_decoder: *mut *mut LeonidaXma2Decoder,
74) -> i32 {
75 unsafe { create_with(sample_rate, channels, out_decoder, Xma2Stream::new_hardware) }
76}
77
78unsafe fn create_with<E>(
79 sample_rate: u32,
80 channels: u32,
81 out_decoder: *mut *mut LeonidaXma2Decoder,
82 make: impl FnOnce(u32, usize) -> Result<Xma2Stream, E>,
83) -> i32 {
62 if out_decoder.is_null() { 84 if out_decoder.is_null() {
63 return LEONIDA_XMA2_INVALID_ARGUMENT; 85 return LEONIDA_XMA2_INVALID_ARGUMENT;
64 } 86 }
@@ -68,8 +90,8 @@ pub unsafe extern "C" fn leonida_xma2_decoder_create(
68 } 90 }
69 91
70 match catch_unwind(AssertUnwindSafe(|| { 92 match catch_unwind(AssertUnwindSafe(|| {
71 let stream = Xma2Stream::new(sample_rate, channels as usize) 93 let stream =
72 .map_err(|_| LEONIDA_XMA2_INVALID_FORMAT)?; 94 make(sample_rate, channels as usize).map_err(|_| LEONIDA_XMA2_INVALID_FORMAT)?;
73 try_new_handle(LeonidaXma2Decoder { 95 try_new_handle(LeonidaXma2Decoder {
74 stream: Mutex::new(stream), 96 stream: Mutex::new(stream),
75 channels: channels as usize, 97 channels: channels as usize,
@@ -87,7 +109,8 @@ pub unsafe extern "C" fn leonida_xma2_decoder_create(
87/// Decodes a buffer containing one or more complete 2048-byte XMA2 packets. 109/// Decodes a buffer containing one or more complete 2048-byte XMA2 packets.
88/// 110///
89/// # Safety 111/// # Safety
90/// `decoder` must be a live handle returned by `leonida_xma2_decoder_create`. 112/// `decoder` must be a live handle returned by `leonida_xma2_decoder_create`
113/// or `leonida_xma2_decoder_create_hardware`.
91/// `input` must reference `input_len` readable bytes and `out_block` must be writable. 114/// `input` must reference `input_len` readable bytes and `out_block` must be writable.
92/// Do not destroy a decoder concurrently with this call. The returned PCM block remains valid 115/// Do not destroy a decoder concurrently with this call. The returned PCM block remains valid
93/// until `leonida_xma2_pcm_destroy` is called. 116/// until `leonida_xma2_pcm_destroy` is called.
@@ -160,8 +183,8 @@ pub unsafe extern "C" fn leonida_xma2_decode_buffer(
160/// Destroys a decoder. Passing null is a no-op. 183/// Destroys a decoder. Passing null is a no-op.
161/// 184///
162/// # Safety 185/// # Safety
163/// A non-null pointer must be a live handle returned by `leonida_xma2_decoder_create`, 186/// A non-null pointer must be a live handle returned by `leonida_xma2_decoder_create`
164/// and no calls may be using it concurrently. 187/// or `leonida_xma2_decoder_create_hardware`. No calls may be using it concurrently.
165#[no_mangle] 188#[no_mangle]
166pub unsafe extern "C" fn leonida_xma2_decoder_destroy(decoder: *mut LeonidaXma2Decoder) { 189pub unsafe extern "C" fn leonida_xma2_decoder_destroy(decoder: *mut LeonidaXma2Decoder) {
167 if !decoder.is_null() { 190 if !decoder.is_null() {
@@ -233,6 +256,24 @@ mod tests {
233 } 256 }
234 257
235 #[test] 258 #[test]
259 fn create_hardware_accepts_stereo_and_rejects_three_channels() {
260 let mut decoder = ptr::null_mut();
261 assert_eq!(
262 unsafe { leonida_xma2_decoder_create_hardware(48_000, 2, &mut decoder) },
263 LEONIDA_XMA2_OK
264 );
265 assert!(!decoder.is_null());
266 unsafe { leonida_xma2_decoder_destroy(decoder) };
267
268 let mut decoder = ptr::dangling_mut();
269 assert_eq!(
270 unsafe { leonida_xma2_decoder_create_hardware(48_000, 3, &mut decoder) },
271 LEONIDA_XMA2_INVALID_FORMAT
272 );
273 assert!(decoder.is_null());
274 }
275
276 #[test]
236 fn pcm_handle_allocation_failure_clears_output_and_allows_retry() { 277 fn pcm_handle_allocation_failure_clears_output_and_allows_retry() {
237 let mut decoder = ptr::null_mut(); 278 let mut decoder = ptr::null_mut();
238 assert_eq!( 279 assert_eq!(
diff --git a/runtime/xma_decoder/tests/ffi_contract.rs b/runtime/xma_decoder/tests/ffi_contract.rs
index 0eb8e5cf4..6e6185c39 100644
--- a/runtime/xma_decoder/tests/ffi_contract.rs
+++ b/runtime/xma_decoder/tests/ffi_contract.rs
@@ -52,6 +52,28 @@ fn make_decoder(rate: u32, channels: u32) -> *mut LeonidaXma2Decoder {
52} 52}
53 53
54#[test] 54#[test]
55fn hardware_mode_keeps_all_samples_of_the_first_stereo_frame() {
56 let mut packet = synthetic_silent_packet(2);
57 packet[..4].copy_from_slice(&[4, 0, 1, 0]); // One frame, no continuation from a previous packet.
58 let mut decoder = ptr::null_mut();
59 let mut block = ptr::null_mut();
60 unsafe {
61 assert_eq!(
62 leonida_xma2_decoder_create_hardware(48_000, 2, &mut decoder),
63 LEONIDA_XMA2_OK
64 );
65 assert_eq!(
66 leonida_xma2_decode_buffer(decoder, packet.as_ptr(), packet.len(), &mut block),
67 LEONIDA_XMA2_OK
68 );
69 let count = leonida_xma2_pcm_sample_count(block);
70 leonida_xma2_pcm_destroy(block);
71 leonida_xma2_decoder_destroy(decoder);
72 assert_eq!(count, 512 * 2);
73 }
74}
75
76#[test]
55fn creation_rejects_invalid_outputs_and_formats() { 77fn creation_rejects_invalid_outputs_and_formats() {
56 assert_eq!( 78 assert_eq!(
57 unsafe { leonida_xma2_decoder_create(48_000, 2, ptr::null_mut()) }, 79 unsafe { leonida_xma2_decoder_create(48_000, 2, ptr::null_mut()) },
diff --git a/scripts/build_runtime.ps1 b/scripts/build_runtime.ps1
index 63acb7ce3..f24cc073f 100644
--- a/scripts/build_runtime.ps1
+++ b/scripts/build_runtime.ps1
@@ -83,10 +83,10 @@ $build || exit /b 1
83} else { 83} else {
84 # Keep this list in step with runtime\CMakeLists.txt. Optional parts that need a dependency are left out here: 84 # Keep this list in step with runtime\CMakeLists.txt. Optional parts that need a dependency are left out here:
85 # the GameInput shim (SDL3), so controllers go through the host's GameInput.dll, if any, as without the shim. 85 # the GameInput shim (SDL3), so controllers go through the host's GameInput.dll, if any, as without the shim.
86 Write-Warning "CMake and Ninja weren't found (neither VS C++ CMake tools nor native PATH tools): building with cl.exe directly, without the GameInput shim (SDL3). Install CMake + Ninja or VS's CMake tools component to get it." 86 Write-Warning "CMake and Ninja weren't found (neither VS C++ CMake tools nor native PATH tools): building with cl.exe directly, without the GameInput shim (SDL3) and without the Rust XMA2 decoder (XMA voices are silent). Install CMake + Ninja or VS's CMake tools component to get it."
87 $xtaskqueueDir = Join-Path $root "third_party\xtaskqueue" 87 $xtaskqueueDir = Join-Path $root "third_party\xtaskqueue"
88 $xtaskqueueFiles = "Source\Task\TaskQueue.cpp", "Source\Task\AsyncLib.cpp", "Source\Task\ThreadPool_win32.cpp", "Source\Task\WaitTimer_win32.cpp" | ForEach-Object { "`"$xtaskqueueDir\$_`"" } 88 $xtaskqueueFiles = "Source\Task\TaskQueue.cpp", "Source\Task\AsyncLib.cpp", "Source\Task\ThreadPool_win32.cpp", "Source\Task\WaitTimer_win32.cpp" | ForEach-Object { "`"$xtaskqueueDir\$_`"" }
89 $files = "src\main.cpp", "src\host_cpu.cpp", "src\pe_loader.cpp", "shims\registry.cpp", "shims\file_system.cpp", "shims\xmem.cpp", "shims\xg_xs.cpp", "shims\acphal.cpp", "shims\d3d12_xs.cpp", "shims\d3d12_xs_device.cpp", "shims\d3d12_xs_rootsig.cpp", "shims\xgameruntime.cpp", "shims\xgameruntime_user.cpp", "shims\xgameruntime_gamesave.cpp", "shims\xgameruntime_store.cpp", "shims\xgameruntime_offline.cpp", "shims\winhttp_offline.cpp", "shims\library_loader.cpp", "shims\process.cpp", "shims\com_shim.cpp", "shims\bcrypt_rng.cpp", "shims\xapu_chad.cpp", "shims\dstorage.cpp" | ForEach-Object { "`"$src\$_`"" } 89 $files = "src\main.cpp", "src\host_cpu.cpp", "src\pe_loader.cpp", "shims\registry.cpp", "shims\file_system.cpp", "shims\xmem.cpp", "shims\xg_xs.cpp", "shims\acphal.cpp", "shims\d3d12_xs.cpp", "shims\d3d12_xs_device.cpp", "shims\d3d12_xs_rootsig.cpp", "shims\xgameruntime.cpp", "shims\xgameruntime_user.cpp", "shims\xgameruntime_gamesave.cpp", "shims\xgameruntime_store.cpp", "shims\xgameruntime_offline.cpp", "shims\winhttp_offline.cpp", "shims\ws2_offline.cpp", "shims\library_loader.cpp", "shims\process.cpp", "shims\com_shim.cpp", "shims\bcrypt_rng.cpp", "shims\xapu_chad.cpp", "shims\dstorage.cpp" | ForEach-Object { "`"$src\$_`"" }
90 $includes = "/I `"$src\src`" /I `"$src\shims`" /I `"$src\shims\xtaskqueue`" /I `"$xtaskqueueDir\Include`" /I `"$xtaskqueueDir\Source\Task`" /I `"$xtaskqueueDir\Source\Common`"" 90 $includes = "/I `"$src\src`" /I `"$src\shims`" /I `"$src\shims\xtaskqueue`" /I `"$xtaskqueueDir\Include`" /I `"$xtaskqueueDir\Source\Task`" /I `"$xtaskqueueDir\Source\Common`""
91 $opt = if ($Debug) { "/Od /MDd" } else { "/O2 /MD" } 91 $opt = if ($Debug) { "/Od /MDd" } else { "/O2 /MD" }
92 $body = @" 92 $body = @"
diff --git a/scripts/check_no_game_data.py b/scripts/check_no_game_data.py
index a5b65e242..bccee5e68 100644
--- a/scripts/check_no_game_data.py
+++ b/scripts/check_no_game_data.py
@@ -21,7 +21,8 @@ under a budget per checked file (64 MiB expanded, 10,000 members), so a zip bomb
21reported as archives that can't be checked. 21reported as archives that can't be checked.
22 22
23Prints one line per match, `<path>: <format>` (`<format> in <archive> (<member>)` for a match inside an archive), and 23Prints one line per match, `<path>: <format>` (`<format> in <archive> (<member>)` for a match inside an archive), and
24exits 1 if there is any. Standard library only, no game files. 24exits 1 if there is any. It exits 2 when a file cannot be read or git cannot list the tracked files (outside a
25repository, or git not installed). Standard library only, no game files.
25""" 26"""
26import bz2 27import bz2
27import gzip 28import gzip
@@ -257,6 +258,14 @@ def tracked_files(root):
257 return [os.path.join(root, p) for p in out.decode("utf-8", "surrogateescape").split("\0") if p] 258 return [os.path.join(root, p) for p in out.decode("utf-8", "surrogateescape").split("\0") if p]
258 259
259 260
261def git_error(e):
262 """One line on why git could not list the files: the first line git printed, or the OS error."""
263 if isinstance(e, subprocess.CalledProcessError):
264 lines = (e.stderr or b"").decode("utf-8", "replace").splitlines()
265 return next((line.strip() for line in lines if line.strip()), f"exit status {e.returncode}")
266 return e.strerror or str(e)
267
268
260def check(paths, unreadable=None): 269def check(paths, unreadable=None):
261 """[(path, format)] for every regular file in `paths` that starts like game data. 270 """[(path, format)] for every regular file in `paths` that starts like game data.
262 271
@@ -285,7 +294,14 @@ def display(path):
285 294
286 295
287def main(argv): 296def main(argv):
288 paths = argv or tracked_files(os.getcwd()) 297 if argv:
298 paths = argv
299 else:
300 try:
301 paths = tracked_files(os.getcwd())
302 except (OSError, subprocess.CalledProcessError) as e:
303 print(f"check_no_game_data: cannot list the tracked files with git: {git_error(e)}", file=sys.stderr)
304 return 2 # not 1: that is the 'game data found' code
289 unreadable = [] 305 unreadable = []
290 found = check(paths, unreadable) 306 found = check(paths, unreadable)
291 for path, name in found: 307 for path, name in found:
diff --git a/scripts/ci_expected_failures.py b/scripts/ci_expected_failures.py
index 8112dcf4b..f398020f7 100644
--- a/scripts/ci_expected_failures.py
+++ b/scripts/ci_expected_failures.py
@@ -2,11 +2,13 @@
2 2
3 python -I scripts/ci_expected_failures.py FAILED_LIST EXIT_STATUS [EXPECTED ...] 3 python -I scripts/ci_expected_failures.py FAILED_LIST EXIT_STATUS [EXPECTED ...]
4 4
5FAILED_LIST is a file with one failed test name per line, EXIT_STATUS the test runner's exit status, and each 5FAILED_LIST is a UTF-8 file with one failed test name per line and an optional BOM.
6EXPECTED argument one or more whitespace-separated test names (so a workflow can pass one quoted list). Exits 1 when a 6EXIT_STATUS is the test runner's exit status. Each EXPECTED argument is one or more whitespace-separated
7test outside EXPECTED failed, the runner failed without naming a test, or the runner was terminated by a signal 7test names, so a workflow can pass one quoted list.
8(its failure list can be incomplete); 2 on a usage error. `--help` prints this text. An expected failure absent 8
9from a completed run gets a GitHub Actions notice so the list in the workflow can shrink. 9Exits 1 when an unexpected test failed, the runner failed without naming a test, or a signal terminated the runner.
10Exits 2 on a usage error. `--help` prints this text. An expected failure absent from a completed run gets a GitHub
11Actions notice so the list in the workflow can shrink.
10""" 12"""
11 13
12import sys 14import sys
@@ -43,10 +45,10 @@ def main(argv: list[str]) -> int:
43 print(f"ci_expected_failures: EXIT_STATUS {argv[1]!r} is not an integer", file=sys.stderr) 45 print(f"ci_expected_failures: EXIT_STATUS {argv[1]!r} is not an integer", file=sys.stderr)
44 return 2 46 return 2
45 try: 47 try:
46 with open(argv[0], encoding="utf-8") as f: 48 with open(argv[0], encoding="utf-8-sig") as f:
47 failed = [line.strip() for line in f if line.strip()] 49 failed = [line.strip() for line in f if line.strip()]
48 except OSError as e: 50 except (OSError, UnicodeDecodeError) as e:
49 print(f"ci_expected_failures: {argv[0]}: {e.strerror or e}", file=sys.stderr) 51 print(f"ci_expected_failures: {argv[0]}: {getattr(e, 'strerror', None) or e}", file=sys.stderr)
50 return 2 52 return 2
51 expected = [name for arg in argv[2:] for name in arg.split()] 53 expected = [name for arg in argv[2:] for name in arg.split()]
52 code, lines = judge(failed, status, expected) 54 code, lines = judge(failed, status, expected)
diff --git a/scripts/merge_check.py b/scripts/merge_check.py
index c4cbdceca..81bb3368a 100644
--- a/scripts/merge_check.py
+++ b/scripts/merge_check.py
@@ -42,7 +42,10 @@ class GitError(Exception):
42 42
43 43
44def git(repo, *args, check=True): 44def git(repo, *args, check=True):
45 r = subprocess.run(["git", "-C", repo, *args], capture_output=True) 45 try:
46 r = subprocess.run(["git", "-C", repo, *args], capture_output=True)
47 except OSError as e: # git is not on PATH, or cannot be executed: a usage error (exit 2), not a traceback
48 raise GitError(f"cannot run git: {e.strerror or e}") from None
46 # Decode without universal-newline translation: a bare CR inside a Git line is content. 49 # Decode without universal-newline translation: a bare CR inside a Git line is content.
47 r.stdout = r.stdout.decode("utf-8", "replace") 50 r.stdout = r.stdout.decode("utf-8", "replace")
48 r.stderr = r.stderr.decode("utf-8", "replace") 51 r.stderr = r.stderr.decode("utf-8", "replace")
@@ -64,7 +67,7 @@ def _merged_pr_number(subject):
64def prior_merges(repo, main, numbers, depth): 67def prior_merges(repo, main, numbers, depth):
65 out = git(repo, "log", main, "--first-parent", f"-n{depth}", "--format=%H%x09%s").stdout 68 out = git(repo, "log", main, "--first-parent", f"-n{depth}", "--format=%H%x09%s").stdout
66 hits = {number: [] for number in numbers} 69 hits = {number: [] for number in numbers}
67 for line in out.splitlines(): 70 for line in out.split("\n"):
68 sha, _, subject = line.partition("\t") 71 sha, _, subject = line.partition("\t")
69 number = _merged_pr_number(subject) 72 number = _merged_pr_number(subject)
70 if number in hits: 73 if number in hits:
diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py
index a075c876a..e8fce4277 100644
--- a/scripts/run_gpu_tests.py
+++ b/scripts/run_gpu_tests.py
@@ -36,6 +36,7 @@ from check import (CMPX_CLASS_WORDS, CVT_F32_SAT_CASES, CVT_PK_U8_WORDS, PK_MUL_
36from check import SIGNED_MIP_TEST, UINT_MIP_TEST 36from check import SIGNED_MIP_TEST, UINT_MIP_TEST
37from check import cbv_modulate_test 37from check import cbv_modulate_test
38from check import HEAP_INIT_EXPECTED, heap_init_env # cs_heap_init: vk_compute_test's VKC_HEAP_INIT 38from check import HEAP_INIT_EXPECTED, heap_init_env # cs_heap_init: vk_compute_test's VKC_HEAP_INIT
39from check import shift64_test # dynamic 64-bit vector shifts and overlapping destinations
39from check import judged_words, words_match # dump words not judged on some devices (cs_signed_zero_nan) 40from check import judged_words, words_match # dump words not judged on some devices (cs_signed_zero_nan)
40from check import TEXOFF_ARGS, texoff_problem # ps_texoff's expected words and arguments live in check.py 41from check import TEXOFF_ARGS, texoff_problem # ps_texoff's expected words and arguments live in check.py
41from check import TEXOFF_FALLBACK, texoff_env # LEONIDA_TEXOFF_FALLBACK=1: texel offsets without maintenance8 42from check import TEXOFF_FALLBACK, texoff_env # LEONIDA_TEXOFF_FALLBACK=1: texel offsets without maintenance8
@@ -149,8 +150,13 @@ def spirv_as(asm_text: str, out_spv: str, assembler: str = "spirv-as") -> None:
149 with open(out_spv, "wb") as f: 150 with open(out_spv, "wb") as f:
150 f.write(spv_bytes) 151 f.write(spv_bytes)
151 return 152 return
152 p = subprocess.run(["spirv-as", "--target-env", "vulkan1.2", "-o", out_spv, "-"], 153 try:
153 input=asm_text, capture_output=True, text=True) 154 p = subprocess.run(["spirv-as", "--target-env", "vulkan1.2", "-o", out_spv, "-"],
155 input=asm_text, capture_output=True, text=True)
156 except FileNotFoundError:
157 raise RuntimeError("spirv-as not found on PATH (use --assembler python to assemble with tools/spirv_asm.py)") from None
158 except OSError as exc:
159 raise RuntimeError(f"spirv-as could not be started: {exc.strerror or exc}") from None
154 if p.returncode != 0: 160 if p.returncode != 0:
155 raise RuntimeError(f"spirv-as failed for {out_spv}:\n{p.stderr}") 161 raise RuntimeError(f"spirv-as failed for {out_spv}:\n{p.stderr}")
156 162
@@ -258,6 +264,8 @@ def read_raw_u32(path: str) -> list[tuple[int, int, int, int]]:
258 return [struct.unpack_from("<4I", data, 16 * i) for i in range(n)] 264 return [struct.unpack_from("<4I", data, 16 * i) for i in range(n)]
259 265
260 266
267# cs_div_fmas_f64_rt's operands a = 1 + 2^-30, c = -(1 + 2^-29) as s4..s7 (low word first).
268DIV_FMAS_F64_SGPRS = "0x00400000,0x3ff00000,0x00800000,0xbff00000"
261UNSUPPORTED = 77 # vk_harness: the device lacks a stage the test draws with (geometry or mesh shaders) 269UNSUPPORTED = 77 # vk_harness: the device lacks a stage the test draws with (geometry or mesh shaders)
262 270
263 271
@@ -975,6 +983,10 @@ def run_suite(a, work: str) -> int:
975 if name in CLIP_CASES: 983 if name in CLIP_CASES:
976 detail = clip_test(a.build, spirv_dir, name) 984 detail = clip_test(a.build, spirv_dir, name)
977 results.append((name, None if isinstance(detail, Skip) else not detail, detail or "four pixel masks exact")) 985 results.append((name, None if isinstance(detail, Skip) else not detail, detail or "four pixel masks exact"))
986 elif name == "cs_w32_shift64":
987 detail = shift64_test(a.build, spirv_dir, cs_env)
988 results.append((name, None if isinstance(detail, Skip) else not detail,
989 detail or "640 words exact (64 shift cases and unchanged inputs)"))
978 elif name == "cs_workgroup_yz": 990 elif name == "cs_workgroup_yz":
979 rc, msg = run_cmd([vk_compute, spv, "2x3x4", "workgroup_yz"], env=cs_env) 991 rc, msg = run_cmd([vk_compute, spv, "2x3x4", "workgroup_yz"], env=cs_env)
980 results.append((name,) + compute_result(rc, msg, rc == 0 and "2x3x4 workgroup Y/Z: 0 mismatches" 992 results.append((name,) + compute_result(rc, msg, rc == 0 and "2x3x4 workgroup Y/Z: 0 mismatches"
@@ -1092,10 +1104,12 @@ def run_suite(a, work: str) -> int:
1092 ok, detail = judge_cs_dump(rc, msg, [0, 0x40040000], wave64=False, partial=False, emulated=False, 1104 ok, detail = judge_cs_dump(rc, msg, [0, 0x40040000], wave64=False, partial=False, emulated=False,
1093 hexwords=True) 1105 hexwords=True)
1094 results.append((name, ok, detail)) 1106 results.append((name, ok, detail))
1095 elif name == "cs_div_fmas_f64": 1107 elif name in ("cs_div_fmas_f64", "cs_div_fmas_f64_rt"):
1096 # One-rounding binary64 FMA: strict where the translator emitted OpFmaKHR on doubles (shaderFmaFloat64, 1108 # One-rounding binary64 FMA: strict where the translator emitted OpFmaKHR on doubles (shaderFmaFloat64,
1097 # --fma khr); under the default GLSL Fma the split result (0) is allowed, as cs_fma_fused allows it. 1109 # --fma khr); under the default GLSL Fma the split result (0) is allowed, as cs_fma_fused allows it.
1098 rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=cs_env) 1110 # The _rt fixture reads the same operands from s4..s7, so the driver cannot fold the Fma at compile time.
1111 env = dict(cs_env or os.environ, VKC_SGPRS=DIV_FMAS_F64_SGPRS) if name.endswith("_rt") else cs_env
1112 rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=env)
1099 if rc == UNSUPPORTED: # no shaderFloat64, or (--fma khr) no shaderFmaFloat64 1113 if rc == UNSUPPORTED: # no shaderFloat64, or (--fma khr) no shaderFmaFloat64
1100 results.append((name, None, unsupported_skip(msg))) 1114 results.append((name, None, unsupported_skip(msg)))
1101 else: 1115 else:
@@ -1105,7 +1119,8 @@ def run_suite(a, work: str) -> int:
1105 ok = rc == 0 and (words == fused or (not strict and words == split)) 1119 ok = rc == 0 and (words == fused or (not strict and words == split))
1106 detail = " ".join(hex(x) for x in words) if words else msg 1120 detail = " ".join(hex(x) for x in words) if words else msg
1107 if ok and words == split: 1121 if ok and words == split:
1108 detail += " (split: the driver rounds GLSL Fma on doubles twice; --fma khr fixes it)" 1122 detail += (" (split: the driver rounded GLSL Fma on doubles twice%s; --fma khr fixes it)"
1123 % ("" if name.endswith("_rt") else " when folding the constants"))
1109 results.append((name, ok, detail)) 1124 results.append((name, ok, detail))
1110 elif name == "cs_cvt_f32_sat": 1125 elif name == "cs_cvt_f32_sat":
1111 # #300's saturating float -> int conversions: one dispatch per input word in s4 (VKC_SGPRS). 1126 # #300's saturating float -> int conversions: one dispatch per input word in s4 (VKC_SGPRS).
@@ -1320,6 +1335,9 @@ def run_suite(a, work: str) -> int:
1320 elif name == "cs_imgstore": 1335 elif name == "cs_imgstore":
1321 rc, msg = run_cmd([vk_store, spv]) 1336 rc, msg = run_cmd([vk_store, spv])
1322 results.append((name, *helper_result(rc, msg))) 1337 results.append((name, *helper_result(rc, msg)))
1338 elif name == "cs_imgstore_cube": # GPU-CUBE-STORE: six-layer 2D-array views at bindings 11/12/13
1339 rc, msg = run_cmd([vk_store, spv, "cube"])
1340 results.append((name, *helper_result(rc, msg)))
1323 elif name in ("cs_imgload", "cs_imgload_tfe", "cs_imgload_d16", "cs_imgload_d16_tfe", "cs_sample_lz_int_d16"): 1341 elif name in ("cs_imgload", "cs_imgload_tfe", "cs_imgload_d16", "cs_imgload_d16_tfe", "cs_sample_lz_int_d16"):
1324 rc, msg = run_cmd([vk_store, spv, "load" if name in ("cs_imgload", "cs_imgload_tfe") else "load-d16"]) 1342 rc, msg = run_cmd([vk_store, spv, "load" if name in ("cs_imgload", "cs_imgload_tfe") else "load-d16"])
1325 results.append((name, *helper_result(rc, msg))) 1343 results.append((name, *helper_result(rc, msg)))
diff --git a/scripts/run_semantic_tests.py b/scripts/run_semantic_tests.py
index c364bb35d..03e0ddab4 100644
--- a/scripts/run_semantic_tests.py
+++ b/scripts/run_semantic_tests.py
@@ -12,12 +12,14 @@ the pattern matches their basenames, not directory paths. Package `__init__.py`
12because discover imports them and runs any TestCase they define regardless of the pattern. No matching files is an 12because discover imports them and runs any TestCase they define regardless of the pattern. No matching files is an
13error in serial and parallel runs. 13error in serial and parallel runs.
14 14
15It runs the files `python -m unittest discover -s tests/semantic` finds (`test*.py` by default, and packages below it), each as 15It runs the files `python -m unittest discover -s tests/semantic` finds (`test*.py` by default, and packages below it), each in its own process from that folder, so a file sees the same import path as under discover.
16`python -m unittest <module>` from that folder, so a file sees the same import path as under discover. The files can 16
17run side by side because each one writes only into its own temporary folder; a new test must do the same. With -j 1, 17The files can run side by side because each one writes only into its own temporary folder; a new test must do the same. With -j 1,
18or on a single core, it runs that discover command itself. Prints the output of every failing file and one summary 18or on a single core, it runs that discover command itself. Prints the output of every failing file and one summary
19line, and exits 1 if a file fails, none is found, or no test ran. Standard library only. 19line, and exits 1 if a file fails, none is found, or no test ran. Standard library only.
20 20
21The count of tests comes from unittest's own result object, not from its output: a module that writes a line shaped like unittest's summary to stderr - a nested runner, or an atexit handler that runs after unittest's own summary - cannot change it.
22
21`--timeout SECONDS` limits each module subprocess in parallel mode, or the entire discover subprocess with 23`--timeout SECONDS` limits each module subprocess in parallel mode, or the entire discover subprocess with
22`-j 1`. The value must be positive and at most 86400 seconds (24 hours), keeping it within platform wait limits. 24`-j 1`. The value must be positive and at most 86400 seconds (24 hours), keeping it within platform wait limits.
23A timeout fails the run and reports any output already produced; other parallel modules keep running. 25A timeout fails the run and reports any output already produced; other parallel modules keep running.
@@ -26,16 +28,34 @@ The default has no time limit. This stops the direct test subprocess, not any de
26import argparse 28import argparse
27import concurrent.futures 29import concurrent.futures
28import fnmatch 30import fnmatch
31import json
29import locale 32import locale
30import math 33import math
31import os 34import os
32import re 35import re
33import subprocess 36import subprocess
34import sys 37import sys
38import tempfile
35import time 39import time
36 40
37MAX_TIMEOUT_SECONDS = 24 * 60 * 60 41MAX_TIMEOUT_SECONDS = 24 * 60 * 60
38 42
43# The child runs the module through unittest's own program and writes the result to a file, so the count of tests
44# comes from the result object and nothing the module writes can change it. The exit codes are unittest's own: 1
45# when a test failed, 5 when nothing ran at all, 0 otherwise. The module is left unset, as `python -m unittest` leaves it, so
46# the name is imported and not looked up as an attribute of the program itself.
47CHILD_PROGRAM = (
48 "import json, os, sys, unittest\n"
49 "program = unittest.TestProgram(module=None, argv=['unittest'] + sys.argv[1:], exit=False)\n"
50 "result = program.result\n"
51 "with open(os.environ['LEONIDA_TEST_COUNT'], 'w', encoding='utf-8') as handle:\n"
52 " json.dump({'testsRun': result.testsRun}, handle)\n"
53 "if not result.wasSuccessful():\n"
54 " sys.exit(1)\n"
55 "elif result.testsRun == 0 and len(result.skipped) == 0:\n"
56 " sys.exit(5)\n"
57 "sys.exit(0)\n")
58
39 59
40def module_path(directory, module): 60def module_path(directory, module):
41 """Source path of a dotted module name, including a package's `__init__.py`.""" 61 """Source path of a dotted module name, including a package's `__init__.py`."""
@@ -73,28 +93,42 @@ def positive_seconds(value):
73 return seconds 93 return seconds
74 94
75 95
96def read_count(path):
97 """The number of tests the child ran, as unittest's own result object reported it."""
98 try:
99 with open(path, encoding="utf-8") as handle:
100 return int(json.load(handle)["testsRun"])
101 except (OSError, ValueError, KeyError, TypeError):
102 # The child wrote no result: it did not finish, so no test is known to have run.
103 return 0
104
105
76def run_module(directory, module, verbose, timeout=None): 106def run_module(directory, module, verbose, timeout=None):
77 """(return code, tests run, output) of `python -m unittest <target>` run from `directory`.""" 107 """(return code, tests run, output) of `python -m unittest <target>` run from `directory`."""
78 # `python -m unittest pkg.__init__` imports pkg and then runs the same file again as pkg.__init__, so a 108 # `python -m unittest pkg.__init__` imports pkg and then runs the same file again as pkg.__init__, so a
79 # registration in the initializer happens twice. Running the package itself imports it once; module_path() is 109 # registration in the initializer happens twice. Running the package itself imports it once; module_path() is
80 # still the initializer's path, so the jobs stay sorted by the file they run. 110 # still the initializer's path, so the jobs stay sorted by the file they run.
81 target = module[:-len(".__init__")] if module.endswith(".__init__") else module 111 target = module[:-len(".__init__")] if module.endswith(".__init__") else module
82 cmd = [sys.executable, "-m", "unittest", *(["-v"] if verbose else []), target] 112 cmd = [sys.executable, "-c", CHILD_PROGRAM, *(["-v"] if verbose else []), target]
83 try: 113 with tempfile.TemporaryDirectory() as scratch:
84 p = subprocess.run(cmd, cwd=directory, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, 114 count_path = os.path.join(scratch, "count.json")
85 errors="replace", timeout=timeout) 115 env = dict(os.environ, LEONIDA_TEST_COUNT=count_path)
86 except subprocess.TimeoutExpired as exc: 116 try:
87 out = exc.stdout or "" 117 p = subprocess.run(cmd, cwd=directory, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
88 if isinstance(out, bytes): # TimeoutExpired retains bytes even when text=True. 118 text=True, errors="replace", timeout=timeout)
89 out = out.decode(locale.getpreferredencoding(False), errors="replace") 119 except subprocess.TimeoutExpired as exc:
90 return 1, 0, out + f"\nTIMED OUT after {timeout:g} s: {module}\n" 120 # TimeoutExpired retains bytes even when text=True.
91 ran = re.search(r"^Ran (\d+) tests? in", p.stdout, re.M) 121 parts = [chunk.decode(locale.getpreferredencoding(False), errors="replace") if isinstance(chunk, bytes)
92 count = int(ran.group(1)) if ran else 0 122 else chunk for chunk in (exc.stdout, exc.stderr) if chunk]
123 out = "".join(parts)
124 return 1, 0, out + f"\nTIMED OUT after {timeout:g} s: {module}\n"
125 count = read_count(count_path)
126 out = p.stdout + p.stderr
93 # Discover imports every package initializer, but an empty one has no tests to run. It is included in the 127 # Discover imports every package initializer, but an empty one has no tests to run. It is included in the
94 # module list so parallel runs see TestCase classes when there are any; without them, it is not a failure. 128 # module list so parallel runs see TestCase classes when there are any; without them, it is not a failure.
95 if p.returncode == 5 and count == 0 and module.endswith(".__init__") and "NO TESTS RAN" in p.stdout: 129 if p.returncode == 5 and count == 0 and module.endswith(".__init__") and "NO TESTS RAN" in p.stderr:
96 return 0, 0, p.stdout 130 return 0, 0, out
97 return p.returncode, count, p.stdout 131 return p.returncode, count, out
98 132
99 133
100def main(argv=None): 134def main(argv=None):
diff --git a/tests/semantic/README.md b/tests/semantic/README.md
index 2d8cf529a..c355e60c1 100644
--- a/tests/semantic/README.md
+++ b/tests/semantic/README.md
@@ -3,7 +3,7 @@
3Standard library only; no GPU, no LLVM, no SPIRV-Tools, no game files. 3Standard library only; no GPU, no LLVM, no SPIRV-Tools, no game files.
4 4
5```sh 5```sh
6python -I scripts/run_semantic_tests.py tests/semantic # one file per core: 26 s instead of 253 s on 16 cores 6python -I scripts/run_semantic_tests.py tests/semantic # one file per core: 297 s instead of 2 401 s on 16 cores (Windows 11)
7python -m unittest discover -s tests/semantic -v # the same tests, one file after another 7python -m unittest discover -s tests/semantic -v # the same tests, one file after another
8python -I scripts/run_semantic_tests.py tests/semantic -j 4 -p 'test_image_*.py' # a matching subset 8python -I scripts/run_semantic_tests.py tests/semantic -j 4 -p 'test_image_*.py' # a matching subset
9``` 9```
diff --git a/tests/semantic/f16_unary_cases.py b/tests/semantic/f16_unary_cases.py
index 361563ece..a24b2b7c0 100644
--- a/tests/semantic/f16_unary_cases.py
+++ b/tests/semantic/f16_unary_cases.py
@@ -162,15 +162,15 @@ class UnaryF16:
162 def test_output_modifiers_and_clamp(self): 162 def test_output_modifiers_and_clamp(self):
163 for a in self.MOD_INPUTS: 163 for a in self.MOD_INPUTS:
164 base = self.ref(a) 164 base = self.ref(a)
165 # `clamp` of a NaN result is not modelled (the translator emits FClamp; docs/design.md, float min/max/med3 with 165 # `clamp` of a NaN result gives +0 (DX10_CLAMP 1 in the game's MODE; Gen.clamp_mods selects +0 for a NaN
166 # NaN), so a NaN result is only checked with the output multipliers. 166 # before FClamp, docs/design.md, float min/max/med3 with NaN).
167 # #4542, measured on gfx1036: an f16 destination ignores omod (mul:2/mul:4/div:2) under the game's MODE 167 # #4542, measured on gfx1036: an f16 destination ignores omod (mul:2/mul:4/div:2) under the game's MODE
168 # (IEEE=0, f16 denormals kept) and keeps clamp (docs/design.md, f16 output modifiers). 168 # (IEEE=0, f16 denormals kept) and keeps clamp (docs/design.md, f16 output modifiers).
169 for suffix, want in ((" mul:2", base), (" mul:4", base), 169 for suffix, want in ((" mul:2", base), (" mul:4", base),
170 (" div:2", base), (" clamp", clamp01(base)), 170 (" div:2", base), (" clamp", clamp01(base)),
171 (" mul:2 clamp", clamp01(base))): 171 (" mul:2 clamp", clamp01(base))):
172 if is_nan(base) and "clamp" in suffix: 172 if is_nan(base) and "clamp" in suffix:
173 continue 173 want = 0
174 with self.subTest(a=hex(a), mod=suffix): 174 with self.subTest(a=hex(a), mod=suffix):
175 got = run(self.line("_e64") + suffix, {"v1": a}) 175 got = run(self.line("_e64") + suffix, {"v1": a})
176 self.assertEqual(got >> 16, OLD >> 16) 176 self.assertEqual(got >> 16, OLD >> 16)
diff --git a/tests/semantic/f64_translate.py b/tests/semantic/f64_translate.py
new file mode 100644
index 000000000..a7a4dd66d
--- /dev/null
+++ b/tests/semantic/f64_translate.py
@@ -0,0 +1,43 @@
1"""Translate one f64 VALU instruction with tools/rdna2spirv.py and run it in tests/spirv_interp.py.
2
3The translator side of the test_valu_{rcp,rsq,sqrt}_f64.py and test_valu_cvt_f32_f64.py oracle files: each of them
4checks the word the translated instruction leaves against its own oracle. The source pair is v[2:3]; the result is
5v[4:5] (or v4 for a 32-bit result), which starts as 0xdeadbeef so a missing write shows. Standard library only; no
6game data, no GPU.
7"""
8import os
9import struct
10import sys
11
12HERE = os.path.dirname(os.path.abspath(__file__))
13TESTS_DIR = os.path.dirname(HERE)
14for p in (HERE, TESTS_DIR):
15 if p not in sys.path:
16 sys.path.insert(0, p)
17
18import spirv_interp # noqa: E402
19from support import translate_lines # noqa: E402 (support puts tools/ on sys.path)
20
21MASK32 = 0xFFFFFFFF
22
23
24def f64_bits(x):
25 """The binary64 word of a Python float."""
26 return struct.unpack("<Q", struct.pack("<d", x))[0]
27
28
29def run_f64(op, src_bits, *, src="v[2:3]", mods="", wide=True):
30 """Run `op v[4:5], <src><mods>` (`op v4, ...` when not `wide`) with v[2:3] = src_bits; return the result word."""
31 dst = "v[4:5]" if wide else "v4"
32 spv = translate_lines("ps_f64_oracle", [
33 f"v_mov_b32 v2, {src_bits & MASK32:#x}",
34 f"v_mov_b32 v3, {(src_bits >> 32) & MASK32:#x}",
35 "v_mov_b32 v4, 0xdeadbeef",
36 "v_mov_b32 v5, 0xdeadbeef",
37 f"{op} {dst}, {src}{mods}",
38 "exp mrt0 v4, v5, v4, v5 done vm",
39 "s_endpgm",
40 ])
41 state = spirv_interp.run(spv)
42 lo, hi = state.vgpr[4] & MASK32, state.vgpr[5] & MASK32
43 return (hi << 32) | lo if wide else lo
diff --git a/tests/semantic/fixtures/disasm/cs_w32_lds_subdword.s b/tests/semantic/fixtures/disasm/cs_w32_lds_subdword.s
index 23d0c5440..e8c19ea86 100644
--- a/tests/semantic/fixtures/disasm/cs_w32_lds_subdword.s
+++ b/tests/semantic/fixtures/disasm/cs_w32_lds_subdword.s
@@ -1,16 +1,19 @@
1; cs_w32_lds_subdword test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/cs_w32_lds_subdword.asm 1; cs_w32_lds_subdword test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/cs_w32_lds_subdword.asm
2 v_cmpx_eq_u32_e32 0, v0
2 v_mov_b32_e32 v2, 0 3 v_mov_b32_e32 v2, 0
3 v_mov_b32_e32 v4, 0x11223344 4 v_mov_b32_e32 v4, 0x11223344
4 v_mov_b32_e32 v5, 0x55667788 5 v_mov_b32_e32 v5, 0x55667788
5 ds_write_b32 v2, v4 6 ds_write_b32 v2, v4
6 ds_write_b32 v2, v5 offset:4 7 ds_write_b32 v2, v5 offset:4
7 s_waitcnt lgkmcnt(0) 8 s_waitcnt lgkmcnt(0)
9 s_barrier
8 v_mov_b32_e32 v3, 0xa1b2c3d4 10 v_mov_b32_e32 v3, 0xa1b2c3d4
9 ds_write_b8 v2, v3 offset:1 11 ds_write_b8 v2, v3 offset:1
10 ds_write_b8_d16_hi v2, v3 offset:2 12 ds_write_b8_d16_hi v2, v3 offset:2
11 ds_write_b16 v2, v3 offset:4 13 ds_write_b16 v2, v3 offset:4
12 ds_write_b16_d16_hi v2, v3 offset:6 14 ds_write_b16_d16_hi v2, v3 offset:6
13 s_waitcnt lgkmcnt(0) 15 s_waitcnt lgkmcnt(0)
16 s_barrier
14 ds_read_b32 v10, v2 17 ds_read_b32 v10, v2
15 ds_read_b32 v11, v2 offset:4 18 ds_read_b32 v11, v2 offset:4
16 ds_read_i8 v12, v2 offset:2 19 ds_read_i8 v12, v2 offset:2
@@ -20,7 +23,6 @@
20 ds_read_u16 v16, v2 offset:6 23 ds_read_u16 v16, v2 offset:6
21 ds_read_i16 v17, v2 offset:4 24 ds_read_i16 v17, v2 offset:4
22 s_waitcnt lgkmcnt(0) 25 s_waitcnt lgkmcnt(0)
23 v_cmpx_eq_u32_e32 0, v0
24 v_mov_b32_e32 v21, 0 26 v_mov_b32_e32 v21, 0
25 buffer_store_dword v10, v21, s[0:3], 0 offen 27 buffer_store_dword v10, v21, s[0:3], 0 offen
26 v_mov_b32_e32 v21, 4 28 v_mov_b32_e32 v21, 4
diff --git a/tests/semantic/spirv_mini_interp.py b/tests/semantic/spirv_mini_interp.py
index 015be2038..8932a2448 100644
--- a/tests/semantic/spirv_mini_interp.py
+++ b/tests/semantic/spirv_mini_interp.py
@@ -134,6 +134,25 @@ def ieee_nan(r, *operands):
134 return r 134 return r
135 135
136 136
137def rsqrt_f64(x):
138 """1 / sqrt(x) for a finite binary64 x > 0, rounded once to nearest even (the result is always normal).
139
140 1.0 / math.sqrt(x) rounds the root and then the quotient, which can miss by one ulp. Here n = floor(r * 2^p),
141 with p chosen so n has about 64 bits, comes from an integer square root of the exact rational 4^p / x; the
142 remainder decides the rounding of n down to 53 bits."""
143 f = Fraction(x)
144 p = 64 - math.frexp(1.0 / math.sqrt(x))[1]
145 scaled = Fraction(4) ** p / f # (r * 2^p)^2, exactly
146 n = math.isqrt(scaled.numerator // scaled.denominator)
147 inexact = n * n != scaled
148 shift = n.bit_length() - 53
149 q, rem = divmod(n, 1 << shift)
150 half = 1 << (shift - 1)
151 if rem > half or (rem == half and (inexact or q & 1)):
152 q += 1
153 return math.ldexp(q, shift - p)
154
155
137class _F32(float): 156class _F32(float):
138 """A binary32 value that came from a bit pattern (OpBitcast) and still carries that exact pattern. 157 """A binary32 value that came from a bit pattern (OpBitcast) and still carries that exact pattern.
139 158
@@ -1088,9 +1107,15 @@ def _invocation(text, inputs, push_constants, memory, step=False, workgroup=None
1088 elif op in ("OpFAdd", "OpFSub", "OpFMul", "OpFDiv"): 1107 elif op in ("OpFAdd", "OpFSub", "OpFMul", "OpFDiv"):
1089 x, y = val(a[1]), val(a[2]) 1108 x, y = val(a[1]), val(a[2])
1090 if types.t[a[0]] == ("float", 64): 1109 if types.t[a[0]] == ("float", 64):
1091 if op != "OpFMul": 1110 # Python floats are binary64 with round to nearest even: the result needs no rounding of its own.
1092 raise UnsupportedConstruct(f"{op} on binary64") 1111 if op == "OpFMul":
1093 values[res] = x * y 1112 values[res] = x * y
1113 elif op == "OpFDiv" and y == 0.0:
1114 raise UnsupportedConstruct("OpFDiv by zero (undefined in SPIR-V)") # as for binary32
1115 else:
1116 r = x + y if op == "OpFAdd" else x - y if op == "OpFSub" else (
1117 math.nan if math.isinf(x) and math.isinf(y) else x / y)
1118 values[res] = ieee_nan(r, x, y)
1094 continue 1119 continue
1095 1120
1096 def _fdiv(p, q): 1121 def _fdiv(p, q):
@@ -1260,6 +1285,10 @@ def _invocation(text, inputs, push_constants, memory, step=False, workgroup=None
1260 values[res] = {"Log2": math.inf, "Sqrt": math.inf, "InverseSqrt": 0.0}[name] 1285 values[res] = {"Log2": math.inf, "Sqrt": math.inf, "InverseSqrt": 0.0}[name]
1261 elif name == "Log2": 1286 elif name == "Log2":
1262 values[res] = f32(math.log2(x)) 1287 values[res] = f32(math.log2(x))
1288 elif types.t[a[0]] == ("float", 64):
1289 # A double result stays binary64: math.sqrt is correctly rounded, and 1.0 / math.sqrt(x)
1290 # would round twice, so the inverse root is rounded once from the exact value.
1291 values[res] = math.sqrt(x) if name == "Sqrt" else rsqrt_f64(x)
1263 elif name == "Sqrt": 1292 elif name == "Sqrt":
1264 values[res] = f32(math.sqrt(x)) # sqrt(-0.0) is -0.0 1293 values[res] = f32(math.sqrt(x)) # sqrt(-0.0) is -0.0
1265 else: 1294 else:
diff --git a/tests/semantic/test_alu_div_fixup_f32.py b/tests/semantic/test_alu_div_fixup_f32.py
index ac17022a2..4029eeac5 100644
--- a/tests/semantic/test_alu_div_fixup_f32.py
+++ b/tests/semantic/test_alu_div_fixup_f32.py
@@ -155,6 +155,39 @@ class TestDivFixupF32(unittest.TestCase):
155 with self.subTest(insn=insn, s0=hex(s0), s1=hex(s1), s2=hex(s2)): 155 with self.subTest(insn=insn, s0=hex(s0), s1=hex(s1), s2=hex(s2)):
156 self.assertEqual(got, want) 156 self.assertEqual(got, want)
157 157
158 def test_neg_of_negative_operand(self):
159 # VOP3 neg flips the sign bit before classification (section 9), so -x of a negative x must give exactly
160 # the word MEASURED holds for the unmodified row with +x. The rows in section 9 negate only positive
161 # inputs, where an OR with the sign bit gives the same word as the flip; these negate negative ones.
162 # (insn, S0, S1, S2, the unmodified MEASURED row whose word they must reproduce)
163 rows = [
164 ("v_div_fixup_f32 v4, v1, -v2, v3", 0xBF400000, 0xC0000000, 0x40400000,
165 (0xBF400000, 0x40000000, 0x40400000)), # -(-2.0) denominator: 0.75, not -0.75
166 ("v_div_fixup_f32 v4, v1, v2, -v3", 0xBF400000, 0x40000000, 0xC0400000,
167 (0xBF400000, 0x40000000, 0x40400000)), # -(-3.0) numerator: 0.75, not -0.75
168 ("v_div_fixup_f32 v4, v1, -v2, v3", 0x3F800000, 0xFFC00011, 0x3F800000,
169 (0x3F800000, 0x7FC00011, 0x3F800000)), # NaN S1 keeps the flipped sign
170 ("v_div_fixup_f32 v4, v1, v2, -v3", 0x3F800000, 0x3F800000, 0xFFC00022,
171 (0x3F800000, 0x3F800000, 0x7FC00022)), # NaN S2 keeps the flipped sign
172 ]
173 plain = "v_div_fixup_f32 v4, v1, v2, v3"
174 measured = {(s0, s1, s2): want for insn, s0, s1, s2, want in MEASURED if insn == plain}
175 body = []
176 for k, (insn, s0, s1, s2, base) in enumerate(rows):
177 self.assertIn(base, measured)
178 body += [
179 f"v_mov_b32 v1, {s0:#x}",
180 f"v_mov_b32 v2, {s1:#x}",
181 f"v_mov_b32 v3, {s2:#x}",
182 "v_mov_b32 v4, 0xdeadbeef",
183 insn,
184 f"buffer_store_dword v4, off, s[0:3], 0 offset:{4 * k}",
185 ]
186 _, words = _run_body(body, len(rows))
187 for (insn, s0, s1, s2, base), got in zip(rows, words):
188 with self.subTest(insn=insn, s0=hex(s0), s1=hex(s1), s2=hex(s2)):
189 self.assertEqual(got, measured[base])
190
158 def test_operand_forms_and_e64(self): 191 def test_operand_forms_and_e64(self):
159 body = [ 192 body = [
160 # SGPR S0, inline float S1/S2, _e64 spelling 193 # SGPR S0, inline float S1/S2, _e64 spelling
diff --git a/tests/semantic/test_alu_f32_min_max.py b/tests/semantic/test_alu_f32_min_max.py
index 123d92fae..af8ed533b 100644
--- a/tests/semantic/test_alu_f32_min_max.py
+++ b/tests/semantic/test_alu_f32_min_max.py
@@ -808,10 +808,11 @@ class TestNegativeControls(unittest.TestCase):
808 # The reference oracle correctly returns 2.0. 808 # The reference oracle correctly returns 2.0.
809 self.assertEqual(ref_min_f32(QNAN, TWO), TWO) 809 self.assertEqual(ref_min_f32(QNAN, TWO), TWO)
810 810
811 def test_clamp_on_all_nan_raises_unsupported(self) -> None: 811 def test_clamp_on_all_nan_gives_plus_zero(self) -> None:
812 # Clamping an all-NaN result is undefined in GLSL.std.450 / SPIR-V and raises UnsupportedConstruct. 812 # The all-NaN result is a NaN; the clamp bit turns it into +0 under the game's DX10_CLAMP 1
813 with self.assertRaises(si.UnsupportedConstruct): 813 # (docs/shader_validation.md), selected before FClamp, which is undefined for a NaN operand.
814 run_f32_2op("v_min_f32", QNAN, QNAN, e64=True, clamp=True) 814 self.assertEqual(run_f32_2op("v_min_f32", QNAN, QNAN, e64=True, clamp=True), POS_ZERO)
815 self.assertEqual(run_f32_2op("v_max_f32", NEG_QNAN, SNAN, e64=True, clamp=True), POS_ZERO)
815 816
816 def test_med3_third_operand_nan_is_min3(self) -> None: 817 def test_med3_third_operand_nan_is_min3(self) -> None:
817 # Since #2029 a NaN operand gives min3 of the operands (measured on gfx1030), not an eager FClamp on NaN. 818 # Since #2029 a NaN operand gives min3 of the operands (measured on gfx1030), not an eager FClamp on NaN.
diff --git a/tests/semantic/test_alu_min3_max3.py b/tests/semantic/test_alu_min3_max3.py
index ec7bd3ce7..fe774fb9b 100644
--- a/tests/semantic/test_alu_min3_max3.py
+++ b/tests/semantic/test_alu_min3_max3.py
@@ -17,8 +17,9 @@ Float min/max and IEEE 754 / RDNA2 semantics:
17- Signed zeros are ordered with -0.0 below +0.0 (the hardware order measured on AMD RDNA2, 17- Signed zeros are ordered with -0.0 below +0.0 (the hardware order measured on AMD RDNA2,
18 docs/design.md): min(+0.0, -0.0) = -0.0 and max(+0.0, -0.0) = +0.0 in either operand order. 18 docs/design.md): min(+0.0, -0.0) = -0.0 and max(+0.0, -0.0) = +0.0 in either operand order.
19- VOP3 input modifiers: absolute value (|src|), negation (-src), and neg-abs (-|src|). 19- VOP3 input modifiers: absolute value (|src|), negation (-src), and neg-abs (-|src|).
20- VOP3 output modifier: clamp to [0.0, 1.0]. If all operands are NaN, clamp raises 20- VOP3 output modifier: clamp to [0.0, 1.0]. If all operands are NaN, the NaN result clamps to +0
21 UnsupportedConstruct because GLSL.std.450 FClamp on NaN is undefined. 21 (DX10_CLAMP 1 in the game's MODE; the translator selects +0 before GLSL.std.450 FClamp, which is
22 undefined for a NaN operand).
22 23
23Integer min/max: 24Integer min/max:
24- v_min3_i32 and v_max3_i32 evaluate operands as signed 32-bit integers in two's complement. 25- v_min3_i32 and v_max3_i32 evaluate operands as signed 32-bit integers in two's complement.
@@ -142,7 +143,7 @@ def ref_float(op: str, a: float, b: float, c: float, *, clamp: bool = False) ->
142 r = ref_nmin_nmax(fn, ref_nmin_nmax(fn, a, b), c) 143 r = ref_nmin_nmax(fn, ref_nmin_nmax(fn, a, b), c)
143 if clamp: 144 if clamp:
144 if math.isnan(r): 145 if math.isnan(r):
145 raise si.UnsupportedConstruct("clamp on NaN is undefined") 146 return 0.0 # DX10_CLAMP 1: the clamp bit turns a NaN into +0
146 r = max(0.0, min(1.0, r)) 147 r = max(0.0, min(1.0, r))
147 return r 148 return r
148 149
@@ -330,8 +331,7 @@ class FloatNanSkippingTests(unittest.TestCase):
330 """GLSL.std.450 NMin and NMax implement IEEE 754-2008 NaN-skipping: 331 """GLSL.std.450 NMin and NMax implement IEEE 754-2008 NaN-skipping:
331 - If one or two operands are NaN, the non-NaN operand is chosen. 332 - If one or two operands are NaN, the non-NaN operand is chosen.
332 - If all three operands are NaN, NaN is returned. 333 - If all three operands are NaN, NaN is returned.
333 - If clamp modifier is specified on all-NaN, UnsupportedConstruct is raised because 334 - If clamp modifier is specified on all-NaN, the result is +0 (DX10_CLAMP 1).
334 FClamp on NaN is undefined.
335 """ 335 """
336 336
337 def test_single_nan_operand_skipped(self) -> None: 337 def test_single_nan_operand_skipped(self) -> None:
@@ -370,11 +370,10 @@ class FloatNanSkippingTests(unittest.TestCase):
370 res = run_alu(op, QNAN_BITS, SNAN_BITS, NEG_QNAN_BITS) 370 res = run_alu(op, QNAN_BITS, SNAN_BITS, NEG_QNAN_BITS)
371 self.assertTrue(math.isnan(u32_to_f32(res))) 371 self.assertTrue(math.isnan(u32_to_f32(res)))
372 372
373 def test_clamp_on_all_nan_rejected(self) -> None: 373 def test_clamp_on_all_nan_gives_plus_zero(self) -> None:
374 for op in FLOAT_OPS: 374 for op in FLOAT_OPS:
375 with self.subTest(op=op): 375 with self.subTest(op=op):
376 with self.assertRaises(si.UnsupportedConstruct): 376 self.assertEqual(run_alu(op, QNAN_BITS, SNAN_BITS, NEG_QNAN_BITS, clamp=True), 0)
377 run_alu(op, QNAN_BITS, SNAN_BITS, NEG_QNAN_BITS, clamp=True)
378 377
379 378
380class FloatModifiersTests(unittest.TestCase): 379class FloatModifiersTests(unittest.TestCase):
diff --git a/tests/semantic/test_alu_vop3_mods_hw.py b/tests/semantic/test_alu_vop3_mods_hw.py
index 8f680afef..4ced572ad 100644
--- a/tests/semantic/test_alu_vop3_mods_hw.py
+++ b/tests/semantic/test_alu_vop3_mods_hw.py
@@ -12,7 +12,8 @@ operand triples each. Only the form is taken from the game; every word here is s
12sample, up to three per form with distinct results. The measured cases not listed match too, except for differences 12sample, up to three per form with distinct results. The measured cases not listed match too, except for differences
13already on record: an omod turning a -0 result into +0 (docs/design.md, Output modifiers rows; #1281), f32 denormal 13already on record: an omod turning a -0 result into +0 (docs/design.md, Output modifiers rows; #1281), f32 denormal
14operands or intermediate results (SHADER-377), NaN sign/payload, 1-ulp differences in v_rcp/v_log/v_sin, and cases 14operands or intermediate results (SHADER-377), NaN sign/payload, 1-ulp differences in v_rcp/v_log/v_sin, and cases
15whose translation is undefined in SPIR-V (FClamp of a NaN, the root or log of a negative or zero). 15whose translation is undefined in SPIR-V (FClamp of a NaN, the root or log of a negative or zero). The f32/f16 clamp of a
16NaN gives +0 since 2026-11-24 (test_vop3_clamp_nan.py); those rows are not replayed here.
16""" 17"""
17import os 18import os
18import struct 19import struct
diff --git a/tests/semantic/test_fma_khr_f64.py b/tests/semantic/test_fma_khr_f64.py
index 861deb530..5b3800297 100644
--- a/tests/semantic/test_fma_khr_f64.py
+++ b/tests/semantic/test_fma_khr_f64.py
@@ -1,6 +1,7 @@
1"""--fma khr on binary64: the f64 fused multiply-adds (v_div_fmas_f64) as OpFmaKHR on doubles. 1"""--fma khr on binary64: the f64 fused multiply-adds (v_div_fmas_f64) as OpFmaKHR on doubles.
2 2
3GLSL.std.450 Fma may round twice on doubles as on floats, and NVIDIA's driver does (RTX 4090, 621.24, Windows: 3GLSL.std.450 Fma may round twice on doubles as on floats, and NVIDIA's driver does when it folds an all-constant
4Fma at pipeline compile time (run-time operands are fused) (RTX 4090, 621.24, Windows:
4runtime/test/shaders/cs_div_fmas_f64.asm gives the split 0 instead of 2^-60). Under FMA_KHR (--fma khr) the 5runtime/test/shaders/cs_div_fmas_f64.asm gives the split 0 instead of 2^-60). Under FMA_KHR (--fma khr) the
5translator emits OpFmaKHR %double, which SPV_KHR_fma defines as correctly rounded; the index then lists feature 6translator emits OpFmaKHR %double, which SPV_KHR_fma defines as correctly rounded; the index then lists feature
6shaderFmaFloat64 (VK_KHR_shader_fma) and, for a module without an f32 FMA, not shaderFmaFloat32. The default output 7shaderFmaFloat64 (VK_KHR_shader_fma) and, for a module without an f32 FMA, not shaderFmaFloat32. The default output
diff --git a/tests/semantic/test_mini_interp_f64.py b/tests/semantic/test_mini_interp_f64.py
new file mode 100644
index 000000000..60469c214
--- /dev/null
+++ b/tests/semantic/test_mini_interp_f64.py
@@ -0,0 +1,112 @@
1"""spirv_mini_interp.py runs the translator's binary64 arithmetic in binary64.
2
3Until this file, GLSL.std.450 Sqrt and InverseSqrt rounded a double result to binary32 (the translated v_sqrt_f64 of
42.0 gave 0x3ff6a09e60000000), and OpFAdd, OpFSub and OpFDiv on binary64 raised UnsupportedConstruct, so v_add_f64 and
5v_rcp_f64 could not run here. Each case translates one instruction with tools/rdna2spirv.py and checks the exported
6pair against a correctly rounded reference: Python's own binary64 operations for the sum, the quotient and the root,
7and a 60-digit decimal for the inverse root (the interpreter's rsqrt_f64 is checked against it, not against itself).
8The translator lowers these ops to correctly rounded SPIR-V (docs/design.md, the v_rcp_f64 / v_rsq_f64 / v_sqrt_f64
9and v_add_f64 rows). Standard library only; no game data, no GPU.
10"""
11import math
12import os
13import random
14import struct
15import sys
16import unittest
17from decimal import Decimal, localcontext
18
19HERE = os.path.dirname(os.path.abspath(__file__))
20sys.dont_write_bytecode = True
21sys.path.insert(0, HERE)
22
23import spirv_mini_interp as si # noqa: E402
24import support # noqa: E402
25
26MASK32 = 0xFFFFFFFF
27
28
29def bits(x):
30 return struct.unpack("<Q", struct.pack("<d", x))[0]
31
32
33def double(word):
34 return struct.unpack("<d", struct.pack("<Q", word))[0]
35
36
37def run(op, a, b=None):
38 """The word pair `op v[4:5], v[0:1][, v[2:3]]` leaves, with the binary64 operands a and b."""
39 lines = [f"v_mov_b32 v0, {bits(a) & MASK32:#x}", f"v_mov_b32 v1, {bits(a) >> 32:#x}"]
40 if b is not None:
41 lines += [f"v_mov_b32 v2, {bits(b) & MASK32:#x}", f"v_mov_b32 v3, {bits(b) >> 32:#x}"]
42 lines += [f"{op} v[4:5], v[0:1]" + (", v[2:3]" if b is not None else ""), "exp mrt0 v4, v5, v4, v5 done vm",
43 "s_endpgm"]
44 words = support.mrt0_words(support.translate_lines("ps_mini_f64", lines))
45 return (words[1] << 32) | words[0]
46
47
48def rsqrt_reference(x):
49 """1 / sqrt(x) to 60 digits, then the nearest binary64 (ties to even)."""
50 with localcontext() as ctx:
51 ctx.prec = 60
52 r = 1 / Decimal(x).sqrt()
53 y = float(r)
54 best = min((math.nextafter(y, 0.0), y, math.nextafter(y, math.inf)),
55 key=lambda c: (abs(Decimal(c) - r), bits(c) & 1))
56 return best
57
58
59FINITE = (1.0, 2.0, 3.0, 4.0, 0.25, 0.1, 7.0, 1 / 3, 1e300, 1e-300, 1.7976931348623157e308, 2.2250738585072014e-308,
60 5e-324, 2.225073858507201e-308)
61
62
63class Binary64Arithmetic(unittest.TestCase):
64 def test_sqrt_stays_binary64(self):
65 self.assertEqual(hex(run("v_sqrt_f64", 2.0)), "0x3ff6a09e667f3bcd") # was 0x3ff6a09e60000000
66 for x in FINITE + (math.inf, 0.0):
67 with self.subTest(x=x):
68 self.assertEqual(hex(run("v_sqrt_f64", x)), hex(bits(math.sqrt(x))))
69
70 def test_inverse_sqrt_is_rounded_once(self):
71 self.assertEqual(hex(run("v_rsq_f64", 2.0)), "0x3fe6a09e667f3bcd") # was 0x3fe6a09e60000000
72 self.assertEqual(run("v_rsq_f64", math.inf), 0)
73 rng = random.Random(0x72737121)
74 xs = list(FINITE) + [double(rng.randrange(1, 0x7FF0000000000000)) for _ in range(40)]
75 for x in xs:
76 with self.subTest(x=x):
77 self.assertEqual(hex(run("v_rsq_f64", x)), hex(bits(rsqrt_reference(x))))
78
79 def test_rsqrt_f64_against_the_decimal_reference(self):
80 # The helper on its own, over more inputs than the translated cases: 1.0 / math.sqrt(x) misses by an ulp
81 # on about a quarter of random doubles, which this would catch.
82 rng = random.Random(0x7273)
83 for _ in range(2000):
84 x = double(rng.randrange(1, 0x7FF0000000000000))
85 self.assertEqual(si.rsqrt_f64(x), rsqrt_reference(x), x)
86
87 def test_reciprocal_runs_in_binary64(self):
88 self.assertEqual(hex(run("v_rcp_f64", 3.0)), "0x3fd5555555555555")
89 for x in FINITE + (-3.0, -1e-300, math.inf, -math.inf):
90 with self.subTest(x=x):
91 self.assertEqual(hex(run("v_rcp_f64", x)), hex(bits(1.0 / x)))
92
93 def test_reciprocal_of_zero_stays_undefined(self):
94 # SPIR-V leaves OpFDiv by zero undefined, as for binary32: the interpreter refuses it.
95 with self.assertRaises(si.UnsupportedConstruct):
96 run("v_rcp_f64", 0.0)
97
98 def test_sum_runs_in_binary64(self):
99 cases = [(3.0, 2.0), (1.0, 2.0 ** -52), (1.0, 2.0 ** -53), (1.0 + 2.0 ** -52, 2.0 ** -53), (0.1, 0.2),
100 (1e308, 1e308), (-0.0, 0.0), (-0.0, -0.0), (5e-324, 5e-324), (math.inf, 1.0), (1e300, -1e300)]
101 for a, b in cases:
102 with self.subTest(a=a, b=b):
103 self.assertEqual(hex(run("v_add_f64", a, b)), hex(bits(a + b)))
104
105 def test_infinity_minus_infinity_is_a_nan(self):
106 word = run("v_add_f64", math.inf, -math.inf)
107 self.assertEqual(word & 0x7FF0000000000000, 0x7FF0000000000000)
108 self.assertNotEqual(word & 0x000FFFFFFFFFFFFF, 0)
109
110
111if __name__ == "__main__":
112 unittest.main()
diff --git a/tests/semantic/test_salu_scc_value.py b/tests/semantic/test_salu_scc_value.py
new file mode 100644
index 000000000..2058aa37e
--- /dev/null
+++ b/tests/semantic/test_salu_scc_value.py
@@ -0,0 +1,116 @@
1"""SCC written by SALU instructions holds exactly 0 or 1, read back as a number through `src_scc`.
2
3Most SCC checks in this suite go through `s_cselect_b32 sN, 1, 0` or `s_cbranch_scc*`, which only see SCC as
4zero / non-zero. `s_addc_u32`, `s_subb_u32` and any `src_scc` operand read it as a number, so a lowering that stored 2
5(or any other non-zero value) for "true" would pass those checks and still break a carry chain. Each case below runs
6one instruction on SGPR inputs, copies SCC with `v_mov_b32 v0, src_scc` and exports it, so the translated program
7must leave exactly the ISA's SCC (RDNA2 ISA, SOP1/SOP2/SOPC). Every instruction has a case where SCC = 1; most also
8have one where SCC = 0. The expected values are written down by hand from the ISA text in the comments.
9
10Standard library only; no GPU, no LLVM, no game files.
11"""
12import os
13import sys
14import unittest
15
16sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
17from support import mrt0_words, translate_lines # noqa: E402
18
19
20# (label, instruction, {sgpr: value}, expected SCC). 64-bit inputs are given as two s_mov_b32 writes.
21CASES = [
22 # SOP2 bitwise, 32-bit: SCC = (D != 0)
23 ("and 1", "s_and_b32 s4, s0, s1", {0: 0xF0, 1: 0x30}, 1),
24 ("and 0", "s_and_b32 s4, s0, s1", {0: 0xF0, 1: 0x0F}, 0),
25 ("or 1", "s_or_b32 s4, s0, s1", {0: 0, 1: 1}, 1),
26 ("or 0", "s_or_b32 s4, s0, s1", {0: 0, 1: 0}, 0),
27 ("xor 1", "s_xor_b32 s4, s0, s1", {0: 5, 1: 4}, 1),
28 ("xor 0", "s_xor_b32 s4, s0, s1", {0: 5, 1: 5}, 0),
29 ("andn2 1", "s_andn2_b32 s4, s0, s1", {0: 0xF, 1: 0x1}, 1), # 0xF & ~1 = 0xE
30 ("orn2 1", "s_orn2_b32 s4, s0, s1", {0: 0, 1: 0}, 1), # 0 | ~0 = ~0
31 ("orn2 0", "s_orn2_b32 s4, s0, s1", {0: 0, 1: 0xFFFFFFFF}, 0), # 0 | 0 = 0
32 ("nand 1", "s_nand_b32 s4, s0, s1", {0: 0, 1: 0}, 1),
33 ("nand 0", "s_nand_b32 s4, s0, s1", {0: 0xFFFFFFFF, 1: 0xFFFFFFFF}, 0),
34 ("nor 1", "s_nor_b32 s4, s0, s1", {0: 0, 1: 0}, 1),
35 ("xnor 1", "s_xnor_b32 s4, s0, s1", {0: 1, 1: 1}, 1), # ~(1 ^ 1) = ~0
36 # SOP1 on 32 bits: SCC = (D != 0)
37 ("not 1", "s_not_b32 s4, s0", {0: 0}, 1),
38 ("not 0", "s_not_b32 s4, s0", {0: 0xFFFFFFFF}, 0),
39 ("abs 1", "s_abs_i32 s4, s0", {0: 0xFFFFFFFB}, 1), # |-5| = 5
40 ("abs 0", "s_abs_i32 s4, s0", {0: 0}, 0),
41 ("bcnt1 1", "s_bcnt1_i32_b32 s4, s0", {0: 7}, 1), # 3 bits set
42 ("bcnt1 0", "s_bcnt1_i32_b32 s4, s0", {0: 0}, 0),
43 ("bcnt0 1", "s_bcnt0_i32_b32 s4, s0", {0: 0}, 1), # 32 zero bits
44 ("bcnt0 0", "s_bcnt0_i32_b32 s4, s0", {0: 0xFFFFFFFF}, 0),
45 # Shifts and bitfield extract: SCC = (D != 0)
46 ("lshl 1", "s_lshl_b32 s4, s0, s1", {0: 1, 1: 31}, 1),
47 ("lshl 0", "s_lshl_b32 s4, s0, s1", {0: 2, 1: 31}, 0), # the set bit is shifted out
48 ("lshr 1", "s_lshr_b32 s4, s0, s1", {0: 0x80000000, 1: 31}, 1),
49 ("lshr 0", "s_lshr_b32 s4, s0, s1", {0: 1, 1: 1}, 0),
50 ("ashr 1", "s_ashr_i32 s4, s0, s1", {0: 0x80000000, 1: 4}, 1),
51 ("ashr 0", "s_ashr_i32 s4, s0, s1", {0: 1, 1: 1}, 0),
52 ("bfe_u32 1", "s_bfe_u32 s4, s0, s1", {0: 0xFF00, 1: 0x00080008}, 1), # width 8 at offset 8: 0xFF
53 ("bfe_u32 0", "s_bfe_u32 s4, s0, s1", {0: 0xFF00, 1: 0x00080010}, 0), # width 8 at offset 16: 0
54 ("bfe_i32 1", "s_bfe_i32 s4, s0, s1", {0: 0x8000, 1: 0x00080008}, 1), # 0x80 sign-extended
55 # Min / max: SCC = (S0 < S1) for min, (S0 > S1) for max
56 ("min_u32 1", "s_min_u32 s4, s0, s1", {0: 3, 1: 5}, 1),
57 ("min_u32 0", "s_min_u32 s4, s0, s1", {0: 5, 1: 3}, 0),
58 ("max_u32 1", "s_max_u32 s4, s0, s1", {0: 5, 1: 3}, 1),
59 ("max_u32 0", "s_max_u32 s4, s0, s1", {0: 3, 1: 5}, 0),
60 ("min_i32 1", "s_min_i32 s4, s0, s1", {0: 0xFFFFFFFF, 1: 1}, 1), # -1 < 1
61 ("max_i32 1", "s_max_i32 s4, s0, s1", {0: 1, 1: 0xFFFFFFFF}, 1), # 1 > -1
62 # Absolute difference: SCC = (D != 0)
63 ("absdiff 1", "s_absdiff_i32 s4, s0, s1", {0: 3, 1: 5}, 1),
64 ("absdiff 0", "s_absdiff_i32 s4, s0, s1", {0: 4, 1: 4}, 0),
65 # Carries and overflow
66 ("add_u32 1", "s_add_u32 s4, s0, s1", {0: 0xFFFFFFFF, 1: 1}, 1), # carry out
67 ("add_u32 0", "s_add_u32 s4, s0, s1", {0: 1, 1: 1}, 0),
68 ("sub_u32 1", "s_sub_u32 s4, s0, s1", {0: 0, 1: 1}, 1), # borrow
69 ("add_i32 1", "s_add_i32 s4, s0, s1", {0: 0x7FFFFFFF, 1: 1}, 1), # signed overflow
70 ("add_i32 0", "s_add_i32 s4, s0, s1", {0: 1, 1: 1}, 0),
71 ("sub_i32 1", "s_sub_i32 s4, s0, s1", {0: 0x80000000, 1: 1}, 1), # signed overflow
72 # Compares and bit tests (SOPC)
73 ("cmp_eq 1", "s_cmp_eq_u32 s0, s1", {0: 5, 1: 5}, 1),
74 ("cmp_eq 0", "s_cmp_eq_u32 s0, s1", {0: 5, 1: 6}, 0),
75 ("cmp_lg 1", "s_cmp_lg_u32 s0, s1", {0: 5, 1: 6}, 1),
76 ("cmp_gt_i32 1", "s_cmp_gt_i32 s0, s1", {0: 1, 1: 0xFFFFFFFF}, 1), # 1 > -1
77 ("cmp_lt_u32 1", "s_cmp_lt_u32 s0, s1", {0: 1, 1: 0xFFFFFFFF}, 1),
78 ("bitcmp1 1", "s_bitcmp1_b32 s0, s1", {0: 8, 1: 3}, 1),
79 ("bitcmp1 0", "s_bitcmp1_b32 s0, s1", {0: 8, 1: 2}, 0),
80 ("bitcmp0 1", "s_bitcmp0_b32 s0, s1", {0: 8, 1: 2}, 1),
81 # 64-bit data in SGPR pairs (not lane masks): SCC = (D != 0) or the compare / bit test
82 ("and_b64 1", "s_and_b64 s[4:5], s[0:1], s[2:3]", {0: 0, 1: 1, 2: 0, 3: 1}, 1), # bit 32 in both
83 ("and_b64 0", "s_and_b64 s[4:5], s[0:1], s[2:3]", {0: 1, 1: 0, 2: 0, 3: 1}, 0),
84 ("not_b64 1", "s_not_b64 s[4:5], s[0:1]", {0: 0xFFFFFFFF, 1: 0}, 1),
85 ("lshl_b64 1", "s_lshl_b64 s[4:5], s[0:1], s2", {0: 1, 1: 0, 2: 40}, 1),
86 ("lshl_b64 0", "s_lshl_b64 s[4:5], s[0:1], s2", {0: 0, 1: 2, 2: 63}, 0),
87 ("bfe_u64 1", "s_bfe_u64 s[4:5], s[0:1], s2", {0: 0, 1: 0xF0, 2: 0x00040024}, 1), # 4 bits at offset 36
88 ("cmp_lg_u64 1", "s_cmp_lg_u64 s[0:1], s[2:3]", {0: 0, 1: 1, 2: 0, 3: 0}, 1),
89 ("cmp_eq_u64 1", "s_cmp_eq_u64 s[0:1], s[2:3]", {0: 7, 1: 1, 2: 7, 3: 1}, 1),
90 ("cmp_eq_u64 0", "s_cmp_eq_u64 s[0:1], s[2:3]", {0: 0, 1: 1, 2: 0, 3: 0}, 0),
91 ("bitcmp1_b64 1", "s_bitcmp1_b64 s[0:1], s2", {0: 0, 1: 0x100, 2: 40}, 1),
92 ("bcnt1_b64 1", "s_bcnt1_i32_b64 s4, s[0:1]", {0: 0, 1: 1}, 1),
93]
94
95
96def scc_after(instruction, sgprs):
97 lines = [f"s_mov_b32 s{r}, {v:#x}" for r, v in sorted(sgprs.items())]
98 lines += [instruction, "v_mov_b32 v0, src_scc", "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"]
99 return mrt0_words(translate_lines("ps_salu_scc_value", lines))
100
101
102class SccIsZeroOrOne(unittest.TestCase):
103 def test_every_case(self):
104 for label, instruction, sgprs, scc in CASES:
105 with self.subTest(label, instruction=instruction):
106 self.assertEqual(scc_after(instruction, sgprs), [scc] * 4)
107
108 def test_each_instruction_has_a_case_with_scc_set(self):
109 # The point is the value stored for "true": an instruction tested only with SCC = 0 proves nothing here.
110 ops = {c[1].split()[0] for c in CASES}
111 set_ops = {c[1].split()[0] for c in CASES if c[3] == 1}
112 self.assertEqual(ops - set_ops, set())
113
114
115if __name__ == "__main__":
116 unittest.main()
diff --git a/tests/semantic/test_sload_vcc_base.py b/tests/semantic/test_sload_vcc_base.py
new file mode 100644
index 000000000..9c063e3e1
--- /dev/null
+++ b/tests/semantic/test_sload_vcc_base.py
@@ -0,0 +1,171 @@
1"""Semantic tests for SMEM s_load_dword* using `vcc` (s[106:107]) as the 64-bit base pointer.
2
3RDNA2 SMEM `s_load_dword*` takes a 2-SGPR-aligned 64-bit base address in `SBASE`, which hardware encodes as
4`sbase * 2`. Register pair `s[106:107]` is `vcc` (`{vcc_lo, vcc_hi}`), emitted by the compiler when VCC is dead
5(79 pipeline-library compute shaders: 72 `s_load_dwordx4 sgpr, vcc`, 6 `s_load_dwordx8 sgpr, vcc`, and 1
6`s_load_dwordx4 [s104,s105,vcc_lo,vcc_hi], vcc`).
7
8Checks SPIR-V generation, 64-bit address construction from `%vcc`/`%vcc_hi`, destination aliasing when `vcc` is
9also written, rejection of `s_buffer_load*` with 2-dword `vcc`, and `spirv-as` + `spirv-val` when on PATH.
10"""
11import json
12import os
13import shutil
14import subprocess
15import sys
16import tempfile
17import unittest
18
19HERE = os.path.dirname(os.path.abspath(__file__))
20ROOT = os.path.dirname(os.path.dirname(HERE))
21TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")
22
23sys.dont_write_bytecode = True
24if TOOLS_DIR not in sys.path:
25 sys.path.insert(0, TOOLS_DIR)
26if HERE not in sys.path:
27 sys.path.insert(0, HERE)
28
29import rdna2spirv # noqa: E402
30from shader_ir import parse_line # noqa: E402
31import support # noqa: E402
32
33
34def _assemble_and_validate(spvasm: str) -> None:
35 spirv_as = shutil.which("spirv-as")
36 spirv_val = shutil.which("spirv-val")
37 if not (spirv_as and spirv_val):
38 return
39 with tempfile.TemporaryDirectory() as tmp:
40 asm_path = os.path.join(tmp, "s.spvasm")
41 spv_path = os.path.join(tmp, "s.spv")
42 with open(asm_path, "w", encoding="utf-8", newline="\n") as f:
43 f.write(spvasm)
44 p1 = subprocess.run([spirv_as, "--target-env", "vulkan1.3", asm_path, "-o", spv_path],
45 capture_output=True, text=True)
46 if p1.returncode != 0:
47 raise AssertionError(f"spirv-as failed:\n{p1.stderr}")
48 p2 = subprocess.run([spirv_val, "--target-env", "vulkan1.3", spv_path],
49 capture_output=True, text=True)
50 if p2.returncode != 0:
51 raise AssertionError(f"spirv-val failed:\n{p2.stderr}")
52
53
54def _translate_cs(lines: list[str]) -> str:
55 with tempfile.TemporaryDirectory() as tmp:
56 disasm_dir = os.path.join(tmp, "disasm")
57 fspx_dir = os.path.join(tmp, "fspx")
58 os.makedirs(disasm_dir)
59 os.makedirs(fspx_dir)
60 with open(os.path.join(fspx_dir, "cs_sload_vcc_base.json"), "w", encoding="utf-8", newline="\n") as f:
61 json.dump({
62 "threads": [64, 1, 1],
63 "wave32": True,
64 "user_sgprs": 8,
65 "tgid_enable": [1, 0, 0],
66 "tidig_comp_cnt": 0,
67 "lds_bytes": 0,
68 "rsrc2": 0x90,
69 }, f)
70 s_path = os.path.join(disasm_dir, "cs_sload_vcc_base.s")
71 with open(s_path, "w", encoding="utf-8", newline="\n") as f:
72 f.write("; synthetic compute shader test\n")
73 for line in lines:
74 f.write(line + "\n")
75 res = rdna2spirv.translate(s_path)
76 return res[0] if isinstance(res, tuple) else res
77
78
79class SloadVccBaseTest(unittest.TestCase):
80 def test_scalar_load_reads_vcc_lo_and_vcc_hi_for_64bit_base(self):
81 for op, dst in (
82 ("s_load_dword", "s10"),
83 ("s_load_dwordx2", "s[10:11]"),
84 ("s_load_dwordx4", "s[12:15]"),
85 ("s_load_dwordx8", "s[16:23]"),
86 ("s_load_dwordx16", "s[24:39]"),
87 ("s_load_dwordx4", "[s104,s105,vcc_lo,vcc_hi]"),
88 ):
89 with self.subTest(op=op, dst=dst):
90 g = rdna2spirv.Gen("cs")
91 ins = parse_line(f"{op} {dst}, vcc, 0x20")
92 g.scalar_load(ins["op"], ins["args"], ins["mods"])
93 body = "\n".join(g.body)
94 self.assertIn("OpLoad %uint %vcc", body)
95 self.assertIn("OpLoad %uint %vcc_hi", body)
96 self.assertTrue(g.uses_psb)
97
98 def test_s_buffer_load_with_vcc_base_is_still_rejected(self):
99 # `vcc` is a 2-dword pair, not a 4-dword V# buffer resource descriptor.
100 g = rdna2spirv.Gen("cs")
101 ins = parse_line("s_buffer_load_dword s10, vcc, 0x0")
102 with self.assertRaises(rdna2spirv.Unsupported) as ctx:
103 g.scalar_load(ins["op"], ins["args"], ins["mods"])
104 self.assertIn("s_buffer_load without V#", str(ctx.exception))
105
106 def test_full_compute_shader_with_vcc_base_validates(self):
107 spvasm = _translate_cs([
108 "\ts_mov_b32 vcc_lo, s0",
109 "\ts_mov_b32 vcc_hi, s1",
110 "\ts_load_dword s10, vcc, 0x0",
111 "\ts_load_dwordx4 s[12:15], vcc, 0x10",
112 "\ts_load_dwordx8 s[16:23], vcc, s2 offset:0x40",
113 "\ts_load_dwordx4 [s104,s105,vcc_lo,vcc_hi], vcc, 0x80",
114 "\ts_waitcnt lgkmcnt(0)",
115 "\tv_mov_b32_e32 v1, s10",
116 "\tv_add_nc_u32_e32 v1, s12, v1",
117 "\tv_add_nc_u32_e32 v1, s16, v1",
118 "\tv_add_nc_u32_e32 v1, vcc_lo, v1",
119 "\tv_add_nc_u32_e32 v1, vcc_hi, v1",
120 "\tbuffer_store_dword v1, v0, s[4:7], 0 offen",
121 "\ts_endpgm",
122 ])
123 self.assertIn("OpLoad %uint %vcc", spvasm)
124 self.assertIn("OpLoad %uint %vcc_hi", spvasm)
125 _assemble_and_validate(spvasm)
126
127 def test_vcc_base_pointer_half_order_executes(self):
128 # Pin vcc_lo as bits [31:0] and vcc_hi as bits [63:32]; swapping or dropping a half reads the wrong address.
129 spv = support.translate_lines("ps_sload_vcc_order", [
130 "s_mov_b32 vcc_hi, 0x3",
131 "s_mov_b32 vcc_lo, 0x2000",
132 "s_load_dword s10, vcc, 0x4",
133 "s_waitcnt lgkmcnt(0)",
134 "v_mov_b32 v4, s10",
135 "exp mrt0 v4, v4, v4, v4 done vm",
136 "s_endpgm",
137 ])
138 _assemble_and_validate(spv)
139 got = support.mrt0_words(spv, memory={
140 0x00000003_00002004: 0xCAFEBABE,
141 0x00002000_00000007: 0xDEADBEEF,
142 0x00000000_00002004: 0xBAD00001,
143 })
144 self.assertEqual(got, [0xCAFEBABE, 0xCAFEBABE, 0xCAFEBABE, 0xCAFEBABE])
145
146 def test_vcc_base_aliasing_destination_executes(self):
147 # Destination [s104,s105,vcc_lo,vcc_hi] aliases the `vcc` base pair; both base halves must be read first.
148 spv = support.translate_lines("ps_sload_vcc_alias", [
149 "s_mov_b32 vcc_hi, 0x2",
150 "s_mov_b32 vcc_lo, 0x4000",
151 "s_load_dwordx4 [s104,s105,vcc_lo,vcc_hi], vcc, 0x10",
152 "s_waitcnt lgkmcnt(0)",
153 "v_mov_b32 v4, s104",
154 "v_mov_b32 v5, s105",
155 "v_mov_b32 v6, vcc_lo",
156 "v_mov_b32 v7, vcc_hi",
157 "exp mrt0 v4, v5, v6, v7 done vm",
158 "s_endpgm",
159 ])
160 _assemble_and_validate(spv)
161 got = support.mrt0_words(spv, memory={
162 0x00000002_00004010: 0x11223344,
163 0x00000002_00004014: 0x55667788,
164 0x00000002_00004018: 0x99AABBCC,
165 0x00000002_0000401C: 0xDDEEFF00,
166 })
167 self.assertEqual(got, [0x11223344, 0x55667788, 0x99AABBCC, 0xDDEEFF00])
168
169
170if __name__ == "__main__":
171 unittest.main()
diff --git a/tests/semantic/test_sopc_validation.py b/tests/semantic/test_sopc_validation.py
index e18a28c76..dc156be26 100644
--- a/tests/semantic/test_sopc_validation.py
+++ b/tests/semantic/test_sopc_validation.py
@@ -67,7 +67,18 @@ def _run_insn_line(line: str) -> rdna2spirv.Gen:
67 return g 67 return g
68 68
69 69
70def _translate_and_validate_cs(name: str, asm_lines: list[str], threads: int = 64) -> str: 70def _require_or_skip_spirv_tools(test_case: unittest.TestCase) -> tuple[str, str]:
71 spirv_as = shutil.which("spirv-as")
72 spirv_val = shutil.which("spirv-val")
73 if spirv_as and spirv_val:
74 return spirv_as, spirv_val
75 msg = "spirv-as and spirv-val must be on PATH"
76 if os.environ.get("LEONIDA_REQUIRE_SPIRV_TOOLS") == "1":
77 test_case.fail(msg)
78 test_case.skipTest(msg)
79
80
81def _translate_cs(name: str, asm_lines: list[str], threads: int = 64) -> str:
71 with tempfile.TemporaryDirectory() as tmp: 82 with tempfile.TemporaryDirectory() as tmp:
72 os.mkdir(os.path.join(tmp, "disasm")) 83 os.mkdir(os.path.join(tmp, "disasm"))
73 os.mkdir(os.path.join(tmp, "fssm")) 84 os.mkdir(os.path.join(tmp, "fssm"))
@@ -84,9 +95,11 @@ def _translate_and_validate_cs(name: str, asm_lines: list[str], threads: int = 6
84 warnings.simplefilter("ignore", ResourceWarning) 95 warnings.simplefilter("ignore", ResourceWarning)
85 spv = rdna2spirv.translate(s_path) 96 spv = rdna2spirv.translate(s_path)
86 gc.collect() 97 gc.collect()
87 spirv_as = shutil.which("spirv-as") 98 return spv
88 spirv_val = shutil.which("spirv-val") 99
89 assert spirv_as and spirv_val, "spirv-as and spirv-val must be on PATH" 100
101def _validate_spirv(name: str, spv: str, spirv_as: str, spirv_val: str) -> None:
102 with tempfile.TemporaryDirectory() as tmp:
90 spvasm = os.path.join(tmp, f"{name}.spvasm") 103 spvasm = os.path.join(tmp, f"{name}.spvasm")
91 spvbin = os.path.join(tmp, f"{name}.spv") 104 spvbin = os.path.join(tmp, f"{name}.spv")
92 with open(spvasm, "w", encoding="utf-8", newline="\n") as f: 105 with open(spvasm, "w", encoding="utf-8", newline="\n") as f:
@@ -101,7 +114,6 @@ def _translate_and_validate_cs(name: str, asm_lines: list[str], threads: int = 6
101 capture_output=True, text=True, 114 capture_output=True, text=True,
102 ) 115 )
103 assert r2.returncode == 0, f"spirv-val failed:\n{r2.stderr}" 116 assert r2.returncode == 0, f"spirv-val failed:\n{r2.stderr}"
104 return spv
105 117
106 118
107def _store_scc(slot: int) -> list[str]: 119def _store_scc(slot: int) -> list[str]:
@@ -246,66 +258,71 @@ class TestSopcNegativeValidation(unittest.TestCase):
246 _run_insn_line(f"{op} s[4:5], {bad}") 258 _run_insn_line(f"{op} s[4:5], {bad}")
247 259
248 260
261def _positive_control_program() -> tuple[list[str], list[tuple[str, int]]]:
262 asm: list[str] = [
263 "s_mov_b32 m0, 0x00000005",
264 "s_mov_b32 s8, -1",
265 "s_mov_b32 s9, 0x3f800000", # 1.0f bits (bit 29 is 1, bit 30 is 0)
266 "s_mov_b32 s10, 0xbf800000", # -1.0f bits
267 "s_mov_b32 s12, 0x00000010", # bit 4 set
268 "s_mov_b32 s13, 0x00000100", # bit 40 set in s[12:13]
269 "s_mov_b32 vcc_lo, s12",
270 "s_mov_b32 vcc_hi, s13",
271 ]
272 expected: list[tuple[str, int]] = []
273
274 def add_case(label: str, insn: str, want: int):
275 slot = len(expected)
276 asm.append(insn)
277 asm.extend(_store_scc(slot))
278 expected.append((label, want))
279
280 # 12 32-bit scalar compares covering sgpr, null, m0, vcc_lo/hi, exec_lo/hi, scc/src_scc,
281 # plain negative integer immediates, positive immediates, and float immediates.
282 add_case("s_cmp_eq_i32 sgpr/neg_imm", "s_cmp_eq_i32 s8, -1", 1)
283 add_case("s_cmp_lg_i32 sgpr/neg_imm", "s_cmp_lg_i32 s8, -16", 1)
284 add_case("s_cmp_gt_i32 null/neg_imm", "s_cmp_gt_i32 null, -1", 1)
285 add_case("s_cmp_ge_i32 m0/imm", "s_cmp_ge_i32 m0, 5", 1)
286 add_case("s_cmp_lt_i32 neg_imm/null", "s_cmp_lt_i32 -1, null", 1)
287 add_case("s_cmp_le_i32 scc/imm", "s_cmp_le_i32 scc, 1", 1)
288 add_case("s_cmp_eq_u32 sgpr/fimm", "s_cmp_eq_u32 s9, 1.0", 1)
289 add_case("s_cmp_eq_u32 sgpr/neg_fimm", "s_cmp_eq_u32 s10, -1.0", 1)
290 add_case("s_cmp_lg_u32 vcc_lo/null", "s_cmp_lg_u32 vcc_lo, null", 1)
291 add_case("s_cmp_gt_u32 vcc_hi/m0", "s_cmp_gt_u32 vcc_hi, m0", 1)
292 add_case("s_cmp_ge_u32 exec_lo/exec_hi", "s_cmp_ge_u32 exec_lo, exec_hi", 1)
293 add_case("s_cmp_lt_u32 src_scc/m0", "s_cmp_lt_u32 src_scc, m0", 1)
294 add_case("s_cmp_le_u32 m0/vcc_lo", "s_cmp_le_u32 m0, vcc_lo", 1)
295
296 # 2 64-bit scalar compares covering s[a:b], vcc, exec, null, 0, -1, hex imm.
297 add_case("s_cmp_eq_u64 pair/vcc", "s_cmp_eq_u64 s[12:13], vcc", 1)
298 add_case("s_cmp_lg_u64 pair/null", "s_cmp_lg_u64 s[12:13], null", 1)
299 add_case("s_cmp_eq_u64 null/0", "s_cmp_eq_u64 null, 0", 1)
300 add_case("s_cmp_eq_u64 exec/-1", "s_cmp_eq_u64 exec, -1", 1)
301 add_case("s_cmp_lg_u64 exec/0", "s_cmp_lg_u64 exec, 0", 1)
302
303 # 4 bit-test ops covering b32 and b64 with valid scalar operands.
304 add_case("s_bitcmp1_b32 s12/4", "s_bitcmp1_b32 s12, 4", 1)
305 add_case("s_bitcmp0_b32 m0/1", "s_bitcmp0_b32 m0, 1", 1)
306 add_case("s_bitcmp1_b32 fimm/29", "s_bitcmp1_b32 1.0, 29", 1)
307 add_case("s_bitcmp0_b32 fimm/30", "s_bitcmp0_b32 1.0, 30", 1)
308 add_case("s_bitcmp0_b32 null/0", "s_bitcmp0_b32 null, 0", 1)
309 add_case("s_bitcmp1_b32 exec_lo/0", "s_bitcmp1_b32 exec_lo, 0", 1)
310 add_case("s_bitcmp1_b64 pair/40", "s_bitcmp1_b64 s[12:13], 40", 1)
311 add_case("s_bitcmp0_b64 pair/41", "s_bitcmp0_b64 s[12:13], 41", 1)
312 add_case("s_bitcmp1_b64 vcc/40", "s_bitcmp1_b64 vcc, 40", 1)
313 add_case("s_bitcmp1_b64 exec/63", "s_bitcmp1_b64 exec, 63", 1)
314 add_case("s_bitcmp0_b64 null/35", "s_bitcmp0_b64 null, 35", 1)
315 add_case("s_bitcmp1_b64 neg_imm/63", "s_bitcmp1_b64 -1, 63", 1)
316 add_case("s_bitcmp1_b64 pair/m0", "s_bitcmp1_b64 s[12:13], m0", 0)
317
318 asm.append("s_endpgm")
319 return asm, expected
320
321
249class TestSopcPositiveControls(unittest.TestCase): 322class TestSopcPositiveControls(unittest.TestCase):
250 def test_all_18_ops_and_valid_scalar_operands_spirv_val_and_interp(self): 323 def test_all_18_ops_and_valid_scalar_operands_interp(self):
251 asm: list[str] = [ 324 asm, expected = _positive_control_program()
252 "s_mov_b32 m0, 0x00000005", 325 spv = _translate_cs("cs_sopc_pos", asm, threads=64)
253 "s_mov_b32 s8, -1",
254 "s_mov_b32 s9, 0x3f800000", # 1.0f bits (bit 29 is 1, bit 30 is 0)
255 "s_mov_b32 s10, 0xbf800000", # -1.0f bits
256 "s_mov_b32 s12, 0x00000010", # bit 4 set
257 "s_mov_b32 s13, 0x00000100", # bit 40 set in s[12:13]
258 "s_mov_b32 vcc_lo, s12",
259 "s_mov_b32 vcc_hi, s13",
260 ]
261 expected: list[tuple[str, int]] = []
262
263 def add_case(label: str, insn: str, want: int):
264 slot = len(expected)
265 asm.append(insn)
266 asm.extend(_store_scc(slot))
267 expected.append((label, want))
268
269 # 12 32-bit scalar compares covering sgpr, null, m0, vcc_lo/hi, exec_lo/hi, scc/src_scc,
270 # plain negative integer immediates, positive immediates, and float immediates.
271 add_case("s_cmp_eq_i32 sgpr/neg_imm", "s_cmp_eq_i32 s8, -1", 1)
272 add_case("s_cmp_lg_i32 sgpr/neg_imm", "s_cmp_lg_i32 s8, -16", 1)
273 add_case("s_cmp_gt_i32 null/neg_imm", "s_cmp_gt_i32 null, -1", 1)
274 add_case("s_cmp_ge_i32 m0/imm", "s_cmp_ge_i32 m0, 5", 1)
275 add_case("s_cmp_lt_i32 neg_imm/null", "s_cmp_lt_i32 -1, null", 1)
276 add_case("s_cmp_le_i32 scc/imm", "s_cmp_le_i32 scc, 1", 1)
277 add_case("s_cmp_eq_u32 sgpr/fimm", "s_cmp_eq_u32 s9, 1.0", 1)
278 add_case("s_cmp_eq_u32 sgpr/neg_fimm", "s_cmp_eq_u32 s10, -1.0", 1)
279 add_case("s_cmp_lg_u32 vcc_lo/null", "s_cmp_lg_u32 vcc_lo, null", 1)
280 add_case("s_cmp_gt_u32 vcc_hi/m0", "s_cmp_gt_u32 vcc_hi, m0", 1)
281 add_case("s_cmp_ge_u32 exec_lo/exec_hi", "s_cmp_ge_u32 exec_lo, exec_hi", 1)
282 add_case("s_cmp_lt_u32 src_scc/m0", "s_cmp_lt_u32 src_scc, m0", 1)
283 add_case("s_cmp_le_u32 m0/vcc_lo", "s_cmp_le_u32 m0, vcc_lo", 1)
284
285 # 2 64-bit scalar compares covering s[a:b], vcc, exec, null, 0, -1, hex imm.
286 add_case("s_cmp_eq_u64 pair/vcc", "s_cmp_eq_u64 s[12:13], vcc", 1)
287 add_case("s_cmp_lg_u64 pair/null", "s_cmp_lg_u64 s[12:13], null", 1)
288 add_case("s_cmp_eq_u64 null/0", "s_cmp_eq_u64 null, 0", 1)
289 add_case("s_cmp_eq_u64 exec/-1", "s_cmp_eq_u64 exec, -1", 1)
290 add_case("s_cmp_lg_u64 exec/0", "s_cmp_lg_u64 exec, 0", 1)
291
292 # 4 bit-test ops covering b32 and b64 with valid scalar operands.
293 add_case("s_bitcmp1_b32 s12/4", "s_bitcmp1_b32 s12, 4", 1)
294 add_case("s_bitcmp0_b32 m0/1", "s_bitcmp0_b32 m0, 1", 1)
295 add_case("s_bitcmp1_b32 fimm/29", "s_bitcmp1_b32 1.0, 29", 1)
296 add_case("s_bitcmp0_b32 fimm/30", "s_bitcmp0_b32 1.0, 30", 1)
297 add_case("s_bitcmp0_b32 null/0", "s_bitcmp0_b32 null, 0", 1)
298 add_case("s_bitcmp1_b32 exec_lo/0", "s_bitcmp1_b32 exec_lo, 0", 1)
299 add_case("s_bitcmp1_b64 pair/40", "s_bitcmp1_b64 s[12:13], 40", 1)
300 add_case("s_bitcmp0_b64 pair/41", "s_bitcmp0_b64 s[12:13], 41", 1)
301 add_case("s_bitcmp1_b64 vcc/40", "s_bitcmp1_b64 vcc, 40", 1)
302 add_case("s_bitcmp1_b64 exec/63", "s_bitcmp1_b64 exec, 63", 1)
303 add_case("s_bitcmp0_b64 null/35", "s_bitcmp0_b64 null, 35", 1)
304 add_case("s_bitcmp1_b64 neg_imm/63", "s_bitcmp1_b64 -1, 63", 1)
305 add_case("s_bitcmp1_b64 pair/m0", "s_bitcmp1_b64 s[12:13], m0", 0)
306
307 asm.append("s_endpgm")
308 spv = _translate_and_validate_cs("cs_sopc_pos", asm, threads=64)
309 mem = si.run_workgroup( 326 mem = si.run_workgroup(
310 spv, 64, 64, 327 spv, 64, 64,
311 inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, 328 inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i},
@@ -316,6 +333,12 @@ class TestSopcPositiveControls(unittest.TestCase):
316 with self.subTest(case=label): 333 with self.subTest(case=label):
317 self.assertEqual(mem[slot * 4], want, label) 334 self.assertEqual(mem[slot * 4], want, label)
318 335
336 def test_all_18_ops_and_valid_scalar_operands_spirv_val(self):
337 spirv_as, spirv_val = _require_or_skip_spirv_tools(self)
338 asm, _ = _positive_control_program()
339 spv = _translate_cs("cs_sopc_pos", asm, threads=64)
340 _validate_spirv("cs_sopc_pos", spv, spirv_as, spirv_val)
341
319 342
320if __name__ == "__main__": 343if __name__ == "__main__":
321 unittest.main() 344 unittest.main()
diff --git a/tests/semantic/test_store_liveins.py b/tests/semantic/test_store_liveins.py
index e5aed90bb..3df702c1d 100644
--- a/tests/semantic/test_store_liveins.py
+++ b/tests/semantic/test_store_liveins.py
@@ -15,6 +15,24 @@ class StoreLiveIns(unittest.TestCase):
15 self.assertEqual(rdna2spirv.reg_reads_writes([ins]), (reads, set())) 15 self.assertEqual(rdna2spirv.reg_reads_writes([ins]), (reads, set()))
16 self.assertEqual(rdna2spirv.read_before_write_vgprs([ins]), reads) 16 self.assertEqual(rdna2spirv.read_before_write_vgprs([ins]), reads)
17 17
18 def test_nsa_address_list_registers_are_sources(self):
19 # An NSA image op names each address register on its own ([v2, v5, v9] parses as one "vlist" operand), so
20 # the registers need not be contiguous: a range from the first one would read v2..v4 and miss v5 and v9.
21 sample = "image_sample v0, [v2, v3], s[0:7], s[8:11] dmask:0x1 dim:SQ_RSRC_IMG_2D"
22 load = "image_load v[4:7], [v2, v5, v9], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_3D unorm"
23 for op, reads, writes in ((sample, {2, 3}, {0}), (load, {2, 5, 9}, {4, 5, 6, 7})):
24 with self.subTest(op=op):
25 ins = parse_line(op)
26 self.assertEqual(rdna2spirv.reg_reads_writes([ins]), (reads, writes))
27 self.assertEqual(rdna2spirv.read_before_write_vgprs([ins]), reads)
28
29 def test_nsa_list_register_written_first_is_no_live_in(self):
30 # v5 is written before the image op reads it, so of the list only v2 and v9 come from shader entry.
31 insns = [parse_line("v_mov_b32 v5, 0"),
32 parse_line("image_load v[4:7], [v2, v5, v9], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_3D unorm")]
33 self.assertEqual(rdna2spirv.read_before_write_vgprs(insns), {2, 9})
34 self.assertEqual(rdna2spirv.reg_reads_writes(insns), ({2, 5, 9}, {4, 5, 6, 7}))
35
18 def test_branch_exports_live_barycentrics(self): 36 def test_branch_exports_live_barycentrics(self):
19 fixture = Path(__file__).parent / "fixtures" / "ps_flat_store_livein.asm" 37 fixture = Path(__file__).parent / "fixtures" / "ps_flat_store_livein.asm"
20 program = fixture.read_text(encoding="ascii").splitlines() 38 program = fixture.read_text(encoding="ascii").splitlines()
diff --git a/tests/semantic/test_unary_f16_validation.py b/tests/semantic/test_unary_f16_validation.py
index b6413441c..d60b1d7e7 100644
--- a/tests/semantic/test_unary_f16_validation.py
+++ b/tests/semantic/test_unary_f16_validation.py
@@ -39,9 +39,20 @@ def h2f(h):
39 return struct.unpack("<e", struct.pack("<H", h & 0xFFFF))[0] 39 return struct.unpack("<e", struct.pack("<H", h & 0xFFFF))[0]
40 40
41 41
42def validate_spirv(spv_text): 42def _require_or_skip_spirv_tools(test_case: unittest.TestCase) -> tuple[str, str]:
43 spirv_as = shutil.which("spirv-as") 43 spirv_as = shutil.which("spirv-as")
44 spirv_val = shutil.which("spirv-val") 44 spirv_val = shutil.which("spirv-val")
45 if spirv_as and spirv_val:
46 return spirv_as, spirv_val
47 msg = "spirv-as / spirv-val not found on PATH"
48 if os.environ.get("LEONIDA_REQUIRE_SPIRV_TOOLS") == "1":
49 test_case.fail(msg)
50 test_case.skipTest(msg)
51
52
53def validate_spirv(spv_text, spirv_as=None, spirv_val=None):
54 spirv_as = spirv_as or shutil.which("spirv-as")
55 spirv_val = spirv_val or shutil.which("spirv-val")
45 if not spirv_as or not spirv_val: 56 if not spirv_as or not spirv_val:
46 raise AssertionError("spirv-as / spirv-val not found on PATH") 57 raise AssertionError("spirv-as / spirv-val not found on PATH")
47 with tempfile.TemporaryDirectory() as d: 58 with tempfile.TemporaryDirectory() as d:
@@ -67,10 +78,84 @@ def validate_spirv(spv_text):
67 78
68def run_ps(lines, name="ps_unary_f16_val"): 79def run_ps(lines, name="ps_unary_f16_val"):
69 spv = translate_lines(name, lines) 80 spv = translate_lines(name, lines)
70 validate_spirv(spv)
71 return mrt0_words(spv) 81 return mrt0_words(spv)
72 82
73 83
84def _combo_opsel_shaders():
85 v1_val = (f2h(0.25) << 16) | f2h(0.0)
86 old = 0xBEEF1234
87 combos = ((0, 0), (1, 0), (0, 1), (1, 1))
88 shaders = []
89 for op in ("v_sin_f16", "v_cos_f16"):
90 for suffix in ("_e64", ""):
91 lines = [f"v_mov_b32 v4, {v1_val:#x}"]
92 for idx, (shi, dhi) in enumerate(combos):
93 lines.append(f"v_mov_b32 v{idx}, {old:#x}")
94 lines.append(f"{op}{suffix} v{idx}, v4 op_sel:[{shi},{dhi}]")
95 lines.append("exp mrt0 v0, v1, v2, v3 done vm")
96 lines.append("s_endpgm")
97 shaders.append((op, suffix, f"ps_{op}_{suffix or 'bare'}_opsel", lines))
98 return combos, old, shaders
99
100
101def _nontrivial_opsel_shader():
102 # lo = 0.125 turns (45 deg): sin ~= 0.707, cos ~= 0.707
103 # hi = 0.75 turns (270 deg): sin = -1.0, cos = 0.0
104 v1_val = (f2h(0.75) << 16) | f2h(0.125)
105 old = 0xCAFE5678
106 lines = [
107 f"v_mov_b32 v4, {v1_val:#x}",
108 f"v_mov_b32 v0, {old:#x}",
109 "v_sin_f16_e64 v0, v4 op_sel:[1,1]", # hi = sin(0.75) = -1.0, lo preserved
110 f"v_mov_b32 v1, {old:#x}",
111 "v_sin_f16_e64 v1, -v4 op_sel:[1,0]", # lo = sin(-0.75) = +1.0, hi preserved
112 f"v_mov_b32 v2, {old:#x}",
113 "v_sin_f16_e64 v2, v4 op_sel:[1,1] clamp", # hi = clamp(-1.0) = 0.0, lo preserved
114 f"v_mov_b32 v3, {old:#x}",
115 "v_cos_f16_e64 v3, |v4| op_sel:[0,1]", # hi = cos(0.125) ~= sqrt(2)/2, lo preserved
116 "exp mrt0 v0, v1, v2, v3 done vm",
117 "s_endpgm",
118 ]
119 return old, "ps_sincos_opsel_mods", lines
120
121
122def _inplace_sdwa_shader():
123 # In-place op_sel:[1,0] reads hi before overwriting lo; SDWA reads WORD_1 and writes WORD_1.
124 v0_init = (f2h(0.25) << 16) | f2h(0.0)
125 old = 0x0000BEEF
126 lines = [
127 f"v_mov_b32 v0, {v0_init:#x}",
128 "v_sin_f16_e64 v0, v0 op_sel:[1,0]", # lo = sin(0.25) = 1.0, hi stays 0.25
129 f"v_mov_b32 v1, {v0_init:#x}",
130 "v_cos_f16_e64 v1, v1 op_sel:[0,1]", # hi = cos(0.0) = 1.0, lo stays 0.0
131 f"v_mov_b32 v4, {v0_init:#x}",
132 f"v_mov_b32 v2, {old:#x}",
133 "v_sin_f16_sdwa v2, v4 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_1",
134 f"v_mov_b32 v3, {old:#x}",
135 "v_cos_f16_sdwa v3, v4 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0",
136 "exp mrt0 v0, v1, v2, v3 done vm",
137 "s_endpgm",
138 ]
139 return old, "ps_sincos_inplace_sdwa", lines
140
141
142def _positive_control_lines(op):
143 valid_forms = [
144 f"{op} v0, v1",
145 f"{op}_e32 v0, v1",
146 f"{op}_e64 v0, -|v1| op_sel:[1,1] clamp mul:2",
147 f"{op} v0, |v1| op_sel:[1,0] div:2 clamp",
148 f"{op}_sdwa v0, -v1 clamp mul:2 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_1",
149 ]
150 return [
151 "v_mov_b32 v0, 0xaaaa3c00",
152 "v_mov_b32 v1, 0x40003800",
153 *valid_forms,
154 "exp mrt0 v0, v0, v0, v0 done vm",
155 "s_endpgm",
156 ]
157
158
74def translate_single(inst_line): 159def translate_single(inst_line):
75 lines = [ 160 lines = [
76 "v_mov_b32 v0, 0xaaaa3c00", 161 "v_mov_b32 v0, 0xaaaa3c00",
@@ -89,14 +174,7 @@ class SinCosF16OpSelTests(unittest.TestCase):
89 """Verify v_sin_f16 / v_cos_f16 honor op_sel:[shi, dhi] and preserve the other half.""" 174 """Verify v_sin_f16 / v_cos_f16 honor op_sel:[shi, dhi] and preserve the other half."""
90 175
91 def test_sin_cos_opsel_all_four_combinations(self): 176 def test_sin_cos_opsel_all_four_combinations(self):
92 # Pack two distinct turn angles into v1: 177 combos, old, shaders = _combo_opsel_shaders()
93 # lo = 0.0 -> sin(0.0) = 0.0, cos(0.0) = 1.0
94 # hi = 0.25 -> sin(0.25) = 1.0, cos(0.25) = 0.0
95 h_lo = f2h(0.0)
96 h_hi = f2h(0.25)
97 v1_val = (h_hi << 16) | h_lo
98 old = 0xBEEF1234
99
100 expected = { 178 expected = {
101 ("v_sin_f16", 0, 0): (old & 0xFFFF0000) | f2h(0.0), 179 ("v_sin_f16", 0, 0): (old & 0xFFFF0000) | f2h(0.0),
102 ("v_sin_f16", 1, 0): (old & 0xFFFF0000) | f2h(1.0), 180 ("v_sin_f16", 1, 0): (old & 0xFFFF0000) | f2h(1.0),
@@ -107,42 +185,15 @@ class SinCosF16OpSelTests(unittest.TestCase):
107 ("v_cos_f16", 0, 1): (f2h(1.0) << 16) | (old & 0xFFFF), 185 ("v_cos_f16", 0, 1): (f2h(1.0) << 16) | (old & 0xFFFF),
108 ("v_cos_f16", 1, 1): (f2h(0.0) << 16) | (old & 0xFFFF), 186 ("v_cos_f16", 1, 1): (f2h(0.0) << 16) | (old & 0xFFFF),
109 } 187 }
110 188 for op, suffix, name, lines in shaders:
111 for op in ("v_sin_f16", "v_cos_f16"): 189 words = run_ps(lines, name)
112 for suffix in ("_e64", ""): 190 for idx, (shi, dhi) in enumerate(combos):
113 lines = [f"v_mov_b32 v4, {v1_val:#x}"] 191 with self.subTest(op=op, suffix=suffix or "bare", shi=shi, dhi=dhi):
114 combos = ((0, 0), (1, 0), (0, 1), (1, 1)) 192 self.assertEqual(words[idx], expected[(op, shi, dhi)])
115 for idx, (shi, dhi) in enumerate(combos):
116 lines.append(f"v_mov_b32 v{idx}, {old:#x}")
117 lines.append(f"{op}{suffix} v{idx}, v4 op_sel:[{shi},{dhi}]")
118 lines.append("exp mrt0 v0, v1, v2, v3 done vm")
119 lines.append("s_endpgm")
120 words = run_ps(lines, f"ps_{op}_{suffix or 'bare'}_opsel")
121 for idx, (shi, dhi) in enumerate(combos):
122 with self.subTest(op=op, suffix=suffix or "bare", shi=shi, dhi=dhi):
123 self.assertEqual(words[idx], expected[(op, shi, dhi)])
124 193
125 def test_sin_cos_opsel_nontrivial_angles_and_mods(self): 194 def test_sin_cos_opsel_nontrivial_angles_and_mods(self):
126 # lo = 0.125 turns (45 deg): sin ~= 0.707, cos ~= 0.707 195 old, name, lines = _nontrivial_opsel_shader()
127 # hi = 0.75 turns (270 deg): sin = -1.0, cos = 0.0 196 words = run_ps(lines, name)
128 h_lo = f2h(0.125)
129 h_hi = f2h(0.75)
130 v1_val = (h_hi << 16) | h_lo
131 old = 0xCAFE5678
132
133 words = run_ps([
134 f"v_mov_b32 v4, {v1_val:#x}",
135 f"v_mov_b32 v0, {old:#x}",
136 "v_sin_f16_e64 v0, v4 op_sel:[1,1]", # hi = sin(0.75) = -1.0, lo preserved
137 f"v_mov_b32 v1, {old:#x}",
138 "v_sin_f16_e64 v1, -v4 op_sel:[1,0]", # lo = sin(-0.75) = +1.0, hi preserved
139 f"v_mov_b32 v2, {old:#x}",
140 "v_sin_f16_e64 v2, v4 op_sel:[1,1] clamp", # hi = clamp(-1.0) = 0.0, lo preserved
141 f"v_mov_b32 v3, {old:#x}",
142 "v_cos_f16_e64 v3, |v4| op_sel:[0,1]", # hi = cos(0.125) ~= sqrt(2)/2, lo preserved
143 "exp mrt0 v0, v1, v2, v3 done vm",
144 "s_endpgm",
145 ], "ps_sincos_opsel_mods")
146 197
147 self.assertEqual(words[0], (f2h(-1.0) << 16) | (old & 0xFFFF)) 198 self.assertEqual(words[0], (f2h(-1.0) << 16) | (old & 0xFFFF))
148 self.assertEqual(words[1], (old & 0xFFFF0000) | f2h(1.0)) 199 self.assertEqual(words[1], (old & 0xFFFF0000) | f2h(1.0))
@@ -151,51 +202,41 @@ class SinCosF16OpSelTests(unittest.TestCase):
151 self.assertAlmostEqual(h2f(words[3] >> 16), math.cos(2.0 * math.pi * 0.125), delta=2e-3) 202 self.assertAlmostEqual(h2f(words[3] >> 16), math.cos(2.0 * math.pi * 0.125), delta=2e-3)
152 203
153 def test_sin_cos_opsel_inplace_and_sdwa(self): 204 def test_sin_cos_opsel_inplace_and_sdwa(self):
154 # In-place op_sel:[1,0] reads hi before overwriting lo; SDWA reads WORD_1 and writes WORD_1. 205 old, name, lines = _inplace_sdwa_shader()
155 v0_init = (f2h(0.25) << 16) | f2h(0.0) 206 words = run_ps(lines, name)
156 old = 0x0000BEEF
157 words = run_ps([
158 f"v_mov_b32 v0, {v0_init:#x}",
159 "v_sin_f16_e64 v0, v0 op_sel:[1,0]", # lo = sin(0.25) = 1.0, hi stays 0.25
160 f"v_mov_b32 v1, {v0_init:#x}",
161 "v_cos_f16_e64 v1, v1 op_sel:[0,1]", # hi = cos(0.0) = 1.0, lo stays 0.0
162 f"v_mov_b32 v4, {v0_init:#x}",
163 f"v_mov_b32 v2, {old:#x}",
164 "v_sin_f16_sdwa v2, v4 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_1",
165 f"v_mov_b32 v3, {old:#x}",
166 "v_cos_f16_sdwa v3, v4 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0",
167 "exp mrt0 v0, v1, v2, v3 done vm",
168 "s_endpgm",
169 ], "ps_sincos_inplace_sdwa")
170 207
171 self.assertEqual(words[0], (f2h(0.25) << 16) | f2h(1.0)) 208 self.assertEqual(words[0], (f2h(0.25) << 16) | f2h(1.0))
172 self.assertEqual(words[1], (f2h(1.0) << 16) | f2h(0.0)) 209 self.assertEqual(words[1], (f2h(1.0) << 16) | f2h(0.0))
173 self.assertEqual(words[2], (f2h(1.0) << 16) | (old & 0xFFFF)) 210 self.assertEqual(words[2], (f2h(1.0) << 16) | (old & 0xFFFF))
174 self.assertEqual(words[3], (f2h(1.0) << 16) | (old & 0xFFFF)) 211 self.assertEqual(words[3], (f2h(1.0) << 16) | (old & 0xFFFF))
175 212
213 def test_sin_cos_opsel_spirv_val(self):
214 spirv_as, spirv_val = _require_or_skip_spirv_tools(self)
215 _, _, shaders = _combo_opsel_shaders()
216 cases = [(name, lines) for _, _, name, lines in shaders]
217 for helper in (_nontrivial_opsel_shader, _inplace_sdwa_shader):
218 _, name, lines = helper()
219 cases.append((name, lines))
220 for name, lines in cases:
221 with self.subTest(shader=name):
222 validate_spirv(translate_lines(name, lines), spirv_as, spirv_val)
223
176 224
177class UnaryF16ValidationTests(unittest.TestCase): 225class UnaryF16ValidationTests(unittest.TestCase):
178 """Positive and negative operand/encoding/modifier validation across all 12 unary f16 ops.""" 226 """Positive and negative operand/encoding/modifier validation across all 12 unary f16 ops."""
179 227
180 def test_positive_controls_all_12_ops(self): 228 def test_positive_controls_all_12_ops(self):
181 for op in UNARY_F16_OPS: 229 for op in UNARY_F16_OPS:
182 valid_forms = [
183 f"{op} v0, v1",
184 f"{op}_e32 v0, v1",
185 f"{op}_e64 v0, -|v1| op_sel:[1,1] clamp mul:2",
186 f"{op} v0, |v1| op_sel:[1,0] div:2 clamp",
187 f"{op}_sdwa v0, -v1 clamp mul:2 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_1",
188 ]
189 lines = [
190 "v_mov_b32 v0, 0xaaaa3c00",
191 "v_mov_b32 v1, 0x40003800",
192 *valid_forms,
193 "exp mrt0 v0, v0, v0, v0 done vm",
194 "s_endpgm",
195 ]
196 with self.subTest(op=op): 230 with self.subTest(op=op):
197 spv = translate_lines(f"ps_pos_{op}", lines) 231 spv = translate_lines(f"ps_pos_{op}", _positive_control_lines(op))
198 validate_spirv(spv) 232 self.assertIn("OpEntryPoint", spv)
233
234 def test_positive_controls_all_12_ops_spirv_val(self):
235 spirv_as, spirv_val = _require_or_skip_spirv_tools(self)
236 for op in UNARY_F16_OPS:
237 with self.subTest(op=op):
238 spv = translate_lines(f"ps_pos_{op}", _positive_control_lines(op))
239 validate_spirv(spv, spirv_as, spirv_val)
199 240
200 def test_negative_validation_all_12_ops(self): 241 def test_negative_validation_all_12_ops(self):
201 invalid_templates = [ 242 invalid_templates = [
diff --git a/tests/semantic/test_valu_cvt_f32_f64.py b/tests/semantic/test_valu_cvt_f32_f64.py
index b860ecc98..056b2643b 100644
--- a/tests/semantic/test_valu_cvt_f32_f64.py
+++ b/tests/semantic/test_valu_cvt_f32_f64.py
@@ -1821,5 +1821,38 @@ class TestValuCvtF32F64NegativeControlsAndMutations(unittest.TestCase):
1821 self.assertNotEqual(sim.read_lane_reg_u32(0, RegKind.VGPR, 0), 0xAAAAAAAA) 1821 self.assertNotEqual(sim.read_lane_reg_u32(0, RegKind.VGPR, 0), 0xAAAAAAAA)
1822 1822
1823 1823
1824# ==============================================================================
1825# The translator: tools/rdna2spirv.py's output, run in tests/spirv_interp.py, gives the oracle's word
1826# ==============================================================================
1827import os as _os # noqa: E402
1828import sys as _sys # noqa: E402
1829
1830_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))
1831import f64_translate as ft # noqa: E402
1832
1833class TranslatorMatchesOracle(unittest.TestCase):
1834 """v_cvt_f32_f64 is OpFConvert to binary32 (round to nearest even). On every input whose binary32 result is a
1835 normal number, a zero or an infinity - no NaN, no binary32 subnormal (it follows the driver's denormal mode), no
1836 overflow - the translated instruction gives ref_cvt_f32_f64's word."""
1837
1838 VALUES = (1.0, 1 / 3, 0.1, 2.5, 1e20, 7.0, 1e-30, 3.4028234663852886e38, 1.1754943508222875e-38, 0.0)
1839
1840 def check(self, word, src="v[2:3]", mods="", **oracle):
1841 with self.subTest(word=hex(word), src=src, mods=mods):
1842 self.assertEqual(hex(ft.run_f64("v_cvt_f32_f64", word, src=src, mods=mods, wide=False)),
1843 hex(ref_cvt_f32_f64(word, **oracle)))
1844
1845 def test_values_both_signs_and_infinities(self):
1846 for word in [ft.f64_bits(x) for x in self.VALUES] + [0x7FF0000000000000]:
1847 for sign in (0, 1 << 63):
1848 self.check(word | sign)
1849
1850 def test_source_modifiers_and_clamp(self):
1851 for x in (0.75, 3.0, -0.5, -1e20):
1852 self.check(ft.f64_bits(x), src="-v[2:3]", neg=True)
1853 self.check(ft.f64_bits(x), src="|v[2:3]|", abs_val=True)
1854 self.check(ft.f64_bits(x), mods=" clamp", clamp=True)
1855
1856
1824if __name__ == "__main__": 1857if __name__ == "__main__":
1825 unittest.main() 1858 unittest.main()
diff --git a/tests/semantic/test_valu_f32_min3_max3_mad.py b/tests/semantic/test_valu_f32_min3_max3_mad.py
index 58d06bbd9..db75232df 100644
--- a/tests/semantic/test_valu_f32_min3_max3_mad.py
+++ b/tests/semantic/test_valu_f32_min3_max3_mad.py
@@ -12,8 +12,8 @@ plain-Python IEEE-754 binary32 / RDNA2 ISA reference oracle (stdlib only, no gam
12Observed translator / interpreter findings (kept out of failing assertions and documented here): 12Observed translator / interpreter findings (kept out of failing assertions and documented here):
13 1. v_min3_f32 / v_max3_f32 with NaN operands: tools/rdna2spirv.py emits GLSL.std.450 NMin / NMax, which give the 13 1. v_min3_f32 / v_max3_f32 with NaN operands: tools/rdna2spirv.py emits GLSL.std.450 NMin / NMax, which give the
14 other operand for a NaN, as RDNA2 hardware does. Those rows are asserted in tests/semantic/ 14 other operand for a NaN, as RDNA2 hardware does. Those rows are asserted in tests/semantic/
15 test_float_nan_fract.py; NaN inputs stay out of the value assertions here (clamp-on-NaN is still FClamp, which 15 test_float_nan_fract.py; NaN inputs stay out of the value assertions here (clamp-on-NaN, which gives +0, is
16 spirv_mini_interp.py rejects). NaN semantics are tested on v_mad_f32, v_fmac_f32, and v_mad_legacy_f32. 16 checked in test_vop3_clamp_nan.py). NaN semantics are tested on v_mad_f32, v_fmac_f32, and v_mad_legacy_f32.
17 2. v_min3_f32 / v_max3_f32 signed-zero ties: RDNA2 hardware orders -0.0 below +0.0 (measured on an AMD Radeon 17 2. v_min3_f32 / v_max3_f32 signed-zero ties: RDNA2 hardware orders -0.0 below +0.0 (measured on an AMD Radeon
18 RX 6800: min(+0, -0) = -0 and max(+0, -0) = +0 in either operand order), and spirv_mini_interp.py's NMin / NMax 18 RX 6800: min(+0, -0) = -0 and max(+0, -0) = +0 in either operand order), and spirv_mini_interp.py's NMin / NMax
19 do the same, so every zero triple asserts exact bit patterns. 19 do the same, so every zero triple asserts exact bit patterns.
diff --git a/tests/semantic/test_valu_frexp_exp_i32_f64.py b/tests/semantic/test_valu_frexp_exp_i32_f64.py
index b990c5b71..da929c627 100644
--- a/tests/semantic/test_valu_frexp_exp_i32_f64.py
+++ b/tests/semantic/test_valu_frexp_exp_i32_f64.py
@@ -31,6 +31,10 @@ RDNA2 Double-Precision Exponent Extraction Rules:
31 31
32Standard library Python only; zero third-party dependencies; zero game data. 32Standard library Python only; zero third-party dependencies; zero game data.
33Python 3.9+ compatible (from __future__ import annotations). 33Python 3.9+ compatible (from __future__ import annotations).
34
35The translator check at the end of this file (TranslatorMatchesOracle) compares the translated v_frexp_exp_i32_f64
36with this oracle on every class of input, NaNs included: for the exponent it agrees with the hardware measured in the
37game's MODE (docs/design.md, the v_frexp_mant_f64 / v_frexp_exp_i32_f64 row).
34""" 38"""
35from __future__ import annotations 39from __future__ import annotations
36 40
@@ -1206,5 +1210,43 @@ class TestValuFrexpExpI32F64MutationDetection(unittest.TestCase):
1206 self.assertEqual(simd.read_lane_reg_u32(0, RegKind.VGPR, 0), canary) 1210 self.assertEqual(simd.read_lane_reg_u32(0, RegKind.VGPR, 0), canary)
1207 1211
1208 1212
1213# ==============================================================================
1214# The translator: tools/rdna2spirv.py's output, run in tests/spirv_interp.py, against this file's oracle
1215# ==============================================================================
1216import os as _os # noqa: E402
1217import sys as _sys # noqa: E402
1218
1219_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))
1220import f64_translate as ft # noqa: E402
1221
1222def _frexp_inputs():
1223 """Normals, subnormals, zeros, infinities and quiet NaNs, both signs."""
1224 words = [ft.f64_bits(x) for x in (1.0, 2.0, 3.0, 0.75, 0.1, 123.456, 1e300, 1e-300, 1.7976931348623157e308,
1225 2.2250738585072014e-308)]
1226 words += [0x0000000000000000, 0x0000000000000001, 0x000FFFFFFFFFFFFF, 0x0008000000000000,
1227 0x7FF0000000000000, 0x7FF8000000000000, 0x7FF8000012345678]
1228 return [w | sign for w in words for sign in (0, 1 << 63)]
1229
1230
1231SNANS = (0x7FF0000000000001, 0xFFF6208167C66911) # signalling NaNs, both signs
1232
1233class TranslatorMatchesOracle(unittest.TestCase):
1234 """The translated v_frexp_exp_i32_f64 gives this file's oracle word on every input class, NaNs included."""
1235
1236 def test_matches_the_oracle(self):
1237 for word in _frexp_inputs() + list(SNANS):
1238 with self.subTest(word=hex(word)):
1239 self.assertEqual(hex(ft.run_f64("v_frexp_exp_i32_f64", word, wide=False)),
1240 hex(ref_frexp_exp_i32_f64(word) & 0xFFFFFFFF))
1241
1242 def test_source_modifiers(self):
1243 for x in (3.0, 0.75, 1e-300, 1.7976931348623157e308):
1244 word = ft.f64_bits(-x)
1245 for src, kw in (("-v[2:3]", dict(neg=True)), ("|v[2:3]|", dict(abs_val=True))):
1246 with self.subTest(word=hex(word), src=src):
1247 self.assertEqual(hex(ft.run_f64("v_frexp_exp_i32_f64", word, src=src, wide=False)),
1248 hex(ref_frexp_exp_i32_ext(word, **kw) & 0xFFFFFFFF))
1249
1250
1209if __name__ == "__main__": 1251if __name__ == "__main__":
1210 unittest.main() 1252 unittest.main()
diff --git a/tests/semantic/test_valu_frexp_f64.py b/tests/semantic/test_valu_frexp_f64.py
index 4335674db..65840022e 100644
--- a/tests/semantic/test_valu_frexp_f64.py
+++ b/tests/semantic/test_valu_frexp_f64.py
@@ -32,6 +32,12 @@ Architecture:
32 - Modifiers: 32 - Modifiers:
33 * Input modifiers on S0: abs (|S0|), neg (-S0). 33 * Input modifiers on S0: abs (|S0|), neg (-S0).
34 * Output modifiers on mantissa: clamp (clamps to [0.0, 1.0]), omod (mul:2, mul:4, div:2). 34 * Output modifiers on mantissa: clamp (clamps to [0.0, 1.0]), omod (mul:2, mul:4, div:2).
35
36The translator check at the end of this file (TranslatorMatchesOracle): this oracle quiets a signalling NaN and
37applies mul:2 / mul:4 / div:2 to the mantissa, which is RDNA2's behaviour under IEEE=1 (and denorm_mode_16_64=0).
38In the game's MODE (IEEE 0, denorm_mode_16_64 3) the hardware passes a signalling NaN through unchanged and ignores
39those output modifiers (docs/design.md, the v_frexp_mant_f64 row, measured on gfx1036), and so does the translator;
40the class compares the two where they agree and pins those two measured behaviours.
35""" 41"""
36 42
37from fractions import Fraction 43from fractions import Fraction
@@ -1568,5 +1574,66 @@ class TestValuFrexpF64Oracle(unittest.TestCase):
1568 self.assertEqual(bits_to_f64(ref_frexp_mant_f64(ONE_F64, omod="div:2")), 0.25) 1574 self.assertEqual(bits_to_f64(ref_frexp_mant_f64(ONE_F64, omod="div:2")), 0.25)
1569 1575
1570 1576
1577# ==============================================================================
1578# The translator: tools/rdna2spirv.py's output, run in tests/spirv_interp.py, against this file's oracle
1579# ==============================================================================
1580import os as _os # noqa: E402
1581import sys as _sys # noqa: E402
1582
1583_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))
1584import f64_translate as ft # noqa: E402
1585
1586def _frexp_inputs():
1587 """Normals, subnormals, zeros, infinities and quiet NaNs, both signs."""
1588 words = [ft.f64_bits(x) for x in (1.0, 2.0, 3.0, 0.75, 0.1, 123.456, 1e300, 1e-300, 1.7976931348623157e308,
1589 2.2250738585072014e-308)]
1590 words += [0x0000000000000000, 0x0000000000000001, 0x000FFFFFFFFFFFFF, 0x0008000000000000,
1591 0x7FF0000000000000, 0x7FF8000000000000, 0x7FF8000012345678]
1592 return [w | sign for w in words for sign in (0, 1 << 63)]
1593
1594
1595SNANS = (0x7FF0000000000001, 0xFFF6208167C66911) # signalling NaNs, both signs
1596
1597class TranslatorMatchesOracle(unittest.TestCase):
1598 """The translated v_frexp_mant_f64 gives ref_frexp_mant_f64's word where the oracle models the game's MODE, and the
1599 measured word where it does not (see the module docstring)."""
1600
1601 def mant(self, word, src="v[2:3]", mods=""):
1602 return ft.run_f64("v_frexp_mant_f64", word, src=src, mods=mods)
1603
1604 def test_matches_the_oracle(self):
1605 for word in _frexp_inputs():
1606 with self.subTest(word=hex(word)):
1607 self.assertEqual(hex(self.mant(word)), hex(ref_frexp_mant_f64(word)))
1608
1609 def test_source_modifiers_and_clamp(self):
1610 for x in (3.0, 0.75, 1e-300):
1611 word = ft.f64_bits(-x)
1612 for src, mods, kw in (("-v[2:3]", "", dict(neg_src0=True)), ("|v[2:3]|", "", dict(abs_src0=True)),
1613 ("v[2:3]", " clamp", dict(clamp=True)), ("-v[2:3]", " clamp", dict(neg_src0=True, clamp=True))):
1614 with self.subTest(word=hex(word), src=src, mods=mods):
1615 self.assertEqual(hex(self.mant(word, src, mods)), hex(ref_frexp_mant_f64(word, **kw)))
1616
1617 def test_signalling_nan_passes_through(self):
1618 # Measured on gfx1036 under IEEE 0 (docs/design.md); the oracle quiets it, as IEEE=1 would.
1619 for word in SNANS:
1620 with self.subTest(word=hex(word)):
1621 self.assertEqual(hex(self.mant(word)), hex(word))
1622
1623 def test_output_multipliers_are_ignored(self):
1624 # Measured on gfx1036 under denorm_mode_16_64 3 (docs/design.md); the oracle scales the mantissa.
1625 for x in (-3.0, 0.75, 123.456):
1626 word = ft.f64_bits(x)
1627 for mods in (" mul:2", " mul:4", " div:2"):
1628 with self.subTest(word=hex(word), mods=mods):
1629 self.assertEqual(hex(self.mant(word, mods=mods)), hex(self.mant(word)))
1630
1631 def test_exponent_matches_the_oracle(self):
1632 for word in _frexp_inputs() + list(SNANS):
1633 with self.subTest(word=hex(word)):
1634 self.assertEqual(hex(ft.run_f64("v_frexp_exp_i32_f64", word, wide=False)),
1635 hex(ref_frexp_exp_i32_f64(word) & 0xFFFFFFFF))
1636
1637
1571if __name__ == "__main__": 1638if __name__ == "__main__":
1572 unittest.main() 1639 unittest.main()
diff --git a/tests/semantic/test_valu_frexp_mant_f64.py b/tests/semantic/test_valu_frexp_mant_f64.py
index 697618b96..9e314555f 100644
--- a/tests/semantic/test_valu_frexp_mant_f64.py
+++ b/tests/semantic/test_valu_frexp_mant_f64.py
@@ -19,6 +19,12 @@ Architecture:
19 - Modifiers (VOP3): 19 - Modifiers (VOP3):
20 * Input modifiers on S0: abs (|S0|), neg (-S0). 20 * Input modifiers on S0: abs (|S0|), neg (-S0).
21 * Output modifiers: clamp (clamps result to [0.0, 1.0]), omod (mul:2, mul:4, div:2). 21 * Output modifiers: clamp (clamps result to [0.0, 1.0]), omod (mul:2, mul:4, div:2).
22
23The translator check at the end of this file (TranslatorMatchesOracle): this oracle quiets a signalling NaN and
24applies mul:2 / mul:4 / div:2 to the mantissa, which is RDNA2's behaviour under IEEE=1 (and denorm_mode_16_64=0).
25In the game's MODE (IEEE 0, denorm_mode_16_64 3) the hardware passes a signalling NaN through unchanged and ignores
26those output modifiers (docs/design.md, the v_frexp_mant_f64 row, measured on gfx1036), and so does the translator;
27the class compares the two where they agree and pins those two measured behaviours.
22""" 28"""
23 29
24from fractions import Fraction 30from fractions import Fraction
@@ -1235,5 +1241,60 @@ class TestValuFrexpMantF64Oracle(unittest.TestCase):
1235 self.assertEqual(bits_to_f64(ref_frexp_mant_f64(ONE_F64, omod="div:2")), 0.25) 1241 self.assertEqual(bits_to_f64(ref_frexp_mant_f64(ONE_F64, omod="div:2")), 0.25)
1236 1242
1237 1243
1244# ==============================================================================
1245# The translator: tools/rdna2spirv.py's output, run in tests/spirv_interp.py, against this file's oracle
1246# ==============================================================================
1247import os as _os # noqa: E402
1248import sys as _sys # noqa: E402
1249
1250_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))
1251import f64_translate as ft # noqa: E402
1252
1253def _frexp_inputs():
1254 """Normals, subnormals, zeros, infinities and quiet NaNs, both signs."""
1255 words = [ft.f64_bits(x) for x in (1.0, 2.0, 3.0, 0.75, 0.1, 123.456, 1e300, 1e-300, 1.7976931348623157e308,
1256 2.2250738585072014e-308)]
1257 words += [0x0000000000000000, 0x0000000000000001, 0x000FFFFFFFFFFFFF, 0x0008000000000000,
1258 0x7FF0000000000000, 0x7FF8000000000000, 0x7FF8000012345678]
1259 return [w | sign for w in words for sign in (0, 1 << 63)]
1260
1261
1262SNANS = (0x7FF0000000000001, 0xFFF6208167C66911) # signalling NaNs, both signs
1263
1264class TranslatorMatchesOracle(unittest.TestCase):
1265 """The translated v_frexp_mant_f64 gives ref_frexp_mant_f64's word where the oracle models the game's MODE, and the
1266 measured word where it does not (see the module docstring)."""
1267
1268 def mant(self, word, src="v[2:3]", mods=""):
1269 return ft.run_f64("v_frexp_mant_f64", word, src=src, mods=mods)
1270
1271 def test_matches_the_oracle(self):
1272 for word in _frexp_inputs():
1273 with self.subTest(word=hex(word)):
1274 self.assertEqual(hex(self.mant(word)), hex(ref_frexp_mant_f64(word)))
1275
1276 def test_source_modifiers_and_clamp(self):
1277 for x in (3.0, 0.75, 1e-300):
1278 word = ft.f64_bits(-x)
1279 for src, mods, kw in (("-v[2:3]", "", dict(neg_src0=True)), ("|v[2:3]|", "", dict(abs_src0=True)),
1280 ("v[2:3]", " clamp", dict(clamp=True)), ("-v[2:3]", " clamp", dict(neg_src0=True, clamp=True))):
1281 with self.subTest(word=hex(word), src=src, mods=mods):
1282 self.assertEqual(hex(self.mant(word, src, mods)), hex(ref_frexp_mant_f64(word, **kw)))
1283
1284 def test_signalling_nan_passes_through(self):
1285 # Measured on gfx1036 under IEEE 0 (docs/design.md); the oracle quiets it, as IEEE=1 would.
1286 for word in SNANS:
1287 with self.subTest(word=hex(word)):
1288 self.assertEqual(hex(self.mant(word)), hex(word))
1289
1290 def test_output_multipliers_are_ignored(self):
1291 # Measured on gfx1036 under denorm_mode_16_64 3 (docs/design.md); the oracle scales the mantissa.
1292 for x in (-3.0, 0.75, 123.456):
1293 word = ft.f64_bits(x)
1294 for mods in (" mul:2", " mul:4", " div:2"):
1295 with self.subTest(word=hex(word), mods=mods):
1296 self.assertEqual(hex(self.mant(word, mods=mods)), hex(self.mant(word)))
1297
1298
1238if __name__ == "__main__": 1299if __name__ == "__main__":
1239 unittest.main() 1300 unittest.main()
diff --git a/tests/semantic/test_valu_rcp_f64.py b/tests/semantic/test_valu_rcp_f64.py
index eb6112698..556cf42e5 100644
--- a/tests/semantic/test_valu_rcp_f64.py
+++ b/tests/semantic/test_valu_rcp_f64.py
@@ -1440,5 +1440,39 @@ class TestVRcpF64ReferenceOracle(unittest.TestCase):
1440 rf.get_vgpr_pair(15) 1440 rf.get_vgpr_pair(15)
1441 1441
1442 1442
1443# ==============================================================================
1444# The translator: tools/rdna2spirv.py's output, run in tests/spirv_interp.py, gives the oracle's word
1445# ==============================================================================
1446import os as _os # noqa: E402
1447import sys as _sys # noqa: E402
1448
1449_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))
1450import f64_translate as ft # noqa: E402
1451
1452class TranslatorMatchesOracle(unittest.TestCase):
1453 """v_rcp_f64 is `OpFDiv %double 1.0 x` (docs/design.md), so on every input whose SPIR-V result is defined - no
1454 NaN and no zero divisor - the translated instruction gives ref_rcp_f64's word, both signs, subnormals included."""
1455
1456 FINITE = (1.0, 2.0, 4.0, 0.25, 3.0, 10.0, 1 / 3, 0.1, 7.0, 1e300, 1e-300, 1.7976931348623157e308,
1457 2.2250738585072014e-308)
1458 SPECIAL = (0x0000000000000001, 0x000FFFFFFFFFFFFF, 0x7FF0000000000000) # subnormals, +inf
1459
1460 def check(self, word, src="v[2:3]", mods="", **oracle):
1461 with self.subTest(word=hex(word), src=src, mods=mods):
1462 self.assertEqual(hex(ft.run_f64("v_rcp_f64", word, src=src, mods=mods)), hex(ref_rcp_f64(word, **oracle)))
1463
1464 def test_finite_subnormal_and_infinite_inputs(self):
1465 for word in [ft.f64_bits(x) for x in self.FINITE] + list(self.SPECIAL):
1466 for sign in (0, 1 << 63):
1467 self.check(word | sign)
1468
1469 def test_source_modifiers_and_clamp(self):
1470 for x in (4.0, 0.25, 3.0):
1471 self.check(ft.f64_bits(-x), src="-v[2:3]", src0_neg=True)
1472 self.check(ft.f64_bits(-x), src="|v[2:3]|", src0_abs=True)
1473 for x in (0.25, 0.5, 4.0, 3.0):
1474 self.check(ft.f64_bits(x), mods=" clamp", clamp=True)
1475
1476
1443if __name__ == "__main__": 1477if __name__ == "__main__":
1444 unittest.main() 1478 unittest.main()
diff --git a/tests/semantic/test_valu_rsq_f64.py b/tests/semantic/test_valu_rsq_f64.py
index 6fe6efed8..10d6e1981 100644
--- a/tests/semantic/test_valu_rsq_f64.py
+++ b/tests/semantic/test_valu_rsq_f64.py
@@ -1505,5 +1505,39 @@ class TestNegativeControlsAndMutations(unittest.TestCase):
1505 self.assertAlmostEqual(rsq_4x, 0.5 * rsq_x, places=14) 1505 self.assertAlmostEqual(rsq_4x, 0.5 * rsq_x, places=14)
1506 1506
1507 1507
1508# ==============================================================================
1509# The translator: tools/rdna2spirv.py's output, run in tests/spirv_interp.py, gives the oracle's word
1510# ==============================================================================
1511import os as _os # noqa: E402
1512import sys as _sys # noqa: E402
1513
1514_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))
1515import f64_translate as ft # noqa: E402
1516
1517class TranslatorMatchesOracle(unittest.TestCase):
1518 """v_rsq_f64 is GLSL.std.450 InverseSqrt on the double (docs/design.md). On every input whose SPIR-V result is
1519 defined - no NaN, nothing at or below zero - the translated instruction gives oracle_v_rsq_f64's word."""
1520
1521 FINITE = (1.0, 2.0, 4.0, 0.25, 3.0, 10.0, 1 / 3, 0.1, 7.0, 1e300, 1e-300, 1.7976931348623157e308,
1522 2.2250738585072014e-308)
1523 SPECIAL = (0x000FFFFFFFFFFFFF, 0x7FF0000000000000) # the largest subnormal, +inf
1524
1525 def check(self, word, src="v[2:3]", mods="", **oracle):
1526 with self.subTest(word=hex(word), src=src, mods=mods):
1527 self.assertEqual(hex(ft.run_f64("v_rsq_f64", word, src=src, mods=mods)),
1528 hex(oracle_v_rsq_f64(word, **oracle)))
1529
1530 def test_positive_inputs(self):
1531 for word in [ft.f64_bits(x) for x in self.FINITE] + list(self.SPECIAL):
1532 self.check(word)
1533
1534 def test_source_modifiers_on_negative_inputs_and_clamp(self):
1535 for x in (4.0, 0.25, 2.0):
1536 self.check(ft.f64_bits(-x), src="-v[2:3]", neg_src=True)
1537 self.check(ft.f64_bits(-x), src="|v[2:3]|", abs_src=True)
1538 for x in (0.25, 4.0, 16.0):
1539 self.check(ft.f64_bits(x), mods=" clamp", clamp=True)
1540
1541
1508if __name__ == "__main__": 1542if __name__ == "__main__":
1509 unittest.main() 1543 unittest.main()
diff --git a/tests/semantic/test_valu_sqrt_f64.py b/tests/semantic/test_valu_sqrt_f64.py
index 01fbc76d0..99bde83fa 100644
--- a/tests/semantic/test_valu_sqrt_f64.py
+++ b/tests/semantic/test_valu_sqrt_f64.py
@@ -1110,5 +1110,40 @@ class TestNegativeControlsAndMutationDetection(unittest.TestCase):
1110 self.assertNotEqual(golden, mutant) 1110 self.assertNotEqual(golden, mutant)
1111 1111
1112 1112
1113# ==============================================================================
1114# The translator: tools/rdna2spirv.py's output, run in tests/spirv_interp.py, gives the oracle's word
1115# ==============================================================================
1116import os as _os # noqa: E402
1117import sys as _sys # noqa: E402
1118
1119_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))
1120import f64_translate as ft # noqa: E402
1121
1122class TranslatorMatchesOracle(unittest.TestCase):
1123 """v_sqrt_f64 is GLSL.std.450 Sqrt on the double (docs/design.md: the correctly rounded root, while RDNA2's own
1124 instruction is not). On every input whose SPIR-V result is defined - no NaN, nothing below zero - the translated
1125 instruction gives oracle_v_sqrt_f64's word."""
1126
1127 FINITE = (1.0, 2.0, 4.0, 0.25, 3.0, 10.0, 1 / 3, 0.1, 7.0, 1e300, 1e-300, 1.7976931348623157e308,
1128 2.2250738585072014e-308)
1129 SPECIAL = (0x0000000000000000, 0x0000000000000001, 0x000FFFFFFFFFFFFF, 0x7FF0000000000000) # +0, subnormals, +inf
1130
1131 def check(self, word, src="v[2:3]", mods="", **oracle):
1132 with self.subTest(word=hex(word), src=src, mods=mods):
1133 self.assertEqual(hex(ft.run_f64("v_sqrt_f64", word, src=src, mods=mods)),
1134 hex(oracle_v_sqrt_f64(word, **oracle)))
1135
1136 def test_non_negative_inputs(self):
1137 for word in [ft.f64_bits(x) for x in self.FINITE] + list(self.SPECIAL):
1138 self.check(word)
1139
1140 def test_source_modifiers_on_negative_inputs_and_clamp(self):
1141 for x in (4.0, 0.25, 2.0, 1e300):
1142 self.check(ft.f64_bits(-x), src="-v[2:3]", neg_mod=True)
1143 self.check(ft.f64_bits(-x), src="|v[2:3]|", abs_mod=True)
1144 for x in (0.25, 0.5, 4.0, 2.0):
1145 self.check(ft.f64_bits(x), mods=" clamp", clamp=True)
1146
1147
1113if __name__ == "__main__": 1148if __name__ == "__main__":
1114 unittest.main() 1149 unittest.main()
diff --git a/tests/semantic/test_vop3_clamp_nan.py b/tests/semantic/test_vop3_clamp_nan.py
new file mode 100644
index 000000000..6b4db1b94
--- /dev/null
+++ b/tests/semantic/test_vop3_clamp_nan.py
@@ -0,0 +1,137 @@
1"""VOP3 `clamp` of a NaN result gives +0 (Gen.clamp_mods).
2
3The game's MODE has DX10_CLAMP 1, and with it the clamp bit turns a NaN result into +0: measured on RDNA2 (gfx1036)
4for v_rcp_iflag_f32 (docs/shader_validation.md, "32-bit float VALU on the GPU": a NaN result +0 except with DX10_CLAMP
5off, 169 programs) and for v_fmac_f16, v_fma_mixlo_f16 and v_fma_mix_f32 (SHADER-186, "f16 output modifiers, clamp and
6v_fma_mix* operands on RDNA2").
7GLSL.std.450 leaves FClamp undefined for a NaN operand, so the translator selects +0 for a NaN before FClamp, as the
8div_fixup and cvt_pknorm clamps already did. Before that the shared helper emitted a bare FClamp, which the CPU
9interpreter refuses (UnsupportedConstruct) and which a driver may return as the NaN.
10
11Each program computes one value in v4 and exports it. The NaN comes from a NaN operand (quiet, negative, signalling)
12or from an invalid operation (inf - inf, -inf * 0); controls without a NaN check that the clamp itself is unchanged.
13Standard library only; no game data.
14"""
15import os
16import sys
17import unittest
18
19sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
20from support import mrt0_words, translate_lines # noqa: E402
21
22QNAN = 0x7FC00000
23NEG_QNAN = 0xFFC00000
24SNAN = 0x7F800001
25POS_INF = 0x7F800000
26NEG_INF = 0xFF800000
27ONE = 0x3F800000
28TWO = 0x40000000
29QUARTER = 0x3E800000
30NEG_ONE = 0xBF800000
31F16_QNAN = 0x7E00
32F16_NEG_QNAN = 0xFE00
33F16_ONE = 0x3C00
34F16_HALF = 0x3800
35
36
37def run(op_line, v1, v2, v3=0):
38 """mrt0.x after `op_line` (which writes v4) with v1..v3 set to the given words."""
39 spv = translate_lines("ps_clamp_nan", [
40 f"v_mov_b32 v1, {v1:#x}",
41 f"v_mov_b32 v2, {v2:#x}",
42 f"v_mov_b32 v3, {v3:#x}",
43 "v_mov_b32 v4, 0xdeadbeef",
44 op_line,
45 "exp mrt0 v4, v4, v4, v4 done vm",
46 "s_endpgm",
47 ])
48 return mrt0_words(spv)[0]
49
50
51class ClampNanF32Tests(unittest.TestCase):
52 def test_nan_operand_clamps_to_plus_zero(self):
53 for nan in (QNAN, NEG_QNAN, SNAN):
54 for line in ("v_add_f32_e64 v4, v1, v2 clamp",
55 "v_sub_f32_e64 v4, v1, v2 clamp",
56 "v_mul_f32_e64 v4, v1, v2 clamp",
57 "v_fma_f32 v4, v1, v2, v2 clamp",
58 "v_mul_f32_e64 v4, v1, v2 mul:2 clamp"):
59 with self.subTest(op=line, nan=hex(nan)):
60 self.assertEqual(run(line, nan, ONE), 0)
61
62 def test_invalid_operation_clamps_to_plus_zero(self):
63 self.assertEqual(run("v_sub_f32_e64 v4, v1, v2 clamp", POS_INF, POS_INF), 0) # inf - inf
64 self.assertEqual(run("v_add_f32_e64 v4, v1, v2 clamp", POS_INF, NEG_INF), 0) # inf + -inf
65 self.assertEqual(run("v_mul_f32_e64 v4, v1, v2 clamp", NEG_INF, 0), 0) # -inf * 0
66 self.assertEqual(run("v_fma_f32 v4, v1, v2, v3 clamp", POS_INF, 0, ONE), 0) # inf * 0 + 1
67
68 def test_all_nan_min_max_clamps_to_plus_zero(self):
69 # Without clamp an all-NaN min/max keeps src0's NaN (docs/design.md); the clamp then gives +0.
70 for op in ("v_min_f32_e64", "v_max_f32_e64"):
71 with self.subTest(op=op):
72 self.assertEqual(run(f"{op} v4, v1, v2 clamp", QNAN, NEG_QNAN), 0)
73 for op in ("v_min3_f32", "v_max3_f32"):
74 with self.subTest(op=op):
75 self.assertEqual(run(f"{op} v4, v1, v2, v3 clamp", QNAN, SNAN, NEG_QNAN), 0)
76
77 def test_nan_without_clamp_is_still_nan(self):
78 # The select is only on the clamp path: without clamp a NaN result stays a NaN.
79 w = run("v_add_f32_e64 v4, v1, v2", QNAN, ONE)
80 self.assertEqual(w & 0x7F800000, 0x7F800000)
81 self.assertNotEqual(w & 0x007FFFFF, 0)
82
83 def test_clamp_controls_unchanged(self):
84 self.assertEqual(run("v_add_f32_e64 v4, v1, v2 clamp", TWO, TWO), ONE)
85 self.assertEqual(run("v_add_f32_e64 v4, v1, v2 clamp", NEG_ONE, 0), 0)
86 self.assertEqual(run("v_add_f32_e64 v4, v1, v2 clamp", QUARTER, 0), QUARTER)
87 self.assertEqual(run("v_mul_f32_e64 v4, v1, v2 clamp", POS_INF, ONE), ONE)
88 self.assertEqual(run("v_mul_f32_e64 v4, v1, v2 clamp", NEG_INF, ONE), 0)
89
90
91 def test_legacy_ops_nan_clamps_to_plus_zero(self):
92 # v_mul_legacy_f32 ... clamp is the most common clamp form in the game's listings (docs/design.md).
93 self.assertEqual(run("v_mul_legacy_f32_e64 v4, v1, v2 clamp", QNAN, ONE), 0)
94 self.assertEqual(run("v_mad_legacy_f32 v4, v1, v2, v3 clamp", QNAN, ONE, 0), 0)
95
96
97# An f16 result written to the low half keeps the high half of v4 (0xdead); op_sel:[0,0,1] and v_fma_mixhi_f16 write
98# the high half and keep the low one (0xbeef).
99LO_ZERO = 0xDEAD0000
100HI_ZERO = 0x0000BEEF
101
102
103class ClampNanF16Tests(unittest.TestCase):
104 def test_f16_nan_clamps_to_plus_zero(self):
105 for nan in (F16_QNAN, F16_NEG_QNAN):
106 for line in ("v_add_f16_e64 v4, v1, v2 clamp",
107 "v_mul_f16_e64 v4, v1, v2 clamp",
108 "v_fmac_f16_e64 v4, v1, v2 clamp",
109 "v_fma_f16 v4, v1, v2, v3 clamp"):
110 with self.subTest(op=line, nan=hex(nan)):
111 self.assertEqual(run(line, nan, F16_ONE), LO_ZERO)
112
113 def test_f16_high_half_nan_clamps_to_plus_zero(self):
114 self.assertEqual(run("v_add_f16_e64 v4, v1, v2 op_sel:[0,0,1] clamp", F16_QNAN, F16_ONE), HI_ZERO)
115 self.assertEqual(run("v_fma_mixhi_f16 v4, v1, v2, v3 clamp", QNAN, ONE, 0), HI_ZERO)
116
117 def test_f16_all_nan_med3_clamps_to_plus_zero(self):
118 self.assertEqual(run("v_med3_f16 v4, v1, v2, v3 clamp", F16_QNAN, F16_NEG_QNAN, 0x7E01), LO_ZERO)
119
120 def test_conversions_nan_clamp_to_plus_zero(self):
121 self.assertEqual(run("v_cvt_f32_f16_e64 v4, v1 clamp", F16_QNAN, 0), 0)
122 self.assertEqual(run("v_cvt_f16_f32_e64 v4, v1 clamp", QNAN, 0), LO_ZERO)
123 self.assertEqual(run("v_cvt_f16_f32_e64 v4, v1 mul:2 clamp", NEG_QNAN, 0), LO_ZERO)
124
125 def test_mix_ops_nan_clamp_to_plus_zero(self):
126 # SHADER-186 measured +0 on gfx1036 for these (docs/shader_validation.md).
127 self.assertEqual(run("v_fma_mix_f32 v4, v1, v2, v3 op_sel_hi:[1,1,1] clamp", F16_QNAN, F16_ONE, 0), 0)
128 self.assertEqual(run("v_fma_mixlo_f16 v4, v1, v2, v3 clamp", QNAN, ONE, 0), LO_ZERO)
129
130 def test_f16_clamp_controls_unchanged(self):
131 self.assertEqual(run("v_add_f16_e64 v4, v1, v2 clamp", F16_ONE, F16_ONE), 0xDEAD0000 | F16_ONE)
132 self.assertEqual(run("v_add_f16_e64 v4, v1, v2 clamp", F16_HALF, 0), 0xDEAD0000 | F16_HALF)
133 self.assertEqual(run("v_fma_mixlo_f16 v4, v1, v2, v3 clamp", TWO, ONE, 0), 0xDEAD0000 | F16_ONE)
134
135
136if __name__ == "__main__":
137 unittest.main()
diff --git a/tests/semantic/test_writelane_read_before_write.py b/tests/semantic/test_writelane_read_before_write.py
new file mode 100644
index 000000000..4cad4a180
--- /dev/null
+++ b/tests/semantic/test_writelane_read_before_write.py
@@ -0,0 +1,82 @@
1"""SHADER-768: v_writelane_b32 keeps its destination's other lanes, for read_before_write_vgprs and reg_reads_writes.
2
3v_writelane_b32 vD, sSRC, sLANE writes one lane of vD and keeps every other lane's value (RDNA2 ISA; the translator's
4emission loads the old vD and selects per lane). read_before_write_vgprs counted it as a full write, so a VGPR whose
5first touch is a writelane and whose kept lanes are then read was not reported. Counting every writelane destination
6as a read is too much the other way (@shdann on #4297): a VS that spills an SGPR into one lane of v40 around the
7fetch call, and reads it back with v_readlane, would be rejected with `fetch mapping`. So the kept lanes are
8*carried*: they become a read when something other than v_readlane_b32 reads the register before a full write.
9reg_reads_writes (per slice) counts the destination as read. Standard library only; no GPU, no game files.
10"""
11import os
12import sys
13import unittest
14
15HERE = os.path.dirname(os.path.abspath(__file__))
16ROOT = os.path.dirname(os.path.dirname(HERE))
17sys.dont_write_bytecode = True
18sys.path.insert(0, os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools"))
19sys.path.insert(0, HERE)
20
21import rdna2spirv # noqa: E402
22import shader_ir # noqa: E402
23import support # noqa: E402
24
25
26def parse(*lines):
27 return [shader_ir.parse_line(ln) for ln in lines]
28
29
30def rbw(*lines):
31 return rdna2spirv.read_before_write_vgprs(parse(*lines))
32
33
34def translate(name, lines):
35 asm = support.translate_lines(name, lines)
36 return asm[0] if isinstance(asm, tuple) else asm
37
38
39VS_SPILL = ["v_writelane_b32 v40, s2, 0", "s_swappc_b64 s[4:5], s[4:5]", "v_readlane_b32 s2, v40, 0",
40 "v_mov_b32_e32 v1, s2", "exp pos0 v1, v1, v1, v1 done", "s_endpgm"]
41
42
43class WritelaneReadBeforeWrite(unittest.TestCase):
44 def test_kept_lanes_read_afterwards_are_a_read(self):
45 self.assertEqual(rbw("v_writelane_b32 v5, s1, 3", "v_mov_b32 v6, v5"), {5})
46 self.assertEqual(rbw("v_writelane_b32 v5, s1, 3", "v_writelane_b32 v5, s2, 4", "v_add_nc_u32 v6, v5, v5"),
47 {5})
48
49 def test_carried_only_is_not_a_read(self):
50 self.assertEqual(rbw("v_writelane_b32 v5, s1, 3"), set())
51 self.assertEqual(rbw("v_writelane_b32 v5, s1, 3", "v_readlane_b32 s6, v5, 3"), set()) # the spill pattern
52
53 def test_a_full_write_ends_the_carry(self):
54 self.assertEqual(rbw("v_writelane_b32 v5, s1, 3", "v_mov_b32 v5, 0", "v_mov_b32 v6, v5"), set())
55
56 def test_written_first_is_not_a_read(self):
57 self.assertEqual(rbw("v_mov_b32 v5, 0", "v_writelane_b32 v5, s1, 3", "v_mov_b32 v6, v5"), set())
58
59 def test_lane_operands_are_scalar(self):
60 self.assertEqual(rbw("v_writelane_b32 v7, 0x1234, s2", "v_mov_b32 v8, v7"), {7})
61
62 def test_reg_reads_writes_counts_the_destination(self):
63 self.assertEqual(rdna2spirv.reg_reads_writes(parse("v_writelane_b32 v5, s1, 3")), ({5}, {5}))
64
65 def test_readlane_and_fmac_unchanged(self):
66 self.assertEqual(rbw("v_readlane_b32 s5, v9, 3"), {9})
67 self.assertEqual(rbw("v_fmac_f32 v4, v1, v2"), {1, 2, 4})
68
69 def test_vs_spill_around_the_fetch_call_translates(self):
70 # shdann's listing: v40 holds a spilled SGPR in lane 0 across the fetch call; it is no vertex attribute
71 self.assertIn("OpEntryPoint", translate("vs_writelane_spill", VS_SPILL))
72 self.assertIn("OpEntryPoint", translate("vs_writelane_spill2", ["v_mov_b32_e32 v40, 0"] + VS_SPILL))
73
74 def test_ps_kept_lanes_of_v0_get_the_barycentric(self):
75 # the other lanes of v0 keep the hardware's barycentric i and v_mov reads them, so v0 is a PS input
76 asm = translate("ps_writelane_v0", ["v_writelane_b32 v0, s2, 0", "v_mov_b32_e32 v20, v0",
77 "exp mrt0 v20, v20, v20, v20 done vm", "s_endpgm"])
78 self.assertIn("BaryCoord", asm)
79
80
81if __name__ == "__main__":
82 unittest.main()
diff --git a/tests/spirv_interp.py b/tests/spirv_interp.py
index 004fde4ec..e70bc6c8a 100644
--- a/tests/spirv_interp.py
+++ b/tests/spirv_interp.py
@@ -205,7 +205,11 @@ def run(spvasm):
205 "OpIEqual": lambda a, b: a == b, "OpINotEqual": lambda a, b: a != b, 205 "OpIEqual": lambda a, b: a == b, "OpINotEqual": lambda a, b: a != b,
206 } 206 }
207 207
208 F64 = {"OpFAdd": lambda a, b: a + b, "OpFSub": lambda a, b: a - b, "OpFMul": lambda a, b: a * b} 208 # Without an entry here a binary64 op falls through to ARITH and is rounded to binary32: until OpFDiv was added,
209 # the translated v_rcp_f64 of 3.0 gave 0x3fd5555560000000 (1/3 as a binary32) and of 1e300 gave 0.
210 F64 = {"OpFAdd": lambda a, b: a + b, "OpFSub": lambda a, b: a - b, "OpFMul": lambda a, b: a * b,
211 "OpFDiv": lambda a, b: a / b if b else
212 math.copysign(math.inf, math.copysign(1.0, a) * math.copysign(1.0, b)) if a and not math.isnan(a) else math.nan}
209 213
210 def float_bits(rt): 214 def float_bits(rt):
211 t = types.get(rt) 215 t = types.get(rt)
@@ -331,6 +335,11 @@ def run(spvasm):
331 elif op == "OpConvertSToF": 335 elif op == "OpConvertSToF":
332 x = float(s32(get(args[1]))) 336 x = float(s32(get(args[1])))
333 val[res] = x if float_bits(args[0]) == 64 else f32(x) 337 val[res] = x if float_bits(args[0]) == 64 else f32(x)
338 elif op == "OpFConvert":
339 # binary64 -> binary32 rounds to nearest even (past the binary32 range: infinity); binary32 -> binary64 is
340 # exact. v_cvt_f32_f64 and v_cvt_f64_f32 are this.
341 x = float(get(args[1]))
342 val[res] = x if float_bits(args[0]) == 64 else f32(x)
334 elif op == "OpConvertFToU": 343 elif op == "OpConvertFToU":
335 x = get(args[1]); val[res] = 0 if math.isnan(x) or x <= 0 else M32 if x >= 2**32 else int(x) 344 x = get(args[1]); val[res] = 0 if math.isnan(x) or x <= 0 else M32 if x >= 2**32 else int(x)
336 elif op == "OpConvertFToS": 345 elif op == "OpConvertFToS":
diff --git a/tests/test_awc_manifest.py b/tests/test_awc_manifest.py
index dde858620..346b23b38 100644
--- a/tests/test_awc_manifest.py
+++ b/tests/test_awc_manifest.py
@@ -358,6 +358,8 @@ class ManifestTest(unittest.TestCase):
358 def test_read_only_manifest_is_refused_without_staging_a_file(self): 358 def test_read_only_manifest_is_refused_without_staging_a_file(self):
359 # The writer opens the destination for writing first, to keep the direct writer's permission check. A 359 # The writer opens the destination for writing first, to keep the direct writer's permission check. A
360 # read-only manifest raises there, before anything is staged, so the directory stays as it was. 360 # read-only manifest raises there, before anything is staged, so the directory stays as it was.
361 if os.name != "nt" and os.geteuid() == 0:
362 self.skipTest("root bypasses read-only file mode")
361 out = os.path.join(self.tmp.name, "manifest.json") 363 out = os.path.join(self.tmp.name, "manifest.json")
362 previous = '{"previous": true}\n' 364 previous = '{"previous": true}\n'
363 with open(out, "w", encoding="utf-8") as f: 365 with open(out, "w", encoding="utf-8") as f:
diff --git a/tests/test_batch_glb.py b/tests/test_batch_glb.py
index 6cc3bd416..58753cbcf 100644
--- a/tests/test_batch_glb.py
+++ b/tests/test_batch_glb.py
@@ -57,11 +57,34 @@ class TestBatchGlb(unittest.TestCase):
57 [sys.executable, "-I", os.path.join(TOOLS, "batch_glb.py"), source, output], 57 [sys.executable, "-I", os.path.join(TOOLS, "batch_glb.py"), source, output],
58 capture_output=True, text=True, errors="replace", check=False, 58 capture_output=True, text=True, errors="replace", check=False,
59 ) 59 )
60 self.assertEqual(result.returncode, 1) 60 self.assertEqual(result.returncode, 2)
61 self.assertTrue(result.stderr.startswith("ERROR: "), result.stderr) 61 self.assertTrue(result.stderr.startswith("ERROR: "), result.stderr)
62 self.assertIn(error, result.stderr) 62 self.assertIn(error, result.stderr)
63 self.assertEqual(len(result.stderr.splitlines()), 1) 63 self.assertEqual(len(result.stderr.splitlines()), 1)
64 64
65 def test_cli_exit_status_follows_the_docstring(self) -> None:
66 script = os.path.join(TOOLS, "batch_glb.py")
67 with tempfile.TemporaryDirectory() as root:
68 empty = os.path.join(root, "empty")
69 broken = os.path.join(root, "broken")
70 os.mkdir(empty)
71 os.mkdir(broken)
72 with open(os.path.join(broken, "broken.obj"), "w", encoding="utf-8", newline="\n") as f:
73 f.write("o broken\nf 1 2 3\n")
74
75 cases = [
76 ("empty input folder: no model failed", [empty, os.path.join(root, "out_empty")], 0),
77 ("one model failed", [broken, os.path.join(root, "out_broken")], 1),
78 ("usage error", ["--bogus"], 2),
79 ]
80 for label, args, expected in cases:
81 with self.subTest(case=label):
82 result = subprocess.run(
83 [sys.executable, "-I", script, *args],
84 capture_output=True, text=True, errors="replace", check=False,
85 )
86 self.assertEqual(result.returncode, expected, result.stdout + result.stderr)
87
65 def test_cli_rejects_invalid_jobs_and_max_tex_size(self) -> None: 88 def test_cli_rejects_invalid_jobs_and_max_tex_size(self) -> None:
66 with tempfile.TemporaryDirectory() as root: 89 with tempfile.TemporaryDirectory() as root:
67 for flag, value, error in [ 90 for flag, value, error in [
diff --git a/tests/test_bink_play_cache_write.py b/tests/test_bink_play_cache_write.py
new file mode 100644
index 000000000..1e01e7bfc
--- /dev/null
+++ b/tests/test_bink_play_cache_write.py
@@ -0,0 +1,87 @@
1"""Synthetic failure and overlap checks for the movie-name cache writer; no game data.
2
3 python -I tests/test_bink_play_cache_write.py
4"""
5import os
6from pathlib import Path
7import sys
8import tempfile
9import unittest
10from unittest import mock
11
12ROOT = Path(__file__).resolve().parents[1]
13sys.path.insert(0, str(ROOT / "tools"))
14import bink_play # noqa: E402
15
16
17class CachePublicationTest(unittest.TestCase):
18 def setUp(self):
19 temporary = tempfile.TemporaryDirectory()
20 self.addCleanup(temporary.cleanup)
21 self.directory = Path(temporary.name)
22 self.archive, self.mount = self.directory / "source.csv", self.directory / "mount.xml"
23 self.archive.write_bytes(b"synthetic source")
24 self.mount.write_bytes(b"synthetic mount")
25 self.cache = self.directory / "cache" / "names.csv"
26 self.cache.parent.mkdir()
27 self.previous = b"previous cache"
28 self.cache.write_bytes(self.previous)
29 self.neighbor = self.cache.parent / "bink_names.unrelated.part"
30 self.neighbor.write_bytes(b"another writer's file")
31 cache_patch = mock.patch.object(bink_play, "cache_path", return_value=self.cache)
32 cache_patch.start()
33 self.addCleanup(cache_patch.stop)
34 names_patch = mock.patch.object(bink_play.bink_names, "main", side_effect=self.generate)
35 names_patch.start()
36 self.addCleanup(names_patch.stop)
37
38 @staticmethod
39 def generate(argv):
40 Path(argv[argv.index("--out") + 1]).write_text(
41 "path,offset,width,height,frames\nsynthetic.bk2,32,16,16,2\n",
42 encoding="utf-8", newline="\n")
43 return 0
44
45 def assert_no_staging_files(self):
46 self.assertEqual(set(self.cache.parent.iterdir()), {self.cache, self.neighbor})
47 self.assertEqual(self.neighbor.read_bytes(), b"another writer's file")
48
49 def test_cache_write_failure_removes_only_its_staging_file(self):
50 with mock.patch.object(bink_play.csv, "writer", side_effect=OSError("write failed")):
51 with self.assertRaisesRegex(OSError, "write failed"):
52 bink_play.load_names(self.archive, self.mount)
53 self.assertEqual(self.cache.read_bytes(), self.previous)
54 self.assert_no_staging_files()
55
56 def test_replace_failure_or_interruption_removes_only_its_staging_file(self):
57 for error in (PermissionError("replace failed"), KeyboardInterrupt()):
58 with self.subTest(error=type(error).__name__):
59 with mock.patch.object(bink_play.os, "replace", side_effect=error):
60 with self.assertRaises(type(error)):
61 bink_play.load_names(self.archive, self.mount)
62 self.assertEqual(self.cache.read_bytes(), self.previous)
63 self.assert_no_staging_files()
64
65 def test_failed_outer_save_preserves_another_writers_published_cache(self):
66 real_replace = os.replace
67 staged = []
68
69 def interleave(source, destination):
70 staged.append(source)
71 if len(staged) == 1:
72 self.assertEqual(bink_play.load_names(self.archive, self.mount),
73 [("synthetic.bk2", 32, "16", "16", "2")])
74 raise PermissionError("outer save failed")
75 real_replace(source, destination)
76
77 with mock.patch.object(bink_play.os, "replace", side_effect=interleave):
78 with self.assertRaisesRegex(PermissionError, "outer save failed"):
79 bink_play.load_names(self.archive, self.mount)
80 self.assertEqual(len(set(staged)), 2)
81 key = bink_play.stamp(self.archive) + "|" + bink_play.stamp(self.mount)
82 self.assertEqual(bink_play._read_cache(self.cache, key), [("synthetic.bk2", 32, "16", "16", "2")])
83 self.assert_no_staging_files()
84
85
86if __name__ == "__main__":
87 unittest.main()
diff --git a/tests/test_boot_trace.py b/tests/test_boot_trace.py
index f8e042a59..42104ec98 100644
--- a/tests/test_boot_trace.py
+++ b/tests/test_boot_trace.py
@@ -540,6 +540,7 @@ class BootTraceTests(unittest.TestCase):
540 for needle in ( 540 for needle in (
541 "pid 123", 541 "pid 123",
542 "modules (2)", 542 "modules (2)",
543 "game.exe, x.dll (relocated)",
543 "dllmain: 1 ok, 1 failed", 544 "dllmain: 1 ok, 1 failed",
544 "unimplemented: 2 unique", 545 "unimplemented: 2 unique",
545 "x.dll!Foo from game.exe+0x10", 546 "x.dll!Foo from game.exe+0x10",
@@ -646,6 +647,19 @@ class BootTraceTests(unittest.TestCase):
646 else: 647 else:
647 self.assertNotIn("more", text) 648 self.assertNotIn("more", text)
648 649
650 def test_counts_only_includes_all_xmem_physical_page_observations(self):
651 self.write(self.startup, [
652 {"kind": "xmem_physical_pages", "api": "private-api", "attributes": "0x20",
653 "pages": 4, "caller": "private-caller"},
654 ] * 3)
655 out = io.StringIO()
656 with contextlib.redirect_stdout(out):
657 self.assertEqual(bt.main([self.startup, "--counts-only", "--limit", "1"]), 0)
658 summary = json.loads(out.getvalue())["startup"]
659 self.assertEqual(summary["xmem_physical_pages_count"], 3)
660 self.assertNotIn("xmem_physical_pages", summary)
661 self.assertNotIn("private-", out.getvalue())
662
649 def test_xmem_physical_pages_handles_missing_and_malformed_fields(self): 663 def test_xmem_physical_pages_handles_missing_and_malformed_fields(self):
650 unknown = {"api": None, "attributes": None, "pages": None, "caller": None} 664 unknown = {"api": None, "attributes": None, "pages": None, "caller": None}
651 nbsp_caller = "fixture\u00a0one.dll+0x20" 665 nbsp_caller = "fixture\u00a0one.dll+0x20"
@@ -665,6 +679,42 @@ class BootTraceTests(unittest.TestCase):
665 self.assertIn(" XMemAllocatePhysicalPages attributes 0x10 requested ? pages from fixture.dll+0x50\n", text) 679 self.assertIn(" XMemAllocatePhysicalPages attributes 0x10 requested ? pages from fixture.dll+0x50\n", text)
666 self.assertIn(f" XMemAllocatePhysicalPages attributes 0x20 requested 4 pages from {nbsp_caller}\n", text) 680 self.assertIn(f" XMemAllocatePhysicalPages attributes 0x20 requested 4 pages from {nbsp_caller}\n", text)
667 681
682 def test_frame_pacing_summary_parsed_formatted_and_kept_in_counts_only(self):
683 self.write_lines(self.d3d12, [
684 "[d3d12-trace] #1 XboxPresentation::PresentX ok",
685 "gta6rt.exe : [rt] present: pacing summary frames=101 samples=100 target_us=16667 "
686 "mean_us=16712.5 drift_us=+45.5 p50_us=16667 p95_us=17100 p99_us=18200 "
687 "latency_samples=101 latency_p50_us=4200 latency_p95_us=6100 latency_p99_us=7900",
688 ])
689 trace = bt.parse_d3d12(self.d3d12)
690 self.assertEqual(trace["ignored_lines"], 0)
691 self.assertEqual(trace["frame_pacing"], {
692 "frames": 101,
693 "samples": 100,
694 "target_us": 16667,
695 "mean_us": 16712.5,
696 "drift_us": 45.5,
697 "p50_us": 16667,
698 "p95_us": 17100,
699 "p99_us": 18200,
700 "latency_samples": 101,
701 "latency_p50_us": 4200,
702 "latency_p95_us": 6100,
703 "latency_p99_us": 7900,
704 })
705 text = bt.format_text(bt.summarize(None, trace), 10)
706 self.assertIn(
707 "frame pacing: 101 frame(s), 100 interval(s), target 16667 us, mean 16712.5 us (drift +45.5 us), "
708 "p50/p95/p99 16667/17100/18200 us; origin-to-present p50/p95/p99 4200/6100/7900 us",
709 text,
710 )
711 out = io.StringIO()
712 with contextlib.redirect_stdout(out):
713 self.assertEqual(bt.main(["--d3d12", self.d3d12, "--counts-only"]), 0)
714 counts = json.loads(out.getvalue())
715 self.assertEqual(counts["d3d12"]["frame_pacing"]["drift_us"], 45.5)
716 self.assertEqual(counts["d3d12"]["frame_pacing"]["p99_us"], 18200)
717
668 718
669if __name__ == "__main__": 719if __name__ == "__main__":
670 unittest.main() 720 unittest.main()
diff --git a/tests/test_bvh_shaders_stage.py b/tests/test_bvh_shaders_stage.py
index 60d16a138..a732b1c99 100644
--- a/tests/test_bvh_shaders_stage.py
+++ b/tests/test_bvh_shaders_stage.py
@@ -386,7 +386,7 @@ class ShadersStageWithTheDlls(unittest.TestCase):
386 386
387 def fake_translate(disasm, spirv, jobs, emulate=False, fallbacks=()): 387 def fake_translate(disasm, spirv, jobs, emulate=False, fallbacks=()):
388 ran.append("translate") 388 ran.append("translate")
389 write("", spirv, "index.json") 389 write('{"shader": {"stage": "vs"}}', spirv, "index.json")
390 390
391 def stage(): 391 def stage():
392 ran.clear() 392 ran.clear()
diff --git a/tests/test_check_no_game_data.py b/tests/test_check_no_game_data.py
index de35ccdea..f250f2525 100644
--- a/tests/test_check_no_game_data.py
+++ b/tests/test_check_no_game_data.py
@@ -181,8 +181,8 @@ PASSED_ARCHIVES = [
181] 181]
182 182
183 183
184def run(args, cwd=None): 184def run(args, cwd=None, env=None):
185 return subprocess.run([sys.executable, "-I", SCRIPT, *args], cwd=cwd, capture_output=True, text=True) 185 return subprocess.run([sys.executable, "-I", SCRIPT, *args], cwd=cwd, env=env, capture_output=True, text=True)
186 186
187 187
188class CheckNoGameData(unittest.TestCase): 188class CheckNoGameData(unittest.TestCase):
@@ -304,6 +304,35 @@ class CheckNoGameData(unittest.TestCase):
304 self.assertEqual(rc, 1, out + err) 304 self.assertEqual(rc, 1, out + err)
305 self.assertIn("PE executable", out) 305 self.assertIn("PE executable", out)
306 306
307 def test_git_missing_is_one_stderr_line_and_exit_2(self):
308 # PATH holds no git: the default mode cannot list the tracked files, and that is not "game data found" (1)
309 empty = os.path.join(self.dir, "empty-bin")
310 os.mkdir(empty)
311 self.write("notes.txt", b"plain text\n")
312 result = run([], cwd=self.dir, env=dict(os.environ, PATH=empty))
313 self.assertEqual(result.returncode, 2, result.stdout + result.stderr)
314 self.assertEqual(result.stdout, "")
315 self.assertEqual(len(result.stderr.splitlines()), 1, result.stderr)
316 self.assertTrue(result.stderr.startswith("check_no_game_data: cannot list the tracked files with git: "),
317 result.stderr)
318 self.assertNotIn("Traceback", result.stderr)
319
320 def test_outside_a_repository_is_one_stderr_line_and_exit_2(self):
321 # GIT_CEILING_DIRECTORIES stops git from finding a repository above the temporary directory, and LC_ALL=C
322 # keeps git's message in English; a GIT_DIR, GIT_WORK_TREE or GIT_INDEX_FILE of the caller would point git at a
323 # repository anyway (a git hook sets them), so they are removed
324 self.write("notes.txt", b"plain text\n")
325 env = {k: v for k, v in os.environ.items() if k not in ("GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE")}
326 env.update(GIT_CEILING_DIRECTORIES=os.path.dirname(self.dir), LC_ALL="C")
327 result = run([], cwd=self.dir, env=env)
328 self.assertEqual(result.returncode, 2, result.stdout + result.stderr)
329 self.assertEqual(result.stdout, "")
330 self.assertEqual(len(result.stderr.splitlines()), 1, result.stderr)
331 self.assertTrue(result.stderr.startswith("check_no_game_data: cannot list the tracked files with git: "),
332 result.stderr)
333 self.assertIn("not a git repository", result.stderr)
334 self.assertNotIn("Traceback", result.stderr)
335
307 @unittest.skipUnless(shutil.which("git"), "git not installed") 336 @unittest.skipUnless(shutil.which("git"), "git not installed")
308 def test_default_mode_reads_tracked_files_only(self): 337 def test_default_mode_reads_tracked_files_only(self):
309 git = ["git", "-c", "init.defaultBranch=main"] 338 git = ["git", "-c", "init.defaultBranch=main"]
diff --git a/tests/test_check_sparse_queue_family.py b/tests/test_check_sparse_queue_family.py
index 630b8bbfb..9e98d33a2 100644
--- a/tests/test_check_sparse_queue_family.py
+++ b/tests/test_check_sparse_queue_family.py
@@ -138,6 +138,63 @@ CONCURRENT_TRACE = (checker.SPARSE_FLAGS + ")\n"
138 " pQueueFamilyIndices[1]: const uint32_t = 1\n") * 6 138 " pQueueFamilyIndices[1]: const uint32_t = 1\n") * 6
139 139
140 140
141def make_queue_trace(pdev: str, families: list[tuple[int, int, tuple[int, int, int]]],
142 created_families: int, buffers: str, *, graphics_family: int = 0) -> str:
143 entries = []
144 for i, (flags, count, (w, h, d)) in enumerate(families):
145 entries.append(
146 f" pQueueFamilyProperties[{i}]: VkQueueFamilyProperties = 0x{i:x}:\n"
147 f" queueFlags: VkQueueFlags = {flags}\n"
148 f" queueCount: uint32_t = {count}\n"
149 f" minImageTransferGranularity: VkExtent3D = 0:\n"
150 f" width: uint32_t = {w}\n"
151 f" height: uint32_t = {h}\n"
152 f" depth: uint32_t = {d}\n"
153 )
154 return (
155 "vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, pQueueFamilyPropertyCount, pQueueFamilyProperties) returns void:\n"
156 "<before calling into implementation>\n"
157 f" physicalDevice: VkPhysicalDevice = {pdev}\n"
158 "<after returning from implementation>\n"
159 f" physicalDevice: VkPhysicalDevice = {pdev}\n"
160 f" pQueueFamilyPropertyCount: uint32_t* = {len(families)}\n"
161 + "".join(entries)
162 + "vkCreateDevice(physicalDevice, pCreateInfo, pAllocator, pDevice) returns VkResult:\n"
163 "<before calling into implementation>\n"
164 f" physicalDevice: VkPhysicalDevice = {pdev}\n"
165 f" queueCreateInfoCount: uint32_t = {created_families}\n"
166 " pQueueCreateInfos[0]: const VkDeviceQueueCreateInfo = 0x1:\n"
167 f" queueFamilyIndex: uint32_t = {graphics_family}\n"
168 + buffers
169 )
170
171
172SINGLE_FAMILY_TRACE = make_queue_trace(
173 "000002C74B774620",
174 [(15, 1, (1, 1, 1)), (32, 2, (1, 1, 1))], # graphics+compute+transfer+sparse, plus video-decode only
175 created_families=1,
176 buffers=EXCLUSIVE_TRACE,
177)
178NO_ASYNC_SPARSE_TRACE = make_queue_trace(
179 "000002C74B774620",
180 [(15, 1, (1, 1, 1)), (6, 2, (1, 1, 1)), (4, 1, (1, 1, 1))], # async compute & copy lack SPARSE_BINDING_BIT (8)
181 created_families=1,
182 buffers=EXCLUSIVE_TRACE,
183)
184MULTI_FAMILY_DROPPED_TRACE = make_queue_trace(
185 "000001C77C556640",
186 [(15, 16, (1, 1, 1)), (12, 2, (1, 1, 1)), (14, 8, (1, 1, 1))],
187 created_families=1,
188 buffers=EXCLUSIVE_TRACE,
189)
190MULTI_FAMILY_OK_TRACE = make_queue_trace(
191 "000001C77C556640",
192 [(15, 16, (1, 1, 1)), (12, 2, (1, 1, 1)), (14, 8, (1, 1, 1))],
193 created_families=3,
194 buffers=CONCURRENT_TRACE,
195)
196
197
141class TraceTest(unittest.TestCase): 198class TraceTest(unittest.TestCase):
142 def check(self, text): 199 def check(self, text):
143 with tempfile.TemporaryDirectory() as td: 200 with tempfile.TemporaryDirectory() as td:
@@ -221,6 +278,139 @@ class MainTest(unittest.TestCase):
221 self.assertEqual(len(calls), 2) 278 self.assertEqual(len(calls), 2)
222 self.assertEqual([c.get("VK_INSTANCE_LAYERS") for c in calls], ["VK_LAYER_LUNARG_api_dump", None]) 279 self.assertEqual([c.get("VK_INSTANCE_LAYERS") for c in calls], ["VK_LAYER_LUNARG_api_dump", None])
223 280
281 def run_main_with_trace(self, trace: str, *, extra_argv: list[str] | None = None,
282 validation_out: str = PASS_OUT) -> int:
283 def fake_run(argv, cwd, env, **kwargs):
284 if env.get("VK_INSTANCE_LAYERS") == "VK_LAYER_LUNARG_api_dump":
285 (Path(cwd) / "sparse_create_info.log").write_text(trace, encoding="utf-8")
286 return Completed(0, PASS_OUT)
287 return Completed(0, validation_out)
288
289 with tempfile.TemporaryDirectory() as td:
290 exe = Path(td) / "t.exe"
291 exe.write_bytes(b"")
292 with mock.patch.object(checker.subprocess, "run", side_effect=fake_run), \
293 mock.patch.object(sys, "argv", ["check", str(exe), *(extra_argv or [])]), \
294 contextlib.redirect_stdout(io.StringIO()):
295 return checker.main()
296
297 def test_single_sparse_family_device_skips_with_77(self) -> None:
298 self.assertEqual(self.run_main_with_trace(SINGLE_FAMILY_TRACE), 77)
299 self.assertEqual(self.run_main_with_trace(NO_ASYNC_SPARSE_TRACE), 77)
300
301 def test_single_sparse_family_baseline_mode_skips_with_77(self) -> None:
302 self.assertEqual(self.run_main_with_trace(SINGLE_FAMILY_TRACE, extra_argv=["--expect-baseline-exclusive"]), 77)
303
304 def test_multi_sparse_family_device_creating_one_family_still_fails(self) -> None:
305 with self.assertRaises(AssertionError):
306 self.run_main_with_trace(MULTI_FAMILY_DROPPED_TRACE)
307
308 def test_single_family_device_with_concurrent_buffers_fails(self) -> None:
309 bad = make_queue_trace("000002C74B774620", [(15, 1, (1, 1, 1))], created_families=1, buffers=CONCURRENT_TRACE)
310 with self.assertRaises(AssertionError):
311 self.run_main_with_trace(bad)
312
313 def test_single_family_device_validation_error_still_fails(self) -> None:
314 with self.assertRaises(AssertionError):
315 self.run_main_with_trace(
316 SINGLE_FAMILY_TRACE,
317 validation_out=PASS_OUT + "Validation Error: [ VUID-vkCmdDraw-None-02699 ] synthetic\n",
318 )
319
320 def test_multi_family_device_passes_concurrent_contract(self) -> None:
321 self.assertEqual(self.run_main_with_trace(MULTI_FAMILY_OK_TRACE), 0)
322
323 def test_non_sparse_async_compute_ahead_of_sparse_compute_skips_with_77(self) -> None:
324 # Mirrors queue_families.h: pick_queue_families chooses the first async compute family ([1]) and
325 # sparse_capable_queue_families falls back to graphics ([0]) when [1] lacks SPARSE_BINDING_BIT.
326 trace = make_queue_trace(
327 "000002C74B774620",
328 [(15, 1, (1, 1, 1)), (6, 2, (1, 1, 1)), (14, 2, (1, 1, 1))],
329 created_families=1,
330 buffers=EXCLUSIVE_TRACE,
331 )
332 self.assertEqual(self.run_main_with_trace(trace), 77)
333 # Zero-count non-sparse compute is skipped by pick_queue_families, so [2] is selected and 1 family must fail.
334 zero_count = make_queue_trace(
335 "000002C74B774620",
336 [(15, 1, (1, 1, 1)), (6, 0, (1, 1, 1)), (14, 2, (1, 1, 1))],
337 created_families=1,
338 buffers=EXCLUSIVE_TRACE,
339 )
340 with self.assertRaises(AssertionError):
341 self.run_main_with_trace(zero_count)
342
343 def test_non_sparse_dma_ahead_of_sparse_dma_skips_with_77(self) -> None:
344 # Mirrors queue_families.h: pick_queue_families chooses the first fine-grained DMA family ([1]) and
345 # sparse_capable_queue_families falls back to graphics ([0]) when [1] lacks SPARSE_BINDING_BIT.
346 trace = make_queue_trace(
347 "000002C74B774620",
348 [(15, 1, (1, 1, 1)), (4, 1, (1, 1, 1)), (12, 1, (1, 1, 1))],
349 created_families=1,
350 buffers=EXCLUSIVE_TRACE,
351 )
352 self.assertEqual(self.run_main_with_trace(trace), 77)
353 # Coarse-grained non-sparse DMA ([1]) is not chosen, so fine-grained sparse DMA ([2]) is picked -> must fail.
354 coarse_first = make_queue_trace(
355 "000002C74B774620",
356 [(15, 1, (1, 1, 1)), (4, 1, (2, 2, 1)), (12, 1, (1, 1, 1))],
357 created_families=1,
358 buffers=EXCLUSIVE_TRACE,
359 )
360 with self.assertRaises(AssertionError):
361 self.run_main_with_trace(coarse_first)
362 # Non-sparse compute ([1]) + fine-grained sparse DMA ([2]) still leaves copy=[2] -> must fail.
363 mixed = make_queue_trace(
364 "000002C74B774620",
365 [(15, 1, (1, 1, 1)), (6, 2, (1, 1, 1)), (12, 1, (1, 1, 1))],
366 created_families=1,
367 buffers=EXCLUSIVE_TRACE,
368 )
369 with self.assertRaises(AssertionError):
370 self.run_main_with_trace(mixed)
371
372 def test_incomplete_queue_family_dump_fails(self) -> None:
373 two_family = make_queue_trace(
374 "000002C74B774620",
375 [(15, 1, (1, 1, 1)), (14, 2, (1, 1, 1))],
376 created_families=1,
377 buffers=EXCLUSIVE_TRACE,
378 )
379 head, tail = two_family.split(" pQueueFamilyProperties[1]:", 1)
380 tail_entry, rest = tail.split("vkCreateDevice(", 1)
381 count_query = (
382 "vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, pQueueFamilyPropertyCount, pQueueFamilyProperties) returns void:\n"
383 "<before calling into implementation>\n"
384 " physicalDevice: VkPhysicalDevice = 000002C74B774620\n"
385 "<after returning from implementation>\n"
386 " physicalDevice: VkPhysicalDevice = 000002C74B774620\n"
387 " pQueueFamilyPropertyCount: uint32_t* = 2\n"
388 " pQueueFamilyProperties: VkQueueFamilyProperties* = NULL\n"
389 )
390 one_family_trace = make_queue_trace(
391 "000002C74B774620",
392 [(15, 1, (1, 1, 1))],
393 created_families=1,
394 buffers=EXCLUSIVE_TRACE,
395 )
396 broken = {
397 "missing extent fields on entry 1": (
398 head + " pQueueFamilyProperties[1]:"
399 + tail_entry.split(" minImageTransferGranularity:", 1)[0]
400 + "vkCreateDevice(" + rest
401 ),
402 "entry 1 dropped while count=2": head + "vkCreateDevice(" + rest,
403 "duplicate index 0 instead of 1": two_family.replace("pQueueFamilyProperties[1]:", "pQueueFamilyProperties[0]:", 1),
404 "out-of-range index 2": two_family.replace("pQueueFamilyProperties[1]:", "pQueueFamilyProperties[2]:", 1),
405 "missing pQueueFamilyPropertyCount": SINGLE_FAMILY_TRACE.replace(
406 " pQueueFamilyPropertyCount: uint32_t* = 2\n", "", 1
407 ),
408 "partial dump smaller than count query": count_query + one_family_trace,
409 }
410 for name, trace in broken.items():
411 with self.subTest(name), self.assertRaises(AssertionError):
412 self.run_main_with_trace(trace)
413
224 414
225if __name__ == "__main__": 415if __name__ == "__main__":
226 unittest.main() 416 unittest.main()
diff --git a/tests/test_ci_expected_failures.py b/tests/test_ci_expected_failures.py
index 9603545e6..73c53b71b 100644
--- a/tests/test_ci_expected_failures.py
+++ b/tests/test_ci_expected_failures.py
@@ -7,6 +7,7 @@ from __future__ import annotations
7import contextlib 7import contextlib
8import io 8import io
9from pathlib import Path 9from pathlib import Path
10import subprocess
10import sys 11import sys
11import tempfile 12import tempfile
12import unittest 13import unittest
@@ -65,6 +66,9 @@ class Main(unittest.TestCase):
65 self.assertEqual(self.run_main("\nxdxr_build_check\n\n", "8", "xdxr_build_check"), 0) 66 self.assertEqual(self.run_main("\nxdxr_build_check\n\n", "8", "xdxr_build_check"), 0)
66 self.assertEqual(self.run_main("a\nb\n", "8", "a"), 1) 67 self.assertEqual(self.run_main("a\nb\n", "8", "a"), 1)
67 68
69 def test_a_utf8_bom_is_not_part_of_the_first_failure_name(self):
70 self.assertEqual(self.run_main("\ufeffknown\n", "8", "known"), 0)
71
68 def test_an_expected_argument_can_hold_several_names(self): 72 def test_an_expected_argument_can_hold_several_names(self):
69 self.assertEqual(self.run_main("a\nb\n", "8", " a b\n"), 0) 73 self.assertEqual(self.run_main("a\nb\n", "8", " a b\n"), 0)
70 self.assertEqual(self.run_main("a\nb\n", "8", ""), 1) 74 self.assertEqual(self.run_main("a\nb\n", "8", ""), 1)
@@ -88,6 +92,19 @@ class Main(unittest.TestCase):
88 self.assertEqual(err.getvalue().count("\n"), 1) 92 self.assertEqual(err.getvalue().count("\n"), 1)
89 self.assertIn(str(missing), err.getvalue()) 93 self.assertIn(str(missing), err.getvalue())
90 94
95 def test_an_invalid_utf8_list_is_one_input_error(self):
96 with tempfile.TemporaryDirectory() as tmp:
97 path = Path(tmp) / "failed.txt"
98 path.write_bytes(b"\xffknown\n")
99 result = subprocess.run(
100 [sys.executable, "-I", str(SCRIPTS / "ci_expected_failures.py"), str(path), "8"],
101 capture_output=True, text=True, errors="replace", timeout=10,
102 )
103 self.assertEqual(result.returncode, 2, result.stderr)
104 self.assertEqual(result.stderr.count("\n"), 1)
105 self.assertIn(path.name, result.stderr)
106 self.assertIn("utf-8", result.stderr.lower())
107
91 def test_a_non_integer_status_is_one_error_line(self): 108 def test_a_non_integer_status_is_one_error_line(self):
92 with tempfile.TemporaryDirectory() as tmp: 109 with tempfile.TemporaryDirectory() as tmp:
93 path = Path(tmp) / "failed.txt" 110 path = Path(tmp) / "failed.txt"
diff --git a/tests/test_cmake_translator_deps.py b/tests/test_cmake_translator_deps.py
index 32ecb40b1..e3af66bcc 100644
--- a/tests/test_cmake_translator_deps.py
+++ b/tests/test_cmake_translator_deps.py
@@ -3,7 +3,8 @@
3They used to list only build.py, compute_fixture.py, rdna2spirv.py and their .asm files, so an edit to a module the 3They used to list only build.py, compute_fixture.py, rdna2spirv.py and their .asm files, so an edit to a module the
4translator imports (tools/spirv_asm.py, spirv_asm_tables.py, shader_ir.py, ...) left the last build's SPIR-V in place 4translator imports (tools/spirv_asm.py, spirv_asm_tables.py, shader_ir.py, ...) left the last build's SPIR-V in place
5(old #3752, BUILD-1064). The rules now depend on LEONIDA_TRANSLATOR_DEPS (runtime/cmake/translator_deps.cmake); this 5(old #3752, BUILD-1064). The rules now depend on LEONIDA_TRANSLATOR_DEPS (runtime/cmake/translator_deps.cmake); this
6checks that list against what build.py reaches. No compiler needed; the cmake -P case is skipped without cmake. 6checks the imports of build.py and the native catalog writer. No compiler is needed. The cmake -P check runs when
7cmake is on PATH.
7""" 8"""
8import ast 9import ast
9import os 10import os
@@ -33,11 +34,12 @@ def listed():
33 34
34 35
35def reached(): 36def reached():
36 """build.py, the tools scripts it runs (named by a string literal) and every local module they import.""" 37 """build.py, the scripts it runs, the native shader catalog and their transitive local imports."""
37 tree = ast.parse(BUILD_PY.read_text(encoding="utf-8")) 38 tree = ast.parse(BUILD_PY.read_text(encoding="utf-8"))
38 todo = [BUILD_PY] + [TOOLS / n.value for n in ast.walk(tree) 39 todo = [BUILD_PY, TOOLS / "native_pso_hashes.py"]
39 if isinstance(n, ast.Constant) and isinstance(n.value, str) 40 todo.extend(TOOLS / n.value for n in ast.walk(tree)
40 and n.value.endswith(".py") and (TOOLS / n.value).is_file()] 41 if isinstance(n, ast.Constant) and isinstance(n.value, str)
42 and n.value.endswith(".py") and (TOOLS / n.value).is_file())
41 seen = set() 43 seen = set()
42 while todo: 44 while todo:
43 path = todo.pop() 45 path = todo.pop()
@@ -60,7 +62,7 @@ def reached():
60 62
61 63
62class TranslatorDepsTest(unittest.TestCase): 64class TranslatorDepsTest(unittest.TestCase):
63 def test_the_list_covers_every_local_module_build_py_reaches(self): 65 def test_the_list_covers_build_py_and_native_catalog_imports(self):
64 self.assertEqual({p for p in listed() if p.endswith(".py")}, reached()) 66 self.assertEqual({p for p in listed() if p.endswith(".py")}, reached())
65 67
66 def test_the_list_has_the_data_files_the_translator_reads(self): 68 def test_the_list_has_the_data_files_the_translator_reads(self):
diff --git a/tests/test_d3d12_xs_surface.py b/tests/test_d3d12_xs_surface.py
index 274dab600..1cdd52272 100644
--- a/tests/test_d3d12_xs_surface.py
+++ b/tests/test_d3d12_xs_surface.py
@@ -81,6 +81,7 @@ def test_sdk_discovery_sorts_versions_numerically():
81 vdir = os.path.join(include, ver) 81 vdir = os.path.join(include, ver)
82 os.makedirs(os.path.join(vdir, "um")) 82 os.makedirs(os.path.join(vdir, "um"))
83 os.makedirs(os.path.join(vdir, "shared")) 83 os.makedirs(os.path.join(vdir, "shared"))
84 open(os.path.join(vdir, "um", "d3d12.h"), "w").close()
84 with mock.patch.dict(os.environ, {"ProgramFiles(x86)": tmp, "ProgramFiles": tmp}, 85 with mock.patch.dict(os.environ, {"ProgramFiles(x86)": tmp, "ProgramFiles": tmp},
85 clear=False): 86 clear=False):
86 os.environ.pop("WINDOWS_SDK_INCLUDE", None) 87 os.environ.pop("WINDOWS_SDK_INCLUDE", None)
@@ -93,6 +94,31 @@ def test_sdk_discovery_sorts_versions_numerically():
93 os.path.join(include, "10.0.100000.0", "shared")), got_shared 94 os.path.join(include, "10.0.100000.0", "shared")), got_shared
94 95
95 96
97def test_sdk_discovery_skips_a_newer_driver_kit_folder():
98 # A Windows Driver Kit adds a newer version folder whose um/ holds only driver headers (measured: 43 files in
99 # 10.0.26100.0 beside a full 10.0.19041.0 on Windows 11); picking it found none of the 83 GUIDs, so the SDK check
100 # failed instead of using the SDK that is there.
101 with tempfile.TemporaryDirectory() as tmp:
102 include = os.path.join(tmp, "Windows Kits", "10", "Include")
103 sdk = os.path.join(include, "10.0.19041.0")
104 wdk = os.path.join(include, "10.0.26100.0")
105 for vdir in (sdk, wdk):
106 os.makedirs(os.path.join(vdir, "um"))
107 os.makedirs(os.path.join(vdir, "shared"))
108 open(os.path.join(sdk, "um", "d3d12.h"), "w").close()
109 open(os.path.join(wdk, "um", "d3d12umddi.h"), "w").close()
110 with mock.patch.dict(os.environ, {"ProgramFiles(x86)": tmp, "ProgramFiles": tmp}, clear=False):
111 os.environ.pop("WINDOWS_SDK_INCLUDE", None)
112 os.environ.pop("SDK_INCLUDE", None)
113 got_um, got_shared = S.find_sdk_include()
114 assert got_um is not None
115 assert os.path.normcase(got_um) == os.path.normcase(os.path.join(sdk, "um")), got_um
116 assert os.path.normcase(got_shared) == os.path.normcase(os.path.join(sdk, "shared")), got_shared
117 # Only the driver kit: no SDK, so the check skips rather than failing on 83 missing GUIDs.
118 os.remove(os.path.join(sdk, "um", "d3d12.h"))
119 assert S.find_sdk_include() == (None, None)
120
121
96def test_scarab_cross_check(): 122def test_scarab_cross_check():
97 root = os.environ.get("SCARAB_REF") 123 root = os.environ.get("SCARAB_REF")
98 if not root: 124 if not root:
@@ -109,6 +135,7 @@ if __name__ == "__main__":
109 test_unrecovered_console_iids_stay_outside_the_table() 135 test_unrecovered_console_iids_stay_outside_the_table()
110 test_sdk_include_override_accepts_a_trailing_separator() 136 test_sdk_include_override_accepts_a_trailing_separator()
111 test_sdk_discovery_sorts_versions_numerically() 137 test_sdk_discovery_sorts_versions_numerically()
138 test_sdk_discovery_skips_a_newer_driver_kit_folder()
112 # Call the two optional checks through their real definitions so this runner cannot drift from them; both 139 # Call the two optional checks through their real definitions so this runner cannot drift from them; both
113 # raise unittest.SkipTest when their inputs (SDK headers, SCARAB_REF) are absent. 140 # raise unittest.SkipTest when their inputs (SDK headers, SCARAB_REF) are absent.
114 for optional in (test_standard_iids_match_sdk, test_scarab_cross_check): 141 for optional in (test_standard_iids_match_sdk, test_scarab_cross_check):
diff --git a/tests/test_f64_conversion.py b/tests/test_f64_conversion.py
index 514ef2398..7601c595b 100644
--- a/tests/test_f64_conversion.py
+++ b/tests/test_f64_conversion.py
@@ -46,6 +46,9 @@ class F64ConversionTest(unittest.TestCase):
46 scale = result(rf"OpBitcast %float {constant}") 46 scale = result(rf"OpBitcast %float {constant}")
47 value = result(rf"OpFMul %float {value} {scale}") 47 value = result(rf"OpFMul %float {value} {scale}")
48 if clamp: 48 if clamp:
49 # DX10_CLAMP: a NaN is replaced by +0 before FClamp (Gen.clamp_mods).
50 nan = result(rf"OpIsNan %bool {value}")
51 value = result(rf"OpSelect %float {nan} %f0 {value}")
49 value = result(rf"OpExtInst %float %glsl FClamp {value} %f0 %f1") 52 value = result(rf"OpExtInst %float %glsl FClamp {value} %f0 %f1")
50 word = result(rf"OpBitcast %uint {value}") 53 word = result(rf"OpBitcast %uint {value}")
51 dest = result(r"OpAccessChain %_ptr_Function_uint %vgpr %c3") 54 dest = result(r"OpAccessChain %_ptr_Function_uint %vgpr %c3")
diff --git a/tests/test_fspx_shaders_stage.py b/tests/test_fspx_shaders_stage.py
index 3d2e94f03..288454a86 100644
--- a/tests/test_fspx_shaders_stage.py
+++ b/tests/test_fspx_shaders_stage.py
@@ -382,7 +382,9 @@ class ShadersStageWithTheDll(unittest.TestCase):
382 382
383 def fake_translate(disasm, spirv, jobs, emulate=False, fallbacks=()): 383 def fake_translate(disasm, spirv, jobs, emulate=False, fallbacks=()):
384 ran.append("translate") 384 ran.append("translate")
385 touch(spirv, "index.json") 385 os.makedirs(spirv, exist_ok=True)
386 with open(os.path.join(spirv, "index.json"), "w", encoding="utf-8") as f:
387 json.dump({"shader": {"stage": "vs"}}, f)
386 388
387 def stage(): 389 def stage():
388 ran.clear() 390 ran.clear()
diff --git a/tests/test_fssm_unpack.py b/tests/test_fssm_unpack.py
index f11f5a101..4e2e60e60 100644
--- a/tests/test_fssm_unpack.py
+++ b/tests/test_fssm_unpack.py
@@ -20,6 +20,7 @@ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
20sys.path.insert(0, os.path.join(ROOT, "tools")) 20sys.path.insert(0, os.path.join(ROOT, "tools"))
21 21
22import fssm_unpack # noqa: E402 22import fssm_unpack # noqa: E402
23import shader_stage_manifest # noqa: E402
23 24
24TOOL = os.path.join(ROOT, "tools", "fssm_unpack.py") 25TOOL = os.path.join(ROOT, "tools", "fssm_unpack.py")
25S_ENDPGM = b"\x00\x00\x81\xbf" 26S_ENDPGM = b"\x00\x00\x81\xbf"
@@ -570,6 +571,60 @@ class TestMainDirectoryProcessing(unittest.TestCase):
570 self.assertEqual(os.listdir(os.path.join(self.src, "fssm")), ["current.fssm"]) 571 self.assertEqual(os.listdir(os.path.join(self.src, "fssm")), ["current.fssm"])
571 self.assertTrue(os.path.isfile(os.path.join(self.src, "obsolete.dxbc"))) 572 self.assertTrue(os.path.isfile(os.path.join(self.src, "obsolete.dxbc")))
572 573
574 def test_program_counts_separate_containers_from_payloads(self):
575 # BL-5: a container is one carved file, a program is one tag-0x0D payload. Five containers, six payloads:
576 # the vertex shader carries two (its ES and VS hardware variants), as 195 of the corpus' containers do.
577 es = make_fssm(version=0x0101, instructions=[(0x100, S_ENDPGM)])
578 vs = make_fssm(version=0x0102, instructions=[(0x100, S_ENDPGM)])
579 one = make_dxbc([(b"DXIL", make_xdat({0x0D: make_xbch(make_fssm())}))])
580 two = make_dxbc([(b"DXIL", make_xdat_list([(0x0D, make_xbch(es)), (0x0D, make_xbch(vs))]))])
581 for name, data in (("vertex", two), ("geometry", one), ("unstaged", one), ("blank", one), ("numbered", one)):
582 with open(os.path.join(self.src, name + ".dxbc"), "wb") as f:
583 f.write(data)
584 index = os.path.join(self.src, "index.json")
585 # Three ways an entry names no stage: no field, an empty one, and one that is not a string.
586 with open(index, "w", encoding="utf-8") as f:
587 json.dump([{"file": "vertex.dxbc", "stage": "vs"}, {"file": "geometry.dxbc", "stage": "gs"},
588 {"file": "unstaged.dxbc"}, {"file": "blank.dxbc", "stage": ""},
589 {"file": "numbered.dxbc", "stage": 7}], f)
590 stages = shader_stage_manifest.shader_stages(index, "file", ".dxbc")
591 self.assertEqual(stages, {"vertex": "vs", "geometry": "gs", "unstaged": None, "blank": None, "numbered": None})
592
593 result = subprocess.run([sys.executable, "-I", TOOL, self.src, "--carve-index", index],
594 capture_output=True, text=True, errors="replace")
595 self.assertEqual(result.returncode, 0, result.stderr)
596 self.assertIn("programs: 6 tag-0x0D payloads in 5 containers, 1 containers with more than one "
597 "(--payload last is the one unpacked)", result.stdout)
598 self.assertIn(" gs: 1 containers, 1 payloads, 0 with more than one", result.stdout)
599 self.assertIn(" vs: 1 containers, 2 payloads, 1 with more than one", result.stdout)
600 # A row the carve index gives no stage is counted, under one heading, not dropped, guessed or split by the
601 # way its stage is missing: three lines for the breakdown, no fourth for "" or 7.
602 self.assertIn(" stage unknown: 3 containers, 3 payloads, 0 with more than one", result.stdout)
603 breakdown = [line for line in result.stdout.splitlines() if line.startswith(" ") and " containers, " in line]
604 self.assertEqual(len(breakdown), 3, breakdown)
605 # The file written for the two-payload container is still one program: the last payload.
606 with open(os.path.join(self.src, "fssm", "vertex.fssm"), "rb") as f:
607 self.assertEqual(f.read(), vs)
608
609 with open(os.path.join(self.src, "fssm_index.json"), encoding="utf-8") as f:
610 rows = json.load(f)
611 counts = fssm_unpack.program_counts(rows, stages)
612 self.assertEqual(counts, {"vs": {"containers": 1, "programs": 2, "multi_payload": 1},
613 "gs": {"containers": 1, "programs": 1, "multi_payload": 0},
614 None: {"containers": 3, "programs": 3, "multi_payload": 0}})
615
616 def test_program_counts_without_a_carve_index_have_no_stage_breakdown(self):
617 two = make_dxbc([(b"DXIL", make_xdat_list([(0x0D, make_xbch(make_fssm(version=0x0101))),
618 (0x0D, make_xbch(make_fssm(version=0x0102)))]))])
619 with open(os.path.join(self.src, "pair.dxbc"), "wb") as f:
620 f.write(two)
621 result = subprocess.run([sys.executable, "-I", TOOL, self.src], capture_output=True, text=True,
622 errors="replace")
623 self.assertEqual(result.returncode, 0, result.stderr)
624 self.assertIn("programs: 2 tag-0x0D payloads in 1 containers, 1 containers with more than one",
625 result.stdout)
626 self.assertNotIn("stage unknown", result.stdout)
627
573 def test_main_rejects_invalid_fssm_magic(self): 628 def test_main_rejects_invalid_fssm_magic(self):
574 bad_payload = b"JUNK\x01\x01" + bytes(58) 629 bad_payload = b"JUNK\x01\x01" + bytes(58)
575 bad_dxbc = make_dxbc([(b"DXIL", make_xdat({0x0D: make_xbch(bad_payload)}))]) 630 bad_dxbc = make_dxbc([(b"DXIL", make_xdat({0x0D: make_xbch(bad_payload)}))])
diff --git a/tests/test_gallery.py b/tests/test_gallery.py
index 708982290..5d4ff84d2 100644
--- a/tests/test_gallery.py
+++ b/tests/test_gallery.py
@@ -607,6 +607,27 @@ class TestGalleryCommandLine(unittest.TestCase):
607 self.assertIn("--port must be between 0 and 65535", stderr.getvalue()) 607 self.assertIn("--port must be between 0 and 65535", stderr.getvalue())
608 start_server.assert_not_called() 608 start_server.assert_not_called()
609 609
610 def test_rejects_non_directory_explicit_paths_before_starting_server(self) -> None:
611 with tempfile.TemporaryDirectory() as tmp:
612 missing = os.path.join(tmp, "missing")
613 regular_file = os.path.join(tmp, "not-a-directory")
614 with open(regular_file, "wb") as f:
615 f.write(b"synthetic")
616 for flag in ("--models-dir", "--textures-dir"):
617 for path in (missing, regular_file, ""):
618 with (
619 self.subTest(flag=flag, path=path),
620 mock.patch.object(gallery, "start_server") as start_server,
621 mock.patch.object(sys, "stderr", new_callable=io.StringIO) as stderr,
622 ):
623 with self.assertRaises(SystemExit) as raised:
624 gallery.main([flag, path, "--no-browser"])
625
626 self.assertEqual(raised.exception.code, 2)
627 self.assertIn(f"{flag} is not a directory", stderr.getvalue())
628 self.assertNotIn("Traceback", stderr.getvalue())
629 start_server.assert_not_called()
630
610 def test_passes_default_and_boundary_ports_to_server(self) -> None: 631 def test_passes_default_and_boundary_ports_to_server(self) -> None:
611 for args, port in (([], 8080), (["--port", "0"], 0), (["--port", "65535"], 65535)): 632 for args, port in (([], 8080), (["--port", "0"], 0), (["--port", "65535"], 65535)):
612 with self.subTest(port=port), mock.patch.object(gallery, "start_server") as start_server: 633 with self.subTest(port=port), mock.patch.object(gallery, "start_server") as start_server:
@@ -616,6 +637,21 @@ class TestGalleryCommandLine(unittest.TestCase):
616 retry_next_port=not args, 637 retry_next_port=not args,
617 ) 638 )
618 639
640 def test_passes_usable_explicit_directories_to_server(self) -> None:
641 with tempfile.TemporaryDirectory() as tmp:
642 models_dir = os.path.join(tmp, "models")
643 textures_dir = os.path.join(tmp, "textures")
644 os.makedirs(models_dir)
645 os.makedirs(textures_dir)
646 with mock.patch.object(gallery, "start_server") as start_server:
647 self.assertEqual(gallery.main([
648 "--models-dir", models_dir, "--textures-dir", textures_dir, "--no-browser",
649 ]), 0)
650 start_server.assert_called_once_with(
651 port=8080, models_dir=models_dir, textures_dir=textures_dir, open_browser=False,
652 retry_next_port=True,
653 )
654
619 def test_reports_unavailable_listen_ports(self) -> None: 655 def test_reports_unavailable_listen_ports(self) -> None:
620 cases = ((["--port", "65535"], [65535]), (["--port", "8080"], [8080]), ([], [8080, 8081])) 656 cases = ((["--port", "65535"], [65535]), (["--port", "8080"], [8080]), ([], [8080, 8081]))
621 for args, ports in cases: 657 for args, ports in cases:
diff --git a/tests/test_gpu_shift64.py b/tests/test_gpu_shift64.py
new file mode 100644
index 000000000..1ef33d475
--- /dev/null
+++ b/tests/test_gpu_shift64.py
@@ -0,0 +1,96 @@
1"""GPU-VALU64-SHIFTS: readback and runner verdicts, without needing a GPU."""
2import contextlib
3import io
4from pathlib import Path
5import struct
6import sys
7import tempfile
8from types import SimpleNamespace
9import unittest
10from unittest.mock import patch
11
12sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts"))
13import run_gpu_tests as rgt
14import check
15
16
17class Shift64Readback(unittest.TestCase):
18 def test_oracle_boundaries(self):
19 initial, expected = check.shift64_words()
20 self.assertEqual(len(initial), 640)
21 self.assertEqual(len(expected), 640)
22 self.assertEqual(initial[:384], [0xEEEEEEEE] * 384)
23 self.assertEqual(initial[384:], expected[384:])
24 # 1 << 32, 1 >> 32, signed(1) >> 32, each as low/high words.
25 self.assertEqual(expected[66:72], [0, 1, 0, 0, 0, 0])
26 # INT64_MIN >> 63 is 1 logically and -1 arithmetically.
27 self.assertEqual(expected[270:276], [0, 0, 1, 0, 0xFFFFFFFF, 0xFFFFFFFF])
28 # A count of 64 leaves the operand unchanged for all three shifts.
29 self.assertEqual(expected[372:378], [0x89ABCDEF, 0x81234567] * 3)
30 self.assertEqual(expected[378:384], [0x13579BDE, 0x02468ACF, 0xC4D5E6F7, 0x4091A2B3,
31 0xC4D5E6F7, 0xC091A2B3])
32
33 def run_readback(self, mutate=None, code=0, output="", missing=False):
34 paths = []
35
36 def launch(*args, env):
37 paths.append(Path(env["VKC_HEAP_INIT"]))
38 initial, expected = check.shift64_words()
39 self.assertEqual(paths[-1].read_bytes(), struct.pack("<640I", *initial))
40 self.assertEqual(env["VKC_SUBGROUP_SIZE"], "32")
41 self.assertEqual(env["VKC_OUT_WORDS"], "640")
42 self.assertEqual(env["LEONIDA_VK_DEVICE"], "synthetic device")
43 if mutate:
44 mutate(expected)
45 if not missing:
46 Path(env["VKC_DUMP"]).write_bytes(struct.pack(f"<{len(expected)}I", *expected))
47 return code, output
48
49 with patch.object(check, "run", side_effect=launch):
50 result = check.shift64_test("unused", "unused", {"LEONIDA_VK_DEVICE": "synthetic device"})
51 self.assertEqual(len(paths), 1)
52 self.assertFalse(paths[0].exists(), "private heap input must be cleaned up")
53 return result
54
55 def test_complete_readback_passes(self):
56 self.assertEqual(self.run_readback(), "")
57
58 def test_late_result_and_untouched_input_corruption_fail(self):
59 for word in (383, 639):
60 with self.subTest(word=word):
61 result = self.run_readback(lambda data: data.__setitem__(word, data[word] ^ 1))
62 self.assertIn(f"word {word}:", result)
63
64 def test_truncated_and_missing_dump_fail(self):
65 self.assertIn("expected 2560 dump bytes, got 2556", self.run_readback(lambda data: data.pop()))
66 self.assertIn("no VKC_DUMP", self.run_readback(missing=True))
67
68 def test_unsupported_int64_skips_but_nonzero_exit_fails(self):
69 self.assertIsInstance(self.run_readback(code=77, output="unsupported: no Int64\n"), check.Skip)
70 self.assertIn("exit 1", self.run_readback(code=1, output="dispatch failed"))
71
72
73class Shift64Runner(unittest.TestCase):
74 def test_filtered_runner_counts_pass_failure_and_skip(self):
75 for detail, expected, verdict in (("", 0, "1/1 passed"), ("word 383: mismatch", 1, "0/1 passed"),
76 (check.Skip("SKIP (no Int64)"), 0, "0/1 passed, 1 skipped")):
77 with self.subTest(detail=detail), tempfile.TemporaryDirectory() as tmp:
78 args = SimpleNamespace(filter="cs_w32_shift64", build=tmp, llvm_mc="unused")
79
80 def translate(_cmd, **_kwargs):
81 (Path(tmp) / "spirv" / "cs_w32_shift64.spv").touch()
82 return 0, ""
83
84 output = io.StringIO()
85 with (patch.object(rgt, "assemble_to_s", side_effect=lambda _mc, _src, dst, _name: Path(dst).touch()),
86 patch.object(rgt, "spirv_as"), patch.object(rgt, "run_cmd", side_effect=translate),
87 patch.object(rgt, "shift64_test", return_value=detail) as readback,
88 contextlib.redirect_stdout(output)):
89 self.assertEqual(rgt.run_suite(args, tmp), expected)
90 readback.assert_called_once()
91 self.assertIn(verdict, output.getvalue())
92 self.assertIn("cs_w32_shift64", output.getvalue())
93
94
95if __name__ == "__main__":
96 unittest.main()
diff --git a/tests/test_guest_scene_reference.py b/tests/test_guest_scene_reference.py
index 3c0ed16dd..9c6df51f8 100644
--- a/tests/test_guest_scene_reference.py
+++ b/tests/test_guest_scene_reference.py
@@ -112,7 +112,9 @@ class GuestSceneReferenceTest(unittest.TestCase):
112 "--shaders", str(root), "--out", str(out)] 112 "--shaders", str(root), "--out", str(out)]
113 if sys.platform != "win32": 113 if sys.platform != "win32":
114 cmd += ["--wine", str(bad_loader), "--wine-arg=-a", "--wine-arg=path with spaces/wine"] 114 cmd += ["--wine", str(bad_loader), "--wine-arg=-a", "--wine-arg=path with spaces/wine"]
115 result = subprocess.run(cmd, capture_output=True, encoding="utf-8", timeout=20) 115 # The runner's "could not launch" line carries the OS error text, which Windows localizes and the child
116 # prints in the ANSI code page (cp1251 on a Russian host): a strict UTF-8 decode would leave stdout None.
117 result = subprocess.run(cmd, capture_output=True, encoding="utf-8", errors="replace", timeout=20)
116 self.assertEqual(result.returncode, 1, result.stdout + result.stderr) 118 self.assertEqual(result.returncode, 1, result.stdout + result.stderr)
117 report = json.loads((out / "report.json").read_text(encoding="utf-8")) 119 report = json.loads((out / "report.json").read_text(encoding="utf-8"))
118 self.assertIn("could not launch", report["error"]) 120 self.assertIn("could not launch", report["error"])
diff --git a/tests/test_hw_oracle_workdir_leak.py b/tests/test_hw_oracle_workdir_leak.py
new file mode 100644
index 000000000..04139a560
--- /dev/null
+++ b/tests/test_hw_oracle_workdir_leak.py
@@ -0,0 +1,162 @@
1"""tools/hw_oracle: a constructor that fails after it made its temporary workdir removes that directory.
2
3runner.Oracle and drm.DrmOracle create the workdir in __init__ and can raise Unavailable after that (a skipped
4probe, exit 77). close() is never reached when __init__ raises, so the directory used to stay behind. Standard
5library only; needs no GPU, no libdrm and no clang."""
6import glob
7import os
8import sys
9import tempfile
10import unittest
11from pathlib import Path
12from unittest import mock
13
14TOOLS = Path(__file__).resolve().parents[1] / "tools"
15sys.path.insert(0, str(TOOLS))
16from hw_oracle import drm, runner # noqa: E402
17
18Unavailable = runner.Unavailable
19PREFIX = "leonida-hw-oracle-"
20
21
22class _Recorder:
23 """Stands in for tempfile.mkdtemp: creates under a base directory the test owns and remembers what it made."""
24
25 def __init__(self, base):
26 self.base = base
27 self.made = []
28 self._real = tempfile.mkdtemp
29
30 def __call__(self, *args, **kwargs):
31 path = self._real(*args, dir=self.base, **kwargs)
32 self.made.append(path)
33 return path
34
35
36class _WorkdirCase(unittest.TestCase):
37 def setUp(self):
38 self._base = tempfile.TemporaryDirectory(prefix="hw-oracle-workdir-test-")
39 self.addCleanup(self._base.cleanup)
40 self.recorder = _Recorder(self._base.name)
41 patch = mock.patch.object(tempfile, "mkdtemp", side_effect=self.recorder)
42 patch.start()
43 self.addCleanup(patch.stop)
44
45 def assertOwnedDirGone(self):
46 self.assertEqual(len(self.recorder.made), 1, "the constructor should have made exactly one workdir")
47 self.assertFalse(os.path.exists(self.recorder.made[0]), f"{self.recorder.made[0]} was left behind")
48
49 def assertLeftoverPrefixed(self):
50 self.assertEqual(glob.glob(os.path.join(self._base.name, PREFIX + "*")), [])
51
52
53class DrmOracleWorkdir(_WorkdirCase):
54 def _patches(self, **over):
55 """find_node and find_clang succeed; _build_launcher, _device_arch and _probe are replaced as the test needs."""
56 defaults = {
57 "find_node": mock.patch.object(drm, "find_node", return_value="/fake/node"),
58 "find_clang": mock.patch.object(runner, "find_clang", return_value="/fake/clang"),
59 "_build_launcher": mock.patch.object(drm.DrmOracle, "_build_launcher", return_value="/fake/exe"),
60 "_probe": mock.patch.object(drm.DrmOracle, "_probe", return_value="fake device"),
61 "_probe_waves": mock.patch.object(drm.DrmOracle, "_probe_waves", create=True),
62 }
63 defaults.update(over)
64 started = []
65 for p in defaults.values():
66 if p is not None:
67 started.append(p.start())
68 self.addCleanup(p.stop)
69 return started
70
71 def test_failure_in_build_launcher_removes_owned_workdir(self):
72 self._patches(_build_launcher=mock.patch.object(drm.DrmOracle, "_build_launcher",
73 side_effect=Unavailable("no gcc")))
74 with self.assertRaises(Unavailable):
75 drm.DrmOracle(arch="gfx1030")
76 self.assertOwnedDirGone()
77 self.assertLeftoverPrefixed()
78
79 def test_late_failure_in_probe_removes_owned_workdir(self):
80 self._patches(_probe=mock.patch.object(drm.DrmOracle, "_probe", side_effect=Unavailable("no device")))
81 with self.assertRaises(Unavailable):
82 drm.DrmOracle(arch="gfx1030")
83 self.assertOwnedDirGone()
84 self.assertLeftoverPrefixed()
85
86 def test_bad_arch_after_build_removes_owned_workdir(self):
87 self._patches()
88 with self.assertRaises(Unavailable):
89 drm.DrmOracle(arch="gfx90a")
90 self.assertOwnedDirGone()
91 self.assertLeftoverPrefixed()
92
93 def test_caller_workdir_is_kept_on_failure(self):
94 caller = os.path.join(self._base.name, "caller-owned")
95 os.mkdir(caller)
96 self._patches(_probe=mock.patch.object(drm.DrmOracle, "_probe", side_effect=Unavailable("no device")))
97 with self.assertRaises(Unavailable):
98 drm.DrmOracle(arch="gfx1030", workdir=caller)
99 self.assertEqual(self.recorder.made, [], "a caller-supplied workdir must not be replaced by a temp one")
100 self.assertTrue(os.path.isdir(caller))
101
102 def test_success_keeps_workdir_until_close(self):
103 self._patches()
104 oracle = drm.DrmOracle(arch="gfx1030")
105 self.assertEqual(len(self.recorder.made), 1)
106 self.assertTrue(os.path.isdir(self.recorder.made[0]), "a successful constructor must keep its workdir")
107 oracle.close()
108 self.assertFalse(os.path.exists(self.recorder.made[0]))
109
110
111class OracleWorkdir(_WorkdirCase):
112 def _patches(self, **over):
113 """The tools the constructor looks up are present; _build_launcher and _probe are replaced as needed."""
114 defaults = {
115 "find_clang": mock.patch.object(runner, "find_clang", return_value="/fake/clang"),
116 "_find_lld": mock.patch.object(runner, "_find_lld", return_value="/fake/lld"),
117 "find_hip_dll": mock.patch.object(runner, "find_hip_dll", return_value="/fake/dll"),
118 "_build_launcher": mock.patch.object(runner.Oracle, "_build_launcher", return_value="/fake/exe"),
119 "_probe": mock.patch.object(runner.Oracle, "_probe", return_value="fake device"),
120 "_needs_true16": mock.patch.object(runner.Oracle, "_needs_true16", return_value=False),
121 "_probe_waves": mock.patch.object(runner.Oracle, "_probe_waves"),
122 }
123 defaults.update(over)
124 for p in defaults.values():
125 p.start()
126 self.addCleanup(p.stop)
127
128 def test_failure_in_build_launcher_removes_owned_workdir(self):
129 self._patches(_build_launcher=mock.patch.object(runner.Oracle, "_build_launcher",
130 side_effect=Unavailable("no hip")))
131 with self.assertRaises(Unavailable):
132 runner.Oracle(arch="gfx1030")
133 self.assertOwnedDirGone()
134 self.assertLeftoverPrefixed()
135
136 def test_late_failure_in_probe_removes_owned_workdir(self):
137 self._patches(_probe=mock.patch.object(runner.Oracle, "_probe", side_effect=Unavailable("no device")))
138 with self.assertRaises(Unavailable):
139 runner.Oracle(arch="gfx1030")
140 self.assertOwnedDirGone()
141 self.assertLeftoverPrefixed()
142
143 def test_caller_workdir_is_kept_on_failure(self):
144 caller = os.path.join(self._base.name, "caller-owned")
145 os.mkdir(caller)
146 self._patches(_probe=mock.patch.object(runner.Oracle, "_probe", side_effect=Unavailable("no device")))
147 with self.assertRaises(Unavailable):
148 runner.Oracle(arch="gfx1030", workdir=caller)
149 self.assertEqual(self.recorder.made, [])
150 self.assertTrue(os.path.isdir(caller))
151
152 def test_success_keeps_workdir_until_close(self):
153 self._patches()
154 oracle = runner.Oracle(arch="gfx1030")
155 self.assertEqual(len(self.recorder.made), 1)
156 self.assertTrue(os.path.isdir(self.recorder.made[0]))
157 oracle.close()
158 self.assertFalse(os.path.exists(self.recorder.made[0]))
159
160
161if __name__ == "__main__":
162 unittest.main()
diff --git a/tests/test_make_game_destinations.py b/tests/test_make_game_destinations.py
index 3ec39b93d..bd442029f 100644
--- a/tests/test_make_game_destinations.py
+++ b/tests/test_make_game_destinations.py
@@ -9,6 +9,7 @@ import os
9import sys 9import sys
10import tempfile 10import tempfile
11import unittest 11import unittest
12from unittest import mock
12from unittest.mock import patch 13from unittest.mock import patch
13 14
14ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 15ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
@@ -121,5 +122,75 @@ class DriveRootGameTests(unittest.TestCase):
121 self.assertIn("--out and --work must be outside the game folder.", err.getvalue()) 122 self.assertIn("--out and --work must be outside the game folder.", err.getvalue())
122 123
123 124
125def other_drive_tmp():
126 """A temporary folder on another drive than the default temp folder when there is one (the repository's drive,
127 on a PC that keeps it apart from the system drive), else on the same drive: the split is then only by folder."""
128 here = os.path.dirname(ROOT)
129 if os.path.splitdrive(here)[0].lower() != os.path.splitdrive(tempfile.gettempdir())[0].lower():
130 try:
131 return tempfile.TemporaryDirectory(dir=here)
132 except OSError:
133 pass
134 return tempfile.TemporaryDirectory()
135
136
137class SeparateRootsTests(unittest.TestCase):
138 """The package, --out (what the game runs from) and --work (the carved and exported files) can each be on a
139 different drive: every stage gets the folder it was given, and a later run with another --work for the assets
140 leaves the port's shader path on the first one."""
141
142 def setUp(self):
143 roots = [tempfile.TemporaryDirectory(), tempfile.TemporaryDirectory(), other_drive_tmp()]
144 for r in roots:
145 self.addCleanup(r.cleanup)
146 self.game = os.path.join(roots[0].name, "package")
147 self.out = os.path.join(roots[1].name, "Leonida")
148 self.work = os.path.join(roots[2].name, "leonida-work")
149 os.makedirs(self.game)
150 self.build = os.path.join(roots[1].name, "build")
151 os.makedirs(self.build)
152 for name in make_game.RUNTIME_FILES:
153 with open(os.path.join(self.build, name), "wb") as f:
154 f.write(b"synthetic")
155 self.version = {"title": "test", "version": "1.0", "expected_exe": "Game.exe", "files": {}}
156
157 def run_main(self, *argv, **stage_mocks):
158 preflight = mock.MagicMock()
159 with patch.object(sys, "argv", ["make_game.py", "--game", self.game, "--out", self.out, "--no-tui", *argv]), \
160 patch.object(make_game, "below_normal"), patch.object(make_game, "log"), \
161 patch.object(make_game, "check", return_value=self.version), \
162 patch.object(make_game, "preflight", preflight), contextlib.ExitStack() as stack:
163 for name, stage in stage_mocks.items():
164 stack.enter_context(patch.object(make_game, name, stage))
165 self.assertEqual(make_game.main(), 0)
166 return preflight
167
168 def test_each_stage_gets_its_own_folder(self):
169 assets, runtime = mock.MagicMock(), mock.MagicMock()
170 preflight = self.run_main("--work", self.work, "--stages", "check,assets,runtime",
171 assets=assets, runtime=runtime)
172 self.assertEqual(preflight.call_args.args[1], self.work) # free space is counted on the --work drive
173 self.assertEqual(assets.call_args.args[:2], (self.game, self.work))
174 self.assertEqual(runtime.call_args.args[:2], (self.game, self.out))
175 self.assertEqual(runtime.call_args.kwargs["work"], self.work)
176
177 def test_assets_in_another_work_folder_keep_the_shader_path(self):
178 self.run_main("--work", self.work, "--stages", "check,runtime", "--runtime-build", self.build)
179 with open(os.path.join(self.out, "game_path.txt"), encoding="utf-8") as f:
180 self.assertEqual(f.read(), self.game)
181 shader_path = os.path.join(self.out, "shader_path.txt")
182 with open(shader_path, "rb") as f:
183 recorded = f.read()
184 self.assertEqual(recorded, os.fsencode(os.path.join(self.work, "shaders", "spirv")))
185
186 assets_work = os.path.join(os.path.dirname(self.out), "assets-work")
187 assets = mock.MagicMock()
188 preflight = self.run_main("--work", assets_work, "--stages", "check,assets", assets=assets)
189 self.assertEqual(preflight.call_args.args[1], assets_work)
190 self.assertEqual(assets.call_args.args[:2], (self.game, assets_work))
191 with open(shader_path, "rb") as f:
192 self.assertEqual(f.read(), recorded)
193
194
124if __name__ == "__main__": 195if __name__ == "__main__":
125 unittest.main() 196 unittest.main()
diff --git a/tests/test_make_game_pipelines.py b/tests/test_make_game_pipelines.py
index b419d792f..e0f15ba6f 100644
--- a/tests/test_make_game_pipelines.py
+++ b/tests/test_make_game_pipelines.py
@@ -70,7 +70,10 @@ class PipelinesJobsTest(unittest.TestCase):
70 pass 70 pass
71 argv = ["make_game.py", "--game", self.game, "--work", self.work, "--out", self.out, 71 argv = ["make_game.py", "--game", self.game, "--work", self.work, "--out", self.out,
72 "--stages", "runtime,pipelines", "--runtime-build", supplied, "--jobs", "3"] 72 "--stages", "runtime,pipelines", "--runtime-build", supplied, "--jobs", "3"]
73 with mock.patch.object(sys, "argv", argv), mock.patch.object(make_game, "ROOT", self.root), \ 73 # main() clamps --jobs to the hardware threads; pin them so 3 is in range anywhere (the
74 # GitHub Windows runners have 4, but a 2-vCPU machine would otherwise compare the clamped 2).
75 with mock.patch.object(make_game.leonida_tui.os, "cpu_count", return_value=16), \
76 mock.patch.object(sys, "argv", argv), mock.patch.object(make_game, "ROOT", self.root), \
74 mock.patch("os.name", "nt"), mock.patch.object(make_game, "below_normal"), \ 77 mock.patch("os.name", "nt"), mock.patch.object(make_game, "below_normal"), \
75 mock.patch.object(make_game, "check", return_value={"expected_exe": "g.exe"}), \ 78 mock.patch.object(make_game, "check", return_value={"expected_exe": "g.exe"}), \
76 mock.patch.object(make_game, "log"), mock.patch.object(make_game, "run") as run: 79 mock.patch.object(make_game, "log"), mock.patch.object(make_game, "run") as run:
diff --git a/tests/test_make_game_translator_flags.py b/tests/test_make_game_translator_flags.py
index 04067440f..c268a33e9 100644
--- a/tests/test_make_game_translator_flags.py
+++ b/tests/test_make_game_translator_flags.py
@@ -133,6 +133,8 @@ class RecordedFlagsTest(unittest.TestCase):
133 json.dump([{"file": "shader.dxbc"}], f) 133 json.dump([{"file": "shader.dxbc"}], f)
134 elif p == os.path.join(self.dxbc, "fssm_index.json"): 134 elif p == os.path.join(self.dxbc, "fssm_index.json"):
135 json.dump([{"name": "shader"}], f) 135 json.dump([{"name": "shader"}], f)
136 elif p == os.path.join(self.spirv, "index.json"):
137 json.dump({"shader": {"stage": "vs"}}, f)
136 elif p.endswith(".s"): 138 elif p.endswith(".s"):
137 f.write("synthetic listing\n") 139 f.write("synthetic listing\n")
138 140
diff --git a/tests/test_manifest_verifier.py b/tests/test_manifest_verifier.py
index 3729b3556..692f22c73 100644
--- a/tests/test_manifest_verifier.py
+++ b/tests/test_manifest_verifier.py
@@ -896,6 +896,58 @@ class TestVerifyCache(unittest.TestCase):
896 with open(self.cache, encoding="utf-8") as f: 896 with open(self.cache, encoding="utf-8") as f:
897 return {os.path.basename(k) for k in json.load(f)["files"]} 897 return {os.path.basename(k) for k in json.load(f)["files"]}
898 898
899 def assert_manifest_cache_refused(self) -> None:
900 with open(self.manifest, "rb") as f:
901 before = f.read()
902 with patch.object(mv, "sha256_file", wraps=mv.sha256_file) as hashing:
903 with self.assertRaisesRegex(mv.ManifestError, "cache must not overwrite the manifest"):
904 self.verify()
905 hashing.assert_not_called()
906 with open(self.manifest, "rb") as f:
907 self.assertEqual(f.read(), before)
908 with open(self.cache, "rb") as f:
909 self.assertEqual(f.read(), before)
910 self.assertFalse(os.path.exists(self.cache + ".tmp"))
911
912 def test_cache_refuses_another_spelling_of_manifest(self) -> None:
913 self.cache = os.path.join(self.game, "..", "manifest.json")
914 self.assert_manifest_cache_refused()
915
916 def test_cache_refuses_manifest_hard_link(self) -> None:
917 try:
918 os.link(self.manifest, self.cache)
919 except OSError as err:
920 self.skipTest(f"hard links unavailable: {err}")
921 self.assert_manifest_cache_refused()
922
923 def test_cache_refuses_manifest_symlink(self) -> None:
924 try:
925 os.symlink(self.manifest, self.cache)
926 except OSError as err:
927 self.skipTest(f"symlinks unavailable: {err}")
928 self.assert_manifest_cache_refused()
929
930 def test_cache_refuses_manifest_case_alias_on_folding_volume(self) -> None:
931 self.cache = os.path.join(self.tmp.name, "MANIFEST.JSON")
932 if not os.path.exists(self.cache):
933 self.skipTest("volume is case-sensitive")
934 self.assert_manifest_cache_refused()
935
936 def test_cli_cache_equal_to_manifest_preserves_input(self) -> None:
937 with open(self.manifest, "rb") as f:
938 before = f.read()
939 result = subprocess.run(
940 [sys.executable, "-I", TOOL, self.game, "--manifest", self.manifest,
941 "--cache", self.manifest, "--json"],
942 capture_output=True, text=True, timeout=15,
943 )
944 with open(self.manifest, "rb") as f:
945 self.assertEqual(f.read(), before)
946 self.assertEqual(result.returncode, 2)
947 self.assertIn("cache must not overwrite the manifest", result.stderr)
948 self.assertNotIn("Traceback", result.stderr)
949 self.assertEqual(result.stdout, "")
950
899 def test_second_run_hashes_nothing(self) -> None: 951 def test_second_run_hashes_nothing(self) -> None:
900 for jobs in (1, 4): 952 for jobs in (1, 4):
901 with self.subTest(jobs=jobs): 953 with self.subTest(jobs=jobs):
@@ -954,6 +1006,61 @@ class TestVerifyCache(unittest.TestCase):
954 report = self.verify() 1006 report = self.verify()
955 self.assertEqual((report.passed, report.cached), (True, 0)) 1007 self.assertEqual((report.passed, report.cached), (True, 0))
956 1008
1009 def assert_input_cache_refused(self) -> None:
1010 with patch.object(mv, "sha256_file", wraps=mv.sha256_file) as hashing:
1011 with self.assertRaisesRegex(mv.ManifestError, "cache must not overwrite a listed input"):
1012 self.verify()
1013 hashing.assert_not_called()
1014 for rel, data in self.data.items():
1015 with open(os.path.join(self.game, rel), "rb") as f:
1016 self.assertEqual(f.read(), data)
1017
1018 def test_cache_refuses_normalized_input_path(self) -> None:
1019 self.cache = os.path.join(self.game, "..", "game", "a.bin")
1020 self.assert_input_cache_refused()
1021
1022 def test_cache_refuses_input_case_alias_on_folding_volume(self) -> None:
1023 self.cache = os.path.join(self.game, "A.BIN")
1024 if not os.path.exists(self.cache):
1025 self.skipTest("volume is case-sensitive")
1026 self.assert_input_cache_refused()
1027
1028 def test_cache_refuses_input_hard_link(self) -> None:
1029 try:
1030 os.link(os.path.join(self.game, "a.bin"), self.cache)
1031 except OSError as err:
1032 self.skipTest(f"hard links unavailable: {err}")
1033 self.assert_input_cache_refused()
1034
1035 def test_cache_refuses_input_symlink(self) -> None:
1036 try:
1037 os.symlink(os.path.join(self.game, "a.bin"), self.cache)
1038 except OSError as err:
1039 self.skipTest(f"symlinks unavailable: {err}")
1040 self.assert_input_cache_refused()
1041
1042 def test_cache_does_not_create_a_missing_listed_input(self) -> None:
1043 self.cache = os.path.join(self.game, "a.bin")
1044 os.unlink(self.cache)
1045 with self.assertRaisesRegex(mv.ManifestError, "cache must not overwrite a listed input"):
1046 self.verify()
1047 self.assertFalse(os.path.exists(self.cache))
1048
1049 def test_cli_cache_equal_to_input_preserves_data(self) -> None:
1050 self.cache = os.path.join(self.game, "a.bin")
1051 result = subprocess.run(
1052 [sys.executable, "-I", TOOL, self.game, "--manifest", self.manifest,
1053 "--cache", self.cache, "--json"],
1054 capture_output=True, text=True, timeout=15,
1055 )
1056 for rel, data in self.data.items():
1057 with open(os.path.join(self.game, rel), "rb") as f:
1058 self.assertEqual(f.read(), data)
1059 self.assertEqual(result.returncode, 2)
1060 self.assertIn("cache must not overwrite a listed input", result.stderr)
1061 self.assertNotIn("Traceback", result.stderr)
1062 self.assertEqual(result.stdout, "")
1063
957 def test_cache_inside_target_and_strict(self) -> None: 1064 def test_cache_inside_target_and_strict(self) -> None:
958 self.cache = os.path.join(self.game, "cache.json") 1065 self.cache = os.path.join(self.game, "cache.json")
959 for _ in range(2): # cold and warm 1066 for _ in range(2): # cold and warm
diff --git a/tests/test_merge_check.py b/tests/test_merge_check.py
index 0b3588ce1..cda334277 100644
--- a/tests/test_merge_check.py
+++ b/tests/test_merge_check.py
@@ -32,7 +32,7 @@ class MergeCheckTest(unittest.TestCase):
32 self.addCleanup(td.cleanup) 32 self.addCleanup(td.cleanup)
33 self.repo = td.name 33 self.repo = td.name
34 env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")} 34 env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")}
35 env.update({"GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1"}) 35 env.update({"GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1", "XDG_CONFIG_HOME": td.name})
36 patcher = mock.patch.dict(os.environ, env, clear=True) 36 patcher = mock.patch.dict(os.environ, env, clear=True)
37 patcher.start() 37 patcher.start()
38 self.addCleanup(patcher.stop) 38 self.addCleanup(patcher.stop)
@@ -117,6 +117,12 @@ class MergeCheckTest(unittest.TestCase):
117 self.assertEqual(len(r["merges"]), 1) 117 self.assertEqual(len(r["merges"]), 1)
118 self.assertEqual(r["commits"], {"total": 1, "on_main": 1}) 118 self.assertEqual(r["commits"], {"total": 1, "on_main": 1})
119 119
120 def test_unicode_line_separator_in_squash_subject(self):
121 self.write("notes.txt", "updated\n")
122 sha = self.commit("Update notes (#10)\u2028and examples (#11)")
123 self.assertEqual(mc.prior_merges(self.repo, "main", [10, 11], 10),
124 {10: [], 11: [sha[:12]]})
125
120 def test_batch_keeps_prior_merges_separate(self): 126 def test_batch_keeps_prior_merges_separate(self):
121 base = self.git("rev-parse", "main") 127 base = self.git("rev-parse", "main")
122 self.pr_branch("landed", base, PARAGRAPH) 128 self.pr_branch("landed", base, PARAGRAPH)
@@ -404,6 +410,33 @@ class MergeCheckTest(unittest.TestCase):
404 self.assertEqual(mc.main(["--repo", self.repo, "--main", "main", "1=no-such-ref"]), 2) 410 self.assertEqual(mc.main(["--repo", self.repo, "--main", "main", "1=no-such-ref"]), 2)
405 self.assertIn("merge_check:", err.getvalue()) 411 self.assertIn("merge_check:", err.getvalue())
406 412
413 def run_without_git(self, patch):
414 out, err = io.StringIO(), io.StringIO()
415 with patch, redirect_stdout(out), redirect_stderr(err):
416 code = mc.main(["--repo", self.repo, "--main", "main", "--json", "20=whatever"])
417 self.assertEqual((code, out.getvalue()), (2, ""))
418 self.assertNotIn("Traceback", err.getvalue())
419 self.assertTrue(err.getvalue().startswith("merge_check: cannot run git: "), err.getvalue())
420 return err.getvalue()
421
422 def test_git_that_cannot_be_run_is_a_git_error_not_a_traceback(self):
423 missing = FileNotFoundError(2, "No such file or directory")
424 message = self.run_without_git(mock.patch.object(subprocess, "run", side_effect=missing))
425 self.assertEqual(message, "merge_check: cannot run git: No such file or directory\n")
426
427 def test_git_missing_from_an_empty_path_is_a_git_error(self):
428 self.run_without_git(mock.patch.dict(os.environ, {"PATH": os.devnull}))
429
430 def test_a_folder_that_is_not_a_repository_is_a_git_error(self):
431 plain = tempfile.TemporaryDirectory(prefix="leonida not a repo ")
432 self.addCleanup(plain.cleanup)
433 err = io.StringIO()
434 with redirect_stdout(io.StringIO()), redirect_stderr(err):
435 code = mc.main(["--repo", plain.name, "--main", "main", "1=HEAD"])
436 self.assertEqual(code, 2)
437 self.assertTrue(err.getvalue().startswith("merge_check: git "), err.getvalue())
438 self.assertNotIn("Traceback", err.getvalue())
439
407 440
408if __name__ == "__main__": 441if __name__ == "__main__":
409 unittest.main() 442 unittest.main()
diff --git a/tests/test_native_pso_hashes.py b/tests/test_native_pso_hashes.py
new file mode 100644
index 000000000..515e5a1d6
--- /dev/null
+++ b/tests/test_native_pso_hashes.py
@@ -0,0 +1,149 @@
1"""tools/native_pso_hashes.py on hand-built DXBC containers and indexes: no game data."""
2import contextlib
3import io
4import json
5import os
6import struct
7import sys
8import tempfile
9import unittest
10from unittest import mock
11
12sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "tools"))
13import native_pso_hashes as tool # noqa: E402
14sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
15import make_game # noqa: E402
16
17
18def container(digest: bytes, other=b"") -> bytes:
19 """A DXBC container with a HASH part (flags 0, then the digest) and an optional second part."""
20 parts = [b"HASH" + struct.pack("<I", 20) + struct.pack("<I", 0) + digest]
21 if other:
22 parts.insert(0, b"PRIV" + struct.pack("<I", len(other)) + other)
23 head = 32 + 4 * len(parts)
24 offsets, at = [], head
25 for p in parts:
26 offsets.append(at)
27 at += len(p)
28 body = b"DXBC" + bytes(16) + struct.pack("<II", 1, at) + struct.pack("<I", len(parts))
29 return body + b"".join(struct.pack("<I", o) for o in offsets) + b"".join(parts)
30
31
32class NativePsoHashesTest(unittest.TestCase):
33 def setUp(self):
34 self.tmp = tempfile.TemporaryDirectory()
35 self.dxbc = os.path.join(self.tmp.name, "shaders", "dxbc")
36 self.spirv = os.path.join(self.tmp.name, "shaders", "spirv")
37 os.makedirs(self.dxbc)
38 os.makedirs(self.spirv)
39
40 def tearDown(self):
41 self.tmp.cleanup()
42
43 def put(self, name, data):
44 with open(os.path.join(self.dxbc, name + ".dxbc"), "wb") as f:
45 f.write(data)
46
47 def index(self, entries):
48 with open(os.path.join(self.spirv, "index.json"), "w", encoding="utf-8", newline="\n") as f:
49 json.dump(entries, f)
50
51 def read(self):
52 with open(os.path.join(self.spirv, tool.OUT_NAME), encoding="utf-8") as f:
53 return f.read().splitlines()
54
55 def test_stage_builds_missing_catalog_and_refreshes_changed_translation(self):
56 d = bytes(range(16))
57 self.put("one", container(d))
58 self.index({"one": {"stage": "vs", "fssm_sha256": "a" * 64}})
59 with mock.patch.object(tool, "build", wraps=tool.build) as build:
60 make_game.native_pso_hashes(self.dxbc, self.spirv)
61 self.assertEqual(build.call_count, 1)
62 self.assertIn(d.hex() + "\tvs\t../dxbc/one.dxbc", self.read())
63 make_game.native_pso_hashes(self.dxbc, self.spirv)
64 self.assertEqual(build.call_count, 1)
65 self.index({})
66 old = os.path.join(self.spirv, tool.OUT_NAME)
67 os.utime(old, (1, 1))
68 make_game.native_pso_hashes(self.dxbc, self.spirv)
69 self.assertEqual(build.call_count, 2)
70 self.assertEqual(self.read(), [tool.HEADER])
71
72 def test_replacing_one_container_refreshes_the_digest(self):
73 self.index({"one": {"stage": "ps", "fssm_sha256": "a" * 64}})
74 self.put("one", container(bytes(16)))
75 make_game.native_pso_hashes(self.dxbc, self.spirv)
76 stamp = os.stat(os.path.join(self.spirv, tool.OUT_NAME)).st_mtime_ns
77 changed = bytes([5]) * 16
78 self.put("one", container(changed))
79 os.utime(os.path.join(self.dxbc, "one.dxbc"), ns=(stamp, stamp + 1000000000))
80 make_game.native_pso_hashes(self.dxbc, self.spirv)
81 self.assertEqual(self.read()[1], changed.hex() + "\tps\t../dxbc/one.dxbc")
82
83 def test_malformed_translator_identity(self):
84 self.put("one", container(bytes(16)))
85 for stage, fssm in (("ps\tvs", "a" * 64), ("vs", "short")):
86 with self.subTest(stage=stage, fssm=fssm):
87 self.index({"one": {"stage": stage, "fssm_sha256": fssm}})
88 with self.assertRaisesRegex(ValueError, "invalid translated stage or FSSM hash"):
89 tool.build(self.dxbc, self.spirv)
90
91 def test_digest_of_a_container(self):
92 d = bytes(range(16))
93 self.assertEqual(tool.hash_digest(container(d)), d)
94 self.assertEqual(tool.hash_digest(container(d, b"x" * 9)), d)
95 self.assertIsNone(tool.hash_digest(b"DXBC" + bytes(28)))
96 self.assertIsNone(tool.hash_digest(container(d)[:-1]))
97 self.assertIsNone(tool.hash_digest(b"FSSM" + bytes(60)))
98
99 def test_map_lines(self):
100 a, b, c = bytes([1] * 16), bytes([2] * 16), bytes([3] * 16)
101 self.put("vs one", container(a))
102 self.put(".ms_dot", container(b))
103 self.put("same_a", container(a, b"other")) # another container with digest a and the same program
104 self.put("untranslated", container(c))
105 self.put("not_dxbc", b"nothing")
106 self.index({"vs one": {"stage": "vs", "fssm_sha256": "1" * 64}, ".ms_dot": {"stage": "ms", "fssm_sha256": "2" * 64},
107 "same_a": {"stage": "vs", "fssm_sha256": "1" * 64}, "not_dxbc": {"stage": "ps", "fssm_sha256": "3" * 64}})
108 self.assertEqual(tool.main(["x", self.dxbc, self.spirv]), 0)
109 lines = self.read()
110 self.assertEqual(lines[0], tool.HEADER)
111 self.assertEqual(lines[1:], [f"{a.hex()}\tvs\t../dxbc/same_a.dxbc", f"{b.hex()}\tms\t../dxbc/.ms_dot.dxbc"])
112 with open(os.path.join(self.spirv, tool.OUT_NAME), "rb") as f:
113 self.assertNotIn(b"\r", f.read())
114
115 def test_a_digest_with_two_programs_does_not_publish_a_partial_map(self):
116 a = bytes([7] * 16)
117 self.put("one", container(a))
118 self.put("two", container(a, b"x"))
119 self.index({"one": {"stage": "ps", "fssm_sha256": "1" * 64}, "two": {"stage": "ps", "fssm_sha256": "2" * 64}})
120 with open(os.path.join(self.spirv, tool.OUT_NAME), "w", encoding="utf-8", newline="\n") as f:
121 f.write("stale\n")
122 with self.assertRaises(tool.DigestClash):
123 tool.build(self.dxbc, self.spirv)
124 self.assertEqual(tool.main(["x", self.dxbc, self.spirv]), 1)
125 self.assertEqual(self.read(), ["stale"])
126
127 def test_no_index(self):
128 self.assertEqual(tool.main(["x", self.dxbc, self.spirv]), 1)
129 self.assertEqual(tool.main(["x"]), 2)
130
131 def test_help_exits_zero(self):
132 for flag in ("-h", "--help"):
133 out = io.StringIO()
134 with contextlib.redirect_stdout(out):
135 self.assertEqual(tool.main(["x", flag]), 0)
136 self.assertIn("native_hashes.txt", out.getvalue())
137
138 def test_a_shared_digest_requires_the_same_stage(self):
139 shared = container(bytes([9]) * 16)
140 self.put("one", shared)
141 self.put("two", shared)
142 self.index({name: {"stage": stage, "fssm_sha256": "1" * 64}
143 for name, stage in (("one", "vs"), ("two", "ps"))})
144 with self.assertRaises(tool.DigestClash):
145 tool.build(self.dxbc, self.spirv)
146
147
148if __name__ == "__main__":
149 unittest.main()
diff --git a/tests/test_native_tool_paths.py b/tests/test_native_tool_paths.py
index 5ed2544b4..078f4901d 100644
--- a/tests/test_native_tool_paths.py
+++ b/tests/test_native_tool_paths.py
@@ -84,15 +84,21 @@ class NativeFolder(unittest.TestCase):
84 with patch.object(run_gpu_tests.os, "name", "posix"): 84 with patch.object(run_gpu_tests.os, "name", "posix"):
85 self.assertEqual(run_gpu_tests.native_folder("/tmp/work-" + MARK), "/tmp/work-" + MARK) 85 self.assertEqual(run_gpu_tests.native_folder("/tmp/work-" + MARK), "/tmp/work-" + MARK)
86 86
87 def test_a_utf8_code_page_keeps_non_ascii_paths(self):
88 with tempfile.TemporaryDirectory() as tmp:
89 work = os.path.join(tmp, "leonida_gpu_work_" + MARK)
90 os.makedirs(work)
91 self.assertEqual(run_gpu_tests.native_folder(work, ansi="utf-8"), work)
92
87 @unittest.skipUnless(os.name == "nt", "8.3 short names are a Windows thing") 93 @unittest.skipUnless(os.name == "nt", "8.3 short names are a Windows thing")
88 def test_a_folder_outside_the_code_page_gets_its_short_name_or_none(self): 94 def test_a_folder_outside_the_code_page_gets_its_short_name_or_none(self):
89 with tempfile.TemporaryDirectory() as tmp: 95 with tempfile.TemporaryDirectory() as tmp:
90 work = os.path.join(tmp, "leonida_gpu_work_" + MARK) 96 work = os.path.join(tmp, "leonida_gpu_work_" + MARK)
91 os.makedirs(work) 97 os.makedirs(work)
92 native = run_gpu_tests.native_folder(work) 98 native = run_gpu_tests.native_folder(work, ansi="cp1252")
93 if native is None: 99 if native is None:
94 self.skipTest("this volume keeps no 8.3 short names (the error path is tested below)") 100 self.skipTest("this volume keeps no 8.3 short names (the error path is tested below)")
95 native.encode("mbcs") # raises if the short name still has a character the code page lacks 101 native.encode("cp1252") # raises if the short name still has a character the code page lacks
96 self.assertNotIn(MARK, native) 102 self.assertNotIn(MARK, native)
97 self.assertTrue(os.path.samefile(native, work)) 103 self.assertTrue(os.path.samefile(native, work))
98 104
diff --git a/tests/test_navmesh_nodes.py b/tests/test_navmesh_nodes.py
index 4dc8e9396..ffd50f93e 100644
--- a/tests/test_navmesh_nodes.py
+++ b/tests/test_navmesh_nodes.py
@@ -272,6 +272,8 @@ class ArchiveTest(unittest.TestCase):
272 def test_cli_refuses_an_unwritable_out_before_the_archives_are_read(self): 272 def test_cli_refuses_an_unwritable_out_before_the_archives_are_read(self):
273 # Both archives are read before the summary is written, so a --out that cannot be written used to cost 273 # Both archives are read before the summary is written, so a --out that cannot be written used to cost
274 # the whole run and then end in a traceback. 274 # the whole run and then end in a traceback.
275 if os.name != "nt" and os.geteuid() == 0:
276 self.skipTest("root bypasses read-only file mode")
275 out = os.path.join(self.tmp.name, "read-only.json") 277 out = os.path.join(self.tmp.name, "read-only.json")
276 with open(out, "w", encoding="utf-8", newline="\n") as f: 278 with open(out, "w", encoding="utf-8", newline="\n") as f:
277 f.write("{}\n") 279 f.write("{}\n")
diff --git a/tests/test_progress_dashboard.py b/tests/test_progress_dashboard.py
index ad22e8149..b5a15e80c 100644
--- a/tests/test_progress_dashboard.py
+++ b/tests/test_progress_dashboard.py
@@ -618,6 +618,22 @@ class Outputs(unittest.TestCase):
618 with open(os.path.join(out, "history.json"), encoding="utf-8") as f: 618 with open(os.path.join(out, "history.json"), encoding="utf-8") as f:
619 self.assertEqual(len(json.load(f)), 1) 619 self.assertEqual(len(json.load(f)), 1)
620 620
621 def test_different_snapshots_in_the_same_second_are_preserved(self):
622 first = {"generated_at": "2026-11-24T00:00:00Z", "git": {"head": "a" * 40},
623 "metrics": [], "content_hash": "a" * 64}
624 second = {**first, "git": {"head": "b" * 40}, "content_hash": "b" * 64}
625 with tempfile.TemporaryDirectory() as out:
626 self.assertTrue(pd.write_outputs(first, out))
627 self.assertTrue(pd.write_outputs(second, out))
628 self.assertFalse(pd.write_outputs(second, out))
629
630 folder = Path(out)
631 snapshots = [json.loads(path.read_text(encoding="utf-8"))
632 for path in (folder / "snapshots").glob("progress_*.json")]
633 self.assertCountEqual(snapshots, [first, second])
634 history = json.loads((folder / "history.json").read_text(encoding="utf-8"))
635 self.assertEqual(history, [pd.summary_line(first), pd.summary_line(second)])
636
621 def test_unmatched_test_filter_preserves_cached_results(self): 637 def test_unmatched_test_filter_preserves_cached_results(self):
622 with tempfile.TemporaryDirectory() as out: 638 with tempfile.TemporaryDirectory() as out:
623 cached = os.path.join(out, "unit_results.json") 639 cached = os.path.join(out, "unit_results.json")
diff --git a/tests/test_rcp_iflag_mods.py b/tests/test_rcp_iflag_mods.py
index f35510611..5439aef92 100644
--- a/tests/test_rcp_iflag_mods.py
+++ b/tests/test_rcp_iflag_mods.py
@@ -74,6 +74,9 @@ class RcpIflagModsTest(unittest.TestCase):
74 self.assertNotRegex(spv, r"\bOpFMul %float\b") 74 self.assertNotRegex(spv, r"\bOpFMul %float\b")
75 75
76 if clamp: 76 if clamp:
77 # DX10_CLAMP: a NaN is replaced by +0 before FClamp (Gen.clamp_mods).
78 nan = match_result(rf"OpIsNan %bool {value}")
79 value = match_result(rf"OpSelect %float {nan} %f0 {value}")
77 value = match_result(rf"OpExtInst %float %glsl FClamp {value} %f0 %f1") 80 value = match_result(rf"OpExtInst %float %glsl FClamp {value} %f0 %f1")
78 else: 81 else:
79 self.assertNotIn("FClamp", spv) 82 self.assertNotIn("FClamp", spv)
diff --git a/tests/test_rpf9dump_exit_codes.py b/tests/test_rpf9dump_exit_codes.py
index 96f0902f1..4caad1823 100644
--- a/tests/test_rpf9dump_exit_codes.py
+++ b/tests/test_rpf9dump_exit_codes.py
@@ -85,11 +85,14 @@ class Rpf9dumpExitCodeTest(unittest.TestCase):
85 src = root / "audio.rpf" 85 src = root / "audio.rpf"
86 awc_rpf(src) 86 awc_rpf(src)
87 wav = root / "out" / "audio" / "xma" / "audio_0001_at_0000000000001000" / "00001234.xma.wav" 87 wav = root / "out" / "audio" / "xma" / "audio_0001_at_0000000000001000" / "00001234.xma.wav"
88 blocker = Path(str(wav) + ".partial") 88 # Util.WriteAtomic stages to unique <path>.<pid>.<tid>.<guid>.partial names, while
89 # File.Exists(wav) is false for a directory, so creating wav as a directory blocks MoveReplace.
90 blocker = wav
89 blocker.mkdir(parents=True) # the write of this one stream fails 91 blocker.mkdir(parents=True) # the write of this one stream fails
90 failed = run("xma", src, root / "out") 92 failed = run("xma", src, root / "out")
91 self.assertNotEqual(failed.returncode, 0, failed.stdout + failed.stderr) 93 self.assertNotEqual(failed.returncode, 0, failed.stdout + failed.stderr)
92 self.assertFalse(wav.exists()) 94 self.assertFalse(wav.is_file())
95 self.assertEqual(list(wav.parent.glob("*.partial")), [])
93 blocker.rmdir() 96 blocker.rmdir()
94 retry = run("xma", src, root / "out") 97 retry = run("xma", src, root / "out")
95 self.assertEqual(retry.returncode, 0, retry.stdout + retry.stderr) 98 self.assertEqual(retry.returncode, 0, retry.stdout + retry.stderr)
@@ -106,11 +109,12 @@ class Rpf9dumpExitCodeTest(unittest.TestCase):
106 texture_dictionary_rpf(src) 109 texture_dictionary_rpf(src)
107 sub = root / "out" / "textures" / "textures" 110 sub = root / "out" / "textures" / "textures"
108 dds = sub / "dictionary_at_0000000000001010" / "000_probe.dds" 111 dds = sub / "dictionary_at_0000000000001010" / "000_probe.dds"
109 blocker = Path(str(dds) + ".partial") 112 blocker = dds
110 blocker.mkdir(parents=True) # the write of this one DDS fails 113 blocker.mkdir(parents=True) # the write of this one DDS fails
111 failed = run("textures", src, root / "out") 114 failed = run("textures", src, root / "out")
112 self.assertNotEqual(failed.returncode, 0, failed.stdout + failed.stderr) 115 self.assertNotEqual(failed.returncode, 0, failed.stdout + failed.stderr)
113 self.assertFalse(dds.exists(), failed.stdout) # the blocked write must not have succeeded 116 self.assertFalse(dds.is_file(), failed.stdout) # the blocked write must not have succeeded
117 self.assertEqual(list(dds.parent.glob("*.partial")), [])
114 self.assertFalse((sub / "manifest.json").exists(), failed.stdout) 118 self.assertFalse((sub / "manifest.json").exists(), failed.stdout)
115 self.assertFalse((sub / "manifest.json.partial").exists()) 119 self.assertFalse((sub / "manifest.json.partial").exists())
116 blocker.rmdir() 120 blocker.rmdir()
diff --git a/tests/test_run_gpu_tests_python_assembler.py b/tests/test_run_gpu_tests_python_assembler.py
index 31a99aa90..d817f4ec0 100644
--- a/tests/test_run_gpu_tests_python_assembler.py
+++ b/tests/test_run_gpu_tests_python_assembler.py
@@ -4,6 +4,7 @@ import json
4import os 4import os
5from pathlib import Path 5from pathlib import Path
6import struct 6import struct
7import subprocess
7import sys 8import sys
8import tempfile 9import tempfile
9from types import SimpleNamespace 10from types import SimpleNamespace
@@ -41,6 +42,44 @@ class PythonAssemblerTests(unittest.TestCase):
41 self.assertGreaterEqual(len(data), 20) 42 self.assertGreaterEqual(len(data), 20)
42 self.assertEqual(struct.unpack("<I", data[:4])[0], 0x07230203) 43 self.assertEqual(struct.unpack("<I", data[:4])[0], 0x07230203)
43 44
45 def test_spirv_as_missing_on_path_is_a_readable_runtime_error(self) -> None:
46 # An empty PATH: spirv-as cannot be found, and the caller must get the RuntimeError it handles for a failed
47 # assembly, not a raw FileNotFoundError traceback (RUN-GPU-SPIRVAS-MISSING).
48 with tempfile.TemporaryDirectory() as tmp, patch.dict(os.environ, {"PATH": ""}):
49 with self.assertRaises(RuntimeError) as ctx:
50 run_gpu_tests.spirv_as("OpCapability Shader\n", str(Path(tmp) / "out.spv"), assembler="spirv-as")
51 self.assertIn("spirv-as not found on PATH", str(ctx.exception))
52 self.assertNotIsInstance(ctx.exception, FileNotFoundError)
53 self.assertIsNone(ctx.exception.__cause__)
54 self.assertTrue(ctx.exception.__suppress_context__)
55
56 def test_spirv_as_other_oserror_is_a_readable_runtime_error(self) -> None:
57 with tempfile.TemporaryDirectory() as tmp, \
58 patch.object(run_gpu_tests.subprocess, "run",
59 side_effect=PermissionError(13, "Permission denied")):
60 with self.assertRaises(RuntimeError) as ctx:
61 run_gpu_tests.spirv_as("", str(Path(tmp) / "out.spv"), assembler="spirv-as")
62 self.assertIn("spirv-as could not be started: Permission denied", str(ctx.exception))
63
64 def test_spirv_as_present_and_succeeding_runs_spirv_as(self) -> None:
65 # Stubbed success: spirv-as is invoked with the same arguments and a zero exit code is not an error.
66 done = subprocess.CompletedProcess(args=[], returncode=0, stdout="", stderr="")
67 with tempfile.TemporaryDirectory() as tmp, \
68 patch.object(run_gpu_tests.subprocess, "run", return_value=done) as run:
69 run_gpu_tests.spirv_as("asm", str(Path(tmp) / "out.spv"), assembler="spirv-as")
70 run.assert_called_once()
71 self.assertEqual(run.call_args.args[0],
72 ["spirv-as", "--target-env", "vulkan1.2", "-o", str(Path(tmp) / "out.spv"), "-"])
73 self.assertEqual(run.call_args.kwargs["input"], "asm")
74
75 def test_spirv_as_nonzero_exit_reports_stderr(self) -> None:
76 bad = subprocess.CompletedProcess(args=[], returncode=1, stdout="", stderr="error: bad opcode")
77 with tempfile.TemporaryDirectory() as tmp, \
78 patch.object(run_gpu_tests.subprocess, "run", return_value=bad):
79 with self.assertRaises(RuntimeError) as ctx:
80 run_gpu_tests.spirv_as("", str(Path(tmp) / "out.spv"), assembler="spirv-as")
81 self.assertIn("error: bad opcode", str(ctx.exception))
82
44 def test_rdna2spirv_assemble_spirv_no_validate_skips_spirv_val(self) -> None: 83 def test_rdna2spirv_assemble_spirv_no_validate_skips_spirv_val(self) -> None:
45 with tempfile.TemporaryDirectory() as tmp: 84 with tempfile.TemporaryDirectory() as tmp:
46 spvasm = Path(tmp) / "fs_passthru.spvasm" 85 spvasm = Path(tmp) / "fs_passthru.spvasm"
diff --git a/tests/test_run_semantic_tests.py b/tests/test_run_semantic_tests.py
index 6cf2d9d31..cf5f3803a 100644
--- a/tests/test_run_semantic_tests.py
+++ b/tests/test_run_semantic_tests.py
@@ -21,6 +21,22 @@ PASS = "import unittest\nimport helper\nclass T(unittest.TestCase):\n def tes
21FAIL = "import unittest\nclass T(unittest.TestCase):\n def test_a(self): self.assertEqual(1, 2, 'boom-msg')\n" 21FAIL = "import unittest\nclass T(unittest.TestCase):\n def test_a(self): self.assertEqual(1, 2, 'boom-msg')\n"
22BROKEN = "import no_such_module_anywhere\n" 22BROKEN = "import no_such_module_anywhere\n"
23HANG = "import time\nprint('before-sleep-marker', flush=True)\ntime.sleep(60)\n" 23HANG = "import time\nprint('before-sleep-marker', flush=True)\ntime.sleep(60)\n"
24RAN0 = ("import unittest\nclass T(unittest.TestCase):\n def test_a(self):\n"
25 " print('Ran 0 tests in 0.000s', flush=True)\n")
26RAN0_AT_EXIT = ("import atexit\nimport unittest\natexit.register(lambda: print('Ran 0 tests in 0.000s'))\n"
27 "class T(unittest.TestCase):\n def test_a(self):\n pass\n")
28# An atexit handler that writes to stderr after unittest's own summary: the count comes from unittest's result
29# object, so the late line cannot change it.
30ATEXIT_STDERR = ("import atexit\nimport sys\nimport unittest\n"
31 "atexit.register(lambda: unittest.TextTestRunner(stream=sys.stderr, verbosity=0)"
32 ".run(unittest.TestSuite()))\n"
33 "class T(unittest.TestCase):\n def test_a(self):\n pass\n")
34LATE_SUMMARY = ("import atexit\nimport sys\nimport unittest\n"
35 "atexit.register(lambda: print('Ran 7 tests in 0.000s', file=sys.stderr))\n"
36 "class T(unittest.TestCase):\n def test_a(self):\n pass\n")
37# A test that runs a nested unittest runner: that runner writes its own summary to stderr while the test runs.
38NESTED = ("import sys\nimport unittest\nclass T(unittest.TestCase):\n def test_a(self):\n"
39 " unittest.TextTestRunner(stream=sys.stderr, verbosity=0).run(unittest.TestSuite())\n")
24 40
25 41
26def suite(tmp, files): 42def suite(tmp, files):
@@ -57,6 +73,39 @@ class RunnerTest(unittest.TestCase):
57 self.assertIn("3 files, 4 tests, 1 files failed", result.stdout) 73 self.assertIn("3 files, 4 tests, 1 files failed", result.stdout)
58 self.assertNotIn("Traceback", result.stdout + result.stderr) 74 self.assertNotIn("Traceback", result.stdout + result.stderr)
59 75
76 def test_the_count_comes_from_unittest_not_from_a_test_line(self):
77 # A test may print a line of the same shape as unittest's own summary. unittest writes its summary to stderr
78 # and a test's own output to stdout, so the count comes from stderr: in the merged output it was whichever
79 # line came first, which depended on stdout buffering.
80 for source in (RAN0, RAN0_AT_EXIT):
81 with self.subTest(source=source.split(chr(10))[0]), tempfile.TemporaryDirectory() as tmp:
82 suite(tmp, {"test_counts.py": source})
83 result = cli(tmp, "-j", "2")
84 self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
85 self.assertIn("1 files, 1 tests, 0 files failed", result.stdout)
86 self.assertNotIn("no tests ran", result.stdout)
87
88 def test_the_count_comes_from_unittest_not_from_a_nested_runner(self):
89 # A test that runs a nested unittest runner writes that runner's summary ("Ran 0 tests in ...") to stderr
90 # while the test runs, before unittest writes its own. The count must come from unittest's own summary.
91 with tempfile.TemporaryDirectory() as tmp:
92 suite(tmp, {"test_counts.py": NESTED})
93 result = cli(tmp, "-j", "2")
94 self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
95 self.assertIn("1 files, 1 tests, 0 files failed", result.stdout)
96 self.assertNotIn("no tests ran", result.stdout)
97
98 def test_the_count_comes_from_the_result_object_not_from_a_late_summary(self):
99 # A summary written to stderr after unittest's own - an atexit handler that runs a nested runner, or one
100 # that prints a line of that shape - must not change the count: it comes from unittest's result object.
101 for source in (ATEXIT_STDERR, LATE_SUMMARY):
102 with self.subTest(source=source.split(chr(10))[0]), tempfile.TemporaryDirectory() as tmp:
103 suite(tmp, {"test_counts.py": source})
104 result = cli(tmp, "-j", "2")
105 self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
106 self.assertIn("1 files, 1 tests, 0 files failed", result.stdout)
107 self.assertNotIn("no tests ran", result.stdout)
108
60 def test_serial_timeout_keeps_discover_output_and_names_the_suite(self): 109 def test_serial_timeout_keeps_discover_output_and_names_the_suite(self):
61 with tempfile.TemporaryDirectory() as tmp: 110 with tempfile.TemporaryDirectory() as tmp:
62 suite(tmp, {"test_hang.py": HANG}) 111 suite(tmp, {"test_hang.py": HANG})
diff --git a/tests/test_semantic_mutants.py b/tests/test_semantic_mutants.py
index 42ac9917a..13743d267 100644
--- a/tests/test_semantic_mutants.py
+++ b/tests/test_semantic_mutants.py
@@ -80,6 +80,133 @@ class Generation(unittest.TestCase):
80 self.assertEqual(sum(1 for m in self.mutants if m.line == line and m.label == "OpIAdd -> OpISub"), 1) 80 self.assertEqual(sum(1 for m in self.mutants if m.line == line and m.label == "OpIAdd -> OpISub"), 1)
81 self.assertFalse(any(m.line == line and m.label == "OpISub -> OpIAdd" for m in self.mutants)) 81 self.assertFalse(any(m.line == line and m.label == "OpISub -> OpIAdd" for m in self.mutants))
82 82
83 def test_docstrings_are_left_alone(self):
84 # A docstring is text: an OpIAdd/UMin named there can't fail a test, so a mutant of it always "survives".
85 source = textwrap.dedent('''\
86 class Gen:
87 def helper(self, x, y):
88 """Emit OpIAdd, then UMin with self.cu(31)."""
89 self.emit(f"{r} = OpIAdd %uint {x} {y}")
90
91 def multi(self, x):
92 """First line.
93
94 OpISub and NMin are named here too.
95 """
96 self.emit(f"{t} = OpExtInst %uint %glsl UMin {x} {self.cu(31)}")
97 s = "OpISub in a plain string assignment is still code"
98 ''').split("\n")
99 for name, code_lines in (("helper", [4]), ("multi", [11, 12])):
100 first, last = sm.find_function(source, name)
101 lines = {m.line for m in sm.mutants_for(source, first, last)}
102 with self.subTest(function=name):
103 self.assertEqual(sorted(lines), code_lines)
104 # A --lines range can start or end inside a docstring, without its opening or closing delimiter.
105 inside = next(i for i, s in enumerate(source) if "OpISub and NMin" in s) # 0-based
106 for first, last in ((inside, inside), (inside, inside + 2), (inside - 3, inside)):
107 with self.subTest(lines=(first + 1, last + 1)):
108 lines = {m.line for m in sm.mutants_for(source, first, last)}
109 self.assertEqual(sorted(lines), [n for n in (11,) if first < n <= last + 1])
110
111 def test_docstring_after_a_comment_with_quotes_and_concatenated_docstring(self):
112 # Two forms ast.get_docstring() accepts (@lixonik on #660): a `"""` in a comment before the docstring is no
113 # delimiter, and adjacent literals ("a " "b") are one docstring.
114 source = textwrap.dedent('''\
115 class Gen:
116 def f(self, x, y):
117 # a comment with """ in it, and one with \'\'\' too
118 """Start of the docstring.
119
120 OpIAdd is named here.
121 """
122 self.emit(f"{r} = OpIAdd %uint {x} {y}")
123
124 def g(self, x, y):
125 "OpIAdd is an example. " "Emit an instruction."
126 self.emit(f"{r} = OpIAdd %uint {x} {y}")
127
128 def h(self, x, y):
129 ("UMin is not a docstring here: the call reads it, so it is code. "
130 "OpISub") and self.emit(f"{r} = OpIAdd %uint {x} {y}")
131 ''').split("\n")
132 named = next(i for i, s in enumerate(source) if "OpIAdd is named here" in s)
133 self.assertEqual(sm.mutants_for(source, named, named), [])
134 for name, code_lines in (("f", [8]), ("g", [12])):
135 first, last = sm.find_function(source, name)
136 with self.subTest(function=name):
137 self.assertEqual(sorted({m.line for m in sm.mutants_for(source, first, last)}), code_lines)
138 first, last = sm.find_function(source, "h")
139 self.assertIn(16, {m.line for m in sm.mutants_for(source, first, last)}) # still code: mutated
140
141
142LOGIC = textwrap.dedent('''\
143 class Gen:
144 def op(self, op, a):
145 if op == "v_other":
146 pass
147 elif op in ("v_logic",):
148 seen, out = set(), []
149 for r in a:
150 if r not in seen and r > 3:
151 out.append(r)
152 seen.update([r])
153 n = 0
154 n += 1
155 n = len(out)
156 ok = n is None or not out
157 both = ok and n and out
158 flag = True
159 self.emit(f"{t} = OpIAdd %uint {x} {self.cu(0)}")
160 s = "a == b and c in d" # a comment: x == y and not z
161 return [x for x in out if x in seen]
162 ''').split("\n")
163
164
165class PythonLogic(unittest.TestCase):
166 """The analysis code around the emission: comparisons, and/or, not, True/False, silent statements."""
167
168 def setUp(self):
169 self.first, self.last = sm.find_branch(LOGIC, "v_logic")
170 self.mutants = sm.mutants_for(LOGIC, self.first, self.last)
171
172 def labels(self, text):
173 line = next(i for i, s in enumerate(LOGIC) if text in s) + 1
174 return sorted(m.label for m in self.mutants if m.line == line)
175
176 def test_comparisons_and_boolean_operators(self):
177 self.assertEqual(self.labels("if r not in seen"), ["> -> >=", "and -> or", "not in -> in"])
178 self.assertEqual(self.labels("ok = n is None"), ["is -> is not", "not removed", "or -> and"])
179 self.assertEqual(self.labels("both = ok"), ["and -> or #1", "and -> or #2"])
180 self.assertEqual(self.labels("flag = True"), ["True -> False"])
181
182 def test_silent_statements_are_removed(self):
183 for text in ("out.append(r)", "seen.update([r])", "n += 1", "n = len(out)"):
184 with self.subTest(statement=text):
185 self.assertEqual(self.labels(text), ["statement removed"])
186 removed = next(m for m in self.mutants if "out.append(r)" in m.old)
187 self.assertEqual(removed.new, removed.old[:len(removed.old) - len(removed.old.lstrip())] + "pass")
188
189 def test_first_assignments_and_compound_lines_stay(self):
190 # Removing a first assignment is only a NameError; `for`, `return` and the emit are not simple statements.
191 self.assertEqual(self.labels("seen, out = set()"), [])
192 self.assertEqual(self.labels("n = 0"), [])
193 self.assertEqual(self.labels("for r in a"), [])
194
195 def test_strings_comments_emit_and_branch_condition_are_left_alone(self):
196 self.assertEqual(self.labels('s = "a == b'), [])
197 self.assertEqual(self.labels("self.emit("), ["OpIAdd -> OpISub", "self.cu(0) -> self.cu(1)"])
198 self.assertEqual(self.labels('elif op in ("v_logic",)'), [])
199
200 def test_the_in_of_a_comprehension_loop_stays(self):
201 self.assertEqual(self.labels("return [x for x in out"), ["in -> not in"])
202
203 def test_every_mutant_still_compiles(self):
204 for m in self.mutants:
205 mutated = list(LOGIC)
206 mutated[m.line - 1] = m.new
207 with self.subTest(line=m.line, label=m.label):
208 compile("\n".join(mutated), "<mutant>", "exec")
209
83 210
84class Tables(unittest.TestCase): 211class Tables(unittest.TestCase):
85 def test_entry_takes_the_other_values_of_its_table(self): 212 def test_entry_takes_the_other_values_of_its_table(self):
diff --git a/tests/test_semantic_translator_use.py b/tests/test_semantic_translator_use.py
index b862c9e84..186e1e555 100644
--- a/tests/test_semantic_translator_use.py
+++ b/tests/test_semantic_translator_use.py
@@ -43,44 +43,10 @@ ALLOWLIST = {
43# or deleting it, simply removes it from the debt. Do not move a file here to silence the guard. 43# or deleting it, simply removes it from the debt. Do not move a file here to silence the guard.
44DEBT = { 44DEBT = {
45 "test_valu_div_fixup.py": "private oracle whose rules RDNA2 disagrees with; TEST-545 replaces it", 45 "test_valu_div_fixup.py": "private oracle whose rules RDNA2 disagrees with; TEST-545 replaces it",
46 "test_alu_cndmask_b64.py": "private oracle merged before this guard (2026-11-22); should translate a listing",
47 "test_int_to_float.py": "private oracle merged before this guard (2026-11-22); should translate a listing",
48 "test_lds_add_sub_src2_u32.py": "private oracle merged before this guard (2026-11-22); should translate a listing",
49 "test_salu_add_sub_co_u32.py": "private oracle merged before this guard (2026-11-22); should translate a listing",
50 "test_salu_and_saveexec_b64.py": "private oracle merged before this guard (2026-11-22); should translate a listing",
51 "test_salu_andn2_saveexec_b64.py": "private oracle merged before this guard (2026-11-22); should translate a listing",
52 "test_salu_nand_nor_saveexec_b64.py": "private oracle merged before this guard (2026-11-22); should translate a listing",
53 "test_salu_or_saveexec_b64.py": "private oracle merged before this guard (2026-11-22); should translate a listing",
54 "test_salu_orn2_saveexec_b64.py": "private oracle merged before this guard (2026-11-22); should translate a listing",
55 "test_salu_xnor_saveexec_b64.py": "private oracle merged before this guard (2026-11-22); should translate a listing",
56 "test_salu_xor_saveexec_b64.py": "private oracle merged before this guard (2026-11-22); should translate a listing",
57 "test_valu_alignbyte_b32.py": "private oracle merged before this guard (2026-11-22); should translate a listing",
58 "test_valu_cvt_f32_f64.py": "private oracle merged before this guard (2026-11-22); should translate a listing",
59 "test_valu_dot4_int.py": "private oracle merged before this guard (2026-11-22); should translate a listing",
60 "test_valu_dot8_int.py": "private oracle merged before this guard (2026-11-22); should translate a listing",
61 "test_valu_fma_f64.py": "private oracle merged before this guard (2026-11-22); should translate a listing", 46 "test_valu_fma_f64.py": "private oracle merged before this guard (2026-11-22); should translate a listing",
62 "test_valu_fract_f16.py": "private oracle merged before this guard (2026-11-22); should translate a listing",
63 "test_valu_fract_f64.py": "private oracle merged before this guard (2026-11-22); should translate a listing", 47 "test_valu_fract_f64.py": "private oracle merged before this guard (2026-11-22); should translate a listing",
64 "test_valu_frexp_exp_i32_f64.py": "private oracle merged before this guard (2026-11-22); should translate a listing",
65 "test_valu_frexp_f64.py": "private oracle merged before this guard (2026-11-22); should translate a listing",
66 "test_valu_frexp_mant_f64.py": "private oracle merged before this guard (2026-11-22); should translate a listing",
67 "test_valu_lerp_u8.py": "private oracle merged before this guard (2026-11-22); should translate a listing",
68 "test_valu_minmax_f64.py": "private oracle merged before this guard (2026-11-22); should translate a listing", 48 "test_valu_minmax_f64.py": "private oracle merged before this guard (2026-11-22); should translate a listing",
69 "test_valu_mul_f64.py": "private oracle merged before this guard (2026-11-22); should translate a listing", 49 "test_valu_mul_f64.py": "private oracle merged before this guard (2026-11-22); should translate a listing",
70 "test_valu_mul_hi.py": "private oracle merged before this guard (2026-11-22); should translate a listing",
71 "test_valu_pack_b32_f16.py": "private oracle merged before this guard (2026-11-22); should translate a listing",
72 "test_valu_perm_b32.py": "private oracle merged before this guard (2026-11-22); should translate a listing",
73 "test_valu_pk_add_f16.py": "private oracle merged before this guard (2026-11-22); should translate a listing",
74 "test_valu_pk_fma_f16.py": "private oracle merged before this guard (2026-11-22); should translate a listing",
75 "test_valu_pk_minmax_f16.py": "private oracle merged before this guard (2026-11-22); should translate a listing",
76 "test_valu_pk_mul_f16.py": "private oracle merged before this guard (2026-11-22); should translate a listing",
77 "test_valu_rcp_f16.py": "private oracle merged before this guard (2026-11-22); should translate a listing",
78 "test_valu_rcp_f64.py": "private oracle merged before this guard (2026-11-22); should translate a listing",
79 "test_valu_rsq_f16.py": "private oracle merged before this guard (2026-11-22); should translate a listing",
80 "test_valu_rsq_f64.py": "private oracle merged before this guard (2026-11-22); should translate a listing",
81 "test_valu_sad_u32.py": "private oracle merged before this guard (2026-11-22); should translate a listing",
82 "test_valu_sqrt_f16.py": "private oracle merged before this guard (2026-11-22); should translate a listing",
83 "test_valu_sqrt_f64.py": "private oracle merged before this guard (2026-11-22); should translate a listing",
84 "test_valu_trig_f64.py": "private oracle merged before this guard (2026-11-22); should translate a listing", 50 "test_valu_trig_f64.py": "private oracle merged before this guard (2026-11-22); should translate a listing",
85} 51}
86 52
diff --git a/tests/test_shader_build_fallbacks.py b/tests/test_shader_build_fallbacks.py
index 206be1f18..e205bfe95 100644
--- a/tests/test_shader_build_fallbacks.py
+++ b/tests/test_shader_build_fallbacks.py
@@ -91,6 +91,11 @@ class BuildUnderFallbackTest(unittest.TestCase):
91 self.assertIn("ps_ij_computed", printed) 91 self.assertIn("ps_ij_computed", printed)
92 self.assertIn("PerVertexKHR", printed) 92 self.assertIn("PerVertexKHR", printed)
93 93
94 def test_missing_mullit_fixture_is_not_accepted_as_a_build_target(self):
95 status, printed = self.run_build(["ps_mullit"], {})
96 self.assertEqual(status, "Unknown test shaders: ps_mullit", printed)
97 self.assertEqual(self.asked, [])
98
94 def test_the_whole_list_builds_under_a_fallback(self): 99 def test_the_whole_list_builds_under_a_fallback(self):
95 # Before: "Translation did not produce validated SPIR-V for: ps_ij_computed", and an empty <out>/spirv. 100 # Before: "Translation did not produce validated SPIR-V for: ps_ij_computed", and an empty <out>/spirv.
96 status, printed = self.run_build([], {"LEONIDA_F16_INTERP_FALLBACK": "1"}) 101 status, printed = self.run_build([], {"LEONIDA_F16_INTERP_FALLBACK": "1"})
diff --git a/tests/test_shader_checks.py b/tests/test_shader_checks.py
index 20758886b..b700f9101 100644
--- a/tests/test_shader_checks.py
+++ b/tests/test_shader_checks.py
@@ -30,14 +30,15 @@ PARTIAL = {n for n, _ in check.W64X_PARTIAL}
30WAVE32_WORDS = {n: w for n, w in check.CS_DUMPS if n in check.WAVE32_DUMPS and n not in ("cs_store", "cs_smem_soffset_imm")} 30WAVE32_WORDS = {n: w for n, w in check.CS_DUMPS if n in check.WAVE32_DUMPS and n not in ("cs_store", "cs_smem_soffset_imm")}
31 31
32 32
33# All check.py cases, including the six vk_store_test shaders and the three mesh fixtures, and TEST-184's 33# All check.py cases, including the seven vk_store_test shaders and the three mesh fixtures, and TEST-184's
34# vk_store_test "words" fixtures and image_get_lod draws. 34# vk_store_test "words" fixtures and image_get_lod draws.
35TOTAL = (len(check.COMPUTE) + 7 + len(check.CS_DUMPS) + len(check.W64X_DUMPS) + len(check.W64X_PARTIAL) + 6 35TOTAL = (len(check.COMPUTE) + 7 + len(check.CS_DUMPS) + len(check.W64X_DUMPS) + len(check.W64X_PARTIAL) + 7
36 + len(check.PIXEL_TESTS) + len(check.CLIP_TESTS) + len(check.BOUNDS) + len(check.GLOBAL_OFFSET) 36 + len(check.PIXEL_TESTS) + len(check.CLIP_TESTS) + len(check.BOUNDS) + len(check.GLOBAL_OFFSET)
37 + len(check.MIP_TEST_PASSES) + len(check.GRADIENT_TESTS) 37 + len(check.MIP_TEST_PASSES) + len(check.GRADIENT_TESTS)
38 + len(check.STORE_WORDS) + len(check.GET_LOD_TESTS) 38 + len(check.STORE_WORDS) + len(check.GET_LOD_TESTS)
39 + len(check.TEXTURE_CONSTANTS) + 16) # three mesh fixtures, ps_tex, ps_imgatomic, ps_table_fetch, six compute fixtures, 39 + len(check.TEXTURE_CONSTANTS) + 17) # three mesh fixtures, ps_tex, ps_imgatomic, ps_table_fetch, six compute fixtures,
40 # ps_ssharp, vs_base_ids, main's standalone cs_fmt_d16_xyz / cs_heap_init dumps (net one more case) and cs_fmt_all 40 # ps_ssharp, vs_base_ids, main's standalone cs_fmt_d16_xyz / cs_heap_init dumps (net one more case), cs_fmt_all
41 # and cs_w32_shift64
41CVT = {bits: [u, s] for bits, u, s in check.CVT_F32_SAT_CASES} 42CVT = {bits: [u, s] for bits, u, s in check.CVT_F32_SAT_CASES}
42 43
43 44
@@ -96,6 +97,14 @@ class Wave64Checks(unittest.TestCase):
96 env.get("VKC_OUT_WORDS") == "68" 97 env.get("VKC_OUT_WORDS") == "68"
97 words = check.HEAP_INIT_EXPECTED if seeded else [0xEEEEEEEE] * 8 98 words = check.HEAP_INIT_EXPECTED if seeded else [0xEEEEEEEE] * 8
98 return 0, "out[0..7] = " + " ".join(map(str, words)) + "\n" 99 return 0, "out[0..7] = " + " ".join(map(str, words)) + "\n"
100 if name == "cs_w32_shift64":
101 # The shifted words come back only if check.py seeded the input records through VKC_HEAP_INIT.
102 initial, expected = check.shift64_words()
103 self.assertEqual((args, env["VKC_OUT_WORDS"]), (("1", "dump"), str(len(expected))))
104 seeded = Path(env["VKC_HEAP_INIT"]).read_bytes() == struct.pack(f"<{len(initial)}I", *initial)
105 words = expected if seeded else initial
106 Path(env["VKC_DUMP"]).write_bytes(struct.pack(f"<{len(words)}I", *words))
107 return 0, ""
99 if name == "cs_user_sgprs": 108 if name == "cs_user_sgprs":
100 # The seeded words come back only if check.py passed them in VKC_SGPRS. 109 # The seeded words come back only if check.py passed them in VKC_SGPRS.
101 seeded = (env or {}).get("VKC_SGPRS") == check.USER_SGPRS_ENV["VKC_SGPRS"] 110 seeded = (env or {}).get("VKC_SGPRS") == check.USER_SGPRS_ENV["VKC_SGPRS"]
@@ -159,8 +168,8 @@ class Wave64Checks(unittest.TestCase):
159 return 0, "out[0..7] = " + " ".join(map(str, (WAVE32_WORDS[name] + [0] * 8)[:8])) + "\n" 168 return 0, "out[0..7] = " + " ".join(map(str, (WAVE32_WORDS[name] + [0] * 8)[:8])) + "\n"
160 if name == "cs_workgroup_yz": # #186: vk_compute_test's 2x3x4 Y/Z histogram line 169 if name == "cs_workgroup_yz": # #186: vk_compute_test's 2x3x4 Y/Z histogram line
161 return 0, "2x3x4 workgroup Y/Z: 0 mismatches\n" 170 return 0, "2x3x4 workgroup Y/Z: 0 mismatches\n"
162 if name in ("cs_imgstore", "cs_imgload", "cs_imgload_tfe", "cs_imgload_d16", "cs_imgload_d16_tfe", 171 if name in ("cs_imgstore", "cs_imgstore_cube", "cs_imgload", "cs_imgload_tfe", "cs_imgload_d16",
163 "cs_sample_lz_int_d16"): # vk_store_test checks 172 "cs_imgload_d16_tfe", "cs_sample_lz_int_d16"): # vk_store_test checks
164 return 0, "0 bad\n0 bad\n0 bad\n" 173 return 0, "0 bad\n0 bad\n0 bad\n"
165 if name in check.STORE_WORDS: # vk_store_test "words": the three images, judged by check.py 174 if name in check.STORE_WORDS: # vk_store_test "words": the three images, judged by check.py
166 self.assertEqual(args, ("words",)) 175 self.assertEqual(args, ("words",))
diff --git a/tests/test_shader_stage_resume.py b/tests/test_shader_stage_resume.py
index 1b5cc2870..e3645dbc5 100644
--- a/tests/test_shader_stage_resume.py
+++ b/tests/test_shader_stage_resume.py
@@ -93,6 +93,10 @@ class ShaderStageResumeTest(unittest.TestCase):
93 json.dump([{"file": "s0.dxbc"}], f) 93 json.dump([{"file": "s0.dxbc"}], f)
94 elif p == os.path.join(self.dxbc, "fssm_index.json"): 94 elif p == os.path.join(self.dxbc, "fssm_index.json"):
95 json.dump([{"name": "s0"}], f) 95 json.dump([{"name": "s0"}], f)
96 elif p == os.path.join(self.spirv, "index.json"):
97 with open(os.path.join(self.dxbc, "index.json"), encoding="utf-8") as source:
98 carved = json.load(source)
99 json.dump({os.path.splitext(entry["file"])[0]: {"stage": "vs"} for entry in carved}, f)
96 elif p.endswith(".s"): 100 elif p.endswith(".s"):
97 f.write("synthetic listing\n") 101 f.write("synthetic listing\n")
98 102
@@ -528,8 +532,8 @@ class ShaderStageResumeTest(unittest.TestCase):
528 532
529 533
530class TranslationSourcesTest(unittest.TestCase): 534class TranslationSourcesTest(unittest.TestCase):
531 def test_the_list_covers_every_local_module_the_translator_imports(self): 535 def test_the_list_covers_the_translator_and_native_catalog_imports(self):
532 seen, todo = set(), ["rdna2spirv"] 536 seen, todo = set(), ["rdna2spirv", "native_pso_hashes"]
533 while todo: 537 while todo:
534 name = todo.pop() 538 name = todo.pop()
535 if name in seen: 539 if name in seen:
@@ -549,6 +553,44 @@ class TranslationSourcesTest(unittest.TestCase):
549 self.assertEqual({n + ".py" for n in seen}, 553 self.assertEqual({n + ".py" for n in seen},
550 {n for n in make_game.TRANSLATION_SOURCES if n.endswith(".py")}) 554 {n for n in make_game.TRANSLATION_SOURCES if n.endswith(".py")})
551 555
556 def test_each_compute_stage_declares_every_module_its_tools_import(self):
557 """The three compute steps' settings lines (make_game.fspx_settings, library_settings, bvh_settings) hash
558 their own tool list plus TRANSLATION_SOURCES. A module a stage tool imports decides what that stage's
559 listings say, so it has to be named by one of the two lists: otherwise editing it leaves a work folder
560 that reuses a cache its own tool change should have thrown away. tools/shader_disasm.py is declared as a
561 tool of all three steps, and it imports tools/rdna2_decode.py, tools/rdna2_isa_tables.py and
562 tools/mc_command.py; tools/shader_library.py carves through tools/shader_carve.py.
563 """
564 declared = {n[:-3] for n in make_game.TRANSLATION_SOURCES if n.endswith(".py")}
565
566 def local_imports(name: str):
567 with open(os.path.join(make_game.TOOLS, name + ".py"), encoding="utf-8") as f:
568 tree = ast.parse(f.read())
569 out = []
570 for node in ast.walk(tree): # function-level imports too
571 if isinstance(node, ast.Import):
572 mods = [a.name for a in node.names]
573 elif isinstance(node, ast.ImportFrom) and node.module and not node.level:
574 mods = [node.module]
575 else:
576 continue
577 out += [m.split(".")[0] for m in mods
578 if os.path.isfile(os.path.join(make_game.TOOLS, m.split(".")[0] + ".py"))]
579 return out
580
581 for stage, tools in (("fspx", make_game.FSPX_TOOLS), ("library", make_game.LIBRARY_TOOLS),
582 ("bvh", make_game.BVH_TOOLS)):
583 seeds, seen, todo = {n[:-3] for n in tools}, set(), []
584 seen |= seeds
585 todo += sorted(seeds)
586 while todo:
587 name = todo.pop()
588 seen.add(name)
589 todo += [n for n in local_imports(name) if n not in seen]
590 left = sorted(seen - declared - seeds)
591 self.assertEqual(left, [], f"{stage} stage: {left} are imported by its declared tools and hashed by "
592 f"neither {stage.upper()}_TOOLS nor TRANSLATION_SOURCES")
593
552 594
553class MergePublishesLastTest(unittest.TestCase): 595class MergePublishesLastTest(unittest.TestCase):
554 """rdna2spirv.py --merge writes the stubs before index.json, which tells make_game.py the translation finished.""" 596 """rdna2spirv.py --merge writes the stubs before index.json, which tells make_game.py the translation finished."""
diff --git a/tests/test_spirv_asm.py b/tests/test_spirv_asm.py
index cd15b0dba..608f20ffe 100644
--- a/tests/test_spirv_asm.py
+++ b/tests/test_spirv_asm.py
@@ -168,6 +168,49 @@ class SpirvAsmUnitTests(unittest.TestCase):
168 with self.subTest(body=body): 168 with self.subTest(body=body):
169 self.assertTrue(spirv_asm.assemble("%uint = OpTypeInt 32 0\n" + body)) 169 self.assertTrue(spirv_asm.assemble("%uint = OpTypeInt 32 0\n" + body))
170 170
171 def test_named_shader_debuginfo_with_forward_references(self):
172 # A function refers to its parent composite, which in turn lists the function as a member.
173 asm = """OpCapability Shader
174OpExtension "SPV_KHR_non_semantic_info"
175OpExtension "SPV_KHR_relaxed_extended_instruction"
176%dbg = OpExtInstImport "NonSemantic.Shader.DebugInfo.100"
177OpMemoryModel Logical GLSL450
178OpEntryPoint GLCompute %main "main"
179OpExecutionMode %main LocalSize 1 1 1
180%name = OpString "demo"
181%void = OpTypeVoid
182%uint = OpTypeInt 32 0
183%zero = OpConstant %uint 0
184%fn = OpTypeFunction %void
185%src = OpExtInst %void %dbg DebugSource %name %name
186%unit = OpExtInst %void %dbg DebugCompilationUnit %zero %zero %src %zero
187%type = OpExtInstWithForwardRefsKHR %void %dbg DebugTypeFunction %zero %class
188%method = OpExtInstWithForwardRefsKHR %void %dbg DebugFunction %name %type %src %zero %zero %class %name %zero %zero
189%class = OpExtInst %void %dbg DebugTypeComposite %name %zero %src %zero %zero %unit %name %zero %zero %method
190%main = OpFunction %void None %fn
191%entry = OpLabel
192OpReturn
193OpFunctionEnd
194"""
195 numeric = asm
196 for name, opcode in (("DebugSource", 35), ("DebugCompilationUnit", 1), ("DebugTypeFunction", 8),
197 ("DebugFunction", 20), ("DebugTypeComposite", 10)):
198 numeric = numeric.replace(f" %dbg {name} ", f" %dbg {opcode} ")
199 spv = spirv_asm.assemble(asm)
200 self.assertEqual(spv, spirv_asm.assemble(numeric))
201 _validate(spv)
202 if SPIRV_AS:
203 with tempfile.TemporaryDirectory() as tmp:
204 src = os.path.join(tmp, "debug.spvasm")
205 out = os.path.join(tmp, "debug.spv")
206 with open(src, "w", encoding="utf-8", newline="\n") as f:
207 f.write(asm)
208 subprocess.run([SPIRV_AS, "--target-env", "vulkan1.2", src, "-o", out],
209 check=True, capture_output=True)
210 with open(out, "rb") as f:
211 reference = f.read()
212 self.assertEqual(spv[:8] + spv[12:], reference[:8] + reference[12:])
213
171 def test_header_and_target_env_versions(self): 214 def test_header_and_target_env_versions(self):
172 asm = ( 215 asm = (
173 "OpCapability Shader\n" 216 "OpCapability Shader\n"
diff --git a/tests/test_stale_build.py b/tests/test_stale_build.py
new file mode 100644
index 000000000..0d30b13e6
--- /dev/null
+++ b/tests/test_stale_build.py
@@ -0,0 +1,143 @@
1"""tools/stale_build.py: which sources of a runtime/test program are newer than its built copy.
2
3 python3 -I tests/test_stale_build.py
4
5Standard library only. Every case builds a small source tree in a temporary folder and sets the modification times
6explicitly, so the results do not depend on how fast the files were written. No game data.
7"""
8import os
9import pathlib
10import sys
11import tempfile
12import unittest
13
14ROOT = pathlib.Path(__file__).resolve().parent.parent
15TOOLS = ROOT / "tools"
16sys.path.insert(0, str(TOOLS))
17import stale_build # noqa: E402
18
19BASE = 1_700_000_000
20OLD = BASE + 100 # the built copy
21NEW = BASE + 1000 # the sources
22
23
24def write(root, rel, text=""):
25 path = os.path.join(root, *rel.split("/"))
26 os.makedirs(os.path.dirname(path), exist_ok=True)
27 with open(path, "w", encoding="utf-8", newline="\n") as f:
28 f.write(text)
29 return path
30
31
32def set_mtime(path, when):
33 os.utime(path, (when, when))
34
35
36def rel(root, paths):
37 return sorted(os.path.relpath(p, root).replace(os.sep, "/") for p in paths)
38
39
40class StaleBuildTests(unittest.TestCase):
41 def setUp(self):
42 self.tmp = tempfile.TemporaryDirectory()
43 self.addCleanup(self.tmp.cleanup)
44 self.root = self.tmp.name
45 # prog.cpp: a header beside it, a header in runtime/src through "../src", and one that does not exist.
46 self.cpp = write(self.root, "runtime/test/prog.cpp",
47 '#include "helper.h"\n#include "../src/x.h"\n#include "missing.h"\nint main() {}\n')
48 self.helper = write(self.root, "runtime/test/helper.h", "#pragma once\n")
49 self.x = write(self.root, "runtime/src/x.h", "#pragma once\n")
50 self.exe = os.path.join(self.root, "build", "prog")
51 os.makedirs(os.path.dirname(self.exe))
52 write(self.root, "build/prog", "binary")
53 for path in (self.cpp, self.helper, self.x):
54 set_mtime(path, NEW)
55
56 def build(self, when):
57 set_mtime(self.exe, when)
58
59 def test_program_sources_follows_includes_and_skips_missing(self):
60 found = stale_build.program_sources(self.root, "prog")
61 self.assertEqual(rel(self.root, found),
62 ["runtime/src/x.h", "runtime/test/helper.h", "runtime/test/prog.cpp"])
63
64 def test_stale_exe_lists_the_newer_sources(self):
65 self.build(OLD)
66 self.assertEqual(sorted(stale_build.newer_sources(self.exe, self.root, "prog")),
67 ["runtime/src/x.h", "runtime/test/helper.h", "runtime/test/prog.cpp"])
68
69 def test_only_the_touched_header_is_reported(self):
70 self.build(BASE + 500)
71 set_mtime(self.helper, BASE + 600)
72 set_mtime(self.cpp, BASE + 400)
73 set_mtime(self.x, BASE + 400)
74 self.assertEqual(stale_build.newer_sources(self.exe, self.root, "prog"), ["runtime/test/helper.h"])
75
76 def test_fresh_exe_lists_nothing(self):
77 self.build(BASE + 2000)
78 self.assertEqual(stale_build.newer_sources(self.exe, self.root, "prog"), [])
79
80 def test_missing_exe_lists_nothing(self):
81 self.assertEqual(stale_build.newer_sources(os.path.join(self.root, "build", "absent"),
82 self.root, "prog"), [])
83
84 def test_missing_exe_path_outside_any_tree(self):
85 self.assertEqual(stale_build.newer_sources("/nonexistent/exe", self.root, "prog"), [])
86
87 def test_program_without_source_lists_nothing(self):
88 self.build(OLD)
89 self.assertEqual(stale_build.program_sources(self.root, "no_such_program"), [])
90 self.assertEqual(stale_build.newer_sources(self.exe, self.root, "no_such_program"), [])
91
92 def test_no_runtime_folder_at_all(self):
93 empty = tempfile.TemporaryDirectory()
94 self.addCleanup(empty.cleanup)
95 self.assertEqual(stale_build.program_sources(empty.name, "prog"), [])
96
97 def test_empty_source_file_is_a_source(self):
98 empty = write(self.root, "runtime/test/empty.cpp", "")
99 set_mtime(empty, NEW)
100 self.build(OLD)
101 self.assertEqual(rel(self.root, stale_build.program_sources(self.root, "empty")),
102 ["runtime/test/empty.cpp"])
103 self.assertEqual(stale_build.newer_sources(self.exe, self.root, "empty"), ["runtime/test/empty.cpp"])
104
105 def test_include_cycle_terminates_and_lists_each_file_once(self):
106 write(self.root, "runtime/test/cyc.cpp", '#include "a.h"\n')
107 write(self.root, "runtime/test/a.h", '#include "b.h"\n')
108 write(self.root, "runtime/test/b.h", '#include "a.h"\n')
109 found = stale_build.program_sources(self.root, "cyc")
110 self.assertEqual(rel(self.root, found), ["runtime/test/a.h", "runtime/test/b.h", "runtime/test/cyc.cpp"])
111
112 def test_header_included_twice_is_listed_once(self):
113 write(self.root, "runtime/test/dup.cpp",
114 '#include "helper.h"\n#include "helper.h"\n#include "../test/helper.h"\n')
115 found = stale_build.program_sources(self.root, "dup")
116 self.assertEqual(rel(self.root, found), ["runtime/test/dup.cpp", "runtime/test/helper.h"])
117
118 def test_directory_named_like_an_include_is_skipped(self):
119 os.makedirs(os.path.join(self.root, "runtime", "test", "isdir.h"))
120 write(self.root, "runtime/test/dirinc.cpp", '#include "isdir.h"\n')
121 found = stale_build.program_sources(self.root, "dirinc")
122 self.assertEqual(rel(self.root, found), ["runtime/test/dirinc.cpp"])
123
124 def test_exe_mtime_equal_to_source_is_not_stale(self):
125 # newer_sources compares with ">", so a source whose mtime equals the exe's is not reported. This pins that
126 # behaviour: a same-second build of an edited source is taken as current.
127 self.build(NEW)
128 self.assertEqual(stale_build.newer_sources(self.exe, self.root, "prog"), [])
129
130 def test_exe_one_second_older_than_one_source_is_stale(self):
131 self.build(NEW - 1)
132 self.assertEqual(sorted(stale_build.newer_sources(self.exe, self.root, "prog")),
133 ["runtime/src/x.h", "runtime/test/helper.h", "runtime/test/prog.cpp"])
134
135 def test_commented_include_is_not_followed(self):
136 write(self.root, "runtime/test/cmt.cpp", '// #include "hidden.h"\n#include "helper.h"\n')
137 write(self.root, "runtime/test/hidden.h", "")
138 found = stale_build.program_sources(self.root, "cmt")
139 self.assertEqual(rel(self.root, found), ["runtime/test/cmt.cpp", "runtime/test/helper.h"])
140
141
142if __name__ == "__main__":
143 unittest.main()
diff --git a/tests/test_stale_build_include_dirs.py b/tests/test_stale_build_include_dirs.py
new file mode 100644
index 000000000..bba596935
--- /dev/null
+++ b/tests/test_stale_build_include_dirs.py
@@ -0,0 +1,109 @@
1"""stale_build: a quoted #include is followed through the CMake include directories too (STALE-BUILD-INCLUDE-DIRS).
2
3 python3 -I tests/test_stale_build_include_dirs.py
4
5A program's header in runtime/src is a source of the program: editing it must mark the built program stale. The
6trees are temporary and hold placeholder text only; the one smoke test reads the real repository's sources.
7"""
8import os
9import sys
10import tempfile
11import unittest
12
13ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
14sys.path.insert(0, os.path.join(ROOT, "tools"))
15import stale_build # noqa: E402
16
17
18def write(root, rel, text):
19 path = os.path.join(root, *rel.split("/"))
20 os.makedirs(os.path.dirname(path), exist_ok=True)
21 with open(path, "w", encoding="utf-8", newline="\n") as f:
22 f.write(text)
23 return path
24
25
26class IncludeDirsTest(unittest.TestCase):
27 def setUp(self):
28 tmp = tempfile.TemporaryDirectory()
29 self.addCleanup(tmp.cleanup)
30 self.root = tmp.name
31
32 def sources(self, name="prog"):
33 return sorted(os.path.relpath(p, self.root).replace(os.sep, "/")
34 for p in stale_build.program_sources(self.root, name))
35
36 def test_header_in_runtime_src_is_a_source(self):
37 write(self.root, "runtime/test/prog.cpp", '#include "helper.h"\n')
38 write(self.root, "runtime/src/helper.h", "// helper\n")
39 self.assertEqual(self.sources(), ["runtime/src/helper.h", "runtime/test/prog.cpp"])
40
41 def test_editing_runtime_src_header_marks_exe_stale(self):
42 source = write(self.root, "runtime/test/prog.cpp", '#include "helper.h"\n')
43 header = write(self.root, "runtime/src/helper.h", "// helper\n")
44 exe = write(self.root, "runtime/build/prog", "exe\n")
45 os.utime(source, (500_000_000, 500_000_000))
46 os.utime(exe, (1_000_000_000, 1_000_000_000))
47 os.utime(header, (2_000_000_000, 2_000_000_000))
48 self.assertEqual(stale_build.newer_sources(exe, self.root, "prog"), ["runtime/src/helper.h"])
49
50 def test_header_next_to_program_wins_over_runtime_src(self):
51 write(self.root, "runtime/test/prog.cpp", '#include "helper.h"\n')
52 write(self.root, "runtime/test/helper.h", "// local\n")
53 write(self.root, "runtime/src/helper.h", "// shared\n")
54 self.assertEqual(self.sources(), ["runtime/test/helper.h", "runtime/test/prog.cpp"])
55
56 def test_every_copy_in_the_include_directories_is_a_source(self):
57 # CMake orders the directories per target (`target_include_directories(prog PRIVATE shims src)` takes the
58 # shims copy), so a header present in both must count whichever one a given program compiles.
59 write(self.root, "runtime/test/prog.cpp", '#include "helper.h"\n')
60 write(self.root, "runtime/src/helper.h", "// src\n")
61 write(self.root, "runtime/shims/helper.h", "// shims\n")
62 self.assertEqual(self.sources(), ["runtime/shims/helper.h", "runtime/src/helper.h", "runtime/test/prog.cpp"])
63
64 def test_editing_only_the_shims_copy_marks_the_exe_stale(self):
65 write(self.root, "runtime/test/prog.cpp", '#include "selection.h"\n')
66 write(self.root, "runtime/src/selection.h", "// src\n")
67 write(self.root, "runtime/shims/selection.h", "// shims\n")
68 exe = write(self.root, "build/prog.exe", "exe")
69 for rel in ("runtime/test/prog.cpp", "runtime/src/selection.h", "build/prog.exe"):
70 os.utime(os.path.join(self.root, *rel.split("/")), (1000, 1000))
71 os.utime(os.path.join(self.root, "runtime", "shims", "selection.h"), (5000, 5000))
72 self.assertEqual(stale_build.newer_sources(exe, self.root, "prog"), ["runtime/shims/selection.h"])
73
74 def test_header_found_in_runtime_shims(self):
75 write(self.root, "runtime/test/prog.cpp", '#include "shim.h"\n')
76 write(self.root, "runtime/shims/shim.h", "// shim\n")
77 self.assertEqual(self.sources(), ["runtime/shims/shim.h", "runtime/test/prog.cpp"])
78
79 def test_header_found_nowhere_is_skipped(self):
80 write(self.root, "runtime/test/prog.cpp", '#include "missing.h"\n#include <vector>\n')
81 self.assertEqual(self.sources(), ["runtime/test/prog.cpp"])
82
83 def test_cycle_through_fallback_directories_terminates(self):
84 write(self.root, "runtime/test/prog.cpp", '#include "a.h"\n')
85 write(self.root, "runtime/src/a.h", '#include "b.h"\n#pragma once\n')
86 write(self.root, "runtime/shims/b.h", '#include "a.h"\n#include "b.h"\n')
87 self.assertEqual(self.sources(), ["runtime/shims/b.h", "runtime/src/a.h", "runtime/test/prog.cpp"])
88
89 def test_relative_resolution_is_unchanged(self):
90 write(self.root, "runtime/test/prog.cpp", '#include "inc/a.h"\n')
91 write(self.root, "runtime/test/inc/a.h", '#include "b.h"\n#include "../c.h"\n')
92 write(self.root, "runtime/test/inc/b.h", "// b\n")
93 write(self.root, "runtime/test/c.h", "// c\n")
94 self.assertEqual(self.sources(), ["runtime/test/c.h", "runtime/test/inc/a.h", "runtime/test/inc/b.h",
95 "runtime/test/prog.cpp"])
96
97 def test_missing_program_is_empty(self):
98 self.assertEqual(stale_build.program_sources(self.root, "nope"), [])
99
100
101class RealTreeTest(unittest.TestCase):
102 def test_pe_loader_test_follows_pe_loader_header(self):
103 sources = stale_build.program_sources(ROOT, "pe_loader_test")
104 rels = {os.path.relpath(p, ROOT).replace(os.sep, "/") for p in sources}
105 self.assertIn("runtime/src/pe_loader.h", rels)
106
107
108if __name__ == "__main__":
109 unittest.main()
diff --git a/tests/test_user_sgpr_census.py b/tests/test_user_sgpr_census.py
index 321423149..eaba51bc6 100644
--- a/tests/test_user_sgpr_census.py
+++ b/tests/test_user_sgpr_census.py
@@ -122,15 +122,19 @@ def test_json_report_refuses_to_overwrite_index(tmp_path, capsys, output_kind):
122 122
123 # same_report_path resolves each path once and calls the private helpers since #6268, so a case-folded volume is 123 # same_report_path resolves each path once and calls the private helpers since #6268, so a case-folded volume is
124 # simulated by patching those: the public path_key / same_name_on_folding_volume are no longer on its path. 124 # simulated by patching those: the public path_key / same_name_on_folding_volume are no longer on its path.
125 # realpath is patched too: on Windows it returns an existing file's name as stored, so INDEX.JSON would resolve to
126 # index.json and match before the probe is asked (as in tests/test_wave64_graphics_scan.py).
125 probe = mock.Mock(return_value=True) 127 probe = mock.Mock(return_value=True)
128 folding = output_kind == "folding-volume-case"
126 ctx = (mock.patch.multiple(report_paths, _resolved_key=mock.Mock(side_effect=str), 129 ctx = (mock.patch.multiple(report_paths, _resolved_key=mock.Mock(side_effect=str),
127 _same_resolved_name=probe) 130 _same_resolved_name=probe)
128 if output_kind == "folding-volume-case" else contextlib.nullcontext()) 131 if folding else contextlib.nullcontext())
129 with ctx, (mock.patch.object(os.path, "samefile", side_effect=OSError("not same")) 132 with ctx, (mock.patch.object(os.path, "samefile", side_effect=OSError("not same"))
130 if output_kind == "folding-volume-case" else contextlib.nullcontext()): 133 if folding else contextlib.nullcontext()), (mock.patch.object(report_paths.os.path, "realpath", side_effect=os.path.abspath)
134 if folding else contextlib.nullcontext()):
131 with pytest.raises(SystemExit) as exc: 135 with pytest.raises(SystemExit) as exc:
132 usc.main([str(index), "--json", str(output)]) 136 usc.main([str(index), "--json", str(output)])
133 if output_kind == "folding-volume-case": 137 if folding:
134 probe.assert_called_once() 138 probe.assert_called_once()
135 139
136 assert exc.value.code == 2 140 assert exc.value.code == 2
diff --git a/tests/test_viewer_studio.cjs b/tests/test_viewer_studio.cjs
index 06eafc9fe..891d39b7d 100644
--- a/tests/test_viewer_studio.cjs
+++ b/tests/test_viewer_studio.cjs
@@ -316,3 +316,35 @@ test('single-mip single-layer DDS still shows dimensions without adding inputs',
316 assert.equal(controls.children[0].children.length, 0); 316 assert.equal(controls.children[0].children.length, 0);
317 assert.equal(image.src, '/a.png'); 317 assert.equal(image.src, '/a.png');
318}); 318});
319
320test('hostile texture preview URLs and format labels render escaped across both batches', () => {
321 function renderCards(preview, format) {
322 const studio = loadStudio();
323 studio.context.textures = Array.from({ length: 81 },
324 () => ({ name: 'plain.png', format, size: 4, preview }));
325 studio.run('allTextures = textures; renderTexturesGrid();');
326 const grid = studio.elements.get('textures-grid');
327 grid.children.at(-1).onclick();
328 const cards = grid.children.filter(child => child.className === 'tex-card');
329 assert.equal(cards.length, 81);
330 return [cards[0].innerHTML, cards[80].innerHTML];
331 }
332
333 const [plain0, plain80] = renderCards('/textures/x.png', 'PNG Image');
334 const plainShape0 = tagShape(plain0);
335 const plainShape80 = tagShape(plain80);
336 for (const [label, preview, format] of [
337 ['preview', '/textures/' + HOSTILE, 'PNG Image'],
338 ['format', '/textures/x.png', HOSTILE],
339 ]) {
340 const cards = renderCards(preview, format);
341 assert.deepEqual(tagShape(cards[0]), plainShape0, `${label} in initial batch injected markup`);
342 assert.deepEqual(tagShape(cards[1]), plainShape80, `${label} in show-all batch injected markup`);
343 for (const markup of cards) {
344 assert.ok(!markup.includes(HOSTILE), `${label} rendered unescaped hostile string`);
345 if (label === 'format') {
346 assert.ok(visibleText(markup).includes(HOSTILE), 'escaped format must preserve visible text');
347 }
348 }
349 }
350});
diff --git a/tests/test_vk_fuzz_run.py b/tests/test_vk_fuzz_run.py
index 67a90f10e..bb2667606 100644
--- a/tests/test_vk_fuzz_run.py
+++ b/tests/test_vk_fuzz_run.py
@@ -92,6 +92,35 @@ class ProgramText(unittest.TestCase):
92 leftovers = [p for p in Path(tmp).iterdir() if p.name.startswith("vk_fuzz_")] 92 leftovers = [p for p in Path(tmp).iterdir() if p.name.startswith("vk_fuzz_")]
93 self.assertEqual(leftovers, []) 93 self.assertEqual(leftovers, [])
94 94
95 def test_read_dump_takes_the_first_wave_of_a_larger_buffer(self):
96 import struct
97 import tempfile
98 with tempfile.TemporaryDirectory() as tmp:
99 dump = Path(tmp) / "d.bin"
100 # wave32, words=1: vk_compute_test's buffer is at least 64 words, so the dump is 64 words long. Each lane
101 # stores its own value, and the tail holds a sentinel that is not the harness fill, so a read that took
102 # the wrong words, the wrong order or the tail would not match.
103 sentinel = 0xDEADBEEF
104 self.assertNotEqual(sentinel, R.FILL)
105 dump.write_bytes(struct.pack("<64I", *([0x100 + lane for lane in range(32)] + [sentinel] * 32)))
106 lanes = R.read_dump(str(dump), 1, 32)
107 self.assertEqual(lanes, [[0x100 + lane] for lane in range(32)])
108 self.assertNotIn([sentinel], lanes)
109 # wave64, words=1 from a two-group dump (128 words): the buffer is longer than the request the other way
110 # round, and only the first 64 words are the wave's.
111 dump.write_bytes(struct.pack("<128I", *([0x200 + lane for lane in range(64)] + [sentinel] * 64)))
112 self.assertEqual(R.read_dump(str(dump), 1, 64), [[0x200 + lane] for lane in range(64)])
113 # An exact-size dump still reads as before.
114 dump.write_bytes(struct.pack("<128I", *range(128)))
115 lanes = R.read_dump(str(dump), 4, 32)
116 self.assertEqual(len(lanes), 32)
117 self.assertEqual(lanes[0], [0, 1, 2, 3])
118 self.assertEqual(lanes[31], [124, 125, 126, 127])
119 # Too short or missing: no result.
120 dump.write_bytes(struct.pack("<31I", *range(31)))
121 self.assertIsNone(R.read_dump(str(dump), 1, 32))
122 self.assertIsNone(R.read_dump(str(Path(tmp) / "missing.bin"), 1, 32))
123
95 def test_judge_counts_skips_and_mismatches(self): 124 def test_judge_counts_skips_and_mismatches(self):
96 import unittest.mock as mock 125 import unittest.mock as mock
97 obs = ["v_mov_b32 v8, v1", "v_mov_b32 v9, v2", "v_mov_b32 v10, v3", "v_mov_b32 v11, v4"] 126 obs = ["v_mov_b32 v8, v1", "v_mov_b32 v9, v2", "v_mov_b32 v10, v3", "v_mov_b32 v11, v4"]
diff --git a/third_party/xma/NOTICE.md b/third_party/xma/NOTICE.md
index 1e2176829..760e6c77d 100644
--- a/third_party/xma/NOTICE.md
+++ b/third_party/xma/NOTICE.md
@@ -10,3 +10,5 @@ The upstream NOTICE identifies this package as a Rust port of FFmpeg's WMA Pro/X
10> This file is part of FFmpeg and is licensed under the GNU Lesser General Public License, version 2.1 or later. 10> This file is part of FFmpeg and is licensed under the GNU Lesser General Public License, version 2.1 or later.
11 11
12Leonida's C ABI wrapper is independently written and licensed under GPL-3.0-or-later. No upstream implementation source is copied or vendored. 12Leonida's C ABI wrapper is independently written and licensed under GPL-3.0-or-later. No upstream implementation source is copied or vendored.
13
14When the Cargo build succeeds, `runtime/CMakeLists.txt` links the decoder and its `xma` dependency statically into `gta6rt` and `acphal_test`. The wrapper source is in `runtime/xma_decoder`. The pinned dependency source is available from the commit linked above.
diff --git a/tools/batch_glb.py b/tools/batch_glb.py
index 12f1949a0..162e939f2 100644
--- a/tools/batch_glb.py
+++ b/tools/batch_glb.py
@@ -6,7 +6,8 @@ and embed textures (.png or .dds) directly into glTF materials. A texture
6that cannot be read or decoded is left out of that model and reported (one 6that cannot be read or decoded is left out of that model and reported (one
7line each, counted in the summary), never dropped silently; a model that 7line each, counted in the summary), never dropped silently; a model that
8fails to convert is named with its error. Exit status is 1 only when a 8fails to convert is named with its error. Exit status is 1 only when a
9model failed. 9model failed. A missing input folder or an output path that cannot be created
10exits 2.
10 11
11Usage: 12Usage:
12 python -I tools/batch_glb.py <in_dir> <out_dir> [--jobs N] [--up z|y] [--textures <dir>] 13 python -I tools/batch_glb.py <in_dir> <out_dir> [--jobs N] [--up z|y] [--textures <dir>]
@@ -264,7 +265,7 @@ def main(argv: list[str] | None = None) -> int:
264 ) 265 )
265 except (ValueError, OSError) as exc: 266 except (ValueError, OSError) as exc:
266 print(f"ERROR: {exc}", file=sys.stderr) 267 print(f"ERROR: {exc}", file=sys.stderr)
267 return 1 268 return 2
268 elapsed = time.monotonic() - t0 269 elapsed = time.monotonic() - t0
269 270
270 for path, err in stats["failures"]: 271 for path, err in stats["failures"]:
diff --git a/tools/bink_play.py b/tools/bink_play.py
index 0d2edf634..ec3cae6f3 100644
--- a/tools/bink_play.py
+++ b/tools/bink_play.py
@@ -84,13 +84,16 @@ def load_names(archive, mount, use_cache=True):
84 tmp.unlink(missing_ok=True) 84 tmp.unlink(missing_ok=True)
85 if use_cache: 85 if use_cache:
86 fd, name = tempfile.mkstemp(prefix="bink_names.", suffix=".part", dir=cache.parent) 86 fd, name = tempfile.mkstemp(prefix="bink_names.", suffix=".part", dir=cache.parent)
87 with open(fd, "w", encoding="utf-8", newline="") as f: 87 try:
88 f.write("# " + key + "\n") 88 with open(fd, "w", encoding="utf-8", newline="") as f:
89 w = csv.writer(f, lineterminator="\n") 89 f.write("# " + key + "\n")
90 w.writerow(CACHE_FIELDS) 90 w = csv.writer(f, lineterminator="\n")
91 for r in rows: 91 w.writerow(CACHE_FIELDS)
92 w.writerow([r["path"], r["offset"], r["width"], r["height"], r["frames"]]) 92 for r in rows:
93 os.replace(name, cache) 93 w.writerow([r["path"], r["offset"], r["width"], r["height"], r["frames"]])
94 os.replace(name, cache)
95 finally:
96 Path(name).unlink(missing_ok=True)
94 return [(r["path"], int(r["offset"]), r["width"], r["height"], r["frames"]) for r in rows] 97 return [(r["path"], int(r["offset"]), r["width"], r["height"], r["frames"]) for r in rows]
95 98
96 99
diff --git a/tools/boot_trace.py b/tools/boot_trace.py
index db8966f79..e65ab7434 100644
--- a/tools/boot_trace.py
+++ b/tools/boot_trace.py
@@ -32,6 +32,12 @@ import re
32import sys 32import sys
33 33
34D3D12_LINE = re.compile(r"^(?:.+ : )?\[d3d12-trace\] #(\d+) (.+) (\S+)\s*$") 34D3D12_LINE = re.compile(r"^(?:.+ : )?\[d3d12-trace\] #(\d+) (.+) (\S+)\s*$")
35PACING_LINE = re.compile(
36 r"^(?:.+ : )?\[rt\] present: pacing summary "
37 r"frames=(\d+) samples=(\d+) target_us=(\d+) mean_us=(-?\d+(?:\.\d+)?) drift_us=([+-]?\d+(?:\.\d+)?) "
38 r"p50_us=(\d+) p95_us=(\d+) p99_us=(\d+) "
39 r"latency_samples=(\d+) latency_p50_us=(\d+) latency_p95_us=(\d+) latency_p99_us=(\d+)\s*$"
40)
35D3D12_PROBLEMS = ("failed", "unsupported", "refused", "partial") 41D3D12_PROBLEMS = ("failed", "unsupported", "refused", "partial")
36D3D12_OUTCOMES = frozenset((*D3D12_PROBLEMS, "called", "ok", "ignored")) 42D3D12_OUTCOMES = frozenset((*D3D12_PROBLEMS, "called", "ok", "ignored"))
37 43
@@ -216,10 +222,29 @@ def parse_d3d12(path: str, limit: int = 10) -> dict:
216 "last_seq": 0, 222 "last_seq": 0,
217 "sequence_break_count": 0, 223 "sequence_break_count": 0,
218 "sequence_breaks": [], 224 "sequence_breaks": [],
225 "frame_pacing": None,
219 } 226 }
220 with _open_text(path) as fh: 227 with _open_text(path) as fh:
221 for line in fh: 228 for line in fh:
222 match = D3D12_LINE.match(line.rstrip("\n")) 229 stripped = line.rstrip("\n")
230 pacing_match = PACING_LINE.match(stripped)
231 if pacing_match:
232 trace["frame_pacing"] = {
233 "frames": int(pacing_match.group(1)),
234 "samples": int(pacing_match.group(2)),
235 "target_us": int(pacing_match.group(3)),
236 "mean_us": float(pacing_match.group(4)),
237 "drift_us": float(pacing_match.group(5)),
238 "p50_us": int(pacing_match.group(6)),
239 "p95_us": int(pacing_match.group(7)),
240 "p99_us": int(pacing_match.group(8)),
241 "latency_samples": int(pacing_match.group(9)),
242 "latency_p50_us": int(pacing_match.group(10)),
243 "latency_p95_us": int(pacing_match.group(11)),
244 "latency_p99_us": int(pacing_match.group(12)),
245 }
246 continue
247 match = D3D12_LINE.match(stripped)
223 # A crash can truncate the final outcome. A known complete outcome is 248 # A crash can truncate the final outcome. A known complete outcome is
224 # still usable when the trace ends just before the newline. 249 # still usable when the trace ends just before the newline.
225 if not match or (not line.endswith("\n") and match.group(3) not in D3D12_OUTCOMES): 250 if not match or (not line.endswith("\n") and match.group(3) not in D3D12_OUTCOMES):
@@ -270,6 +295,7 @@ def counts_only(summary: dict) -> dict:
270 dllmain_failed=startup["dllmain"]["failed"], 295 dllmain_failed=startup["dllmain"]["failed"],
271 unimplemented_imports=len(startup["unimplemented"]), 296 unimplemented_imports=len(startup["unimplemented"]),
272 int3_skipped=len(startup["int3_skipped"]), 297 int3_skipped=len(startup["int3_skipped"]),
298 xmem_physical_pages_count=startup["kinds"].get("xmem_physical_pages", 0),
273 exit_observed=startup["exit"] is not None, 299 exit_observed=startup["exit"] is not None,
274 ) 300 )
275 if d3d12 := summary["d3d12"]: 301 if d3d12 := summary["d3d12"]:
@@ -283,6 +309,8 @@ def counts_only(summary: dict) -> dict:
283 "sequence_break_count": d3d12["sequence_break_count"], 309 "sequence_break_count": d3d12["sequence_break_count"],
284 "outcomes": outcomes, 310 "outcomes": outcomes,
285 } 311 }
312 if d3d12.get("frame_pacing") is not None:
313 counters["d3d12"]["frame_pacing"] = dict(d3d12["frame_pacing"])
286 return counters 314 return counters
287 315
288 316
@@ -305,7 +333,8 @@ def format_text(summary: dict, limit: int) -> str:
305 kinds = ", ".join(f"{k} {v}" for k, v in sorted(startup["kinds"].items())) 333 kinds = ", ".join(f"{k} {v}" for k, v in sorted(startup["kinds"].items()))
306 out.append(f" kinds: {kinds}") 334 out.append(f" kinds: {kinds}")
307 if startup["modules"]: 335 if startup["modules"]:
308 names = [m["module"] for m in startup["modules"]] 336 # A relocated module is marked: triage step 1 asks whether the executable sits at its preferred base.
337 names = [m["module"] + (" (relocated)" if m.get("relocated") else "") for m in startup["modules"]]
309 out.append(f" modules ({len(names)}): {_tail(names, limit)}") 338 out.append(f" modules ({len(names)}): {_tail(names, limit)}")
310 out.append(f" tls callbacks: {startup['tls_callbacks']}") 339 out.append(f" tls callbacks: {startup['tls_callbacks']}")
311 if callback := startup.get("last_tls_callback"): 340 if callback := startup.get("last_tls_callback"):
@@ -382,6 +411,18 @@ def format_text(summary: dict, limit: int) -> str:
382 " (the [rt] diagnostics are not summarized)" 411 " (the [rt] diagnostics are not summarized)"
383 + (f": {outcomes}" if outcomes else "") 412 + (f": {outcomes}" if outcomes else "")
384 ) 413 )
414 if fp := d3d12.get("frame_pacing"):
415 line = (
416 f" frame pacing: {fp['frames']} frame(s), {fp['samples']} interval(s), "
417 f"target {fp['target_us']} us, mean {fp['mean_us']:.1f} us (drift {fp['drift_us']:+.1f} us), "
418 f"p50/p95/p99 {fp['p50_us']}/{fp['p95_us']}/{fp['p99_us']} us"
419 )
420 if fp["latency_samples"]:
421 line += (
422 f"; origin-to-present p50/p95/p99 "
423 f"{fp['latency_p50_us']}/{fp['latency_p95_us']}/{fp['latency_p99_us']} us"
424 )
425 out.append(line)
385 if last_call := d3d12.get("last_call"): 426 if last_call := d3d12.get("last_call"):
386 out.append(f" last recorded call: #{last_call['seq']} {last_call['method']} {last_call['outcome']}") 427 out.append(f" last recorded call: #{last_call['seq']} {last_call['method']} {last_call['outcome']}")
387 if d3d12["sequence_break_count"]: 428 if d3d12["sequence_break_count"]:
diff --git a/tools/d3d12_xs_surface.py b/tools/d3d12_xs_surface.py
index 72d7d86cb..fe54de18c 100644
--- a/tools/d3d12_xs_surface.py
+++ b/tools/d3d12_xs_surface.py
@@ -404,7 +404,7 @@ def check_iid_order():
404 404
405 405
406def find_sdk_include(): 406def find_sdk_include():
407 """Return (um_dir, shared_dir) for the newest installed Windows SDK, or (None, None).""" 407 """Return (um_dir, shared_dir) for the newest installed Windows SDK with the D3D headers, or (None, None)."""
408 env = os.environ.get("WINDOWS_SDK_INCLUDE") or os.environ.get("SDK_INCLUDE") 408 env = os.environ.get("WINDOWS_SDK_INCLUDE") or os.environ.get("SDK_INCLUDE")
409 if env: 409 if env:
410 candidates = [env] 410 candidates = [env]
@@ -420,7 +420,9 @@ def find_sdk_include():
420 path = os.path.normpath(path) # "...\um\" has an empty basename 420 path = os.path.normpath(path) # "...\um\" has an empty basename
421 um = path if os.path.basename(path).lower() == "um" else os.path.join(path, "um") 421 um = path if os.path.basename(path).lower() == "um" else os.path.join(path, "um")
422 shared = os.path.join(os.path.dirname(um), "shared") 422 shared = os.path.join(os.path.dirname(um), "shared")
423 if os.path.isdir(um): 423 # A Windows Driver Kit installs its own version folder (10.0.26100.0 beside an SDK's 10.0.19041.0, say) that
424 # holds only driver headers; take the newest folder that has the D3D headers, not the newest one there is.
425 if os.path.isdir(um) and (env or os.path.isfile(os.path.join(um, "d3d12.h"))):
424 name = os.path.basename(os.path.dirname(um)) 426 name = os.path.basename(os.path.dirname(um))
425 try: 427 try:
426 key = (1, tuple(map(int, name.split(".")))) 428 key = (1, tuple(map(int, name.split("."))))
diff --git a/tools/exe_sha.py b/tools/exe_sha.py
index b42d6978c..8be64f80c 100644
--- a/tools/exe_sha.py
+++ b/tools/exe_sha.py
@@ -156,4 +156,5 @@ def main(argv: list[str] | None = None) -> int:
156 156
157 157
158if __name__ == "__main__": 158if __name__ == "__main__":
159 sys.stdout.reconfigure(errors="replace")
159 sys.exit(main()) 160 sys.exit(main())
diff --git a/tools/fssm_unpack.py b/tools/fssm_unpack.py
index 42d3658a8..85ef82c4e 100644
--- a/tools/fssm_unpack.py
+++ b/tools/fssm_unpack.py
@@ -37,7 +37,7 @@ from collections import Counter
37 37
38# `python -I` leaves the script's directory off sys.path. 38# `python -I` leaves the script's directory off sys.path.
39sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) 39sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
40from shader_stage_manifest import shader_stems # noqa: E402 40from shader_stage_manifest import shader_stages # noqa: E402
41from replace_retry import replace as replace_retry # noqa: E402 41from replace_retry import replace as replace_retry # noqa: E402
42 42
43# Defensive per-blob ceiling, not a maximum defined by the XBCH format. 43# Defensive per-blob ceiling, not a maximum defined by the XBCH format.
@@ -152,6 +152,22 @@ def unpack(dxbc: bytes, payload: str = "last"):
152 return _inflate_xbch(blob), ents 152 return _inflate_xbch(blob), ents
153 153
154 154
155def program_counts(rows: list, stages: dict) -> dict:
156 """Containers, programs (tag-0x0D payloads) and containers with more than one payload, per stage.
157
158 A container is one carved DXBC file and one row here; a program is one tag-0x0D payload in it. The two counts
159 differ wherever a container carries more than one payload (docs/shader_library.md, "Containers and programs").
160 `stages` maps a row's name to the stage the carve index recorded. A name it lacks, or one it holds without a
161 stage, is counted under None: its stage is unknown."""
162 out = {}
163 for row in rows:
164 counts = out.setdefault(stages.get(row["name"]), {"containers": 0, "programs": 0, "multi_payload": 0})
165 counts["containers"] += 1
166 counts["programs"] += row["xbch_payloads"]
167 counts["multi_payload"] += row["xbch_payloads"] > 1
168 return out
169
170
155def main(argv=None) -> int: 171def main(argv=None) -> int:
156 ap = argparse.ArgumentParser(description="Unpack the FSSM program from each carved shader container.") 172 ap = argparse.ArgumentParser(description="Unpack the FSSM program from each carved shader container.")
157 ap.add_argument("src", help="carved shader directory") 173 ap.add_argument("src", help="carved shader directory")
@@ -165,10 +181,11 @@ def main(argv=None) -> int:
165 what = "is not a folder" if os.path.exists(src) else "does not exist" 181 what = "is not a folder" if os.path.exists(src) else "does not exist"
166 print(f"ERROR: {src} {what}. Give the folder with the carved .dxbc files.", file=sys.stderr) 182 print(f"ERROR: {src} {what}. Give the folder with the carved .dxbc files.", file=sys.stderr)
167 return 2 183 return 2
184 stages = {}
168 try: 185 try:
169 if a.carve_index: 186 if a.carve_index:
170 names = shader_stems(a.carve_index, "file", ".dxbc") 187 stages = shader_stages(a.carve_index, "file", ".dxbc")
171 shaders = sorted(os.path.join(src, name + ".dxbc") for name in names) 188 shaders = sorted(os.path.join(src, name + ".dxbc") for name in stages)
172 for path in shaders: 189 for path in shaders:
173 if not os.path.isfile(path): 190 if not os.path.isfile(path):
174 raise ValueError(f"{a.carve_index}: declared shader file is missing: {path}") 191 raise ValueError(f"{a.carve_index}: declared shader file is missing: {path}")
@@ -225,6 +242,15 @@ def main(argv=None) -> int:
225 replace_retry(tmp, os.path.join(src, "fssm_index.json")) # a scanner or sync client may hold tmp briefly on Windows 242 replace_retry(tmp, os.path.join(src, "fssm_index.json")) # a scanner or sync client may hold tmp briefly on Windows
226 print("magic:", dict(Counter(r["magic"] for r in rows))) 243 print("magic:", dict(Counter(r["magic"] for r in rows)))
227 print("s_endpgm per blob:", dict(Counter(len(r["endpgm"]) for r in rows))) 244 print("s_endpgm per blob:", dict(Counter(len(r["endpgm"]) for r in rows)))
245 counts = program_counts(rows, stages)
246 print(f"programs: {sum(c['programs'] for c in counts.values())} tag-0x0D payloads in {len(rows)} containers, "
247 f"{sum(c['multi_payload'] for c in counts.values())} containers with more than one "
248 f"(--payload {a.payload} is the one unpacked)")
249 if stages: # a stage comes from the carve index; without one there is nothing to break the counts down by
250 for stage in sorted(counts, key=lambda s: (s is None, s or "")):
251 c = counts[stage]
252 print(f" {stage or 'stage unknown'}: {c['containers']} containers, {c['programs']} payloads, "
253 f"{c['multi_payload']} with more than one")
228 sizes = sorted(r["size"] for r in rows) 254 sizes = sorted(r["size"] for r in rows)
229 print(f"size min {sizes[0]}, median {sizes[len(sizes) // 2]}, max {sizes[-1]}, total {sum(sizes) / 2**20:.0f} MiB") 255 print(f"size min {sizes[0]}, median {sizes[len(sizes) // 2]}, max {sizes[-1]}, total {sum(sizes) / 2**20:.0f} MiB")
230 return 0 256 return 0
diff --git a/tools/gallery.py b/tools/gallery.py
index 2762858c3..e163a6846 100644
--- a/tools/gallery.py
+++ b/tools/gallery.py
@@ -529,6 +529,9 @@ def main(argv: list[str] | None = None) -> int:
529 port = 8080 if args.port is None else args.port 529 port = 8080 if args.port is None else args.port
530 if not 0 <= port <= 65535: 530 if not 0 <= port <= 65535:
531 parser.error("--port must be between 0 and 65535") 531 parser.error("--port must be between 0 and 65535")
532 for flag, path in (("--models-dir", args.models_dir), ("--textures-dir", args.textures_dir)):
533 if path is not None and not os.path.isdir(path):
534 parser.error(f"{flag} is not a directory: {path}")
532 try: 535 try:
533 start_server( 536 start_server(
534 port=port, 537 port=port,
diff --git a/tools/hw_oracle/drm.py b/tools/hw_oracle/drm.py
index 701bbcb84..0ea20147a 100644
--- a/tools/hw_oracle/drm.py
+++ b/tools/hw_oracle/drm.py
@@ -155,17 +155,23 @@ class DrmOracle(runner.Oracle):
155 self.node = find_node() 155 self.node = find_node()
156 self.clang = runner.find_clang() 156 self.clang = runner.find_clang()
157 self.chunk = chunk 157 self.chunk = chunk
158 owned = not workdir # a temporary directory made here is removed if the constructor fails
158 self.workdir = workdir or tempfile.mkdtemp(prefix="leonida-hw-oracle-") 159 self.workdir = workdir or tempfile.mkdtemp(prefix="leonida-hw-oracle-")
159 self._offsets, self._registers = {}, {}
160 self.exe = self._build_launcher()
161 self.arch = arch or os.environ.get("LEONIDA_HW_ARCH") or self._device_arch()
162 try: 160 try:
163 asm.family(self.arch) 161 self._offsets, self._registers = {}, {}
164 except ValueError as e: # as in runner.Oracle: an architecture without spellings is a skip 162 self.exe = self._build_launcher()
165 raise Unavailable(f"{e} (set LEONIDA_HW_ARCH)") from None 163 self.arch = arch or os.environ.get("LEONIDA_HW_ARCH") or self._device_arch()
166 self.device = self._probe() 164 try:
167 if hasattr(self, "_probe_waves"): # runner.Oracle has it once it runs kernels of both wave sizes 165 asm.family(self.arch)
168 self._probe_waves() 166 except ValueError as e: # as in runner.Oracle: an architecture without spellings is a skip
167 raise Unavailable(f"{e} (set LEONIDA_HW_ARCH)") from None
168 self.device = self._probe()
169 if hasattr(self, "_probe_waves"): # runner.Oracle has it once it runs kernels of both wave sizes
170 self._probe_waves()
171 except BaseException: # close() never runs for an object that was not built: remove the directory here
172 if owned:
173 shutil.rmtree(self.workdir, ignore_errors=True)
174 raise
169 175
170 def _build_launcher(self): 176 def _build_launcher(self):
171 with open(SOURCE, "rb") as f: 177 with open(SOURCE, "rb") as f:
diff --git a/tools/hw_oracle/runner.py b/tools/hw_oracle/runner.py
index fc9b274f9..61e926296 100644
--- a/tools/hw_oracle/runner.py
+++ b/tools/hw_oracle/runner.py
@@ -209,11 +209,17 @@ class Oracle:
209 except ValueError as e: # a GPU the kernels have no spellings for is a skip, like a missing tool 209 except ValueError as e: # a GPU the kernels have no spellings for is a skip, like a missing tool
210 raise Unavailable(f"{e} (set LEONIDA_HW_ARCH)") from None 210 raise Unavailable(f"{e} (set LEONIDA_HW_ARCH)") from None
211 self.chunk = chunk 211 self.chunk = chunk
212 owned = not workdir # a temporary directory made here is removed if the constructor fails
212 self.workdir = workdir or tempfile.mkdtemp(prefix="leonida-hw-oracle-") 213 self.workdir = workdir or tempfile.mkdtemp(prefix="leonida-hw-oracle-")
213 self.exe = self._build_launcher() 214 try:
214 self.device = self._probe() 215 self.exe = self._build_launcher()
215 self.true16 = self._needs_true16() 216 self.device = self._probe()
216 self._probe_waves() 217 self.true16 = self._needs_true16()
218 self._probe_waves()
219 except BaseException: # close() never runs for an object that was not built: remove the directory here
220 if owned:
221 shutil.rmtree(self.workdir, ignore_errors=True)
222 raise
217 223
218 def _build_launcher(self): 224 def _build_launcher(self):
219 src = os.path.join(HERE, "hw_oracle.c") 225 src = os.path.join(HERE, "hw_oracle.c")
diff --git a/tools/manifest_verifier.py b/tools/manifest_verifier.py
index 49a96f912..5fe36fcd5 100644
--- a/tools/manifest_verifier.py
+++ b/tools/manifest_verifier.py
@@ -28,6 +28,9 @@ import sys
28import time 28import time
29from typing import Callable, Optional, TextIO 29from typing import Callable, Optional, TextIO
30 30
31sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
32from report_paths import same_report_path # noqa: E402
33
31CHUNK = 8 * 1024 * 1024 34CHUNK = 8 * 1024 * 1024
32DEFAULT_MANIFEST = os.path.join(os.path.dirname(__file__), "..", "reports", "manifest.json") 35DEFAULT_MANIFEST = os.path.join(os.path.dirname(__file__), "..", "reports", "manifest.json")
33CACHE_VERSION = 1 36CACHE_VERSION = 1
@@ -326,6 +329,8 @@ def verify_manifest(
326 cache_path: Optional[str] = None, 329 cache_path: Optional[str] = None,
327) -> ManifestReport: 330) -> ManifestReport:
328 """Verifies target_dir against manifest_path, optionally in parallel.""" 331 """Verifies target_dir against manifest_path, optionally in parallel."""
332 if cache_path is not None and same_report_path(cache_path, manifest_path):
333 raise ManifestError(f"cache must not overwrite the manifest: {cache_path}")
329 try: 334 try:
330 mode = os.stat(target_dir).st_mode 335 mode = os.stat(target_dir).st_mode
331 except FileNotFoundError: 336 except FileNotFoundError:
@@ -336,6 +341,10 @@ def verify_manifest(
336 raise ManifestError(f"target path is not a directory: {target_dir}") 341 raise ManifestError(f"target path is not a directory: {target_dir}")
337 342
338 want = load_manifest(manifest_path) 343 want = load_manifest(manifest_path)
344 if cache_path is not None:
345 for rel in want:
346 if same_report_path(cache_path, os.path.join(target_dir, rel)):
347 raise ManifestError(f"cache must not overwrite a listed input: {rel}")
339 have = dict(walk(target_dir, exclude=manifest_path if cache_path is None else (manifest_path, cache_path))) 348 have = dict(walk(target_dir, exclude=manifest_path if cache_path is None else (manifest_path, cache_path)))
340 if not want and have: 349 if not want and have:
341 # A cut-short create or a mistyped --manifest would otherwise print OK without checking a file. 350 # A cut-short create or a mistyped --manifest would otherwise print OK without checking a file.
diff --git a/tools/native_pso_hashes.py b/tools/native_pso_hashes.py
new file mode 100644
index 000000000..d6316be61
--- /dev/null
+++ b/tools/native_pso_hashes.py
@@ -0,0 +1,122 @@
1"""Write <spirv>/native_hashes.txt: the HASH digest of each carved DXBC container -> its stage and path.
2
3Xbox device slot 57 creates the game's graphics pipelines from native code, and each stage's records name the
4source container by the 16-byte digest of its HASH part (docs/fspx.md, kind 7). This catalog connects that
5identifier to the original local container and the stage in the translation index.
6
7Usage: python -I tools/native_pso_hashes.py <work>/shaders/dxbc <work>/shaders/spirv
8
9Only containers in the translator's index are written. Entries sharing a digest must agree on stage and
10fssm_sha256. Adapted from enx/leonida's native graphics PSO index (commit 5c175db90).
11"""
12import json
13import os
14import re
15import sys
16import tempfile
17
18sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
19from shader_carve import parts
20
21HEADER = "# native_pso_hashes 1"
22OUT_NAME = "native_hashes.txt"
23
24
25class DigestClash(ValueError):
26 """One digest names two different programs."""
27
28
29def hash_digest(data: bytes):
30 """The 16-byte digest of a DXBC container's HASH part (after its u32 flags), or None."""
31 if data[:4] != b"DXBC":
32 return None
33 try:
34 chunk = parts(data).get("HASH")
35 except ValueError:
36 return None
37 if not chunk or chunk[1] < 20:
38 return None
39 offset, _ = chunk
40 return data[offset + 4:offset + 20]
41
42
43def build(dxbc: str, spirv: str) -> dict:
44 """{digest hex: (stage, path relative to spirv)}. Raises DigestClash when one digest names two programs."""
45 workspace = os.path.dirname(os.path.realpath(spirv))
46 if os.path.commonpath((workspace, os.path.realpath(dxbc))) != workspace:
47 raise ValueError("the carved folder must be inside the same shader workspace as the translation")
48 with open(os.path.join(spirv, "index.json"), encoding="utf-8") as f:
49 index = json.load(f)
50 if not isinstance(index, dict):
51 raise ValueError("index.json is not an object")
52 found = {}
53 for name in sorted(os.listdir(dxbc)):
54 if not name.endswith(".dxbc"):
55 continue
56 stem = name[:-5]
57 entry = index.get(stem)
58 if not isinstance(entry, dict):
59 continue
60 with open(os.path.join(dxbc, name), "rb") as f:
61 digest = hash_digest(f.read())
62 if digest is None:
63 continue
64 stage, fssm = entry.get("stage"), entry.get("fssm_sha256")
65 if (not isinstance(stage, str) or re.fullmatch(r"[a-z]+", stage) is None or
66 not isinstance(fssm, str) or re.fullmatch(r"[0-9a-f]{64}", fssm) is None):
67 raise ValueError(f"invalid translated stage or FSSM hash for {name!r}")
68 if any(c in stem for c in "\\:\t\r\n"):
69 raise ValueError(f"cannot represent this container name in the native catalog: {name!r}")
70 key = digest.hex()
71 path = os.path.relpath(os.path.join(dxbc, name), spirv).replace(os.sep, "/")
72 if key in found:
73 first = found[key]
74 if first[2] != fssm or first[0] != stage:
75 raise DigestClash(f"digest {key} names two programs: {first[3]} and {stem}")
76 continue
77 found[key] = (stage, path, fssm, stem)
78 return {k: (v[0], v[1]) for k, v in found.items()}
79
80
81def write(spirv: str, table: dict) -> str:
82 out = os.path.join(spirv, OUT_NAME)
83 tmp = tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", newline="\n", dir=spirv,
84 prefix=".native_hashes.", suffix=".tmp", delete=False)
85 try:
86 with tmp:
87 tmp.write(HEADER + "\n")
88 for key in sorted(table):
89 stage, path = table[key]
90 tmp.write(f"{key}\t{stage}\t{path}\n")
91 os.replace(tmp.name, out)
92 finally:
93 if os.path.exists(tmp.name):
94 os.unlink(tmp.name)
95 return out
96
97
98def main(argv) -> int:
99 if argv[1:] in (["-h"], ["--help"]):
100 print(__doc__.strip())
101 return 0
102 if len(argv) != 3:
103 print(__doc__.strip().splitlines()[0], file=sys.stderr)
104 print("usage: native_pso_hashes.py <dxbc dir> <spirv dir>", file=sys.stderr)
105 return 2
106 dxbc, spirv = argv[1], argv[2]
107 try:
108 table = build(dxbc, spirv)
109 out = write(spirv, table)
110 except (OSError, ValueError) as e:
111 print(f"native_pso_hashes: {e}", file=sys.stderr)
112 return 1
113 print(f"native_pso_hashes: {len(table)} digests -> {out}")
114 return 0
115
116
117if __name__ == "__main__":
118 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
119 sys.stdout.reconfigure(errors="replace")
120 except (AttributeError, ValueError, OSError):
121 pass
122 sys.exit(main(sys.argv))
diff --git a/tools/pr_conflict_label.py b/tools/pr_conflict_label.py
index 79206f9c1..69afe760e 100644
--- a/tools/pr_conflict_label.py
+++ b/tools/pr_conflict_label.py
@@ -146,4 +146,5 @@ def main(argv=None):
146 146
147 147
148if __name__ == "__main__": 148if __name__ == "__main__":
149 sys.stdout.reconfigure(errors="replace")
149 sys.exit(main()) 150 sys.exit(main())
diff --git a/tools/progress_dashboard.py b/tools/progress_dashboard.py
index 9e9d0eb28..43d3fafdb 100644
--- a/tools/progress_dashboard.py
+++ b/tools/progress_dashboard.py
@@ -5,7 +5,7 @@
5 5
6Writes, into --out only (a folder inside the repository is refused, so nothing here can be committed by accident): 6Writes, into --out only (a folder inside the repository is refused, so nothing here can be committed by accident):
7 progress.html one self-contained page (no network, no packages; open it from disk) 7 progress.html one self-contained page (no network, no packages; open it from disk)
8 snapshots/progress_<utc>.json the data behind it; a snapshot equal to the previous one is not written again 8 snapshots/progress_<utc>_<hash>.json the data behind it; an unchanged snapshot is not written again
9 history.json one summary line per snapshot, for the trend chart 9 history.json one summary line per snapshot, for the trend chart
10 unit_results.json the last --run-tests outcome, kept so a later run can show what changed since 10 unit_results.json the last --run-tests outcome, kept so a later run can show what changed since
11 11
@@ -1025,7 +1025,8 @@ def write_outputs(snap, out_dir):
1025 new = not history or history[-1]["content_hash"] != snap["content_hash"][:16] 1025 new = not history or history[-1]["content_hash"] != snap["content_hash"][:16]
1026 if new: 1026 if new:
1027 stamp = snap["generated_at"].replace("-", "").replace(":", "") 1027 stamp = snap["generated_at"].replace("-", "").replace(":", "")
1028 save_text(os.path.join(out_dir, "snapshots", f"progress_{stamp}.json"), dump_json(snap)) 1028 archive = f"progress_{stamp}_{snap['content_hash']}.json"
1029 save_text(os.path.join(out_dir, "snapshots", archive), dump_json(snap))
1029 history.append(summary_line(snap)) 1030 history.append(summary_line(snap))
1030 save_text(hist_path, dump_json(history)) 1031 save_text(hist_path, dump_json(history))
1031 save_text(os.path.join(out_dir, "progress.html"), render_page(snap, history)) 1032 save_text(os.path.join(out_dir, "progress.html"), render_page(snap, history))
diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py
index 802096fcf..85c79b637 100644
--- a/tools/rdna2spirv.py
+++ b/tools/rdna2spirv.py
@@ -1229,7 +1229,8 @@ class Gen:
1229 1229
1230 def emit_fma64(self, r, x, y, z): 1230 def emit_fma64(self, r, x, y, z):
1231 """r = x * y + z on doubles with ONE rounding, as RDNA2's f64 multiply-adds do. GLSL.std.450 Fma may round 1231 """r = x * y + z on doubles with ONE rounding, as RDNA2's f64 multiply-adds do. GLSL.std.450 Fma may round
1232 twice here as for f32, and NVIDIA's driver does (RTX 4090, 621.24: the fma(a, a, c) cancellation probe with 1232 twice here as for f32, and NVIDIA's driver does when it folds an all-constant Fma at pipeline compile time
1233 (run-time operands are fused there) (RTX 4090, 621.24: the fma(a, a, c) cancellation probe with
1233 a = 1 + 2^-30 gives 0, not 2^-60). With --fma khr it is OpFmaKHR on doubles, which needs VK_KHR_shader_fma + 1234 a = 1 + 2^-30 gives 0, not 2^-60). With --fma khr it is OpFmaKHR on doubles, which needs VK_KHR_shader_fma +
1234 shaderFmaFloat64 (feature shaderFmaFloat64 in the index). --fma exact has no f64 form and keeps Fma.""" 1235 shaderFmaFloat64 (feature shaderFmaFloat64 in the index). --fma exact has no f64 form and keeps Fma."""
1235 if FMA_KHR: 1236 if FMA_KHR:
@@ -6593,8 +6594,13 @@ class Gen:
6593 self.emit(f"{g} = OpFMul %float {v} {c}") 6594 self.emit(f"{g} = OpFMul %float {v} {c}")
6594 v = g 6595 v = g
6595 if "clamp" in mods: 6596 if "clamp" in mods:
6596 g = self.tmp() 6597 # The game's MODE has DX10_CLAMP=1, so the clamp bit turns a NaN result into +0
6597 self.emit(f"{g} = OpExtInst %float %glsl FClamp {v} %f0 %f1") 6598 # (docs/shader_validation.md). GLSL.std.450 FClamp leaves a NaN operand undefined,
6599 # so select +0 for a NaN first, as the div_fixup and cvt_pknorm clamps do.
6600 nan, safe, g = self.tmp(), self.tmp(), self.tmp()
6601 self.emit(f"{nan} = OpIsNan %bool {v}")
6602 self.emit(f"{safe} = OpSelect %float {nan} %f0 {v}")
6603 self.emit(f"{g} = OpExtInst %float %glsl FClamp {safe} %f0 %f1")
6598 return g 6604 return g
6599 return v 6605 return v
6600 6606
@@ -12436,7 +12442,9 @@ class Gen:
12436 (n == 2 and d["k"] == "special" and d["t"] == "vcc") 12442 (n == 2 and d["k"] == "special" and d["t"] == "vcc")
12437 slist_dst = d["k"] == "slist" and len(d["r"]) == n 12443 slist_dst = d["k"] == "slist" and len(d["r"]) == n
12438 base_slots = (list(range(base["r"], base["r"] + base.get("n", 1))) if base["k"] == "sgpr" 12444 base_slots = (list(range(base["r"], base["r"] + base.get("n", 1))) if base["k"] == "sgpr"
12439 else list(base["r"]) if base["k"] == "slist" else None) 12445 else list(base["r"]) if base["k"] == "slist"
12446 else ["vcc_lo", "vcc_hi"] if (base["k"] == "special" and base["t"] == "vcc")
12447 else None)
12440 if (d["k"] != "sgpr" and not single_special and not slist_dst) or base_slots is None: 12448 if (d["k"] != "sgpr" and not single_special and not slist_dst) or base_slots is None:
12441 raise Unsupported(f"{op} operands {d.get('t', d['k'])} {base.get('t', base['k'])}") 12449 raise Unsupported(f"{op} operands {d.get('t', d['k'])} {base.get('t', base['k'])}")
12442 12450
@@ -16656,14 +16664,28 @@ def sdwa_reads_dst(op: str, mods: list[str]) -> bool:
16656 and any(m.startswith(("dst_sel:BYTE_", "dst_sel:WORD_")) for m in mods)) 16664 and any(m.startswith(("dst_sel:BYTE_", "dst_sel:WORD_")) for m in mods))
16657 16665
16658 16666
16667# Ops whose VGPR destination is also a source operand (the accumulating forms, and v_swap_b32, which reads both).
16668DST_ALSO_READ = ("v_swap_b32", "v_fmac_f32", "v_mac_f32", "v_mac_legacy_f32", "v_fmac_f16", "v_dot4c_i32_i8", "v_pk_fmac_f16",
16669 "v_dot2c_f32_f16", "v_dot2c_i32_i16", "v_dot2c_u32_u16", "v_dot4c_u32_u8", "v_dot8c_i32_i4",
16670 "v_dot8c_u32_u4")
16671
16672
16659# All VGPR operands of these instructions are sources, including store address and data ranges. 16673# All VGPR operands of these instructions are sources, including store address and data ranges.
16660VGPR_READ_ONLY_PREFIXES = ("exp", "buffer_store", "tbuffer_store", "image_store", "v_cmp", "ds_write", 16674VGPR_READ_ONLY_PREFIXES = ("exp", "buffer_store", "tbuffer_store", "image_store", "v_cmp", "ds_write",
16661 "global_store", "flat_store", "scratch_store") 16675 "global_store", "flat_store", "scratch_store")
16662 16676
16663 16677
16664def read_before_write_vgprs(insns): 16678def read_before_write_vgprs(insns):
16665 """VGPRs a shader reads before writing them: for a fetch-calling VS these are the fetched attributes.""" 16679 """VGPRs a shader reads before writing them: for a fetch-calling VS these are the fetched attributes.
16666 written, first = set(), [] 16680
16681 v_writelane_b32 writes one lane and keeps the others (SHADER-768), so its destination is not written by it: the
16682 kept lanes still hold what the register held at entry. They are *carried*, and become a read only when something
16683 other than v_readlane_b32 reads the register before a full write (shdann's two cases on #4297: a PS whose first
16684 touch of v0 is a writelane, then a v_mov of v0, reads the barycentric in the other lanes; a VS that spills an
16685 SGPR into one lane of v40 around the fetch call and reads it back with v_readlane never uses the entry value,
16686 so v40 is not a fetched attribute). The approximation: a v_readlane of a lane the writelane didn't write would
16687 read the entry value, and is not counted."""
16688 written, first, carried = set(), [], set()
16667 for ins in insns: 16689 for ins in insns:
16668 a, op = ins["args"], ins["op"] 16690 a, op = ins["args"], ins["op"]
16669 if not a: 16691 if not a:
@@ -16676,17 +16698,22 @@ def read_before_write_vgprs(insns):
16676 regs += range(x["r"], x["r"] + x.get("n", 1)) 16698 regs += range(x["r"], x["r"] + x.get("n", 1))
16677 elif x["k"] == "vlist": 16699 elif x["k"] == "vlist":
16678 regs += x["r"] 16700 regs += x["r"]
16679 if (base_op(op) in ("v_swap_b32", "v_fmac_f32", "v_mac_f32", "v_mac_legacy_f32", "v_fmac_f16", "v_dot4c_i32_i8", "v_pk_fmac_f16", 16701 if (base_op(op) in DST_ALSO_READ or
16680 "v_dot2c_f32_f16", "v_dot2c_i32_i16", "v_dot2c_u32_u16", "v_dot4c_u32_u8",
16681 "v_dot8c_i32_i4", "v_dot8c_u32_u4") or
16682 (op.startswith(("global_load_", "buffer_load_")) and "_d16" in op and "format" not in op)) and \ 16702 (op.startswith(("global_load_", "buffer_load_")) and "_d16" in op and "format" not in op)) and \
16683 a[0]["k"] == "vgpr": # d16 keeps a half 16703 a[0]["k"] == "vgpr": # d16 keeps a half
16684 regs.append(a[0]["r"]) 16704 regs.append(a[0]["r"])
16705 lane_read = base_op(op) == "v_readlane_b32"
16685 for r in regs: 16706 for r in regs:
16686 if r not in written and r not in first: 16707 if r in written or r in first or (r in carried and lane_read):
16687 first.append(r) 16708 continue
16688 if not reads_all and a[0]["k"] == "vgpr": 16709 first.append(r)
16689 written.update(vgpr_dest_registers(ins)) 16710 if base_op(op) == "v_writelane_b32" and a[0]["k"] == "vgpr":
16711 if a[0]["r"] not in written:
16712 carried.add(a[0]["r"])
16713 elif not reads_all and a[0]["k"] == "vgpr":
16714 dst = vgpr_dest_registers(ins)
16715 written.update(dst)
16716 carried.difference_update(dst)
16690 return set(first) 16717 return set(first)
16691 16718
16692def interp_ij_analysis(insns, g): 16719def interp_ij_analysis(insns, g):
@@ -16937,9 +16964,8 @@ def reg_reads_writes(insns):
16937 regs += range(x["r"], x["r"] + x.get("n", 1)) 16964 regs += range(x["r"], x["r"] + x.get("n", 1))
16938 elif x["k"] == "vlist": 16965 elif x["k"] == "vlist":
16939 regs += x["r"] 16966 regs += x["r"]
16940 if base_op(op) in ("v_swap_b32", "v_fmac_f32", "v_mac_f32", "v_mac_legacy_f32", "v_fmac_f16", "v_dot4c_i32_i8", "v_pk_fmac_f16", 16967 if (base_op(op) in DST_ALSO_READ or base_op(op) == "v_writelane_b32") and a[0]["k"] == "vgpr":
16941 "v_dot2c_f32_f16", "v_dot2c_i32_i16", "v_dot2c_u32_u16", "v_dot4c_u32_u8", 16968 # v_writelane_b32 keeps the other lanes: over a slice that is a read of the destination
16942 "v_dot8c_i32_i4", "v_dot8c_u32_u4") and a[0]["k"] == "vgpr":
16943 regs.append(a[0]["r"]) 16969 regs.append(a[0]["r"])
16944 rr.update(regs) 16970 rr.update(regs)
16945 if not reads_all and a[0]["k"] == "vgpr": 16971 if not reads_all and a[0]["k"] == "vgpr":
diff --git a/tools/semantic_mutants.py b/tools/semantic_mutants.py
index 2350e0b8b..32be6525d 100644
--- a/tools/semantic_mutants.py
+++ b/tools/semantic_mutants.py
@@ -9,7 +9,12 @@ branch naming it (--op), a whole method (--function), or an explicit line range
9mutants of that code with standard operators: swapped opcode pairs (OpIAdd/OpISub, OpBitwiseAnd/Or, shifts), swapped 9mutants of that code with standard operators: swapped opcode pairs (OpIAdd/OpISub, OpBitwiseAnd/Or, shifts), swapped
10GLSL.std.450 pairs (UMin/UMax, SMin/UMin, NMin/FMin, Floor/Ceil, ...), comparisons made strict or non-strict or of the 10GLSL.std.450 pairs (UMin/UMax, SMin/UMin, NMin/FMin, Floor/Ceil, ...), comparisons made strict or non-strict or of the
11other signedness, small `self.cu(N)` constants moved by one, the two arms of an OpSelect swapped, and the last operand 11other signedness, small `self.cu(N)` constants moved by one, the two arms of an OpSelect swapped, and the last operand
12of an emitted instruction replaced by the one before it. Each mutant is written into a private copy of tools/ (the 12of an emitted instruction replaced by the one before it. The Python around the emission (register liveness, lane-mask
13tracking, operand checks) gets mutants too: comparisons flipped (== / !=, < / <=, > / >=, in / not in, is / is not),
14and / or swapped, a `not` dropped, True / False swapped, and a one-line statement that can fail silently replaced by
15`pass` (a call that is not an emit, an augmented assignment, or a rebinding of a name assigned earlier in the range).
16The branch's own `if op ...` condition is left alone: a mutant there only sends other ops through the branch. Each
17mutant is written into a private copy of tools/ (the
13repository's own tools/ is never modified) and the test file is run against it through LEONIDA_TOOLS_DIR, as 18repository's own tools/ is never modified) and the test file is run against it through LEONIDA_TOOLS_DIR, as
14tests/semantic/test_mutations.py does. A mutant the test file still passes is reported as SURVIVED. 19tests/semantic/test_mutations.py does. A mutant the test file still passes is reported as SURVIVED.
15 20
@@ -27,7 +32,9 @@ import shutil
27import subprocess 32import subprocess
28import sys 33import sys
29import tempfile 34import tempfile
35import textwrap
30import time 36import time
37import tokenize
31from dataclasses import dataclass 38from dataclasses import dataclass
32 39
33ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 40ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
@@ -52,6 +59,14 @@ CU = re.compile(r"self\.cu\((0x[0-9A-Fa-f]+|\d+)\)")
52SELECT = re.compile(r"(OpSelect %\w+ \{[^}]+\} )(\{[^}]+\}|%\w+)( )(\{[^}]+\}|%\w+)") 59SELECT = re.compile(r"(OpSelect %\w+ \{[^}]+\} )(\{[^}]+\}|%\w+)( )(\{[^}]+\}|%\w+)")
53LAST_OPERAND = re.compile(r"(\{[A-Za-z_][\w\[\]]*\}) (\{[A-Za-z_][\w\[\]]*\})(\"\))") 60LAST_OPERAND = re.compile(r"(\{[A-Za-z_][\w\[\]]*\}) (\{[A-Za-z_][\w\[\]]*\})(\"\))")
54 61
62# Python logic: comparison flips, and the statements whose removal is not a NameError or a syntax error.
63COMPARE = {"==": "!=", "!=": "==", "<": "<=", "<=": "<", ">": ">=", ">=": ">"}
64AUG_ASSIGN = {"+=", "-=", "*=", "/=", "//=", "%=", "&=", "|=", "^=", "<<=", ">>="}
65NOT_SIMPLE = {"if", "elif", "else", "for", "while", "def", "class", "return", "raise", "try", "except", "finally",
66 "with", "yield", "break", "continue", "pass", "import", "from", "assert", "global", "nonlocal", "del",
67 "async", "await", "lambda", "match", "case"}
68SKIPPED_TOKENS = (tokenize.NL, tokenize.COMMENT, tokenize.INDENT, tokenize.DEDENT, tokenize.ENDMARKER)
69
55 70
56@dataclass 71@dataclass
57class Mutant: 72class Mutant:
@@ -140,9 +155,215 @@ def find_function(lines: list[str], name: str) -> tuple[int, int]:
140 raise LookupError(f"no method named {name}") 155 raise LookupError(f"no method named {name}")
141 156
142 157
158def docstring_lines(lines: list[str]) -> set[int]:
159 """0-based lines that belong to a string standing alone as a statement (a docstring): text, not code, so a
160 mutant there can never fail a test. Empty when the lines do not tokenize."""
161 out: set[int] = set()
162 source = iter(line + "\n" for line in lines)
163 prev = tokenize.NEWLINE
164 try:
165 tokens = list(tokenize.generate_tokens(lambda: next(source, "")))
166 except (tokenize.TokenError, SyntaxError):
167 return out
168 for i, tok in enumerate(tokens):
169 if tok.type == tokenize.STRING and prev in (tokenize.NEWLINE, tokenize.INDENT, tokenize.DEDENT):
170 # Adjacent literals are one string ("a " "b"), so the statement may go on with more of them.
171 rest = (t for t in tokens[i + 1:] if t.type not in (tokenize.COMMENT, tokenize.NL))
172 end, after = tok, next(rest, None)
173 while after is not None and after.type == tokenize.STRING:
174 end, after = after, next(rest, None)
175 if after is None or after.type in (tokenize.NEWLINE, tokenize.ENDMARKER):
176 out.update(range(tok.start[0] - 1, end.end[0]))
177 if tok.type not in (tokenize.COMMENT, tokenize.NL):
178 prev = tok.type
179 return out
180
181
182def open_triple_quote(line: str, open_: str | None) -> str | None:
183 """The triple-quote delimiter still open at the end of `line` (None when none), given the one open at its start.
184 Quotes in a comment or inside a one-line string do not count, nor does an escaped delimiter."""
185 i, n = 0, len(line)
186 while i < n:
187 if open_:
188 j = line.find(open_, i)
189 while j > 0 and (len(line[:j]) - len(line[:j].rstrip("\\"))) % 2 == 1:
190 j = line.find(open_, j + 1) # \""" inside the string
191 if j < 0:
192 return open_
193 i, open_ = j + 3, None
194 elif line.startswith(('"""', "'''"), i):
195 open_, i = line[i:i + 3], i + 3
196 elif line[i] == "#":
197 return None
198 elif line[i] in "\"'":
199 j = i + 1
200 while j < n and line[j] != line[i]:
201 j += 2 if line[j] == "\\" else 1
202 i = j + 1
203 else:
204 i += 1
205 return open_
206
207
208def string_context(lines: list[str], first: int, last: int) -> tuple[int, int]:
209 """Widen [first, last] to whole triple-quoted strings, so a range that starts or ends inside a docstring (a
210 --lines span) is tokenized with both of its delimiters. Delimiters are followed from the enclosing def or class,
211 a text scan that stays cheap inside the translator's long dispatch method."""
212 top = first
213 while top > 0 and not re.match(r"\s*(async\s+def|def|class)\s", lines[top]):
214 top -= 1
215 open_, opened_at = None, first
216 for i in range(top, first):
217 before, open_ = open_, open_triple_quote(lines[i], open_)
218 if open_ and not before:
219 opened_at = i # a string that is still open at `first` began here
220 start = opened_at if open_ else first
221 end, open_ = last, None
222 for i in range(start, len(lines)):
223 open_ = open_triple_quote(lines[i], open_)
224 if i >= last and not open_:
225 end = i
226 break
227 return start, end
228
229
230def condition_lines(lines: list[str], first: int) -> set[int]:
231 """0-based lines of the `if op ...` / `elif op ...` condition that starts at `first`, empty when `first` does not
232 start one. It decides which ops run the branch at all, so mutating it only sends other ops through the code."""
233 stripped = lines[first].lstrip()
234 if not re.match(r"(el)?if\b", stripped):
235 return set()
236 cond, j = lines[first], first
237 while not cond.rstrip().endswith(":") and j + 1 < len(lines):
238 j += 1
239 cond += lines[j]
240 return set(range(first, j + 1)) if re.search(r"\bop\b", cond) and '"' in cond else set()
241
242
243def logical_lines(span: list[str]) -> list[list[tokenize.TokenInfo]]:
244 """The tokens of each logical line of `span` (NL, comments, indents and dedents dropped). A span that stops
245 inside a bracket or a string keeps the lines that tokenized before it."""
246 source = iter(s + "\n" for s in span)
247 out: list[list[tokenize.TokenInfo]] = [[]]
248 try:
249 for tok in tokenize.generate_tokens(lambda: next(source, "")):
250 if tok.type == tokenize.NEWLINE:
251 out.append([])
252 elif tok.type not in SKIPPED_TOKENS:
253 out[-1].append(tok)
254 except (tokenize.TokenError, SyntaxError):
255 out[-1] = [] # the unfinished line
256 return [ll for ll in out if ll]
257
258
259def logic_mutants(lines: list[str], first: int, last: int, start: int, span: list[str],
260 skip: set[int]) -> list[tuple[int, str, str]]:
261 """(0-based line, label, mutated line) for the Python logic in lines[first..last]; `span` is lines[start..]
262 dedented. Only names and operators are touched, so strings, f-strings (the emitted SPIR-V) and comments are
263 left alone; lines in `skip` (docstrings, the branch condition) get none."""
264 out: list[tuple[int, str, str]] = []
265 assigned: set[str] = set()
266
267 def line_of(tok: tokenize.TokenInfo) -> int:
268 return start + tok.start[0] - 1
269
270 def in_range(i: int) -> bool:
271 return first <= i <= last and i not in skip
272
273 def replace(tok_a: tokenize.TokenInfo, tok_b: tokenize.TokenInfo, text: str, label: str, a_end: bool = False,
274 b_end: bool = True) -> None:
275 # Replace lines[i] from tok_a's start (or end) to tok_b's end (or start) with `text`; both on line i.
276 i = line_of(tok_a)
277 if line_of(tok_b) != i or not in_range(i):
278 return
279 k = tok_a.start[0] - 1
280 off = len(lines[i]) - len(span[k]) # the indentation dedent removed
281 a = (tok_a.end if a_end else tok_a.start)[1] + off
282 b = (tok_b.end if b_end else tok_b.start)[1] + off
283 out.append((i, label, lines[i][:a] + text + lines[i][b:]))
284
285 for ll in logical_lines(span):
286 depth, fors, consumed = 0, [], set()
287 targets: list[str] = []
288 top_eq = top_aug = False
289 for n, tok in enumerate(ll):
290 nxt = ll[n + 1] if n + 1 < len(ll) else None
291 if tok.type == tokenize.OP:
292 if tok.string in "([{":
293 depth += 1
294 elif tok.string in ")]}":
295 depth -= 1
296 elif tok.string in COMPARE:
297 replace(tok, tok, COMPARE[tok.string], f"{tok.string} -> {COMPARE[tok.string]}")
298 elif depth == 0 and tok.string == "=":
299 if not top_eq:
300 top_eq = True
301 names = [t for t in ll[:n] if not (t.type == tokenize.OP and t.string == ",")]
302 if all(t.type == tokenize.NAME for t in names):
303 targets = [t.string for t in names]
304 elif depth == 0 and tok.string in AUG_ASSIGN:
305 top_aug = True
306 continue
307 if tok.type != tokenize.NAME or n in consumed:
308 continue
309 word = tok.string
310 if word == "for":
311 fors.append(depth)
312 elif word in ("and", "or"):
313 other = "or" if word == "and" else "and"
314 replace(tok, tok, other, f"{word} -> {other}")
315 elif word in ("True", "False"):
316 other = "False" if word == "True" else "True"
317 replace(tok, tok, other, f"{word} -> {other}")
318 elif word == "not" and nxt is not None and nxt.type == tokenize.NAME and nxt.string == "in":
319 replace(tok, nxt, "", "not in -> in", b_end=False)
320 consumed.add(n + 1)
321 elif word == "not" and nxt is not None:
322 replace(tok, nxt, "", "not removed", b_end=False)
323 elif word == "in":
324 if fors and fors[-1] == depth: # the `in` of a for loop or a comprehension
325 fors.pop()
326 else:
327 replace(tok, tok, "not in", "in -> not in")
328 elif word == "is":
329 if nxt is not None and nxt.type == tokenize.NAME and nxt.string == "not":
330 replace(tok, nxt, "", "is not -> is", a_end=True)
331 consumed.add(n + 1)
332 else:
333 replace(tok, tok, "is not", "is -> is not")
334 # A one-line statement that can fail silently: a call that is not an emit, an augmented assignment, or a
335 # rebinding of a name the range assigned before. Removing a first assignment would only be a NameError.
336 i, head = line_of(ll[0]), ll[0]
337 one_line = line_of(ll[-1]) == i
338 simple = head.type == tokenize.NAME and head.string not in NOT_SIMPLE
339 call = (not top_eq and not top_aug and ll[-1].type == tokenize.OP and ll[-1].string == ")"
340 and not any(t.type == tokenize.NAME and t.string == "emit" for t in ll))
341 rebind = top_eq and bool(targets) and all(t in assigned for t in targets)
342 if one_line and simple and in_range(i) and (call or top_aug or rebind):
343 indent = lines[i][:len(lines[i]) - len(lines[i].lstrip())]
344 out.append((i, "statement removed", indent + "pass"))
345 assigned.update(targets)
346 # The same flip twice on one line (`a and b and c`) gets "#1", "#2", ... from the left, so the report tells them apart.
347 count: dict[tuple[int, str], int] = {}
348 for i, label, _ in out:
349 count[(i, label)] = count.get((i, label), 0) + 1
350 seen: dict[tuple[int, str], int] = {}
351 numbered = []
352 for i, label, new in out:
353 if count[(i, label)] > 1:
354 seen[(i, label)] = seen.get((i, label), 0) + 1
355 label = f"{label} #{seen[(i, label)]}"
356 numbered.append((i, label, new))
357 return numbered
358
359
143def mutants_for(lines: list[str], first: int, last: int) -> list[Mutant]: 360def mutants_for(lines: list[str], first: int, last: int) -> list[Mutant]:
144 out: list[Mutant] = [] 361 out: list[Mutant] = []
145 seen: set[tuple[int, str]] = set() 362 seen: set[tuple[int, str]] = set()
363 # Only the mutated range is tokenized (the whole translator takes seconds); dedented, a branch or method tokenizes.
364 start, end = string_context(lines, first, last)
365 span = textwrap.dedent("\n".join(lines[start:end + 1])).split("\n")
366 docs = {start + i for i in docstring_lines(span)}
146 367
147 def add(i: int, label: str, new: str) -> None: 368 def add(i: int, label: str, new: str) -> None:
148 if new != lines[i] and (i, new) not in seen: 369 if new != lines[i] and (i, new) not in seen:
@@ -150,6 +371,8 @@ def mutants_for(lines: list[str], first: int, last: int) -> list[Mutant]:
150 out.append(Mutant(i + 1, label, lines[i], new)) 371 out.append(Mutant(i + 1, label, lines[i], new))
151 372
152 for i in range(first, last + 1): 373 for i in range(first, last + 1):
374 if i in docs:
375 continue
153 line = lines[i] 376 line = lines[i]
154 code = line.split("#", 1)[0] if not line.lstrip().startswith(("f\"", "\"", "'")) else line 377 code = line.split("#", 1)[0] if not line.lstrip().startswith(("f\"", "\"", "'")) else line
155 if not code.strip() or code.lstrip().startswith("#"): 378 if not code.strip() or code.lstrip().startswith("#"):
@@ -178,6 +401,8 @@ def mutants_for(lines: list[str], first: int, last: int) -> list[Mutant]:
178 if m: 401 if m:
179 add(i, f"last operand {m.group(2)} -> {m.group(1)}", 402 add(i, f"last operand {m.group(2)} -> {m.group(1)}",
180 line[:m.start()] + f"{m.group(1)} {m.group(1)}{m.group(3)}" + line[m.end():]) 403 line[:m.start()] + f"{m.group(1)} {m.group(1)}{m.group(3)}" + line[m.end():])
404 for i, label, new in logic_mutants(lines, first, last, start, span, docs | condition_lines(lines, first)):
405 add(i, label, new)
181 return out 406 return out
182 407
183 408
diff --git a/tools/shader_stage_manifest.py b/tools/shader_stage_manifest.py
index eb5ffc913..fe9e94572 100644
--- a/tools/shader_stage_manifest.py
+++ b/tools/shader_stage_manifest.py
@@ -8,7 +8,8 @@ import ntpath
8import posixpath 8import posixpath
9 9
10 10
11def shader_stems(path: str, field: str, suffix: str = "") -> set[str]: 11def _stem_rows(path: str, field: str, suffix: str = "") -> list[tuple[str, dict]]:
12 """Each entry of the index as (validated stem, row)."""
12 try: 13 try:
13 # utf-8-sig: PowerShell 5.1 and old Notepad write JSON with a UTF-8 BOM. 14 # utf-8-sig: PowerShell 5.1 and old Notepad write JSON with a UTF-8 BOM.
14 with open(path, encoding="utf-8-sig") as f: 15 with open(path, encoding="utf-8-sig") as f:
@@ -19,7 +20,7 @@ def shader_stems(path: str, field: str, suffix: str = "") -> set[str]:
19 raise ValueError(f"{path}: invalid JSON: {exc}") from exc 20 raise ValueError(f"{path}: invalid JSON: {exc}") from exc
20 if not isinstance(rows, list): 21 if not isinstance(rows, list):
21 raise ValueError(f"{path}: expected an array of shader entries") 22 raise ValueError(f"{path}: expected an array of shader entries")
22 stems = set() 23 out = []
23 for row in rows: 24 for row in rows:
24 value = row.get(field) if isinstance(row, dict) else None 25 value = row.get(field) if isinstance(row, dict) else None
25 if ( 26 if (
@@ -39,5 +40,19 @@ def shader_stems(path: str, field: str, suffix: str = "") -> set[str]:
39 stem = value.removesuffix(suffix) 40 stem = value.removesuffix(suffix)
40 if not stem or stem in (".", ".."): 41 if not stem or stem in (".", ".."):
41 raise ValueError(f"{path}: expected a shader basename in {field!r}") 42 raise ValueError(f"{path}: expected a shader basename in {field!r}")
42 stems.add(stem) 43 out.append((stem, row))
43 return stems 44 return out
45
46
47def shader_stems(path: str, field: str, suffix: str = "") -> set[str]:
48 return {stem for stem, _ in _stem_rows(path, field, suffix)}
49
50
51def shader_stages(path: str, field: str, suffix: str = "") -> dict[str, str | None]:
52 """The stage the index records for each shader, by stem. None where an entry has no stage string: the stage is
53 then unknown, not absent, and the caller says so."""
54 stages = {}
55 for stem, row in _stem_rows(path, field, suffix):
56 stage = row.get("stage")
57 stages[stem] = stage if isinstance(stage, str) and stage else None
58 return stages
diff --git a/tools/spirv_asm.py b/tools/spirv_asm.py
index 49d0809e1..e32dd83af 100644
--- a/tools/spirv_asm.py
+++ b/tools/spirv_asm.py
@@ -30,7 +30,8 @@ if _HERE not in sys.path:
30 sys.path.insert(0, _HERE) 30 sys.path.insert(0, _HERE)
31 31
32from spirv_asm_tables import ( # noqa: E402 32from spirv_asm_tables import ( # noqa: E402
33 BIT_ENUMS, GLSL_STD_450, INSTRUCTIONS, NONSEMANTIC_DEBUGPRINTF, VALUE_ENUMS, 33 BIT_ENUMS, GLSL_STD_450, INSTRUCTIONS, NONSEMANTIC_DEBUGPRINTF,
34 NONSEMANTIC_SHADER_DEBUGINFO_100, VALUE_ENUMS,
34) 35)
35 36
36SPIRV_MAGIC = 0x07230203 37SPIRV_MAGIC = 0x07230203
@@ -54,6 +55,7 @@ TARGET_ENV_VERSION = {
54_ID_KINDS = frozenset(("IdRef", "IdResult", "IdResultType", "IdScope", "IdMemorySemantics")) 55_ID_KINDS = frozenset(("IdRef", "IdResult", "IdResultType", "IdScope", "IdMemorySemantics"))
55_ID_RE = re.compile(r"%[A-Za-z0-9_]+") 56_ID_RE = re.compile(r"%[A-Za-z0-9_]+")
56_EXT_SETS = { 57_EXT_SETS = {
58 "NonSemantic.Shader.DebugInfo.100": NONSEMANTIC_SHADER_DEBUGINFO_100,
57 "GLSL.std.450": GLSL_STD_450, 59 "GLSL.std.450": GLSL_STD_450,
58 "NonSemantic.DebugPrintf": NONSEMANTIC_DEBUGPRINTF, # spirv-dis writes its instruction by name 60 "NonSemantic.DebugPrintf": NONSEMANTIC_DEBUGPRINTF, # spirv-dis writes its instruction by name
59} 61}
@@ -638,7 +640,7 @@ def _assemble(instructions, version: int, track_switch_types: bool) -> bytes:
638 640
639 cur_ext_table = None 641 cur_ext_table = None
640 switch_type = None # (width, signed) of the OpSwitch selector's integer type 642 switch_type = None # (width, signed) of the OpSwitch selector's integer type
641 if opname == "OpExtInst" and arg_idx < len(toks): 643 if opname in ("OpExtInst", "OpExtInstWithForwardRefsKHR") and arg_idx < len(toks):
642 cur_ext_table = ext_imports.get(get_id(toks[arg_idx], lineno)) 644 cur_ext_table = ext_imports.get(get_id(toks[arg_idx], lineno))
643 elif opname == "OpSwitch" and arg_idx < len(toks): 645 elif opname == "OpSwitch" and arg_idx < len(toks):
644 sel_id = get_id(toks[arg_idx], lineno) 646 sel_id = get_id(toks[arg_idx], lineno)
diff --git a/tools/spirv_asm_tables.py b/tools/spirv_asm_tables.py
index a58311c14..7714d734f 100644
--- a/tools/spirv_asm_tables.py
+++ b/tools/spirv_asm_tables.py
@@ -1111,3 +1111,51 @@ GLSL_STD_450 = {
1111NONSEMANTIC_DEBUGPRINTF = { 1111NONSEMANTIC_DEBUGPRINTF = {
1112 'DebugPrintf': 1, 1112 'DebugPrintf': 1,
1113} 1113}
1114
1115# extinst.nonsemantic.shader.debuginfo.100.grammar.json (SPIRV-Headers).
1116NONSEMANTIC_SHADER_DEBUGINFO_100 = {
1117 'DebugBuildIdentifier': 105,
1118 'DebugCompilationUnit': 1,
1119 'DebugDeclare': 28,
1120 'DebugEntryPoint': 107,
1121 'DebugExpression': 31,
1122 'DebugFunction': 20,
1123 'DebugFunctionDeclaration': 19,
1124 'DebugFunctionDefinition': 101,
1125 'DebugGlobalVariable': 18,
1126 'DebugImportedEntity': 34,
1127 'DebugInfoNone': 0,
1128 'DebugInlinedAt': 25,
1129 'DebugInlinedVariable': 27,
1130 'DebugLexicalBlock': 21,
1131 'DebugLexicalBlockDiscriminator': 22,
1132 'DebugLine': 103,
1133 'DebugLocalVariable': 26,
1134 'DebugMacroDef': 32,
1135 'DebugMacroUndef': 33,
1136 'DebugNoLine': 104,
1137 'DebugNoScope': 24,
1138 'DebugOperation': 30,
1139 'DebugScope': 23,
1140 'DebugSource': 35,
1141 'DebugSourceContinued': 102,
1142 'DebugStoragePath': 106,
1143 'DebugTypeArray': 5,
1144 'DebugTypeBasic': 2,
1145 'DebugTypeComposite': 10,
1146 'DebugTypedef': 7,
1147 'DebugTypeEnum': 9,
1148 'DebugTypeFunction': 8,
1149 'DebugTypeInheritance': 12,
1150 'DebugTypeMatrix': 108,
1151 'DebugTypeMember': 11,
1152 'DebugTypePointer': 3,
1153 'DebugTypePtrToMember': 13,
1154 'DebugTypeQualifier': 4,
1155 'DebugTypeTemplate': 14,
1156 'DebugTypeTemplateParameter': 15,
1157 'DebugTypeTemplateParameterPack': 17,
1158 'DebugTypeTemplateTemplateParameter': 16,
1159 'DebugTypeVector': 6,
1160 'DebugValue': 29,
1161}
diff --git a/tools/stale_build.py b/tools/stale_build.py
index 0945e5fed..140cecd93 100644
--- a/tools/stale_build.py
+++ b/tools/stale_build.py
@@ -3,7 +3,8 @@
3make_game.py (vk_pipeline_check) and first_light.py (vk_harness) take a program already in runtime/build when there 3make_game.py (vk_pipeline_check) and first_light.py (vk_harness) take a program already in runtime/build when there
4is one. After a pull that changed the program, that copy is from the old sources and would run silently. The 4is one. After a pull that changed the program, that copy is from the old sources and would run silently. The
5sources are runtime/test/<name>.cpp and the headers it pulls in with #include "..." (followed through other 5sources are runtime/test/<name>.cpp and the headers it pulls in with #include "..." (followed through other
6headers): a change to any of them recompiles and relinks the program, so a current build is never older than them. 6headers, each looked up next to the including file, then in the include directories of runtime/CMakeLists.txt): a
7change to any of them recompiles and relinks the program, so a current build is never older than them.
7runtime/CMakeLists.txt isn't one: a change there that doesn't concern the program leaves it as it was. 8runtime/CMakeLists.txt isn't one: a change there that doesn't concern the program leaves it as it was.
8""" 9"""
9import os 10import os
@@ -11,6 +12,32 @@ import re
11 12
12_INCLUDE = re.compile(r'^\s*#\s*include\s*"([^"]+)"', re.MULTILINE) 13_INCLUDE = re.compile(r'^\s*#\s*include\s*"([^"]+)"', re.MULTILINE)
13 14
15# The include directories runtime/CMakeLists.txt gives the runtime/test programs, searched after the directory of the
16# including file: runtime/src and runtime/shims (target_include_directories of pe_loader_test, lines 657-660, which
17# other test programs repeat), then the xtaskqueue ones (lines 90-92, 1206-1210 and 1227-1229). Paths are relative to
18# the repository root. The list is the union over the programs, not one target's order: no header name exists in two
19# of these directories today, and if one did, every copy would count as a source of the program.
20_INCLUDE_DIRS = (
21 "runtime/src",
22 "runtime/shims",
23 "runtime/shims/xtaskqueue",
24 "third_party/xtaskqueue/Source/Task",
25 "third_party/xtaskqueue/Source/Common",
26 "third_party/xtaskqueue/Include",
27)
28
29
30def _resolve_include(root, path, inc):
31 """The files a quoted `#include inc` in `path` may name: the one next to `path` when there is one (the compiler
32 looks there first and nowhere else), otherwise every match in _INCLUDE_DIRS. CMake orders those directories per
33 target, so which match the compiler takes can differ from one program to the next; following all of them can add a
34 rebuild but never miss one. Empty when nothing has it (a system or generated header)."""
35 local = os.path.join(os.path.dirname(path), inc)
36 if os.path.isfile(local):
37 return [local]
38 matches = (os.path.join(root, directory, inc) for directory in _INCLUDE_DIRS)
39 return [candidate for candidate in matches if os.path.isfile(candidate)]
40
14 41
15def program_sources(root, name): 42def program_sources(root, name):
16 """The files program `name` of runtime/test is built from, as far as they exist in this checkout.""" 43 """The files program `name` of runtime/test is built from, as far as they exist in this checkout."""
@@ -29,7 +56,8 @@ def program_sources(root, name):
29 text = f.read() 56 text = f.read()
30 except OSError: 57 except OSError:
31 continue 58 continue
32 pending.extend(os.path.join(os.path.dirname(path), inc) for inc in _INCLUDE.findall(text)) 59 for inc in _INCLUDE.findall(text):
60 pending.extend(_resolve_include(root, path, inc))
33 return found 61 return found
34 62
35 63
diff --git a/tools/vk_fuzz_run.py b/tools/vk_fuzz_run.py
index 797010296..88cde0d8f 100644
--- a/tools/vk_fuzz_run.py
+++ b/tools/vk_fuzz_run.py
@@ -79,6 +79,19 @@ def program_text(name, lines, words, wave, opaque=False, rewrite=True):
79 return "\n".join(out) + "\n" 79 return "\n".join(out) + "\n"
80 80
81 81
82def read_dump(path, words, wave):
83 """The `wave` lanes of `words` words each from a VKC_DUMP file, or None when it is missing or too short.
84 vk_compute_test's output buffer is at least one 64-thread group of words (VKC_OUT_WORDS only raises it), and
85 VKC_DUMP writes the whole buffer, so a request under 64 words (wave32 with words=1) gives a larger file: only its
86 first words * wave words are the program's stores, the rest keep the fill."""
87 need = 4 * words * wave
88 if not os.path.isfile(path) or os.path.getsize(path) < need:
89 return None
90 with open(path, "rb") as f:
91 flat = struct.unpack(f"<{words * wave}I", f.read(need))
92 return [list(flat[k:k + words]) for k in range(0, words * wave, words)]
93
94
82def run_programs(texts, words=4, wave=32, build=None, work_parent=None, retries=2, opaque=True, rewrite=True, 95def run_programs(texts, words=4, wave=32, build=None, work_parent=None, retries=2, opaque=True, rewrite=True,
83 per_lane=False, uniform=True): 96 per_lane=False, uniform=True):
84 """Per program lane 0's `words` words, or a str (see the module docstring). words must be 1, 2, 4 or 8.""" 97 """Per program lane 0's `words` words, or a str (see the module docstring). words must be 1, 2, 4 or 8."""
@@ -158,12 +171,11 @@ def run_programs(texts, words=4, wave=32, build=None, work_parent=None, retries=
158 results[i] = "vk_compute_test: " + (msg.splitlines()[-1] if msg else "unsupported") 171 results[i] = "vk_compute_test: " + (msg.splitlines()[-1] if msg else "unsupported")
159 elif wave == 32 and unpinned_subgroup(msg): 172 elif wave == 32 and unpinned_subgroup(msg):
160 results[i] = f"the device can't run 32-lane subgroups ({unpinned_subgroup(msg)} lanes)" 173 results[i] = f"the device can't run 32-lane subgroups ({unpinned_subgroup(msg)} lanes)"
161 elif r.returncode or not os.path.isfile(dump) or os.path.getsize(dump) != 4 * words * wave: 174 elif r.returncode:
162 results[i] = f"vk_compute_test exit {r.returncode}" 175 results[i] = f"vk_compute_test exit {r.returncode}"
176 elif (lanes := read_dump(dump, words, wave)) is None:
177 results[i] = f"vk_compute_test: no dump of {4 * words * wave} bytes or more"
163 else: 178 else:
164 with open(dump, "rb") as f:
165 flat = struct.unpack(f"<{words * wave}I", f.read())
166 lanes = [list(flat[k:k + words]) for k in range(0, words * wave, words)]
167 odd = [k for k, w in enumerate(lanes) if w != lanes[0]] 179 odd = [k for k, w in enumerate(lanes) if w != lanes[0]]
168 if per_lane: 180 if per_lane:
169 results[i] = lanes 181 results[i] = lanes
diff --git a/viewer/studio.html b/viewer/studio.html
index b8118382d..7e43fbdec 100644
--- a/viewer/studio.html
+++ b/viewer/studio.html
@@ -997,12 +997,12 @@ function renderTexturesGrid() {
997 card.className = 'tex-card'; 997 card.className = 'tex-card';
998 card.innerHTML = ` 998 card.innerHTML = `
999 <div class="tex-preview"> 999 <div class="tex-preview">
1000 <img src="${t.preview}" alt="${escapeHtml(t.name)}" loading="lazy" onerror="this.onerror=null; this.src=''; this.alt='DDS / Pre-converted'"> 1000 <img src="${escapeHtml(t.preview)}" alt="${escapeHtml(t.name)}" loading="lazy" onerror="this.onerror=null; this.src=''; this.alt='DDS / Pre-converted'">
1001 </div> 1001 </div>
1002 <div class="tex-info"> 1002 <div class="tex-info">
1003 <div class="tex-name" title="${escapeHtml(t.name)}">${escapeHtml(t.name)}</div> 1003 <div class="tex-name" title="${escapeHtml(t.name)}">${escapeHtml(t.name)}</div>
1004 <div class="tex-meta"> 1004 <div class="tex-meta">
1005 <span>${t.format}</span> 1005 <span>${escapeHtml(t.format)}</span>
1006 <span>${formatBytes(t.size)}</span> 1006 <span>${formatBytes(t.size)}</span>
1007 </div> 1007 </div>
1008 </div> 1008 </div>
@@ -1024,12 +1024,12 @@ function renderTexturesGrid() {
1024 card.className = 'tex-card'; 1024 card.className = 'tex-card';
1025 card.innerHTML = ` 1025 card.innerHTML = `
1026 <div class="tex-preview"> 1026 <div class="tex-preview">
1027 <img src="${t.preview}" alt="${escapeHtml(t.name)}" loading="lazy" onerror="this.onerror=null; this.src=''; this.alt='DDS / Pre-converted'"> 1027 <img src="${escapeHtml(t.preview)}" alt="${escapeHtml(t.name)}" loading="lazy" onerror="this.onerror=null; this.src=''; this.alt='DDS / Pre-converted'">
1028 </div> 1028 </div>
1029 <div class="tex-info"> 1029 <div class="tex-info">
1030 <div class="tex-name" title="${escapeHtml(t.name)}">${escapeHtml(t.name)}</div> 1030 <div class="tex-name" title="${escapeHtml(t.name)}">${escapeHtml(t.name)}</div>
1031 <div class="tex-meta"> 1031 <div class="tex-meta">
1032 <span>${t.format}</span> 1032 <span>${escapeHtml(t.format)}</span>
1033 <span>${formatBytes(t.size)}</span> 1033 <span>${formatBytes(t.size)}</span>
1034 </div> 1034 </div>
1035 </div> 1035 </div>